@serwist/core 8.1.0 → 8.2.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 +11 -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.d.cts +0 -0
  20. package/dist/index.internal.cjs +244 -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.internal.old.cjs → quotaErrorCallbacks-efexit-Y.js} +81 -322
  28. package/dist/{index.old.cjs → quotaErrorCallbacks-t3P-jWKl.js} +6 -150
  29. package/dist/registerQuotaErrorCallback.d.cts +8 -0
  30. package/dist/setCacheNameDetails.d.cts +9 -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.old.d.cts +0 -11
  36. /package/dist/{index.internal.old.d.cts → index.internal.d.cts} +0 -0
package/dist/index.js CHANGED
@@ -1,53 +1,4 @@
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 _cacheNameDetails = {
8
- googleAnalytics: "googleAnalytics",
9
- precache: "precache-v2",
10
- prefix: "serwist",
11
- runtime: "runtime",
12
- suffix: typeof registration !== "undefined" ? registration.scope : ""
13
- };
14
- const _createCacheName = (cacheName)=>{
15
- return [
16
- _cacheNameDetails.prefix,
17
- cacheName,
18
- _cacheNameDetails.suffix
19
- ].filter((value)=>value && value.length > 0).join("-");
20
- };
21
- const eachCacheNameDetail = (fn)=>{
22
- for (const key of Object.keys(_cacheNameDetails)){
23
- fn(key);
24
- }
25
- };
26
- const cacheNames$1 = {
27
- updateDetails: (details)=>{
28
- eachCacheNameDetail((key)=>{
29
- const detail = details[key];
30
- if (typeof detail === "string") {
31
- _cacheNameDetails[key] = detail;
32
- }
33
- });
34
- },
35
- getGoogleAnalyticsName: (userCacheName)=>{
36
- return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
37
- },
38
- getPrecacheName: (userCacheName)=>{
39
- return userCacheName || _createCacheName(_cacheNameDetails.precache);
40
- },
41
- getPrefix: ()=>{
42
- return _cacheNameDetails.prefix;
43
- },
44
- getRuntimeName: (userCacheName)=>{
45
- return userCacheName || _createCacheName(_cacheNameDetails.runtime);
46
- },
47
- getSuffix: ()=>{
48
- return _cacheNameDetails.suffix;
49
- }
50
- };
1
+ import { c as cacheNames$1, S as SerwistError, a as canConstructResponseFromBodyStream, f as finalAssertExports, q as quotaErrorCallbacks, l as logger } from './quotaErrorCallbacks-efexit-Y.js';
51
2
 
