@serwist/precaching 9.0.0-preview.2 → 9.0.0-preview.21

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 (74) hide show
  1. package/dist/index.d.ts +5 -24
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -533
  4. package/package.json +8 -11
  5. package/src/index.ts +5 -36
  6. package/dist/PrecacheController.d.ts +0 -138
  7. package/dist/PrecacheController.d.ts.map +0 -1
  8. package/dist/PrecacheFallbackPlugin.d.ts +0 -44
  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 -16
  19. package/dist/addRoute.d.ts.map +0 -1
  20. package/dist/cleanupOutdatedCaches.d.ts +0 -7
  21. package/dist/cleanupOutdatedCaches.d.ts.map +0 -1
  22. package/dist/createHandlerBoundToURL.d.ts +0 -18
  23. package/dist/createHandlerBoundToURL.d.ts.map +0 -1
  24. package/dist/getCacheKeyForURL.d.ts +0 -20
  25. package/dist/getCacheKeyForURL.d.ts.map +0 -1
  26. package/dist/matchPrecache.d.ts +0 -15
  27. package/dist/matchPrecache.d.ts.map +0 -1
  28. package/dist/precache.d.ts +0 -20
  29. package/dist/precache.d.ts.map +0 -1
  30. package/dist/precacheAndRoute.d.ts +0 -15
  31. package/dist/precacheAndRoute.d.ts.map +0 -1
  32. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +0 -17
  33. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  34. package/dist/utils/PrecacheInstallReportPlugin.d.ts +0 -15
  35. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +0 -1
  36. package/dist/utils/createCacheKey.d.ts +0 -16
  37. package/dist/utils/createCacheKey.d.ts.map +0 -1
  38. package/dist/utils/deleteOutdatedCaches.d.ts +0 -19
  39. package/dist/utils/deleteOutdatedCaches.d.ts.map +0 -1
  40. package/dist/utils/generateURLVariations.d.ts +0 -12
  41. package/dist/utils/generateURLVariations.d.ts.map +0 -1
  42. package/dist/utils/getCacheKeyForURL.d.ts +0 -14
  43. package/dist/utils/getCacheKeyForURL.d.ts.map +0 -1
  44. package/dist/utils/getOrCreatePrecacheController.d.ts +0 -7
  45. package/dist/utils/getOrCreatePrecacheController.d.ts.map +0 -1
  46. package/dist/utils/printCleanupDetails.d.ts +0 -6
  47. package/dist/utils/printCleanupDetails.d.ts.map +0 -1
  48. package/dist/utils/printInstallDetails.d.ts +0 -7
  49. package/dist/utils/printInstallDetails.d.ts.map +0 -1
  50. package/dist/utils/removeIgnoredSearchParams.d.ts +0 -12
  51. package/dist/utils/removeIgnoredSearchParams.d.ts.map +0 -1
  52. package/src/PrecacheController.ts +0 -331
  53. package/src/PrecacheFallbackPlugin.ts +0 -61
  54. package/src/PrecacheRoute.ts +0 -50
  55. package/src/PrecacheStrategy.ts +0 -239
  56. package/src/_types.ts +0 -46
  57. package/src/addPlugins.ts +0 -23
  58. package/src/addRoute.ts +0 -33
  59. package/src/cleanupOutdatedCaches.ts +0 -34
  60. package/src/createHandlerBoundToURL.ts +0 -32
  61. package/src/getCacheKeyForURL.ts +0 -33
  62. package/src/matchPrecache.ts +0 -28
  63. package/src/precache.ts +0 -33
  64. package/src/precacheAndRoute.ts +0 -29
  65. package/src/utils/PrecacheCacheKeyPlugin.ts +0 -36
  66. package/src/utils/PrecacheInstallReportPlugin.ts +0 -49
  67. package/src/utils/createCacheKey.ts +0 -68
  68. package/src/utils/deleteOutdatedCaches.ts +0 -42
  69. package/src/utils/generateURLVariations.ts +0 -55
  70. package/src/utils/getCacheKeyForURL.ts +0 -36
  71. package/src/utils/getOrCreatePrecacheController.ts +0 -22
  72. package/src/utils/printCleanupDetails.ts +0 -38
  73. package/src/utils/printInstallDetails.ts +0 -53
  74. package/src/utils/removeIgnoredSearchParams.ts +0 -29
