serwist 9.0.0-preview.24

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 (330) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/dist/NavigationRoute.d.ts +57 -0
  4. package/dist/NavigationRoute.d.ts.map +1 -0
  5. package/dist/PrecacheRoute.d.ts +17 -0
  6. package/dist/PrecacheRoute.d.ts.map +1 -0
  7. package/dist/PrecacheStrategy.d.ts +66 -0
  8. package/dist/PrecacheStrategy.d.ts.map +1 -0
  9. package/dist/RegExpRoute.d.ts +24 -0
  10. package/dist/RegExpRoute.d.ts.map +1 -0
  11. package/dist/Route.d.ts +33 -0
  12. package/dist/Route.d.ts.map +1 -0
  13. package/dist/Serwist.d.ts +331 -0
  14. package/dist/Serwist.d.ts.map +1 -0
  15. package/dist/cacheNames.d.ts +20 -0
  16. package/dist/cacheNames.d.ts.map +1 -0
  17. package/dist/chunks/NetworkOnly.js +599 -0
  18. package/dist/chunks/PrecacheFallbackPlugin.js +634 -0
  19. package/dist/chunks/Serwist.js +1034 -0
  20. package/dist/chunks/registerQuotaErrorCallback.js +17 -0
  21. package/dist/chunks/resultingClientExists.js +32 -0
  22. package/dist/chunks/timeout.js +400 -0
  23. package/dist/chunks/waitUntil.js +24 -0
  24. package/dist/cleanupOutdatedCaches.d.ts +6 -0
  25. package/dist/cleanupOutdatedCaches.d.ts.map +1 -0
  26. package/dist/clientsClaim.d.ts +6 -0
  27. package/dist/clientsClaim.d.ts.map +1 -0
  28. package/dist/constants.d.ts +15 -0
  29. package/dist/constants.d.ts.map +1 -0
  30. package/dist/copyResponse.d.ts +20 -0
  31. package/dist/copyResponse.d.ts.map +1 -0
  32. package/dist/disableDevLogs.d.ts +7 -0
  33. package/dist/disableDevLogs.d.ts.map +1 -0
  34. package/dist/index.d.ts +21 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.internal.d.ts +16 -0
  37. package/dist/index.internal.d.ts.map +1 -0
  38. package/dist/index.internal.js +24 -0
  39. package/dist/index.js +27 -0
  40. package/dist/index.legacy.d.ts +32 -0
  41. package/dist/index.legacy.d.ts.map +1 -0
  42. package/dist/index.legacy.js +640 -0
  43. package/dist/index.plugins.d.ts +41 -0
  44. package/dist/index.plugins.d.ts.map +1 -0
  45. package/dist/index.plugins.js +669 -0
  46. package/dist/index.strategies.d.ts +22 -0
  47. package/dist/index.strategies.d.ts.map +1 -0
  48. package/dist/index.strategies.js +144 -0
  49. package/dist/legacy/PrecacheController.d.ts +146 -0
  50. package/dist/legacy/PrecacheController.d.ts.map +1 -0
  51. package/dist/legacy/PrecacheFallbackPlugin.d.ts +62 -0
  52. package/dist/legacy/PrecacheFallbackPlugin.d.ts.map +1 -0
  53. package/dist/legacy/PrecacheRoute.d.ts +19 -0
  54. package/dist/legacy/PrecacheRoute.d.ts.map +1 -0
  55. package/dist/legacy/Router.d.ts +151 -0
  56. package/dist/legacy/Router.d.ts.map +1 -0
  57. package/dist/legacy/addPlugins.d.ts +9 -0
  58. package/dist/legacy/addPlugins.d.ts.map +1 -0
  59. package/dist/legacy/addRoute.d.ts +16 -0
  60. package/dist/legacy/addRoute.d.ts.map +1 -0
  61. package/dist/legacy/createHandlerBoundToURL.d.ts +18 -0
  62. package/dist/legacy/createHandlerBoundToURL.d.ts.map +1 -0
  63. package/dist/legacy/fallbacks.d.ts +59 -0
  64. package/dist/legacy/fallbacks.d.ts.map +1 -0
  65. package/dist/legacy/getCacheKeyForURL.d.ts +20 -0
  66. package/dist/legacy/getCacheKeyForURL.d.ts.map +1 -0
  67. package/dist/legacy/handlePrecaching.d.ts +54 -0
  68. package/dist/legacy/handlePrecaching.d.ts.map +1 -0
  69. package/dist/legacy/installSerwist.d.ts +15 -0
  70. package/dist/legacy/installSerwist.d.ts.map +1 -0
  71. package/dist/legacy/matchPrecache.d.ts +15 -0
  72. package/dist/legacy/matchPrecache.d.ts.map +1 -0
  73. package/dist/legacy/precache.d.ts +20 -0
  74. package/dist/legacy/precache.d.ts.map +1 -0
  75. package/dist/legacy/precacheAndRoute.d.ts +15 -0
  76. package/dist/legacy/precacheAndRoute.d.ts.map +1 -0
  77. package/dist/legacy/registerRoute.d.ts +16 -0
  78. package/dist/legacy/registerRoute.d.ts.map +1 -0
  79. package/dist/legacy/registerRuntimeCaching.d.ts +11 -0
  80. package/dist/legacy/registerRuntimeCaching.d.ts.map +1 -0
  81. package/dist/legacy/setCatchHandler.d.ts +10 -0
  82. package/dist/legacy/setCatchHandler.d.ts.map +1 -0
  83. package/dist/legacy/setDefaultHandler.d.ts +13 -0
  84. package/dist/legacy/setDefaultHandler.d.ts.map +1 -0
  85. package/dist/legacy/singletonPrecacheController.d.ts +34 -0
  86. package/dist/legacy/singletonPrecacheController.d.ts.map +1 -0
  87. package/dist/legacy/singletonRouter.d.ts +41 -0
  88. package/dist/legacy/singletonRouter.d.ts.map +1 -0
  89. package/dist/legacy/unregisterRoute.d.ts +9 -0
  90. package/dist/legacy/unregisterRoute.d.ts.map +1 -0
  91. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts +16 -0
  92. package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  93. package/dist/legacy/utils/getCacheKeyForURL.d.ts +14 -0
  94. package/dist/legacy/utils/getCacheKeyForURL.d.ts.map +1 -0
  95. package/dist/models/messages/messageGenerator.d.ts +4 -0
  96. package/dist/models/messages/messageGenerator.d.ts.map +1 -0
  97. package/dist/models/messages/messages.d.ts +44 -0
  98. package/dist/models/messages/messages.d.ts.map +1 -0
  99. package/dist/models/pluginEvents.d.ts +10 -0
  100. package/dist/models/pluginEvents.d.ts.map +1 -0
  101. package/dist/models/quotaErrorCallbacks.d.ts +3 -0
  102. package/dist/models/quotaErrorCallbacks.d.ts.map +1 -0
  103. package/dist/navigationPreload.d.ts +24 -0
  104. package/dist/navigationPreload.d.ts.map +1 -0
  105. package/dist/parseRoute.d.ts +16 -0
  106. package/dist/parseRoute.d.ts.map +1 -0
  107. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts +23 -0
  108. package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts.map +1 -0
  109. package/dist/plugins/backgroundSync/Queue.d.ts +166 -0
  110. package/dist/plugins/backgroundSync/Queue.d.ts.map +1 -0
  111. package/dist/plugins/backgroundSync/QueueDb.d.ts +90 -0
  112. package/dist/plugins/backgroundSync/QueueDb.d.ts.map +1 -0
  113. package/dist/plugins/backgroundSync/QueueStore.d.ts +75 -0
  114. package/dist/plugins/backgroundSync/QueueStore.d.ts.map +1 -0
  115. package/dist/plugins/backgroundSync/StorableRequest.d.ts +51 -0
  116. package/dist/plugins/backgroundSync/StorableRequest.d.ts.map +1 -0
  117. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts +45 -0
  118. package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +1 -0
  119. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts +27 -0
  120. package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +1 -0
  121. package/dist/plugins/broadcastUpdate/constants.d.ts +5 -0
  122. package/dist/plugins/broadcastUpdate/constants.d.ts.map +1 -0
  123. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts +11 -0
  124. package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts.map +1 -0
  125. package/dist/plugins/broadcastUpdate/types.d.ts +34 -0
  126. package/dist/plugins/broadcastUpdate/types.d.ts.map +1 -0
  127. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts +40 -0
  128. package/dist/plugins/cacheableResponse/CacheableResponse.d.ts.map +1 -0
  129. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts +27 -0
  130. package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts.map +1 -0
  131. package/dist/plugins/expiration/CacheExpiration.d.ts +66 -0
  132. package/dist/plugins/expiration/CacheExpiration.d.ts.map +1 -0
  133. package/dist/plugins/expiration/ExpirationPlugin.d.ts +116 -0
  134. package/dist/plugins/expiration/ExpirationPlugin.d.ts.map +1 -0
  135. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts +73 -0
  136. package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts.map +1 -0
  137. package/dist/plugins/googleAnalytics/constants.d.ts +10 -0
  138. package/dist/plugins/googleAnalytics/constants.d.ts.map +1 -0
  139. package/dist/plugins/googleAnalytics/initialize.d.ts +30 -0
  140. package/dist/plugins/googleAnalytics/initialize.d.ts.map +1 -0
  141. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts +53 -0
  142. package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts.map +1 -0
  143. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts +19 -0
  144. package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts.map +1 -0
  145. package/dist/plugins/rangeRequests/createPartialResponse.d.ts +18 -0
  146. package/dist/plugins/rangeRequests/createPartialResponse.d.ts.map +1 -0
  147. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts +14 -0
  148. package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +1 -0
  149. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts +12 -0
  150. package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts.map +1 -0
  151. package/dist/registerQuotaErrorCallback.d.ts +8 -0
  152. package/dist/registerQuotaErrorCallback.d.ts.map +1 -0
  153. package/dist/setCacheNameDetails.d.ts +9 -0
  154. package/dist/setCacheNameDetails.d.ts.map +1 -0
  155. package/dist/strategies/CacheFirst.d.ts +23 -0
  156. package/dist/strategies/CacheFirst.d.ts.map +1 -0
  157. package/dist/strategies/CacheOnly.d.ts +20 -0
  158. package/dist/strategies/CacheOnly.d.ts.map +1 -0
  159. package/dist/strategies/NetworkFirst.d.ts +61 -0
  160. package/dist/strategies/NetworkFirst.d.ts.map +1 -0
  161. package/dist/strategies/NetworkOnly.d.ts +32 -0
  162. package/dist/strategies/NetworkOnly.d.ts.map +1 -0
  163. package/dist/strategies/StaleWhileRevalidate.d.ts +35 -0
  164. package/dist/strategies/StaleWhileRevalidate.d.ts.map +1 -0
  165. package/dist/strategies/Strategy.d.ts +83 -0
  166. package/dist/strategies/Strategy.d.ts.map +1 -0
  167. package/dist/strategies/StrategyHandler.d.ts +189 -0
  168. package/dist/strategies/StrategyHandler.d.ts.map +1 -0
  169. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +3 -0
  170. package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -0
  171. package/dist/strategies/utils/messages.d.ts +5 -0
  172. package/dist/strategies/utils/messages.d.ts.map +1 -0
  173. package/dist/types.d.ts +317 -0
  174. package/dist/types.d.ts.map +1 -0
  175. package/dist/utils/Deferred.d.ts +19 -0
  176. package/dist/utils/Deferred.d.ts.map +1 -0
  177. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +16 -0
  178. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  179. package/dist/utils/PrecacheInstallReportPlugin.d.ts +14 -0
  180. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +1 -0
  181. package/dist/utils/SerwistError.d.ts +24 -0
  182. package/dist/utils/SerwistError.d.ts.map +1 -0
  183. package/dist/utils/assert.d.ts +11 -0
  184. package/dist/utils/assert.d.ts.map +1 -0
  185. package/dist/utils/cacheMatchIgnoreParams.d.ts +15 -0
  186. package/dist/utils/cacheMatchIgnoreParams.d.ts.map +1 -0
  187. package/dist/utils/cacheNames.d.ts +40 -0
  188. package/dist/utils/cacheNames.d.ts.map +1 -0
  189. package/dist/utils/canConstructReadableStream.d.ts +12 -0
  190. package/dist/utils/canConstructReadableStream.d.ts.map +1 -0
  191. package/dist/utils/canConstructResponseFromBodyStream.d.ts +11 -0
  192. package/dist/utils/canConstructResponseFromBodyStream.d.ts.map +1 -0
  193. package/dist/utils/createCacheKey.d.ts +16 -0
  194. package/dist/utils/createCacheKey.d.ts.map +1 -0
  195. package/dist/utils/deleteOutdatedCaches.d.ts +18 -0
  196. package/dist/utils/deleteOutdatedCaches.d.ts.map +1 -0
  197. package/dist/utils/dontWaitFor.d.ts +7 -0
  198. package/dist/utils/dontWaitFor.d.ts.map +1 -0
  199. package/dist/utils/executeQuotaErrorCallbacks.d.ts +8 -0
  200. package/dist/utils/executeQuotaErrorCallbacks.d.ts.map +1 -0
  201. package/dist/utils/generateURLVariations.d.ts +12 -0
  202. package/dist/utils/generateURLVariations.d.ts.map +1 -0
  203. package/dist/utils/getFriendlyURL.d.ts +3 -0
  204. package/dist/utils/getFriendlyURL.d.ts.map +1 -0
  205. package/dist/utils/logger.d.ts +24 -0
  206. package/dist/utils/logger.d.ts.map +1 -0
  207. package/dist/utils/normalizeHandler.d.ts +10 -0
  208. package/dist/utils/normalizeHandler.d.ts.map +1 -0
  209. package/dist/utils/pluginUtils.d.ts +5 -0
  210. package/dist/utils/pluginUtils.d.ts.map +1 -0
  211. package/dist/utils/printCleanupDetails.d.ts +6 -0
  212. package/dist/utils/printCleanupDetails.d.ts.map +1 -0
  213. package/dist/utils/printInstallDetails.d.ts +7 -0
  214. package/dist/utils/printInstallDetails.d.ts.map +1 -0
  215. package/dist/utils/removeIgnoredSearchParams.d.ts +12 -0
  216. package/dist/utils/removeIgnoredSearchParams.d.ts.map +1 -0
  217. package/dist/utils/resultingClientExists.d.ts +12 -0
  218. package/dist/utils/resultingClientExists.d.ts.map +1 -0
  219. package/dist/utils/timeout.d.ts +10 -0
  220. package/dist/utils/timeout.d.ts.map +1 -0
  221. package/dist/utils/waitUntil.d.ts +11 -0
  222. package/dist/utils/waitUntil.d.ts.map +1 -0
  223. package/dist/utils/welcome.d.ts +2 -0
  224. package/dist/utils/welcome.d.ts.map +1 -0
  225. package/package.json +85 -0
  226. package/src/NavigationRoute.ts +119 -0
  227. package/src/PrecacheRoute.ts +46 -0
  228. package/src/PrecacheStrategy.ts +239 -0
  229. package/src/RegExpRoute.ts +74 -0
  230. package/src/Route.ts +67 -0
  231. package/src/Serwist.ts +920 -0
  232. package/src/cacheNames.ts +39 -0
  233. package/src/cleanupOutdatedCaches.ts +32 -0
  234. package/src/clientsClaim.ts +18 -0
  235. package/src/constants.ts +24 -0
  236. package/src/copyResponse.ts +60 -0
  237. package/src/disableDevLogs.ts +10 -0
  238. package/src/index.internal.ts +33 -0
  239. package/src/index.legacy.ts +66 -0
  240. package/src/index.plugins.ts +95 -0
  241. package/src/index.strategies.ts +26 -0
  242. package/src/index.ts +39 -0
  243. package/src/legacy/PrecacheController.ts +337 -0
  244. package/src/legacy/PrecacheFallbackPlugin.ts +93 -0
  245. package/src/legacy/PrecacheRoute.ts +48 -0
  246. package/src/legacy/Router.ts +484 -0
  247. package/src/legacy/addPlugins.ts +21 -0
  248. package/src/legacy/addRoute.ts +29 -0
  249. package/src/legacy/createHandlerBoundToURL.ts +30 -0
  250. package/src/legacy/fallbacks.ts +94 -0
  251. package/src/legacy/getCacheKeyForURL.ts +32 -0
  252. package/src/legacy/handlePrecaching.ts +86 -0
  253. package/src/legacy/installSerwist.ts +19 -0
  254. package/src/legacy/matchPrecache.ts +26 -0
  255. package/src/legacy/precache.ts +31 -0
  256. package/src/legacy/precacheAndRoute.ts +28 -0
  257. package/src/legacy/registerRoute.ts +27 -0
  258. package/src/legacy/registerRuntimeCaching.ts +17 -0
  259. package/src/legacy/setCatchHandler.ts +21 -0
  260. package/src/legacy/setDefaultHandler.ts +24 -0
  261. package/src/legacy/singletonPrecacheController.ts +53 -0
  262. package/src/legacy/singletonRouter.ts +70 -0
  263. package/src/legacy/unregisterRoute.ts +12 -0
  264. package/src/legacy/utils/PrecacheCacheKeyPlugin.ts +33 -0
  265. package/src/legacy/utils/getCacheKeyForURL.ts +36 -0
  266. package/src/models/messages/messageGenerator.ts +29 -0
  267. package/src/models/messages/messages.ts +233 -0
  268. package/src/models/pluginEvents.ts +17 -0
  269. package/src/models/quotaErrorCallbacks.ts +13 -0
  270. package/src/navigationPreload.ts +68 -0
  271. package/src/parseRoute.ts +78 -0
  272. package/src/plugins/backgroundSync/BackgroundSyncPlugin.ts +38 -0
  273. package/src/plugins/backgroundSync/Queue.ts +440 -0
  274. package/src/plugins/backgroundSync/QueueDb.ts +176 -0
  275. package/src/plugins/backgroundSync/QueueStore.ts +160 -0
  276. package/src/plugins/backgroundSync/StorableRequest.ts +142 -0
  277. package/src/plugins/broadcastUpdate/BroadcastCacheUpdate.ts +161 -0
  278. package/src/plugins/broadcastUpdate/BroadcastUpdatePlugin.ts +42 -0
  279. package/src/plugins/broadcastUpdate/constants.ts +12 -0
  280. package/src/plugins/broadcastUpdate/responsesAreSame.ts +49 -0
  281. package/src/plugins/broadcastUpdate/types.ts +37 -0
  282. package/src/plugins/cacheableResponse/CacheableResponse.ts +144 -0
  283. package/src/plugins/cacheableResponse/CacheableResponsePlugin.ts +45 -0
  284. package/src/plugins/expiration/CacheExpiration.ts +193 -0
  285. package/src/plugins/expiration/ExpirationPlugin.ts +300 -0
  286. package/src/plugins/expiration/models/CacheTimestampsModel.ts +184 -0
  287. package/src/plugins/googleAnalytics/constants.ts +22 -0
  288. package/src/plugins/googleAnalytics/initialize.ts +209 -0
  289. package/src/plugins/precaching/PrecacheFallbackPlugin.ts +83 -0
  290. package/src/plugins/rangeRequests/RangeRequestsPlugin.ts +38 -0
  291. package/src/plugins/rangeRequests/createPartialResponse.ts +93 -0
  292. package/src/plugins/rangeRequests/utils/calculateEffectiveBoundaries.ts +59 -0
  293. package/src/plugins/rangeRequests/utils/parseRangeHeader.ts +55 -0
  294. package/src/registerQuotaErrorCallback.ts +34 -0
  295. package/src/setCacheNameDetails.ts +53 -0
  296. package/src/strategies/CacheFirst.ts +88 -0
  297. package/src/strategies/CacheOnly.ts +59 -0
  298. package/src/strategies/NetworkFirst.ts +229 -0
  299. package/src/strategies/NetworkOnly.ts +98 -0
  300. package/src/strategies/StaleWhileRevalidate.ts +110 -0
  301. package/src/strategies/Strategy.ts +204 -0
  302. package/src/strategies/StrategyHandler.ts +554 -0
  303. package/src/strategies/plugins/cacheOkAndOpaquePlugin.ts +26 -0
  304. package/src/strategies/utils/messages.ts +21 -0
  305. package/src/types.ts +358 -0
  306. package/src/utils/Deferred.ts +33 -0
  307. package/src/utils/PrecacheCacheKeyPlugin.ts +33 -0
  308. package/src/utils/PrecacheInstallReportPlugin.ts +47 -0
  309. package/src/utils/SerwistError.ts +41 -0
  310. package/src/utils/assert.ts +89 -0
  311. package/src/utils/cacheMatchIgnoreParams.ts +54 -0
  312. package/src/utils/cacheNames.ts +87 -0
  313. package/src/utils/canConstructReadableStream.ts +34 -0
  314. package/src/utils/canConstructResponseFromBodyStream.ts +37 -0
  315. package/src/utils/createCacheKey.ts +68 -0
  316. package/src/utils/deleteOutdatedCaches.ts +40 -0
  317. package/src/utils/dontWaitFor.ts +16 -0
  318. package/src/utils/executeQuotaErrorCallbacks.ts +33 -0
  319. package/src/utils/generateURLVariations.ts +55 -0
  320. package/src/utils/getFriendlyURL.ts +16 -0
  321. package/src/utils/logger.ts +95 -0
  322. package/src/utils/normalizeHandler.ts +40 -0
  323. package/src/utils/pluginUtils.ts +15 -0
  324. package/src/utils/printCleanupDetails.ts +38 -0
  325. package/src/utils/printInstallDetails.ts +53 -0
  326. package/src/utils/removeIgnoredSearchParams.ts +29 -0
  327. package/src/utils/resultingClientExists.ts +58 -0
  328. package/src/utils/timeout.ts +19 -0
  329. package/src/utils/waitUntil.ts +21 -0
  330. package/src/utils/welcome.ts +19 -0
