@serwist/broadcast-update 9.0.0-preview.2 → 9.0.0-preview.21

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/README.md CHANGED
@@ -1 +1 @@
1
- This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-broadcast-update
1
+ This module's documentation can be found at https://serwist.pages.dev/docs/broadcast-update
package/dist/index.d.ts CHANGED
@@ -1,10 +1,3 @@
1
- import type { BroadcastCacheUpdateOptions } from "./BroadcastCacheUpdate.js";
2
- import { BroadcastCacheUpdate } from "./BroadcastCacheUpdate.js";
3
- import { BroadcastUpdatePlugin } from "./BroadcastUpdatePlugin.js";
4
- import { responsesAreSame } from "./responsesAreSame.js";
5
- /**
6
- * @module workbox-broadcast-update
7
- */
8
- export { BroadcastCacheUpdate, BroadcastUpdatePlugin, responsesAreSame };
9
- export type { BroadcastCacheUpdateOptions };
1
+ export { BroadcastCacheUpdate, BroadcastUpdatePlugin, responsesAreSame, BROADCAST_UPDATE_MESSAGE_META as CACHE_UPDATED_MESSAGE_META, BROADCAST_UPDATE_MESSAGE_TYPE as CACHE_UPDATED_MESSAGE_TYPE, BROADCAST_UPDATE_DEFAULT_HEADERS as defaultHeadersToCheck, } from "@serwist/sw/plugins";
2
+ export type { BroadcastCacheUpdateOptions, BroadcastPayload, BroadcastPayloadGenerator, BroadcastMessage } from "@serwist/sw/plugins";
10
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,CAAC;AAEzE,YAAY,EAAE,2BAA2B,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EACrB,gBAAgB,EAChB,6BAA6B,IAAI,0BAA0B,EAC3D,6BAA6B,IAAI,0BAA0B,EAC3D,gCAAgC,IAAI,qBAAqB,GAC1D,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EAAE,2BAA2B,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -1,121 +1 @@
1
- import { SerwistError, logger, assert, resultingClientExists, timeout, dontWaitFor } from '@serwist/core/internal';
2
-
3
- const responsesAreSame = (firstResponse, secondResponse, headersToCheck)=>{
4
- if (process.env.NODE_ENV !== "production") {
5
- if (!(firstResponse instanceof Response && secondResponse instanceof Response)) {
6
- throw new SerwistError("invalid-responses-are-same-args");
7
- }
8
- }
9
- const atLeastOneHeaderAvailable = headersToCheck.some((header)=>{
10
- return firstResponse.headers.has(header) && secondResponse.headers.has(header);
11
- });
12
- if (!atLeastOneHeaderAvailable) {
13
- if (process.env.NODE_ENV !== "production") {
14
- logger.warn("Unable to determine where the response has been updated " + "because none of the headers that would be checked are present.");
15
- logger.debug("Attempting to compare the following: ", firstResponse, secondResponse, headersToCheck);
16
- }
17
- return true;
18
- }
19
- return headersToCheck.every((header)=>{
20
- const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header);
21
- const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header);
22
- return headerStateComparison && headerValueComparison;
23
- });
24
- };
25
-
26
- const CACHE_UPDATED_MESSAGE_TYPE = "CACHE_UPDATED";
27
- const CACHE_UPDATED_MESSAGE_META = "serwist-broadcast-update";
28
- const NOTIFY_ALL_CLIENTS = true;
29
- const DEFAULT_HEADERS_TO_CHECK = [
30
- "content-length",
31
- "etag",
32
- "last-modified"
33
- ];
34
-
35
- const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
36
- function defaultPayloadGenerator(data) {
37
- return {
38
- cacheName: data.cacheName,
39
- updatedURL: data.request.url
40
- };
41
- }
42
- class BroadcastCacheUpdate {
43
- _headersToCheck;
44
- _generatePayload;
45
- _notifyAllClients;
46
- constructor({ generatePayload, headersToCheck, notifyAllClients } = {}){
47
- this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;
48
- this._generatePayload = generatePayload || defaultPayloadGenerator;
49
- this._notifyAllClients = notifyAllClients ?? NOTIFY_ALL_CLIENTS;
50
- }
51
- async notifyIfUpdated(options) {
52
- if (process.env.NODE_ENV !== "production") {
53
- assert.isType(options.cacheName, "string", {
54
- moduleName: "@serwist/broadcast-update",
55
- className: "BroadcastCacheUpdate",
56
- funcName: "notifyIfUpdated",
57
- paramName: "cacheName"
58
- });
59
- assert.isInstance(options.newResponse, Response, {
60
- moduleName: "@serwist/broadcast-update",
61
- className: "BroadcastCacheUpdate",
62
- funcName: "notifyIfUpdated",
63
- paramName: "newResponse"
64
- });
65
- assert.isInstance(options.request, Request, {
66
- moduleName: "@serwist/broadcast-update",
67
- className: "BroadcastCacheUpdate",
68
- funcName: "notifyIfUpdated",
69
- paramName: "request"
70
- });
71
- }
72
- if (!options.oldResponse) {
73
- return;
74
- }
75
- if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {
76
- if (process.env.NODE_ENV !== "production") {
77
- logger.log("Newer response found (and cached) for:", options.request.url);
78
- }
79
- const messageData = {
80
- type: CACHE_UPDATED_MESSAGE_TYPE,
81
- meta: CACHE_UPDATED_MESSAGE_META,
82
- payload: this._generatePayload(options)
83
- };
84
- if (options.request.mode === "navigate") {
85
- let resultingClientId;
86
- if (options.event instanceof FetchEvent) {
87
- resultingClientId = options.event.resultingClientId;
88
- }
89
- const resultingWin = await resultingClientExists(resultingClientId);
90
- if (!resultingWin || isSafari) {
91
- await timeout(3500);
92
- }
93
- }
94
- if (this._notifyAllClients) {
95
- const windows = await self.clients.matchAll({
96
- type: "window"
97
- });
98
- for (const win of windows){
99
- win.postMessage(messageData);
100
- }
101
- } else {
102
- if (options.event instanceof FetchEvent) {
103
- const client = await self.clients.get(options.event.clientId);
104
- client?.postMessage(messageData);
105
- }
106
- }
107
- }
108
- }
109
- }
110
-
111
- class BroadcastUpdatePlugin {
112
- _broadcastUpdate;
113
- constructor(options){
114
- this._broadcastUpdate = new BroadcastCacheUpdate(options);
115
- }
116
- cacheDidUpdate = async (options)=>{
117
- dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));
118
- };
119
- }
120
-
121
- export { BroadcastCacheUpdate, BroadcastUpdatePlugin, responsesAreSame };
1
+ export { BroadcastCacheUpdate, BroadcastUpdatePlugin, BROADCAST_UPDATE_MESSAGE_META as CACHE_UPDATED_MESSAGE_META, BROADCAST_UPDATE_MESSAGE_TYPE as CACHE_UPDATED_MESSAGE_TYPE, BROADCAST_UPDATE_DEFAULT_HEADERS as defaultHeadersToCheck, responsesAreSame } from '@serwist/sw/plugins';
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@serwist/broadcast-update",
3
- "version": "9.0.0-preview.2",
3
+ "version": "9.0.0-preview.21",
4
4
  "type": "module",
