or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Workbox Cacheable Response

1

2

Workbox Cacheable Response is a TypeScript library that takes a Response object and determines whether it's cacheable based on a specific configuration. It provides flexible control over which HTTP responses should be stored in the cache by evaluating status codes and headers according to configurable rules.

3

4

## Package Information

5

6

- **Package Name**: workbox-cacheable-response

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install workbox-cacheable-response`

10

- **Dependencies**: workbox-core (^7.3.0)

11

12

## Core Imports

13

14

```typescript

15

import { CacheableResponse, CacheableResponsePlugin, CacheableResponseOptions } from "workbox-cacheable-response";

16

```

17

18

For CommonJS:

19

20

```javascript

21

const { CacheableResponse, CacheableResponsePlugin } = require("workbox-cacheable-response");

22

```

23

24

## Basic Usage

25

26

```typescript

27

import { CacheableResponse, CacheableResponsePlugin, CacheableResponseOptions } from "workbox-cacheable-response";

28

29

// Direct usage for response evaluation

30

const cacheableResponse = new CacheableResponse({

31

statuses: [0, 200],

32

headers: { 'X-Is-Cacheable': 'true' }

33

});

34

35

// Check if a response is cacheable

36

const response = await fetch('/api/data');

37

const isCacheable = cacheableResponse.isResponseCacheable(response);

38

39

// Plugin usage with Workbox strategies

40

const plugin = new CacheableResponsePlugin({

41

statuses: [0, 200, 404]

42

});

43

```

44

45

## Architecture

46

47

The package is built around two main components:

48

49

- **CacheableResponse**: Core class that implements the caching rules logic and evaluates responses

50

- **CacheableResponsePlugin**: Workbox plugin wrapper that integrates with Workbox caching strategies via the `cacheWillUpdate` lifecycle

51

- **Configuration Interface**: `CacheableResponseOptions` provides type-safe configuration for both classes

52

53

## Capabilities

54

55

### Response Cacheability Evaluation

56

57

Direct evaluation of HTTP responses based on configurable rules for status codes and headers.

58

59

```typescript { .api }

60

/**

61

* Core class that allows setting up rules determining what status codes

62

* and/or headers need to be present for a Response to be considered cacheable

63

*/

64

class CacheableResponse {

65

/**

66

* Creates a new CacheableResponse instance. At least one of statuses or headers must be provided.

67

* @param config - Configuration options for cacheability rules (defaults to empty object)

68

* @throws WorkboxError when neither statuses nor headers are provided

69

*/

70

constructor(config: CacheableResponseOptions = {});

71

72

/**

73

* Checks a response to see whether it's cacheable based on configuration

74

* @param response - The response whose cacheability is being checked

75

* @returns true if the Response is cacheable, false otherwise

76

*/

77

isResponseCacheable(response: Response): boolean;

78

}

79

```

80

81

### Workbox Strategy Integration

82

83

Plugin implementation for seamless integration with Workbox caching strategies.

84

85

```typescript { .api }

86

/**

87

* A class implementing the cacheWillUpdate lifecycle callback for integration

88

* with Workbox's built-in strategies

89

*/

90

class CacheableResponsePlugin implements WorkboxPlugin {

91

/**

92

* Creates a new CacheableResponsePlugin instance

93

* @param config - Configuration options for cacheability rules

94

*/

95

constructor(config: CacheableResponseOptions);

96

97

/**

98

* Workbox lifecycle callback that determines if a response should be cached

99

* @param options - Object containing the response to evaluate

100

* @param options.request - The request object

101

* @param options.response - The response object to evaluate

102

* @param options.event - The ExtendableEvent associated with the request

103

* @param options.state - Plugin state object

104

* @returns Promise resolving to the response if cacheable, null otherwise

105

*/

106

cacheWillUpdate(options: {

107

request: Request;

108

response: Response;

109

event: ExtendableEvent;

110

state?: PluginState;

111

}): Promise<Response | null>;

112

}

113

```

114

115

## Types

116

117

```typescript { .api }

118

/**

119

* Configuration options for both CacheableResponse and CacheableResponsePlugin.

120

* At least one of statuses or headers must be provided.

121

*/

122

interface CacheableResponseOptions {

123

/**

124

* One or more status codes that a Response can have and be considered cacheable

125

* @example [0, 200, 404]

126

*/

127

statuses?: number[];

128

129

/**

130

* A mapping of header names and expected values that a Response can have

131

* and be considered cacheable. If multiple headers are provided, only one needs to be present

132

* @example { 'X-Is-Cacheable': 'true', 'Cache-Control': 'public' }

133

*/

134

headers?: {[headerName: string]: string};

135

}

136

137

/**

138

* Type representing plugin state object for Workbox plugins

139

*/

140

type PluginState = {[key: string]: any};

141

142

/**

143

* Workbox plugin interface with lifecycle callbacks

144

*/

145

interface WorkboxPlugin {

146

cacheWillUpdate?: (options: {

147

request: Request;

148

response: Response;

149

event: ExtendableEvent;

150

state?: PluginState;

151

}) => Promise<Response | void | null | undefined>;

152

}

153

```

154

155

## Usage Examples

156

157

### Basic Response Evaluation

158

159

```typescript

160

import { CacheableResponse, CacheableResponseOptions } from "workbox-cacheable-response";

161

162

// Create instance with status code rules

163

const config: CacheableResponseOptions = {

164

statuses: [0, 200]

165

};

166

const cacheableResponse = new CacheableResponse(config);

167

168

// Evaluate a response

169

const response = await fetch('/api/users');

170

if (cacheableResponse.isResponseCacheable(response)) {

171

// Cache the response

172

await cache.put(request, response);

173

}

174

```

175

176

### Header-Based Caching Rules

177

178

```typescript

179

import { CacheableResponse } from "workbox-cacheable-response";

180

181

// Create instance with header rules

182

const cacheableResponse = new CacheableResponse({

183

headers: { 'X-Is-Cacheable': 'true' }

184

});

185

186

const response = await fetch('/api/dynamic-content');

187

if (cacheableResponse.isResponseCacheable(response)) {

188

// Only cache responses with the specific header

189

await cache.put(request, response);

190

}

191

```

192

193

### Combined Rules

194

195

```typescript

196

import { CacheableResponse } from "workbox-cacheable-response";

197

198

// Both status and header conditions must be met

199

const cacheableResponse = new CacheableResponse({

200

statuses: [200, 404],

201

headers: { 'Content-Type': 'application/json' }

202

});

203

```

204

205

### Workbox Strategy Integration

206

207

```typescript

208

import { registerRoute } from 'workbox-routing';

209

import { StaleWhileRevalidate } from 'workbox-strategies';

210

import { CacheableResponsePlugin } from 'workbox-cacheable-response';

211

212

// Use with Workbox caching strategy

213

registerRoute(

214

({ request }) => request.destination === 'image',

215

new StaleWhileRevalidate({

216

cacheName: 'images',

217

plugins: [

218

new CacheableResponsePlugin({

219

statuses: [0, 200]

220

})

221

]

222

})

223

);

224

```

225

226

## Error Handling

227

228

The package throws `WorkboxError` (from workbox-core) when:

229

- Neither `statuses` nor `headers` are provided in the constructor configuration

230

- Invalid parameter types are passed (in development mode only)

231

232

Development mode also provides detailed logging when responses are not cacheable, including:

233

- Current cacheability criteria

234

- Response status and headers

235

- Full response details for debugging

236

237

## Dependencies

238

239

This package depends on:

240

- **workbox-core**: Provides core utilities including error handling, logging, and type definitions