@serwist/core 8.1.1 → 8.3.0

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 (36) hide show
  1. package/dist/_private/Deferred.d.cts +18 -0
  2. package/dist/_private/SerwistError.d.cts +23 -0
  3. package/dist/_private/assert.d.cts +10 -0
  4. package/dist/_private/cacheMatchIgnoreParams.d.cts +14 -0
  5. package/dist/_private/cacheNames.d.cts +39 -0
  6. package/dist/_private/canConstructReadableStream.d.cts +11 -0
  7. package/dist/_private/canConstructResponseFromBodyStream.d.cts +10 -0
  8. package/dist/_private/dontWaitFor.d.cts +6 -0
  9. package/dist/_private/executeQuotaErrorCallbacks.d.cts +8 -0
  10. package/dist/_private/getFriendlyURL.d.cts +2 -0
  11. package/dist/_private/logger.d.cts +10 -0
  12. package/dist/_private/resultingClientExists.d.cts +11 -0
  13. package/dist/_private/timeout.d.cts +9 -0
  14. package/dist/_private/waitUntil.d.cts +0 -0
  15. package/dist/cacheNames.d.cts +20 -0
  16. package/dist/clientsClaim.d.cts +6 -0
  17. package/dist/copyResponse.d.cts +20 -0
  18. package/dist/index.cjs +154 -0
  19. package/dist/index.internal.cjs +244 -0
  20. package/dist/index.internal.d.cts +0 -0
  21. package/dist/index.internal.js +7 -429
  22. package/dist/index.js +1 -424
  23. package/dist/models/messages/messageGenerator.d.cts +1 -0
  24. package/dist/models/messages/messages.d.cts +8 -0
  25. package/dist/models/pluginEvents.d.cts +9 -0
  26. package/dist/models/quotaErrorCallbacks.d.cts +2 -0
  27. package/dist/{index.old.cjs → quotaErrorCallbacks.cjs} +6 -150
  28. package/dist/{index.internal.old.cjs → quotaErrorCallbacks.js} +81 -322
  29. package/dist/registerQuotaErrorCallback.d.cts +0 -0
  30. package/dist/setCacheNameDetails.d.cts +0 -0
  31. package/dist/types.d.cts +272 -0
  32. package/dist/utils/pluginUtils.d.cts +4 -0
  33. package/dist/utils/welcome.d.cts +1 -0
  34. package/package.json +7 -7
  35. package/dist/index.internal.old.d.cts +0 -15
  36. /package/dist/{index.old.d.cts → index.d.cts} +0 -0
