serwist 9.0.12 → 10.0.0-preview.1

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 (151) hide show
  1. package/dist/Serwist.d.ts +74 -52
  2. package/dist/Serwist.d.ts.map +1 -1
  3. package/dist/chunks/resultingClientExists.js +426 -2
  4. package/dist/{legacy/utils → controllers/PrecacheController}/PrecacheCacheKeyPlugin.d.ts +4 -4
  5. package/dist/controllers/PrecacheController/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  6. package/dist/{legacy → controllers/PrecacheController}/PrecacheController.d.ts +73 -64
  7. package/dist/controllers/PrecacheController/PrecacheController.d.ts.map +1 -0
  8. package/dist/controllers/PrecacheController/PrecacheInstallReportPlugin.d.ts +14 -0
  9. package/dist/controllers/PrecacheController/PrecacheInstallReportPlugin.d.ts.map +1 -0
  10. package/dist/{PrecacheRoute.d.ts → controllers/PrecacheController/PrecacheRoute.d.ts} +4 -5
  11. package/dist/controllers/PrecacheController/PrecacheRoute.d.ts.map +1 -0
  12. package/dist/{lib/strategies → controllers/PrecacheController}/PrecacheStrategy.d.ts +6 -6
  13. package/dist/controllers/PrecacheController/PrecacheStrategy.d.ts.map +1 -0
  14. package/dist/controllers/PrecacheController/parsePrecacheOptions.d.ts +25 -0
  15. package/dist/controllers/PrecacheController/parsePrecacheOptions.d.ts.map +1 -0
  16. package/dist/controllers/RuntimeCacheController.d.ts +65 -0
  17. package/dist/controllers/RuntimeCacheController.d.ts.map +1 -0
  18. package/dist/index.d.ts +4 -3
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.internal.js +25 -3
  21. package/dist/index.js +1868 -211
  22. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts +2 -2
  23. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts.map +1 -1
  24. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.d.ts +2 -2
  25. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +1 -1
  26. package/dist/lib/cacheableResponse/CacheableResponsePlugin.d.ts +3 -3
  27. package/dist/lib/cacheableResponse/CacheableResponsePlugin.d.ts.map +1 -1
  28. package/dist/lib/expiration/ExpirationPlugin.d.ts +2 -2
  29. package/dist/lib/expiration/ExpirationPlugin.d.ts.map +1 -1
  30. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts +7 -7
  31. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts.map +1 -1
  32. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts +3 -3
  33. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts.map +1 -1
  34. package/dist/lib/strategies/Strategy.d.ts +3 -3
  35. package/dist/lib/strategies/Strategy.d.ts.map +1 -1
  36. package/dist/lib/strategies/StrategyHandler.d.ts +4 -4
  37. package/dist/lib/strategies/StrategyHandler.d.ts.map +1 -1
  38. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +2 -2
  39. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -1
  40. package/dist/types.d.ts +16 -64
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/utils/pluginUtils.d.ts +2 -2
  43. package/dist/utils/pluginUtils.d.ts.map +1 -1
  44. package/package.json +5 -12
  45. package/src/Serwist.ts +157 -262
  46. package/src/{legacy/utils → controllers/PrecacheController}/PrecacheCacheKeyPlugin.ts +5 -6
  47. package/src/{legacy → controllers/PrecacheController}/PrecacheController.ts +143 -155
  48. package/src/{utils → controllers/PrecacheController}/PrecacheInstallReportPlugin.ts +5 -5
  49. package/src/{PrecacheRoute.ts → controllers/PrecacheController/PrecacheRoute.ts} +11 -12
  50. package/src/{lib/strategies → controllers/PrecacheController}/PrecacheStrategy.ts +7 -7
  51. package/src/controllers/PrecacheController/parsePrecacheOptions.ts +46 -0
  52. package/src/controllers/RuntimeCacheController.ts +119 -0
  53. package/src/index.ts +5 -2
  54. package/src/lib/backgroundSync/BackgroundSyncPlugin.ts +2 -2
  55. package/src/lib/broadcastUpdate/BroadcastUpdatePlugin.ts +2 -2
  56. package/src/lib/cacheableResponse/CacheableResponsePlugin.ts +3 -3
  57. package/src/lib/expiration/ExpirationPlugin.ts +2 -2
  58. package/src/lib/precaching/PrecacheFallbackPlugin.ts +10 -10
  59. package/src/lib/rangeRequests/RangeRequestsPlugin.ts +3 -3
  60. package/src/lib/strategies/Strategy.ts +3 -3
  61. package/src/lib/strategies/StrategyHandler.ts +9 -9
  62. package/src/lib/strategies/plugins/cacheOkAndOpaquePlugin.ts +2 -2
  63. package/src/types.ts +24 -67
  64. package/src/utils/pluginUtils.ts +2 -2
  65. package/dist/PrecacheRoute.d.ts.map +0 -1
  66. package/dist/chunks/printInstallDetails.js +0 -1601
  67. package/dist/chunks/waitUntil.js +0 -449
  68. package/dist/index.legacy.d.ts +0 -28
  69. package/dist/index.legacy.d.ts.map +0 -1
  70. package/dist/index.legacy.js +0 -790
  71. package/dist/legacy/PrecacheController.d.ts.map +0 -1
  72. package/dist/legacy/PrecacheFallbackPlugin.d.ts +0 -61
  73. package/dist/legacy/PrecacheFallbackPlugin.d.ts.map +0 -1
  74. package/dist/legacy/PrecacheRoute.d.ts +0 -19
  75. package/dist/legacy/PrecacheRoute.d.ts.map +0 -1
  76. package/dist/legacy/Router.d.ts +0 -151
  77. package/dist/legacy/Router.d.ts.map +0 -1
  78. package/dist/legacy/addPlugins.d.ts +0 -9
  79. package/dist/legacy/addPlugins.d.ts.map +0 -1
  80. package/dist/legacy/addRoute.d.ts +0 -14
  81. package/dist/legacy/addRoute.d.ts.map +0 -1
  82. package/dist/legacy/constants.d.ts +0 -10
  83. package/dist/legacy/constants.d.ts.map +0 -1
  84. package/dist/legacy/createHandlerBoundToURL.d.ts +0 -17
  85. package/dist/legacy/createHandlerBoundToURL.d.ts.map +0 -1
  86. package/dist/legacy/fallbacks.d.ts +0 -59
  87. package/dist/legacy/fallbacks.d.ts.map +0 -1
  88. package/dist/legacy/getCacheKeyForURL.d.ts +0 -20
  89. package/dist/legacy/getCacheKeyForURL.d.ts.map +0 -1
  90. package/dist/legacy/handlePrecaching.d.ts +0 -54
  91. package/dist/legacy/handlePrecaching.d.ts.map +0 -1
  92. package/dist/legacy/initializeGoogleAnalytics.d.ts +0 -38
  93. package/dist/legacy/initializeGoogleAnalytics.d.ts.map +0 -1
  94. package/dist/legacy/installSerwist.d.ts +0 -81
  95. package/dist/legacy/installSerwist.d.ts.map +0 -1
  96. package/dist/legacy/matchPrecache.d.ts +0 -15
  97. package/dist/legacy/matchPrecache.d.ts.map +0 -1
  98. package/dist/legacy/precache.d.ts +0 -20
  99. package/dist/legacy/precache.d.ts.map +0 -1
  100. package/dist/legacy/precacheAndRoute.d.ts +0 -14
  101. package/dist/legacy/precacheAndRoute.d.ts.map +0 -1
  102. package/dist/legacy/registerRoute.d.ts +0 -16
  103. package/dist/legacy/registerRoute.d.ts.map +0 -1
  104. package/dist/legacy/registerRuntimeCaching.d.ts +0 -11
  105. package/dist/legacy/registerRuntimeCaching.d.ts.map +0 -1
  106. package/dist/legacy/setCatchHandler.d.ts +0 -10
  107. package/dist/legacy/setCatchHandler.d.ts.map +0 -1
  108. package/dist/legacy/setDefaultHandler.d.ts +0 -13
  109. package/dist/legacy/setDefaultHandler.d.ts.map +0 -1
  110. package/dist/legacy/singletonPrecacheController.d.ts +0 -34
  111. package/dist/legacy/singletonPrecacheController.d.ts.map +0 -1
  112. package/dist/legacy/singletonRouter.d.ts +0 -41
  113. package/dist/legacy/singletonRouter.d.ts.map +0 -1
  114. package/dist/legacy/unregisterRoute.d.ts +0 -9
  115. package/dist/legacy/unregisterRoute.d.ts.map +0 -1
  116. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  117. package/dist/legacy/utils/getCacheKeyForURL.d.ts +0 -14
  118. package/dist/legacy/utils/getCacheKeyForURL.d.ts.map +0 -1
  119. package/dist/lib/strategies/PrecacheStrategy.d.ts.map +0 -1
  120. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +0 -16
  121. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  122. package/dist/utils/PrecacheInstallReportPlugin.d.ts +0 -14
  123. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +0 -1
  124. package/dist/utils/parsePrecacheOptions.d.ts +0 -26
  125. package/dist/utils/parsePrecacheOptions.d.ts.map +0 -1
  126. package/src/index.legacy.ts +0 -62
  127. package/src/legacy/PrecacheFallbackPlugin.ts +0 -92
  128. package/src/legacy/PrecacheRoute.ts +0 -48
  129. package/src/legacy/Router.ts +0 -484
  130. package/src/legacy/addPlugins.ts +0 -21
  131. package/src/legacy/addRoute.ts +0 -27
  132. package/src/legacy/constants.ts +0 -22
  133. package/src/legacy/createHandlerBoundToURL.ts +0 -30
  134. package/src/legacy/fallbacks.ts +0 -94
  135. package/src/legacy/getCacheKeyForURL.ts +0 -32
  136. package/src/legacy/handlePrecaching.ts +0 -86
  137. package/src/legacy/initializeGoogleAnalytics.ts +0 -218
  138. package/src/legacy/installSerwist.ts +0 -170
  139. package/src/legacy/matchPrecache.ts +0 -27
  140. package/src/legacy/precache.ts +0 -33
  141. package/src/legacy/precacheAndRoute.ts +0 -27
  142. package/src/legacy/registerRoute.ts +0 -28
  143. package/src/legacy/registerRuntimeCaching.ts +0 -17
  144. package/src/legacy/setCatchHandler.ts +0 -21
  145. package/src/legacy/setDefaultHandler.ts +0 -24
  146. package/src/legacy/singletonPrecacheController.ts +0 -53
  147. package/src/legacy/singletonRouter.ts +0 -70
  148. package/src/legacy/unregisterRoute.ts +0 -13
  149. package/src/legacy/utils/getCacheKeyForURL.ts +0 -36
  150. package/src/utils/PrecacheCacheKeyPlugin.ts +0 -33
  151. package/src/utils/parsePrecacheOptions.ts +0 -47
