serwist 9.1.1 → 10.0.0-preview.10

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 (335) hide show
  1. package/dist/chunks/waitUntil.js +141 -134
  2. package/dist/index.d.ts +22 -49
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.internal.d.ts +16 -16
  5. package/dist/index.internal.d.ts.map +1 -1
  6. package/dist/index.internal.js +25 -3
  7. package/dist/index.js +2231 -452
  8. package/dist/lib/{backgroundSync → background-sync}/BackgroundSyncPlugin.d.ts +2 -2
  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 +6 -0
  16. package/dist/lib/background-sync/index.d.ts.map +1 -0
  17. package/dist/lib/{broadcastUpdate → broadcast-update}/BroadcastCacheUpdate.d.ts +1 -1
  18. package/dist/lib/broadcast-update/BroadcastCacheUpdate.d.ts.map +1 -0
  19. package/dist/lib/{broadcastUpdate → broadcast-update}/BroadcastUpdatePlugin.d.ts +2 -2
  20. package/dist/lib/broadcast-update/BroadcastUpdatePlugin.d.ts.map +1 -0
  21. package/dist/lib/broadcast-update/constants.d.ts.map +1 -0
  22. package/dist/lib/broadcast-update/index.d.ts +6 -0
  23. package/dist/lib/broadcast-update/index.d.ts.map +1 -0
  24. package/dist/lib/broadcast-update/responsesAreSame.d.ts.map +1 -0
  25. package/dist/lib/{broadcastUpdate → broadcast-update}/types.d.ts +1 -1
  26. package/dist/lib/broadcast-update/types.d.ts.map +1 -0
  27. package/dist/{cacheNames.d.ts → lib/cache-name.d.ts} +1 -1
  28. package/dist/lib/cache-name.d.ts.map +1 -0
  29. package/dist/lib/cacheable-response/CacheableResponse.d.ts.map +1 -0
  30. package/dist/lib/{cacheableResponse → cacheable-response}/CacheableResponsePlugin.d.ts +3 -3
  31. package/dist/lib/cacheable-response/CacheableResponsePlugin.d.ts.map +1 -0
  32. package/dist/lib/cacheable-response/index.d.ts +4 -0
  33. package/dist/lib/cacheable-response/index.d.ts.map +1 -0
  34. package/dist/{constants.d.ts → lib/constants.d.ts} +1 -1
  35. package/dist/lib/constants.d.ts.map +1 -0
  36. package/dist/lib/core.d.ts +62 -0
  37. package/dist/lib/core.d.ts.map +1 -0
  38. package/dist/lib/expiration/ExpirationPlugin.d.ts +2 -2
  39. package/dist/lib/expiration/ExpirationPlugin.d.ts.map +1 -1
  40. package/dist/lib/expiration/index.d.ts +4 -0
  41. package/dist/lib/expiration/index.d.ts.map +1 -0
  42. package/dist/lib/extension.d.ts +30 -0
  43. package/dist/lib/extension.d.ts.map +1 -0
  44. package/dist/lib/extensions/google-analytics/constants.d.ts.map +1 -0
  45. package/dist/lib/extensions/google-analytics/extension.d.ts +79 -0
  46. package/dist/lib/extensions/google-analytics/extension.d.ts.map +1 -0
  47. package/dist/lib/extensions/google-analytics/index.d.ts +2 -0
  48. package/dist/lib/extensions/google-analytics/index.d.ts.map +1 -0
  49. package/dist/lib/extensions/google-analytics/initialize.d.ts +12 -0
  50. package/dist/lib/extensions/google-analytics/initialize.d.ts.map +1 -0
  51. package/dist/lib/extensions/index.d.ts +14 -0
  52. package/dist/lib/extensions/index.d.ts.map +1 -0
  53. package/dist/{legacy/PrecacheController.d.ts → lib/extensions/precache/extension.d.ts} +56 -66
  54. package/dist/lib/extensions/precache/extension.d.ts.map +1 -0
  55. package/dist/lib/extensions/precache/options.d.ts +26 -0
  56. package/dist/lib/extensions/precache/options.d.ts.map +1 -0
  57. package/dist/lib/extensions/precache/plugin-cache-key.d.ts +16 -0
  58. package/dist/lib/extensions/precache/plugin-cache-key.d.ts.map +1 -0
  59. package/dist/lib/{precaching/PrecacheFallbackPlugin.d.ts → extensions/precache/plugin-fallback.d.ts} +4 -4
  60. package/dist/lib/extensions/precache/plugin-fallback.d.ts.map +1 -0
  61. package/dist/lib/extensions/precache/plugin-install-report.d.ts +14 -0
  62. package/dist/lib/extensions/precache/plugin-install-report.d.ts.map +1 -0
  63. package/dist/lib/extensions/precache/route.d.ts +42 -0
  64. package/dist/lib/extensions/precache/route.d.ts.map +1 -0
  65. package/dist/lib/{strategies/PrecacheStrategy.d.ts → extensions/precache/strategy.d.ts} +7 -7
  66. package/dist/lib/extensions/precache/strategy.d.ts.map +1 -0
  67. package/dist/lib/extensions/runtime-cache.d.ts +71 -0
  68. package/dist/lib/extensions/runtime-cache.d.ts.map +1 -0
  69. package/dist/lib/functions/handlers.d.ts +60 -0
  70. package/dist/lib/functions/handlers.d.ts.map +1 -0
  71. package/dist/lib/functions/router.d.ts +60 -0
  72. package/dist/lib/functions/router.d.ts.map +1 -0
  73. package/dist/{navigationPreload.d.ts → lib/navigation-preload.d.ts} +1 -1
  74. package/dist/lib/navigation-preload.d.ts.map +1 -0
  75. package/dist/lib/{rangeRequests → range-requests}/RangeRequestsPlugin.d.ts +3 -3
  76. package/dist/lib/range-requests/RangeRequestsPlugin.d.ts.map +1 -0
  77. package/dist/lib/range-requests/createPartialResponse.d.ts.map +1 -0
  78. package/dist/lib/range-requests/index.d.ts +3 -0
  79. package/dist/lib/range-requests/index.d.ts.map +1 -0
  80. package/dist/lib/range-requests/utils/calculateEffectiveBoundaries.d.ts.map +1 -0
  81. package/dist/lib/range-requests/utils/parseRangeHeader.d.ts.map +1 -0
  82. package/dist/lib/route.d.ts +106 -0
  83. package/dist/lib/route.d.ts.map +1 -0
  84. package/dist/{Serwist.d.ts → lib/serwist.d.ts} +71 -62
  85. package/dist/lib/serwist.d.ts.map +1 -0
  86. package/dist/lib/strategies/NetworkFirst.d.ts.map +1 -1
  87. package/dist/lib/strategies/StaleWhileRevalidate.d.ts.map +1 -1
  88. package/dist/lib/strategies/Strategy.d.ts +3 -3
  89. package/dist/lib/strategies/Strategy.d.ts.map +1 -1
  90. package/dist/lib/strategies/StrategyHandler.d.ts +4 -4
  91. package/dist/lib/strategies/StrategyHandler.d.ts.map +1 -1
  92. package/dist/lib/strategies/index.d.ts +11 -0
  93. package/dist/lib/strategies/index.d.ts.map +1 -0
  94. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +2 -2
  95. package/dist/lib/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -1
  96. package/dist/{types.d.ts → lib/types.d.ts} +7 -65
  97. package/dist/lib/types.d.ts.map +1 -0
  98. package/dist/{copyResponse.d.ts → lib/utils.d.ts} +22 -1
  99. package/dist/lib/utils.d.ts.map +1 -0
  100. package/dist/models/messages/messageGenerator.d.ts +1 -1
  101. package/dist/models/messages/messageGenerator.d.ts.map +1 -1
  102. package/dist/utils/SerwistError.d.ts +2 -2
  103. package/dist/utils/SerwistError.d.ts.map +1 -1
  104. package/dist/utils/assert.d.ts +1 -1
  105. package/dist/utils/assert.d.ts.map +1 -1
  106. package/dist/utils/createCacheKey.d.ts +1 -1
  107. package/dist/utils/createCacheKey.d.ts.map +1 -1
  108. package/dist/utils/generateURLVariations.d.ts +1 -1
  109. package/dist/utils/generateURLVariations.d.ts.map +1 -1
  110. package/dist/utils/logger.d.ts +1 -1
  111. package/dist/utils/logger.d.ts.map +1 -1
  112. package/dist/utils/normalizeHandler.d.ts +1 -1
  113. package/dist/utils/normalizeHandler.d.ts.map +1 -1
  114. package/dist/utils/parseRoute.d.ts +3 -3
  115. package/dist/utils/parseRoute.d.ts.map +1 -1
  116. package/dist/utils/pluginUtils.d.ts +2 -2
  117. package/dist/utils/pluginUtils.d.ts.map +1 -1
  118. package/package.json +28 -11
  119. package/src/index.internal.ts +16 -16
  120. package/src/index.ts +100 -107
  121. package/src/lib/{backgroundSync → background-sync}/BackgroundSyncPlugin.ts +2 -2
  122. package/src/lib/{backgroundSync → background-sync}/BackgroundSyncQueue.ts +4 -4
  123. package/src/lib/{backgroundSync → background-sync}/BackgroundSyncQueueStore.ts +1 -1
  124. package/src/lib/{backgroundSync → background-sync}/StorableRequest.ts +2 -2
  125. package/src/lib/background-sync/index.ts +5 -0
  126. package/src/lib/{broadcastUpdate → broadcast-update}/BroadcastCacheUpdate.ts +5 -5
  127. package/src/lib/{broadcastUpdate → broadcast-update}/BroadcastUpdatePlugin.ts +2 -2
  128. package/src/lib/broadcast-update/index.ts +5 -0
  129. package/src/lib/{broadcastUpdate → broadcast-update}/responsesAreSame.ts +2 -2
  130. package/src/lib/{broadcastUpdate → broadcast-update}/types.ts +1 -1
  131. package/src/{cacheNames.ts → lib/cache-name.ts} +1 -1
  132. package/src/lib/{cacheableResponse → cacheable-response}/CacheableResponse.ts +4 -4
  133. package/src/lib/{cacheableResponse → cacheable-response}/CacheableResponsePlugin.ts +3 -3
  134. package/src/lib/cacheable-response/index.ts +3 -0
  135. package/src/lib/core.ts +128 -0
  136. package/src/lib/expiration/CacheExpiration.ts +3 -3
  137. package/src/lib/expiration/ExpirationPlugin.ts +9 -10
  138. package/src/lib/expiration/index.ts +3 -0
  139. package/src/lib/extension.ts +37 -0
  140. package/src/lib/{googleAnalytics/initializeGoogleAnalytics.ts → extensions/google-analytics/extension.ts} +42 -48
  141. package/src/lib/extensions/google-analytics/index.ts +0 -0
  142. package/src/lib/extensions/google-analytics/initialize.ts +48 -0
  143. package/src/lib/extensions/index.ts +13 -0
  144. package/src/lib/extensions/precache/extension.ts +306 -0
  145. package/src/lib/extensions/precache/options.ts +49 -0
  146. package/src/{legacy/utils/PrecacheCacheKeyPlugin.ts → lib/extensions/precache/plugin-cache-key.ts} +7 -8
  147. package/src/lib/{precaching/PrecacheFallbackPlugin.ts → extensions/precache/plugin-fallback.ts} +19 -8
  148. package/src/{utils/PrecacheInstallReportPlugin.ts → lib/extensions/precache/plugin-install-report.ts} +5 -5
  149. package/src/lib/extensions/precache/route.ts +72 -0
  150. package/src/lib/{strategies/PrecacheStrategy.ts → extensions/precache/strategy.ts} +12 -12
  151. package/src/lib/extensions/runtime-cache.ts +126 -0
  152. package/src/lib/functions/handlers.ts +149 -0
  153. package/src/lib/functions/router.ts +314 -0
  154. package/src/{navigationPreload.ts → lib/navigation-preload.ts} +1 -1
  155. package/src/lib/{rangeRequests → range-requests}/RangeRequestsPlugin.ts +3 -3
  156. package/src/lib/{rangeRequests → range-requests}/createPartialResponse.ts +3 -3
  157. package/src/lib/range-requests/index.ts +2 -0
  158. package/src/lib/{rangeRequests → range-requests}/utils/calculateEffectiveBoundaries.ts +2 -2
  159. package/src/lib/{rangeRequests → range-requests}/utils/parseRangeHeader.ts +2 -2
  160. package/src/lib/route.ts +234 -0
  161. package/src/lib/serwist.ts +443 -0
  162. package/src/lib/strategies/CacheFirst.ts +3 -3
  163. package/src/lib/strategies/CacheOnly.ts +3 -3
  164. package/src/lib/strategies/NetworkFirst.ts +4 -4
  165. package/src/lib/strategies/NetworkOnly.ts +4 -4
  166. package/src/lib/strategies/StaleWhileRevalidate.ts +4 -4
  167. package/src/lib/strategies/Strategy.ts +7 -7
  168. package/src/lib/strategies/StrategyHandler.ts +18 -18
  169. package/src/lib/strategies/index.ts +10 -0
  170. package/src/lib/strategies/plugins/cacheOkAndOpaquePlugin.ts +2 -2
  171. package/src/lib/strategies/utils/messages.ts +2 -2
  172. package/src/{types.ts → lib/types.ts} +17 -70
  173. package/src/lib/utils.ts +137 -0
  174. package/src/models/messages/messageGenerator.ts +1 -1
  175. package/src/models/messages/messages.ts +3 -3
  176. package/src/utils/SerwistError.ts +3 -3
  177. package/src/utils/assert.ts +1 -1
  178. package/src/utils/createCacheKey.ts +1 -2
  179. package/src/utils/executeQuotaErrorCallbacks.ts +1 -1
  180. package/src/utils/generateURLVariations.ts +1 -1
  181. package/src/utils/logger.ts +1 -1
  182. package/src/utils/normalizeHandler.ts +1 -1
  183. package/src/utils/parseRoute.ts +4 -5
  184. package/src/utils/pluginUtils.ts +2 -2
  185. package/dist/NavigationRoute.d.ts +0 -56
  186. package/dist/NavigationRoute.d.ts.map +0 -1
  187. package/dist/PrecacheRoute.d.ts +0 -16
  188. package/dist/PrecacheRoute.d.ts.map +0 -1
  189. package/dist/RegExpRoute.d.ts +0 -24
  190. package/dist/RegExpRoute.d.ts.map +0 -1
  191. package/dist/Route.d.ts +0 -33
  192. package/dist/Route.d.ts.map +0 -1
  193. package/dist/Serwist.d.ts.map +0 -1
  194. package/dist/cacheNames.d.ts.map +0 -1
  195. package/dist/chunks/printInstallDetails.js +0 -1601
  196. package/dist/chunks/resultingClientExists.js +0 -32
  197. package/dist/constants.d.ts.map +0 -1
  198. package/dist/copyResponse.d.ts.map +0 -1
  199. package/dist/disableDevLogs.d.ts +0 -7
  200. package/dist/disableDevLogs.d.ts.map +0 -1
  201. package/dist/index.legacy.d.ts +0 -28
  202. package/dist/index.legacy.d.ts.map +0 -1
  203. package/dist/index.legacy.js +0 -790
  204. package/dist/legacy/PrecacheController.d.ts.map +0 -1
  205. package/dist/legacy/PrecacheFallbackPlugin.d.ts +0 -61
  206. package/dist/legacy/PrecacheFallbackPlugin.d.ts.map +0 -1
  207. package/dist/legacy/PrecacheRoute.d.ts +0 -19
  208. package/dist/legacy/PrecacheRoute.d.ts.map +0 -1
  209. package/dist/legacy/Router.d.ts +0 -151
  210. package/dist/legacy/Router.d.ts.map +0 -1
  211. package/dist/legacy/addPlugins.d.ts +0 -9
  212. package/dist/legacy/addPlugins.d.ts.map +0 -1
  213. package/dist/legacy/addRoute.d.ts +0 -14
  214. package/dist/legacy/addRoute.d.ts.map +0 -1
  215. package/dist/legacy/constants.d.ts.map +0 -1
  216. package/dist/legacy/createHandlerBoundToURL.d.ts +0 -17
  217. package/dist/legacy/createHandlerBoundToURL.d.ts.map +0 -1
  218. package/dist/legacy/fallbacks.d.ts +0 -59
  219. package/dist/legacy/fallbacks.d.ts.map +0 -1
  220. package/dist/legacy/getCacheKeyForURL.d.ts +0 -20
  221. package/dist/legacy/getCacheKeyForURL.d.ts.map +0 -1
  222. package/dist/legacy/handlePrecaching.d.ts +0 -54
  223. package/dist/legacy/handlePrecaching.d.ts.map +0 -1
  224. package/dist/legacy/initializeGoogleAnalytics.d.ts +0 -38
  225. package/dist/legacy/initializeGoogleAnalytics.d.ts.map +0 -1
  226. package/dist/legacy/installSerwist.d.ts +0 -81
  227. package/dist/legacy/installSerwist.d.ts.map +0 -1
  228. package/dist/legacy/matchPrecache.d.ts +0 -15
  229. package/dist/legacy/matchPrecache.d.ts.map +0 -1
  230. package/dist/legacy/precache.d.ts +0 -20
  231. package/dist/legacy/precache.d.ts.map +0 -1
  232. package/dist/legacy/precacheAndRoute.d.ts +0 -14
  233. package/dist/legacy/precacheAndRoute.d.ts.map +0 -1
  234. package/dist/legacy/registerRoute.d.ts +0 -16
  235. package/dist/legacy/registerRoute.d.ts.map +0 -1
  236. package/dist/legacy/registerRuntimeCaching.d.ts +0 -11
  237. package/dist/legacy/registerRuntimeCaching.d.ts.map +0 -1
  238. package/dist/legacy/setCatchHandler.d.ts +0 -10
  239. package/dist/legacy/setCatchHandler.d.ts.map +0 -1
  240. package/dist/legacy/setDefaultHandler.d.ts +0 -13
  241. package/dist/legacy/setDefaultHandler.d.ts.map +0 -1
  242. package/dist/legacy/singletonPrecacheController.d.ts +0 -34
  243. package/dist/legacy/singletonPrecacheController.d.ts.map +0 -1
  244. package/dist/legacy/singletonRouter.d.ts +0 -41
  245. package/dist/legacy/singletonRouter.d.ts.map +0 -1
  246. package/dist/legacy/unregisterRoute.d.ts +0 -9
  247. package/dist/legacy/unregisterRoute.d.ts.map +0 -1
  248. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts +0 -16
  249. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  250. package/dist/legacy/utils/getCacheKeyForURL.d.ts +0 -14
  251. package/dist/legacy/utils/getCacheKeyForURL.d.ts.map +0 -1
  252. package/dist/lib/backgroundSync/BackgroundSyncPlugin.d.ts.map +0 -1
  253. package/dist/lib/backgroundSync/BackgroundSyncQueue.d.ts.map +0 -1
  254. package/dist/lib/backgroundSync/BackgroundSyncQueueDb.d.ts.map +0 -1
  255. package/dist/lib/backgroundSync/BackgroundSyncQueueStore.d.ts.map +0 -1
  256. package/dist/lib/backgroundSync/StorableRequest.d.ts.map +0 -1
  257. package/dist/lib/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +0 -1
  258. package/dist/lib/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +0 -1
  259. package/dist/lib/broadcastUpdate/constants.d.ts.map +0 -1
  260. package/dist/lib/broadcastUpdate/responsesAreSame.d.ts.map +0 -1
  261. package/dist/lib/broadcastUpdate/types.d.ts.map +0 -1
  262. package/dist/lib/cacheableResponse/CacheableResponse.d.ts.map +0 -1
  263. package/dist/lib/cacheableResponse/CacheableResponsePlugin.d.ts.map +0 -1
  264. package/dist/lib/googleAnalytics/constants.d.ts +0 -10
  265. package/dist/lib/googleAnalytics/constants.d.ts.map +0 -1
  266. package/dist/lib/googleAnalytics/initializeGoogleAnalytics.d.ts +0 -30
  267. package/dist/lib/googleAnalytics/initializeGoogleAnalytics.d.ts.map +0 -1
  268. package/dist/lib/precaching/PrecacheFallbackPlugin.d.ts.map +0 -1
  269. package/dist/lib/rangeRequests/RangeRequestsPlugin.d.ts.map +0 -1
  270. package/dist/lib/rangeRequests/createPartialResponse.d.ts.map +0 -1
  271. package/dist/lib/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +0 -1
  272. package/dist/lib/rangeRequests/utils/parseRangeHeader.d.ts.map +0 -1
  273. package/dist/lib/strategies/PrecacheStrategy.d.ts.map +0 -1
  274. package/dist/navigationPreload.d.ts.map +0 -1
  275. package/dist/registerQuotaErrorCallback.d.ts +0 -8
  276. package/dist/registerQuotaErrorCallback.d.ts.map +0 -1
  277. package/dist/setCacheNameDetails.d.ts +0 -9
  278. package/dist/setCacheNameDetails.d.ts.map +0 -1
  279. package/dist/types.d.ts.map +0 -1
  280. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +0 -16
  281. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +0 -1
  282. package/dist/utils/PrecacheInstallReportPlugin.d.ts +0 -14
  283. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +0 -1
  284. package/dist/utils/parsePrecacheOptions.d.ts +0 -26
  285. package/dist/utils/parsePrecacheOptions.d.ts.map +0 -1
  286. package/src/NavigationRoute.ts +0 -118
  287. package/src/PrecacheRoute.ts +0 -45
  288. package/src/RegExpRoute.ts +0 -74
  289. package/src/Route.ts +0 -67
  290. package/src/Serwist.ts +0 -867
  291. package/src/copyResponse.ts +0 -58
  292. package/src/disableDevLogs.ts +0 -10
  293. package/src/index.legacy.ts +0 -62
  294. package/src/legacy/PrecacheController.ts +0 -337
  295. package/src/legacy/PrecacheFallbackPlugin.ts +0 -92
  296. package/src/legacy/PrecacheRoute.ts +0 -48
  297. package/src/legacy/Router.ts +0 -484
  298. package/src/legacy/addPlugins.ts +0 -21
  299. package/src/legacy/addRoute.ts +0 -27
  300. package/src/legacy/createHandlerBoundToURL.ts +0 -30
  301. package/src/legacy/fallbacks.ts +0 -94
  302. package/src/legacy/getCacheKeyForURL.ts +0 -32
  303. package/src/legacy/handlePrecaching.ts +0 -86
  304. package/src/legacy/initializeGoogleAnalytics.ts +0 -218
  305. package/src/legacy/installSerwist.ts +0 -170
  306. package/src/legacy/matchPrecache.ts +0 -27
  307. package/src/legacy/precache.ts +0 -33
  308. package/src/legacy/precacheAndRoute.ts +0 -27
  309. package/src/legacy/registerRoute.ts +0 -28
  310. package/src/legacy/registerRuntimeCaching.ts +0 -17
  311. package/src/legacy/setCatchHandler.ts +0 -21
  312. package/src/legacy/setDefaultHandler.ts +0 -24
  313. package/src/legacy/singletonPrecacheController.ts +0 -53
  314. package/src/legacy/singletonRouter.ts +0 -70
  315. package/src/legacy/unregisterRoute.ts +0 -13
  316. package/src/legacy/utils/getCacheKeyForURL.ts +0 -36
  317. package/src/lib/googleAnalytics/constants.ts +0 -22
  318. package/src/registerQuotaErrorCallback.ts +0 -34
  319. package/src/setCacheNameDetails.ts +0 -53
  320. package/src/utils/PrecacheCacheKeyPlugin.ts +0 -33
  321. package/src/utils/parsePrecacheOptions.ts +0 -47
  322. /package/dist/lib/{backgroundSync → background-sync}/BackgroundSyncQueue.d.ts +0 -0
  323. /package/dist/lib/{backgroundSync → background-sync}/BackgroundSyncQueueDb.d.ts +0 -0
  324. /package/dist/lib/{backgroundSync → background-sync}/BackgroundSyncQueueStore.d.ts +0 -0
  325. /package/dist/lib/{broadcastUpdate → broadcast-update}/constants.d.ts +0 -0
  326. /package/dist/lib/{broadcastUpdate → broadcast-update}/responsesAreSame.d.ts +0 -0
  327. /package/dist/lib/{cacheableResponse → cacheable-response}/CacheableResponse.d.ts +0 -0
  328. /package/dist/{legacy → lib/extensions/google-analytics}/constants.d.ts +0 -0
  329. /package/dist/lib/{rangeRequests → range-requests}/createPartialResponse.d.ts +0 -0
  330. /package/dist/lib/{rangeRequests → range-requests}/utils/calculateEffectiveBoundaries.d.ts +0 -0
  331. /package/dist/lib/{rangeRequests → range-requests}/utils/parseRangeHeader.d.ts +0 -0
  332. /package/src/lib/{backgroundSync → background-sync}/BackgroundSyncQueueDb.ts +0 -0
  333. /package/src/lib/{broadcastUpdate → broadcast-update}/constants.ts +0 -0
  334. /package/src/{constants.ts → lib/constants.ts} +0 -0
  335. /package/src/{legacy → lib/extensions/google-analytics}/constants.ts +0 -0