package/dist/index.d.ts CHANGED
@@ -1,25 +1,6 @@
1
- import { PrecacheController } from "./PrecacheController.js";
2
- import { PrecacheFallbackPlugin } from "./PrecacheFallbackPlugin.js";
3
- import { PrecacheRoute } from "./PrecacheRoute.js";
4
- import { PrecacheStrategy } from "./PrecacheStrategy.js";
5
- import { addPlugins } from "./addPlugins.js";
6
- import { addRoute } from "./addRoute.js";
7
- import { cleanupOutdatedCaches } from "./cleanupOutdatedCaches.js";
8
- import { createHandlerBoundToURL } from "./createHandlerBoundToURL.js";
9
- import { getCacheKeyForURL } from "./getCacheKeyForURL.js";
10
- import { matchPrecache } from "./matchPrecache.js";
11
- import { precache } from "./precache.js";
12
- import { precacheAndRoute } from "./precacheAndRoute.js";
13
- /**
14
- * Most consumers of this module will want to use the
15
- * `@serwist/precaching.precacheAndRoute`
16
- * method to add assets to the cache and respond to network requests with these
17
- * cached assets.
18
- *
19
- * If you require more control over caching and routing, you can use the
20
- * `@serwist/precaching.PrecacheController`
21
- * interface.
22
- */
23
- export { addPlugins, addRoute, cleanupOutdatedCaches, createHandlerBoundToURL, getCacheKeyForURL, matchPrecache, precache, precacheAndRoute, PrecacheController, PrecacheFallbackPlugin, PrecacheRoute, PrecacheStrategy, };
24
- export * from "./_types.js";
1
+ export { addPlugins, addRoute, cleanupOutdatedCaches, createHandlerBoundToURL, getCacheKeyForURL, matchPrecache, precache, precacheAndRoute, PrecacheController, PrecacheRoute, PrecacheStrategy, } from "@serwist/sw/precaching";
2
+ export { PrecacheFallbackPlugin } from "@serwist/sw/plugins";
3
+ export type * from "@serwist/sw/precaching";
4
+ export type { UrlManipulation as urlManipulation } from "@serwist/sw/precaching";
5
+ export type { PrecacheFallbackEntry, PrecacheFallbackPluginOptions } from "@serwist/sw/plugins";
25
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD;;;;;;;;;GASG;AAEH,OAAO,EACL,UAAU,EACV,QAAQ,EACR,qBAAqB,EACrB,uBAAuB,EACvB,iBAAiB,EACjB,aAAa,EACb,QAAQ,EACR,gBAAgB,EAChB,kBAAkB,EAClB,sBAAsB,EACtB,aAAa,EACb,gBAAgB,GACjB,CAAC;AAEF,cAAc,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,QAAQ,EACR,qBAAqB,EACrB,uBAAuB,EACvB,iBAAiB,EACjB,aAAa,EACb,QAAQ,EACR,gBAAgB,EAChB,kBAAkB,EAClB,aAAa,EACb,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,mBAAmB,wBAAwB,CAAC;AAC5C,YAAY,EAAE,eAAe,IAAI,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACjF,YAAY,EAAE,qBAAqB,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -1,533 +1,2 @@
1
- import { privateCacheNames, logger, getFriendlyURL, SerwistError, assert, waitUntil } from '@serwist/core/internal';
2
- import { copyResponse } from '@serwist/core';
3
- import { Strategy } from '@serwist/strategies';
4
- import { Route, registerRoute } from '@serwist/routing';
5
-
6
- class PrecacheStrategy extends Strategy {
7
- _fallbackToNetwork;
8
- static defaultPrecacheCacheabilityPlugin = {
9
- async cacheWillUpdate ({ response }) {
10
- if (!response || response.status >= 400) {
11
- return null;
12
- }
13
- return response;
14
- }
15
- };
16
- static copyRedirectedCacheableResponsesPlugin = {
17
- async cacheWillUpdate ({ response }) {
18
- return response.redirected ? await copyResponse(response) : response;
19
- }
20
- };
21
- constructor(options = {}){
22
- options.cacheName = privateCacheNames.getPrecacheName(options.cacheName);
23
- super(options);
24
- this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
25
- this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
26
- }
27
- async _handle(request, handler) {
28
- const response = await handler.cacheMatch(request);
29
- if (response) {
30
- return response;
31
- }
32
- if (handler.event && handler.event.type === "install") {
33
- return await this._handleInstall(request, handler);
34
- }
35
- return await this._handleFetch(request, handler);
36
- }
37
- async _handleFetch(request, handler) {
38
- let response = undefined;
39
- const params = handler.params || {};
40
- if (this._fallbackToNetwork) {
41
- if (process.env.NODE_ENV !== "production") {
42
- logger.warn(`The precached response for ${getFriendlyURL(request.url)} in ${this.cacheName} was not found. Falling back to the network.`);
43
- }
44
- const integrityInManifest = params.integrity;
45
- const integrityInRequest = request.integrity;
46
- const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
47
- response = await handler.fetch(new Request(request, {
48
- integrity: request.mode !== "no-cors" ? integrityInRequest || integrityInManifest : undefined
49
- }));
50
- if (integrityInManifest && noIntegrityConflict && request.mode !== "no-cors") {
51
- this._useDefaultCacheabilityPluginIfNeeded();
52
- const wasCached = await handler.cachePut(request, response.clone());
53
- if (process.env.NODE_ENV !== "production") {
54
- if (wasCached) {
55
- logger.log(`A response for ${getFriendlyURL(request.url)} was used to "repair" the precache.`);
56
- }
57
- }
58
- }
59
- } else {
60
- throw new SerwistError("missing-precache-entry", {
61
- cacheName: this.cacheName,
62
- url: request.url
63
- });
64
- }
65
- if (process.env.NODE_ENV !== "production") {
66
- const cacheKey = params.cacheKey || await handler.getCacheKey(request, "read");
67
- logger.groupCollapsed(`Precaching is responding to: ${getFriendlyURL(request.url)}`);
68
- logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
69
- logger.groupCollapsed("View request details here.");
70
- logger.log(request);
71
- logger.groupEnd();
72
- logger.groupCollapsed("View response details here.");
73
- logger.log(response);
74
- logger.groupEnd();
75
- logger.groupEnd();
76
- }
77
- return response;
78
- }
79
- async _handleInstall(request, handler) {
80
- this._useDefaultCacheabilityPluginIfNeeded();
81
- const response = await handler.fetch(request);
82
- const wasCached = await handler.cachePut(request, response.clone());
83
- if (!wasCached) {
84
- throw new SerwistError("bad-precaching-response", {
85
- url: request.url,
86
- status: response.status
87
- });
88
- }
89
- return response;
90
- }
91
- _useDefaultCacheabilityPluginIfNeeded() {
92
- let defaultPluginIndex = null;
93
- let cacheWillUpdatePluginCount = 0;
94
- for (const [index, plugin] of this.plugins.entries()){
95
- if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
96
- continue;
97
- }
98
- if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
99
- defaultPluginIndex = index;
100
- }
101
- if (plugin.cacheWillUpdate) {
102
- cacheWillUpdatePluginCount++;
103
- }
104
- }
105
- if (cacheWillUpdatePluginCount === 0) {
106
- this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
107
- } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
108
- this.plugins.splice(defaultPluginIndex, 1);
109
- }
110
- }
111
- }
112
-
113
- class PrecacheCacheKeyPlugin {
114
- _precacheController;
115
- constructor({ precacheController }){
116
- this._precacheController = precacheController;
117
- }
118
- cacheKeyWillBeUsed = async ({ request, params })=>{
119
- const cacheKey = params?.cacheKey || this._precacheController.getCacheKeyForURL(request.url);
120
- return cacheKey ? new Request(cacheKey, {
121
- headers: request.headers
122
- }) : request;
123
- };
124
- }
125
-
126
- class PrecacheInstallReportPlugin {
127
- updatedURLs = [];
128
- notUpdatedURLs = [];
129
- handlerWillStart = async ({ request, state })=>{
130
- if (state) {
131
- state.originalRequest = request;
132
- }
133
- };
134
- cachedResponseWillBeUsed = async ({ event, state, cachedResponse })=>{
135
- if (event.type === "install") {
136
- if (state?.originalRequest && state.originalRequest instanceof Request) {
137
- const url = state.originalRequest.url;
138
- if (cachedResponse) {
139
- this.notUpdatedURLs.push(url);
140
- } else {
141
- this.updatedURLs.push(url);
142
- }
143
- }
144
- }
145
- return cachedResponse;
146
- };
147
- }
148
-
149
- const REVISION_SEARCH_PARAM = "__WB_REVISION__";
150
- function createCacheKey(entry) {
151
- if (!entry) {
152
- throw new SerwistError("add-to-cache-list-unexpected-type", {
153
- entry
154
- });
155
- }
156
- if (typeof entry === "string") {
157
- const urlObject = new URL(entry, location.href);
158
- return {
159
- cacheKey: urlObject.href,
160
- url: urlObject.href
161
- };
162
- }
163
- const { revision, url } = entry;
164
- if (!url) {
165
- throw new SerwistError("add-to-cache-list-unexpected-type", {
166
- entry
167
- });
168
- }
169
- if (!revision) {
170
- const urlObject = new URL(url, location.href);
171
- return {
172
- cacheKey: urlObject.href,
173
- url: urlObject.href
174
- };
175
- }
176
- const cacheKeyURL = new URL(url, location.href);
177
- const originalURL = new URL(url, location.href);
178
- cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
179
- return {
180
- cacheKey: cacheKeyURL.href,
181
- url: originalURL.href
182
- };
183
- }
184
-
185
- const logGroup = (groupTitle, deletedURLs)=>{
186
- logger.groupCollapsed(groupTitle);
187
- for (const url of deletedURLs){
188
- logger.log(url);
189
- }
190
- logger.groupEnd();
191
- };
192
- function printCleanupDetails(deletedURLs) {
193
- const deletionCount = deletedURLs.length;
194
- if (deletionCount > 0) {
195
- logger.groupCollapsed(`During precaching cleanup, ${deletionCount} cached request${deletionCount === 1 ? " was" : "s were"} deleted.`);
196
- logGroup("Deleted Cache Requests", deletedURLs);
197
- logger.groupEnd();
198
- }
199
- }
200
-
201
- function _nestedGroup(groupTitle, urls) {
202
- if (urls.length === 0) {
203
- return;
204
- }
205
- logger.groupCollapsed(groupTitle);
206
- for (const url of urls){
207
- logger.log(url);
208
- }
209
- logger.groupEnd();
210
- }
211
- function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
212
- const precachedCount = urlsToPrecache.length;
213
- const alreadyPrecachedCount = urlsAlreadyPrecached.length;
214
- if (precachedCount || alreadyPrecachedCount) {
215
- let message = `Precaching ${precachedCount} file${precachedCount === 1 ? "" : "s"}.`;
216
- if (alreadyPrecachedCount > 0) {
217
- message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? " is" : "s are"} already cached.`;
218
- }
219
- logger.groupCollapsed(message);
220
- _nestedGroup("View newly precached URLs.", urlsToPrecache);
221
- _nestedGroup("View previously precached URLs.", urlsAlreadyPrecached);
222
- logger.groupEnd();
223
- }
224
- }
225
-
226
- class PrecacheController {
227
- _installAndActiveListenersAdded;
228
- _strategy;
229
- _urlsToCacheKeys = new Map();
230
- _urlsToCacheModes = new Map();
231
- _cacheKeysToIntegrities = new Map();
232
- constructor({ cacheName, plugins = [], fallbackToNetwork = true } = {}){
233
- this._strategy = new PrecacheStrategy({
234
- cacheName: privateCacheNames.getPrecacheName(cacheName),
235
- plugins: [
236
- ...plugins,
237
- new PrecacheCacheKeyPlugin({
238
- precacheController: this
239
- })
240
- ],
241
- fallbackToNetwork
242
- });
243
- this.install = this.install.bind(this);
244
- this.activate = this.activate.bind(this);
245
- }
246
- get strategy() {
247
- return this._strategy;
248
- }
249
- precache(entries) {
250
- this.addToCacheList(entries);
251
- if (!this._installAndActiveListenersAdded) {
252
- self.addEventListener("install", this.install);
253
- self.addEventListener("activate", this.activate);
254
- this._installAndActiveListenersAdded = true;
255
- }
256
- }
257
- addToCacheList(entries) {
258
- if (process.env.NODE_ENV !== "production") {
259
- assert.isArray(entries, {
260
- moduleName: "@serwist/precaching",
261
- className: "PrecacheController",
262
- funcName: "addToCacheList",
263
- paramName: "entries"
264
- });
265
- }
266
- const urlsToWarnAbout = [];
267
- for (const entry of entries){
268
- if (typeof entry === "string") {
269
- urlsToWarnAbout.push(entry);
270
- } else if (entry && entry.revision === undefined) {
271
- urlsToWarnAbout.push(entry.url);
272
- }
273
- const { cacheKey, url } = createCacheKey(entry);
274
- const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default";
275
- if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
276
- throw new SerwistError("add-to-cache-list-conflicting-entries", {
277
- firstEntry: this._urlsToCacheKeys.get(url),
278
- secondEntry: cacheKey
279
- });
280
- }
281
- if (typeof entry !== "string" && entry.integrity) {
282
- if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
283
- throw new SerwistError("add-to-cache-list-conflicting-integrities", {
284
- url
285
- });
286
- }
287
- this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
288
- }
289
- this._urlsToCacheKeys.set(url, cacheKey);
290
- this._urlsToCacheModes.set(url, cacheMode);
291
- if (urlsToWarnAbout.length > 0) {
292
- const warningMessage = `Serwist is precaching URLs without revision info: ${urlsToWarnAbout.join(", ")}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;
293
- if (process.env.NODE_ENV === "production") {
294
- console.warn(warningMessage);
295
- } else {
296
- logger.warn(warningMessage);
297
- }
298
- }
299
- }
300
- }
301
- install(event) {
302
- return waitUntil(event, async ()=>{
303
- const installReportPlugin = new PrecacheInstallReportPlugin();
304
- this.strategy.plugins.push(installReportPlugin);
305
- for (const [url, cacheKey] of this._urlsToCacheKeys){
306
- const integrity = this._cacheKeysToIntegrities.get(cacheKey);
307
- const cacheMode = this._urlsToCacheModes.get(url);
308
- const request = new Request(url, {
309
- integrity,
310
- cache: cacheMode,
311
- credentials: "same-origin"
312
- });
313
- await Promise.all(this.strategy.handleAll({
314
- params: {
315
- cacheKey
316
- },
317
- request,
318
- event
319
- }));
320
- }
321
- const { updatedURLs, notUpdatedURLs } = installReportPlugin;
322
- if (process.env.NODE_ENV !== "production") {
323
- printInstallDetails(updatedURLs, notUpdatedURLs);
324
- }
325
- return {
326
- updatedURLs,
327
- notUpdatedURLs
328
- };
329
- });
330
- }
331
- activate(event) {
332
- return waitUntil(event, async ()=>{
333
- const cache = await self.caches.open(this.strategy.cacheName);
334
- const currentlyCachedRequests = await cache.keys();
335
- const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
336
- const deletedURLs = [];
337
- for (const request of currentlyCachedRequests){
338
- if (!expectedCacheKeys.has(request.url)) {
339
- await cache.delete(request);
340
- deletedURLs.push(request.url);
341
- }
342
- }
343
- if (process.env.NODE_ENV !== "production") {
344
- printCleanupDetails(deletedURLs);
345
- }
346
- return {
347
- deletedURLs
348
- };
349
- });
350
- }
351
- getURLsToCacheKeys() {
352
- return this._urlsToCacheKeys;
353
- }
354
- getCachedURLs() {
355
- return [
356
- ...this._urlsToCacheKeys.keys()
357
- ];
358
- }
359
- getCacheKeyForURL(url) {
360
- const urlObject = new URL(url, location.href);
361
- return this._urlsToCacheKeys.get(urlObject.href);
362
- }
363
- getIntegrityForCacheKey(cacheKey) {
364
- return this._cacheKeysToIntegrities.get(cacheKey);
365
- }
366
- async matchPrecache(request) {
367
- const url = request instanceof Request ? request.url : request;
368
- const cacheKey = this.getCacheKeyForURL(url);
369
- if (cacheKey) {
370
- const cache = await self.caches.open(this.strategy.cacheName);
371
- return cache.match(cacheKey);
372
- }
373
- return undefined;
374
- }
375
- createHandlerBoundToURL(url) {
376
- const cacheKey = this.getCacheKeyForURL(url);
377
- if (!cacheKey) {
378
- throw new SerwistError("non-precached-url", {
379
- url
380
- });
381
- }
382
- return (options)=>{
383
- options.request = new Request(url);
384
- options.params = {
385
- cacheKey,
386
- ...options.params
387
- };
388
- return this.strategy.handle(options);
389
- };
390
- }
391
- }
392
-
393
- let precacheController;
394
- const getOrCreatePrecacheController = ()=>{
395
- if (!precacheController) {
396
- precacheController = new PrecacheController();
397
- }
398
- return precacheController;
399
- };
400
-
401
- class PrecacheFallbackPlugin {
402
- _fallbackURL;
403
- _precacheController;
404
- constructor({ fallbackURL, precacheController }){
405
- this._fallbackURL = fallbackURL;
406
- this._precacheController = precacheController || getOrCreatePrecacheController();
407
- }
408
- handlerDidError = ()=>this._precacheController.matchPrecache(this._fallbackURL);
409
- }
410
-
411
- function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {
412
- for (const paramName of [
413
- ...urlObject.searchParams.keys()
414
- ]){
415
- if (ignoreURLParametersMatching.some((regExp)=>regExp.test(paramName))) {
416
- urlObject.searchParams.delete(paramName);
417
- }
418
- }
419
- return urlObject;
420
- }
421
-
422
- function* generateURLVariations(url, { ignoreURLParametersMatching = [
423
- /^utm_/,
424
- /^fbclid$/
425
- ], directoryIndex = "index.html", cleanURLs = true, urlManipulation } = {}) {
426
- const urlObject = new URL(url, location.href);
427
- urlObject.hash = "";
428
- yield urlObject.href;
429
- const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
430
- yield urlWithoutIgnoredParams.href;
431
- if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith("/")) {
432
- const directoryURL = new URL(urlWithoutIgnoredParams.href);
433
- directoryURL.pathname += directoryIndex;
434
- yield directoryURL.href;
435
- }
436
- if (cleanURLs) {
437
- const cleanURL = new URL(urlWithoutIgnoredParams.href);
438
- cleanURL.pathname += ".html";
439
- yield cleanURL.href;
440
- }
441
- if (urlManipulation) {
442
- const additionalURLs = urlManipulation({
443
- url: urlObject
444
- });
445
- for (const urlToAttempt of additionalURLs){
446
- yield urlToAttempt.href;
447
- }
448
- }
449
- }
450
-
451
- class PrecacheRoute extends Route {
452
- constructor(precacheController, options){
453
- const match = ({ request })=>{
454
- const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
455
- for (const possibleURL of generateURLVariations(request.url, options)){
456
- const cacheKey = urlsToCacheKeys.get(possibleURL);
457
- if (cacheKey) {
458
- const integrity = precacheController.getIntegrityForCacheKey(cacheKey);
459
- return {
460
- cacheKey,
461
- integrity
462
- };
463
- }
464
- }
465
- if (process.env.NODE_ENV !== "production") {
466
- logger.debug(`Precaching did not find a match for ${getFriendlyURL(request.url)}`);
467
- }
468
- return;
469
- };
470
- super(match, precacheController.strategy);
471
- }
472
- }
473
-
474
- function addPlugins(plugins) {
475
- const precacheController = getOrCreatePrecacheController();
476
- precacheController.strategy.plugins.push(...plugins);
477
- }
478
-
479
- function addRoute(options) {
480
- const precacheController = getOrCreatePrecacheController();
481
- const precacheRoute = new PrecacheRoute(precacheController, options);
482
- registerRoute(precacheRoute);
483
- }
484
-
485
- const SUBSTRING_TO_FIND = "-precache-";
486
- const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND)=>{
487
- const cacheNames = await self.caches.keys();
488
- const cacheNamesToDelete = cacheNames.filter((cacheName)=>{
489
- return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
490
- });
491
- await Promise.all(cacheNamesToDelete.map((cacheName)=>self.caches.delete(cacheName)));
492
- return cacheNamesToDelete;
493
- };
494
-
495
- function cleanupOutdatedCaches() {
496
- self.addEventListener("activate", (event)=>{
497
- const cacheName = privateCacheNames.getPrecacheName();
498
- event.waitUntil(deleteOutdatedCaches(cacheName).then((cachesDeleted)=>{
499
- if (process.env.NODE_ENV !== "production") {
500
- if (cachesDeleted.length > 0) {
501
- logger.log("The following out-of-date precaches were cleaned up " + "automatically:", cachesDeleted);
502
- }
503
- }
504
- }));
505
- });
506
- }
507
-
508
- function createHandlerBoundToURL(url) {
509
- const precacheController = getOrCreatePrecacheController();
510
- return precacheController.createHandlerBoundToURL(url);
511
- }
512
-
513
- function getCacheKeyForURL(url) {
514
- const precacheController = getOrCreatePrecacheController();
515
- return precacheController.getCacheKeyForURL(url);
516
- }
517
-
518
- function matchPrecache(request) {
519
- const precacheController = getOrCreatePrecacheController();
520
- return precacheController.matchPrecache(request);
521
- }
522
-
523
- function precache(entries) {
524
- const precacheController = getOrCreatePrecacheController();
525
- precacheController.precache(entries);
526
- }
527
-
528
- function precacheAndRoute(entries, options) {
529
- precache(entries);
530
- addRoute(options);
531
- }
532
-
533
- export { PrecacheController, PrecacheFallbackPlugin, PrecacheRoute, PrecacheStrategy, addPlugins, addRoute, cleanupOutdatedCaches, createHandlerBoundToURL, getCacheKeyForURL, matchPrecache, precache, precacheAndRoute };
1
+ export { PrecacheController, PrecacheRoute, PrecacheStrategy, addPlugins, addRoute, cleanupOutdatedCaches, createHandlerBoundToURL, getCacheKeyForURL, matchPrecache, precache, precacheAndRoute } from '@serwist/sw/precaching';
2
+ export { PrecacheFallbackPlugin } from '@serwist/sw/plugins';
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@serwist/precaching",
3
- "version": "9.0.0-preview.2",
3
+ "version": "9.0.0-preview.21",
4
4
  "type": "module",
