serwist 10.0.0-preview.8 → 10.0.0-preview.9

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 (261) hide show
  1. package/dist/chunks/waitUntil.js +129 -129
  2. package/dist/index.d.ts +19 -21
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.internal.d.ts +2 -2
  5. package/dist/index.internal.d.ts.map +1 -1
  6. package/dist/index.internal.js +3 -3
  7. package/dist/index.js +2026 -1917
  8. package/dist/lib/{backgroundSync → background-sync}/BackgroundSyncPlugin.d.ts +1 -1
  9. package/dist/lib/background-sync/BackgroundSyncPlugin.d.ts.map +1 -0
  10. package/dist/lib/background-sync/BackgroundSyncQueue.d.ts.map +1 -0
  11. package/dist/lib/background-sync/BackgroundSyncQueueDb.d.ts.map +1 -0
  12. package/dist/lib/background-sync/BackgroundSyncQueueStore.d.ts.map +1 -0
  13. package/dist/lib/{backgroundSync → background-sync}/StorableRequest.d.ts +1 -1
  14. package/dist/lib/background-sync/StorableRequest.d.ts.map +1 -0
  15. package/dist/lib/background-sync/index.d.ts.map +1 -0
  16. package/dist/lib/{broadcastUpdate → broadcast-update}/BroadcastCacheUpdate.d.ts +1 -1
  17. package/dist/lib/broadcast-update/BroadcastCacheUpdate.d.ts.map +1 -0
  18. package/dist/lib/{broadcastUpdate → broadcast-update}/BroadcastUpdatePlugin.d.ts +1 -1
  19. package/dist/lib/broadcast-update/BroadcastUpdatePlugin.d.ts.map +1 -0
  20. package/dist/lib/broadcast-update/constants.d.ts.map +1 -0
  21. package/dist/lib/broadcast-update/index.d.ts.map +1 -0
  22. package/dist/lib/broadcast-update/responsesAreSame.d.ts.map +1 -0
  23. package/dist/lib/{broadcastUpdate → broadcast-update}/types.d.ts +1 -1
  24. package/dist/lib/broadcast-update/types.d.ts.map +1 -0
  25. package/dist/{cacheNames.d.ts → lib/cache-name.d.ts} +1 -1
  26. package/dist/lib/cache-name.d.ts.map +1 -0
  27. package/dist/lib/cacheable-response/CacheableResponse.d.ts.map +1 -0
  28. package/dist/lib/{cacheableResponse → cacheable-response}/CacheableResponsePlugin.d.ts +1 -1
  29. package/dist/lib/cacheable-response/CacheableResponsePlugin.d.ts.map +1 -0
  30. package/dist/lib/{cacheableResponse → cacheable-response}/index.d.ts +1 -1
  31. package/dist/lib/cacheable-response/index.d.ts.map +1 -0
  32. package/dist/{constants.d.ts → lib/constants.d.ts} +1 -1
  33. package/dist/lib/constants.d.ts.map +1 -0
  34. package/dist/lib/core.d.ts +62 -0
  35. package/dist/lib/core.d.ts.map +1 -0
  36. package/dist/lib/expiration/ExpirationPlugin.d.ts +1 -1
  37. package/dist/lib/expiration/ExpirationPlugin.d.ts.map +1 -1
  38. package/dist/lib/extension.d.ts +30 -0
  39. package/dist/lib/extension.d.ts.map +1 -0
  40. package/dist/lib/extensions/google-analytics/constants.d.ts.map +1 -0
  41. package/dist/lib/extensions/google-analytics/extension.d.ts +79 -0
  42. package/dist/lib/extensions/google-analytics/extension.d.ts.map +1 -0
  43. package/dist/lib/extensions/google-analytics/index.d.ts +2 -0
  44. package/dist/lib/extensions/google-analytics/index.d.ts.map +1 -0
  45. package/dist/lib/extensions/google-analytics/initialize.d.ts +12 -0
  46. package/dist/lib/extensions/google-analytics/initialize.d.ts.map +1 -0
  47. package/dist/lib/extensions/index.d.ts +14 -0
  48. package/dist/lib/extensions/index.d.ts.map +1 -0
  49. package/dist/lib/{controllers/PrecacheController/PrecacheController.d.ts → extensions/precache/extension.d.ts} +11 -34
  50. package/dist/lib/extensions/precache/extension.d.ts.map +1 -0
  51. package/dist/lib/extensions/precache/options.d.ts +26 -0
  52. package/dist/lib/extensions/precache/options.d.ts.map +1 -0
  53. package/dist/lib/{controllers/PrecacheController/PrecacheCacheKeyPlugin.d.ts → extensions/precache/plugin-cache-key.d.ts} +4 -4
  54. package/dist/lib/extensions/precache/plugin-cache-key.d.ts.map +1 -0
  55. package/dist/lib/{precaching/PrecacheFallbackPlugin.d.ts → extensions/precache/plugin-fallback.d.ts} +7 -12
  56. package/dist/lib/extensions/precache/plugin-fallback.d.ts.map +1 -0
  57. package/dist/lib/{controllers/PrecacheController/PrecacheInstallReportPlugin.d.ts → extensions/precache/plugin-install-report.d.ts} +2 -2
  58. package/dist/lib/extensions/precache/plugin-install-report.d.ts.map +1 -0
  59. package/dist/lib/extensions/precache/route.d.ts +42 -0
  60. package/dist/lib/extensions/precache/route.d.ts.map +1 -0
  61. package/dist/lib/{controllers/PrecacheController/PrecacheStrategy.d.ts → extensions/precache/strategy.d.ts} +2 -2
  62. package/dist/lib/extensions/precache/strategy.d.ts.map +1 -0
  63. package/dist/lib/{controllers/RuntimeCacheController.d.ts → extensions/runtime-cache.d.ts} +9 -8
  64. package/dist/lib/extensions/runtime-cache.d.ts.map +1 -0
  65. package/dist/lib/functions/handlers.d.ts +60 -0
  66. package/dist/lib/functions/handlers.d.ts.map +1 -0
  67. package/dist/lib/functions/router.d.ts +60 -0
  68. package/dist/lib/functions/router.d.ts.map +1 -0
  69. package/dist/{navigationPreload.d.ts → lib/navigation-preload.d.ts} +1 -1
  70. package/dist/lib/navigation-preload.d.ts.map +1 -0
  71. package/dist/lib/{rangeRequests → range-requests}/RangeRequestsPlugin.d.ts +1 -1
  72. package/dist/lib/range-requests/RangeRequestsPlugin.d.ts.map +1 -0
  73. package/dist/lib/range-requests/createPartialResponse.d.ts.map +1 -0
  74. package/dist/lib/{rangeRequests → range-requests}/index.d.ts +1 -1
  75. package/dist/lib/range-requests/index.d.ts.map +1 -0
  76. package/dist/lib/range-requests/utils/calculateEffectiveBoundaries.d.ts.map +1 -0
  77. package/dist/lib/range-requests/utils/parseRangeHeader.d.ts.map +1 -0
  78. package/dist/lib/route.d.ts +106 -0
  79. package/dist/lib/route.d.ts.map +1 -0
  80. package/dist/{Serwist.d.ts → lib/serwist.d.ts} +27 -40
  81. package/dist/lib/serwist.d.ts.map +1 -0
  82. package/dist/lib/strategies/NetworkFirst.d.ts.map +1 -1
  83. package/dist/lib/strategies/StaleWhileRevalidate.d.ts.map +1 -1
  84. package/dist/lib/strategies/Strategy.d.ts +1 -1
  85. package/dist/lib/strategies/Strategy.d.ts.map +1 -1
  86. package/dist/lib/strategies/StrategyHandler.d.ts +1 -1
  87. package/dist/lib/strategies/StrategyHandler.d.ts.map +1 -1
  88. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +1 -1
  89. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -1
  90. package/dist/{types.d.ts → lib/types.d.ts} +15 -43
  91. package/dist/lib/types.d.ts.map +1 -0
  92. package/dist/{copyResponse.d.ts → lib/utils.d.ts} +22 -1
  93. package/dist/lib/utils.d.ts.map +1 -0
  94. package/dist/models/messages/messageGenerator.d.ts +1 -1
  95. package/dist/models/messages/messageGenerator.d.ts.map +1 -1
  96. package/dist/utils/SerwistError.d.ts +1 -1
  97. package/dist/utils/SerwistError.d.ts.map +1 -1
  98. package/dist/utils/assert.d.ts +1 -1
  99. package/dist/utils/assert.d.ts.map +1 -1
  100. package/dist/utils/cacheNames.d.ts.map +1 -1
  101. package/dist/utils/createCacheKey.d.ts +1 -1
  102. package/dist/utils/createCacheKey.d.ts.map +1 -1
  103. package/dist/utils/generateURLVariations.d.ts +1 -1
  104. package/dist/utils/generateURLVariations.d.ts.map +1 -1
  105. package/dist/utils/logger.d.ts +1 -1
  106. package/dist/utils/logger.d.ts.map +1 -1
  107. package/dist/utils/normalizeHandler.d.ts +1 -1
  108. package/dist/utils/normalizeHandler.d.ts.map +1 -1
  109. package/dist/utils/parseRoute.d.ts +3 -3
  110. package/dist/utils/parseRoute.d.ts.map +1 -1
  111. package/dist/utils/pluginUtils.d.ts +1 -1
  112. package/dist/utils/pluginUtils.d.ts.map +1 -1
  113. package/package.json +5 -5
  114. package/src/index.internal.ts +2 -2
  115. package/src/index.ts +51 -33
  116. package/src/lib/{backgroundSync → background-sync}/BackgroundSyncPlugin.ts +1 -1
  117. package/src/lib/{backgroundSync → background-sync}/BackgroundSyncQueue.ts +4 -4
  118. package/src/lib/{backgroundSync → background-sync}/BackgroundSyncQueueDb.ts +1 -1
  119. package/src/lib/{backgroundSync → background-sync}/BackgroundSyncQueueStore.ts +0 -2
  120. package/src/lib/{backgroundSync → background-sync}/StorableRequest.ts +1 -1
  121. package/src/lib/{broadcastUpdate → broadcast-update}/BroadcastCacheUpdate.ts +1 -1
  122. package/src/lib/{broadcastUpdate → broadcast-update}/BroadcastUpdatePlugin.ts +1 -1
  123. package/src/lib/{broadcastUpdate → broadcast-update}/types.ts +1 -1
  124. package/src/lib/{cacheableResponse → cacheable-response}/CacheableResponsePlugin.ts +1 -1
  125. package/src/lib/core.ts +128 -0
  126. package/src/lib/expiration/CacheExpiration.ts +1 -1
  127. package/src/lib/expiration/ExpirationPlugin.ts +4 -5
  128. package/src/lib/extension.ts +37 -0
  129. package/src/lib/{googleAnalytics/initializeGoogleAnalytics.ts → extensions/google-analytics/extension.ts} +40 -46
  130. package/src/lib/extensions/google-analytics/index.ts +0 -0
  131. package/src/lib/extensions/google-analytics/initialize.ts +48 -0
  132. package/src/lib/extensions/index.ts +13 -0
  133. package/src/lib/{controllers/PrecacheController/PrecacheController.ts → extensions/precache/extension.ts} +23 -45
  134. package/src/lib/{controllers/PrecacheController/parsePrecacheOptions.ts → extensions/precache/options.ts} +11 -8
  135. package/src/lib/{controllers/PrecacheController/PrecacheCacheKeyPlugin.ts → extensions/precache/plugin-cache-key.ts} +4 -4
  136. package/src/lib/{precaching/PrecacheFallbackPlugin.ts → extensions/precache/plugin-fallback.ts} +22 -21
  137. package/src/lib/{controllers/PrecacheController/PrecacheInstallReportPlugin.ts → extensions/precache/plugin-install-report.ts} +1 -1
  138. package/src/lib/extensions/precache/route.ts +72 -0
  139. package/src/lib/{controllers/PrecacheController/PrecacheStrategy.ts → extensions/precache/strategy.ts} +5 -5
  140. package/src/lib/{controllers/RuntimeCacheController.ts → extensions/runtime-cache.ts} +21 -14
  141. package/src/lib/functions/handlers.ts +149 -0
  142. package/src/lib/functions/router.ts +314 -0
  143. package/src/lib/{rangeRequests → range-requests}/RangeRequestsPlugin.ts +1 -1
  144. package/src/lib/route.ts +234 -0
  145. package/src/lib/serwist.ts +443 -0
  146. package/src/lib/strategies/CacheFirst.ts +2 -2
  147. package/src/lib/strategies/CacheOnly.ts +1 -1
  148. package/src/lib/strategies/NetworkFirst.ts +4 -4
  149. package/src/lib/strategies/NetworkOnly.ts +2 -2
  150. package/src/lib/strategies/StaleWhileRevalidate.ts +3 -3
  151. package/src/lib/strategies/Strategy.ts +6 -6
  152. package/src/lib/strategies/StrategyHandler.ts +5 -5
  153. package/src/lib/strategies/plugins/cacheOkAndOpaquePlugin.ts +1 -1
  154. package/src/{types.ts → lib/types.ts} +17 -57
  155. package/src/{copyResponse.ts → lib/utils.ts} +81 -2
  156. package/src/models/messages/messageGenerator.ts +1 -1
  157. package/src/utils/SerwistError.ts +1 -1
  158. package/src/utils/assert.ts +1 -2
  159. package/src/utils/cacheNames.ts +0 -2
  160. package/src/utils/canConstructReadableStream.ts +1 -1
  161. package/src/utils/canConstructResponseFromBodyStream.ts +1 -1
  162. package/src/utils/createCacheKey.ts +1 -2
  163. package/src/utils/generateURLVariations.ts +1 -1
  164. package/src/utils/normalizeHandler.ts +1 -1
  165. package/src/utils/parseRoute.ts +4 -5
  166. package/src/utils/pluginUtils.ts +1 -1
  167. package/src/utils/resultingClientExists.ts +1 -1
  168. package/dist/NavigationRoute.d.ts +0 -56
  169. package/dist/NavigationRoute.d.ts.map +0 -1
  170. package/dist/RegExpRoute.d.ts +0 -24
  171. package/dist/RegExpRoute.d.ts.map +0 -1
  172. package/dist/Route.d.ts +0 -33
  173. package/dist/Route.d.ts.map +0 -1
  174. package/dist/Serwist.d.ts.map +0 -1
  175. package/dist/cacheNames.d.ts.map +0 -1
  176. package/dist/constants.d.ts.map +0 -1
  177. package/dist/copyResponse.d.ts.map +0 -1
  178. package/dist/disableDevLogs.d.ts +0 -7
  179. package/dist/disableDevLogs.d.ts.map +0 -1
  180. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts.map +0 -1
  181. package/dist/lib/backgroundSync/BackgroundSyncQueue.d.ts.map +0 -1
  182. package/dist/lib/backgroundSync/BackgroundSyncQueueDb.d.ts.map +0 -1
  183. package/dist/lib/backgroundSync/BackgroundSyncQueueStore.d.ts.map +0 -1
  184. package/dist/lib/backgroundSync/StorableRequest.d.ts.map +0 -1
  185. package/dist/lib/backgroundSync/index.d.ts.map +0 -1
  186. package/dist/lib/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +0 -1
  187. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +0 -1
  188. package/dist/lib/broadcastUpdate/constants.d.ts.map +0 -1
  189. package/dist/lib/broadcastUpdate/index.d.ts.map +0 -1
  190. package/dist/lib/broadcastUpdate/responsesAreSame.d.ts.map +0 -1
  191. package/dist/lib/broadcastUpdate/types.d.ts.map +0 -1
  192. package/dist/lib/cacheableResponse/CacheableResponse.d.ts.map +0 -1
  193. package/dist/lib/cacheableResponse/CacheableResponsePlugin.d.ts.map +0 -1
  194. package/dist/lib/cacheableResponse/index.d.ts.map +0 -1
  195. package/dist/lib/controllers/PrecacheController/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  196. package/dist/lib/controllers/PrecacheController/PrecacheController.d.ts.map +0 -1
  197. package/dist/lib/controllers/PrecacheController/PrecacheInstallReportPlugin.d.ts.map +0 -1
  198. package/dist/lib/controllers/PrecacheController/PrecacheRoute.d.ts +0 -15
  199. package/dist/lib/controllers/PrecacheController/PrecacheRoute.d.ts.map +0 -1
  200. package/dist/lib/controllers/PrecacheController/PrecacheStrategy.d.ts.map +0 -1
  201. package/dist/lib/controllers/PrecacheController/parsePrecacheOptions.d.ts +0 -25
  202. package/dist/lib/controllers/PrecacheController/parsePrecacheOptions.d.ts.map +0 -1
  203. package/dist/lib/controllers/RuntimeCacheController.d.ts.map +0 -1
  204. package/dist/lib/controllers/index.d.ts +0 -4
  205. package/dist/lib/controllers/index.d.ts.map +0 -1
  206. package/dist/lib/googleAnalytics/constants.d.ts.map +0 -1
  207. package/dist/lib/googleAnalytics/index.d.ts +0 -3
  208. package/dist/lib/googleAnalytics/index.d.ts.map +0 -1
  209. package/dist/lib/googleAnalytics/initializeGoogleAnalytics.d.ts +0 -30
  210. package/dist/lib/googleAnalytics/initializeGoogleAnalytics.d.ts.map +0 -1
  211. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts.map +0 -1
  212. package/dist/lib/precaching/index.d.ts +0 -3
  213. package/dist/lib/precaching/index.d.ts.map +0 -1
  214. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts.map +0 -1
  215. package/dist/lib/rangeRequests/createPartialResponse.d.ts.map +0 -1
  216. package/dist/lib/rangeRequests/index.d.ts.map +0 -1
  217. package/dist/lib/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +0 -1
  218. package/dist/lib/rangeRequests/utils/parseRangeHeader.d.ts.map +0 -1
  219. package/dist/navigationPreload.d.ts.map +0 -1
  220. package/dist/registerQuotaErrorCallback.d.ts +0 -8
  221. package/dist/registerQuotaErrorCallback.d.ts.map +0 -1
  222. package/dist/setCacheNameDetails.d.ts +0 -9
  223. package/dist/setCacheNameDetails.d.ts.map +0 -1
  224. package/dist/types.d.ts.map +0 -1
  225. package/src/NavigationRoute.ts +0 -118
  226. package/src/RegExpRoute.ts +0 -74
  227. package/src/Route.ts +0 -67
  228. package/src/Serwist.ts +0 -766
  229. package/src/disableDevLogs.ts +0 -10
  230. package/src/lib/controllers/PrecacheController/PrecacheRoute.ts +0 -44
  231. package/src/lib/controllers/index.ts +0 -3
  232. package/src/lib/googleAnalytics/index.ts +0 -2
  233. package/src/lib/precaching/index.ts +0 -2
  234. package/src/registerQuotaErrorCallback.ts +0 -34
  235. package/src/setCacheNameDetails.ts +0 -53
  236. package/dist/lib/{backgroundSync → background-sync}/BackgroundSyncQueue.d.ts +0 -0
  237. package/dist/lib/{backgroundSync → background-sync}/BackgroundSyncQueueDb.d.ts +0 -0
  238. package/dist/lib/{backgroundSync → background-sync}/BackgroundSyncQueueStore.d.ts +0 -0
  239. package/dist/lib/{backgroundSync → background-sync}/index.d.ts +0 -0
  240. package/dist/lib/{broadcastUpdate → broadcast-update}/constants.d.ts +0 -0
  241. package/dist/lib/{broadcastUpdate → broadcast-update}/index.d.ts +0 -0
  242. package/dist/lib/{broadcastUpdate → broadcast-update}/responsesAreSame.d.ts +0 -0
  243. package/dist/lib/{cacheableResponse → cacheable-response}/CacheableResponse.d.ts +0 -0
  244. package/dist/lib/{googleAnalytics → extensions/google-analytics}/constants.d.ts +0 -0
  245. package/dist/lib/{rangeRequests → range-requests}/createPartialResponse.d.ts +0 -0
  246. package/dist/lib/{rangeRequests → range-requests}/utils/calculateEffectiveBoundaries.d.ts +0 -0
  247. package/dist/lib/{rangeRequests → range-requests}/utils/parseRangeHeader.d.ts +0 -0
  248. package/src/lib/{backgroundSync → background-sync}/index.ts +0 -0
  249. package/src/lib/{broadcastUpdate → broadcast-update}/constants.ts +0 -0
  250. package/src/lib/{broadcastUpdate → broadcast-update}/index.ts +0 -0
  251. package/src/lib/{broadcastUpdate → broadcast-update}/responsesAreSame.ts +1 -1
  252. package/src/{cacheNames.ts → lib/cache-name.ts} +0 -0
  253. package/src/lib/{cacheableResponse → cacheable-response}/CacheableResponse.ts +1 -1
  254. package/src/lib/{cacheableResponse → cacheable-response}/index.ts +1 -1
  255. package/src/{constants.ts → lib/constants.ts} +0 -0
  256. package/src/lib/{googleAnalytics → extensions/google-analytics}/constants.ts +0 -0
  257. package/src/{navigationPreload.ts → lib/navigation-preload.ts} +0 -0
  258. package/src/lib/{rangeRequests → range-requests}/createPartialResponse.ts +1 -1
  259. package/src/lib/{rangeRequests → range-requests}/index.ts +1 -1
  260. package/src/lib/{rangeRequests → range-requests}/utils/calculateEffectiveBoundaries.ts +1 -1
  261. package/src/lib/{rangeRequests → range-requests}/utils/parseRangeHeader.ts +1 -1
