@serwist/sw 8.4.4 → 9.0.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1,2 @@
1
1
  export declare const disableDevLogs: () => void;
2
+ //# sourceMappingURL=disableDevLogs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"disableDevLogs.d.ts","sourceRoot":"","sources":["../src/disableDevLogs.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,cAAc,YAE1B,CAAC"}
@@ -1,6 +1,6 @@
1
- import type { RuntimeCaching } from "@serwist/build";
2
1
  import type { HandlerDidErrorCallbackParam } from "@serwist/core";
3
2
  import type { PrecacheRouteOptions } from "@serwist/precaching";
3
+ import type { RuntimeCaching } from "./types.js";
4
4
  export type FallbackMatcher = (_: HandlerDidErrorCallbackParam) => boolean;
5
5
  export interface FallbackEntry {
6
6
  /**
@@ -30,3 +30,4 @@ export interface FallbacksOptions {
30
30
  precacheOptions?: PrecacheRouteOptions;
31
31
  }
32
32
  export declare const fallbacks: ({ runtimeCaching, entries, precacheOptions }: FallbacksOptions) => RuntimeCaching[];
33
+ //# sourceMappingURL=fallbacks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fallbacks.d.ts","sourceRoot":"","sources":["../src/fallbacks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAGhE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,EAAE,4BAA4B,KAAK,OAAO,CAAC;AAE3E,MAAM,WAAW,aAAa;IAC5B;;;OAGG;IACH,OAAO,EAAE,eAAe,CAAC;IACzB;;OAEG;IACH,GAAG,EAAE,GAAG,GAAG,MAAM,CAAC;IAClB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,sBAAsB,CAAC;CAC5C;AAED,MAAM,WAAW,gBAAgB;IAC/B,cAAc,EAAE,cAAc,EAAE,CAAC;IACjC,OAAO,EAAE,aAAa,EAAE,CAAC;IACzB,eAAe,CAAC,EAAE,oBAAoB,CAAC;CACxC;AAED,eAAO,MAAM,SAAS,iDAAkD,gBAAgB,qBA4BvF,CAAC"}
@@ -11,3 +11,4 @@ export type HandlePrecachingOptions = {
11
11
  navigateFallback?: never;
12
12
  });
13
13
  export declare const handlePrecaching: ({ precacheEntries, precacheOptions, cleanupOutdatedCaches: shouldCleanupOutdatedCaches, ...options }: HandlePrecachingOptions) => void;
14
+ //# sourceMappingURL=handlePrecaching.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlePrecaching.d.ts","sourceRoot":"","sources":["../src/handlePrecaching.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAI/E,MAAM,MAAM,uBAAuB,GAAG;IACpC,eAAe,CAAC,EAAE,CAAC,aAAa,GAAG,MAAM,CAAC,EAAE,CAAC;IAC7C,eAAe,CAAC,EAAE,oBAAoB,CAAC;IAEvC,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC,GAAG,CAAC;IAAE,gBAAgB,EAAE,MAAM,CAAC;IAAC,yBAAyB,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,wBAAwB,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG;IAAE,gBAAgB,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC,CAAC;AAE7I,eAAO,MAAM,gBAAgB,yGAK1B,uBAAuB,SAoBzB,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,25 +1,10 @@
1
- import type { RuntimeCaching } from "@serwist/build";
2
- import { type GoogleAnalyticsInitializeOptions } from "@serwist/google-analytics/initialize";
3
1
  import { disableDevLogs } from "./disableDevLogs.js";
4
2
  import type { FallbackEntry, FallbackMatcher, FallbacksOptions } from "./fallbacks.js";
5
3
  import { fallbacks } from "./fallbacks.js";
6
4
  import { type HandlePrecachingOptions, handlePrecaching } from "./handlePrecaching.js";
5
+ import { type InstallSerwistOptions, installSerwist } from "./installSerwist.js";
7
6
  import { registerRuntimeCaching } from "./registerRuntimeCaching.js";
8
- export type SerwistOptions = HandlePrecachingOptions & {
9
- skipWaiting?: boolean;
10
- importScripts?: string[];
11
- navigationPreload?: boolean;
12
- cacheId?: string | undefined;
13
- clientsClaim?: boolean;
14
- runtimeCaching?: RuntimeCaching[];
15
- offlineAnalyticsConfig?: GoogleAnalyticsInitializeOptions | boolean;
16
- disableDevLogs?: boolean;
17
- fallbacks?: Omit<FallbacksOptions, "runtimeCaching">;
18
- };
19
- /**
20
- * A function that abstracts away the core APIs of Serwist.
21
- * @param options - `installSerwist` options.
22
- */
23
- export declare const installSerwist: ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting: shouldSkipWaiting, importScripts: scriptsToImport, navigationPreload, cacheId, clientsClaim: shouldClaimClients, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: shouldDisableDevLogs, fallbacks: fallbacksOptions, ...options }: SerwistOptions) => void;
24
- export { disableDevLogs, fallbacks, handlePrecaching, registerRuntimeCaching };
25
- export type { FallbackEntry, FallbackMatcher, FallbacksOptions, HandlePrecachingOptions };
7
+ import type { RuntimeCaching } from "./types.js";
8
+ export { disableDevLogs, fallbacks, handlePrecaching, installSerwist, registerRuntimeCaching };
9
+ export type { FallbackEntry, FallbackMatcher, FallbacksOptions, HandlePrecachingOptions, InstallSerwistOptions as SerwistOptions, RuntimeCaching };
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACvF,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,KAAK,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACvF,OAAO,EAAE,KAAK,qBAAqB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,gBAAgB,EAAE,cAAc,EAAE,sBAAsB,EAAE,CAAC;AAC/F,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,qBAAqB,IAAI,cAAc,EAAE,cAAc,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
+ import { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL, PrecacheFallbackPlugin } from '@serwist/precaching';
2
+ import { registerRoute, NavigationRoute } from '@serwist/routing';
1
3
  import { setCacheNameDetails, clientsClaim } from '@serwist/core';
4
+ import { logger } from '@serwist/core/internal';
2
5
  import { initialize } from '@serwist/google-analytics/initialize';
3
6
  import { enable } from '@serwist/navigation-preload';
4
- import { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL, PrecacheFallbackPlugin } from '@serwist/precaching';
5
- import { registerRoute, NavigationRoute } from '@serwist/routing';
6
7
  import { BackgroundSyncPlugin } from '@serwist/background-sync';
7
8
  import { BroadcastUpdatePlugin } from '@serwist/broadcast-update';
8
9
  import { CacheableResponsePlugin } from '@serwist/cacheable-response';