@@ -1,270 +1,5 @@
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
- */ const messages = {
8
- "invalid-value": ({ paramName, validValueDescription, value })=>{
9
- if (!paramName || !validValueDescription) {
10
- throw new Error(`Unexpected input to 'invalid-value' error.`);
11
- }
12
- return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
13
- },
14
- "not-an-array": ({ moduleName, className, funcName, paramName })=>{
15
- if (!moduleName || !className || !funcName || !paramName) {
16
- throw new Error(`Unexpected input to 'not-an-array' error.`);
17
- }
18
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
19
- },
20
- "incorrect-type": ({ expectedType, paramName, moduleName, className, funcName })=>{
21
- if (!expectedType || !paramName || !moduleName || !funcName) {
22
- throw new Error(`Unexpected input to 'incorrect-type' error.`);
23
- }
24
- const classNameStr = className ? `${className}.` : "";
25
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
26
- },
27
- "incorrect-class": ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem })=>{
28
- if (!expectedClassName || !moduleName || !funcName) {
29
- throw new Error(`Unexpected input to 'incorrect-class' error.`);
30
- }
31
- const classNameStr = className ? `${className}.` : "";
32
- if (isReturnValueProblem) {
33
- return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
34
- }
35
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
36
- },
37
- "missing-a-method": ({ expectedMethod, paramName, moduleName, className, funcName })=>{
38
- if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
39
- throw new Error(`Unexpected input to 'missing-a-method' error.`);
40
- }
41
- return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
42
- },
43
- "add-to-cache-list-unexpected-type": ({ entry })=>{
44
- return `An unexpected entry was passed to ` + `'@serwist/precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`;
45
- },
46
- "add-to-cache-list-conflicting-entries": ({ firstEntry, secondEntry })=>{
47
- if (!firstEntry || !secondEntry) {
48
- throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
49
- }
50
- return `Two of the entries passed to ` + `'@serwist/precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry} but different revision details. Serwist is ` + `unable to cache and version the asset correctly. Please remove one ` + `of the entries.`;
51
- },
52
- "plugin-error-request-will-fetch": ({ thrownErrorMessage })=>{
53
- if (!thrownErrorMessage) {
54
- throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
55
- }
56
- return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`;
57
- },
58
- "invalid-cache-name": ({ cacheNameId, value })=>{
59
- if (!cacheNameId) {
60
- throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
61
- }
62
- return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
63
- },
64
- "unregister-route-but-not-found-with-method": ({ method })=>{
65
- if (!method) {
66
- throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
67
- }
68
- return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
69
- },
70
- "unregister-route-route-not-registered": ()=>{
71
- return `The route you're trying to unregister was not previously ` + `registered.`;
72
- },
73
- "queue-replay-failed": ({ name })=>{
74
- return `Replaying the background sync queue '${name}' failed.`;
75
- },
76
- "duplicate-queue-name": ({ name })=>{
77
- return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
78
- },
79
- "expired-test-without-max-age": ({ methodName, paramName })=>{
80
- return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
81
- },
82
- "unsupported-route-type": ({ moduleName, className, funcName, paramName })=>{
83
- return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
84
- },
85
- "not-array-of-class": ({ value, expectedClass, moduleName, className, funcName, paramName })=>{
86
- return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`;
87
- },
88
- "max-entries-or-age-required": ({ moduleName, className, funcName })=>{
89
- return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
90
- },
91
- "statuses-or-headers-required": ({ moduleName, className, funcName })=>{
92
- return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
93
- },
94
- "invalid-string": ({ moduleName, funcName, paramName })=>{
95
- if (!paramName || !moduleName || !funcName) {
96
- throw new Error(`Unexpected input to 'invalid-string' error.`);
97
- }
98
- return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.`;
99
- },
100
- "channel-name-required": ()=>{
101
- return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
102
- },
103
- "invalid-responses-are-same-args": ()=>{
104
- return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
105
- },
106
- "expire-custom-caches-only": ()=>{
107
- return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
108
- },
109
- "unit-must-be-bytes": ({ normalizedRangeHeader })=>{
110
- if (!normalizedRangeHeader) {
111
- throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
112
- }
113
- return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
114
- },
115
- "single-range-only": ({ normalizedRangeHeader })=>{
116
- if (!normalizedRangeHeader) {
117
- throw new Error(`Unexpected input to 'single-range-only' error.`);
118
- }
119
- return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
120
- },
121
- "invalid-range-values": ({ normalizedRangeHeader })=>{
122
- if (!normalizedRangeHeader) {
123
- throw new Error(`Unexpected input to 'invalid-range-values' error.`);
124
- }
125
- return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`;
126
- },
127
- "no-range-header": ()=>{
128
- return `No Range header was found in the Request provided.`;
129
- },
130
- "range-not-satisfiable": ({ size, start, end })=>{
131
- return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
132
- },
133
- "attempt-to-cache-non-get-request": ({ url, method })=>{
134
- return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
135
- },
136
- "cache-put-with-no-response": ({ url })=>{
137
- return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
138
- },
139
- "no-response": ({ url, error })=>{
140
- let message = `The strategy could not generate a response for '${url}'.`;
141
- if (error) {
142
- message += ` The underlying error is ${error}.`;
143
- }
144
- return message;
145
- },
146
- "bad-precaching-response": ({ url, status })=>{
147
- return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`);
148
- },
149
- "non-precached-url": ({ url })=>{
150
- return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
151
- },
152
- "add-to-cache-list-conflicting-integrities": ({ url })=>{
153
- return `Two of the entries passed to ` + `'@serwist/precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
154
- },
155
- "missing-precache-entry": ({ cacheName, url })=>{
156
- return `Unable to find a precached response in ${cacheName} for ${url}.`;
157
- },
158
- "cross-origin-copy-response": ({ origin })=>{
159
- return `@serwist/core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`;
160
- },
161
- "opaque-streams-source": ({ type })=>{
162
- const message = `One of the @serwist/streams sources resulted in an ` + `'${type}' response.`;
163
- if (type === "opaqueredirect") {
164
- return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`;
165
- }
166
- return `${message} Please ensure your sources are CORS-enabled.`;
167
- }
168
- };
169
-
170
- const fallback = (code, ...args)=>{
171
- let msg = code;
172
- if (args.length > 0) {
173
- msg += ` :: ${JSON.stringify(args)}`;
174
- }
175
- return msg;
176
- };
177
- const generatorFunction = (code, details = {})=>{
178
- const message = messages[code];
179
- if (!message) {
180
- throw new Error(`Unable to find message for code '${code}'.`);
181
- }
182
- return message(details);
183
- };
184
- const messageGenerator = process.env.NODE_ENV === "production" ? fallback : generatorFunction;
185
-
186
- /**
187
- * Serwist errors should be thrown with this class.
188
- * This allows use to ensure the type easily in tests,
189
- * helps developers identify errors from Serwist
190
- * easily and allows use to optimise error
191
- * messages correctly.
192
- *
193
- * @private
194
- */ class SerwistError extends Error {
195
- details;
196
- /**
197
- *
198
- * @param errorCode The error code that
199
- * identifies this particular error.
200
- * @param details Any relevant arguments
201
- * that will help developers identify issues should
202
- * be added as a key on the context object.
203
- */ constructor(errorCode, details){
204
- const message = messageGenerator(errorCode, details);
205
- super(message);
206
- this.name = errorCode;
207
- this.details = details;
208
- }
209
- }
210
-
211
- /*
212
- * This method throws if the supplied value is not an array.
213
- * The destructed values are required to produce a meaningful error for users.
214
- * The destructed and restructured object is so it's clear what is
215
- * needed.
216
- */ const isArray = (value, details)=>{
217
- if (!Array.isArray(value)) {
218
- throw new SerwistError("not-an-array", details);
219
- }
220
- };
221
- const hasMethod = (object, expectedMethod, details)=>{
222
- const type = typeof object[expectedMethod];
223
- if (type !== "function") {
224
- details["expectedMethod"] = expectedMethod;
225
- throw new SerwistError("missing-a-method", details);
226
- }
227
- };
228
- const isType = (object, expectedType, details)=>{
229
- if (typeof object !== expectedType) {
230
- details["expectedType"] = expectedType;
231
- throw new SerwistError("incorrect-type", details);
232
- }
233
- };
234
- const isInstance = (object, // Need the general type to do the check later.
235
- // eslint-disable-next-line @typescript-eslint/ban-types
236
- expectedClass, details)=>{
237
- if (!(object instanceof expectedClass)) {
238
- details["expectedClassName"] = expectedClass.name;
239
- throw new SerwistError("incorrect-class", details);
240
- }
241
- };
242
- const isOneOf = (value, validValues, details)=>{
243
- if (!validValues.includes(value)) {
244
- details["validValueDescription"] = `Valid values are ${JSON.stringify(validValues)}.`;
245
- throw new SerwistError("invalid-value", details);
246
- }
247
- };
248
- const isArrayOfClass = (value, // Need general type to do check later.
249
- expectedClass, details)=>{
250
- const error = new SerwistError("not-array-of-class", details);
251
- if (!Array.isArray(value)) {
252
- throw error;
253
- }
254
- for (const item of value){
255
- if (!(item instanceof expectedClass)) {
256
- throw error;
257
- }
258
- }
259
- };
260
- const finalAssertExports = process.env.NODE_ENV === "production" ? null : {
261
- hasMethod,
262
- isArray,
263
- isInstance,
264
- isOneOf,
265
- isType,
266
- isArrayOfClass
267
- };
1
+ import { l as logger, q as quotaErrorCallbacks } from './quotaErrorCallbacks.js';
2
+ export { S as SerwistError, f as assert, a as canConstructResponseFromBodyStream, c as privateCacheNames } from './quotaErrorCallbacks.js';
268
3
 