package/src/Serwist.ts DELETED
@@ -1,867 +0,0 @@
1
- import { parallel } from "@serwist/utils";
2
- import { NavigationRoute } from "./NavigationRoute.js";
3
- import { PrecacheRoute } from "./PrecacheRoute.js";
4
- import type { Route } from "./Route.js";
5
- import { type HTTPMethod, defaultMethod } from "./constants.js";
6
- import { disableDevLogs as disableDevLogsImpl } from "./disableDevLogs.js";
7
- import { type GoogleAnalyticsInitializeOptions, initializeGoogleAnalytics } from "./lib/googleAnalytics/initializeGoogleAnalytics.js";
8
- import { type PrecacheFallbackEntry, PrecacheFallbackPlugin } from "./lib/precaching/PrecacheFallbackPlugin.js";
9
- import { PrecacheStrategy } from "./lib/strategies/PrecacheStrategy.js";
10
- import { Strategy } from "./lib/strategies/Strategy.js";
11
- import { enableNavigationPreload } from "./navigationPreload.js";
12
- import { setCacheNameDetails } from "./setCacheNameDetails.js";
13
- import type {
14
- PrecacheOptions,
15
- RouteHandler,
16
- RouteHandlerCallback,
17
- RouteHandlerCallbackOptions,
18
- RouteHandlerObject,
19
- RouteMatchCallback,
20
- RouteMatchCallbackOptions,
21
- } from "./types.js";
22
- import type { RuntimeCaching } from "./types.js";
23
- import type { CleanupResult, InstallResult, PrecacheEntry } from "./types.js";
24
- import { PrecacheInstallReportPlugin } from "./utils/PrecacheInstallReportPlugin.js";
25
- import { SerwistError } from "./utils/SerwistError.js";
26
- import { assert } from "./utils/assert.js";
27
- import { cleanupOutdatedCaches as cleanupOutdatedCachesImpl } from "./utils/cleanupOutdatedCaches.js";
28
- import { clientsClaim as clientsClaimImpl } from "./utils/clientsClaim.js";
29
- import { createCacheKey } from "./utils/createCacheKey.js";
30
- import { getFriendlyURL } from "./utils/getFriendlyURL.js";
31
- import { logger } from "./utils/logger.js";
32
- import { normalizeHandler } from "./utils/normalizeHandler.js";
33
- import { parseRoute } from "./utils/parseRoute.js";
34
- import { printCleanupDetails } from "./utils/printCleanupDetails.js";
35
- import { printInstallDetails } from "./utils/printInstallDetails.js";
36
- import { waitUntil } from "./utils/waitUntil.js";
37
- import { parsePrecacheOptions } from "./utils/parsePrecacheOptions.js";
38
-
39
- declare const self: ServiceWorkerGlobalScope;
40
-
41
- export interface FallbackEntry extends PrecacheFallbackEntry {}
42
-
43
- export interface FallbacksOptions {
44
- /**
45
- * A list of fallback entries.
46
- */
47
- entries: FallbackEntry[];
48
- }
49
-
50
- export interface SerwistOptions {
51
- /**
52
- * A list of URLs that should be cached.
53
- */
54
- precacheEntries?: (PrecacheEntry | string)[];
55
- /**
56
- * Options to customize how Serwist precaches the URLs in the precache list.
57
- */
58
- precacheOptions?: PrecacheOptions;
59
- /**
60
- * Forces the waiting service worker to become the active one.
61
- *
62
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting
63
- */
64
- skipWaiting?: boolean;
65
- /**
66
- * Imports external scripts. They are executed in the order they
67
- * are passed.
68
- *
69
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts
70
- */
71
- importScripts?: string[];
72
- /**
73
- * Enables navigation preloading if it is supported.
74
- *
75
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/navigationPreload
76
- */
77
- navigationPreload?: boolean;
78
- /**
79
- * Modifies the prefix of the default cache names used by Serwist packages.
80
- */
81
- cacheId?: string | undefined;
82
- /**
83
- * Claims any currently available clients once the service worker
84
- * becomes active. This is normally used in conjunction with `skipWaiting()`.
85
- *
86
- * @default false
87
- */
88
- clientsClaim?: boolean;
89
- /**
90
- * A list of caching strategies.
91
- */
92
- runtimeCaching?: RuntimeCaching[];
93
- /**
94
- * Your configuration for {@linkcode initializeGoogleAnalytics}. This plugin is
95
- * only initialized when this option is not `undefined` or `false`.
96
- */
97
- offlineAnalyticsConfig?: Omit<GoogleAnalyticsInitializeOptions, "serwist"> | boolean;
98
- /**
99
- * Disables Serwist's logging in development mode.
100
- *
101
- * @default false
102
- */
103
- disableDevLogs?: boolean;
104
- /**
105
- * Precaches routes so that they can be used as a fallback when
106
- * a {@linkcode Strategy} fails to generate a response.
107
- *
108
- * Note: This option mutates `runtimeCaching`. It also expects the URLs
109
- * defined in `entries` to have been precached beforehand.
110
- */
111
- fallbacks?: FallbacksOptions;
112
- }
113
-
114
- type RequestArgs = string | [string, RequestInit?];
115
-
116
- interface CacheURLsMessageData {
117
- type: string;
118
- payload: {
119
- urlsToCache: RequestArgs[];
120
- };
121
- }
122
-
123
- /**
124
- * A class that helps bootstrap the service worker.
125
- *
126
- * @see https://serwist.pages.dev/docs/serwist/core/serwist
127
- */
128
- export class Serwist {
129
- private readonly _urlsToCacheKeys: Map<string, string> = new Map();
130
- private readonly _urlsToCacheModes: Map<string, "reload" | "default" | "no-store" | "no-cache" | "force-cache" | "only-if-cached"> = new Map();
131
- private readonly _cacheKeysToIntegrities: Map<string, string> = new Map();
132
- private _concurrentPrecaching: number;
133
- private readonly _precacheStrategy: Strategy;
134
- private readonly _routes: Map<HTTPMethod, Route[]>;
135
- private readonly _defaultHandlerMap: Map<HTTPMethod, RouteHandlerObject>;
136
- private _catchHandler?: RouteHandlerObject;
137
-
138
- constructor({
139
- precacheEntries,
140
- precacheOptions,
141
- skipWaiting = false,
142
- importScripts,
143
- navigationPreload = false,
144
- cacheId,
145
- clientsClaim = false,
146
- runtimeCaching,
147
- offlineAnalyticsConfig,
148
- disableDevLogs = false,
149
- fallbacks,
150
- }: SerwistOptions = {}) {
151
- const { precacheStrategyOptions, precacheRouteOptions, precacheMiscOptions } = parsePrecacheOptions(this, precacheOptions);
152
-
153
- this._concurrentPrecaching = precacheMiscOptions.concurrency;
154
- this._precacheStrategy = new PrecacheStrategy(precacheStrategyOptions);
155
- this._routes = new Map();
156
- this._defaultHandlerMap = new Map();
157
-
158
- this.handleInstall = this.handleInstall.bind(this);
159
- this.handleActivate = this.handleActivate.bind(this);
160
- this.handleFetch = this.handleFetch.bind(this);
161
- this.handleCache = this.handleCache.bind(this);
162
-
163
- if (!!importScripts && importScripts.length > 0) self.importScripts(...importScripts);
164
-
165
- if (navigationPreload) enableNavigationPreload();
166
-
167
- if (cacheId !== undefined) {
168
- setCacheNameDetails({
169
- prefix: cacheId,
170
- });
171
- }
172
-
173
- if (skipWaiting) {
174
- self.skipWaiting();
175
- } else {
176
- self.addEventListener("message", (event) => {
177
- if (event.data && event.data.type === "SKIP_WAITING") {
178
- self.skipWaiting();
179
- }
180
- });
181
- }
182
-
183
- if (clientsClaim) clientsClaimImpl();
184
-
185
- if (!!precacheEntries && precacheEntries.length > 0) {
186
- this.addToPrecacheList(precacheEntries);
187
- }
188
-
189
- if (precacheMiscOptions.cleanupOutdatedCaches) {
190
- cleanupOutdatedCachesImpl(precacheStrategyOptions.cacheName);
191
- }
192
-
193
- this.registerRoute(new PrecacheRoute(this, precacheRouteOptions));
194
-
195
- if (precacheMiscOptions.navigateFallback) {
196
- this.registerRoute(
197
- new NavigationRoute(this.createHandlerBoundToUrl(precacheMiscOptions.navigateFallback), {
198
- allowlist: precacheMiscOptions.navigateFallbackAllowlist,
199
- denylist: precacheMiscOptions.navigateFallbackDenylist,
200
- }),
201
- );
202
- }
203
-
204
- if (offlineAnalyticsConfig !== undefined) {
205
- if (typeof offlineAnalyticsConfig === "boolean") {
206
- offlineAnalyticsConfig && initializeGoogleAnalytics({ serwist: this });
207
- } else {
208
- initializeGoogleAnalytics({
209
- ...offlineAnalyticsConfig,
210
- serwist: this,
211
- });
212
- }
213
- }
214
-
215
- if (runtimeCaching !== undefined) {
216
- if (fallbacks !== undefined) {
217
- const fallbackPlugin = new PrecacheFallbackPlugin({
218
- fallbackUrls: fallbacks.entries,
219
- serwist: this,
220
- });
221
-
222
- runtimeCaching.forEach((cacheEntry) => {
223
- if (
224
- cacheEntry.handler instanceof Strategy &&
225
- // This also filters entries with `PrecacheFallbackPlugin` as it also has `handlerDidError`.
226
- !cacheEntry.handler.plugins.some((plugin) => "handlerDidError" in plugin)
227
- ) {
228
- cacheEntry.handler.plugins.push(fallbackPlugin);
229
- }
230
- });
231
- }
232
- for (const entry of runtimeCaching) {
233
- this.registerCapture(entry.matcher, entry.handler, entry.method);
234
- }
235
- }
236
-
237
- if (disableDevLogs) disableDevLogsImpl();
238
- }
239
-
240
- /**
241
- * The strategy used to precache assets and respond to `fetch` events.
242
- */
243
- get precacheStrategy(): Strategy {
244
- return this._precacheStrategy;
245
- }
246
- /**
247
- * A `Map` of HTTP method name (`'GET'`, etc.) to an array of all corresponding registered {@linkcode Route}
248
- * instances.
249
- */
250
- get routes(): Map<HTTPMethod, Route[]> {
251
- return this._routes;
252
- }
253
-
254
- /**
255
- * Adds Serwist's event listeners for you. Before calling it, add your own listeners should you need to.
256
- */
257
- addEventListeners() {
258
- self.addEventListener("install", this.handleInstall);
259
- self.addEventListener("activate", this.handleActivate);
260
- self.addEventListener("fetch", this.handleFetch);
261
- self.addEventListener("message", this.handleCache);
262
- }
263
-
264
- /**
265
- * Adds items to the precache list, removing duplicates and ensuring the information is valid.
266
- *
267
- * @param entries Array of entries to precache.
268
- */
269
- addToPrecacheList(entries: (PrecacheEntry | string)[]): void {
270
- if (process.env.NODE_ENV !== "production") {
271
- assert!.isArray(entries, {
272
- moduleName: "serwist",
273
- className: "Serwist",
274
- funcName: "addToCacheList",
275
- paramName: "entries",
276
- });
277
- }
278
-
279
- const urlsToWarnAbout: string[] = [];
280
- for (const entry of entries) {
281
- // See https://github.com/GoogleChrome/workbox/issues/2259
282
- if (typeof entry === "string") {
283
- urlsToWarnAbout.push(entry);
284
- } else if (entry && !entry.integrity && entry.revision === undefined) {
285
- urlsToWarnAbout.push(entry.url);
286
- }
287
-
288
- const { cacheKey, url } = createCacheKey(entry);
289
- const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default";
290
-
291
- if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
292
- throw new SerwistError("add-to-cache-list-conflicting-entries", {
293
- firstEntry: this._urlsToCacheKeys.get(url),
294
- secondEntry: cacheKey,
295
- });
296
- }
297
-
298
- if (typeof entry !== "string" && entry.integrity) {
299
- if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
300
- throw new SerwistError("add-to-cache-list-conflicting-integrities", {
301
- url,
302
- });
303
- }
304
- this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
305
- }
306
-
307
- this._urlsToCacheKeys.set(url, cacheKey);
308
- this._urlsToCacheModes.set(url, cacheMode);
309
-
310
- if (urlsToWarnAbout.length > 0) {
311
- const warningMessage = `Serwist is precaching URLs without revision info: ${urlsToWarnAbout.join(
312
- ", ",
313
- )}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;
314
- if (process.env.NODE_ENV === "production") {
315
- // Use console directly to display this warning without bloating
316
- // bundle sizes by pulling in all of the logger codebase in prod.
317
- console.warn(warningMessage);
318
- } else {
319
- logger.warn(warningMessage);
320
- }
321
- }
322
- }
323
- }
324
-
325
- /**
326
- * Precaches new and updated assets. Call this method from the service worker's
327
- * `install` event.
328
- *
329
- * Note: this method calls `event.waitUntil()` for you, so you do not need
330
- * to call it yourself in your event handlers.
331
- *
332
- * @param event
333
- * @returns
334
- */
335
- handleInstall(event: ExtendableEvent): Promise<InstallResult> {
336
- return waitUntil<InstallResult>(event, async () => {
337
- const installReportPlugin = new PrecacheInstallReportPlugin();
338
- this.precacheStrategy.plugins.push(installReportPlugin);
339
-
340
- await parallel(this._concurrentPrecaching, Array.from(this._urlsToCacheKeys.entries()), async ([url, cacheKey]): Promise<void> => {
341
- const integrity = this._cacheKeysToIntegrities.get(cacheKey);
342
- const cacheMode = this._urlsToCacheModes.get(url);
343
-
344
- const request = new Request(url, {
345
- integrity,
346
- cache: cacheMode,
347
- credentials: "same-origin",
348
- });
349
-
350
- await Promise.all(
351
- this.precacheStrategy.handleAll({
352
- event,
353
- request,
354
- url: new URL(request.url),
355
- params: { cacheKey },
356
- }),
357
- );
358
- });
359
-
360
- const { updatedURLs, notUpdatedURLs } = installReportPlugin;
361
-
362
- if (process.env.NODE_ENV !== "production") {
363
- printInstallDetails(updatedURLs, notUpdatedURLs);
364
- }
365
-
366
- return { updatedURLs, notUpdatedURLs };
367
- });
368
- }
369
-
370
- /**
371
- * Deletes assets that are no longer present in the current precache manifest.
372
- * Call this method from the service worker's `activate` event.
373
- *
374
- * Note: this method calls `event.waitUntil()` for you, so you do not need
375
- * to call it yourself in your event handlers.
376
- *
377
- * @param event
378
- * @returns
379
- */
380
- handleActivate(event: ExtendableEvent): Promise<CleanupResult> {
381
- return waitUntil<CleanupResult>(event, async () => {
382
- const cache = await self.caches.open(this.precacheStrategy.cacheName);
383
- const currentlyCachedRequests = await cache.keys();
384
- const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
385
-
386
- const deletedCacheRequests: string[] = [];
387
-
388
- for (const request of currentlyCachedRequests) {
389
- if (!expectedCacheKeys.has(request.url)) {
390
- await cache.delete(request);
391
- deletedCacheRequests.push(request.url);
392
- }
393
- }
394
-
395
- if (process.env.NODE_ENV !== "production") {
396
- printCleanupDetails(deletedCacheRequests);
397
- }
398
-
399
- return { deletedCacheRequests };
400
- });
401
- }
402
-
403
- /**
404
- * Gets a `Response` from an appropriate `Route`'s handler. Call this method
405
- * from the service worker's `fetch` event.
406
- * @param event
407
- */
408
- handleFetch(event: FetchEvent) {
409
- const { request } = event;
410
- const responsePromise = this.handleRequest({ request, event });
411
- if (responsePromise) {
412
- event.respondWith(responsePromise);
413
- }
414
- }
415
-
416
- /**
417
- * Caches new URLs on demand. Call this method from the service worker's
418
- * `message` event. To trigger the handler, send a message of type `"CACHE_URLS"`
419
- * alongside a list of URLs that should be cached as `urlsToCache`.
420
- * @param event
421
- */
422
- handleCache(event: ExtendableMessageEvent) {
423
- if (event.data && event.data.type === "CACHE_URLS") {
424
- const { payload }: CacheURLsMessageData = event.data;
425
-
426
- if (process.env.NODE_ENV !== "production") {
427
- logger.debug("Caching URLs from the window", payload.urlsToCache);
428
- }
429
-
430
- const requestPromises = Promise.all(
431
- payload.urlsToCache.map((entry: string | [string, RequestInit?]) => {
432
- let request: Request;
433
- if (typeof entry === "string") {
434
- request = new Request(entry);
435
- } else {
436
- request = new Request(...entry);
437
- }
438
- return this.handleRequest({ request, event });
439
- }),
440
- );
441
-
442
- event.waitUntil(requestPromises);
443
-
444
- // If a MessageChannel was used, reply to the message on success.
445
- if (event.ports?.[0]) {
446
- void requestPromises.then(() => event.ports[0].postMessage(true));
447
- }
448
- }
449
- }
450
-
451
- /**
452
- * Define a default handler that's called when no routes explicitly
453
- * match the incoming request.
454
- *
455
- * Each HTTP method (`'GET'`, `'POST'`, etc.) gets its own default handler.
456
- *
457
- * Without a default handler, unmatched requests will go against the
458
- * network as if there were no service worker present.
459
- *
460
- * @param handler A callback function that returns a `Promise` resulting in a `Response`.
461
- * @param method The HTTP method to associate with this default handler. Each method
462
- * has its own default. Defaults to `'GET'`.
463
- */
464
- setDefaultHandler(handler: RouteHandler, method: HTTPMethod = defaultMethod): void {
465
- this._defaultHandlerMap.set(method, normalizeHandler(handler));
466
- }
467
-
468
- /**
469
- * If a {@linkcode Route} throws an error while handling a request, this handler
470
- * will be called and given a chance to provide a response.
471
- *
472
- * @param handler A callback function that returns a `Promise` resulting
473
- * in a `Response`.
474
- */
475
- setCatchHandler(handler: RouteHandler): void {
476
- this._catchHandler = normalizeHandler(handler);
477
- }
478
-
479
- /**
480
- * Registers a `RegExp`, string, or function with a caching
481
- * strategy to the router.
482
- *
483
- * @param capture If the capture param is a {@linkcode Route} object, all other arguments will be ignored.
484
- * @param handler A callback function that returns a `Promise` resulting in a `Response`.
485
- * This parameter is required if `capture` is not a {@linkcode Route} object.
486
- * @param method The HTTP method to match the route against. Defaults to `'GET'`.
487
- * @returns The generated {@linkcode Route} object.
488
- */
489
- registerCapture<T extends RegExp | string | RouteMatchCallback | Route>(
490
- capture: T,
491
- handler?: T extends Route ? never : RouteHandler,
492
- method?: T extends Route ? never : HTTPMethod,
493
- ): Route {
494
- const route = parseRoute(capture, handler, method);
495
- this.registerRoute(route);
496
- return route;
497
- }
498
-
499
- /**
500
- * Registers a {@linkcode Route} with the router.
501
- *
502
- * @param route The {@linkcode Route} to register.
503
- */
504
- registerRoute(route: Route): void {
505
- if (process.env.NODE_ENV !== "production") {
506
- assert!.isType(route, "object", {
507
- moduleName: "serwist",
508
- className: "Serwist",
509
- funcName: "registerRoute",
510
- paramName: "route",
511
- });
512
-
513
- assert!.hasMethod(route, "match", {
514
- moduleName: "serwist",
515
- className: "Serwist",
516
- funcName: "registerRoute",
517
- paramName: "route",
518
- });
519
-
520
- assert!.isType(route.handler, "object", {
521
- moduleName: "serwist",
522
- className: "Serwist",
523
- funcName: "registerRoute",
524
- paramName: "route",
525
- });
526
-
527
- assert!.hasMethod(route.handler, "handle", {
528
- moduleName: "serwist",
529
- className: "Serwist",
530
- funcName: "registerRoute",
531
- paramName: "route.handler",
532
- });
533
-
534
- assert!.isType(route.method, "string", {
535
- moduleName: "serwist",
536
- className: "Serwist",
537
- funcName: "registerRoute",
538
- paramName: "route.method",
539
- });
540
- }
541
-
542
- if (!this._routes.has(route.method)) {
543
- this._routes.set(route.method, []);
544
- }
545
-
546
- // Give precedence to all of the earlier routes by adding this additional
547
- // route to the end of the array.
548
- this._routes.get(route.method)!.push(route);
549
- }
550
-
551
- /**
552
- * Unregisters a route from the router.
553
- *
554
- * @param route The {@linkcode Route} object to unregister.
555
- */
556
- unregisterRoute(route: Route): void {
557
- if (!this._routes.has(route.method)) {
558
- throw new SerwistError("unregister-route-but-not-found-with-method", {
559
- method: route.method,
560
- });
561
- }
562
-
563
- const routeIndex = this._routes.get(route.method)!.indexOf(route);
564
- if (routeIndex > -1) {
565
- this._routes.get(route.method)!.splice(routeIndex, 1);
566
- } else {
567
- throw new SerwistError("unregister-route-route-not-registered");
568
- }
569
- }
570
-
571
- /**
572
- * Returns a mapping of a precached URL to the corresponding cache key, taking
573
- * into account the revision information for the URL.
574
- *
575
- * @returns A URL to cache key mapping.
576
- */
577
- getUrlsToPrecacheKeys(): Map<string, string> {
578
- return this._urlsToCacheKeys;
579
- }
580
-
581
- /**
582
- * Returns a list of all the URLs that have been precached by the current
583
- * service worker.
584
- *
585
- * @returns The precached URLs.
586
- */
587
- getPrecachedUrls(): string[] {
588
- return [...this._urlsToCacheKeys.keys()];
589
- }
590
-
591
- /**
592
- * Returns the cache key used for storing a given URL. If that URL is
593
- * unversioned, like "/index.html", then the cache key will be the original
594
- * URL with a search parameter appended to it.
595
- *
596
- * @param url A URL whose cache key you want to look up.
597
- * @returns The versioned URL that corresponds to a cache key
598
- * for the original URL, or undefined if that URL isn't precached.
599
- */
600
- getPrecacheKeyForUrl(url: string): string | undefined {
601
- const urlObject = new URL(url, location.href);
602
- return this._urlsToCacheKeys.get(urlObject.href);
603
- }
604
-
605
- /**
606
- * @param url A cache key whose SRI you want to look up.
607
- * @returns The subresource integrity associated with the cache key,
608
- * or undefined if it's not set.
609
- */
610
- getIntegrityForPrecacheKey(cacheKey: string): string | undefined {
611
- return this._cacheKeysToIntegrities.get(cacheKey);
612
- }
613
-
614
- /**
615
- * This acts as a drop-in replacement for
616
- * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
617
- * with the following differences:
618
- *
619
- * - It knows what the name of the precache is, and only checks in that cache.
620
- * - It allows you to pass in an "original" URL without versioning parameters,
621
- * and it will automatically look up the correct cache key for the currently
622
- * active revision of that URL.
623
- *
624
- * E.g., `matchPrecache('index.html')` will find the correct precached
625
- * response for the currently active service worker, even if the actual cache
626
- * key is `'/index.html?__WB_REVISION__=1234abcd'`.
627
- *
628
- * @param request The key (without revisioning parameters)
629
- * to look up in the precache.
630
- * @returns
631
- */
632
- async matchPrecache(request: string | Request): Promise<Response | undefined> {
633
- const url = request instanceof Request ? request.url : request;
634
- const cacheKey = this.getPrecacheKeyForUrl(url);
635
- if (cacheKey) {
636
- const cache = await self.caches.open(this.precacheStrategy.cacheName);
637
- return cache.match(cacheKey);
638
- }
639
- return undefined;
640
- }
641
-
642
- /**
643
- * Returns a function that looks up `url` in the precache (taking into
644
- * account revision information), and returns the corresponding `Response`.
645
- *
646
- * @param url The precached URL which will be used to lookup the response.
647
- * @return
648
- */
649
- createHandlerBoundToUrl(url: string): RouteHandlerCallback {
650
- const cacheKey = this.getPrecacheKeyForUrl(url);
651
- if (!cacheKey) {
652
- throw new SerwistError("non-precached-url", { url });
653
- }
654
- return (options) => {
655
- options.request = new Request(url);
656
- options.params = { cacheKey, ...options.params };
657
-
658
- return this.precacheStrategy.handle(options);
659
- };
660
- }
661
-
662
- /**
663
- * Applies the routing rules to a `FetchEvent` object to get a response from an
664
- * appropriate route.
665
- *
666
- * @param options
667
- * @returns A promise is returned if a registered route can handle the request.
668
- * If there is no matching route and there's no default handler, `undefined`
669
- * is returned.
670
- */
671
- handleRequest({
672
- request,
673
- event,
674
- }: {
675
- /**
676
- * The request to handle.
677
- */
678
- request: Request;
679
- /**
680
- * The event that triggered the request.
681
- */
682
- event: ExtendableEvent;
683
- }): Promise<Response> | undefined {
684
- if (process.env.NODE_ENV !== "production") {
685
- assert!.isInstance(request, Request, {
686
- moduleName: "serwist",
687
- className: "Serwist",
688
- funcName: "handleRequest",
689
- paramName: "options.request",
690
- });
691
- }
692
-
693
- const url = new URL(request.url, location.href);
694
- if (!url.protocol.startsWith("http")) {
695
- if (process.env.NODE_ENV !== "production") {
696
- logger.debug("Router only supports URLs that start with 'http'.");
697
- }
698
- return;
699
- }
700
-
701
- const sameOrigin = url.origin === location.origin;
702
- const { params, route } = this.findMatchingRoute({
703
- event,
704
- request,
705
- sameOrigin,
706
- url,
707
- });
708
- let handler = route?.handler;
709
-
710
- const debugMessages = [];
711
- if (process.env.NODE_ENV !== "production") {
712
- if (handler) {
713
- debugMessages.push(["Found a route to handle this request:", route]);
714
-
715
- if (params) {
716
- debugMessages.push([`Passing the following params to the route's handler:`, params]);
717
- }
718
- }
719
- }
720
-
721
- // If we don't have a handler because there was no matching route, then
722
- // fall back to defaultHandler if that's defined.
723
- const method = request.method as HTTPMethod;
724
- if (!handler && this._defaultHandlerMap.has(method)) {
725
- if (process.env.NODE_ENV !== "production") {
726
- debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`);
727
- }
728
- handler = this._defaultHandlerMap.get(method);
729
- }
730
-
731
- if (!handler) {
732
- if (process.env.NODE_ENV !== "production") {
733
- // No handler so Serwist will do nothing. If logs is set of debug
734
- // i.e. verbose, we should print out this information.
735
- logger.debug(`No route found for: ${getFriendlyURL(url)}`);
736
- }
737
- return;
738
- }
739
-
740
- if (process.env.NODE_ENV !== "production") {
741
- // We have a handler, meaning Serwist is going to handle the route.
742
- // print the routing details to the console.
743
- logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
744
-
745
- for (const msg of debugMessages) {
746
- if (Array.isArray(msg)) {
747
- logger.log(...msg);
748
- } else {
749
- logger.log(msg);
750
- }
751
- }
752
-
753
- logger.groupEnd();
754
- }
755
-
756
- // Wrap in try and catch in case the handle method throws a synchronous
757
- // error. It should still callback to the catch handler.
758
- let responsePromise: Promise<Response>;
759
- try {
760
- responsePromise = handler.handle({ url, request, event, params });
761
- } catch (err) {
762
- responsePromise = Promise.reject(err);
763
- }
764
-
765
- // Get route's catch handler, if it exists
766
- const catchHandler = route?.catchHandler;
767
-
768
- if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
769
- responsePromise = responsePromise.catch(async (err) => {
770
- // If there's a route catch handler, process that first
771
- if (catchHandler) {
772
- if (process.env.NODE_ENV !== "production") {
773
- // Still include URL here as it will be async from the console group
774
- // and may not make sense without the URL
775
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
776
- logger.error("Error thrown by:", route);
777
- logger.error(err);
778
- logger.groupEnd();
779
- }
780
-
781
- try {
782
- return await catchHandler.handle({ url, request, event, params });
783
- } catch (catchErr) {
784
- if (catchErr instanceof Error) {
785
- err = catchErr;
786
- }
787
- }
788
- }
789
-
790
- if (this._catchHandler) {
791
- if (process.env.NODE_ENV !== "production") {
792
- // Still include URL here as it will be async from the console group
793
- // and may not make sense without the URL
794
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
795
- logger.error("Error thrown by:", route);
796
- logger.error(err);
797
- logger.groupEnd();
798
- }
799
- return this._catchHandler.handle({ url, request, event });
800
- }
801
-
802
- throw err;
803
- });
804
- }
805
-
806
- return responsePromise;
807
- }
808
-
809
- /**
810
- * Checks a request and URL (and optionally an event) against the list of
811
- * registered routes, and if there's a match, returns the corresponding
812
- * route along with any params generated by the match.
813
- *
814
- * @param options
815
- * @returns An object with `route` and `params` properties. They are populated
816
- * if a matching route was found or `undefined` otherwise.
817
- */
818
- findMatchingRoute({ url, sameOrigin, request, event }: RouteMatchCallbackOptions): {
819
- route?: Route;
820
- params?: RouteHandlerCallbackOptions["params"];
821
- } {
822
- const routes = this._routes.get(request.method as HTTPMethod) || [];
823
- for (const route of routes) {
824
- let params: Promise<any> | undefined;
825
- // route.match returns type any, not possible to change right now.
826
- const matchResult = route.match({ url, sameOrigin, request, event });
827
- if (matchResult) {
828
- if (process.env.NODE_ENV !== "production") {
829
- // Warn developers that using an async matchCallback is almost always
830
- // not the right thing to do.
831
- if (matchResult instanceof Promise) {
832
- logger.warn(
833
- `While routing ${getFriendlyURL(
834
- url,
835
- )}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`,
836
- route,
837
- );
838
- }
839
- }
840
-
841
- // See https://github.com/GoogleChrome/workbox/issues/2079
842
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
843
- params = matchResult;
844
- if (Array.isArray(params) && params.length === 0) {
845
- // Instead of passing an empty array in as params, use undefined.
846
- params = undefined;
847
- } else if (
848
- matchResult.constructor === Object && // eslint-disable-line
849
- Object.keys(matchResult).length === 0
850
- ) {
851
- // Instead of passing an empty object in as params, use undefined.
852
- params = undefined;
853
- } else if (typeof matchResult === "boolean") {
854
- // For the boolean value true (rather than just something truth-y),
855
- // don't set params.
856
- // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
857
- params = undefined;
858
- }
859
-
860
- // Return early if have a match.
861
- return { route, params };
862
- }
863
- }
864
- // If no match was found above, return and empty object.
865
- return {};
866
- }
867
- }