@@ -45,11 +46,7 @@ const fallbacks = ({ runtimeCaching, entries, precacheOptions })=>{
45
46
 
46
47
  const handlePrecaching = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches: shouldCleanupOutdatedCaches = false, ...options })=>{
47
48
  if (!!precacheEntries && precacheEntries.length > 0) {
48
- /**
49
- * The precacheAndRoute() method efficiently caches and responds to
50
- * requests for URLs in the manifest.
51
- * See https://goo.gl/S9QRab
52
- */ precacheAndRoute(precacheEntries, precacheOptions);
49
+ precacheAndRoute(precacheEntries, precacheOptions);
53
50
  }
54
51
  if (shouldCleanupOutdatedCaches) cleanupOutdatedCaches();
55
52
  if (options.navigateFallback) {
@@ -70,9 +67,16 @@ const HANDLER_NAME_TO_METHOD = {
70
67
  StaleWhileRevalidate
71
68
  };
72
69
  const registerRuntimeCaching = (...runtimeCachingList)=>{
70
+ if (!("__WB_FORCE_RUNTIME_CACHING" in globalThis)) {
71
+ self.__WB_FORCE_RUNTIME_CACHING = false;
72
+ }
73
+ if (!self.__WB_FORCE_RUNTIME_CACHING && process.env.NODE_ENV !== "production") {
74
+ logger.info("registerRuntimeCaching is disabled in development mode.");
75
+ return;
76
+ }
73
77
  for (const rcEntry of runtimeCachingList){
74
78
  if (typeof rcEntry.handler === "string") {
75
- const { cacheName, networkTimeoutSeconds, fetchOptions, matchOptions, plugins, backgroundSync, broadcastUpdate, cacheableResponse, expiration, precacheFallback, rangeRequests } = rcEntry.options; // entry.options is always defined when entry.handler is of type 'string'.
79
+ const { cacheName, networkTimeoutSeconds, fetchOptions, matchOptions, plugins, backgroundSync, broadcastUpdate, cacheableResponse, expiration, precacheFallback, rangeRequests } = rcEntry.options;
76
80
  const Handler = HANDLER_NAME_TO_METHOD[rcEntry.handler];
77
81
  registerRoute(rcEntry.urlPattern, new Handler({
78
82
  cacheName: cacheName ?? undefined,
@@ -83,7 +87,6 @@ const registerRuntimeCaching = (...runtimeCachingList)=>{
83
87
  ...plugins ?? [],
84
88
  backgroundSync && new BackgroundSyncPlugin(backgroundSync.name, backgroundSync.options),
85
89
  broadcastUpdate && new BroadcastUpdatePlugin({
86
- // @ts-expect-error weird...
87
90
  channelName: broadcastUpdate.channelName,
88
91
  ...broadcastUpdate.options
89
92
  }),
@@ -99,16 +102,15 @@ const registerRuntimeCaching = (...runtimeCachingList)=>{
99
102
  }
100
103
  };
101
104
 
102
- /**
103
- * A function that abstracts away the core APIs of Serwist.
104
- * @param options - `installSerwist` options.
105
- */ const installSerwist = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting: shouldSkipWaiting = false, importScripts: scriptsToImport, navigationPreload = false, cacheId, clientsClaim: shouldClaimClients = false, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: shouldDisableDevLogs, fallbacks: fallbacksOptions, ...options })=>{
106
- if (!!scriptsToImport && scriptsToImport.length > 0) self.importScripts(...scriptsToImport);
105
+ const installSerwist = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting = false, importScripts, navigationPreload = false, cacheId, clientsClaim: clientsClaim$1 = false, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: disableDevLogs$1, fallbacks: fallbacks$1, ...options })=>{
106
+ if (!!importScripts && importScripts.length > 0) self.importScripts(...importScripts);
107
107
  if (navigationPreload) enable();
108
- if (cacheId !== undefined) setCacheNameDetails({
109
- prefix: cacheId
110
- });
111
- if (shouldSkipWaiting) {
108
+ if (cacheId !== undefined) {
109
+ setCacheNameDetails({
110
+ prefix: cacheId
111
+ });
112
+ }
113
+ if (skipWaiting) {
112
114
  self.skipWaiting();
113
115
  } else {
114
116
  self.addEventListener("message", (event)=>{
@@ -117,7 +119,7 @@ const registerRuntimeCaching = (...runtimeCachingList)=>{
117
119
  }
118
120
  });
119
121
  }
120
- if (shouldClaimClients) clientsClaim();
122
+ if (clientsClaim$1) clientsClaim();
121
123
  handlePrecaching({
122
124
  precacheEntries,
123
125
  precacheOptions,
@@ -129,13 +131,20 @@ const registerRuntimeCaching = (...runtimeCachingList)=>{
129
131
  }
130
132
  });
131
133
  if (runtimeCaching !== undefined) {
132
- if (fallbacksOptions !== undefined) {
133
- runtimeCaching = fallbacks({
134
- ...fallbacksOptions,
135
- runtimeCaching
136
- });
134
+ if (!("__WB_FORCE_RUNTIME_CACHING" in globalThis)) {
135
+ self.__WB_FORCE_RUNTIME_CACHING = false;
136
+ }
137
+ if (!self.__WB_FORCE_RUNTIME_CACHING && process.env.NODE_ENV !== "production") {
138
+ logger.info("runtimeCaching and fallbacks are disabled in development mode.");
139
+ } else {
140
+ if (fallbacks$1 !== undefined) {
141
+ runtimeCaching = fallbacks({
142
+ ...fallbacks$1,
143
+ runtimeCaching
144
+ });
145
+ }
146
+ registerRuntimeCaching(...runtimeCaching);
137
147
  }
138
- registerRuntimeCaching(...runtimeCaching);
139
148
  }
140
149
  if (offlineAnalyticsConfig !== undefined) {
141
150
  if (typeof offlineAnalyticsConfig === "boolean") {
@@ -144,7 +153,7 @@ const registerRuntimeCaching = (...runtimeCachingList)=>{
144
153
  initialize(offlineAnalyticsConfig);
145
154
  }
146
155
  }
147
- if (shouldDisableDevLogs) disableDevLogs();
156
+ if (disableDevLogs$1) disableDevLogs();
148
157
  };
149
158
 
150
159
  export { disableDevLogs, fallbacks, handlePrecaching, installSerwist, registerRuntimeCaching };
@@ -0,0 +1,21 @@
1
+ import { type GoogleAnalyticsInitializeOptions } from "@serwist/google-analytics/initialize";
2
+ import type { FallbacksOptions } from "./fallbacks.js";
3
+ import { type HandlePrecachingOptions } from "./handlePrecaching.js";
4
+ import type { RuntimeCaching } from "./types.js";
5
+ export type InstallSerwistOptions = HandlePrecachingOptions & {
6
+ skipWaiting?: boolean;
7
+ importScripts?: string[];
8
+ navigationPreload?: boolean;
9
+ cacheId?: string | undefined;
10
+ clientsClaim?: boolean;
11
+ runtimeCaching?: RuntimeCaching[];
12
+ offlineAnalyticsConfig?: GoogleAnalyticsInitializeOptions | boolean;
13
+ disableDevLogs?: boolean;
14
+ fallbacks?: Omit<FallbacksOptions, "runtimeCaching">;
15
+ };
16
+ /**
17
+ * A function that abstracts away the core APIs of Serwist.
18
+ * @param options - `installSerwist` options.
19
+ */
20
+ export declare const installSerwist: ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting, importScripts, navigationPreload, cacheId, clientsClaim, runtimeCaching, offlineAnalyticsConfig, disableDevLogs, fallbacks, ...options }: InstallSerwistOptions) => void;
21
+ //# sourceMappingURL=installSerwist.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installSerwist.d.ts","sourceRoot":"","sources":["../src/installSerwist.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,gCAAgC,EAAc,MAAM,sCAAsC,CAAC;AAIzG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EAAE,KAAK,uBAAuB,EAAoB,MAAM,uBAAuB,CAAC;AAEvF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAIjD,MAAM,MAAM,qBAAqB,GAAG,uBAAuB,GAAG;IAC5D,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,cAAc,EAAE,CAAC;IAClC,sBAAsB,CAAC,EAAE,gCAAgC,GAAG,OAAO,CAAC;IACpE,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,CAAC;CACtD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,cAAc,qNAexB,qBAAqB,SA4DvB,CAAC"}
@@ -1,2 +1,3 @@
1
- import type { RuntimeCaching } from "@serwist/build";
1
+ import type { RuntimeCaching } from "./types.js";
2
2
  export declare const registerRuntimeCaching: (...runtimeCachingList: RuntimeCaching[]) => void;
3
+ //# sourceMappingURL=registerRuntimeCaching.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registerRuntimeCaching.d.ts","sourceRoot":"","sources":["../src/registerRuntimeCaching.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,cAAc,EAAgB,MAAM,YAAY,CAAC;AAY/D,eAAO,MAAM,sBAAsB,0BAA2B,cAAc,EAAE,SAsD7E,CAAC"}
@@ -0,0 +1,110 @@
1
+ import type { QueueOptions } from "@serwist/background-sync";
2
+ import type { BroadcastCacheUpdateOptions } from "@serwist/broadcast-update";
3
+ import type { CacheableResponseOptions } from "@serwist/cacheable-response";
4
+ import type { RouteHandler, RouteMatchCallback, SerwistPlugin } from "@serwist/core";
5
+ import type { ExpirationPluginOptions } from "@serwist/expiration";
6
+ import type { HTTPMethod } from "@serwist/routing";
7
+ export type StrategyName = "CacheFirst" | "CacheOnly" | "NetworkFirst" | "NetworkOnly" | "StaleWhileRevalidate";
8
+ export interface RuntimeCaching {
9
+ /**
10
+ * This determines how the runtime route will generate a response.
11
+ * To use one of the built-in `@serwist/strategies`, provide its name,
12
+ * like `'NetworkFirst'`.
13
+ * Alternatively, this can be a `@serwist/core.RouteHandler` callback
14
+ * function with custom response logic.
15
+ */
16
+ handler: RouteHandler | StrategyName;
17
+ /**
18
+ * The HTTP method to match against. The default value of `'GET'` is normally
19
+ * sufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or
20
+ * another type of request.
21
+ * @default "GET"
22
+ */
23
+ method?: HTTPMethod;
24
+ options?: {
25
+ /**
26
+ * Configuring this will add a
27
+ * `@serwist/background-sync.BackgroundSyncPlugin` instance to the
28
+ * `@serwist/strategies` configured in `handler`.
29
+ */
30
+ backgroundSync?: {
31
+ name: string;
32
+ options?: QueueOptions;
33
+ };
34
+ /**
35
+ * Configuring this will add a
36
+ * `@serwist/broadcast-update.BroadcastUpdatePlugin` instance to the
37
+ * `@serwist/strategies` configured in `handler`.
38
+ */
39
+ broadcastUpdate?: {
40
+ channelName?: string;
41
+ options: BroadcastCacheUpdateOptions;
42
+ };
43
+ /**
44
+ * Configuring this will add a
45
+ * `@serwist/cacheable-response.CacheableResponsePlugin` instance to
46
+ * the `@serwist/strategies` configured in `handler`.
47
+ */
48
+ cacheableResponse?: CacheableResponseOptions;
49
+ /**
50
+ * If provided, this will set the `cacheName` property of the
51
+ * `@serwist/strategies` configured in `handler`.
52
+ */
53
+ cacheName?: string | null;
54
+ /**
55
+ * Configuring this will add a
56
+ * `@serwist/expiration.ExpirationPlugin` instance to
57
+ * the `@serwist/strategies` configured in `handler`.
58
+ */
59
+ expiration?: ExpirationPluginOptions;
60
+ /**
61
+ * If provided, this will set the `networkTimeoutSeconds` property of the
62
+ * `@serwist/strategies` configured in `handler`. Note that only
63
+ * `'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.
64
+ */
65
+ networkTimeoutSeconds?: number;
66
+ /**
67
+ * Configuring this allows the use of one or more Serwist plugins that
68
+ * don't have "shortcut" options (like `expiration` for
69
+ * `@serwist/expiration.ExpirationPlugin`). The plugins provided here
70
+ * will be added to the `@serwist/strategies` configured in `handler`.
71
+ */
72
+ plugins?: SerwistPlugin[];
73
+ /**
74
+ * Configuring this will add a
75
+ * `@serwist/precaching.PrecacheFallbackPlugin` instance to
76
+ * the `@serwist/strategies` configured in `handler`.
77
+ */
78
+ precacheFallback?: {
79
+ fallbackURL: string;
80
+ };
81
+ /**
82
+ * Enabling this will add a
83
+ * `@serwist/range-requests.RangeRequestsPlugin` instance to
84
+ * the `@serwist/strategies` configured in `handler`.
85
+ */
86
+ rangeRequests?: boolean;
87
+ /**
88
+ * Configuring this will pass along the `fetchOptions` value to
89
+ * the `@serwist/strategies` configured in `handler`.
90
+ */
91
+ fetchOptions?: RequestInit;
92
+ /**
93
+ * Configuring this will pass along the `matchOptions` value to
94
+ * the `@serwist/strategies` configured in `handler`.
95
+ */
96
+ matchOptions?: CacheQueryOptions;
97
+ };
98
+ /**
99
+ * This match criteria determines whether the configured handler will
100
+ * generate a response for any requests that don't match one of the precached
101
+ * URLs. If multiple `RuntimeCaching` routes are defined, then the first one
102
+ * whose `urlPattern` matches will be the one that responds.
103
+ *
104
+ * This value directly maps to the first parameter passed to
105
+ * `@serwist/routing.registerRoute`. It's recommended to use a
106
+ * `@serwist/core.RouteMatchCallback` function for greatest flexibility.
107
+ */
108
+ urlPattern: RegExp | string | RouteMatchCallback;
109
+ }
110
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACrF,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,YAAY,GAAG,YAAY,GAAG,WAAW,GAAG,cAAc,GAAG,aAAa,GAAG,sBAAsB,CAAC;AAEhH,MAAM,WAAW,cAAc;IAC7B;;;;;;OAMG;IACH,OAAO,EAAE,YAAY,GAAG,YAAY,CAAC;IACrC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,OAAO,CAAC,EAAE;QACR;;;;WAIG;QACH,cAAc,CAAC,EAAE;YACf,IAAI,EAAE,MAAM,CAAC;YACb,OAAO,CAAC,EAAE,YAAY,CAAC;SACxB,CAAC;QACF;;;;WAIG;QACH,eAAe,CAAC,EAAE;YAGhB,WAAW,CAAC,EAAE,MAAM,CAAC;YACrB,OAAO,EAAE,2BAA2B,CAAC;SACtC,CAAC;QACF;;;;WAIG;QACH,iBAAiB,CAAC,EAAE,wBAAwB,CAAC;QAC7C;;;WAGG;QACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC1B;;;;WAIG;QACH,UAAU,CAAC,EAAE,uBAAuB,CAAC;QACrC;;;;WAIG;QACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;QAC/B;;;;;WAKG;QACH,OAAO,CAAC,EAAE,aAAa,EAAE,CAAC;QAC1B;;;;WAIG;QACH,gBAAgB,CAAC,EAAE;YACjB,WAAW,EAAE,MAAM,CAAC;SACrB,CAAC;QACF;;;;WAIG;QACH,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB;;;WAGG;QACH,YAAY,CAAC,EAAE,WAAW,CAAC;QAC3B;;;WAGG;QACH,YAAY,CAAC,EAAE,iBAAiB,CAAC;KAClC,CAAC;IACF;;;;;;;;;OASG;IACH,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,kBAAkB,CAAC;CAClD"}
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@serwist/sw",
3
- "version": "8.4.4",
3
+ "version": "9.0.0-preview.1",
4
4
  "type": "module",
5
5
  "description": "This module makes it easy to get started with the Serwist service worker libraries.",
6
6
  "files": [
7
- "dist",
8
- "!dist/**/dts"
7
+ "src",
8
+ "dist"
9
9
  ],
10
10
  "keywords": [
11
11
  "serwist",
@@ -18,39 +18,41 @@
18
18
  "repository": "serwist/serwist",
19
19
  "bugs": "https://github.com/serwist/serwist/issues",
20
20
  "homepage": "https://serwist.pages.dev",
21
- "module": "./dist/index.js",
22
- "main": "./dist/index.cjs",
21
+ "main": "./dist/index.js",
23
22
  "types": "./dist/index.d.ts",
24
23
  "exports": {
25
24
  ".": {
26
- "import": {
27
- "types": "./dist/index.d.ts",
28
- "default": "./dist/index.js"
29
- },
30
- "require": {
31
- "types": "./dist/index.d.cts",
32
- "default": "./dist/index.cjs"
33
- }
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
34
27
  },
35
28
  "./package.json": "./package.json"
36
29
  },
37
30
  "dependencies": {
38
- "@serwist/background-sync": "8.4.4",
39
- "@serwist/broadcast-update": "8.4.4",
40
- "@serwist/cacheable-response": "8.4.4",
41
- "@serwist/core": "8.4.4",
42
- "@serwist/expiration": "8.4.4",
43
- "@serwist/google-analytics": "8.4.4",
44
- "@serwist/navigation-preload": "8.4.4",
45
- "@serwist/precaching": "8.4.4",
46
- "@serwist/range-requests": "8.4.4",
47
- "@serwist/routing": "8.4.4",
48
- "@serwist/strategies": "8.4.4"
31
+ "@serwist/background-sync": "9.0.0-preview.1",
32
+ "@serwist/broadcast-update": "9.0.0-preview.1",
33
+ "@serwist/cacheable-response": "9.0.0-preview.1",
34
+ "@serwist/core": "9.0.0-preview.1",
35
+ "@serwist/expiration": "9.0.0-preview.1",
36
+ "@serwist/google-analytics": "9.0.0-preview.1",
37
+ "@serwist/navigation-preload": "9.0.0-preview.1",
38
+ "@serwist/precaching": "9.0.0-preview.1",
39
+ "@serwist/range-requests": "9.0.0-preview.1",
40
+ "@serwist/routing": "9.0.0-preview.1",
41
+ "@serwist/strategies": "9.0.0-preview.1"
49
42
  },
50
43
  "devDependencies": {
51
- "rollup": "4.9.1",
52
- "@serwist/build": "8.4.4",
53
- "@serwist/constants": "8.4.4"
44
+ "rollup": "4.9.6",
45
+ "typescript": "5.4.0-dev.20240203",
46
+ "@serwist/constants": "9.0.0-preview.1",
47
+ "@serwist/utils": "9.0.0-preview.1"
48
+ },
49
+ "peerDependencies": {
50
+ "typescript": ">=5.0.0"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "typescript": {
54
+ "optional": true
55
+ }
54
56
  },
55
57
  "scripts": {
56
58
  "build": "rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js",
@@ -0,0 +1,7 @@
1
+ declare const self: WorkerGlobalScope & {
2
+ __WB_DISABLE_DEV_LOGS: boolean;
3
+ };
4
+
5
+ export const disableDevLogs = () => {
6
+ self.__WB_DISABLE_DEV_LOGS = true;
7
+ };
@@ -0,0 +1,66 @@
1
+ import type { HandlerDidErrorCallbackParam } from "@serwist/core";
2
+ import type { PrecacheRouteOptions } from "@serwist/precaching";
3
+ import { precacheAndRoute } from "@serwist/precaching";
4
+
5
+ import type { RuntimeCaching } from "./types.js";
6
+
7
+ export type FallbackMatcher = (_: HandlerDidErrorCallbackParam) => boolean;
8
+
9
+ export interface FallbackEntry {
10
+ /**
11
+ * The matcher, which checks whether the fallback entry can be used
12
+ * for a Request.
13
+ */
14
+ matcher: FallbackMatcher;
15
+ /**
16
+ * The fallback URL.
17
+ */
18
+ url: URL | string;
19
+ /**
20
+ * The revision used for precaching.
21
+ */
22
+ revision: string;
23
+ /**
24
+ * How the Response in the cache should be matched.
25
+ *
26
+ * @default
27
+ * { ignoreSearch: true }
28
+ */
29
+ cacheMatchOptions?: MultiCacheQueryOptions;
30
+ }
31
+
32
+ export interface FallbacksOptions {
33
+ runtimeCaching: RuntimeCaching[];
34
+ entries: FallbackEntry[];
35
+ precacheOptions?: PrecacheRouteOptions;
36
+ }
37
+
38
+ export const fallbacks = ({ runtimeCaching, entries, precacheOptions }: FallbacksOptions) => {
39
+ precacheAndRoute(
40
+ entries.map(({ url, revision }) => ({ url: typeof url === "string" ? url : url.toString(), revision })),
41
+ precacheOptions,
42
+ );
43
+ runtimeCaching = runtimeCaching.map((cacheEntry) => {
44
+ if (!cacheEntry.options || cacheEntry.options.precacheFallback || cacheEntry.options.plugins?.some((plugin) => "handlerDidError" in plugin)) {
45
+ return cacheEntry;
46
+ }
47
+
48
+ if (!cacheEntry.options.plugins) {
49
+ cacheEntry.options.plugins = [];
50
+ }
51
+
52
+ cacheEntry.options.plugins.push({
53
+ async handlerDidError(info) {
54
+ for (const { matcher, url, cacheMatchOptions = { ignoreSearch: true } } of entries) {
55
+ if (matcher(info)) {
56
+ return caches.match(url, cacheMatchOptions);
57
+ }
58
+ }
59
+ return Response.error();
60
+ },
61
+ });
62
+
63
+ return cacheEntry;
64
+ });
65
+ return runtimeCaching;
66
+ };
@@ -0,0 +1,37 @@
1
+ import type { PrecacheEntry, PrecacheRouteOptions } from "@serwist/precaching";
2
+ import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from "@serwist/precaching";
3
+ import { NavigationRoute, registerRoute } from "@serwist/routing";
4
+
5
+ export type HandlePrecachingOptions = {
6
+ precacheEntries?: (PrecacheEntry | string)[];
7
+ precacheOptions?: PrecacheRouteOptions;
8
+
9
+ cleanupOutdatedCaches?: boolean;
10
+ } & ({ navigateFallback: string; navigateFallbackAllowlist?: RegExp[]; navigateFallbackDenylist?: RegExp[] } | { navigateFallback?: never });
11
+
12
+ export const handlePrecaching = ({
13
+ precacheEntries,
14
+ precacheOptions,
15
+ cleanupOutdatedCaches: shouldCleanupOutdatedCaches = false,
16
+ ...options
17
+ }: HandlePrecachingOptions) => {
18
+ if (!!precacheEntries && precacheEntries.length > 0) {
19
+ /**
20
+ * The precacheAndRoute() method efficiently caches and responds to
21
+ * requests for URLs in the manifest.
22
+ * See https://goo.gl/S9QRab
23
+ */
24
+ precacheAndRoute(precacheEntries, precacheOptions);
25
+ }
26
+
27
+ if (shouldCleanupOutdatedCaches) cleanupOutdatedCaches();
28
+
29
+ if (options.navigateFallback) {
30
+ registerRoute(
31
+ new NavigationRoute(createHandlerBoundToURL(options.navigateFallback), {
32
+ allowlist: options.navigateFallbackAllowlist,
33
+ denylist: options.navigateFallbackDenylist,
34
+ }),
35
+ );
36
+ }
37
+ };
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { disableDevLogs } from "./disableDevLogs.js";
2
+ import type { FallbackEntry, FallbackMatcher, FallbacksOptions } from "./fallbacks.js";
3
+ import { fallbacks } from "./fallbacks.js";
4
+ import { type HandlePrecachingOptions, handlePrecaching } from "./handlePrecaching.js";
5
+ import { type InstallSerwistOptions, installSerwist } from "./installSerwist.js";
6
+ import { registerRuntimeCaching } from "./registerRuntimeCaching.js";
7
+ import type { RuntimeCaching } from "./types.js";
8
+
9
+ export { disableDevLogs, fallbacks, handlePrecaching, installSerwist, registerRuntimeCaching };
10
+ export type { FallbackEntry, FallbackMatcher, FallbacksOptions, HandlePrecachingOptions, InstallSerwistOptions as SerwistOptions, RuntimeCaching };
@@ -0,0 +1,106 @@
1
+ import { clientsClaim as clientsClaimImpl, setCacheNameDetails } from "@serwist/core";
2
+ import { logger } from "@serwist/core/internal";
3
+ import { type GoogleAnalyticsInitializeOptions, initialize } from "@serwist/google-analytics/initialize";
4
+ import { enable } from "@serwist/navigation-preload";
5
+
6
+ import { disableDevLogs as disableDevLogsImpl } from "./disableDevLogs.js";
7
+ import type { FallbacksOptions } from "./fallbacks.js";
8
+ import { fallbacks as fallbacksImpl } from "./fallbacks.js";
9
+ import { type HandlePrecachingOptions, handlePrecaching } from "./handlePrecaching.js";
10
+ import { registerRuntimeCaching } from "./registerRuntimeCaching.js";
11
+ import type { RuntimeCaching } from "./types.js";
12
+
13
+ declare const self: ServiceWorkerGlobalScope;
14
+
15
+ export type InstallSerwistOptions = HandlePrecachingOptions & {
16
+ skipWaiting?: boolean;
17
+ importScripts?: string[];
18
+ navigationPreload?: boolean;
19
+ cacheId?: string | undefined;
20
+ clientsClaim?: boolean;
21
+ runtimeCaching?: RuntimeCaching[];
22
+ offlineAnalyticsConfig?: GoogleAnalyticsInitializeOptions | boolean;
23
+ disableDevLogs?: boolean;
24
+ fallbacks?: Omit<FallbacksOptions, "runtimeCaching">;
25
+ };
26
+
27
+ /**
28
+ * A function that abstracts away the core APIs of Serwist.
29
+ * @param options - `installSerwist` options.
30
+ */
31
+ export const installSerwist = ({
32
+ precacheEntries,
33
+ precacheOptions,
34
+ cleanupOutdatedCaches,
35
+
36
+ skipWaiting = false,
37
+ importScripts,
38
+ navigationPreload = false,
39
+ cacheId,
40
+ clientsClaim = false,
41
+ runtimeCaching,
42
+ offlineAnalyticsConfig,
43
+ disableDevLogs,
44
+ fallbacks,
45
+ ...options
46
+ }: InstallSerwistOptions) => {
47
+ if (!!importScripts && importScripts.length > 0) self.importScripts(...importScripts);
48
+
49
+ if (navigationPreload) enable();
50
+
51
+ if (cacheId !== undefined) {
52
+ setCacheNameDetails({
53
+ prefix: cacheId,
54
+ });
55
+ }
56
+
57
+ if (skipWaiting) {
58
+ self.skipWaiting();
59
+ } else {
60
+ self.addEventListener("message", (event) => {
61
+ if (event.data && event.data.type === "SKIP_WAITING") {
62
+ self.skipWaiting();
63
+ }
64
+ });
65
+ }
66
+
67
+ if (clientsClaim) clientsClaimImpl();
68
+
69
+ handlePrecaching({
70
+ precacheEntries,
71
+ precacheOptions,
72
+ cleanupOutdatedCaches,
73
+ ...(options.navigateFallback && {
74
+ navigateFallback: options.navigateFallback,
75
+ navigateFallbackAllowlist: options.navigateFallbackAllowlist,
76
+ navigateFallbackDenylist: options.navigateFallbackDenylist,
77
+ }),
78
+ });
79
+
80
+ if (runtimeCaching !== undefined) {
81
+ if (!("__WB_FORCE_RUNTIME_CACHING" in globalThis)) {
82
+ self.__WB_FORCE_RUNTIME_CACHING = false;
83
+ }
84
+ if (!self.__WB_FORCE_RUNTIME_CACHING && process.env.NODE_ENV !== "production") {
85
+ logger.info("runtimeCaching and fallbacks are disabled in development mode.");
86
+ } else {
87
+ if (fallbacks !== undefined) {
88
+ runtimeCaching = fallbacksImpl({
89
+ ...fallbacks,
90
+ runtimeCaching,
91
+ });
92
+ }
93
+ registerRuntimeCaching(...runtimeCaching);
94
+ }
95
+ }
96
+
97
+ if (offlineAnalyticsConfig !== undefined) {
98
+ if (typeof offlineAnalyticsConfig === "boolean") {
99
+ offlineAnalyticsConfig && initialize();
100
+ } else {
101
+ initialize(offlineAnalyticsConfig);
102
+ }
103
+ }
104
+
105
+ if (disableDevLogs) disableDevLogsImpl();
106
+ };
@@ -0,0 +1,78 @@
1
+ import { BackgroundSyncPlugin } from "@serwist/background-sync";
2
+ import { BroadcastUpdatePlugin } from "@serwist/broadcast-update";
3
+ import { CacheableResponsePlugin } from "@serwist/cacheable-response";
4
+ import { logger } from "@serwist/core/internal";
5
+ import { ExpirationPlugin } from "@serwist/expiration";
6
+ import { PrecacheFallbackPlugin } from "@serwist/precaching";
7
+ import { RangeRequestsPlugin } from "@serwist/range-requests";
8
+ import { registerRoute } from "@serwist/routing";
9
+ import { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate } from "@serwist/strategies";
10
+ import { nonNullable } from "@serwist/utils";
11
+
12
+ import type { RuntimeCaching, StrategyName } from "./types.js";
13
+
14
+ declare const self: ServiceWorkerGlobalScope;
15
+
16
+ const HANDLER_NAME_TO_METHOD = {
17
+ CacheFirst,
18
+ CacheOnly,
19
+ NetworkFirst,
20
+ NetworkOnly,
21
+ StaleWhileRevalidate,
22
+ } satisfies Record<StrategyName, unknown>;
23
+
24
+ export const registerRuntimeCaching = (...runtimeCachingList: RuntimeCaching[]) => {
25
+ if (!("__WB_FORCE_RUNTIME_CACHING" in globalThis)) {
26
+ self.__WB_FORCE_RUNTIME_CACHING = false;
27
+ }
28
+
29
+ if (!self.__WB_FORCE_RUNTIME_CACHING && process.env.NODE_ENV !== "production") {
30
+ logger.info("registerRuntimeCaching is disabled in development mode.");
31
+ return;
32
+ }
33
+
34
+ for (const rcEntry of runtimeCachingList) {
35
+ if (typeof rcEntry.handler === "string") {
36
+ const {
37
+ cacheName,
38
+ networkTimeoutSeconds,
39
+ fetchOptions,
40
+ matchOptions,
41
+ plugins,
42
+ backgroundSync,
43
+ broadcastUpdate,
44
+ cacheableResponse,
45
+ expiration,
46
+ precacheFallback,
47
+ rangeRequests,
48
+ } = rcEntry.options!; // entry.options is always defined when entry.handler is of type 'string'.
49
+ const Handler = HANDLER_NAME_TO_METHOD[rcEntry.handler];
50
+ registerRoute(
51
+ rcEntry.urlPattern,
52
+ new Handler({
53
+ cacheName: cacheName ?? undefined,
54
+ networkTimeoutSeconds,
55
+ fetchOptions,
56
+ matchOptions,
57
+ plugins: [
58
+ ...(plugins ?? []),
59
+ backgroundSync && new BackgroundSyncPlugin(backgroundSync.name, backgroundSync.options),
60
+ broadcastUpdate &&
61
+ new BroadcastUpdatePlugin({
62
+ // @ts-expect-error weird...
63
+ channelName: broadcastUpdate.channelName,
64
+ ...broadcastUpdate.options,
65
+ }),
66
+ cacheableResponse && new CacheableResponsePlugin(cacheableResponse),
67
+ expiration && new ExpirationPlugin(expiration),
68
+ precacheFallback && new PrecacheFallbackPlugin(precacheFallback),
69
+ rangeRequests ? new RangeRequestsPlugin() : undefined,
70
+ ].filter(nonNullable),
71
+ }),
72
+ rcEntry.method,
73
+ );
74
+ } else {
75
+ registerRoute(rcEntry.urlPattern, rcEntry.handler, rcEntry.method);
76
+ }
77
+ }
78
+ };
package/src/types.ts ADDED
@@ -0,0 +1,113 @@
1
+ import type { QueueOptions } from "@serwist/background-sync";
2
+ import type { BroadcastCacheUpdateOptions } from "@serwist/broadcast-update";
3
+ import type { CacheableResponseOptions } from "@serwist/cacheable-response";
4
+ import type { RouteHandler, RouteMatchCallback, SerwistPlugin } from "@serwist/core";
5
+ import type { ExpirationPluginOptions } from "@serwist/expiration";
6
+ import type { HTTPMethod } from "@serwist/routing";
7
+
8
+ export type StrategyName = "CacheFirst" | "CacheOnly" | "NetworkFirst" | "NetworkOnly" | "StaleWhileRevalidate";
9
+
10
+ export interface RuntimeCaching {
11
+ /**
12
+ * This determines how the runtime route will generate a response.
13
+ * To use one of the built-in `@serwist/strategies`, provide its name,
14
+ * like `'NetworkFirst'`.
15
+ * Alternatively, this can be a `@serwist/core.RouteHandler` callback
16
+ * function with custom response logic.
17
+ */
18
+ handler: RouteHandler | StrategyName;
19
+ /**
20
+ * The HTTP method to match against. The default value of `'GET'` is normally
21
+ * sufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or
22
+ * another type of request.
23
+ * @default "GET"
24
+ */
25
+ method?: HTTPMethod;
26
+ options?: {
27
+ /**
28
+ * Configuring this will add a
29
+ * `@serwist/background-sync.BackgroundSyncPlugin` instance to the
30
+ * `@serwist/strategies` configured in `handler`.
31
+ */
32
+ backgroundSync?: {
33
+ name: string;
34
+ options?: QueueOptions;
35
+ };
36
+ /**
37
+ * Configuring this will add a
38
+ * `@serwist/broadcast-update.BroadcastUpdatePlugin` instance to the
39
+ * `@serwist/strategies` configured in `handler`.
40
+ */
41
+ broadcastUpdate?: {
42
+ // TODO: This option is ignored since we switched to using postMessage().
43
+ // Remove it in the next major release.
44
+ channelName?: string;
45
+ options: BroadcastCacheUpdateOptions;
46
+ };
47
+ /**
48
+ * Configuring this will add a
49
+ * `@serwist/cacheable-response.CacheableResponsePlugin` instance to
50
+ * the `@serwist/strategies` configured in `handler`.
51
+ */
52
+ cacheableResponse?: CacheableResponseOptions;
53
+ /**
54
+ * If provided, this will set the `cacheName` property of the
55
+ * `@serwist/strategies` configured in `handler`.
56
+ */
57
+ cacheName?: string | null;
58
+ /**
59
+ * Configuring this will add a
60
+ * `@serwist/expiration.ExpirationPlugin` instance to
61
+ * the `@serwist/strategies` configured in `handler`.
62
+ */
63
+ expiration?: ExpirationPluginOptions;
64
+ /**
65
+ * If provided, this will set the `networkTimeoutSeconds` property of the
66
+ * `@serwist/strategies` configured in `handler`. Note that only
67
+ * `'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.
68
+ */
69
+ networkTimeoutSeconds?: number;
70
+ /**
71
+ * Configuring this allows the use of one or more Serwist plugins that
72
+ * don't have "shortcut" options (like `expiration` for
73
+ * `@serwist/expiration.ExpirationPlugin`). The plugins provided here
74
+ * will be added to the `@serwist/strategies` configured in `handler`.
75
+ */
76
+ plugins?: SerwistPlugin[];
77
+ /**
78
+ * Configuring this will add a
79
+ * `@serwist/precaching.PrecacheFallbackPlugin` instance to
80
+ * the `@serwist/strategies` configured in `handler`.
81
+ */
82
+ precacheFallback?: {
83
+ fallbackURL: string;
84
+ };
85
+ /**
86
+ * Enabling this will add a
87
+ * `@serwist/range-requests.RangeRequestsPlugin` instance to
88
+ * the `@serwist/strategies` configured in `handler`.
89
+ */
90
+ rangeRequests?: boolean;
91
+ /**
92
+ * Configuring this will pass along the `fetchOptions` value to
93
+ * the `@serwist/strategies` configured in `handler`.
94
+ */
95
+ fetchOptions?: RequestInit;
96
+ /**
97
+ * Configuring this will pass along the `matchOptions` value to
98
+ * the `@serwist/strategies` configured in `handler`.
99
+ */
100
+ matchOptions?: CacheQueryOptions;
101
+ };
102
+ /**
103
+ * This match criteria determines whether the configured handler will
104
+ * generate a response for any requests that don't match one of the precached
105
+ * URLs. If multiple `RuntimeCaching` routes are defined, then the first one
106
+ * whose `urlPattern` matches will be the one that responds.
107
+ *
108
+ * This value directly maps to the first parameter passed to
109
+ * `@serwist/routing.registerRoute`. It's recommended to use a
110
+ * `@serwist/core.RouteMatchCallback` function for greatest flexibility.
111
+ */
112
+ urlPattern: RegExp | string | RouteMatchCallback;
113
+ }
package/dist/index.cjs DELETED
@@ -1,156 +0,0 @@
1
- 'use strict';
2
-
3
- var core = require('@serwist/core');
4
- var initialize = require('@serwist/google-analytics/initialize');
5
- var navigationPreload = require('@serwist/navigation-preload');
6
- var precaching = require('@serwist/precaching');
7
- var routing = require('@serwist/routing');
8
- var backgroundSync = require('@serwist/background-sync');
9
- var broadcastUpdate = require('@serwist/broadcast-update');
10
- var cacheableResponse = require('@serwist/cacheable-response');
11
- var expiration = require('@serwist/expiration');
12
- var rangeRequests = require('@serwist/range-requests');
13
- var strategies = require('@serwist/strategies');
14
-
15
- const disableDevLogs = ()=>{
16
- self.__WB_DISABLE_DEV_LOGS = true;
17
- };
18
-
19
- const fallbacks = ({ runtimeCaching, entries, precacheOptions })=>{
20
- precaching.precacheAndRoute(entries.map(({ url, revision })=>({
21
- url: typeof url === "string" ? url : url.toString(),
22
- revision
23
- })), precacheOptions);
24
- runtimeCaching = runtimeCaching.map((cacheEntry)=>{
25
- if (!cacheEntry.options || cacheEntry.options.precacheFallback || cacheEntry.options.plugins?.some((plugin)=>"handlerDidError" in plugin)) {
26
- return cacheEntry;
27
- }
28
- if (!cacheEntry.options.plugins) {
29
- cacheEntry.options.plugins = [];
30
- }
31
- cacheEntry.options.plugins.push({
32
- async handlerDidError (info) {
33
- for (const { matcher, url, cacheMatchOptions = {
34
- ignoreSearch: true
35
- } } of entries){
36
- if (matcher(info)) {
37
- return caches.match(url, cacheMatchOptions);
38
- }
39
- }
40
- return Response.error();
41
- }
42
- });
43
- return cacheEntry;
44
- });
45
- return runtimeCaching;
46
- };
47
-
48
- const handlePrecaching = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches: shouldCleanupOutdatedCaches = false, ...options })=>{
49
- if (!!precacheEntries && precacheEntries.length > 0) {
50
- /**
51
- * The precacheAndRoute() method efficiently caches and responds to
52
- * requests for URLs in the manifest.
53
- * See https://goo.gl/S9QRab
54
- */ precaching.precacheAndRoute(precacheEntries, precacheOptions);
55
- }
56
- if (shouldCleanupOutdatedCaches) precaching.cleanupOutdatedCaches();
57
- if (options.navigateFallback) {
58
- routing.registerRoute(new routing.NavigationRoute(precaching.createHandlerBoundToURL(options.navigateFallback), {
59
- allowlist: options.navigateFallbackAllowlist,
60
- denylist: options.navigateFallbackDenylist
61
- }));
62
- }
63
- };
64
-
65
- const nonNullable = (value)=>value !== null && value !== undefined;
66
-
67
- const HANDLER_NAME_TO_METHOD = {
68
- CacheFirst: strategies.CacheFirst,
69
- CacheOnly: strategies.CacheOnly,
70
- NetworkFirst: strategies.NetworkFirst,
71
- NetworkOnly: strategies.NetworkOnly,
72
- StaleWhileRevalidate: strategies.StaleWhileRevalidate
73
- };
74
- const registerRuntimeCaching = (...runtimeCachingList)=>{
75
- for (const rcEntry of runtimeCachingList){
76
- if (typeof rcEntry.handler === "string") {
77
- const { cacheName, networkTimeoutSeconds, fetchOptions, matchOptions, plugins, backgroundSync: backgroundSync$1, broadcastUpdate: broadcastUpdate$1, cacheableResponse: cacheableResponse$1, expiration: expiration$1, precacheFallback, rangeRequests: rangeRequests$1 } = rcEntry.options; // entry.options is always defined when entry.handler is of type 'string'.
78
- const Handler = HANDLER_NAME_TO_METHOD[rcEntry.handler];
79
- routing.registerRoute(rcEntry.urlPattern, new Handler({
80
- cacheName: cacheName ?? undefined,
81
- networkTimeoutSeconds,
82
- fetchOptions,
83
- matchOptions,
84
- plugins: [
85
- ...plugins ?? [],
86
- backgroundSync$1 && new backgroundSync.BackgroundSyncPlugin(backgroundSync$1.name, backgroundSync$1.options),
87
- broadcastUpdate$1 && new broadcastUpdate.BroadcastUpdatePlugin({
88
- // @ts-expect-error weird...
89
- channelName: broadcastUpdate$1.channelName,
90
- ...broadcastUpdate$1.options
91
- }),
92
- cacheableResponse$1 && new cacheableResponse.CacheableResponsePlugin(cacheableResponse$1),
93
- expiration$1 && new expiration.ExpirationPlugin(expiration$1),
94
- precacheFallback && new precaching.PrecacheFallbackPlugin(precacheFallback),
95
- rangeRequests$1 ? new rangeRequests.RangeRequestsPlugin() : undefined
96
- ].filter(nonNullable)
97
- }), rcEntry.method);
98
- } else {
99
- routing.registerRoute(rcEntry.urlPattern, rcEntry.handler, rcEntry.method);
100
- }
101
- }
102
- };
103
-
104
- /**
105
- * A function that abstracts away the core APIs of Serwist.
106
- * @param options - `installSerwist` options.
107
- */ const installSerwist = ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting: shouldSkipWaiting = false, importScripts: scriptsToImport, navigationPreload: navigationPreload$1 = false, cacheId, clientsClaim: shouldClaimClients = false, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: shouldDisableDevLogs, fallbacks: fallbacksOptions, ...options })=>{
108
- if (!!scriptsToImport && scriptsToImport.length > 0) self.importScripts(...scriptsToImport);
109
- if (navigationPreload$1) navigationPreload.enable();
110
- if (cacheId !== undefined) core.setCacheNameDetails({
111
- prefix: cacheId
112
- });
113
- if (shouldSkipWaiting) {
114
- self.skipWaiting();
115
- } else {
116
- self.addEventListener("message", (event)=>{
117
- if (event.data && event.data.type === "SKIP_WAITING") {
118
- self.skipWaiting();
119
- }
120
- });
121
- }
122
- if (shouldClaimClients) core.clientsClaim();
123
- handlePrecaching({
124
- precacheEntries,
125
- precacheOptions,
126
- cleanupOutdatedCaches,
127
- ...options.navigateFallback && {
128
- navigateFallback: options.navigateFallback,
129
- navigateFallbackAllowlist: options.navigateFallbackAllowlist,
130
- navigateFallbackDenylist: options.navigateFallbackDenylist
131
- }
132
- });
133
- if (runtimeCaching !== undefined) {
134
- if (fallbacksOptions !== undefined) {
135
- runtimeCaching = fallbacks({
136
- ...fallbacksOptions,
137
- runtimeCaching
138
- });
139
- }
140
- registerRuntimeCaching(...runtimeCaching);
141
- }
142
- if (offlineAnalyticsConfig !== undefined) {
143
- if (typeof offlineAnalyticsConfig === "boolean") {
144
- offlineAnalyticsConfig && initialize.initialize();
145
- } else {
146
- initialize.initialize(offlineAnalyticsConfig);
147
- }
148
- }
149
- if (shouldDisableDevLogs) disableDevLogs();
150
- };
151
-
152
- exports.disableDevLogs = disableDevLogs;
153
- exports.fallbacks = fallbacks;
154
- exports.handlePrecaching = handlePrecaching;
155
- exports.installSerwist = installSerwist;
156
- exports.registerRuntimeCaching = registerRuntimeCaching;
package/dist/index.d.cts DELETED
@@ -1,25 +0,0 @@
1
- import type { RuntimeCaching } from "@serwist/build";
2
- import { type GoogleAnalyticsInitializeOptions } from "@serwist/google-analytics/initialize";
3
- import { disableDevLogs } from "./disableDevLogs.js";
4
- import type { FallbackEntry, FallbackMatcher, FallbacksOptions } from "./fallbacks.js";
5
- import { fallbacks } from "./fallbacks.js";
6
- import { type HandlePrecachingOptions, handlePrecaching } from "./handlePrecaching.js";
7
- import { registerRuntimeCaching } from "./registerRuntimeCaching.js";
8
- export type SerwistOptions = HandlePrecachingOptions & {
9
- skipWaiting?: boolean;
10
- importScripts?: string[];
11
- navigationPreload?: boolean;
12
- cacheId?: string | undefined;
13
- clientsClaim?: boolean;
14
- runtimeCaching?: RuntimeCaching[];
15
- offlineAnalyticsConfig?: GoogleAnalyticsInitializeOptions | boolean;
16
- disableDevLogs?: boolean;
17
- fallbacks?: Omit<FallbacksOptions, "runtimeCaching">;
18
- };
19
- /**
20
- * A function that abstracts away the core APIs of Serwist.
21
- * @param options - `installSerwist` options.
22
- */
23
- export declare const installSerwist: ({ precacheEntries, precacheOptions, cleanupOutdatedCaches, skipWaiting: shouldSkipWaiting, importScripts: scriptsToImport, navigationPreload, cacheId, clientsClaim: shouldClaimClients, runtimeCaching, offlineAnalyticsConfig, disableDevLogs: shouldDisableDevLogs, fallbacks: fallbacksOptions, ...options }: SerwistOptions) => void;
24
- export { disableDevLogs, fallbacks, handlePrecaching, registerRuntimeCaching };
25
- export type { FallbackEntry, FallbackMatcher, FallbacksOptions, HandlePrecachingOptions };
@@ -1 +0,0 @@
1
- export declare const nonNullable: <T>(value: T) => value is NonNullable<T>;