or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cache-management.mdfile-stores.mdhttp-stores.mdindex.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Utility functions for cache key generation and error classes for handling cache-specific exceptions. Provides essential support functionality for cache operations.

3

4

## Capabilities

5

6

### Hash Generation

7

8

Stable hash function for generating consistent cache keys from JavaScript values.

9

10

```javascript { .api }

11

/**

12

* Generate stable MD5 hash for cache keys from any JavaScript value

13

* Ensures consistent hashing across runs by using canonical JSON serialization

14

* @param value - Any JavaScript value to hash (objects, arrays, primitives)

15

* @returns MD5 hash as Buffer suitable for use as cache key

16

*/

17

function stableHash(value: mixed): Buffer;

18

```

19

20

**Usage Examples:**

21

22

```javascript

23

const { stableHash } = require("metro-cache");

24

25

// Hash simple values

26

const stringKey = stableHash("my-cache-key");

27

const numberKey = stableHash(42);

28

29

// Hash complex objects (order-independent)

30

const objectKey = stableHash({

31

file: "app.js",

32

transforms: ["babel", "minify"],

33

options: { target: "es5" }

34

});

35

36

// Same object, different property order = same hash

37

const sameObjectKey = stableHash({

38

transforms: ["babel", "minify"],

39

options: { target: "es5" },

40

file: "app.js"

41

});

42

43

console.log(objectKey.equals(sameObjectKey)); // true

44

45

// Hash arrays (order-dependent)

46

const arrayKey = stableHash(["transform1", "transform2"]);

47

48

// Use with Cache

49

const cache = new Cache([fileStore]);

50

const key = stableHash({ source: sourceCode, config: babelConfig });

51

const result = await cache.get(key);

52

```

53

54

### Error Classes

55

56

Specialized error classes for different types of cache failures.

57

58

#### HttpError

59

60

HTTP-specific error with status code information.

61

62

```javascript { .api }

63

/**

64

* HTTP-specific error with status code

65

* Thrown by HttpStore for HTTP protocol errors

66

*/

67

class HttpError extends Error {

68

/**

69

* Create HTTP error with message and status code

70

* @param message - Error description

71

* @param code - HTTP status code (e.g., 404, 500)

72

*/

73

constructor(message: string, code: number);

74

75

/**

76

* HTTP status code associated with this error

77

*/

78

code: number;

79

}

80

```

81

82

**Usage Examples:**

83

84

```javascript

85

const { HttpStore } = require("metro-cache");

86

87

const httpStore = new HttpStore({ endpoint: "https://cache.example.com" });

88

89

try {

90

await httpStore.get(key);

91

} catch (error) {

92

if (error instanceof HttpStore.HttpError) {

93

switch (error.code) {

94

case 404:

95

console.log("Cache miss");

96

break;

97

case 401:

98

console.error("Authentication failed");

99

break;

100

case 500:

101

console.error("Server error:", error.message);

102

break;

103

default:

104

console.error(`HTTP ${error.code}: ${error.message}`);

105

}

106

}

107

}

108

```

109

110

#### NetworkError

111

112

Network connectivity error with error code information.

113

114

```javascript { .api }

115

/**

116

* Network connectivity error

117

* Thrown by HttpStore for network-level issues

118

*/

119

class NetworkError extends Error {

120

/**

121

* Create network error with message and error code

122

* @param message - Error description

123

* @param code - Network error code (e.g., "ECONNREFUSED", "TIMEOUT")

124

*/

125

constructor(message: string, code: string);

126

127

/**

128

* Network error code associated with this error

129

*/

130

code: string;

131

}

132

```

133

134

**Usage Examples:**

135

136

```javascript

137

const { HttpStore } = require("metro-cache");

138

139

const httpStore = new HttpStore({

140

endpoint: "https://cache.example.com",

141

timeout: 5000

142

});

143

144

try {

145

await httpStore.set(key, value);

146

} catch (error) {

147

if (error instanceof HttpStore.NetworkError) {

148

switch (error.code) {

149

case "ECONNREFUSED":

150

console.error("Cache server is not running");

151

break;

152

case "ENOTFOUND":

153

console.error("Cache server hostname not found");

154

break;

155

case "TIMEOUT":

156

console.error("Request timed out");

157

break;

158

default:

159

console.error(`Network error ${error.code}: ${error.message}`);

160

}

161

}

162

}

163

```

164

165

## Hash Algorithm Details

166

167

The `stableHash` function provides deterministic hashing by:

168

169

1. **Canonical Serialization**: Uses metro-core's canonicalize function to ensure consistent JSON serialization regardless of object property order

170

2. **MD5 Hashing**: Applies MD5 hash algorithm to the canonical JSON string

171

3. **Buffer Output**: Returns hash as Buffer for direct use as cache keys

172

173

## Error Hierarchy

174

175

```

176

Error

177

├── HttpError (HTTP protocol errors)

178

└── NetworkError (Network connectivity errors)

179

```

180

181

Both error classes extend the standard JavaScript Error class and add specific error code information for more precise error handling in caching scenarios.

182

183

## Integration Notes

184

185

These utilities integrate seamlessly with the rest of the metro-cache system:

186

187

- **stableHash**: Used throughout Metro bundler for generating consistent cache keys

188

- **Error Classes**: Referenced as static properties on HttpStore for convenient access

189

- **Logging**: All operations are automatically logged via Metro's Logger system