5
- "description": "A service worker helper library that uses the Broadcast Channel API to announce when a cached response has updated",
5
+ "description": "A module that uses the Broadcast Channel API to announce when a cached response has updated.",
6
6
  "files": [
7
7
  "src",
8
8
  "dist"
@@ -17,8 +17,8 @@
17
17
  ],
18
18
  "author": "Google's Web DevRel Team, Serwist's Team",
19
19
  "license": "MIT",
20
- "repository": "serwist/serwist",
21
- "bugs": "https://github.com/serwist/serwist/issues",
20
+ "repository": "https://gitlab.com/serwist/serwist",
21
+ "bugs": "https://gitlab.com/serwist/serwist/issues",
22
22
  "homepage": "https://serwist.pages.dev",
23
23
  "main": "./dist/index.js",
24
24
  "types": "./dist/index.d.ts",
@@ -29,12 +29,12 @@
29
29
  }
30
30
  },
31
31
  "dependencies": {
32
- "@serwist/core": "9.0.0-preview.2"
32
+ "@serwist/sw": "9.0.0-preview.21"
33
33
  },
34
34
  "devDependencies": {
35
- "rollup": "4.9.6",
36
- "typescript": "5.4.0-dev.20240206",
37
- "@serwist/constants": "9.0.0-preview.2"
35
+ "rollup": "4.13.0",
36
+ "typescript": "5.5.0-dev.20240323",
37
+ "@serwist/constants": "9.0.0-preview.21"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "typescript": ">=5.0.0"
package/src/index.ts CHANGED
@@ -6,15 +6,12 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import type { BroadcastCacheUpdateOptions } from "./BroadcastCacheUpdate.js";
10
- import { BroadcastCacheUpdate } from "./BroadcastCacheUpdate.js";
11
- import { BroadcastUpdatePlugin } from "./BroadcastUpdatePlugin.js";
12
- import { responsesAreSame } from "./responsesAreSame.js";
13
-
14
- /**
15
- * @module workbox-broadcast-update
16
- */
17
-
18
- export { BroadcastCacheUpdate, BroadcastUpdatePlugin, responsesAreSame };
19
-
20
- export type { BroadcastCacheUpdateOptions };
9
+ export {
10
+ BroadcastCacheUpdate,
11
+ BroadcastUpdatePlugin,
12
+ responsesAreSame,
13
+ BROADCAST_UPDATE_MESSAGE_META as CACHE_UPDATED_MESSAGE_META,
14
+ BROADCAST_UPDATE_MESSAGE_TYPE as CACHE_UPDATED_MESSAGE_TYPE,
15
+ BROADCAST_UPDATE_DEFAULT_HEADERS as defaultHeadersToCheck,
16
+ } from "@serwist/sw/plugins";
17
+ export type { BroadcastCacheUpdateOptions, BroadcastPayload, BroadcastPayloadGenerator, BroadcastMessage } from "@serwist/sw/plugins";
@@ -1,71 +0,0 @@
1
- import type { CacheDidUpdateCallbackParam } from "@serwist/core";
2
- export interface BroadcastCacheUpdateOptions {
3
- /**
4
- * A list of headers that will be used to determine whether the responses
5
- * differ.
6
- *
7
- * @default ['content-length', 'etag', 'last-modified']
8
- */
9
- headersToCheck?: string[];
10
- /**
11
- * A function whose return value
12
- * will be used as the `payload` field in any cache update messages sent
13
- * to the window clients.
14
- * @param options
15
- * @returns
16
- */
17
- generatePayload?: (options: CacheDidUpdateCallbackParam) => Record<string, any>;
18
- /**
19
- * If true (the default) then all open clients will receive a message. If false,
20
- * then only the client that make the original request will be notified of the update.
21
- *
22
- * @default true
23
- */
24
- notifyAllClients?: boolean;
25
- }
26
- /**
27
- * Uses the `postMessage()` API to inform any open windows/tabs when a cached
28
- * response has been updated.
29
- *
30
- * For efficiency's sake, the underlying response bodies are not compared;
31
- * only specific response headers are checked.
32
- */
33
- declare class BroadcastCacheUpdate {
34
- private readonly _headersToCheck;
35
- private readonly _generatePayload;
36
- private readonly _notifyAllClients;
37
- /**
38
- * Construct a BroadcastCacheUpdate instance with a specific `channelName` to
39
- * broadcast messages on
40
- *
41
- * @param options
42
- */
43
- constructor({ generatePayload, headersToCheck, notifyAllClients }?: BroadcastCacheUpdateOptions);
44
- /**
45
- * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)
46
- * and sends a message (via `postMessage()`) to all window clients if the
47
- * responses differ. Neither of the Responses can be
48
- * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
49
- *
50
- * The message that's posted has the following format (where `payload` can
51
- * be customized via the `generatePayload` option the instance is created
52
- * with):
53
- *
54
- * ```
55
- * {
56
- * type: 'CACHE_UPDATED',
57
- * meta: 'workbox-broadcast-update',
58
- * payload: {
59
- * cacheName: 'the-cache-name',
60
- * updatedURL: 'https://example.com/'
61
- * }
62
- * }
63
- * ```
64
- *
65
- * @param options
66
- * @returns Resolves once the update is sent.
67
- */
68
- notifyIfUpdated(options: CacheDidUpdateCallbackParam): Promise<void>;
69
- }
70
- export { BroadcastCacheUpdate };
71
- //# sourceMappingURL=BroadcastCacheUpdate.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"BroadcastCacheUpdate.d.ts","sourceRoot":"","sources":["../src/BroadcastCacheUpdate.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAcjE,MAAM,WAAW,2BAA2B;IAC1C;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,2BAA2B,KAAK,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAChF;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAgBD;;;;;;GAMG;AACH,cAAM,oBAAoB;IACxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAW;IAC3C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAgE;IACjG,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAU;IAE5C;;;;;OAKG;gBACS,EAAE,eAAe,EAAE,cAAc,EAAE,gBAAgB,EAAE,GAAE,2BAAgC;IAMnG;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACG,eAAe,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC;CA4E3E;AAED,OAAO,EAAE,oBAAoB,EAAE,CAAC"}
@@ -1,28 +0,0 @@
1
- import type { SerwistPlugin } from "@serwist/core";
2
- import type { BroadcastCacheUpdateOptions } from "./BroadcastCacheUpdate.js";
3
- /**
4
- * This plugin will automatically broadcast a message whenever a cached response
5
- * is updated.
6
- */
7
- declare class BroadcastUpdatePlugin implements SerwistPlugin {
8
- private readonly _broadcastUpdate;
9
- /**
10
- * Construct a `@serwist/broadcast-update.BroadcastCacheUpdate` instance with
11
- * the passed options and calls its `notifyIfUpdated` method whenever the
12
- * plugin's `cacheDidUpdate` callback is invoked.
13
- *
14
- * @param options
15
- */
16
- constructor(options?: BroadcastCacheUpdateOptions);
17
- /**
18
- * A "lifecycle" callback that will be triggered automatically by
19
- * `@serwist/build.RuntimeCaching` handlers when an entry is
20
- * added to a cache.
21
- *
22
- * @private
23
- * @param options The input object to this function.
24
- */
25
- cacheDidUpdate: SerwistPlugin["cacheDidUpdate"];
26
- }
27
- export { BroadcastUpdatePlugin };
28
- //# sourceMappingURL=BroadcastUpdatePlugin.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"BroadcastUpdatePlugin.d.ts","sourceRoot":"","sources":["../src/BroadcastUpdatePlugin.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAGnD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAG7E;;;GAGG;AACH,cAAM,qBAAsB,YAAW,aAAa;IAClD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAuB;IAExD;;;;;;OAMG;gBACS,OAAO,CAAC,EAAE,2BAA2B;IAIjD;;;;;;;OAOG;IACH,cAAc,EAAE,aAAa,CAAC,gBAAgB,CAAC,CAE7C;CACH;AAED,OAAO,EAAE,qBAAqB,EAAE,CAAC"}
@@ -1,12 +0,0 @@
1
- /**
2
- * Given two `Response's`, compares several header values to see if they are
3
- * the same or not.
4
- *
5
- * @param firstResponse
6
- * @param secondResponse
7
- * @param headersToCheck
8
- * @returns
9
- */
10
- declare const responsesAreSame: (firstResponse: Response, secondResponse: Response, headersToCheck: string[]) => boolean;
11
- export { responsesAreSame };
12
- //# sourceMappingURL=responsesAreSame.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"responsesAreSame.d.ts","sourceRoot":"","sources":["../src/responsesAreSame.ts"],"names":[],"mappings":"AAUA;;;;;;;;GAQG;AACH,QAAA,MAAM,gBAAgB,kBAAmB,QAAQ,kBAAkB,QAAQ,kBAAkB,MAAM,EAAE,KAAG,OA4BvG,CAAC;AAEF,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
@@ -1,5 +0,0 @@
1
- export declare const CACHE_UPDATED_MESSAGE_TYPE = "CACHE_UPDATED";
2
- export declare const CACHE_UPDATED_MESSAGE_META = "serwist-broadcast-update";
3
- export declare const NOTIFY_ALL_CLIENTS = true;
4
- export declare const DEFAULT_HEADERS_TO_CHECK: string[];
5
- //# sourceMappingURL=constants.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/utils/constants.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,0BAA0B,kBAAkB,CAAC;AAC1D,eAAO,MAAM,0BAA0B,6BAA6B,CAAC;AACrE,eAAO,MAAM,kBAAkB,OAAO,CAAC;AACvC,eAAO,MAAM,wBAAwB,EAAE,MAAM,EAAgD,CAAC"}
@@ -1,188 +0,0 @@
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 { CacheDidUpdateCallbackParam } from "@serwist/core";
10
- import { assert, logger, resultingClientExists, timeout } from "@serwist/core/internal";
11
-
12
- import { responsesAreSame } from "./responsesAreSame.js";
13
- import { CACHE_UPDATED_MESSAGE_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS } from "./utils/constants.js";
14
-
15
- // UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser
16
- // TODO(philipwalton): remove once this Safari bug fix has been released.
17
- // https://bugs.webkit.org/show_bug.cgi?id=201169
18
- const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
19
-
20
- // Give TypeScript the correct global.
21
- declare let self: ServiceWorkerGlobalScope;
22
-
23
- export interface BroadcastCacheUpdateOptions {
24
- /**
25
- * A list of headers that will be used to determine whether the responses
26
- * differ.
27
- *
28
- * @default ['content-length', 'etag', 'last-modified']
29
- */
30
- headersToCheck?: string[];
31
- /**
32
- * A function whose return value
33
- * will be used as the `payload` field in any cache update messages sent
34
- * to the window clients.
35
- * @param options
36
- * @returns
37
- */
38
- generatePayload?: (options: CacheDidUpdateCallbackParam) => Record<string, any>;
39
- /**
40
- * If true (the default) then all open clients will receive a message. If false,
41
- * then only the client that make the original request will be notified of the update.
42
- *
43
- * @default true
44
- */
45
- notifyAllClients?: boolean;
46
- }
47
-
48
- /**
49
- * Generates the default payload used in update messages. By default the
50
- * payload includes the `cacheName` and `updatedURL` fields.
51
- *
52
- * @returns
53
- * @private
54
- */
55
- function defaultPayloadGenerator(data: CacheDidUpdateCallbackParam): Record<string, any> {
56
- return {
57
- cacheName: data.cacheName,
58
- updatedURL: data.request.url,
59
- };
60
- }
61
-
62
- /**
63
- * Uses the `postMessage()` API to inform any open windows/tabs when a cached
64
- * response has been updated.
65
- *
66
- * For efficiency's sake, the underlying response bodies are not compared;
67
- * only specific response headers are checked.
68
- */
69
- class BroadcastCacheUpdate {
70
- private readonly _headersToCheck: string[];
71
- private readonly _generatePayload: (options: CacheDidUpdateCallbackParam) => Record<string, any>;
72
- private readonly _notifyAllClients: boolean;
73
-
74
- /**
75
- * Construct a BroadcastCacheUpdate instance with a specific `channelName` to
76
- * broadcast messages on
77
- *
78
- * @param options
79
- */
80
- constructor({ generatePayload, headersToCheck, notifyAllClients }: BroadcastCacheUpdateOptions = {}) {
81
- this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;
82
- this._generatePayload = generatePayload || defaultPayloadGenerator;
83
- this._notifyAllClients = notifyAllClients ?? NOTIFY_ALL_CLIENTS;
84
- }
85
-
86
- /**
87
- * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)
88
- * and sends a message (via `postMessage()`) to all window clients if the
89
- * responses differ. Neither of the Responses can be
90
- * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
91
- *
92
- * The message that's posted has the following format (where `payload` can
93
- * be customized via the `generatePayload` option the instance is created
94
- * with):
95
- *
96
- * ```
97
- * {
98
- * type: 'CACHE_UPDATED',
99
- * meta: 'workbox-broadcast-update',
100
- * payload: {
101
- * cacheName: 'the-cache-name',
102
- * updatedURL: 'https://example.com/'
103
- * }
104
- * }
105
- * ```
106
- *
107
- * @param options
108
- * @returns Resolves once the update is sent.
109
- */
110
- async notifyIfUpdated(options: CacheDidUpdateCallbackParam): Promise<void> {
111
- if (process.env.NODE_ENV !== "production") {
112
- assert!.isType(options.cacheName, "string", {
113
- moduleName: "@serwist/broadcast-update",
114
- className: "BroadcastCacheUpdate",
115
- funcName: "notifyIfUpdated",
116
- paramName: "cacheName",
117
- });
118
- assert!.isInstance(options.newResponse, Response, {
119
- moduleName: "@serwist/broadcast-update",
120
- className: "BroadcastCacheUpdate",
121
- funcName: "notifyIfUpdated",
122
- paramName: "newResponse",
123
- });
124
- assert!.isInstance(options.request, Request, {
125
- moduleName: "@serwist/broadcast-update",
126
- className: "BroadcastCacheUpdate",
127
- funcName: "notifyIfUpdated",
128
- paramName: "request",
129
- });
130
- }
131
-
132
- // Without two responses there is nothing to compare.
133
- if (!options.oldResponse) {
134
- return;
135
- }
136
-
137
- if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {
138
- if (process.env.NODE_ENV !== "production") {
139
- logger.log("Newer response found (and cached) for:", options.request.url);
140
- }
141
-
142
- const messageData = {
143
- type: CACHE_UPDATED_MESSAGE_TYPE,
144
- meta: CACHE_UPDATED_MESSAGE_META,
145
- payload: this._generatePayload(options),
146
- };
147
-
148
- // For navigation requests, wait until the new window client exists
149
- // before sending the message
150
- if (options.request.mode === "navigate") {
151
- let resultingClientId: string | undefined;
152
- if (options.event instanceof FetchEvent) {
153
- resultingClientId = options.event.resultingClientId;
154
- }
155
-
156
- const resultingWin = await resultingClientExists(resultingClientId);
157
-
158
- // Safari does not currently implement postMessage buffering and
159
- // there's no good way to feature detect that, so to increase the
160
- // chances of the message being delivered in Safari, we add a timeout.
161
- // We also do this if `resultingClientExists()` didn't return a client,
162
- // which means it timed out, so it's worth waiting a bit longer.
163
- if (!resultingWin || isSafari) {
164
- // 3500 is chosen because (according to CrUX data) 80% of mobile
165
- // websites hit the DOMContentLoaded event in less than 3.5 seconds.
166
- // And presumably sites implementing service worker are on the
167
- // higher end of the performance spectrum.
168
- await timeout(3500);
169
- }
170
- }
171
-
172
- if (this._notifyAllClients) {
173
- const windows = await self.clients.matchAll({ type: "window" });
174
- for (const win of windows) {
175
- win.postMessage(messageData);
176
- }
177
- } else {
178
- // See https://github.com/GoogleChrome/workbox/issues/2895
179
- if (options.event instanceof FetchEvent) {
180
- const client = await self.clients.get(options.event.clientId);
181
- client?.postMessage(messageData);
182
- }
183
- }
184
- }
185
- }
186
- }
187
-
188
- export { BroadcastCacheUpdate };
@@ -1,46 +0,0 @@
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 { SerwistPlugin } from "@serwist/core";
10
- import { dontWaitFor } from "@serwist/core/internal";
11
-
12
- import type { BroadcastCacheUpdateOptions } from "./BroadcastCacheUpdate.js";
13
- import { BroadcastCacheUpdate } from "./BroadcastCacheUpdate.js";
14
-
15
- /**
16
- * This plugin will automatically broadcast a message whenever a cached response
17
- * is updated.
18
- */
19
- class BroadcastUpdatePlugin implements SerwistPlugin {
20
- private readonly _broadcastUpdate: BroadcastCacheUpdate;
21
-
22
- /**
23
- * Construct a `@serwist/broadcast-update.BroadcastCacheUpdate` instance with
24
- * the passed options and calls its `notifyIfUpdated` method whenever the
25
- * plugin's `cacheDidUpdate` callback is invoked.
26
- *
27
- * @param options
28
- */
29
- constructor(options?: BroadcastCacheUpdateOptions) {
30
- this._broadcastUpdate = new BroadcastCacheUpdate(options);
31
- }
32
-
33
- /**
34
- * A "lifecycle" callback that will be triggered automatically by
35
- * `@serwist/build.RuntimeCaching` handlers when an entry is
36
- * added to a cache.
37
- *
38
- * @private
39
- * @param options The input object to this function.
40
- */
41
- cacheDidUpdate: SerwistPlugin["cacheDidUpdate"] = async (options) => {
42
- dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));
43
- };
44
- }
45
-
46
- export { BroadcastUpdatePlugin };
@@ -1,50 +0,0 @@
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 { SerwistError, logger } from "@serwist/core/internal";
10
-
11
- /**
12
- * Given two `Response's`, compares several header values to see if they are
13
- * the same or not.
14
- *
15
- * @param firstResponse
16
- * @param secondResponse
17
- * @param headersToCheck
18
- * @returns
19
- */
20
- const responsesAreSame = (firstResponse: Response, secondResponse: Response, headersToCheck: string[]): boolean => {
21
- if (process.env.NODE_ENV !== "production") {
22
- if (!(firstResponse instanceof Response && secondResponse instanceof Response)) {
23
- throw new SerwistError("invalid-responses-are-same-args");
24
- }
25
- }
26
-
27
- const atLeastOneHeaderAvailable = headersToCheck.some((header) => {
28
- return firstResponse.headers.has(header) && secondResponse.headers.has(header);
29
- });
30
-
31
- if (!atLeastOneHeaderAvailable) {
32
- if (process.env.NODE_ENV !== "production") {
33
- logger.warn("Unable to determine where the response has been updated " + "because none of the headers that would be checked are present.");
34
- logger.debug("Attempting to compare the following: ", firstResponse, secondResponse, headersToCheck);
35
- }
36
-
37
- // Just return true, indicating the that responses are the same, since we
38
- // can't determine otherwise.
39
- return true;
40
- }
41
-
42
- return headersToCheck.every((header) => {
43
- const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header);
44
- const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header);
45
-
46
- return headerStateComparison && headerValueComparison;
47
- });
48
- };
49
-
50
- export { responsesAreSame };
@@ -1,12 +0,0 @@
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
- export const CACHE_UPDATED_MESSAGE_TYPE = "CACHE_UPDATED";
10
- export const CACHE_UPDATED_MESSAGE_META = "serwist-broadcast-update";
11
- export const NOTIFY_ALL_CLIENTS = true;
12
- export const DEFAULT_HEADERS_TO_CHECK: string[] = ["content-length", "etag", "last-modified"];