@@ -0,0 +1,443 @@
1
+ import { createSerwist, type Serwist as SerwistState } from "#lib/core.js";
2
+ import type { GoogleAnalyticsOptions, Precache, PrecacheFallbackEntry, PrecacheOptions } from "#lib/extensions/index.js";
3
+ import { GoogleAnalytics, RuntimeCache } from "#lib/extensions/index.js";
4
+ import {
5
+ createActivateHandler,
6
+ createCacheHandler,
7
+ createFetchHandler,
8
+ createInstallHandler,
9
+ setCatchHandler,
10
+ setDefaultHandler,
11
+ } from "#lib/functions/handlers.js";
12
+ import { findMatchingRoute, handleRequest, registerCapture, registerRoute, unregisterRoute } from "#lib/functions/router.js";
13
+ import type { Strategy } from "#lib/strategies/Strategy.js";
14
+ import type { HTTPMethod } from "./constants.js";
15
+ import type { Extension } from "./extension.js";
16
+ import type { Route } from "./route.js";
17
+ import type {
18
+ PrecacheEntry,
19
+ RouteHandler,
20
+ RouteHandlerCallback,
21
+ RouteHandlerCallbackOptions,
22
+ RouteMatchCallback,
23
+ RouteMatchCallbackOptions,
24
+ RuntimeCaching,
25
+ } from "./types.js";
26
+
27
+ declare const self: ServiceWorkerGlobalScope;
28
+
29
+ export interface FallbackEntry extends PrecacheFallbackEntry {}
30
+
31
+ export interface FallbacksOptions {
32
+ /**
33
+ * A list of fallback entries.
34
+ */
35
+ entries: FallbackEntry[];
36
+ }
37
+
38
+ /**
39
+ * @deprecated Legacy `Serwist` class. Please migrate to `createSerwist`.
40
+ */
41
+ export interface SerwistOptions {
42
+ /**
43
+ * A list of URLs that should be cached.
44
+ */
45
+ precacheEntries?: (PrecacheEntry | string)[];
46
+ /**
47
+ * Options to customize how Serwist precaches the URLs in the precache list.
48
+ */
49
+ precacheOptions?: Omit<PrecacheOptions, "entries">;
50
+ /**
51
+ * Forces the waiting service worker to become the active one.
52
+ *
53
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting
54
+ */
55
+ skipWaiting?: boolean;
56
+ /**
57
+ * Imports external scripts. They are executed in the order they
58
+ * are passed.
59
+ *
60
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts
61
+ */
62
+ importScripts?: string[];
63
+ /**
64
+ * Enables navigation preloading if it is supported.
65
+ *
66
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/navigationPreload
67
+ */
68
+ navigationPreload?: boolean;
69
+ /**
70
+ * Modifies the prefix of the default cache names used by Serwist packages.
71
+ */
72
+ cacheId?: string | undefined;
73
+ /**
74
+ * Claims any currently available clients once the service worker
75
+ * becomes active. This is normally used in conjunction with `skipWaiting()`.
76
+ *
77
+ * @default false
78
+ */
79
+ clientsClaim?: boolean;
80
+ /**
81
+ * A list of caching strategies.
82
+ */
83
+ runtimeCaching?: RuntimeCaching[];
84
+ /**
85
+ * Your configuration for {@linkcode GoogleAnalytics}. This plugin is
86
+ * only initialized when this option is not `undefined` or `false`.
87
+ */
88
+ offlineAnalyticsConfig?: GoogleAnalyticsOptions | boolean;
89
+ /**
90
+ * Disables Serwist's logging in development mode.
91
+ *
92
+ * @default false
93
+ */
94
+ disableDevLogs?: boolean;
95
+ /**
96
+ * Precaches routes so that they can be used as a fallback when
97
+ * a {@linkcode Strategy} fails to generate a response.
98
+ *
99
+ * Note: This option mutates `runtimeCaching`. It also expects the URLs
100
+ * defined in `entries` to have been precached beforehand.
101
+ */
102
+ fallbacks?: FallbacksOptions;
103
+ /**
104
+ * A list of extensions.
105
+ */
106
+ extensions?: Extension[];
107
+ }
108
+
109
+ /**
110
+ * A class that helps bootstrap the service worker.
111
+ *
112
+ * @deprecated Legacy `Serwist` class. Please migrate to `createSerwist`.
113
+ * @see https://serwist.pages.dev/docs/serwist/core/serwist
114
+ */
115
+ export class Serwist {
116
+ private readonly _state: SerwistState;
117
+ private readonly _installHandler: (event: ExtendableEvent) => Promise<void>;
118
+ private readonly _activateHandler: (event: ExtendableEvent) => Promise<void>;
119
+ private readonly _fetchHandler: (event: FetchEvent) => void;
120
+ private readonly _cacheHandler: (event: ExtendableMessageEvent) => void;
121
+
122
+ constructor({
123
+ precacheEntries,
124
+ precacheOptions,
125
+ skipWaiting = false,
126
+ importScripts,
127
+ navigationPreload = false,
128
+ cacheId,
129
+ clientsClaim = false,
130
+ runtimeCaching,
131
+ offlineAnalyticsConfig,
132
+ disableDevLogs = false,
133
+ fallbacks,
134
+ extensions,
135
+ }: SerwistOptions = {}) {
136
+ this.handleInstall = this.handleInstall.bind(this);
137
+ this.handleActivate = this.handleActivate.bind(this);
138
+ this.handleFetch = this.handleFetch.bind(this);
139
+ this.handleCache = this.handleCache.bind(this);
140
+
141
+ this._state = createSerwist({
142
+ precache: { entries: precacheEntries ?? [], ...precacheOptions },
143
+ extensions: [
144
+ !extensions?.some((ext) => ext instanceof RuntimeCache) && runtimeCaching !== undefined
145
+ ? new RuntimeCache(runtimeCaching, { fallbacks })
146
+ : undefined,
147
+ !extensions?.some((ext) => ext instanceof GoogleAnalytics) && offlineAnalyticsConfig !== undefined
148
+ ? typeof offlineAnalyticsConfig === "boolean"
149
+ ? offlineAnalyticsConfig
150
+ ? new GoogleAnalytics()
151
+ : undefined
152
+ : new GoogleAnalytics(offlineAnalyticsConfig)
153
+ : undefined,
154
+ ...(extensions ?? []),
155
+ ].filter((extension) => extension !== undefined),
156
+ skipWaiting,
157
+ importScripts,
158
+ navigationPreload,
159
+ cacheId,
160
+ clientsClaim,
161
+ disableDevLogs,
162
+ });
163
+
164
+ this._installHandler = createInstallHandler(this._state);
165
+ this._activateHandler = createActivateHandler(this._state);
166
+ this._fetchHandler = createFetchHandler(this._state);
167
+ this._cacheHandler = createCacheHandler(this._state);
168
+ }
169
+
170
+ /**
171
+ * The {@linkcode Precache} used to handle precaching.
172
+ */
173
+ get precache(): Precache {
174
+ return this._state.precache;
175
+ }
176
+
177
+ /**
178
+ * The strategy used to precache assets and respond to `fetch` events.
179
+ */
180
+ get precacheStrategy(): Strategy {
181
+ return this._state.precache.strategy;
182
+ }
183
+
184
+ /**
185
+ * A `Map` of HTTP method name (`'GET'`, etc.) to an array of all corresponding registered {@linkcode Route}
186
+ * instances.
187
+ */
188
+ get routes(): Map<HTTPMethod, Route[]> {
189
+ return this._state.routes;
190
+ }
191
+
192
+ get state(): SerwistState {
193
+ return this._state;
194
+ }
195
+
196
+ /**
197
+ * Adds Serwist's event listeners. Before calling it, add your own listeners should you need to.
198
+ */
199
+ addEventListeners() {
200
+ self.addEventListener("install", this._installHandler);
201
+ self.addEventListener("activate", this._activateHandler);
202
+ self.addEventListener("fetch", this._fetchHandler);
203
+ self.addEventListener("message", this._cacheHandler);
204
+ }
205
+
206
+ /**
207
+ * Precaches new and updated assets. Call this method from the service worker's
208
+ * `install` event.
209
+ *
210
+ * Note: this method calls `event.waitUntil()` for you, so you do not need
211
+ * to call it yourself in your event handlers.
212
+ *
213
+ * @param event
214
+ * @returns
215
+ */
216
+ handleInstall(event: ExtendableEvent): Promise<void> {
217
+ return this._installHandler(event);
218
+ }
219
+
220
+ /**
221
+ * Deletes assets that are no longer present in the current precache manifest.
222
+ * Call this method from the service worker's `activate` event.
223
+ *
224
+ * Note: this method calls `event.waitUntil()` for you, so you do not need
225
+ * to call it yourself in your event handlers.
226
+ *
227
+ * @param event
228
+ * @returns
229
+ */
230
+ handleActivate(event: ExtendableEvent): Promise<void> {
231
+ return this._activateHandler(event);
232
+ }
233
+
234
+ /**
235
+ * Gets a `Response` from an appropriate `Route`'s handler. Call this method
236
+ * from the service worker's `fetch` event.
237
+ * @param event
238
+ */
239
+ handleFetch(event: FetchEvent) {
240
+ return this._fetchHandler(event);
241
+ }
242
+
243
+ /**
244
+ * Caches new URLs on demand. Call this method from the service worker's
245
+ * `message` event. To trigger the handler, send a message of type `"CACHE_URLS"`
246
+ * alongside a list of URLs that should be cached as `urlsToCache`.
247
+ * @param event
248
+ */
249
+ handleCache(event: ExtendableMessageEvent) {
250
+ return this._cacheHandler(event);
251
+ }
252
+
253
+ /**
254
+ * Define a default handler that's called when no routes explicitly
255
+ * match the incoming request.
256
+ *
257
+ * Each HTTP method (`'GET'`, `'POST'`, etc.) gets its own default handler.
258
+ *
259
+ * Without a default handler, unmatched requests will go against the
260
+ * network as if there were no service worker present.
261
+ *
262
+ * @param handler A callback function that returns a `Promise` resulting in a `Response`.
263
+ * @param method The HTTP method to associate with this default handler. Each method
264
+ * has its own default. Defaults to `'GET'`.
265
+ */
266
+ setDefaultHandler(handler: RouteHandler, method?: HTTPMethod): void {
267
+ setDefaultHandler(this._state, handler, method);
268
+ }
269
+
270
+ /**
271
+ * If a {@linkcode Route} throws an error while handling a request, this handler
272
+ * will be called and given a chance to provide a response.
273
+ *
274
+ * @param handler A callback function that returns a `Promise` resulting
275
+ * in a `Response`.
276
+ */
277
+ setCatchHandler(handler: RouteHandler): void {
278
+ setCatchHandler(this._state, handler);
279
+ }
280
+
281
+ /**
282
+ * Registers a `RegExp`, string, or function with a caching
283
+ * strategy to the router.
284
+ *
285
+ * @param capture If the capture param is a {@linkcode Route} object, all other arguments will be ignored.
286
+ * @param handler A callback function that returns a `Promise` resulting in a `Response`.
287
+ * This parameter is required if `capture` is not a {@linkcode Route} object.
288
+ * @param method The HTTP method to match the route against. Defaults to `'GET'`.
289
+ * @returns The generated {@linkcode Route} object.
290
+ */
291
+ registerCapture<T extends RegExp | string | RouteMatchCallback | Route>(
292
+ capture: T,
293
+ handler?: T extends Route ? never : RouteHandler,
294
+ method?: T extends Route ? never : HTTPMethod,
295
+ ): Route {
296
+ return registerCapture(this._state, capture, handler, method);
297
+ }
298
+
299
+ /**
300
+ * Registers a {@linkcode Route} with the router.
301
+ *
302
+ * @param route The {@linkcode Route} to register.
303
+ */
304
+ registerRoute(route: Route): void {
305
+ registerRoute(this._state, route);
306
+ }
307
+
308
+ /**
309
+ * Unregisters a route from the router.
310
+ *
311
+ * @param route The {@linkcode Route} object to unregister.
312
+ */
313
+ unregisterRoute(route: Route): void {
314
+ unregisterRoute(this._state, route);
315
+ }
316
+
317
+ /**
318
+ * Applies the routing rules to a `FetchEvent` object to get a response from an
319
+ * appropriate route.
320
+ *
321
+ * @param options
322
+ * @returns A promise is returned if a registered route can handle the request.
323
+ * If there is no matching route and there's no default handler, `undefined`
324
+ * is returned.
325
+ */
326
+ handleRequest({
327
+ request,
328
+ event,
329
+ }: {
330
+ /**
331
+ * The request to handle.
332
+ */
333
+ request: Request;
334
+ /**
335
+ * The event that triggered the request.
336
+ */
337
+ event: ExtendableEvent;
338
+ }): Promise<Response> | undefined {
339
+ return handleRequest(this._state, { request, event });
340
+ }
341
+
342
+ /**
343
+ * Checks a request and URL (and optionally an event) against the list of
344
+ * registered routes, and if there's a match, returns the corresponding
345
+ * route along with any params generated by the match.
346
+ *
347
+ * @param options
348
+ * @returns An object with `route` and `params` properties. They are populated
349
+ * if a matching route was found or `undefined` otherwise.
350
+ */
351
+ findMatchingRoute({ url, sameOrigin, request, event }: RouteMatchCallbackOptions): {
352
+ route?: Route;
353
+ params?: RouteHandlerCallbackOptions["params"];
354
+ } {
355
+ return findMatchingRoute(this._state, { url, sameOrigin, request, event });
356
+ }
357
+
358
+ // The following are deprecated methods:
359
+
360
+ /**
361
+ * Adds items to the precache list, removing duplicates and ensuring the information is valid.
362
+ *
363
+ * @param entries Array of entries to precache.
364
+ */
365
+ addToPrecacheList(entries: (PrecacheEntry | string)[]): void {
366
+ this.precache.addToCacheList(entries);
367
+ }
368
+
369
+ /**
370
+ * Returns a mapping of a precached URL to the corresponding cache key, taking
371
+ * into account the revision information for the URL.
372
+ *
373
+ * @returns A URL to cache key mapping.
374
+ */
375
+ getUrlsToPrecacheKeys(): Map<string, string> {
376
+ return this.precache.getUrlsToPrecacheKeys();
377
+ }
378
+
379
+ /**
380
+ * Returns a list of all the URLs that have been precached by the current
381
+ * service worker.
382
+ *
383
+ * @returns The precached URLs.
384
+ */
385
+ getPrecachedUrls(): string[] {
386
+ return this.precache.getPrecachedUrls();
387
+ }
388
+
389
+ /**
390
+ * Returns the cache key used for storing a given URL. If that URL is
391
+ * unversioned, like "/index.html", then the cache key will be the original
392
+ * URL with a search parameter appended to it.
393
+ *
394
+ * @param url A URL whose cache key you want to look up.
395
+ * @returns The versioned URL that corresponds to a cache key
396
+ * for the original URL, or undefined if that URL isn't precached.
397
+ */
398
+ getPrecacheKeyForUrl(url: string): string | undefined {
399
+ return this.precache.getPrecacheKeyForUrl(url);
400
+ }
401
+
402
+ /**
403
+ * @param url A cache key whose SRI you want to look up.
404
+ * @returns The subresource integrity associated with the cache key,
405
+ * or undefined if it's not set.
406
+ */
407
+ getIntegrityForPrecacheKey(cacheKey: string): string | undefined {
408
+ return this.precache.getIntegrityForPrecacheKey(cacheKey);
409
+ }
410
+
411
+ /**
412
+ * This acts as a drop-in replacement for
413
+ * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
414
+ * with the following differences:
415
+ *
416
+ * - It knows what the name of the precache is, and only checks in that cache.
417
+ * - It allows you to pass in an "original" URL without versioning parameters,
418
+ * and it will automatically look up the correct cache key for the currently
419
+ * active revision of that URL.
420
+ *
421
+ * E.g., `matchPrecache('index.html')` will find the correct precached
422
+ * response for the currently active service worker, even if the actual cache
423
+ * key is `'/index.html?__WB_REVISION__=1234abcd'`.
424
+ *
425
+ * @param request The key (without revisioning parameters)
426
+ * to look up in the precache.
427
+ * @returns
428
+ */
429
+ matchPrecache(request: string | Request): Promise<Response | undefined> {
430
+ return this.precache.matchPrecache(request);
431
+ }
432
+
433
+ /**
434
+ * Returns a function that looks up `url` in the precache (taking into
435
+ * account revision information), and returns the corresponding `Response`.
436
+ *
437
+ * @param url The precached URL which will be used to lookup the response.
438
+ * @return
439
+ */
440
+ createHandlerBoundToUrl(url: string): RouteHandlerCallback {
441
+ return this.precache.createHandlerBoundToUrl(url);
442
+ }
443
+ }
@@ -6,9 +6,9 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { SerwistError } from "#utils/SerwistError.js";
10
9
  import { assert } from "#utils/assert.js";
