@serwist/precaching 9.0.0-preview.17 → 9.0.0-preview.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/index.d.ts +5 -26
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -155
  4. package/package.json +3 -17
  5. package/src/index.ts +5 -39
  6. package/dist/PrecacheController.d.ts +0 -146
  7. package/dist/PrecacheController.d.ts.map +0 -1
  8. package/dist/PrecacheFallbackPlugin.d.ts +0 -54
  9. package/dist/PrecacheFallbackPlugin.d.ts.map +0 -1
  10. package/dist/PrecacheRoute.d.ts +0 -20
  11. package/dist/PrecacheRoute.d.ts.map +0 -1
  12. package/dist/PrecacheStrategy.d.ts +0 -67
  13. package/dist/PrecacheStrategy.d.ts.map +0 -1
  14. package/dist/_types.d.ts +0 -37
  15. package/dist/_types.d.ts.map +0 -1
  16. package/dist/addPlugins.d.ts +0 -9
  17. package/dist/addPlugins.d.ts.map +0 -1
  18. package/dist/addRoute.d.ts +0 -15
  19. package/dist/addRoute.d.ts.map +0 -1
  20. package/dist/chunks/getOrCreatePrecacheController.js +0 -436
  21. package/dist/cleanupOutdatedCaches.d.ts +0 -6
  22. package/dist/cleanupOutdatedCaches.d.ts.map +0 -1
  23. package/dist/createHandlerBoundToURL.d.ts +0 -17
  24. package/dist/createHandlerBoundToURL.d.ts.map +0 -1
  25. package/dist/getCacheKeyForURL.d.ts +0 -20
  26. package/dist/getCacheKeyForURL.d.ts.map +0 -1
  27. package/dist/index.internal.d.ts +0 -3
  28. package/dist/index.internal.d.ts.map +0 -1
  29. package/dist/index.internal.js +0 -4
  30. package/dist/matchPrecache.d.ts +0 -15
  31. package/dist/matchPrecache.d.ts.map +0 -1
  32. package/dist/precache.d.ts +0 -19
  33. package/dist/precache.d.ts.map +0 -1
  34. package/dist/precacheAndRoute.d.ts +0 -14
  35. package/dist/precacheAndRoute.d.ts.map +0 -1
  36. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +0 -17
  37. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  38. package/dist/utils/PrecacheInstallReportPlugin.d.ts +0 -15
  39. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +0 -1
  40. package/dist/utils/createCacheKey.d.ts +0 -16
  41. package/dist/utils/createCacheKey.d.ts.map +0 -1
  42. package/dist/utils/deleteOutdatedCaches.d.ts +0 -18
  43. package/dist/utils/deleteOutdatedCaches.d.ts.map +0 -1
  44. package/dist/utils/generateURLVariations.d.ts +0 -12
  45. package/dist/utils/generateURLVariations.d.ts.map +0 -1
  46. package/dist/utils/getCacheKeyForURL.d.ts +0 -14
  47. package/dist/utils/getCacheKeyForURL.d.ts.map +0 -1
  48. package/dist/utils/getOrCreatePrecacheController.d.ts +0 -7
  49. package/dist/utils/getOrCreatePrecacheController.d.ts.map +0 -1
  50. package/dist/utils/printCleanupDetails.d.ts +0 -6
  51. package/dist/utils/printCleanupDetails.d.ts.map +0 -1
  52. package/dist/utils/printInstallDetails.d.ts +0 -7
  53. package/dist/utils/printInstallDetails.d.ts.map +0 -1
  54. package/dist/utils/removeIgnoredSearchParams.d.ts +0 -12
  55. package/dist/utils/removeIgnoredSearchParams.d.ts.map +0 -1
  56. package/src/PrecacheController.ts +0 -344
  57. package/src/PrecacheFallbackPlugin.ts +0 -86
  58. package/src/PrecacheRoute.ts +0 -50
  59. package/src/PrecacheStrategy.ts +0 -239
  60. package/src/_types.ts +0 -46
  61. package/src/addPlugins.ts +0 -23
  62. package/src/addRoute.ts +0 -31
  63. package/src/cleanupOutdatedCaches.ts +0 -33
  64. package/src/createHandlerBoundToURL.ts +0 -30
  65. package/src/getCacheKeyForURL.ts +0 -33
  66. package/src/index.internal.ts +0 -3
  67. package/src/matchPrecache.ts +0 -28
  68. package/src/precache.ts +0 -31
  69. package/src/precacheAndRoute.ts +0 -27
  70. package/src/utils/PrecacheCacheKeyPlugin.ts +0 -36
  71. package/src/utils/PrecacheInstallReportPlugin.ts +0 -49
  72. package/src/utils/createCacheKey.ts +0 -68
  73. package/src/utils/deleteOutdatedCaches.ts +0 -40
  74. package/src/utils/generateURLVariations.ts +0 -55
  75. package/src/utils/getCacheKeyForURL.ts +0 -36
  76. package/src/utils/getOrCreatePrecacheController.ts +0 -22
  77. package/src/utils/printCleanupDetails.ts +0 -38
  78. package/src/utils/printInstallDetails.ts +0 -53
  79. package/src/utils/removeIgnoredSearchParams.ts +0 -29