@@ -1,4 +1,428 @@
1
- import { t as timeout } from './waitUntil.js';
1
+ const messages = {
2
+ "invalid-value": ({ paramName, validValueDescription, value })=>{
3
+ if (!paramName || !validValueDescription) {
4
+ throw new Error(`Unexpected input to 'invalid-value' error.`);
5
+ }
6
+ return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
7
+ },
8
+ "not-an-array": ({ moduleName, className, funcName, paramName })=>{
9
+ if (!moduleName || !className || !funcName || !paramName) {
10
+ throw new Error(`Unexpected input to 'not-an-array' error.`);
11
+ }
12
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
13
+ },
14
+ "incorrect-type": ({ expectedType, paramName, moduleName, className, funcName })=>{
15
+ if (!expectedType || !paramName || !moduleName || !funcName) {
16
+ throw new Error(`Unexpected input to 'incorrect-type' error.`);
17
+ }
18
+ const classNameStr = className ? `${className}.` : "";
19
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`;
20
+ },
21
+ "incorrect-class": ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem })=>{
22
+ if (!expectedClassName || !moduleName || !funcName) {
23
+ throw new Error(`Unexpected input to 'incorrect-class' error.`);
24
+ }
25
+ const classNameStr = className ? `${className}.` : "";
26
+ if (isReturnValueProblem) {
27
+ return `The return value from '${moduleName}.${classNameStr}${funcName}()' must be an instance of class ${expectedClassName}.`;
28
+ }
29
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`;
30
+ },
31
+ "missing-a-method": ({ expectedMethod, paramName, moduleName, className, funcName })=>{
32
+ if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
33
+ throw new Error(`Unexpected input to 'missing-a-method' error.`);
34
+ }
35
+ return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
36
+ },
37
+ "add-to-cache-list-unexpected-type": ({ entry })=>{
38
+ return `An unexpected entry was passed to 'serwist.Serwist.addToPrecacheList()' 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.`;
39
+ },
40
+ "add-to-cache-list-conflicting-entries": ({ firstEntry, secondEntry })=>{
41
+ if (!firstEntry || !secondEntry) {
42
+ throw new Error("Unexpected input to " + `'add-to-cache-list-duplicate-entries' error.`);
43
+ }
44
+ return `Two of the entries passed to 'serwist.Serwist.addToPrecacheList()' had the URL ${firstEntry} but different revision details. Serwist is unable to cache and version the asset correctly. Please remove one of the entries.`;
45
+ },
46
+ "plugin-error-request-will-fetch": ({ thrownErrorMessage })=>{
47
+ if (!thrownErrorMessage) {
48
+ throw new Error("Unexpected input to " + `'plugin-error-request-will-fetch', error.`);
49
+ }
50
+ return `An error was thrown by a plugin's 'requestWillFetch()' method. The thrown error message was: '${thrownErrorMessage}'.`;
51
+ },
52
+ "invalid-cache-name": ({ cacheNameId, value })=>{
53
+ if (!cacheNameId) {
54
+ throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
55
+ }
56
+ return `You must provide a name containing at least one character for setCacheDetails({${cacheNameId}: '...'}). Received a value of '${JSON.stringify(value)}'`;
57
+ },
58
+ "unregister-route-but-not-found-with-method": ({ method })=>{
59
+ if (!method) {
60
+ throw new Error("Unexpected input to " + `'unregister-route-but-not-found-with-method' error.`);
61
+ }
62
+ return `The route you're trying to unregister was not previously registered for the method type '${method}'.`;
63
+ },
64
+ "unregister-route-route-not-registered": ()=>{
65
+ return `The route you're trying to unregister was not previously ` + "registered.";
66
+ },
67
+ "queue-replay-failed": ({ name })=>{
68
+ return `Replaying the background sync queue '${name}' failed.`;
69
+ },
70
+ "duplicate-queue-name": ({ name })=>{
71
+ return `The queue name '${name}' is already being used. All instances of 'serwist.BackgroundSyncQueue' must be given unique names.`;
72
+ },
73
+ "expired-test-without-max-age": ({ methodName, paramName })=>{
74
+ return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
75
+ },
76
+ "unsupported-route-type": ({ moduleName, className, funcName, paramName })=>{
77
+ return `The supplied '${paramName}' parameter was an unsupported type. Please check the docs for ${moduleName}.${className}.${funcName} for valid input types.`;
78
+ },
79
+ "not-array-of-class": ({ value, expectedClass, moduleName, className, funcName, paramName })=>{
80
+ 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.`;
81
+ },
82
+ "max-entries-or-age-required": ({ moduleName, className, funcName })=>{
83
+ return `You must define either 'config.maxEntries' or 'config.maxAgeSeconds' in '${moduleName}.${className}.${funcName}'`;
84
+ },
85
+ "statuses-or-headers-required": ({ moduleName, className, funcName })=>{
86
+ return `You must define either 'config.statuses' or 'config.headers' in '${moduleName}.${className}.${funcName}'`;
87
+ },
88
+ "invalid-string": ({ moduleName, funcName, paramName })=>{
89
+ if (!paramName || !moduleName || !funcName) {
90
+ throw new Error(`Unexpected input to 'invalid-string' error.`);
91
+ }
92
+ 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.`;
93
+ },
94
+ "channel-name-required": ()=>{
95
+ return "You must provide a channelName to construct a " + "BroadcastCacheUpdate instance.";
96
+ },
97
+ "invalid-responses-are-same-args": ()=>{
98
+ return "The arguments passed into responsesAreSame() appear to be " + "invalid. Please ensure valid Responses are used.";
99
+ },
100
+ "expire-custom-caches-only": ()=>{
101
+ return `You must provide a 'cacheName' property when using the ` + "expiration plugin with a runtime caching strategy.";
102
+ },
103
+ "unit-must-be-bytes": ({ normalizedRangeHeader })=>{
104
+ if (!normalizedRangeHeader) {
105
+ throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
106
+ }
107
+ return `The 'unit' portion of the Range header must be set to 'bytes'. The Range header provided was "${normalizedRangeHeader}"`;
108
+ },
109
+ "single-range-only": ({ normalizedRangeHeader })=>{
110
+ if (!normalizedRangeHeader) {
111
+ throw new Error(`Unexpected input to 'single-range-only' error.`);
112
+ }
113
+ return `Multiple ranges are not supported. Please use a single start value, and optional end value. The Range header provided was "${normalizedRangeHeader}"`;
114
+ },
115
+ "invalid-range-values": ({ normalizedRangeHeader })=>{
116
+ if (!normalizedRangeHeader) {
117
+ throw new Error(`Unexpected input to 'invalid-range-values' error.`);
118
+ }
119
+ 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}"`;
120
+ },
121
+ "no-range-header": ()=>{
122
+ return "No Range header was found in the Request provided.";
123
+ },
124
+ "range-not-satisfiable": ({ size, start, end })=>{
125
+ return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
126
+ },
127
+ "attempt-to-cache-non-get-request": ({ url, method })=>{
128
+ return `Unable to cache '${url}' because it is a '${method}' request and only 'GET' requests can be cached.`;
129
+ },
130
+ "cache-put-with-no-response": ({ url })=>{
131
+ return `There was an attempt to cache '${url}' but the response was not defined.`;
132
+ },
133
+ "no-response": ({ url, error })=>{
134
+ let message = `The strategy could not generate a response for '${url}'.`;
135
+ if (error) {
136
+ message += ` The underlying error is ${error}.`;
137
+ }
138
+ return message;
139
+ },
140
+ "bad-precaching-response": ({ url, status })=>{
141
+ return `The precaching request for '${url}' failed${status ? ` with an HTTP status of ${status}.` : "."}`;
142
+ },
143
+ "non-precached-url": ({ url })=>{
144
+ return `'createHandlerBoundToURL("${url}")' was called, but that URL is not precached. Please pass in a URL that is precached instead.`;
145
+ },
146
+ "add-to-cache-list-conflicting-integrities": ({ url })=>{
147
+ return `Two of the entries passed to 'serwist.Serwist.addToPrecacheList()' had the URL ${url} with different integrity values. Please remove one of them.`;
148
+ },
149
+ "missing-precache-entry": ({ cacheName, url })=>{
150
+ return `Unable to find a precached response in ${cacheName} for ${url}.`;
151
+ },
152
+ "cross-origin-copy-response": ({ origin })=>{
153
+ return `'@serwist/core.copyResponse()' can only be used with same-origin responses. It was passed a response with origin ${origin}.`;
154
+ },
155
+ "opaque-streams-source": ({ type })=>{
156
+ const message = `One of the '@serwist/streams' sources resulted in an '${type}' response.`;
157
+ if (type === "opaqueredirect") {
158
+ return `${message} Please do not use a navigation request that results in a redirect as a source.`;
159
+ }
160
+ return `${message} Please ensure your sources are CORS-enabled.`;
161
+ }
162
+ };
163
+
164
+ const fallback = (code, ...args)=>{
165
+ let msg = code;
166
+ if (args.length > 0) {
167
+ msg += ` :: ${JSON.stringify(args)}`;
168
+ }
169
+ return msg;
170
+ };
171
+ const generatorFunction = (code, details = {})=>{
172
+ const message = messages[code];
173
+ if (!message) {
174
+ throw new Error(`Unable to find message for code '${code}'.`);
175
+ }
176
+ return message(details);
177
+ };
178
+ const messageGenerator = process.env.NODE_ENV === "production" ? fallback : generatorFunction;
179
+
180
+ class SerwistError extends Error {
181
+ details;
182
+ constructor(errorCode, details){
183
+ const message = messageGenerator(errorCode, details);
184
+ super(message);
185
+ this.name = errorCode;
186
+ this.details = details;
187
+ }
188
+ }
189
+
190
+ let supportStatus;
191
+ function canConstructResponseFromBodyStream() {
192
+ if (supportStatus === undefined) {
193
+ const testResponse = new Response("");
194
+ if ("body" in testResponse) {
195
+ try {
196
+ new Response(testResponse.body);
197
+ supportStatus = true;
198
+ } catch (error) {
199
+ supportStatus = false;
200
+ }
201
+ }
202
+ supportStatus = false;
203
+ }
204
+ return supportStatus;
205
+ }
206
+
207
+ const _cacheNameDetails = {
208
+ googleAnalytics: "googleAnalytics",
209
+ precache: "precache-v2",
210
+ prefix: "serwist",
211
+ runtime: "runtime",
212
+ suffix: typeof registration !== "undefined" ? registration.scope : ""
213
+ };
214
+ const _createCacheName = (cacheName)=>{
215
+ return [
216
+ _cacheNameDetails.prefix,
217
+ cacheName,
218
+ _cacheNameDetails.suffix
219
+ ].filter((value)=>value && value.length > 0).join("-");
220
+ };
221
+ const eachCacheNameDetail = (fn)=>{
222
+ for (const key of Object.keys(_cacheNameDetails)){
223
+ fn(key);
224
+ }
225
+ };
226
+ const cacheNames = {
227
+ updateDetails: (details)=>{
228
+ eachCacheNameDetail((key)=>{
229
+ const detail = details[key];
230
+ if (typeof detail === "string") {
231
+ _cacheNameDetails[key] = detail;
232
+ }
233
+ });
234
+ },
235
+ getGoogleAnalyticsName: (userCacheName)=>{
236
+ return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
237
+ },
238
+ getPrecacheName: (userCacheName)=>{
239
+ return userCacheName || _createCacheName(_cacheNameDetails.precache);
240
+ },
241
+ getPrefix: ()=>{
242
+ return _cacheNameDetails.prefix;
243
+ },
244
+ getRuntimeName: (userCacheName)=>{
245
+ return userCacheName || _createCacheName(_cacheNameDetails.runtime);
246
+ },
247
+ getSuffix: ()=>{
248
+ return _cacheNameDetails.suffix;
249
+ }
250
+ };
251
+
252
+ const getFriendlyURL = (url)=>{
253
+ const urlObj = new URL(String(url), location.href);
254
+ return urlObj.href.replace(new RegExp(`^${location.origin}`), "");
255
+ };
256
+
257
+ const logger = process.env.NODE_ENV === "production" ? null : (()=>{
258
+ if (!("__WB_DISABLE_DEV_LOGS" in globalThis)) {
259
+ self.__WB_DISABLE_DEV_LOGS = false;
260
+ }
261
+ let inGroup = false;
262
+ const methodToColorMap = {
263
+ debug: "#7f8c8d",
264
+ log: "#2ecc71",
265
+ warn: "#f39c12",
266
+ error: "#c0392b",
267
+ groupCollapsed: "#3498db",
268
+ groupEnd: null
269
+ };
270
+ const print = (method, args)=>{
271
+ if (self.__WB_DISABLE_DEV_LOGS) {
272
+ return;
273
+ }
274
+ if (method === "groupCollapsed") {
275
+ if (typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
276
+ console[method](...args);
277
+ return;
278
+ }
279
+ }
280
+ const styles = [
281
+ `background: ${methodToColorMap[method]}`,
282
+ "border-radius: 0.5em",
283
+ "color: white",
284
+ "font-weight: bold",
285
+ "padding: 2px 0.5em"
286
+ ];
287
+ const logPrefix = inGroup ? [] : [
288
+ "%cserwist",
289
+ styles.join(";")
290
+ ];
291
+ console[method](...logPrefix, ...args);
292
+ if (method === "groupCollapsed") {
293
+ inGroup = true;
294
+ }
295
+ if (method === "groupEnd") {
296
+ inGroup = false;
297
+ }
298
+ };
299
+ const loggerMethods = Object.keys(methodToColorMap);
300
+ return loggerMethods.reduce((api, method)=>{
301
+ api[method] = (...args)=>{
302
+ print(method, args);
303
+ };
304
+ return api;
305
+ }, {});
306
+ })();
307
+
308
+ class Deferred {
309
+ promise;
310
+ resolve;
311
+ reject;
312
+ constructor(){
313
+ this.promise = new Promise((resolve, reject)=>{
314
+ this.resolve = resolve;
315
+ this.reject = reject;
316
+ });
317
+ }
318
+ }
319
+
320
+ const isArray = (value, details)=>{
321
+ if (!Array.isArray(value)) {
322
+ throw new SerwistError("not-an-array", details);
323
+ }
324
+ };
325
+ const hasMethod = (object, expectedMethod, details)=>{
326
+ const type = typeof object[expectedMethod];
327
+ if (type !== "function") {
328
+ details.expectedMethod = expectedMethod;
329
+ throw new SerwistError("missing-a-method", details);
330
+ }
331
+ };
332
+ const isType = (object, expectedType, details)=>{
333
+ if (typeof object !== expectedType) {
334
+ details.expectedType = expectedType;
335
+ throw new SerwistError("incorrect-type", details);
336
+ }
337
+ };
338
+ const isInstance = (object, expectedClass, details)=>{
339
+ if (!(object instanceof expectedClass)) {
340
+ details.expectedClassName = expectedClass.name;
341
+ throw new SerwistError("incorrect-class", details);
342
+ }
343
+ };
344
+ const isOneOf = (value, validValues, details)=>{
345
+ if (!validValues.includes(value)) {
346
+ details.validValueDescription = `Valid values are ${JSON.stringify(validValues)}.`;
347
+ throw new SerwistError("invalid-value", details);
348
+ }
349
+ };
350
+ const isArrayOfClass = (value, expectedClass, details)=>{
351
+ const error = new SerwistError("not-array-of-class", details);
352
+ if (!Array.isArray(value)) {
353
+ throw error;
354
+ }
355
+ for (const item of value){
356
+ if (!(item instanceof expectedClass)) {
357
+ throw error;
358
+ }
359
+ }
360
+ };
361
+ const finalAssertExports = process.env.NODE_ENV === "production" ? null : {
362
+ hasMethod,
363
+ isArray,
364
+ isInstance,
365
+ isOneOf,
366
+ isType,
367
+ isArrayOfClass
368
+ };
369
+
370
+ function stripParams(fullURL, ignoreParams) {
371
+ const strippedURL = new URL(fullURL);
372
+ for (const param of ignoreParams){
373
+ strippedURL.searchParams.delete(param);
374
+ }
375
+ return strippedURL.href;
376
+ }
377
+ async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {
378
+ const strippedRequestURL = stripParams(request.url, ignoreParams);
379
+ if (request.url === strippedRequestURL) {
380
+ return cache.match(request, matchOptions);
381
+ }
382
+ const keysOptions = {
383
+ ...matchOptions,
384
+ ignoreSearch: true
385
+ };
386
+ const cacheKeys = await cache.keys(request, keysOptions);
387
+ for (const cacheKey of cacheKeys){
388
+ const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);
389
+ if (strippedRequestURL === strippedCacheKeyURL) {
390
+ return cache.match(cacheKey, matchOptions);
391
+ }
392
+ }
393
+ return;
394
+ }
395
+
396
+ const quotaErrorCallbacks = new Set();
397
+
398
+ const executeQuotaErrorCallbacks = async ()=>{
399
+ if (process.env.NODE_ENV !== "production") {
400
+ logger.log(`About to run ${quotaErrorCallbacks.size} callbacks to clean up caches.`);
401
+ }
402
+ for (const callback of quotaErrorCallbacks){
403
+ await callback();
404
+ if (process.env.NODE_ENV !== "production") {
405
+ logger.log(callback, "is complete.");
406
+ }
407
+ }
408
+ if (process.env.NODE_ENV !== "production") {
409
+ logger.log("Finished running callbacks.");
410
+ }
411
+ };
412
+
413
+ function timeout(ms) {
414
+ return new Promise((resolve)=>setTimeout(resolve, ms));
415
+ }
416
+
417
+ const clientsClaim = ()=>{
418
+ self.addEventListener("activate", ()=>self.clients.claim());
419
+ };
420
+
421
+ const waitUntil = (event, asyncFn)=>{
422
+ const returnPromise = asyncFn();
423
+ event.waitUntil(returnPromise);
424
+ return returnPromise;
425
+ };
2
426
 