269
4
  /*
270
5
  Copyright 2020 Google LLC
@@ -310,64 +45,13 @@ const finalAssertExports = process.env.NODE_ENV === "production" ? null : {
310
45
  return;
311
46
  }
312
47
 
313
- /*
314
- Copyright 2018 Google LLC
315
-
316
- Use of this source code is governed by an MIT-style
317
- license that can be found in the LICENSE file or at
318
- https://opensource.org/licenses/MIT.
319
- */ const _cacheNameDetails = {
320
- googleAnalytics: "googleAnalytics",
321
- precache: "precache-v2",
322
- prefix: "serwist",
323
- runtime: "runtime",
324
- suffix: typeof registration !== "undefined" ? registration.scope : ""
325
- };
326
- const _createCacheName = (cacheName)=>{
327
- return [
328
- _cacheNameDetails.prefix,
329
- cacheName,
330
- _cacheNameDetails.suffix
331
- ].filter((value)=>value && value.length > 0).join("-");
332
- };
333
- const eachCacheNameDetail = (fn)=>{
334
- for (const key of Object.keys(_cacheNameDetails)){
335
- fn(key);
336
- }
337
- };
338
- const cacheNames = {
339
- updateDetails: (details)=>{
340
- eachCacheNameDetail((key)=>{
341
- const detail = details[key];
342
- if (typeof detail === "string") {
343
- _cacheNameDetails[key] = detail;
344
- }
345
- });
346
- },
347
- getGoogleAnalyticsName: (userCacheName)=>{
348
- return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
349
- },
350
- getPrecacheName: (userCacheName)=>{
351
- return userCacheName || _createCacheName(_cacheNameDetails.precache);
352
- },
353
- getPrefix: ()=>{
354
- return _cacheNameDetails.prefix;
355
- },
356
- getRuntimeName: (userCacheName)=>{
357
- return userCacheName || _createCacheName(_cacheNameDetails.runtime);
358
- },
359
- getSuffix: ()=>{
360
- return _cacheNameDetails.suffix;
361
- }
362
- };
363
-
364
48
  /*
365
49
  Copyright 2019 Google LLC
366
50
 
367
51
  Use of this source code is governed by an MIT-style
368
52
  license that can be found in the LICENSE file or at
369
53
  https://opensource.org/licenses/MIT.
370
- */ let supportStatus$1;
54
+ */ let supportStatus;
371
55
  /**
372
56
  * A utility function that determines whether the current browser supports
373
57
  * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)
@@ -377,46 +61,16 @@ const cacheNames = {
377
61
  *
378
62
  * @private
379
63
  */ function canConstructReadableStream() {
380
- if (supportStatus$1 === undefined) {
64
+ if (supportStatus === undefined) {
381
65
  // See https://github.com/GoogleChrome/workbox/issues/1473
382
66
  try {
383
67
  new ReadableStream({
384
68
  start () {}
385
69
  });
386
- supportStatus$1 = true;
70
+ supportStatus = true;
387
71
  } catch (error) {
388
- supportStatus$1 = false;
389
- }
390
- }
391
- return supportStatus$1;
392
- }
393
-
394
- /*
395
- Copyright 2019 Google LLC
396
-
397
- Use of this source code is governed by an MIT-style
398
- license that can be found in the LICENSE file or at
399
- https://opensource.org/licenses/MIT.
400
- */ let supportStatus;
401
- /**
402
- * A utility function that determines whether the current browser supports
403
- * constructing a new `Response` from a `response.body` stream.
404
- *
405
- * @returns `true`, if the current browser can successfully construct
406
- * a `Response` from a `response.body` stream, `false` otherwise.
407
- * @private
408
- */ function canConstructResponseFromBodyStream() {
409
- if (supportStatus === undefined) {
410
- const testResponse = new Response("");
411
- if ("body" in testResponse) {
412
- try {
413
- new Response(testResponse.body);
414
- supportStatus = true;
415
- } catch (error) {
416
- supportStatus = false;
417
- }
72
+ supportStatus = false;
418
73
  }
419
- supportStatus = false;
420
74
  }
421
75
  return supportStatus;
422
76
  }
@@ -462,82 +116,6 @@ const cacheNames = {
462
116
  void promise.then(()=>{});
463
117
  }
464
118
 
465
- /*
466
- Copyright 2019 Google LLC
467
- Use of this source code is governed by an MIT-style
468
- license that can be found in the LICENSE file or at
469
- https://opensource.org/licenses/MIT.
470
- */ // logger is used inside of both service workers and the window global scope.
471
- const logger = process.env.NODE_ENV === "production" ? null : (()=>{
472
- // Don't overwrite this value if it's already set.
473
- // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
474
- if (!("__WB_DISABLE_DEV_LOGS" in globalThis)) {
475
- self.__WB_DISABLE_DEV_LOGS = false;
476
- }
477
- let inGroup = false;
478
- const methodToColorMap = {
479
- debug: `#7f8c8d`,
480
- log: `#2ecc71`,
481
- warn: `#f39c12`,
482
- error: `#c0392b`,
483
- groupCollapsed: `#3498db`,
484
- groupEnd: null
485
- };
486
- const print = function(method, args) {
487
- if (self.__WB_DISABLE_DEV_LOGS) {
488
- return;
489
- }
490
- if (method === "groupCollapsed") {
491
- // Safari doesn't print all console.groupCollapsed() arguments:
492
- // https://bugs.webkit.org/show_bug.cgi?id=182754
493
- if (typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
494
- console[method](...args);
495
- return;
496
- }
497
- }
498
- const styles = [
499
- `background: ${methodToColorMap[method]}`,
500
- `border-radius: 0.5em`,
501
- `color: white`,
502
- `font-weight: bold`,
503
- `padding: 2px 0.5em`
504
- ];
505
- // When in a group, the serwist prefix is not displayed.
506
- const logPrefix = inGroup ? [] : [
507
- "%cserwist",
508
- styles.join(";")
509
- ];
510
- console[method](...logPrefix, ...args);
511
- if (method === "groupCollapsed") {
512
- inGroup = true;
513
- }
514
- if (method === "groupEnd") {
515
- inGroup = false;
516
- }
517
- };
518
- // eslint-disable-next-line @typescript-eslint/ban-types
519
- const api = {};
520
- const loggerMethods = Object.keys(methodToColorMap);
521
- for (const key of loggerMethods){
522
- const method = key;
523
- api[method] = (...args)=>{
524
- print(method, args);
525
- };
526
- }
527
- return api;
528
- })();
529
-
530
- /*
531
- Copyright 2018 Google LLC
532
-
533
- Use of this source code is governed by an MIT-style
534
- license that can be found in the LICENSE file or at
535
- https://opensource.org/licenses/MIT.
536
- */ // Callbacks to be executed whenever there's a quota error.
537
- // Can't change Function type right now.
538
- // eslint-disable-next-line @typescript-eslint/ban-types
539
- const quotaErrorCallbacks = new Set();
540
-
541
119
  /**
542
120
  * Runs all of the callback functions, one at a time sequentially, in the order
543
121
  * in which they were registered.
@@ -649,4 +227,4 @@ const MAX_RETRY_TIME = 2000;
649
227
  return returnPromise;
650
228
  }
651
229
 
652
- export { Deferred, SerwistError, finalAssertExports as assert, cacheMatchIgnoreParams, canConstructReadableStream, canConstructResponseFromBodyStream, dontWaitFor, executeQuotaErrorCallbacks, getFriendlyURL, logger, cacheNames as privateCacheNames, resultingClientExists, timeout, waitUntil };
230
+ export { Deferred, cacheMatchIgnoreParams, canConstructReadableStream, dontWaitFor, executeQuotaErrorCallbacks, getFriendlyURL, logger, resultingClientExists, timeout, waitUntil };