@@ -1,18 +0,0 @@
1
- /**
2
- * Cleans up incompatible precaches that were created by older versions of
3
- * Serwist, by a service worker registered under the current scope.
4
- *
5
- * This is meant to be called as part of the `activate` event.
6
- *
7
- * This should be safe to use as long as you don't include `substringToFind`
8
- * (defaulting to `-precache-`) in your non-precache cache names.
9
- *
10
- * @param currentPrecacheName The cache name currently in use for
11
- * precaching. This cache won't be deleted.
12
- * @param substringToFind Cache names which include this
13
- * substring will be deleted (excluding `currentPrecacheName`).
14
- * @returns A list of all the cache names that were deleted.
15
- * @private
16
- */
17
- export declare const deleteOutdatedCaches: (currentPrecacheName: string, substringToFind?: string) => Promise<string[]>;
18
- //# sourceMappingURL=deleteOutdatedCaches.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"deleteOutdatedCaches.d.ts","sourceRoot":"","sources":["../../src/utils/deleteOutdatedCaches.ts"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,oBAAoB,wBAA+B,MAAM,oBAAmB,MAAM,KAAuB,QAAQ,MAAM,EAAE,CAUrI,CAAC"}
@@ -1,12 +0,0 @@
1
- import type { PrecacheRouteOptions } from "../_types.js";
2
- /**
3
- * Generator function that yields possible variations on the original URL to
4
- * check, one at a time.
5
- *
6
- * @param url
7
- * @param options
8
- *
9
- * @private
10
- */
11
- export declare function generateURLVariations(url: string, { ignoreURLParametersMatching, directoryIndex, cleanURLs, urlManipulation, }?: PrecacheRouteOptions): Generator<string, void, unknown>;
12
- //# sourceMappingURL=generateURLVariations.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generateURLVariations.d.ts","sourceRoot":"","sources":["../../src/utils/generateURLVariations.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAGzD;;;;;;;;GAQG;AACH,wBAAiB,qBAAqB,CACpC,GAAG,EAAE,MAAM,EACX,EACE,2BAAmD,EACnD,cAA6B,EAC7B,SAAgB,EAChB,eAAe,GAChB,GAAE,oBAAyB,GAC3B,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CA0BlC"}
@@ -1,14 +0,0 @@
1
- import type { PrecacheRouteOptions } from "../_types.js";
2
- /**
3
- * This function will take the request URL and manipulate it based on the
4
- * configuration options.
5
- *
6
- * @param url
7
- * @param options
8
- * @returns Returns the URL in the cache that matches the request,
9
- * if possible.
10
- *
11
- * @private
12
- */
13
- export declare const getCacheKeyForURL: (url: string, options: PrecacheRouteOptions) => string | undefined;
14
- //# sourceMappingURL=getCacheKeyForURL.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getCacheKeyForURL.d.ts","sourceRoot":"","sources":["../../src/utils/getCacheKeyForURL.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAIzD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,QAAS,MAAM,WAAW,oBAAoB,KAAG,MAAM,GAAG,SAYvF,CAAC"}
@@ -1,7 +0,0 @@
1
- import { PrecacheController } from "../PrecacheController.js";
2
- /**
3
- * @returns
4
- * @private
5
- */
6
- export declare const getOrCreatePrecacheController: () => PrecacheController;
7
- //# sourceMappingURL=getOrCreatePrecacheController.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getOrCreatePrecacheController.d.ts","sourceRoot":"","sources":["../../src/utils/getOrCreatePrecacheController.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAI9D;;;GAGG;AACH,eAAO,MAAM,6BAA6B,QAAO,kBAKhD,CAAC"}
@@ -1,6 +0,0 @@
1
- /**
2
- * @param deletedURLs
3
- * @private
4
- */
5
- export declare function printCleanupDetails(deletedURLs: string[]): void;
6
- //# sourceMappingURL=printCleanupDetails.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"printCleanupDetails.d.ts","sourceRoot":"","sources":["../../src/utils/printCleanupDetails.ts"],"names":[],"mappings":"AA0BA;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,IAAI,CAO/D"}
@@ -1,7 +0,0 @@
1
- /**
2
- * @param urlsToPrecache
3
- * @param urlsAlreadyPrecached
4
- * @private
5
- */
6
- export declare function printInstallDetails(urlsToPrecache: string[], urlsAlreadyPrecached: string[]): void;
7
- //# sourceMappingURL=printInstallDetails.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"printInstallDetails.d.ts","sourceRoot":"","sources":["../../src/utils/printInstallDetails.ts"],"names":[],"mappings":"AA8BA;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,oBAAoB,EAAE,MAAM,EAAE,GAAG,IAAI,CAiBlG"}
@@ -1,12 +0,0 @@
1
- /**
2
- * Removes any URL search parameters that should be ignored.
3
- *
4
- * @param urlObject The original URL.
5
- * @param ignoreURLParametersMatching RegExps to test against
6
- * each search parameter name. Matches mean that the search parameter should be
7
- * ignored.
8
- * @returns The URL with any ignored search parameters removed.
9
- * @private
10
- */
11
- export declare function removeIgnoredSearchParams(urlObject: URL, ignoreURLParametersMatching?: RegExp[]): URL;
12
- //# sourceMappingURL=removeIgnoredSearchParams.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"removeIgnoredSearchParams.d.ts","sourceRoot":"","sources":["../../src/utils/removeIgnoredSearchParams.ts"],"names":[],"mappings":"AAQA;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,GAAG,EAAE,2BAA2B,GAAE,MAAM,EAAO,GAAG,GAAG,CAUzG"}
@@ -1,344 +0,0 @@
1
- /*
2
- Copyright 2019 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { RouteHandlerCallback, SerwistPlugin } from "@serwist/core";
10
- import { assert, SerwistError, logger, privateCacheNames, waitUntil } from "@serwist/core/internal";
11
- import type { Strategy } from "@serwist/strategies";
12
- import { parallel } from "@serwist/utils";
13
-
14
- import { PrecacheStrategy } from "./PrecacheStrategy.js";
15
- import type { CleanupResult, InstallResult, PrecacheEntry } from "./_types.js";
16
- import { PrecacheCacheKeyPlugin } from "./utils/PrecacheCacheKeyPlugin.js";
17
- import { PrecacheInstallReportPlugin } from "./utils/PrecacheInstallReportPlugin.js";
18
- import { createCacheKey } from "./utils/createCacheKey.js";
19
- import { printCleanupDetails } from "./utils/printCleanupDetails.js";
20
- import { printInstallDetails } from "./utils/printInstallDetails.js";
21
-
22
- // Give TypeScript the correct global.
23
- declare const self: ServiceWorkerGlobalScope;
24
-
25
- interface PrecacheControllerOptions {
26
- /**
27
- * The cache to use for precaching.
28
- */
29
- cacheName?: string;
30
- /**
31
- * Plugins to use when precaching as well as responding to fetch
32
- * events for precached assets.
33
- */
34
- plugins?: SerwistPlugin[];
35
- /**
36
- * Whether to attempt to get the response from the network if there's
37
- * a precache miss.
38
- */
39
- fallbackToNetwork?: boolean;
40
- /**
41
- * A number of how many precache requests should be made concurrently.
42
- * By default, this value is set to 1, but this can be overriden by
43
- * setting this option or `self.__WB_CONCURRENT_PRECACHING`. The former takes
44
- * precedence over the latter.
45
- */
46
- concurrentPrecaching?: number;
47
- }
48
-
49
- /**
50
- * Performs efficient precaching of assets.
51
- */
52
- export class PrecacheController {
53
- private _installAndActiveListenersAdded?: boolean;
54
- private _concurrentPrecaching: number | undefined;
55
- private readonly _strategy: Strategy;
56
- private readonly _urlsToCacheKeys: Map<string, string> = new Map();
57
- private readonly _urlsToCacheModes: Map<string, "reload" | "default" | "no-store" | "no-cache" | "force-cache" | "only-if-cached"> = new Map();
58
- private readonly _cacheKeysToIntegrities: Map<string, string> = new Map();
59
-
60
- /**
61
- * Create a new PrecacheController.
62
- *
63
- * @param options
64
- */
65
- constructor({ cacheName, plugins = [], fallbackToNetwork = true, concurrentPrecaching }: PrecacheControllerOptions = {}) {
66
- this._strategy = new PrecacheStrategy({
67
- cacheName: privateCacheNames.getPrecacheName(cacheName),
68
- plugins: [...plugins, new PrecacheCacheKeyPlugin({ precacheController: this })],
69
- fallbackToNetwork,
70
- });
71
- this._concurrentPrecaching = concurrentPrecaching;
72
-
73
- // Bind the install and activate methods to the instance.
74
- this.install = this.install.bind(this);
75
- this.activate = this.activate.bind(this);
76
- }
77
-
78
- /**
79
- * The strategy created by this controller and
80
- * used to cache assets and respond to fetch events.
81
- */
82
- get strategy(): Strategy {
83
- return this._strategy;
84
- }
85
-
86
- /**
87
- * Adds items to the precache list, removing any duplicates and
88
- * stores the files in the precache cache when the service
89
- * worker installs.
90
- *
91
- * This method can be called multiple times.
92
- *
93
- * @param entries Array of entries to precache.
94
- */
95
- precache(entries: (PrecacheEntry | string)[]): void {
96
- this.addToCacheList(entries);
97
-
98
- if (!this._installAndActiveListenersAdded) {
99
- self.addEventListener("install", this.install);
100
- self.addEventListener("activate", this.activate);
101
- this._installAndActiveListenersAdded = true;
102
- }
103
- }
104
-
105
- /**
106
- * This method will add items to the precache list, removing duplicates
107
- * and ensuring the information is valid.
108
- *
109
- * @param entries Array of entries to precache.
110
- */
111
- addToCacheList(entries: (PrecacheEntry | string)[]): void {
112
- if (process.env.NODE_ENV !== "production") {
113
- assert!.isArray(entries, {
114
- moduleName: "@serwist/precaching",
115
- className: "PrecacheController",
116
- funcName: "addToCacheList",
117
- paramName: "entries",
118
- });
119
- }
120
-
121
- const urlsToWarnAbout: string[] = [];
122
- for (const entry of entries) {
123
- // See https://github.com/GoogleChrome/workbox/issues/2259
124
- if (typeof entry === "string") {
125
- urlsToWarnAbout.push(entry);
126
- } else if (entry && !entry.integrity && entry.revision === undefined) {
127
- urlsToWarnAbout.push(entry.url);
128
- }
129
-
130
- const { cacheKey, url } = createCacheKey(entry);
131
- const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default";
132
-
133
- if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
134
- throw new SerwistError("add-to-cache-list-conflicting-entries", {
135
- firstEntry: this._urlsToCacheKeys.get(url),
136
- secondEntry: cacheKey,
137
- });
138
- }
139
-
140
- if (typeof entry !== "string" && entry.integrity) {
141
- if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
142
- throw new SerwistError("add-to-cache-list-conflicting-integrities", {
143
- url,
144
- });
145
- }
146
- this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
147
- }
148
-
149
- this._urlsToCacheKeys.set(url, cacheKey);
150
- this._urlsToCacheModes.set(url, cacheMode);
151
-
152
- if (urlsToWarnAbout.length > 0) {
153
- const warningMessage = `Serwist is precaching URLs without revision info: ${urlsToWarnAbout.join(
154
- ", ",
155
- )}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;
156
- if (process.env.NODE_ENV === "production") {
157
- // Use console directly to display this warning without bloating
158
- // bundle sizes by pulling in all of the logger codebase in prod.
159
- console.warn(warningMessage);
160
- } else {
161
- logger.warn(warningMessage);
162
- }
163
- }
164
- }
165
- }
166
-
167
- /**
168
- * Precaches new and updated assets. Call this method from the service worker
169
- * install event.
170
- *
171
- * Note: this method calls `event.waitUntil()` for you, so you do not need
172
- * to call it yourself in your event handlers.
173
- *
174
- * @param event
175
- * @returns
176
- */
177
- install(event: ExtendableEvent): Promise<InstallResult> {
178
- return waitUntil<InstallResult>(event, async () => {
179
- const installReportPlugin = new PrecacheInstallReportPlugin();
180
- this.strategy.plugins.push(installReportPlugin);
181
-
182
- let concurrents = this._concurrentPrecaching;
183
-
184
- if (concurrents === undefined) {
185
- if (!("__WB_CONCURRENT_PRECACHING" in globalThis)) {
186
- self.__WB_CONCURRENT_PRECACHING = 1;
187
- }
188
- concurrents = self.__WB_CONCURRENT_PRECACHING;
189
- }
190
-
191
- await parallel(concurrents, Array.from(this._urlsToCacheKeys.entries()), async ([url, cacheKey]): Promise<void> => {
192
- const integrity = this._cacheKeysToIntegrities.get(cacheKey);
193
- const cacheMode = this._urlsToCacheModes.get(url);
194
-
195
- const request = new Request(url, {
196
- integrity,
197
- cache: cacheMode,
198
- credentials: "same-origin",
199
- });
200
-
201
- await Promise.all(
202
- this.strategy.handleAll({
203
- event,
204
- request,
205
- url: new URL(request.url),
206
- params: { cacheKey },
207
- }),
208
- );
209
- });
210
-
211
- const { updatedURLs, notUpdatedURLs } = installReportPlugin;
212
-
213
- if (process.env.NODE_ENV !== "production") {
214
- printInstallDetails(updatedURLs, notUpdatedURLs);
215
- }
216
-
217
- return { updatedURLs, notUpdatedURLs };
218
- });
219
- }
220
-
221
- /**
222
- * Deletes assets that are no longer present in the current precache manifest.
223
- * Call this method from the service worker activate event.
224
- *
225
- * Note: this method calls `event.waitUntil()` for you, so you do not need
226
- * to call it yourself in your event handlers.
227
- *
228
- * @param event
229
- * @returns
230
- */
231
- activate(event: ExtendableEvent): Promise<CleanupResult> {
232
- return waitUntil<CleanupResult>(event, async () => {
233
- const cache = await self.caches.open(this.strategy.cacheName);
234
- const currentlyCachedRequests = await cache.keys();
235
- const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
236
-
237
- const deletedCacheRequests: string[] = [];
238
-
239
- for (const request of currentlyCachedRequests) {
240
- if (!expectedCacheKeys.has(request.url)) {
241
- await cache.delete(request);
242
- deletedCacheRequests.push(request.url);
243
- }
244
- }
245
-
246
- if (process.env.NODE_ENV !== "production") {
247
- printCleanupDetails(deletedCacheRequests);
248
- }
249
-
250
- return { deletedCacheRequests };
251
- });
252
- }
253
-
254
- /**
255
- * Returns a mapping of a precached URL to the corresponding cache key, taking
256
- * into account the revision information for the URL.
257
- *
258
- * @returns A URL to cache key mapping.
259
- */
260
- getURLsToCacheKeys(): Map<string, string> {
261
- return this._urlsToCacheKeys;
262
- }
263
-
264
- /**
265
- * Returns a list of all the URLs that have been precached by the current
266
- * service worker.
267
- *
268
- * @returns The precached URLs.
269
- */
270
- getCachedURLs(): string[] {
271
- return [...this._urlsToCacheKeys.keys()];
272
- }
273
-
274
- /**
275
- * Returns the cache key used for storing a given URL. If that URL is
276
- * unversioned, like `/index.html', then the cache key will be the original
277
- * URL with a search parameter appended to it.
278
- *
279
- * @param url A URL whose cache key you want to look up.
280
- * @returns The versioned URL that corresponds to a cache key
281
- * for the original URL, or undefined if that URL isn't precached.
282
- */
283
- getCacheKeyForURL(url: string): string | undefined {
284
- const urlObject = new URL(url, location.href);
285
- return this._urlsToCacheKeys.get(urlObject.href);
286
- }
287
-
288
- /**
289
- * @param url A cache key whose SRI you want to look up.
290
- * @returns The subresource integrity associated with the cache key,
291
- * or undefined if it's not set.
292
- */
293
- getIntegrityForCacheKey(cacheKey: string): string | undefined {
294
- return this._cacheKeysToIntegrities.get(cacheKey);
295
- }
296
-
297
- /**
298
- * This acts as a drop-in replacement for
299
- * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
300
- * with the following differences:
301
- *
302
- * - It knows what the name of the precache is, and only checks in that cache.
303
- * - It allows you to pass in an "original" URL without versioning parameters,
304
- * and it will automatically look up the correct cache key for the currently
305
- * active revision of that URL.
306
- *
307
- * E.g., `matchPrecache('index.html')` will find the correct precached
308
- * response for the currently active service worker, even if the actual cache
309
- * key is `'/index.html?__WB_REVISION__=1234abcd'`.
310
- *
311
- * @param request The key (without revisioning parameters)
312
- * to look up in the precache.
313
- * @returns
314
- */
315
- async matchPrecache(request: string | Request): Promise<Response | undefined> {
316
- const url = request instanceof Request ? request.url : request;
317
- const cacheKey = this.getCacheKeyForURL(url);
318
- if (cacheKey) {
319
- const cache = await self.caches.open(this.strategy.cacheName);
320
- return cache.match(cacheKey);
321
- }
322
- return undefined;
323
- }
324
-
325
- /**
326
- * Returns a function that looks up `url` in the precache (taking into
327
- * account revision information), and returns the corresponding `Response`.
328
- *
329
- * @param url The precached URL which will be used to lookup the response.
330
- * @return
331
- */
332
- createHandlerBoundToURL(url: string): RouteHandlerCallback {
333
- const cacheKey = this.getCacheKeyForURL(url);
334
- if (!cacheKey) {
335
- throw new SerwistError("non-precached-url", { url });
336
- }
337
- return (options) => {
338
- options.request = new Request(url);
339
- options.params = { cacheKey, ...options.params };
340
-
341
- return this.strategy.handle(options);
342
- };
343
- }
344
- }
@@ -1,86 +0,0 @@
1
- /*
2
- Copyright 2020 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { HandlerDidErrorCallbackParam, SerwistPlugin } from "@serwist/core";
10
-
11
- import type { PrecacheController } from "./PrecacheController.js";
12
- import { getOrCreatePrecacheController } from "./utils/getOrCreatePrecacheController.js";
13
-
14
- export interface PrecacheFallbackEntry {
15
- /**
16
- * A function that checks whether the fallback entry can be used
17
- * for a request.
18
- */
19
- matcher: (param: HandlerDidErrorCallbackParam) => boolean;
20
- /**
21
- * A precached URL to be used as a fallback.
22
- */
23
- url: string;
24
- }
25
-
26
- export interface PrecacheFallbackPluginOptions {
27
- /**
28
- * Precached URLs to use as the fallback
29
- * if the associated strategy can't generate a response.
30
- */
31
- fallbackUrls: (string | PrecacheFallbackEntry)[];
32
- /**
33
- * An optional `PrecacheController` instance. If not provided, the default
34
- * `PrecacheController` will be used.
35
- */
36
- precacheController?: PrecacheController;
37
- }
38
-
39
- /**
40
- * `PrecacheFallbackPlugin` allows you to specify offline fallbacks
41
- * to be used when a given strategy is unable to generate a response.
42
- *
43
- * It does this by intercepting the `handlerDidError` plugin callback
44
- * and returning a precached response, taking the expected revision parameter
45
- * into account automatically.
46
- *
47
- * Unless you explicitly pass in a `PrecacheController` instance to the
48
- * constructor, the default instance will be used. Generally speaking, most
49
- * developers will end up using the default.
50
- */
51
- export class PrecacheFallbackPlugin implements SerwistPlugin {
52
- private readonly _fallbackUrls: (string | PrecacheFallbackEntry)[];
53
- private readonly _precacheController: PrecacheController;
54
-
55
- /**
56
- * Constructs a new `PrecacheFallbackPlugin` with the associated `fallbackUrls`.
57
- *
58
- * @param config
59
- */
60
- constructor({ fallbackUrls, precacheController }: PrecacheFallbackPluginOptions) {
61
- this._fallbackUrls = fallbackUrls;
62
- this._precacheController = precacheController || getOrCreatePrecacheController();
63
- }
64
-
65
- /**
66
- * @returns The precache response for one of the fallback URLs, or `undefined` if
67
- * nothing satisfies the conditions.
68
- * @private
69
- */
70
- async handlerDidError(param: HandlerDidErrorCallbackParam) {
71
- for (const fallback of this._fallbackUrls) {
72
- if (typeof fallback === "string") {
73
- const fallbackResponse = await this._precacheController.matchPrecache(fallback);
74
- if (fallbackResponse !== undefined) {
75
- return fallbackResponse;
76
- }
77
- } else if (fallback.matcher(param)) {
78
- const fallbackResponse = await this._precacheController.matchPrecache(fallback.url);
79
- if (fallbackResponse !== undefined) {
80
- return fallbackResponse;
81
- }
82
- }
83
- }
84
- return undefined;
85
- }
86
- }
@@ -1,50 +0,0 @@
1
- /*
2
- Copyright 2020 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { RouteMatchCallback, RouteMatchCallbackOptions } from "@serwist/core";
10
- import { getFriendlyURL, logger } from "@serwist/core/internal";
11
- import { Route } from "@serwist/routing";
12
-
13
- import type { PrecacheController } from "./PrecacheController.js";
14
- import type { PrecacheRouteOptions } from "./_types.js";
15
- import { generateURLVariations } from "./utils/generateURLVariations.js";
16
-
17
- /**
18
- * A subclass of `@serwist/routing.Route` that takes a
19
- * `@serwist/precaching.PrecacheController`
20
- * instance and uses it to match incoming requests and handle fetching
21
- * responses from the precache.
22
- */
23
- class PrecacheRoute extends Route {
24
- /**
25
- * @param precacheController A `PrecacheController`
26
- * instance used to both match requests and respond to fetch events.
27
- * @param options Options to control how requests are matched
28
- * against the list of precached URLs.
29
- */
30
- constructor(precacheController: PrecacheController, options?: PrecacheRouteOptions) {
31
- const match: RouteMatchCallback = ({ request }: RouteMatchCallbackOptions) => {
32
- const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
33
- for (const possibleURL of generateURLVariations(request.url, options)) {
34
- const cacheKey = urlsToCacheKeys.get(possibleURL);
35
- if (cacheKey) {
36
- const integrity = precacheController.getIntegrityForCacheKey(cacheKey);
37
- return { cacheKey, integrity };
38
- }
39
- }
40
- if (process.env.NODE_ENV !== "production") {
41
- logger.debug(`Precaching did not find a match for ${getFriendlyURL(request.url)}`);
42
- }
43
- return;
44
- };
45
-
46
- super(match, precacheController.strategy);
47
- }
48
- }
49
-
50
- export { PrecacheRoute };