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.
- package/LICENSE +21 -0
- package/README.md +1 -0
- package/dist/NavigationRoute.d.ts +57 -0
- package/dist/NavigationRoute.d.ts.map +1 -0
- package/dist/PrecacheRoute.d.ts +17 -0
- package/dist/PrecacheRoute.d.ts.map +1 -0
- package/dist/PrecacheStrategy.d.ts +66 -0
- package/dist/PrecacheStrategy.d.ts.map +1 -0
- package/dist/RegExpRoute.d.ts +24 -0
- package/dist/RegExpRoute.d.ts.map +1 -0
- package/dist/Route.d.ts +33 -0
- package/dist/Route.d.ts.map +1 -0
- package/dist/Serwist.d.ts +331 -0
- package/dist/Serwist.d.ts.map +1 -0
- package/dist/cacheNames.d.ts +20 -0
- package/dist/cacheNames.d.ts.map +1 -0
- package/dist/chunks/NetworkOnly.js +599 -0
- package/dist/chunks/PrecacheFallbackPlugin.js +634 -0
- package/dist/chunks/Serwist.js +1034 -0
- package/dist/chunks/registerQuotaErrorCallback.js +17 -0
- package/dist/chunks/resultingClientExists.js +32 -0
- package/dist/chunks/timeout.js +400 -0
- package/dist/chunks/waitUntil.js +24 -0
- package/dist/cleanupOutdatedCaches.d.ts +6 -0
- package/dist/cleanupOutdatedCaches.d.ts.map +1 -0
- package/dist/clientsClaim.d.ts +6 -0
- package/dist/clientsClaim.d.ts.map +1 -0
- package/dist/constants.d.ts +15 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/copyResponse.d.ts +20 -0
- package/dist/copyResponse.d.ts.map +1 -0
- package/dist/disableDevLogs.d.ts +7 -0
- package/dist/disableDevLogs.d.ts.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.internal.d.ts +16 -0
- package/dist/index.internal.d.ts.map +1 -0
- package/dist/index.internal.js +24 -0
- package/dist/index.js +27 -0
- package/dist/index.legacy.d.ts +32 -0
- package/dist/index.legacy.d.ts.map +1 -0
- package/dist/index.legacy.js +640 -0
- package/dist/index.plugins.d.ts +41 -0
- package/dist/index.plugins.d.ts.map +1 -0
- package/dist/index.plugins.js +669 -0
- package/dist/index.strategies.d.ts +22 -0
- package/dist/index.strategies.d.ts.map +1 -0
- package/dist/index.strategies.js +144 -0
- package/dist/legacy/PrecacheController.d.ts +146 -0
- package/dist/legacy/PrecacheController.d.ts.map +1 -0
- package/dist/legacy/PrecacheFallbackPlugin.d.ts +62 -0
- package/dist/legacy/PrecacheFallbackPlugin.d.ts.map +1 -0
- package/dist/legacy/PrecacheRoute.d.ts +19 -0
- package/dist/legacy/PrecacheRoute.d.ts.map +1 -0
- package/dist/legacy/Router.d.ts +151 -0
- package/dist/legacy/Router.d.ts.map +1 -0
- package/dist/legacy/addPlugins.d.ts +9 -0
- package/dist/legacy/addPlugins.d.ts.map +1 -0
- package/dist/legacy/addRoute.d.ts +16 -0
- package/dist/legacy/addRoute.d.ts.map +1 -0
- package/dist/legacy/createHandlerBoundToURL.d.ts +18 -0
- package/dist/legacy/createHandlerBoundToURL.d.ts.map +1 -0
- package/dist/legacy/fallbacks.d.ts +59 -0
- package/dist/legacy/fallbacks.d.ts.map +1 -0
- package/dist/legacy/getCacheKeyForURL.d.ts +20 -0
- package/dist/legacy/getCacheKeyForURL.d.ts.map +1 -0
- package/dist/legacy/handlePrecaching.d.ts +54 -0
- package/dist/legacy/handlePrecaching.d.ts.map +1 -0
- package/dist/legacy/installSerwist.d.ts +15 -0
- package/dist/legacy/installSerwist.d.ts.map +1 -0
- package/dist/legacy/matchPrecache.d.ts +15 -0
- package/dist/legacy/matchPrecache.d.ts.map +1 -0
- package/dist/legacy/precache.d.ts +20 -0
- package/dist/legacy/precache.d.ts.map +1 -0
- package/dist/legacy/precacheAndRoute.d.ts +15 -0
- package/dist/legacy/precacheAndRoute.d.ts.map +1 -0
- package/dist/legacy/registerRoute.d.ts +16 -0
- package/dist/legacy/registerRoute.d.ts.map +1 -0
- package/dist/legacy/registerRuntimeCaching.d.ts +11 -0
- package/dist/legacy/registerRuntimeCaching.d.ts.map +1 -0
- package/dist/legacy/setCatchHandler.d.ts +10 -0
- package/dist/legacy/setCatchHandler.d.ts.map +1 -0
- package/dist/legacy/setDefaultHandler.d.ts +13 -0
- package/dist/legacy/setDefaultHandler.d.ts.map +1 -0
- package/dist/legacy/singletonPrecacheController.d.ts +34 -0
- package/dist/legacy/singletonPrecacheController.d.ts.map +1 -0
- package/dist/legacy/singletonRouter.d.ts +41 -0
- package/dist/legacy/singletonRouter.d.ts.map +1 -0
- package/dist/legacy/unregisterRoute.d.ts +9 -0
- package/dist/legacy/unregisterRoute.d.ts.map +1 -0
- package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts +16 -0
- package/dist/legacy/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -0
- package/dist/legacy/utils/getCacheKeyForURL.d.ts +14 -0
- package/dist/legacy/utils/getCacheKeyForURL.d.ts.map +1 -0
- package/dist/models/messages/messageGenerator.d.ts +4 -0
- package/dist/models/messages/messageGenerator.d.ts.map +1 -0
- package/dist/models/messages/messages.d.ts +44 -0
- package/dist/models/messages/messages.d.ts.map +1 -0
- package/dist/models/pluginEvents.d.ts +10 -0
- package/dist/models/pluginEvents.d.ts.map +1 -0
- package/dist/models/quotaErrorCallbacks.d.ts +3 -0
- package/dist/models/quotaErrorCallbacks.d.ts.map +1 -0
- package/dist/navigationPreload.d.ts +24 -0
- package/dist/navigationPreload.d.ts.map +1 -0
- package/dist/parseRoute.d.ts +16 -0
- package/dist/parseRoute.d.ts.map +1 -0
- package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts +23 -0
- package/dist/plugins/backgroundSync/BackgroundSyncPlugin.d.ts.map +1 -0
- package/dist/plugins/backgroundSync/Queue.d.ts +166 -0
- package/dist/plugins/backgroundSync/Queue.d.ts.map +1 -0
- package/dist/plugins/backgroundSync/QueueDb.d.ts +90 -0
- package/dist/plugins/backgroundSync/QueueDb.d.ts.map +1 -0
- package/dist/plugins/backgroundSync/QueueStore.d.ts +75 -0
- package/dist/plugins/backgroundSync/QueueStore.d.ts.map +1 -0
- package/dist/plugins/backgroundSync/StorableRequest.d.ts +51 -0
- package/dist/plugins/backgroundSync/StorableRequest.d.ts.map +1 -0
- package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts +45 -0
- package/dist/plugins/broadcastUpdate/BroadcastCacheUpdate.d.ts.map +1 -0
- package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts +27 -0
- package/dist/plugins/broadcastUpdate/BroadcastUpdatePlugin.d.ts.map +1 -0
- package/dist/plugins/broadcastUpdate/constants.d.ts +5 -0
- package/dist/plugins/broadcastUpdate/constants.d.ts.map +1 -0
- package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts +11 -0
- package/dist/plugins/broadcastUpdate/responsesAreSame.d.ts.map +1 -0
- package/dist/plugins/broadcastUpdate/types.d.ts +34 -0
- package/dist/plugins/broadcastUpdate/types.d.ts.map +1 -0
- package/dist/plugins/cacheableResponse/CacheableResponse.d.ts +40 -0
- package/dist/plugins/cacheableResponse/CacheableResponse.d.ts.map +1 -0
- package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts +27 -0
- package/dist/plugins/cacheableResponse/CacheableResponsePlugin.d.ts.map +1 -0
- package/dist/plugins/expiration/CacheExpiration.d.ts +66 -0
- package/dist/plugins/expiration/CacheExpiration.d.ts.map +1 -0
- package/dist/plugins/expiration/ExpirationPlugin.d.ts +116 -0
- package/dist/plugins/expiration/ExpirationPlugin.d.ts.map +1 -0
- package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts +73 -0
- package/dist/plugins/expiration/models/CacheTimestampsModel.d.ts.map +1 -0
- package/dist/plugins/googleAnalytics/constants.d.ts +10 -0
- package/dist/plugins/googleAnalytics/constants.d.ts.map +1 -0
- package/dist/plugins/googleAnalytics/initialize.d.ts +30 -0
- package/dist/plugins/googleAnalytics/initialize.d.ts.map +1 -0
- package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts +53 -0
- package/dist/plugins/precaching/PrecacheFallbackPlugin.d.ts.map +1 -0
- package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts +19 -0
- package/dist/plugins/rangeRequests/RangeRequestsPlugin.d.ts.map +1 -0
- package/dist/plugins/rangeRequests/createPartialResponse.d.ts +18 -0
- package/dist/plugins/rangeRequests/createPartialResponse.d.ts.map +1 -0
- package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts +14 -0
- package/dist/plugins/rangeRequests/utils/calculateEffectiveBoundaries.d.ts.map +1 -0
- package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts +12 -0
- package/dist/plugins/rangeRequests/utils/parseRangeHeader.d.ts.map +1 -0
- package/dist/registerQuotaErrorCallback.d.ts +8 -0
- package/dist/registerQuotaErrorCallback.d.ts.map +1 -0
- package/dist/setCacheNameDetails.d.ts +9 -0
- package/dist/setCacheNameDetails.d.ts.map +1 -0
- package/dist/strategies/CacheFirst.d.ts +23 -0
- package/dist/strategies/CacheFirst.d.ts.map +1 -0
- package/dist/strategies/CacheOnly.d.ts +20 -0
- package/dist/strategies/CacheOnly.d.ts.map +1 -0
- package/dist/strategies/NetworkFirst.d.ts +61 -0
- package/dist/strategies/NetworkFirst.d.ts.map +1 -0
- package/dist/strategies/NetworkOnly.d.ts +32 -0
- package/dist/strategies/NetworkOnly.d.ts.map +1 -0
- package/dist/strategies/StaleWhileRevalidate.d.ts +35 -0
- package/dist/strategies/StaleWhileRevalidate.d.ts.map +1 -0
- package/dist/strategies/Strategy.d.ts +83 -0
- package/dist/strategies/Strategy.d.ts.map +1 -0
- package/dist/strategies/StrategyHandler.d.ts +189 -0
- package/dist/strategies/StrategyHandler.d.ts.map +1 -0
- package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts +3 -0
- package/dist/strategies/plugins/cacheOkAndOpaquePlugin.d.ts.map +1 -0
- package/dist/strategies/utils/messages.d.ts +5 -0
- package/dist/strategies/utils/messages.d.ts.map +1 -0
- package/dist/types.d.ts +317 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/Deferred.d.ts +19 -0
- package/dist/utils/Deferred.d.ts.map +1 -0
- package/dist/utils/PrecacheCacheKeyPlugin.d.ts +16 -0
- package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -0
- package/dist/utils/PrecacheInstallReportPlugin.d.ts +14 -0
- package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +1 -0
- package/dist/utils/SerwistError.d.ts +24 -0
- package/dist/utils/SerwistError.d.ts.map +1 -0
- package/dist/utils/assert.d.ts +11 -0
- package/dist/utils/assert.d.ts.map +1 -0
- package/dist/utils/cacheMatchIgnoreParams.d.ts +15 -0
- package/dist/utils/cacheMatchIgnoreParams.d.ts.map +1 -0
- package/dist/utils/cacheNames.d.ts +40 -0
- package/dist/utils/cacheNames.d.ts.map +1 -0
- package/dist/utils/canConstructReadableStream.d.ts +12 -0
- package/dist/utils/canConstructReadableStream.d.ts.map +1 -0
- package/dist/utils/canConstructResponseFromBodyStream.d.ts +11 -0
- package/dist/utils/canConstructResponseFromBodyStream.d.ts.map +1 -0
- package/dist/utils/createCacheKey.d.ts +16 -0
- package/dist/utils/createCacheKey.d.ts.map +1 -0
- package/dist/utils/deleteOutdatedCaches.d.ts +18 -0
- package/dist/utils/deleteOutdatedCaches.d.ts.map +1 -0
- package/dist/utils/dontWaitFor.d.ts +7 -0
- package/dist/utils/dontWaitFor.d.ts.map +1 -0
- package/dist/utils/executeQuotaErrorCallbacks.d.ts +8 -0
- package/dist/utils/executeQuotaErrorCallbacks.d.ts.map +1 -0
- package/dist/utils/generateURLVariations.d.ts +12 -0
- package/dist/utils/generateURLVariations.d.ts.map +1 -0
- package/dist/utils/getFriendlyURL.d.ts +3 -0
- package/dist/utils/getFriendlyURL.d.ts.map +1 -0
- package/dist/utils/logger.d.ts +24 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/normalizeHandler.d.ts +10 -0
- package/dist/utils/normalizeHandler.d.ts.map +1 -0
- package/dist/utils/pluginUtils.d.ts +5 -0
- package/dist/utils/pluginUtils.d.ts.map +1 -0
- package/dist/utils/printCleanupDetails.d.ts +6 -0
- package/dist/utils/printCleanupDetails.d.ts.map +1 -0
- package/dist/utils/printInstallDetails.d.ts +7 -0
- package/dist/utils/printInstallDetails.d.ts.map +1 -0
- package/dist/utils/removeIgnoredSearchParams.d.ts +12 -0
- package/dist/utils/removeIgnoredSearchParams.d.ts.map +1 -0
- package/dist/utils/resultingClientExists.d.ts +12 -0
- package/dist/utils/resultingClientExists.d.ts.map +1 -0
- package/dist/utils/timeout.d.ts +10 -0
- package/dist/utils/timeout.d.ts.map +1 -0
- package/dist/utils/waitUntil.d.ts +11 -0
- package/dist/utils/waitUntil.d.ts.map +1 -0
- package/dist/utils/welcome.d.ts +2 -0
- package/dist/utils/welcome.d.ts.map +1 -0
- package/package.json +85 -0
- package/src/NavigationRoute.ts +119 -0
- package/src/PrecacheRoute.ts +46 -0
- package/src/PrecacheStrategy.ts +239 -0
- package/src/RegExpRoute.ts +74 -0
- package/src/Route.ts +67 -0
- package/src/Serwist.ts +920 -0
- package/src/cacheNames.ts +39 -0
- package/src/cleanupOutdatedCaches.ts +32 -0
- package/src/clientsClaim.ts +18 -0
- package/src/constants.ts +24 -0
- package/src/copyResponse.ts +60 -0
- package/src/disableDevLogs.ts +10 -0
- package/src/index.internal.ts +33 -0
- package/src/index.legacy.ts +66 -0
- package/src/index.plugins.ts +95 -0
- package/src/index.strategies.ts +26 -0
- package/src/index.ts +39 -0
- package/src/legacy/PrecacheController.ts +337 -0
- package/src/legacy/PrecacheFallbackPlugin.ts +93 -0
- package/src/legacy/PrecacheRoute.ts +48 -0
- package/src/legacy/Router.ts +484 -0
- package/src/legacy/addPlugins.ts +21 -0
- package/src/legacy/addRoute.ts +29 -0
- package/src/legacy/createHandlerBoundToURL.ts +30 -0
- package/src/legacy/fallbacks.ts +94 -0
- package/src/legacy/getCacheKeyForURL.ts +32 -0
- package/src/legacy/handlePrecaching.ts +86 -0
- package/src/legacy/installSerwist.ts +19 -0
- package/src/legacy/matchPrecache.ts +26 -0
- package/src/legacy/precache.ts +31 -0
- package/src/legacy/precacheAndRoute.ts +28 -0
- package/src/legacy/registerRoute.ts +27 -0
- package/src/legacy/registerRuntimeCaching.ts +17 -0
- package/src/legacy/setCatchHandler.ts +21 -0
- package/src/legacy/setDefaultHandler.ts +24 -0
- package/src/legacy/singletonPrecacheController.ts +53 -0
- package/src/legacy/singletonRouter.ts +70 -0
- package/src/legacy/unregisterRoute.ts +12 -0
- package/src/legacy/utils/PrecacheCacheKeyPlugin.ts +33 -0
- package/src/legacy/utils/getCacheKeyForURL.ts +36 -0
- package/src/models/messages/messageGenerator.ts +29 -0
- package/src/models/messages/messages.ts +233 -0
- package/src/models/pluginEvents.ts +17 -0
- package/src/models/quotaErrorCallbacks.ts +13 -0
- package/src/navigationPreload.ts +68 -0
- package/src/parseRoute.ts +78 -0
- package/src/plugins/backgroundSync/BackgroundSyncPlugin.ts +38 -0
- package/src/plugins/backgroundSync/Queue.ts +440 -0
- package/src/plugins/backgroundSync/QueueDb.ts +176 -0
- package/src/plugins/backgroundSync/QueueStore.ts +160 -0
- package/src/plugins/backgroundSync/StorableRequest.ts +142 -0
- package/src/plugins/broadcastUpdate/BroadcastCacheUpdate.ts +161 -0
- package/src/plugins/broadcastUpdate/BroadcastUpdatePlugin.ts +42 -0
- package/src/plugins/broadcastUpdate/constants.ts +12 -0
- package/src/plugins/broadcastUpdate/responsesAreSame.ts +49 -0
- package/src/plugins/broadcastUpdate/types.ts +37 -0
- package/src/plugins/cacheableResponse/CacheableResponse.ts +144 -0
- package/src/plugins/cacheableResponse/CacheableResponsePlugin.ts +45 -0
- package/src/plugins/expiration/CacheExpiration.ts +193 -0
- package/src/plugins/expiration/ExpirationPlugin.ts +300 -0
- package/src/plugins/expiration/models/CacheTimestampsModel.ts +184 -0
- package/src/plugins/googleAnalytics/constants.ts +22 -0
- package/src/plugins/googleAnalytics/initialize.ts +209 -0
- package/src/plugins/precaching/PrecacheFallbackPlugin.ts +83 -0
- package/src/plugins/rangeRequests/RangeRequestsPlugin.ts +38 -0
- package/src/plugins/rangeRequests/createPartialResponse.ts +93 -0
- package/src/plugins/rangeRequests/utils/calculateEffectiveBoundaries.ts +59 -0
- package/src/plugins/rangeRequests/utils/parseRangeHeader.ts +55 -0
- package/src/registerQuotaErrorCallback.ts +34 -0
- package/src/setCacheNameDetails.ts +53 -0
- package/src/strategies/CacheFirst.ts +88 -0
- package/src/strategies/CacheOnly.ts +59 -0
- package/src/strategies/NetworkFirst.ts +229 -0
- package/src/strategies/NetworkOnly.ts +98 -0
- package/src/strategies/StaleWhileRevalidate.ts +110 -0
- package/src/strategies/Strategy.ts +204 -0
- package/src/strategies/StrategyHandler.ts +554 -0
- package/src/strategies/plugins/cacheOkAndOpaquePlugin.ts +26 -0
- package/src/strategies/utils/messages.ts +21 -0
- package/src/types.ts +358 -0
- package/src/utils/Deferred.ts +33 -0
- package/src/utils/PrecacheCacheKeyPlugin.ts +33 -0
- package/src/utils/PrecacheInstallReportPlugin.ts +47 -0
- package/src/utils/SerwistError.ts +41 -0
- package/src/utils/assert.ts +89 -0
- package/src/utils/cacheMatchIgnoreParams.ts +54 -0
- package/src/utils/cacheNames.ts +87 -0
- package/src/utils/canConstructReadableStream.ts +34 -0
- package/src/utils/canConstructResponseFromBodyStream.ts +37 -0
- package/src/utils/createCacheKey.ts +68 -0
- package/src/utils/deleteOutdatedCaches.ts +40 -0
- package/src/utils/dontWaitFor.ts +16 -0
- package/src/utils/executeQuotaErrorCallbacks.ts +33 -0
- package/src/utils/generateURLVariations.ts +55 -0
- package/src/utils/getFriendlyURL.ts +16 -0
- package/src/utils/logger.ts +95 -0
- package/src/utils/normalizeHandler.ts +40 -0
- package/src/utils/pluginUtils.ts +15 -0
- package/src/utils/printCleanupDetails.ts +38 -0
- package/src/utils/printInstallDetails.ts +53 -0
- package/src/utils/removeIgnoredSearchParams.ts +29 -0
- package/src/utils/resultingClientExists.ts +58 -0
- package/src/utils/timeout.ts +19 -0
- package/src/utils/waitUntil.ts +21 -0
- package/src/utils/welcome.ts +19 -0
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2018 Google LLC
|
|
3
|
+
|
|
4
|
+
Use of this source code is governed by an MIT-style
|
|
5
|
+
license that can be found in the LICENSE file or at
|
|
6
|
+
https://opensource.org/licenses/MIT.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { RouteHandler, RouteHandlerCallbackOptions, RouteHandlerObject, RouteMatchCallback, RouteMatchCallbackOptions } from "../types.js";
|
|
10
|
+
import { assert } from "../utils/assert.js";
|
|
11
|
+
import { SerwistError } from "../utils/SerwistError.js";
|
|
12
|
+
import { getFriendlyURL } from "../utils/getFriendlyURL.js";
|
|
13
|
+
import { logger } from "../utils/logger.js";
|
|
14
|
+
import type { Route } from "../Route.js";
|
|
15
|
+
import type { HTTPMethod } from "../constants.js";
|
|
16
|
+
import { defaultMethod } from "../constants.js";
|
|
17
|
+
import { parseRoute } from "../parseRoute.js";
|
|
18
|
+
import { normalizeHandler } from "../utils/normalizeHandler.js";
|
|
19
|
+
|
|
20
|
+
declare const self: ServiceWorkerGlobalScope;
|
|
21
|
+
|
|
22
|
+
type RequestArgs = string | [string, RequestInit?];
|
|
23
|
+
|
|
24
|
+
interface CacheURLsMessageData {
|
|
25
|
+
type: string;
|
|
26
|
+
payload: {
|
|
27
|
+
urlsToCache: RequestArgs[];
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* `Router` can be used to process a `FetchEvent` using one or more `Route`(s), responding with a `Response`
|
|
33
|
+
* if a matching route exists.
|
|
34
|
+
*
|
|
35
|
+
* If no `Route` matches given a `Request`, the `Router` will use the default handler if one is defined.
|
|
36
|
+
*
|
|
37
|
+
* Should the matching Route throw an error, the Router will use the catch handler if one is defined to
|
|
38
|
+
* gracefully deal with issues and respond with a `Request`.
|
|
39
|
+
*
|
|
40
|
+
* If a `Request` matches multiple routes, the earliest registered route will be used to respond to the `Request`.
|
|
41
|
+
* @deprecated
|
|
42
|
+
*/
|
|
43
|
+
export class Router {
|
|
44
|
+
private readonly _routes: Map<HTTPMethod, Route[]>;
|
|
45
|
+
private readonly _defaultHandlerMap: Map<HTTPMethod, RouteHandlerObject>;
|
|
46
|
+
private _fetchListenerHandler: ((ev: FetchEvent) => void) | null = null;
|
|
47
|
+
private _cacheListenerHandler: ((ev: ExtendableMessageEvent) => void) | null = null;
|
|
48
|
+
private _catchHandler?: RouteHandlerObject;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Initializes a new Router.
|
|
52
|
+
*/
|
|
53
|
+
constructor() {
|
|
54
|
+
this._routes = new Map();
|
|
55
|
+
this._defaultHandlerMap = new Map();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @returns routes A `Map` of HTTP method name (`'GET'`, etc.) to an array of all the corresponding `Route`
|
|
60
|
+
* instances that are registered.
|
|
61
|
+
*/
|
|
62
|
+
get routes(): Map<HTTPMethod, Route[]> {
|
|
63
|
+
return this._routes;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Adds a `fetch` event listener to respond to events when a `Route` matches
|
|
68
|
+
* the event's request. Effectively no-op if `addFEtchListener` has been
|
|
69
|
+
* called, but `removeFetchListener` has not.
|
|
70
|
+
*/
|
|
71
|
+
addFetchListener(): void {
|
|
72
|
+
if (!this._fetchListenerHandler) {
|
|
73
|
+
this._fetchListenerHandler = (event) => {
|
|
74
|
+
const { request } = event;
|
|
75
|
+
const responsePromise = this.handleRequest({ request, event });
|
|
76
|
+
if (responsePromise) {
|
|
77
|
+
event.respondWith(responsePromise);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
self.addEventListener("fetch", this._fetchListenerHandler);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Removes `fetch` event listener added by `addFetchListener`.
|
|
86
|
+
* Effectively no-op if either `addFetchListener` has not been called or,
|
|
87
|
+
* if it has, so has `removeFetchListener`.
|
|
88
|
+
*/
|
|
89
|
+
removeFetchListener(): void {
|
|
90
|
+
if (this._fetchListenerHandler) {
|
|
91
|
+
self.removeEventListener("fetch", this._fetchListenerHandler);
|
|
92
|
+
this._fetchListenerHandler = null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Adds a `message` event listener for URLs to cache from the window.
|
|
98
|
+
* This is useful to cache resources loaded on the page prior to when the
|
|
99
|
+
* service worker started controlling it. Effectively no-op if `addCacheListener`
|
|
100
|
+
* has been called, but `removeCacheListener` hasn't.
|
|
101
|
+
*
|
|
102
|
+
* The format of the message data sent from the window should be as follows.
|
|
103
|
+
* Where the `urlsToCache` array may consist of URL strings or an array of
|
|
104
|
+
* URL string + `requestInit` object (the same as you'd pass to `fetch()`).
|
|
105
|
+
*
|
|
106
|
+
* ```
|
|
107
|
+
* {
|
|
108
|
+
* type: 'CACHE_URLS',
|
|
109
|
+
* payload: {
|
|
110
|
+
* urlsToCache: [
|
|
111
|
+
* './script1.js',
|
|
112
|
+
* './script2.js',
|
|
113
|
+
* ['./script3.js', {mode: 'no-cors'}],
|
|
114
|
+
* ],
|
|
115
|
+
* },
|
|
116
|
+
* }
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
addCacheListener(): void {
|
|
120
|
+
if (!this._cacheListenerHandler) {
|
|
121
|
+
this._cacheListenerHandler = (event) => {
|
|
122
|
+
if (event.data && event.data.type === "CACHE_URLS") {
|
|
123
|
+
const { payload }: CacheURLsMessageData = event.data;
|
|
124
|
+
|
|
125
|
+
if (process.env.NODE_ENV !== "production") {
|
|
126
|
+
logger.debug("Caching URLs from the window", payload.urlsToCache);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const requestPromises = Promise.all(
|
|
130
|
+
payload.urlsToCache.map((entry: string | [string, RequestInit?]) => {
|
|
131
|
+
if (typeof entry === "string") {
|
|
132
|
+
entry = [entry];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const request = new Request(...entry);
|
|
136
|
+
return this.handleRequest({ request, event });
|
|
137
|
+
}),
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
event.waitUntil(requestPromises);
|
|
141
|
+
|
|
142
|
+
// If a MessageChannel was used, reply to the message on success.
|
|
143
|
+
if (event.ports?.[0]) {
|
|
144
|
+
void requestPromises.then(() => event.ports[0].postMessage(true));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
self.addEventListener("message", this._cacheListenerHandler);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Removes the `message` event listener added by `addCacheListener`.
|
|
154
|
+
* Effectively no-op if either `addCacheListener` has not been called or,
|
|
155
|
+
* if it has, so has `removeCacheListener`.
|
|
156
|
+
*/
|
|
157
|
+
removeCacheListener(): void {
|
|
158
|
+
if (this._cacheListenerHandler) {
|
|
159
|
+
self.removeEventListener("message", this._cacheListenerHandler);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Apply the routing rules to a `FetchEvent` object to get a `Response` from an
|
|
165
|
+
* appropriate `Route`'s handler.
|
|
166
|
+
*
|
|
167
|
+
* @param options
|
|
168
|
+
* @returns A promise is returned if a registered route can handle the request.
|
|
169
|
+
* If there is no matching route and there's no `defaultHandler`, `undefined`
|
|
170
|
+
* is returned.
|
|
171
|
+
*/
|
|
172
|
+
handleRequest({
|
|
173
|
+
request,
|
|
174
|
+
event,
|
|
175
|
+
}: {
|
|
176
|
+
/**
|
|
177
|
+
* The request to handle.
|
|
178
|
+
*/
|
|
179
|
+
request: Request;
|
|
180
|
+
/**
|
|
181
|
+
* The event that triggered the request.
|
|
182
|
+
*/
|
|
183
|
+
event: ExtendableEvent;
|
|
184
|
+
}): Promise<Response> | undefined {
|
|
185
|
+
if (process.env.NODE_ENV !== "production") {
|
|
186
|
+
assert!.isInstance(request, Request, {
|
|
187
|
+
moduleName: "serwist/legacy",
|
|
188
|
+
className: "Router",
|
|
189
|
+
funcName: "handleRequest",
|
|
190
|
+
paramName: "options.request",
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const url = new URL(request.url, location.href);
|
|
195
|
+
if (!url.protocol.startsWith("http")) {
|
|
196
|
+
if (process.env.NODE_ENV !== "production") {
|
|
197
|
+
logger.debug("Router only supports URLs that start with 'http'.");
|
|
198
|
+
}
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const sameOrigin = url.origin === location.origin;
|
|
203
|
+
const { params, route } = this.findMatchingRoute({
|
|
204
|
+
event,
|
|
205
|
+
request,
|
|
206
|
+
sameOrigin,
|
|
207
|
+
url,
|
|
208
|
+
});
|
|
209
|
+
let handler = route?.handler;
|
|
210
|
+
|
|
211
|
+
const debugMessages = [];
|
|
212
|
+
if (process.env.NODE_ENV !== "production") {
|
|
213
|
+
if (handler) {
|
|
214
|
+
debugMessages.push(["Found a route to handle this request:", route]);
|
|
215
|
+
|
|
216
|
+
if (params) {
|
|
217
|
+
debugMessages.push([`Passing the following params to the route's handler:`, params]);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// If we don't have a handler because there was no matching route, then
|
|
223
|
+
// fall back to defaultHandler if that's defined.
|
|
224
|
+
const method = request.method as HTTPMethod;
|
|
225
|
+
if (!handler && this._defaultHandlerMap.has(method)) {
|
|
226
|
+
if (process.env.NODE_ENV !== "production") {
|
|
227
|
+
debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`);
|
|
228
|
+
}
|
|
229
|
+
handler = this._defaultHandlerMap.get(method);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (!handler) {
|
|
233
|
+
if (process.env.NODE_ENV !== "production") {
|
|
234
|
+
// No handler so Serwist will do nothing. If logs is set of debug
|
|
235
|
+
// i.e. verbose, we should print out this information.
|
|
236
|
+
logger.debug(`No route found for: ${getFriendlyURL(url)}`);
|
|
237
|
+
}
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (process.env.NODE_ENV !== "production") {
|
|
242
|
+
// We have a handler, meaning Serwist is going to handle the route.
|
|
243
|
+
// print the routing details to the console.
|
|
244
|
+
logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
|
|
245
|
+
|
|
246
|
+
for (const msg of debugMessages) {
|
|
247
|
+
if (Array.isArray(msg)) {
|
|
248
|
+
logger.log(...msg);
|
|
249
|
+
} else {
|
|
250
|
+
logger.log(msg);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
logger.groupEnd();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Wrap in try and catch in case the handle method throws a synchronous
|
|
258
|
+
// error. It should still callback to the catch handler.
|
|
259
|
+
let responsePromise: Promise<Response>;
|
|
260
|
+
try {
|
|
261
|
+
responsePromise = handler.handle({ url, request, event, params });
|
|
262
|
+
} catch (err) {
|
|
263
|
+
responsePromise = Promise.reject(err);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Get route's catch handler, if it exists
|
|
267
|
+
const catchHandler = route?.catchHandler;
|
|
268
|
+
|
|
269
|
+
if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
|
|
270
|
+
responsePromise = responsePromise.catch(async (err) => {
|
|
271
|
+
// If there's a route catch handler, process that first
|
|
272
|
+
if (catchHandler) {
|
|
273
|
+
if (process.env.NODE_ENV !== "production") {
|
|
274
|
+
// Still include URL here as it will be async from the console group
|
|
275
|
+
// and may not make sense without the URL
|
|
276
|
+
logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
|
|
277
|
+
logger.error("Error thrown by:", route);
|
|
278
|
+
logger.error(err);
|
|
279
|
+
logger.groupEnd();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
try {
|
|
283
|
+
return await catchHandler.handle({ url, request, event, params });
|
|
284
|
+
} catch (catchErr) {
|
|
285
|
+
if (catchErr instanceof Error) {
|
|
286
|
+
err = catchErr;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (this._catchHandler) {
|
|
292
|
+
if (process.env.NODE_ENV !== "production") {
|
|
293
|
+
// Still include URL here as it will be async from the console group
|
|
294
|
+
// and may not make sense without the URL
|
|
295
|
+
logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
|
|
296
|
+
logger.error("Error thrown by:", route);
|
|
297
|
+
logger.error(err);
|
|
298
|
+
logger.groupEnd();
|
|
299
|
+
}
|
|
300
|
+
return this._catchHandler.handle({ url, request, event });
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
throw err;
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return responsePromise;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Checks a request and URL (and optionally an event) against the list of
|
|
312
|
+
* registered routes, and if there's a match, returns the corresponding
|
|
313
|
+
* route along with any params generated by the match.
|
|
314
|
+
*
|
|
315
|
+
* @param options
|
|
316
|
+
* @returns An object with `route` and `params` properties. They are populated
|
|
317
|
+
* if a matching route was found or `undefined` otherwise.
|
|
318
|
+
*/
|
|
319
|
+
findMatchingRoute({ url, sameOrigin, request, event }: RouteMatchCallbackOptions): {
|
|
320
|
+
route?: Route;
|
|
321
|
+
params?: RouteHandlerCallbackOptions["params"];
|
|
322
|
+
} {
|
|
323
|
+
const routes = this._routes.get(request.method as HTTPMethod) || [];
|
|
324
|
+
for (const route of routes) {
|
|
325
|
+
let params: Promise<any> | undefined;
|
|
326
|
+
// route.match returns type any, not possible to change right now.
|
|
327
|
+
const matchResult = route.match({ url, sameOrigin, request, event });
|
|
328
|
+
if (matchResult) {
|
|
329
|
+
if (process.env.NODE_ENV !== "production") {
|
|
330
|
+
// Warn developers that using an async matchCallback is almost always
|
|
331
|
+
// not the right thing to do.
|
|
332
|
+
if (matchResult instanceof Promise) {
|
|
333
|
+
logger.warn(
|
|
334
|
+
`While routing ${getFriendlyURL(
|
|
335
|
+
url,
|
|
336
|
+
)}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`,
|
|
337
|
+
route,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// See https://github.com/GoogleChrome/workbox/issues/2079
|
|
343
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
344
|
+
params = matchResult;
|
|
345
|
+
if (Array.isArray(params) && params.length === 0) {
|
|
346
|
+
// Instead of passing an empty array in as params, use undefined.
|
|
347
|
+
params = undefined;
|
|
348
|
+
} else if (
|
|
349
|
+
matchResult.constructor === Object && // eslint-disable-line
|
|
350
|
+
Object.keys(matchResult).length === 0
|
|
351
|
+
) {
|
|
352
|
+
// Instead of passing an empty object in as params, use undefined.
|
|
353
|
+
params = undefined;
|
|
354
|
+
} else if (typeof matchResult === "boolean") {
|
|
355
|
+
// For the boolean value true (rather than just something truth-y),
|
|
356
|
+
// don't set params.
|
|
357
|
+
// See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
|
|
358
|
+
params = undefined;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Return early if have a match.
|
|
362
|
+
return { route, params };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
// If no match was found above, return and empty object.
|
|
366
|
+
return {};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Define a default `handler` that's called when no routes explicitly
|
|
371
|
+
* match the incoming request.
|
|
372
|
+
*
|
|
373
|
+
* Each HTTP method (`'GET'`, `'POST'`, etc.) gets its own default handler.
|
|
374
|
+
*
|
|
375
|
+
* Without a default handler, unmatched requests will go against the
|
|
376
|
+
* network as if there were no service worker present.
|
|
377
|
+
*
|
|
378
|
+
* @param handler A callback function that returns a `Promise` resulting in a `Response`.
|
|
379
|
+
* @param method The HTTP method to associate with this default handler. Each method
|
|
380
|
+
* has its own default. Defaults to `'GET'`.
|
|
381
|
+
*/
|
|
382
|
+
setDefaultHandler(handler: RouteHandler, method: HTTPMethod = defaultMethod): void {
|
|
383
|
+
this._defaultHandlerMap.set(method, normalizeHandler(handler));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* If a `Route` throws an error while handling a request, this `handler`
|
|
388
|
+
* will be called and given a chance to provide a response.
|
|
389
|
+
*
|
|
390
|
+
* @param handler A callback function that returns a Promise resulting
|
|
391
|
+
* in a Response.
|
|
392
|
+
*/
|
|
393
|
+
setCatchHandler(handler: RouteHandler): void {
|
|
394
|
+
this._catchHandler = normalizeHandler(handler);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Registers a `RegExp`, string, or function with a caching
|
|
399
|
+
* strategy to the `Router`.
|
|
400
|
+
*
|
|
401
|
+
* @param capture If the capture param is a `Route`, all other arguments will be ignored.
|
|
402
|
+
* @param handler A callback function that returns a `Promise` resulting in a `Response`.
|
|
403
|
+
* This parameter is required if `capture` is not a `Route` object.
|
|
404
|
+
* @param method The HTTP method to match the Route against. Defaults to `'GET'`.
|
|
405
|
+
* @returns The generated `Route`.
|
|
406
|
+
*/
|
|
407
|
+
registerCapture(capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route {
|
|
408
|
+
const route = parseRoute(capture, handler, method);
|
|
409
|
+
this.registerRoute(route);
|
|
410
|
+
return route;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Registers a `Route` with the router.
|
|
415
|
+
*
|
|
416
|
+
* @param route The `Route` to register.
|
|
417
|
+
*/
|
|
418
|
+
registerRoute(route: Route): void {
|
|
419
|
+
if (process.env.NODE_ENV !== "production") {
|
|
420
|
+
assert!.isType(route, "object", {
|
|
421
|
+
moduleName: "serwist/legacy",
|
|
422
|
+
className: "Router",
|
|
423
|
+
funcName: "registerRoute",
|
|
424
|
+
paramName: "route",
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
assert!.hasMethod(route, "match", {
|
|
428
|
+
moduleName: "serwist/legacy",
|
|
429
|
+
className: "Router",
|
|
430
|
+
funcName: "registerRoute",
|
|
431
|
+
paramName: "route",
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
assert!.isType(route.handler, "object", {
|
|
435
|
+
moduleName: "serwist/legacy",
|
|
436
|
+
className: "Router",
|
|
437
|
+
funcName: "registerRoute",
|
|
438
|
+
paramName: "route",
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
assert!.hasMethod(route.handler, "handle", {
|
|
442
|
+
moduleName: "serwist/legacy",
|
|
443
|
+
className: "Router",
|
|
444
|
+
funcName: "registerRoute",
|
|
445
|
+
paramName: "route.handler",
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
assert!.isType(route.method, "string", {
|
|
449
|
+
moduleName: "serwist/legacy",
|
|
450
|
+
className: "Router",
|
|
451
|
+
funcName: "registerRoute",
|
|
452
|
+
paramName: "route.method",
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (!this._routes.has(route.method)) {
|
|
457
|
+
this._routes.set(route.method, []);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// Give precedence to all of the earlier routes by adding this additional
|
|
461
|
+
// route to the end of the array.
|
|
462
|
+
this._routes.get(route.method)!.push(route);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Unregisters a `Route` with the `Router`.
|
|
467
|
+
*
|
|
468
|
+
* @param route The `Route` to unregister.
|
|
469
|
+
*/
|
|
470
|
+
unregisterRoute(route: Route): void {
|
|
471
|
+
if (!this._routes.has(route.method)) {
|
|
472
|
+
throw new SerwistError("unregister-route-but-not-found-with-method", {
|
|
473
|
+
method: route.method,
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const routeIndex = this._routes.get(route.method)!.indexOf(route);
|
|
478
|
+
if (routeIndex > -1) {
|
|
479
|
+
this._routes.get(route.method)!.splice(routeIndex, 1);
|
|
480
|
+
} else {
|
|
481
|
+
throw new SerwistError("unregister-route-route-not-registered");
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2019 Google LLC
|
|
3
|
+
|
|
4
|
+
Use of this source code is governed by an MIT-style
|
|
5
|
+
license that can be found in the LICENSE file or at
|
|
6
|
+
https://opensource.org/licenses/MIT.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { SerwistPlugin } from "../types.js";
|
|
10
|
+
import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Adds plugins to the precaching strategy.
|
|
14
|
+
*
|
|
15
|
+
* @param plugins
|
|
16
|
+
* @deprecated
|
|
17
|
+
*/
|
|
18
|
+
export const addPlugins = (plugins: SerwistPlugin[]): void => {
|
|
19
|
+
const precacheController = getSingletonPrecacheController();
|
|
20
|
+
precacheController.strategy.plugins.push(...plugins);
|
|
21
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2019 Google LLC
|
|
3
|
+
Use of this source code is governed by an MIT-style
|
|
4
|
+
license that can be found in the LICENSE file or at
|
|
5
|
+
https://opensource.org/licenses/MIT.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { PrecacheRouteOptions } from "../types.js";
|
|
9
|
+
import { PrecacheRoute } from "./PrecacheRoute.js";
|
|
10
|
+
import { registerRoute } from "./registerRoute.js";
|
|
11
|
+
import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Add a `fetch` listener to the service worker that will
|
|
15
|
+
* respond to
|
|
16
|
+
* [network requests](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests)
|
|
17
|
+
* with precached assets.
|
|
18
|
+
*
|
|
19
|
+
* Requests for assets that aren't precached, the `FetchEvent` will not be
|
|
20
|
+
* responded to, allowing the event to fall through to other `fetch` event
|
|
21
|
+
* listeners.
|
|
22
|
+
*
|
|
23
|
+
* @param options See `serwist.PrecacheRouteOptions`.
|
|
24
|
+
* @deprecated
|
|
25
|
+
*/
|
|
26
|
+
export const addRoute = (options?: PrecacheRouteOptions): void => {
|
|
27
|
+
const precacheRoute = new PrecacheRoute(getSingletonPrecacheController(), options);
|
|
28
|
+
registerRoute(precacheRoute);
|
|
29
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2019 Google LLC
|
|
3
|
+
|
|
4
|
+
Use of this source code is governed by an MIT-style
|
|
5
|
+
license that can be found in the LICENSE file or at
|
|
6
|
+
https://opensource.org/licenses/MIT.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { RouteHandlerCallback } from "../types.js";
|
|
10
|
+
import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Helper function that calls `PrecacheController#createHandlerBoundToURL`
|
|
14
|
+
* on the default `PrecacheController` instance.
|
|
15
|
+
*
|
|
16
|
+
* If you are creating your own `PrecacheController`, then call the
|
|
17
|
+
* `PrecacheController#createHandlerBoundToURL` on that instance,
|
|
18
|
+
* instead of using this function.
|
|
19
|
+
*
|
|
20
|
+
* @param url The precached URL which will be used to lookup the
|
|
21
|
+
* `Response`.
|
|
22
|
+
* @param fallbackToNetwork Whether to attempt to get the
|
|
23
|
+
* response from the network if there's a precache miss.
|
|
24
|
+
* @return
|
|
25
|
+
* @deprecated
|
|
26
|
+
*/
|
|
27
|
+
export const createHandlerBoundToURL = (url: string): RouteHandlerCallback => {
|
|
28
|
+
const precacheController = getSingletonPrecacheController();
|
|
29
|
+
return precacheController.createHandlerBoundToURL(url);
|
|
30
|
+
};
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { PrecacheFallbackPlugin } from "./PrecacheFallbackPlugin.js";
|
|
2
|
+
import { Strategy } from "../strategies/Strategy.js";
|
|
3
|
+
import type { PrecacheRouteOptions, RuntimeCaching } from "../types.js";
|
|
4
|
+
import type { PrecacheController } from "./PrecacheController.js";
|
|
5
|
+
import { PrecacheRoute } from "./PrecacheRoute.js";
|
|
6
|
+
import type { Router } from "./Router.js";
|
|
7
|
+
import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
|
|
8
|
+
import { getSingletonRouter } from "./singletonRouter.js";
|
|
9
|
+
import type { PrecacheFallbackEntry } from "./PrecacheFallbackPlugin.js";
|
|
10
|
+
|
|
11
|
+
export interface FallbackEntry extends PrecacheFallbackEntry {
|
|
12
|
+
/**
|
|
13
|
+
* The revision used for precaching.
|
|
14
|
+
*/
|
|
15
|
+
revision: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface FallbacksOptions {
|
|
19
|
+
/**
|
|
20
|
+
* A list of fallback entries.
|
|
21
|
+
*/
|
|
22
|
+
entries: FallbackEntry[];
|
|
23
|
+
/**
|
|
24
|
+
* Precache options that will be used for your
|
|
25
|
+
* fallback entries.
|
|
26
|
+
*/
|
|
27
|
+
precacheOptions?: PrecacheRouteOptions;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface FallbacksOptions {
|
|
31
|
+
/**
|
|
32
|
+
* An optional `PrecacheController` instance. If not provided, the singleton
|
|
33
|
+
* `PrecacheController` will be used.
|
|
34
|
+
*/
|
|
35
|
+
precacheController?: PrecacheController;
|
|
36
|
+
/**
|
|
37
|
+
* An optional `Router` instance. If not provided, the singleton `Router`
|
|
38
|
+
* will be used.
|
|
39
|
+
*/
|
|
40
|
+
router?: Router;
|
|
41
|
+
/**
|
|
42
|
+
* Your previous list of caching strategies.
|
|
43
|
+
*/
|
|
44
|
+
runtimeCaching: RuntimeCaching[];
|
|
45
|
+
/**
|
|
46
|
+
* A list of fallback entries.
|
|
47
|
+
*/
|
|
48
|
+
entries: FallbackEntry[];
|
|
49
|
+
/**
|
|
50
|
+
* Precache options that will be used for your
|
|
51
|
+
* fallback entries.
|
|
52
|
+
*/
|
|
53
|
+
precacheOptions?: PrecacheRouteOptions;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Precaches routes so that they can be used as a fallback when
|
|
58
|
+
* a Strategy fails to generate a response.
|
|
59
|
+
*
|
|
60
|
+
* Note: This function mutates `runtimeCaching`. It also precaches the URLs
|
|
61
|
+
* defined in `entries`, so you must NOT precache any of them beforehand.
|
|
62
|
+
*
|
|
63
|
+
* @param options
|
|
64
|
+
* @returns The modified `runtimeCaching` array.
|
|
65
|
+
* @deprecated
|
|
66
|
+
*/
|
|
67
|
+
export const fallbacks = ({
|
|
68
|
+
precacheController = getSingletonPrecacheController(),
|
|
69
|
+
router = getSingletonRouter(),
|
|
70
|
+
runtimeCaching,
|
|
71
|
+
entries,
|
|
72
|
+
precacheOptions,
|
|
73
|
+
}: FallbacksOptions): RuntimeCaching[] => {
|
|
74
|
+
precacheController.precache(entries);
|
|
75
|
+
router.registerRoute(new PrecacheRoute(precacheController, precacheOptions));
|
|
76
|
+
|
|
77
|
+
const fallbackPlugin = new PrecacheFallbackPlugin({
|
|
78
|
+
fallbackUrls: entries,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
runtimeCaching.forEach((cacheEntry) => {
|
|
82
|
+
if (
|
|
83
|
+
cacheEntry.handler instanceof Strategy &&
|
|
84
|
+
// PrecacheFallbackPlugin also has `handlerDidError`, so we don't need to check for its instances.
|
|
85
|
+
!cacheEntry.handler.plugins.some((plugin) => "handlerDidError" in plugin)
|
|
86
|
+
) {
|
|
87
|
+
cacheEntry.handler.plugins.push(fallbackPlugin);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return cacheEntry;
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
return runtimeCaching;
|
|
94
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2019 Google LLC
|
|
3
|
+
|
|
4
|
+
Use of this source code is governed by an MIT-style
|
|
5
|
+
license that can be found in the LICENSE file or at
|
|
6
|
+
https://opensource.org/licenses/MIT.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { getSingletonPrecacheController } from "./singletonPrecacheController.js";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Takes in a URL, and returns the corresponding URL that could be used to
|
|
13
|
+
* lookup the entry in the precache.
|
|
14
|
+
*
|
|
15
|
+
* If a relative URL is provided, the location of the service worker file will
|
|
16
|
+
* be used as the base.
|
|
17
|
+
*
|
|
18
|
+
* For precached entries without revision information, the cache key will be the
|
|
19
|
+
* same as the original URL.
|
|
20
|
+
*
|
|
21
|
+
* For precached entries with revision information, the cache key will be the
|
|
22
|
+
* original URL with the addition of a query parameter used for keeping track of
|
|
23
|
+
* the revision info.
|
|
24
|
+
*
|
|
25
|
+
* @param url The URL whose cache key to look up.
|
|
26
|
+
* @returns The cache key that corresponds to that URL.
|
|
27
|
+
* @deprecated
|
|
28
|
+
*/
|
|
29
|
+
export const getCacheKeyForURL = (url: string): string | undefined => {
|
|
30
|
+
const precacheController = getSingletonPrecacheController();
|
|
31
|
+
return precacheController.getCacheKeyForURL(url);
|
|
32
|
+
};
|