5
- "description": "This module efficiently precaches assets.",
5
+ "description": "A module that efficiently precaches assets.",
6
6
  "files": [
7
7
  "src",
8
8
  "dist"
@@ -15,8 +15,8 @@
15
15
  ],
16
16
  "author": "Google's Web DevRel Team, Serwist's Team",
17
17
  "license": "MIT",
18
- "repository": "serwist/serwist",
19
- "bugs": "https://github.com/serwist/serwist/issues",
18
+ "repository": "https://gitlab.com/serwist/serwist",
19
+ "bugs": "https://gitlab.com/serwist/serwist/issues",
20
20
  "homepage": "https://serwist.pages.dev",
21
21
  "main": "./dist/index.js",
22
22
  "types": "./dist/index.d.ts",
@@ -28,14 +28,12 @@
28
28
  "./package.json": "./package.json"
29
29
  },
30
30
  "dependencies": {
31
- "@serwist/core": "9.0.0-preview.2",
32
- "@serwist/routing": "9.0.0-preview.2",
33
- "@serwist/strategies": "9.0.0-preview.2"
31
+ "@serwist/sw": "9.0.0-preview.21"
34
32
  },
35
33
  "devDependencies": {
36
- "rollup": "4.9.6",
37
- "typescript": "5.4.0-dev.20240206",
38
- "@serwist/constants": "9.0.0-preview.2"
34
+ "rollup": "4.13.0",
35
+ "typescript": "5.5.0-dev.20240323",
36
+ "@serwist/constants": "9.0.0-preview.21"
39
37
  },