3
427
  const MAX_RETRY_TIME = 2000;
4
428
  async function resultingClientExists(resultingClientId) {
@@ -29,4 +453,4 @@ async function resultingClientExists(resultingClientId) {
29
453
  return resultingWindow;
30
454
  }
31
455
 
32
- export { resultingClientExists as r };
456
+ export { Deferred as D, SerwistError as S, cacheMatchIgnoreParams as a, cacheNames as b, canConstructResponseFromBodyStream as c, clientsClaim as d, executeQuotaErrorCallbacks as e, finalAssertExports as f, getFriendlyURL as g, logger as l, quotaErrorCallbacks as q, resultingClientExists as r, timeout as t, waitUntil as w };
@@ -1,16 +1,16 @@
1
- import type { SerwistPlugin } from "../../types.js";
2
- import type { PrecacheController } from "../PrecacheController.js";
1
+ import type { PrecacheController } from "./PrecacheController.js";
2
+ import type { StrategyPlugin } from "../../types.js";
3
3
  /**
4
4
  * A plugin, designed to be used with PrecacheController, to translate URLs into
5
5
  * the corresponding cache key, based on the current revision info.
6
6
  *
7
7
  * @private
8
8
  */
9
- export declare class PrecacheCacheKeyPlugin implements SerwistPlugin {
9
+ export declare class PrecacheCacheKeyPlugin implements StrategyPlugin {
10
10
  private readonly _precacheController;
11
11
  constructor({ precacheController }: {
12
12
  precacheController: PrecacheController;
13
13
  });
14
- cacheKeyWillBeUsed: SerwistPlugin["cacheKeyWillBeUsed"];
14
+ cacheKeyWillBeUsed: StrategyPlugin["cacheKeyWillBeUsed"];
15
15
  }
16
16
  //# sourceMappingURL=PrecacheCacheKeyPlugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PrecacheCacheKeyPlugin.d.ts","sourceRoot":"","sources":["../../../src/controllers/PrecacheController/PrecacheCacheKeyPlugin.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,KAAK,EAAE,cAAc,EAA+B,MAAM,gBAAgB,CAAC;AAElF;;;;;GAKG;AACH,qBAAa,sBAAuB,YAAW,cAAc;IAC3D,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAqB;gBAE7C,EAAE,kBAAkB,EAAE,EAAE;QAAE,kBAAkB,EAAE,kBAAkB,CAAA;KAAE;IAI9E,kBAAkB,EAAE,cAAc,CAAC,oBAAoB,CAAC,CAOtD;CACH"}
@@ -1,119 +1,129 @@
1
- import type { Strategy } from "../lib/strategies/Strategy.js";
2
- import type { RouteHandlerCallback, SerwistPlugin } from "../types.js";
3
- import type { CleanupResult, InstallResult, PrecacheEntry } from "../types.js";
4
- interface PrecacheControllerOptions {
1
+ import type { Strategy } from "../../lib/strategies/Strategy.js";
2
+ import type { Controller, RouteHandlerCallback, UrlManipulation } from "../../types.js";
3
+ import type { Serwist } from "../../Serwist.js";
4
+ import type { PrecacheStrategyOptions } from "./PrecacheStrategy.js";
5
+ export interface PrecacheEntry {
6
+ integrity?: string;
7
+ url: string;
8
+ revision?: string | null;
9
+ }
10
+ export interface PrecacheRouteOptions {
5
11
  /**
6
- * The cache to use for precaching.
12
+ * Tells Serwist to check the precache for an entry whose URL is the request URL appended
13
+ * with the specified value. Only applies if the request URL ends with "/".
14
+ *
15
+ * @default "index.html"
7
16
  */
8
- cacheName?: string;
17
+ directoryIndex?: string | null;
18
+ /**
19
+ * An array of `RegExp` objects matching search params that should be removed when looking
20
+ * for a precache match.
21
+ */
22
+ ignoreURLParametersMatching?: RegExp[];
23
+ /**
24
+ * Tells Serwist to check the precache for an entry whose URL is the request URL appended
25
+ * with ".html".
26
+ *
27
+ * @default true
28
+ */
29
+ cleanURLs?: boolean;
30
+ /**
31
+ * A function that should take a URL and return an array of alternative URLs that should
32
+ * be checked for precache matches.
33
+ */
34
+ urlManipulation?: UrlManipulation;
35
+ }
36
+ export interface PrecacheControllerOptions {
9
37
  /**
10
- * Plugins to use when precaching as well as responding to fetch
11
- * events for precached assets.
38
+ * The cache to use for precaching.
12
39
  */
13
- plugins?: SerwistPlugin[];
40
+ cacheName?: string;
14
41
  /**
15
- * Whether to attempt to get the response from the network if there's
16
- * a precache miss.
42
+ * Whether outdated caches should be removed.
43
+ *
44
+ * @default false
17
45
  */
18
- fallbackToNetwork?: boolean;
46
+ cleanupOutdatedCaches?: boolean;
19
47
  /**
20
48
  * The number of precache requests that should be made concurrently.
21
49
  *
22
- * @default 1
50
+ * @default 10
23
51
  */
24
- concurrentPrecaching?: number;
52
+ concurrency?: number;
53
+ /**
54
+ * An URL that should point to a HTML file with which navigation requests for URLs that aren't
55
+ * precached will be fulfilled.
56
+ */
57
+ navigateFallback?: string;
58
+ /**
59
+ * URLs that should be allowed to use the `navigateFallback` handler.
60
+ */
61
+ navigateFallbackAllowlist?: RegExp[];
62
+ /**
63
+ * URLs that should not be allowed to use the `navigateFallback` handler. This takes precedence
64
+ * over `navigateFallbackAllowlist`.
65
+ */
66
+ navigateFallbackDenylist?: RegExp[];
25
67
  }
26
- /**
27
- * Performs efficient precaching of assets.
28
- * @deprecated
29
- */
30
- export declare class PrecacheController {
31
- private _installAndActiveListenersAdded?;
32
- private _concurrentPrecaching;
33
- private readonly _strategy;
68
+ export interface PrecacheOptions extends PrecacheStrategyOptions, PrecacheRouteOptions, PrecacheControllerOptions {
69
+ }
70
+ export declare class PrecacheController implements Controller {
34
71
  private readonly _urlsToCacheKeys;
35
72
  private readonly _urlsToCacheModes;
36
73
  private readonly _cacheKeysToIntegrities;
74
+ private readonly _strategy;
75
+ private _options;
76
+ private _routeOptions;
37
77
  /**
38
78
  * Create a new PrecacheController.
39
79
  *
40
80
  * @param options
41
81
  */
42
- constructor({ cacheName, plugins, fallbackToNetwork, concurrentPrecaching }?: PrecacheControllerOptions);
82
+ constructor(entries: (PrecacheEntry | string)[], precacheOptions?: PrecacheOptions);
43
83
  /**
44
84
  * The strategy created by this controller and
45
85
  * used to cache assets and respond to `fetch` events.
46
86
  */
47
87
  get strategy(): Strategy;
48
88
  /**
49
- * Adds items to the precache list, removing any duplicates and
50
- * stores the files in the precache cache when the service
51
- * worker installs.
52
- *
53
- * This method can be called multiple times.
54
- *
55
- * @param entries Array of entries to precache.
56
- */
57
- precache(entries: (PrecacheEntry | string)[]): void;
58
- /**
59
- * This method will add items to the precache list, removing duplicates
60
- * and ensuring the information is valid.
89
+ * Adds items to the cache list, removing duplicates and ensuring the information is valid.
61
90
  *
62
91
  * @param entries Array of entries to precache.
63
92
  */
64
93
  addToCacheList(entries: (PrecacheEntry | string)[]): void;
65
- /**
66
- * Precaches new and updated assets. Call this method from the service worker
67
- * install event.
68
- *
69
- * Note: this method calls `event.waitUntil()` for you, so you do not need
70
- * to call it yourself in your event handlers.
71
- *
72
- * @param event
73
- * @returns
74
- */
75
- install(event: ExtendableEvent): Promise<InstallResult>;
76
- /**
77
- * Deletes assets that are no longer present in the current precache manifest.
78
- * Call this method from the service worker activate event.
79
- *
80
- * Note: this method calls `event.waitUntil()` for you, so you do not need
81
- * to call it yourself in your event handlers.
82
- *
83
- * @param event
84
- * @returns
85
- */
86
- activate(event: ExtendableEvent): Promise<CleanupResult>;
94
+ init(serwist: Serwist): void;
95
+ install(event: ExtendableEvent): Promise<void>;
96
+ activate(): Promise<void>;
87
97
  /**
88
98
  * Returns a mapping of a precached URL to the corresponding cache key, taking
89
99
  * into account the revision information for the URL.
90
100
  *
91
101
  * @returns A URL to cache key mapping.
92
102
  */
93
- getURLsToCacheKeys(): Map<string, string>;
103
+ getUrlsToPrecacheKeys(): Map<string, string>;
94
104
  /**
95
105
  * Returns a list of all the URLs that have been precached by the current
96
106
  * service worker.
97
107
  *
98
108
  * @returns The precached URLs.
99
109
  */
100
- getCachedURLs(): string[];
110
+ getPrecachedUrls(): string[];
101
111
  /**
102
112
  * Returns the cache key used for storing a given URL. If that URL is
103
- * unversioned, like `/index.html', then the cache key will be the original
113
+ * unversioned, like "/index.html", then the cache key will be the original
104
114
  * URL with a search parameter appended to it.
105
115
  *
106
116
  * @param url A URL whose cache key you want to look up.
107
117
  * @returns The versioned URL that corresponds to a cache key
108
118
  * for the original URL, or undefined if that URL isn't precached.
109
119
  */
110
- getCacheKeyForURL(url: string): string | undefined;
120
+ getPrecacheKeyForUrl(url: string): string | undefined;
111
121
  /**
112
122
  * @param url A cache key whose SRI you want to look up.
113
123
  * @returns The subresource integrity associated with the cache key,
114
124
  * or undefined if it's not set.
115
125
  */
116
- getIntegrityForCacheKey(cacheKey: string): string | undefined;
126
+ getIntegrityForPrecacheKey(cacheKey: string): string | undefined;
117
127
  /**
118
128
  * This acts as a drop-in replacement for
119
129
  * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
@@ -140,7 +150,6 @@ export declare class PrecacheController {
140
150
  * @param url The precached URL which will be used to lookup the response.
141
151
  * @return
142
152
  */
143
- createHandlerBoundToURL(url: string): RouteHandlerCallback;
153
+ createHandlerBoundToUrl(url: string): RouteHandlerCallback;
144
154
  }
145
- export {};
146
155
  //# sourceMappingURL=PrecacheController.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PrecacheController.d.ts","sourceRoot":"","sources":["../../../src/controllers/PrecacheController/PrecacheController.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAUxF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAEhD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAGrE,MAAM,WAAW,aAAa;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,oBAAoB;IACnC;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B;;;OAGG;IACH,2BAA2B,CAAC,EAAE,MAAM,EAAE,CAAC;IACvC;;;;;OAKG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;;OAGG;IACH,eAAe,CAAC,EAAE,eAAe,CAAC;CACnC;AAED,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;OAEG;IACH,yBAAyB,CAAC,EAAE,MAAM,EAAE,CAAC;IACrC;;;OAGG;IACH,wBAAwB,CAAC,EAAE,MAAM,EAAE,CAAC;CACrC;AAED,MAAM,WAAW,eAAgB,SAAQ,uBAAuB,EAAE,oBAAoB,EAAE,yBAAyB;CAAG;AAEpH,qBAAa,kBAAmB,YAAW,UAAU;IACnD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAkC;IACnE,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAA6G;IAC/I,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAkC;IAC1E,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;IACrC,OAAO,CAAC,QAAQ,CAA4B;IAC5C,OAAO,CAAC,aAAa,CAAuB;IAC5C;;;;OAIG;gBACS,OAAO,EAAE,CAAC,aAAa,GAAG,MAAM,CAAC,EAAE,EAAE,eAAe,CAAC,EAAE,eAAe;IAUlF;;;OAGG;IACH,IAAI,QAAQ,IAAI,QAAQ,CAEvB;IACD;;;;OAIG;IACH,cAAc,CAAC,OAAO,EAAE,CAAC,aAAa,GAAG,MAAM,CAAC,EAAE,GAAG,IAAI;IAuDzD,IAAI,CAAC,OAAO,EAAE,OAAO;IAYf,OAAO,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IA6B9C,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAmB/B;;;;;OAKG;IACH,qBAAqB,IAAI,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC;IAI5C;;;;;OAKG;IACH,gBAAgB,IAAI,MAAM,EAAE;IAI5B;;;;;;;;OAQG;IACH,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAKrD;;;;OAIG;IACH,0BAA0B,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAIhE;;;;;;;;;;;;;;;;;OAiBG;IACG,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC;IAU7E;;;;;;OAMG;IACH,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,oBAAoB;CAY3D"}
@@ -0,0 +1,14 @@
1
+ import type { StrategyPlugin } from "../../types.js";
2
+ /**
3
+ * A plugin designed to determine the number of assets that were updated (or not updated)
4
+ * during the `install` event.
5
+ *
6
+ * @private
7
+ */
8
+ export declare class PrecacheInstallReportPlugin implements StrategyPlugin {
9
+ updatedURLs: string[];
10
+ notUpdatedURLs: string[];
11
+ handlerWillStart: StrategyPlugin["handlerWillStart"];
12
+ cachedResponseWillBeUsed: StrategyPlugin["cachedResponseWillBeUsed"];
13
+ }
14
+ //# sourceMappingURL=PrecacheInstallReportPlugin.d.ts.map