@@ -0,0 +1,669 @@
1
+ export { B as BackgroundSyncPlugin, Q as BackgroundSyncQueue, a as BackgroundSyncQueueStore, P as PrecacheFallbackPlugin, S as StorableRequest, i as initializeGoogleAnalytics } from './chunks/PrecacheFallbackPlugin.js';
2
+ import { S as SerwistError, l as logger, f as finalAssertExports, t as timeout, g as getFriendlyURL, c as cacheNames } from './chunks/timeout.js';
3
+ import { r as resultingClientExists } from './chunks/resultingClientExists.js';
4
+ import { deleteDB, openDB } from 'idb';
5
+ import { r as registerQuotaErrorCallback } from './chunks/registerQuotaErrorCallback.js';
6
+ import './chunks/NetworkOnly.js';
7
+
8
+ const CACHE_UPDATED_MESSAGE_TYPE = "CACHE_UPDATED";
9
+ const CACHE_UPDATED_MESSAGE_META = "serwist-broadcast-update";
10
+ const defaultNotifyAllClients = true;
11
+ const defaultHeadersToCheck = [
12
+ "content-length",
13
+ "etag",
14
+ "last-modified"
15
+ ];
16
+
17
+ const responsesAreSame = (firstResponse, secondResponse, headersToCheck)=>{
18
+ if (process.env.NODE_ENV !== "production") {
19
+ if (!(firstResponse instanceof Response && secondResponse instanceof Response)) {
20
+ throw new SerwistError("invalid-responses-are-same-args");
21
+ }
22
+ }
23
+ const atLeastOneHeaderAvailable = headersToCheck.some((header)=>{
24
+ return firstResponse.headers.has(header) && secondResponse.headers.has(header);
25
+ });
26
+ if (!atLeastOneHeaderAvailable) {
27
+ if (process.env.NODE_ENV !== "production") {
28
+ logger.warn("Unable to determine where the response has been updated because none of the headers that would be checked are present.");
29
+ logger.debug("Attempting to compare the following: ", firstResponse, secondResponse, headersToCheck);
30
+ }
31
+ return true;
32
+ }
33
+ return headersToCheck.every((header)=>{
34
+ const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header);
35
+ const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header);
36
+ return headerStateComparison && headerValueComparison;
37
+ });
38
+ };
39
+
40
+ const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
41
+ const defaultPayloadGenerator = (data)=>{
42
+ return {
43
+ cacheName: data.cacheName,
44
+ updatedURL: data.request.url
45
+ };
46
+ };
47
+ class BroadcastCacheUpdate {
48
+ _headersToCheck;
49
+ _generatePayload;
50
+ _notifyAllClients;
51
+ constructor({ generatePayload, headersToCheck, notifyAllClients } = {}){
52
+ this._headersToCheck = headersToCheck || defaultHeadersToCheck;
53
+ this._generatePayload = generatePayload || defaultPayloadGenerator;
54
+ this._notifyAllClients = notifyAllClients ?? defaultNotifyAllClients;
55
+ }
56
+ async notifyIfUpdated(options) {
57
+ if (process.env.NODE_ENV !== "production") {
58
+ finalAssertExports.isType(options.cacheName, "string", {
59
+ moduleName: "serwist/plugins",
60
+ className: "BroadcastCacheUpdate",
61
+ funcName: "notifyIfUpdated",
62
+ paramName: "cacheName"
63
+ });
64
+ finalAssertExports.isInstance(options.newResponse, Response, {
65
+ moduleName: "serwist/plugins",
66
+ className: "BroadcastCacheUpdate",
67
+ funcName: "notifyIfUpdated",
68
+ paramName: "newResponse"
69
+ });
70
+ finalAssertExports.isInstance(options.request, Request, {
71
+ moduleName: "serwist/plugins",
72
+ className: "BroadcastCacheUpdate",
73
+ funcName: "notifyIfUpdated",
74
+ paramName: "request"
75
+ });
76
+ }
77
+ if (!options.oldResponse) {
78
+ return;
79
+ }
80
+ if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {
81
+ if (process.env.NODE_ENV !== "production") {
82
+ logger.log("Newer response found (and cached) for:", options.request.url);
83
+ }
84
+ const messageData = {
85
+ type: CACHE_UPDATED_MESSAGE_TYPE,
86
+ meta: CACHE_UPDATED_MESSAGE_META,
87
+ payload: this._generatePayload(options)
88
+ };
89
+ if (options.request.mode === "navigate") {
90
+ let resultingClientId;
91
+ if (options.event instanceof FetchEvent) {
92
+ resultingClientId = options.event.resultingClientId;
93
+ }
94
+ const resultingWin = await resultingClientExists(resultingClientId);
95
+ if (!resultingWin || isSafari) {
96
+ await timeout(3500);
97
+ }
98
+ }
99
+ if (this._notifyAllClients) {
100
+ const windows = await self.clients.matchAll({
101
+ type: "window"
102
+ });
103
+ for (const win of windows){
104
+ win.postMessage(messageData);
105
+ }
106
+ } else {
107
+ if (options.event instanceof FetchEvent) {
108
+ const client = await self.clients.get(options.event.clientId);
109
+ client?.postMessage(messageData);
110
+ }
111
+ }
112
+ }
113
+ }
114
+ }
115
+
116
+ class BroadcastUpdatePlugin {
117
+ _broadcastUpdate;
118
+ constructor(options){
119
+ this._broadcastUpdate = new BroadcastCacheUpdate(options);
120
+ }
121
+ cacheDidUpdate(options) {
122
+ void this._broadcastUpdate.notifyIfUpdated(options);
123
+ }
124
+ }
125
+
126
+ class CacheableResponse {
127
+ _statuses;
128
+ _headers;
129
+ constructor(config = {}){
130
+ if (process.env.NODE_ENV !== "production") {
131
+ if (!(config.statuses || config.headers)) {
132
+ throw new SerwistError("statuses-or-headers-required", {
133
+ moduleName: "serwist/plugins",
134
+ className: "CacheableResponse",
135
+ funcName: "constructor"
136
+ });
137
+ }
138
+ if (config.statuses) {
139
+ finalAssertExports.isArray(config.statuses, {
140
+ moduleName: "serwist/plugins",
141
+ className: "CacheableResponse",
142
+ funcName: "constructor",
143
+ paramName: "config.statuses"
144
+ });
145
+ }
146
+ if (config.headers) {
147
+ finalAssertExports.isType(config.headers, "object", {
148
+ moduleName: "serwist/plugins",
149
+ className: "CacheableResponse",
150
+ funcName: "constructor",
151
+ paramName: "config.headers"
152
+ });
153
+ }
154
+ }
155
+ this._statuses = config.statuses;
156
+ if (config.headers) {
157
+ this._headers = new Headers(config.headers);
158
+ }
159
+ }
160
+ isResponseCacheable(response) {
161
+ if (process.env.NODE_ENV !== "production") {
162
+ finalAssertExports.isInstance(response, Response, {
163
+ moduleName: "serwist/plugins",
164
+ className: "CacheableResponse",
165
+ funcName: "isResponseCacheable",
166
+ paramName: "response"
167
+ });
168
+ }
169
+ let cacheable = true;
170
+ if (this._statuses) {
171
+ cacheable = this._statuses.includes(response.status);
172
+ }
173
+ if (this._headers && cacheable) {
174
+ for (const [headerName, headerValue] of this._headers.entries()){
175
+ if (response.headers.get(headerName) !== headerValue) {
176
+ cacheable = false;
177
+ break;
178
+ }
179
+ }
180
+ }
181
+ if (process.env.NODE_ENV !== "production") {
182
+ if (!cacheable) {
183
+ logger.groupCollapsed(`The request for '${getFriendlyURL(response.url)}' returned a response that does not meet the criteria for being cached.`);
184
+ logger.groupCollapsed("View cacheability criteria here.");
185
+ logger.log(`Cacheable statuses: ${JSON.stringify(this._statuses)}`);
186
+ logger.log(`Cacheable headers: ${JSON.stringify(this._headers, null, 2)}`);
187
+ logger.groupEnd();
188
+ const logFriendlyHeaders = {};
189
+ response.headers.forEach((value, key)=>{
190
+ logFriendlyHeaders[key] = value;
191
+ });
192
+ logger.groupCollapsed("View response status and headers here.");
193
+ logger.log(`Response status: ${response.status}`);
194
+ logger.log(`Response headers: ${JSON.stringify(logFriendlyHeaders, null, 2)}`);
195
+ logger.groupEnd();
196
+ logger.groupCollapsed("View full response details here.");
197
+ logger.log(response.headers);
198
+ logger.log(response);
199
+ logger.groupEnd();
200
+ logger.groupEnd();
201
+ }
202
+ }
203
+ return cacheable;
204
+ }
205
+ }
206
+
207
+ class CacheableResponsePlugin {
208
+ _cacheableResponse;
209
+ constructor(config){
210
+ this._cacheableResponse = new CacheableResponse(config);
211
+ }
212
+ cacheWillUpdate = async ({ response })=>{
213
+ if (this._cacheableResponse.isResponseCacheable(response)) {
214
+ return response;
215
+ }
216
+ return null;
217
+ };
218
+ }
219
+
220
+ const DB_NAME = "serwist-expiration";
221
+ const CACHE_OBJECT_STORE = "cache-entries";
222
+ const normalizeURL = (unNormalizedUrl)=>{
223
+ const url = new URL(unNormalizedUrl, location.href);
224
+ url.hash = "";
225
+ return url.href;
226
+ };
227
+ class CacheTimestampsModel {
228
+ _cacheName;
229
+ _db = null;
230
+ constructor(cacheName){
231
+ this._cacheName = cacheName;
232
+ }
233
+ _getId(url) {
234
+ return `${this._cacheName}|${normalizeURL(url)}`;
235
+ }
236
+ _upgradeDb(db) {
237
+ const objStore = db.createObjectStore(CACHE_OBJECT_STORE, {
238
+ keyPath: "id"
239
+ });
240
+ objStore.createIndex("cacheName", "cacheName", {
241
+ unique: false
242
+ });
243
+ objStore.createIndex("timestamp", "timestamp", {
244
+ unique: false
245
+ });
246
+ }
247
+ _upgradeDbAndDeleteOldDbs(db) {
248
+ this._upgradeDb(db);
249
+ if (this._cacheName) {
250
+ void deleteDB(this._cacheName);
251
+ }
252
+ }
253
+ async setTimestamp(url, timestamp) {
254
+ url = normalizeURL(url);
255
+ const entry = {
256
+ id: this._getId(url),
257
+ cacheName: this._cacheName,
258
+ url,
259
+ timestamp
260
+ };
261
+ const db = await this.getDb();
262
+ const tx = db.transaction(CACHE_OBJECT_STORE, "readwrite", {
263
+ durability: "relaxed"
264
+ });
265
+ await tx.store.put(entry);
266
+ await tx.done;
267
+ }
268
+ async getTimestamp(url) {
269
+ const db = await this.getDb();
270
+ const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));
271
+ return entry?.timestamp;
272
+ }
273
+ async expireEntries(minTimestamp, maxCount) {
274
+ const db = await this.getDb();
275
+ let cursor = await db.transaction(CACHE_OBJECT_STORE, "readwrite").store.index("timestamp").openCursor(null, "prev");
276
+ const urlsDeleted = [];
277
+ let entriesNotDeletedCount = 0;
278
+ while(cursor){
279
+ const result = cursor.value;
280
+ if (result.cacheName === this._cacheName) {
281
+ if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
282
+ cursor.delete();
283
+ urlsDeleted.push(result.url);
284
+ } else {
285
+ entriesNotDeletedCount++;
286
+ }
287
+ }
288
+ cursor = await cursor.continue();
289
+ }
290
+ return urlsDeleted;
291
+ }
292
+ async getDb() {
293
+ if (!this._db) {
294
+ this._db = await openDB(DB_NAME, 1, {
295
+ upgrade: this._upgradeDbAndDeleteOldDbs.bind(this)
296
+ });
297
+ }
298
+ return this._db;
299
+ }
300
+ }
301
+
302
+ class CacheExpiration {
303
+ _isRunning = false;
304
+ _rerunRequested = false;
305
+ _maxEntries;
306
+ _maxAgeSeconds;
307
+ _matchOptions;
308
+ _cacheName;
309
+ _timestampModel;
310
+ constructor(cacheName, config = {}){
311
+ if (process.env.NODE_ENV !== "production") {
312
+ finalAssertExports.isType(cacheName, "string", {
313
+ moduleName: "serwist/plugins",
314
+ className: "CacheExpiration",
315
+ funcName: "constructor",
316
+ paramName: "cacheName"
317
+ });
318
+ if (!(config.maxEntries || config.maxAgeSeconds)) {
319
+ throw new SerwistError("max-entries-or-age-required", {
320
+ moduleName: "serwist/plugins",
321
+ className: "CacheExpiration",
322
+ funcName: "constructor"
323
+ });
324
+ }
325
+ if (config.maxEntries) {
326
+ finalAssertExports.isType(config.maxEntries, "number", {
327
+ moduleName: "serwist/plugins",
328
+ className: "CacheExpiration",
329
+ funcName: "constructor",
330
+ paramName: "config.maxEntries"
331
+ });
332
+ }
333
+ if (config.maxAgeSeconds) {
334
+ finalAssertExports.isType(config.maxAgeSeconds, "number", {
335
+ moduleName: "serwist/plugins",
336
+ className: "CacheExpiration",
337
+ funcName: "constructor",
338
+ paramName: "config.maxAgeSeconds"
339
+ });
340
+ }
341
+ }
342
+ this._maxEntries = config.maxEntries;
343
+ this._maxAgeSeconds = config.maxAgeSeconds;
344
+ this._matchOptions = config.matchOptions;
345
+ this._cacheName = cacheName;
346
+ this._timestampModel = new CacheTimestampsModel(cacheName);
347
+ }
348
+ async expireEntries() {
349
+ if (this._isRunning) {
350
+ this._rerunRequested = true;
351
+ return;
352
+ }
353
+ this._isRunning = true;
354
+ const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0;
355
+ const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
356
+ const cache = await self.caches.open(this._cacheName);
357
+ for (const url of urlsExpired){
358
+ await cache.delete(url, this._matchOptions);
359
+ }
360
+ if (process.env.NODE_ENV !== "production") {
361
+ if (urlsExpired.length > 0) {
362
+ logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? "entry" : "entries"} and removed ` + `${urlsExpired.length === 1 ? "it" : "them"} from the ` + `'${this._cacheName}' cache.`);
363
+ logger.log(`Expired the following ${urlsExpired.length === 1 ? "URL" : "URLs"}:`);
364
+ for (const url of urlsExpired){
365
+ logger.log(` ${url}`);
366
+ }
367
+ logger.groupEnd();
368
+ } else {
369
+ logger.debug("Cache expiration ran and found no entries to remove.");
370
+ }
371
+ }
372
+ this._isRunning = false;
373
+ if (this._rerunRequested) {
374
+ this._rerunRequested = false;
375
+ void this.expireEntries();
376
+ }
377
+ }
378
+ async updateTimestamp(url) {
379
+ if (process.env.NODE_ENV !== "production") {
380
+ finalAssertExports.isType(url, "string", {
381
+ moduleName: "serwist/plugins",
382
+ className: "CacheExpiration",
383
+ funcName: "updateTimestamp",
384
+ paramName: "url"
385
+ });
386
+ }
387
+ await this._timestampModel.setTimestamp(url, Date.now());
388
+ }
389
+ async isURLExpired(url) {
390
+ if (!this._maxAgeSeconds) {
391
+ if (process.env.NODE_ENV !== "production") {
392
+ throw new SerwistError("expired-test-without-max-age", {
393
+ methodName: "isURLExpired",
394
+ paramName: "maxAgeSeconds"
395
+ });
396
+ }
397
+ return false;
398
+ }
399
+ const timestamp = await this._timestampModel.getTimestamp(url);
400
+ const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
401
+ return timestamp !== undefined ? timestamp < expireOlderThan : true;
402
+ }
403
+ async delete() {
404
+ this._rerunRequested = false;
405
+ await this._timestampModel.expireEntries(Number.POSITIVE_INFINITY);
406
+ }
407
+ }
408
+
409
+ class ExpirationPlugin {
410
+ _config;
411
+ _cacheExpirations;
412
+ constructor(config = {}){
413
+ if (process.env.NODE_ENV !== "production") {
414
+ if (!(config.maxEntries || config.maxAgeSeconds)) {
415
+ throw new SerwistError("max-entries-or-age-required", {
416
+ moduleName: "serwist/plugins",
417
+ className: "ExpirationPlugin",
418
+ funcName: "constructor"
419
+ });
420
+ }
421
+ if (config.maxEntries) {
422
+ finalAssertExports.isType(config.maxEntries, "number", {
423
+ moduleName: "serwist/plugins",
424
+ className: "ExpirationPlugin",
425
+ funcName: "constructor",
426
+ paramName: "config.maxEntries"
427
+ });
428
+ }
429
+ if (config.maxAgeSeconds) {
430
+ finalAssertExports.isType(config.maxAgeSeconds, "number", {
431
+ moduleName: "serwist/plugins",
432
+ className: "ExpirationPlugin",
433
+ funcName: "constructor",
434
+ paramName: "config.maxAgeSeconds"
435
+ });
436
+ }
437
+ if (config.maxAgeFrom) {
438
+ finalAssertExports.isType(config.maxAgeFrom, "string", {
439
+ moduleName: "serwist/plugins",
440
+ className: "ExpirationPlugin",
441
+ funcName: "constructor",
442
+ paramName: "config.maxAgeFrom"
443
+ });
444
+ }
445
+ }
446
+ this._config = config;
447
+ this._cacheExpirations = new Map();
448
+ if (!this._config.maxAgeFrom) {
449
+ this._config.maxAgeFrom = "last-fetched";
450
+ }
451
+ if (this._config.purgeOnQuotaError) {
452
+ registerQuotaErrorCallback(()=>this.deleteCacheAndMetadata());
453
+ }
454
+ }
455
+ _getCacheExpiration(cacheName) {
456
+ if (cacheName === cacheNames.getRuntimeName()) {
457
+ throw new SerwistError("expire-custom-caches-only");
458
+ }
459
+ let cacheExpiration = this._cacheExpirations.get(cacheName);
460
+ if (!cacheExpiration) {
461
+ cacheExpiration = new CacheExpiration(cacheName, this._config);
462
+ this._cacheExpirations.set(cacheName, cacheExpiration);
463
+ }
464
+ return cacheExpiration;
465
+ }
466
+ cachedResponseWillBeUsed({ event, cacheName, request, cachedResponse }) {
467
+ if (!cachedResponse) {
468
+ return null;
469
+ }
470
+ const isFresh = this._isResponseDateFresh(cachedResponse);
471
+ const cacheExpiration = this._getCacheExpiration(cacheName);
472
+ const isMaxAgeFromLastUsed = this._config.maxAgeFrom === "last-used";
473
+ const done = (async ()=>{
474
+ if (isMaxAgeFromLastUsed) {
475
+ await cacheExpiration.updateTimestamp(request.url);
476
+ }
477
+ await cacheExpiration.expireEntries();
478
+ })();
479
+ try {
480
+ event.waitUntil(done);
481
+ } catch (error) {
482
+ if (process.env.NODE_ENV !== "production") {
483
+ if (event instanceof FetchEvent) {
484
+ logger.warn(`Unable to ensure service worker stays alive when updating cache entry for '${getFriendlyURL(event.request.url)}'.`);
485
+ }
486
+ }
487
+ }
488
+ return isFresh ? cachedResponse : null;
489
+ }
490
+ _isResponseDateFresh(cachedResponse) {
491
+ const isMaxAgeFromLastUsed = this._config.maxAgeFrom === "last-used";
492
+ if (isMaxAgeFromLastUsed) {
493
+ return true;
494
+ }
495
+ const now = Date.now();
496
+ if (!this._config.maxAgeSeconds) {
497
+ return true;
498
+ }
499
+ const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
500
+ if (dateHeaderTimestamp === null) {
501
+ return true;
502
+ }
503
+ return dateHeaderTimestamp >= now - this._config.maxAgeSeconds * 1000;
504
+ }
505
+ _getDateHeaderTimestamp(cachedResponse) {
506
+ if (!cachedResponse.headers.has("date")) {
507
+ return null;
508
+ }
509
+ const dateHeader = cachedResponse.headers.get("date");
510
+ const parsedDate = new Date(dateHeader);
511
+ const headerTime = parsedDate.getTime();
512
+ if (Number.isNaN(headerTime)) {
513
+ return null;
514
+ }
515
+ return headerTime;
516
+ }
517
+ async cacheDidUpdate({ cacheName, request }) {
518
+ if (process.env.NODE_ENV !== "production") {
519
+ finalAssertExports.isType(cacheName, "string", {
520
+ moduleName: "serwist/plugins",
521
+ className: "Plugin",
522
+ funcName: "cacheDidUpdate",
523
+ paramName: "cacheName"
524
+ });
525
+ finalAssertExports.isInstance(request, Request, {
526
+ moduleName: "serwist/plugins",
527
+ className: "Plugin",
528
+ funcName: "cacheDidUpdate",
529
+ paramName: "request"
530
+ });
531
+ }
532
+ const cacheExpiration = this._getCacheExpiration(cacheName);
533
+ await cacheExpiration.updateTimestamp(request.url);
534
+ await cacheExpiration.expireEntries();
535
+ }
536
+ async deleteCacheAndMetadata() {
537
+ for (const [cacheName, cacheExpiration] of this._cacheExpirations){
538
+ await self.caches.delete(cacheName);
539
+ await cacheExpiration.delete();
540
+ }
541
+ this._cacheExpirations = new Map();
542
+ }
543
+ }
544
+
545
+ const calculateEffectiveBoundaries = (blob, start, end)=>{
546
+ if (process.env.NODE_ENV !== "production") {
547
+ finalAssertExports.isInstance(blob, Blob, {
548
+ moduleName: "@serwist/range-requests",
549
+ funcName: "calculateEffectiveBoundaries",
550
+ paramName: "blob"
551
+ });
552
+ }
553
+ const blobSize = blob.size;
554
+ if (end && end > blobSize || start && start < 0) {
555
+ throw new SerwistError("range-not-satisfiable", {
556
+ size: blobSize,
557
+ end,
558
+ start
559
+ });
560
+ }
561
+ let effectiveStart;
562
+ let effectiveEnd;
563
+ if (start !== undefined && end !== undefined) {
564
+ effectiveStart = start;
565
+ effectiveEnd = end + 1;
566
+ } else if (start !== undefined && end === undefined) {
567
+ effectiveStart = start;
568
+ effectiveEnd = blobSize;
569
+ } else if (end !== undefined && start === undefined) {
570
+ effectiveStart = blobSize - end;
571
+ effectiveEnd = blobSize;
572
+ }
573
+ return {
574
+ start: effectiveStart,
575
+ end: effectiveEnd
576
+ };
577
+ };
578
+
579
+ const parseRangeHeader = (rangeHeader)=>{
580
+ if (process.env.NODE_ENV !== "production") {
581
+ finalAssertExports.isType(rangeHeader, "string", {
582
+ moduleName: "@serwist/range-requests",
583
+ funcName: "parseRangeHeader",
584
+ paramName: "rangeHeader"
585
+ });
586
+ }
587
+ const normalizedRangeHeader = rangeHeader.trim().toLowerCase();
588
+ if (!normalizedRangeHeader.startsWith("bytes=")) {
589
+ throw new SerwistError("unit-must-be-bytes", {
590
+ normalizedRangeHeader
591
+ });
592
+ }
593
+ if (normalizedRangeHeader.includes(",")) {
594
+ throw new SerwistError("single-range-only", {
595
+ normalizedRangeHeader
596
+ });
597
+ }
598
+ const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader);
599
+ if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {
600
+ throw new SerwistError("invalid-range-values", {
601
+ normalizedRangeHeader
602
+ });
603
+ }
604
+ return {
605
+ start: rangeParts[1] === "" ? undefined : Number(rangeParts[1]),
606
+ end: rangeParts[2] === "" ? undefined : Number(rangeParts[2])
607
+ };
608
+ };
609
+
610
+ const createPartialResponse = async (request, originalResponse)=>{
611
+ try {
612
+ if (process.env.NODE_ENV !== "production") {
613
+ finalAssertExports.isInstance(request, Request, {
614
+ moduleName: "@serwist/range-requests",
615
+ funcName: "createPartialResponse",
616
+ paramName: "request"
617
+ });
618
+ finalAssertExports.isInstance(originalResponse, Response, {
619
+ moduleName: "@serwist/range-requests",
620
+ funcName: "createPartialResponse",
621
+ paramName: "originalResponse"
622
+ });
623
+ }
624
+ if (originalResponse.status === 206) {
625
+ return originalResponse;
626
+ }
627
+ const rangeHeader = request.headers.get("range");
628
+ if (!rangeHeader) {
629
+ throw new SerwistError("no-range-header");
630
+ }
631
+ const boundaries = parseRangeHeader(rangeHeader);
632
+ const originalBlob = await originalResponse.blob();
633
+ const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end);
634
+ const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end);
635
+ const slicedBlobSize = slicedBlob.size;
636
+ const slicedResponse = new Response(slicedBlob, {
637
+ status: 206,
638
+ statusText: "Partial Content",
639
+ headers: originalResponse.headers
640
+ });
641
+ slicedResponse.headers.set("Content-Length", String(slicedBlobSize));
642
+ slicedResponse.headers.set("Content-Range", `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + `${originalBlob.size}`);
643
+ return slicedResponse;
644
+ } catch (error) {
645
+ if (process.env.NODE_ENV !== "production") {
646
+ logger.warn("Unable to construct a partial response; returning a " + "416 Range Not Satisfiable response instead.");
647
+ logger.groupCollapsed("View details here.");
648
+ logger.log(error);
649
+ logger.log(request);
650
+ logger.log(originalResponse);
651
+ logger.groupEnd();
652
+ }
653
+ return new Response("", {
654
+ status: 416,
655
+ statusText: "Range Not Satisfiable"
656
+ });
657
+ }
658
+ };
659
+
660
+ class RangeRequestsPlugin {
661
+ cachedResponseWillBeUsed = async ({ request, cachedResponse })=>{
662
+ if (cachedResponse && request.headers.has("range")) {
663
+ return await createPartialResponse(request, cachedResponse);
664
+ }
665
+ return cachedResponse;
666
+ };
667
+ }
668
+
669
+ export { defaultHeadersToCheck as BROADCAST_UPDATE_DEFAULT_HEADERS, CACHE_UPDATED_MESSAGE_META as BROADCAST_UPDATE_MESSAGE_META, CACHE_UPDATED_MESSAGE_TYPE as BROADCAST_UPDATE_MESSAGE_TYPE, BroadcastCacheUpdate, BroadcastUpdatePlugin, CacheExpiration, CacheableResponse, CacheableResponsePlugin, ExpirationPlugin, RangeRequestsPlugin, createPartialResponse, responsesAreSame };
@@ -0,0 +1,22 @@
1
+ import { CacheFirst } from "./strategies/CacheFirst.js";
2
+ import { CacheOnly } from "./strategies/CacheOnly.js";
3
+ import type { NetworkFirstOptions } from "./strategies/NetworkFirst.js";
4
+ import { NetworkFirst } from "./strategies/NetworkFirst.js";
5
+ import type { NetworkOnlyOptions } from "./strategies/NetworkOnly.js";
6
+ import { NetworkOnly } from "./strategies/NetworkOnly.js";
7
+ import { StaleWhileRevalidate } from "./strategies/StaleWhileRevalidate.js";
8
+ import type { StrategyOptions } from "./strategies/Strategy.js";
9
+ import { Strategy } from "./strategies/Strategy.js";
10
+ import { StrategyHandler } from "./strategies/StrategyHandler.js";
11
+ declare global {
12
+ interface FetchEvent {
13
+ readonly preloadResponse: Promise<any>;
14
+ }
15
+ }
16
+ /**
17
+ * There are common caching strategies that most service workers will need
18
+ * and use. This module provides simple implementations of these strategies.
19
+ */
20
+ export { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate, Strategy, StrategyHandler };
21
+ export type { NetworkFirstOptions, NetworkOnlyOptions, StrategyOptions };
22
+ //# sourceMappingURL=index.strategies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.strategies.d.ts","sourceRoot":"","sources":["../src/index.strategies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAGlE,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,UAAU;QAElB,QAAQ,CAAC,eAAe,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;KACxC;CACF;AAED;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,oBAAoB,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC;AAE7G,YAAY,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,eAAe,EAAE,CAAC"}