11
10
  import { logger } from "#utils/logger.js";
11
+ import { SerwistError } from "#utils/SerwistError.js";
12
12
  import { Strategy } from "./Strategy.js";
13
13
  import type { StrategyHandler } from "./StrategyHandler.js";
14
14
  import { messages } from "./utils/messages.js";
@@ -45,7 +45,7 @@ export class CacheFirst extends Strategy {
45
45
 
46
46
  let response = await handler.cacheMatch(request);
47
47
 
48
- let error: Error | undefined = undefined;
48
+ let error: Error | undefined;
49
49
  if (!response) {
50
50
  if (process.env.NODE_ENV !== "production") {
51
51
  logs.push(`No response found in the '${this.cacheName}' cache. Will respond with a network request.`);
@@ -6,9 +6,9 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { SerwistError } from "#utils/SerwistError.js";
10
9
  import { assert } from "#utils/assert.js";
11
10
  import { logger } from "#utils/logger.js";
11
+ import { SerwistError } from "#utils/SerwistError.js";
12
12
  import { Strategy } from "./Strategy.js";
13
13
  import type { StrategyHandler } from "./StrategyHandler.js";
14
14
  import { messages } from "./utils/messages.js";
@@ -6,13 +6,13 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { SerwistError } from "#utils/SerwistError.js";
10
9
  import { assert } from "#utils/assert.js";
11
10
  import { logger } from "#utils/logger.js";
11
+ import { SerwistError } from "#utils/SerwistError.js";
12
+ import { cacheOkAndOpaquePlugin } from "./plugins/cacheOkAndOpaquePlugin.js";
12
13
  import type { StrategyOptions } from "./Strategy.js";
13
14
  import { Strategy } from "./Strategy.js";
14
15
  import type { StrategyHandler } from "./StrategyHandler.js";
15
- import { cacheOkAndOpaquePlugin } from "./plugins/cacheOkAndOpaquePlugin.js";
16
16
  import { messages } from "./utils/messages.js";
17
17
 
18
18
  export interface NetworkFirstOptions extends StrategyOptions {
@@ -190,8 +190,8 @@ export class NetworkFirst extends Strategy {
190
190
  timeoutId?: number;
191
191
  handler: StrategyHandler;
192
192
  }): Promise<Response | undefined> {
193
- let error: Error | undefined = undefined;
194
- let response: Response | undefined = undefined;
193
+ let error: Error | undefined;
194
+ let response: Response | undefined;
195
195
  try {
196
196
  response = await handler.fetchAndCachePut(request);
197
197
  } catch (fetchError) {
@@ -6,9 +6,9 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { SerwistError } from "#utils/SerwistError.js";
10
9
  import { assert } from "#utils/assert.js";
11
10
  import { logger } from "#utils/logger.js";
11
+ import { SerwistError } from "#utils/SerwistError.js";
12
12
  import { timeout } from "#utils/timeout.js";
13
13
  import type { StrategyOptions } from "./Strategy.js";
14
14
  import { Strategy } from "./Strategy.js";
@@ -58,7 +58,7 @@ export class NetworkOnly extends Strategy {
58
58
  });
59
59
  }
60
60
 
61
- let error: Error | undefined = undefined;
61
+ let error: Error | undefined;
62
62
  let response: Response | undefined;
63
63
 
64
64
  try {
@@ -6,13 +6,13 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { SerwistError } from "#utils/SerwistError.js";
10
9
  import { assert } from "#utils/assert.js";
11
10
  import { logger } from "#utils/logger.js";
11
+ import { SerwistError } from "#utils/SerwistError.js";
12
+ import { cacheOkAndOpaquePlugin } from "./plugins/cacheOkAndOpaquePlugin.js";
12
13
  import type { StrategyOptions } from "./Strategy.js";
13
14
  import { Strategy } from "./Strategy.js";
14
15
  import type { StrategyHandler } from "./StrategyHandler.js";
15
- import { cacheOkAndOpaquePlugin } from "./plugins/cacheOkAndOpaquePlugin.js";
16
16
  import { messages } from "./utils/messages.js";
17
17
 
18
18
  /**
@@ -73,7 +73,7 @@ export class StaleWhileRevalidate extends Strategy {
73
73
 
74
74
  let response = await handler.cacheMatch(request);
75
75
 
76
- let error: Error | undefined = undefined;
76
+ let error: Error | undefined;
77
77
  if (response) {
78
78
  if (process.env.NODE_ENV !== "production") {
79
79
  logs.push(`Found a cached response in the '${this.cacheName}' cache. Will update with the network response in the background.`);
@@ -6,11 +6,11 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { SerwistError } from "#utils/SerwistError.js";
9
+ import type { HandlerCallbackOptions, RouteHandlerObject, StrategyPlugin } from "#lib/types.js";
10
10
  import { cacheNames as privateCacheNames } from "#utils/cacheNames.js";
11
11
  import { getFriendlyURL } from "#utils/getFriendlyURL.js";
12
12
  import { logger } from "#utils/logger.js";
13
- import type { HandlerCallbackOptions, RouteHandlerObject, StrategyPlugin } from "../../types.js";
13
+ import { SerwistError } from "#utils/SerwistError.js";
14
14
  import { StrategyHandler } from "./StrategyHandler.js";
15
15
 
16
16
  export interface StrategyOptions {
@@ -124,7 +124,7 @@ export abstract class Strategy implements RouteHandlerObject {
124
124
  async _getResponse(handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise<Response> {
125
125
  await handler.runCallbacks("handlerWillStart", { event, request });
126
126
 
127
- let response: Response | undefined = undefined;
127
+ let response: Response | undefined;
128
128
  try {
129
129
  response = await this._handle(request, handler);
130
130
  // The "official" Strategy subclasses all throw this error automatically,
@@ -163,12 +163,12 @@ export abstract class Strategy implements RouteHandlerObject {
163
163
  }
164
164
 
165
165
  async _awaitComplete(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise<void> {
166
- let response: Response | undefined = undefined;
167
- let error: Error | undefined = undefined;
166
+ let response: Response | undefined;
167
+ let error: Error | undefined;
168
168
 
169
169
  try {
170
170
  response = await responseDone;
171
- } catch (error) {
171
+ } catch {
172
172
  // Ignore errors, as response errors should be caught via the `response`
173
173
  // promise above. The `done` promise will only throw for errors in
174
174
  // promises passed to `handler.waitUntil()`.
@@ -6,16 +6,16 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { Deferred } from "#utils/Deferred.js";
10
- import { SerwistError } from "#utils/SerwistError.js";
9
+ import type { Route } from "#lib/route.js";
10
+ import type { HandlerCallbackOptions, MapLikeObject, StrategyPlugin, StrategyPluginCallbackParam } from "#lib/types.js";
11
11
  import { assert } from "#utils/assert.js";
12
12
  import { cacheMatchIgnoreParams } from "#utils/cacheMatchIgnoreParams.js";
13
+ import { Deferred } from "#utils/Deferred.js";
13
14
  import { executeQuotaErrorCallbacks } from "#utils/executeQuotaErrorCallbacks.js";
14
15
  import { getFriendlyURL } from "#utils/getFriendlyURL.js";
15
16
  import { logger } from "#utils/logger.js";
17
+ import { SerwistError } from "#utils/SerwistError.js";
16
18
  import { timeout } from "#utils/timeout.js";
17
- import type { Route } from "../../Route.js";
18
- import type { HandlerCallbackOptions, MapLikeObject, StrategyPlugin, StrategyPluginCallbackParam } from "../../types.js";
19
19
  import type { Strategy } from "./Strategy.js";
20
20
 
21
21
  function toRequest(input: RequestInfo) {
@@ -480,7 +480,7 @@ export class StrategyHandler {
480
480
  * the service worker thread may be killed prior to your work completing.
481
481
  */
482
482
  async doneWaiting(): Promise<void> {
483
- let promise: Promise<any> | undefined = undefined;
483
+ let promise: Promise<any> | undefined;
484
484
  while ((promise = this._extendLifetimePromises.shift())) {
485
485
  await promise;
486
486
  }
@@ -6,7 +6,7 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import type { StrategyPlugin } from "../../../types.js";
9
+ import type { StrategyPlugin } from "#lib/types.js";
10
10
 
11
11
  export const cacheOkAndOpaquePlugin: StrategyPlugin = {
12
12
  /**