40
38
  "peerDependencies": {
41
39
  "typescript": ">=5.0.0"
@@ -47,7 +45,6 @@
47
45
  },
48
46
  "scripts": {
49
47
  "build": "rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js",
50
- "dev": "rollup --config rollup.config.js --watch",
51
48
  "lint": "biome lint ./src",
52
49
  "typecheck": "tsc"
53
50
  }
package/src/index.ts CHANGED
@@ -1,35 +1,3 @@
1
- /*
2
- Copyright 2018 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 { PrecacheController } from "./PrecacheController.js";
10
- import { PrecacheFallbackPlugin } from "./PrecacheFallbackPlugin.js";
11
- import { PrecacheRoute } from "./PrecacheRoute.js";
12
- import { PrecacheStrategy } from "./PrecacheStrategy.js";
13
- import { addPlugins } from "./addPlugins.js";
14
- import { addRoute } from "./addRoute.js";
15
- import { cleanupOutdatedCaches } from "./cleanupOutdatedCaches.js";
16
- import { createHandlerBoundToURL } from "./createHandlerBoundToURL.js";
17
- import { getCacheKeyForURL } from "./getCacheKeyForURL.js";
18
- import { matchPrecache } from "./matchPrecache.js";
19
- import { precache } from "./precache.js";
20
- import { precacheAndRoute } from "./precacheAndRoute.js";
21
-
22
- /**
23
- * Most consumers of this module will want to use the
24
- * `@serwist/precaching.precacheAndRoute`
25
- * method to add assets to the cache and respond to network requests with these
26
- * cached assets.
27
- *
28
- * If you require more control over caching and routing, you can use the
29
- * `@serwist/precaching.PrecacheController`
30
- * interface.
31
- */
32
-
33
1
  export {
34
2
  addPlugins,
35
3
  addRoute,
@@ -40,9 +8,10 @@ export {
40
8
  precache,
41
9
  precacheAndRoute,
42
10
  PrecacheController,
43
- PrecacheFallbackPlugin,
44
11
  PrecacheRoute,
45
12
  PrecacheStrategy,
46
- };
47
-
48
- export * from "./_types.js";
13
+ } from "@serwist/sw/precaching";
14
+ export { PrecacheFallbackPlugin } from "@serwist/sw/plugins";
15
+ export type * from "@serwist/sw/precaching";
16
+ export type { UrlManipulation as urlManipulation } from "@serwist/sw/precaching";
17
+ export type { PrecacheFallbackEntry, PrecacheFallbackPluginOptions } from "@serwist/sw/plugins";