52
3
  /**
53
4
  * Get the current cache names and prefix/suffix used by Workbox.
@@ -92,246 +43,6 @@ const cacheNames$1 = {
92
43
  self.addEventListener("activate", ()=>self.clients.claim());
93
44
  }
94
45
 
95
- /*
96
- Copyright 2019 Google LLC
97
-
98
- Use of this source code is governed by an MIT-style
99
- license that can be found in the LICENSE file or at
100
- https://opensource.org/licenses/MIT.
101
- */ let supportStatus;
102
- /**
103
- * A utility function that determines whether the current browser supports
104
- * constructing a new `Response` from a `response.body` stream.
105
- *
106
- * @returns `true`, if the current browser can successfully construct
107
- * a `Response` from a `response.body` stream, `false` otherwise.
108
- * @private
109
- */ function canConstructResponseFromBodyStream() {
110
- if (supportStatus === undefined) {
111
- const testResponse = new Response("");
112
- if ("body" in testResponse) {
113
- try {
114
- new Response(testResponse.body);
115
- supportStatus = true;
116
- } catch (error) {
117
- supportStatus = false;
118
- }
119
- }
120
- supportStatus = false;
121
- }
122
- return supportStatus;
123
- }
124
-
125
- /*
126
- Copyright 2018 Google LLC
127
-
128
- Use of this source code is governed by an MIT-style
129
- license that can be found in the LICENSE file or at
130
- https://opensource.org/licenses/MIT.
131
- */ const messages = {
132
- "invalid-value": ({ paramName, validValueDescription, value })=>{
133
- if (!paramName || !validValueDescription) {
134
- throw new Error(`Unexpected input to 'invalid-value' error.`);
135
- }
136
- return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
137
- },
138
- "not-an-array": ({ moduleName, className, funcName, paramName })=>{
139
- if (!moduleName || !className || !funcName || !paramName) {
140
- throw new Error(`Unexpected input to 'not-an-array' error.`);
141
- }
142
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
143
- },
144
- "incorrect-type": ({ expectedType, paramName, moduleName, className, funcName })=>{
145
- if (!expectedType || !paramName || !moduleName || !funcName) {
146
- throw new Error(`Unexpected input to 'incorrect-type' error.`);
147
- }
148
- const classNameStr = className ? `${className}.` : "";
149
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
150
- },
151
- "incorrect-class": ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem })=>{
152
- if (!expectedClassName || !moduleName || !funcName) {
153
- throw new Error(`Unexpected input to 'incorrect-class' error.`);
154
- }
155
- const classNameStr = className ? `${className}.` : "";
156
- if (isReturnValueProblem) {
157
- return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
158
- }
159
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
160
- },
161
- "missing-a-method": ({ expectedMethod, paramName, moduleName, className, funcName })=>{
162
- if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
163
- throw new Error(`Unexpected input to 'missing-a-method' error.`);
164
- }
165
- return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
166
- },
167
- "add-to-cache-list-unexpected-type": ({ entry })=>{
168
- 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.`;
169
- },
170
- "add-to-cache-list-conflicting-entries": ({ firstEntry, secondEntry })=>{
171
- if (!firstEntry || !secondEntry) {
172
- throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
173
- }
174
- 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.`;
175
- },
176
- "plugin-error-request-will-fetch": ({ thrownErrorMessage })=>{
177
- if (!thrownErrorMessage) {
178
- throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
179
- }
180
- return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`;
181
- },
182
- "invalid-cache-name": ({ cacheNameId, value })=>{
183
- if (!cacheNameId) {
184
- throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
185
- }
186
- return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
187
- },
188
- "unregister-route-but-not-found-with-method": ({ method })=>{
189
- if (!method) {
190
- throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
191
- }
192
- return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
193
- },
194
- "unregister-route-route-not-registered": ()=>{
195
- return `The route you're trying to unregister was not previously ` + `registered.`;
196
- },
197
- "queue-replay-failed": ({ name })=>{
198
- return `Replaying the background sync queue '${name}' failed.`;
199
- },
200
- "duplicate-queue-name": ({ name })=>{
201
- return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
202
- },
203
- "expired-test-without-max-age": ({ methodName, paramName })=>{
204
- return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
205
- },
206
- "unsupported-route-type": ({ moduleName, className, funcName, paramName })=>{
207
- return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
208
- },
209
- "not-array-of-class": ({ value, expectedClass, moduleName, className, funcName, paramName })=>{
210
- 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.`;
211
- },
212
- "max-entries-or-age-required": ({ moduleName, className, funcName })=>{
213
- return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
214
- },
215
- "statuses-or-headers-required": ({ moduleName, className, funcName })=>{
216
- return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
217
- },
218
- "invalid-string": ({ moduleName, funcName, paramName })=>{
219
- if (!paramName || !moduleName || !funcName) {
220
- throw new Error(`Unexpected input to 'invalid-string' error.`);
221
- }
222
- 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.`;
223
- },
224
- "channel-name-required": ()=>{
225
- return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
226
- },
227
- "invalid-responses-are-same-args": ()=>{
228
- return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
229
- },
230
- "expire-custom-caches-only": ()=>{
231
- return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
232
- },
233
- "unit-must-be-bytes": ({ normalizedRangeHeader })=>{
234
- if (!normalizedRangeHeader) {
235
- throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
236
- }
237
- return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
238
- },
239
- "single-range-only": ({ normalizedRangeHeader })=>{
240
- if (!normalizedRangeHeader) {
241
- throw new Error(`Unexpected input to 'single-range-only' error.`);
242
- }
243
- return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
244
- },
245
- "invalid-range-values": ({ normalizedRangeHeader })=>{
246
- if (!normalizedRangeHeader) {
247
- throw new Error(`Unexpected input to 'invalid-range-values' error.`);
248
- }
249
- 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}"`;
250
- },
251
- "no-range-header": ()=>{
252
- return `No Range header was found in the Request provided.`;
253
- },
254
- "range-not-satisfiable": ({ size, start, end })=>{
255
- return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
256
- },
257
- "attempt-to-cache-non-get-request": ({ url, method })=>{
258
- return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
259
- },
260
- "cache-put-with-no-response": ({ url })=>{
261
- return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
262
- },
263
- "no-response": ({ url, error })=>{
264
- let message = `The strategy could not generate a response for '${url}'.`;
265
- if (error) {
266
- message += ` The underlying error is ${error}.`;
267
- }
268
- return message;
269
- },
270
- "bad-precaching-response": ({ url, status })=>{
271
- return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`);
272
- },
273
- "non-precached-url": ({ url })=>{
274
- return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
275
- },
276
- "add-to-cache-list-conflicting-integrities": ({ url })=>{
277
- return `Two of the entries passed to ` + `'@serwist/precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
278
- },
279
- "missing-precache-entry": ({ cacheName, url })=>{
280
- return `Unable to find a precached response in ${cacheName} for ${url}.`;
281
- },
282
- "cross-origin-copy-response": ({ origin })=>{
283
- return `@serwist/core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`;
284
- },
285
- "opaque-streams-source": ({ type })=>{
286
- const message = `One of the @serwist/streams sources resulted in an ` + `'${type}' response.`;
287
- if (type === "opaqueredirect") {
288
- return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`;
289
- }
290
- return `${message} Please ensure your sources are CORS-enabled.`;
291
- }
292
- };
293
-
294
- const fallback = (code, ...args)=>{
295
- let msg = code;
296
- if (args.length > 0) {
297
- msg += ` :: ${JSON.stringify(args)}`;
298
- }
299
- return msg;
300
- };
301
- const generatorFunction = (code, details = {})=>{
302
- const message = messages[code];
303
- if (!message) {
304
- throw new Error(`Unable to find message for code '${code}'.`);
305
- }
306
- return message(details);
307
- };
308
- const messageGenerator = process.env.NODE_ENV === "production" ? fallback : generatorFunction;
309
-
310
- /**
311
- * Serwist errors should be thrown with this class.
312
- * This allows use to ensure the type easily in tests,
313
- * helps developers identify errors from Serwist
314
- * easily and allows use to optimise error
315
- * messages correctly.
316
- *
317
- * @private
318
- */ class SerwistError extends Error {
319
- details;
320
- /**
321
- *
322
- * @param errorCode The error code that
323
- * identifies this particular error.
324
- * @param details Any relevant arguments
325
- * that will help developers identify issues should
326
- * be added as a key on the context object.
327
- */ constructor(errorCode, details){
328
- const message = messageGenerator(errorCode, details);
329
- super(message);
330
- this.name = errorCode;
331
- this.details = details;
332
- }
333
- }
334
-
335
46
  /**
336
47
  * Allows developers to copy a response and modify its `headers`, `status`,
337
48
  * or `statusText` values (the values settable via a
@@ -377,140 +88,6 @@ const messageGenerator = process.env.NODE_ENV === "production" ? fallback : gene
377
88
  return new Response(body, modifiedResponseInit);
378
89
  }
379
90
 
380
- /*
381
- * This method throws if the supplied value is not an array.
382
- * The destructed values are required to produce a meaningful error for users.
383
- * The destructed and restructured object is so it's clear what is
384
- * needed.
385
- */ const isArray = (value, details)=>{
386
- if (!Array.isArray(value)) {
387
- throw new SerwistError("not-an-array", details);
388
- }
389
- };
390
- const hasMethod = (object, expectedMethod, details)=>{
391
- const type = typeof object[expectedMethod];
392
- if (type !== "function") {
393
- details["expectedMethod"] = expectedMethod;
394
- throw new SerwistError("missing-a-method", details);
395
- }
396
- };
397
- const isType = (object, expectedType, details)=>{
398
- if (typeof object !== expectedType) {
399
- details["expectedType"] = expectedType;
400
- throw new SerwistError("incorrect-type", details);
401
- }
402
- };
403
- const isInstance = (object, // Need the general type to do the check later.
404
- // eslint-disable-next-line @typescript-eslint/ban-types
405
- expectedClass, details)=>{
406
- if (!(object instanceof expectedClass)) {
407
- details["expectedClassName"] = expectedClass.name;
408
- throw new SerwistError("incorrect-class", details);
409
- }
410
- };
411
- const isOneOf = (value, validValues, details)=>{
412
- if (!validValues.includes(value)) {
413
- details["validValueDescription"] = `Valid values are ${JSON.stringify(validValues)}.`;
414
- throw new SerwistError("invalid-value", details);
415
- }
416
- };
417
- const isArrayOfClass = (value, // Need general type to do check later.
418
- expectedClass, details)=>{
419
- const error = new SerwistError("not-array-of-class", details);
420
- if (!Array.isArray(value)) {
421
- throw error;
422
- }
423
- for (const item of value){
424
- if (!(item instanceof expectedClass)) {
425
- throw error;
426
- }
427
- }
428
- };
429
- const finalAssertExports = process.env.NODE_ENV === "production" ? null : {
430
- hasMethod,
431
- isArray,
432
- isInstance,
433
- isOneOf,
434
- isType,
435
- isArrayOfClass
436
- };
437
-
438
- /*
439
- Copyright 2019 Google LLC
440
- Use of this source code is governed by an MIT-style
441
- license that can be found in the LICENSE file or at
442
- https://opensource.org/licenses/MIT.
443
- */ // logger is used inside of both service workers and the window global scope.
444
- const logger = process.env.NODE_ENV === "production" ? null : (()=>{
445
- // Don't overwrite this value if it's already set.
446
- // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
447
- if (!("__WB_DISABLE_DEV_LOGS" in globalThis)) {
448
- self.__WB_DISABLE_DEV_LOGS = false;
449
- }
450
- let inGroup = false;
451
- const methodToColorMap = {
452
- debug: `#7f8c8d`,
453
- log: `#2ecc71`,
454
- warn: `#f39c12`,
455
- error: `#c0392b`,
456
- groupCollapsed: `#3498db`,
457
- groupEnd: null
458
- };
459
- const print = function(method, args) {
460
- if (self.__WB_DISABLE_DEV_LOGS) {
461
- return;
462
- }
463
- if (method === "groupCollapsed") {
464
- // Safari doesn't print all console.groupCollapsed() arguments:
465
- // https://bugs.webkit.org/show_bug.cgi?id=182754
466
- if (typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
467
- console[method](...args);
468
- return;
469
- }
470
- }
471
- const styles = [
472
- `background: ${methodToColorMap[method]}`,
473
- `border-radius: 0.5em`,
474
- `color: white`,
475
- `font-weight: bold`,
476
- `padding: 2px 0.5em`
477
- ];
478
- // When in a group, the serwist prefix is not displayed.
479
- const logPrefix = inGroup ? [] : [
480
- "%cserwist",
481
- styles.join(";")
482
- ];
483
- console[method](...logPrefix, ...args);
484
- if (method === "groupCollapsed") {
485
- inGroup = true;
486
- }
487
- if (method === "groupEnd") {
488
- inGroup = false;
489
- }
490
- };
491
- // eslint-disable-next-line @typescript-eslint/ban-types
492
- const api = {};
493
- const loggerMethods = Object.keys(methodToColorMap);
494
- for (const key of loggerMethods){
495
- const method = key;
496
- api[method] = (...args)=>{
497
- print(method, args);
498
- };
499
- }
500
- return api;
501
- })();
502
-
503
- /*
504
- Copyright 2018 Google LLC
505
-
506
- Use of this source code is governed by an MIT-style
507
- license that can be found in the LICENSE file or at
508
- https://opensource.org/licenses/MIT.
509
- */ // Callbacks to be executed whenever there's a quota error.
510
- // Can't change Function type right now.
511
- // eslint-disable-next-line @typescript-eslint/ban-types
512
- const quotaErrorCallbacks = new Set();
513
-
514
91
  /**
515
92
  * Adds a function to the set of quotaErrorCallbacks that will be executed if
516
93
  * there's a quota error.
@@ -0,0 +1 @@
1
+ export declare const messageGenerator: ((code: string, ...args: any[]) => string) | ((code: string, details?: {}) => string);
@@ -0,0 +1,8 @@
1
+ interface LoggableObject {
2
+ [key: string]: string | number;
3
+ }
4
+ interface MessageMap {
5
+ [messageID: string]: (param: LoggableObject) => string;
6
+ }
7
+ export declare const messages: MessageMap;
8
+ export {};
@@ -0,0 +1,9 @@
1
+ export declare const enum pluginEvents {
2
+ CACHE_DID_UPDATE = "cacheDidUpdate",
3
+ CACHE_KEY_WILL_BE_USED = "cacheKeyWillBeUsed",
4
+ CACHE_WILL_UPDATE = "cacheWillUpdate",
5
+ CACHED_RESPONSE_WILL_BE_USED = "cachedResponseWillBeUsed",
6
+ FETCH_DID_FAIL = "fetchDidFail",
7
+ FETCH_DID_SUCCEED = "fetchDidSucceed",
8
+ REQUEST_WILL_FETCH = "requestWillFetch"
9
+ }
@@ -0,0 +1,2 @@
1
+ declare const quotaErrorCallbacks: Set<Function>;
2
+ export { quotaErrorCallbacks };