@serwist/window 9.0.0-preview.0 → 9.0.0-preview.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Serwist.d.ts CHANGED
@@ -31,13 +31,11 @@ export declare class Serwist extends SerwistEventTarget {
31
31
  * options. The script URL and options are the same as those used when
32
32
  * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).
33
33
  *
34
- * @param scriptURL The service worker script
35
- * associated with this instance. Using a
36
- * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.
37
- * @param registerOptions The service worker options associated
38
- * with this instance.
34
+ * @param scriptURL The service worker script associated with this instance. Using a
35
+ * [`TrustedScriptURL`](https://developer.mozilla.org/en-US/docs/Web/API/TrustedScriptURL) is supported.
36
+ * @param registerOptions The service worker options associated with this instance.
39
37
  */
40
- constructor(scriptURL: string | TrustedScriptURL, registerOptions?: {});
38
+ constructor(scriptURL: string | TrustedScriptURL, registerOptions?: RegistrationOptions);
41
39
  /**
42
40
  * Registers a service worker for this instances script URL and service
43
41
  * worker options. By default this method delays registration until after
@@ -108,7 +106,7 @@ export declare class Serwist extends SerwistEventTarget {
108
106
  * @param data An object to send to the service worker
109
107
  * @returns
110
108
  */
111
- messageSW(data: object): Promise<any>;
109
+ messageSW(data: any): Promise<any>;
112
110
  /**
113
111
  * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's
114
112
  * currently in the `waiting` state associated with the current registration.
@@ -1 +1 @@
1
- {"version":3,"file":"Serwist.d.ts","sourceRoot":"","sources":["../src/Serwist.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAK1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAgBnE;;;;;;;;;;GAUG;AACH,qBAAa,OAAQ,SAAQ,kBAAkB;IAC7C,OAAO,CAAC,QAAQ,CAAC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;;;;;;;;;GAiBG;AAEH;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;;;;;GAaG"}
package/dist/index.js CHANGED
@@ -1,25 +1,6 @@
1
- import { Deferred, logger, dontWaitFor } from '@serwist/core/internal';
1
+ import { Deferred, logger } from '@serwist/core/internal';
2
2
 
3
- /*
4
- Copyright 2019 Google LLC
5
-
6
- Use of this source code is governed by an MIT-style
7
- license that can be found in the LICENSE file or at
8
- https://opensource.org/licenses/MIT.
9
- */ /**
10
- * Sends a data object to a service worker via `postMessage` and resolves with
11
- * a response (if any).
12
- *
13
- * A response can be set in a message handler in the service worker by
14
- * calling `event.ports[0].postMessage(...)`, which will resolve the promise
15
- * returned by `messageSW()`. If no response is set, the promise will not
16
- * resolve.
17
- *
18
- * @param sw The service worker to send the message to.
19
- * @param data An object to send to the service worker.
20
- * @returns
21
- */ // biome-ignore lint/complexity/noBannedTypes: Better not change type of data.
22
- function messageSW(sw, data) {
3
+ const messageSW = (sw, data)=>{
23
4
  return new Promise((resolve)=>{
24
5
  const messageChannel = new MessageChannel();
25
6
  messageChannel.port1.onmessage = (event)=>{
@@ -29,20 +10,9 @@ function messageSW(sw, data) {
29
10
  messageChannel.port2
30
11
  ]);
31
12
  });
32
- }
33
-
34
- /*
35
- Copyright 2019 Google LLC
13
+ };
36
14
 
37
- Use of this source code is governed by an MIT-style
38
- license that can be found in the LICENSE file or at
39
- https://opensource.org/licenses/MIT.
40
- */ /**
41
- * A minimal `Event` subclass shim.
42
- * This doesn't *actually* subclass `Event` because not all browsers support
43
- * constructable `EventTarget`, and using a real `Event` will error.
44
- * @private
45
- */ class SerwistEvent {
15
+ class SerwistEvent {
46
16
  type;
47
17
  target;
48
18
  sw;
@@ -54,52 +24,23 @@ function messageSW(sw, data) {
54
24
  }
55
25
  }
56
26
 
57
- /*
58
- Copyright 2019 Google LLC
59
-
60
- Use of this source code is governed by an MIT-style
61
- license that can be found in the LICENSE file or at
62
- https://opensource.org/licenses/MIT.
63
- */ /**
64
- * A minimal `EventTarget` shim.
65
- * This is necessary because not all browsers support constructable
66
- * `EventTarget`, so using a real `EventTarget` will error.
67
- * @private
68
- */ class SerwistEventTarget {
27
+ class SerwistEventTarget {
69
28
  _eventListenerRegistry = new Map();
70
- /**
71
- * @param type
72
- * @param listener
73
- * @private
74
- */ addEventListener(type, listener) {
29
+ addEventListener(type, listener) {
75
30
  const foo = this._getEventListenersByType(type);
76
31
  foo.add(listener);
77
32
  }
78
- /**
79
- * @param type
80
- * @param listener
81
- * @private
82
- */ removeEventListener(type, listener) {
33
+ removeEventListener(type, listener) {
83
34
  this._getEventListenersByType(type).delete(listener);
84
35
  }
85
- /**
86
- * @param event
87
- * @private
88
- */ dispatchEvent(event) {
36
+ dispatchEvent(event) {
89
37
  event.target = this;
90
38
  const listeners = this._getEventListenersByType(event.type);
91
39
  for (const listener of listeners){
92
40
  listener(event);
93
41
  }
94
42
  }
95
- /**
96
- * Returns a Set of listeners associated with the passed event type.
97
- * If no handlers have been registered, an empty Set is returned.
98
- *
99
- * @param type The event type.
100
- * @returns An array of handler functions.
101
- * @private
102
- */ _getEventListenersByType(type) {
43
+ _getEventListenersByType(type) {
103
44
  if (!this._eventListenerRegistry.has(type)) {
104
45
  this._eventListenerRegistry.set(type, new Set());
105
46
  }
@@ -107,52 +48,20 @@ function messageSW(sw, data) {
107
48
  }
108
49
  }
109
50
 
110
- /*
111
- Copyright 2019 Google LLC
112
-
113
- Use of this source code is governed by an MIT-style
114
- license that can be found in the LICENSE file or at
115
- https://opensource.org/licenses/MIT.
116
- */ /**
117
- * Returns true if two URLs have the same `.href` property. The URLS can be
118
- * relative, and if they are the current location href is used to resolve URLs.
119
- *
120
- * @private
121
- * @param url1
122
- * @param url2
123
- * @returns
124
- */ function urlsMatch(url1, url2) {
51
+ function urlsMatch(url1, url2) {
125
52
  const { href } = location;
126
53
  return new URL(url1, href).href === new URL(url2, href).href;
127
54
  }
128
55
 
129
- // The time a SW must be in the waiting phase before we can conclude
130
- // `skipWaiting()` wasn't called. This 200 amount wasn't scientifically
131
- // chosen, but it seems to avoid false positives in my testing.
132
56
  const WAITING_TIMEOUT_DURATION = 200;
133
- // The amount of time after a registration that we can reasonably conclude
134
- // that the registration didn't trigger an update.
135
57
  const REGISTRATION_TIMEOUT_DURATION = 60000;
136
- // The de facto standard message that a service worker should be listening for
137
- // to trigger a call to skipWaiting().
138
58
  const SKIP_WAITING_MESSAGE = {
139
59
  type: "SKIP_WAITING"
140
60
  };
141
- /**
142
- * A class to aid in handling service worker registration, updates, and
143
- * reacting to service worker lifecycle events.
144
- *
145
- * @fires `@serwist/window.Serwist.message`
146
- * @fires `@serwist/window.Serwist.installed`
147
- * @fires `@serwist/window.Serwist.waiting`
148
- * @fires `@serwist/window.Serwist.controlling`
149
- * @fires `@serwist/window.Serwist.activated`
150
- * @fires `@serwist/window.Serwist.redundant`
151
- */ class Serwist extends SerwistEventTarget {
61
+ class Serwist extends SerwistEventTarget {
152
62
  _scriptURL;
153
63
  _registerOptions = {};
154
64
  _updateFoundCount = 0;
155
- // Deferreds we can resolve later.
156
65
  _swDeferred = new Deferred();
157
66
  _activeDeferred = new Deferred();
158
67
  _controllingDeferred = new Deferred();
@@ -164,52 +73,25 @@ const SKIP_WAITING_MESSAGE = {
164
73
  _ownSWs = new Set();
165
74
  _externalSW;
166
75
  _waitingTimeout;
167
- /**
168
- * Creates a new Serwist instance with a script URL and service worker
169
- * options. The script URL and options are the same as those used when
170
- * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).
171
- *
172
- * @param scriptURL The service worker script
173
- * associated with this instance. Using a
174
- * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.
175
- * @param registerOptions The service worker options associated
176
- * with this instance.
177
- */ // biome-ignore lint/complexity/noBannedTypes: Unknown reason
178
76
  constructor(scriptURL, registerOptions = {}){
179
77
  super();
180
78
  this._scriptURL = scriptURL;
181
79
  this._registerOptions = registerOptions;
182
- // Add a message listener immediately since messages received during
183
- // page load are buffered only until the DOMContentLoaded event:
184
- // https://github.com/GoogleChrome/workbox/issues/2202
185
80
  navigator.serviceWorker.addEventListener("message", this._onMessage);
186
81
  }
187
- /**
188
- * Registers a service worker for this instances script URL and service
189
- * worker options. By default this method delays registration until after
190
- * the window has loaded.
191
- *
192
- * @param options
193
- */ async register({ immediate = false } = {}) {
82
+ async register({ immediate = false } = {}) {
194
83
  if (process.env.NODE_ENV !== "production") {
195
84
  if (this._registrationTime) {
196
- logger.error("Cannot re-register a Serwist instance after it has " + "been registered. Create a new instance instead.");
85
+ logger.error("Cannot re-register a Serwist instance after it has been registered. Create a new instance instead.");
197
86
  return;
198
87
  }
199
88
  }
200
89
  if (!immediate && document.readyState !== "complete") {
201
90
  await new Promise((res)=>window.addEventListener("load", res));
202
91
  }
203
- // Set this flag to true if any service worker was controlling the page
204
- // at registration time.
205
92
  this._isUpdate = Boolean(navigator.serviceWorker.controller);
206
- // Before registering, attempt to determine if a SW is already controlling
207
- // the page, and if that SW script (and version, if specified) matches this
208
- // instance's script.
209
93
  this._compatibleControllingSW = this._getControllingSWIfCompatible();
210
94
  this._registration = await this._registerScript();
211
- // If we have a compatible controller, store the controller as the "own"
212
- // SW, resolve active/controlling deferreds and add necessary listeners.
213
95
  if (this._compatibleControllingSW) {
214
96
  this._sw = this._compatibleControllingSW;
215
97
  this._activeDeferred.resolve(this._compatibleControllingSW);
@@ -218,29 +100,19 @@ const SKIP_WAITING_MESSAGE = {
218
100
  once: true
219
101
  });
220
102
  }
221
- // If there's a waiting service worker with a matching URL before the
222
- // `updatefound` event fires, it likely means that this site is open
223
- // in another tab, or the user refreshed the page (and thus the previous
224
- // page wasn't fully unloaded before this page started loading).
225
- // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting
226
103
  const waitingSW = this._registration.waiting;
227
104
  if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {
228
- // Store the waiting SW as the "own" Sw, even if it means overwriting
229
- // a compatible controller.
230
105
  this._sw = waitingSW;
231
- // Run this in the next microtask, so any code that adds an event
232
- // listener after awaiting `register()` will get this event.
233
- dontWaitFor(Promise.resolve().then(()=>{
106
+ void Promise.resolve().then(()=>{
234
107
  this.dispatchEvent(new SerwistEvent("waiting", {
235
108
  sw: waitingSW,
236
109
  wasWaitingBeforeRegister: true
237
110
  }));
238
111
  if (process.env.NODE_ENV !== "production") {
239
- logger.warn("A service worker was already waiting to activate " + "before this script was registered...");
112
+ logger.warn("A service worker was already waiting to activate before this script was registered...");
240
113
  }
241
- }));
114
+ });
242
115
  }
243
- // If an "own" SW is already set, resolve the deferred.
244
116
  if (this._sw) {
245
117
  this._swDeferred.resolve(this._sw);
246
118
  this._ownSWs.add(this._sw);
@@ -249,9 +121,9 @@ const SKIP_WAITING_MESSAGE = {
249
121
  logger.log("Successfully registered service worker.", this._scriptURL.toString());
250
122
  if (navigator.serviceWorker.controller) {
251
123
  if (this._compatibleControllingSW) {
252
- logger.debug("A service worker with the same script URL " + "is already controlling this page.");
124
+ logger.debug("A service worker with the same script URL is already controlling this page.");
253
125
  } else {
254
- logger.debug("A service worker with a different script URL is " + "currently controlling the page. The browser is now fetching " + "the new script now...");
126
+ logger.debug("A service worker with a different script URL is currently controlling the page. The browser is now fetching the new script now...");
255
127
  }
256
128
  }
257
129
  const currentPageIsOutOfScope = ()=>{
@@ -260,172 +132,67 @@ const SKIP_WAITING_MESSAGE = {
260
132
  return !location.pathname.startsWith(scopeURLBasePath);
261
133
  };
262
134
  if (currentPageIsOutOfScope()) {
263
- logger.warn("The current page is not in scope for the registered " + "service worker. Was this a mistake?");
135
+ logger.warn("The current page is not in scope for the registered service worker. Was this a mistake?");
264
136
  }
265
137
  }
266
138
  this._registration.addEventListener("updatefound", this._onUpdateFound);
267
139
  navigator.serviceWorker.addEventListener("controllerchange", this._onControllerChange);
268
140
  return this._registration;
269
141
  }
270
- /**
271
- * Checks for updates of the registered service worker.
272
- */ async update() {
142
+ async update() {
273
143
  if (!this._registration) {
274
144
  if (process.env.NODE_ENV !== "production") {
275
- logger.error("Cannot update a Serwist instance without " + "being registered. Register the Serwist instance first.");
145
+ logger.error("Cannot update a Serwist instance without being registered. Register the Serwist instance first.");
276
146
  }
277
147
  return;
278
148
  }
279
- // Try to update registration
280
149
  await this._registration.update();
281
150
  }
282
- /**
283
- * Resolves to the service worker registered by this instance as soon as it
284
- * is active. If a service worker was already controlling at registration
285
- * time then it will resolve to that if the script URLs (and optionally
286
- * script versions) match, otherwise it will wait until an update is found
287
- * and activates.
288
- *
289
- * @returns
290
- */ get active() {
151
+ get active() {
291
152
  return this._activeDeferred.promise;
292
153
  }
293
- /**
294
- * Resolves to the service worker registered by this instance as soon as it
295
- * is controlling the page. If a service worker was already controlling at
296
- * registration time then it will resolve to that if the script URLs (and
297
- * optionally script versions) match, otherwise it will wait until an update
298
- * is found and starts controlling the page.
299
- * Note: the first time a service worker is installed it will active but
300
- * not start controlling the page unless `clients.claim()` is called in the
301
- * service worker.
302
- *
303
- * @returns
304
- */ get controlling() {
154
+ get controlling() {
305
155
  return this._controllingDeferred.promise;
306
156
  }
307
- /**
308
- * Resolves with a reference to a service worker that matches the script URL
309
- * of this instance, as soon as it's available.
310
- *
311
- * If, at registration time, there's already an active or waiting service
312
- * worker with a matching script URL, it will be used (with the waiting
313
- * service worker taking precedence over the active service worker if both
314
- * match, since the waiting service worker would have been registered more
315
- * recently).
316
- * If there's no matching active or waiting service worker at registration
317
- * time then the promise will not resolve until an update is found and starts
318
- * installing, at which point the installing service worker is used.
319
- *
320
- * @returns
321
- */ getSW() {
322
- // If `this._sw` is set, resolve with that as we want `getSW()` to
323
- // return the correct (new) service worker if an update is found.
157
+ getSW() {
324
158
  return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise;
325
159
  }
326
- /**
327
- * Sends the passed data object to the service worker registered by this
328
- * instance (via `@serwist/window.Serwist.getSW`) and resolves
329
- * with a response (if any).
330
- *
331
- * A response can be set in a message handler in the service worker by
332
- * calling `event.ports[0].postMessage(...)`, which will resolve the promise
333
- * returned by `messageSW()`. If no response is set, the promise will never
334
- * resolve.
335
- *
336
- * @param data An object to send to the service worker
337
- * @returns
338
- */ // We might be able to change the 'data' type to Record<string, unknown> in the future.
339
- // eslint-disable-next-line @typescript-eslint/ban-types
340
160
  async messageSW(data) {
341
161
  const sw = await this.getSW();
342
162
  return messageSW(sw, data);
343
163
  }
344
- /**
345
- * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's
346
- * currently in the `waiting` state associated with the current registration.
347
- *
348
- * If there is no current registration or no service worker is `waiting`,
349
- * calling this will have no effect.
350
- */ messageSkipWaiting() {
164
+ messageSkipWaiting() {
351
165
  if (this._registration?.waiting) {
352
166
  void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);
353
167
  }
354
168
  }
355
- /**
356
- * Checks for a service worker already controlling the page and returns
357
- * it if its script URL matches.
358
- *
359
- * @private
360
- * @returns
361
- */ _getControllingSWIfCompatible() {
169
+ _getControllingSWIfCompatible() {
362
170
  const controller = navigator.serviceWorker.controller;
363
171
  if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) {
364
172
  return controller;
365
173
  }
366
174
  return undefined;
367
175
  }
368
- /**
369
- * Registers a service worker for this instances script URL and register
370
- * options and tracks the time registration was complete.
371
- *
372
- * @private
373
- */ async _registerScript() {
176
+ async _registerScript() {
374
177
  try {
375
- // this._scriptURL may be a TrustedScriptURL, but there's no support for
376
- // passing that to register() in lib.dom right now.
377
- // https://github.com/GoogleChrome/workbox/issues/2855
378
178
  const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);
379
- // Keep track of when registration happened, so it can be used in the
380
- // `this._onUpdateFound` heuristic. Also use the presence of this
381
- // property as a way to see if `.register()` has been called.
382
179
  this._registrationTime = performance.now();
383
180
  return reg;
384
181
  } catch (error) {
385
182
  if (process.env.NODE_ENV !== "production") {
386
183
  logger.error(error);
387
184
  }
388
- // Re-throw the error.
389
185
  throw error;
390
186
  }
391
187
  }
392
- /**
393
- * @private
394
- * @param originalEvent
395
- */ _onUpdateFound = (originalEvent)=>{
396
- // `this._registration` will never be `undefined` after an update is found.
188
+ _onUpdateFound = (originalEvent)=>{
397
189
  const registration = this._registration;
398
190
  const installingSW = registration.installing;
399
- // If the script URL passed to `navigator.serviceWorker.register()` is
400
- // different from the current controlling SW's script URL, we know any
401
- // successful registration calls will trigger an `updatefound` event.
402
- // But if the registered script URL is the same as the current controlling
403
- // SW's script URL, we'll only get an `updatefound` event if the file
404
- // changed since it was last registered. This can be a problem if the user
405
- // opens up the same page in a different tab, and that page registers
406
- // a SW that triggers an update. It's a problem because this page has no
407
- // good way of knowing whether the `updatefound` event came from the SW
408
- // script it registered or from a registration attempt made by a newer
409
- // version of the page running in another tab.
410
- // To minimize the possibility of a false positive, we use the logic here:
411
- const updateLikelyTriggeredExternally = // Since we enforce only calling `register()` once, and since we don't
412
- // add the `updatefound` event listener until the `register()` call, if
413
- // `_updateFoundCount` is > 0 then it means this method has already
414
- // been called, thus this SW must be external
415
- this._updateFoundCount > 0 || // If the script URL of the installing SW is different from this
416
- // instance's script URL, we know it's definitely not from our
417
- // registration.
418
- !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || // If all of the above are false, then we use a time-based heuristic:
419
- // Any `updatefound` event that occurs long after our registration is
420
- // assumed to be external.
421
- performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? // triggered by this instance.
422
- true : false;
191
+ const updateLikelyTriggeredExternally = this._updateFoundCount > 0 || !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION;
423
192
  if (updateLikelyTriggeredExternally) {
424
193
  this._externalSW = installingSW;
425
194
  registration.removeEventListener("updatefound", this._onUpdateFound);
426
195
  } else {
427
- // If the update was not triggered externally we know the installing
428
- // SW is the one we registered, so we set it.
429
196
  this._sw = installingSW;
430
197
  this._ownSWs.add(installingSW);
431
198
  this._swDeferred.resolve(installingSW);
@@ -437,25 +204,16 @@ const SKIP_WAITING_MESSAGE = {
437
204
  }
438
205
  }
439
206
  }
440
- // Dispatch the `installing` event when the SW is installing.
441
207
  this.dispatchEvent(new SerwistEvent("installing", {
442
208
  sw: installingSW,
443
209
  originalEvent,
444
210
  isExternal: updateLikelyTriggeredExternally,
445
211
  isUpdate: this._isUpdate
446
212
  }));
447
- // Increment the `updatefound` count, so future invocations of this
448
- // method can be sure they were triggered externally.
449
213
  ++this._updateFoundCount;
450
- // Add a `statechange` listener regardless of whether this update was
451
- // triggered externally, since we have callbacks for both.
452
214
  installingSW.addEventListener("statechange", this._onStateChange);
453
215
  };
454
- /**
455
- * @private
456
- * @param originalEvent
457
- */ _onStateChange = (originalEvent)=>{
458
- // `this._registration` will never be `undefined` after an update is found.
216
+ _onStateChange = (originalEvent)=>{
459
217
  const registration = this._registration;
460
218
  const sw = originalEvent.target;
461
219
  const { state } = sw;
@@ -470,16 +228,7 @@ const SKIP_WAITING_MESSAGE = {
470
228
  }
471
229
  this.dispatchEvent(new SerwistEvent(state, eventProps));
472
230
  if (state === "installed") {
473
- // This timeout is used to ignore cases where the service worker calls
474
- // `skipWaiting()` in the install event, thus moving it directly in the
475
- // activating state. (Since all service workers *must* go through the
476
- // waiting phase, the only way to detect `skipWaiting()` called in the
477
- // install event is to observe that the time spent in the waiting phase
478
- // is very short.)
479
- // NOTE: we don't need separate timeouts for the own and external SWs
480
- // since they can't go through these phases at the same time.
481
231
  this._waitingTimeout = self.setTimeout(()=>{
482
- // Ensure the SW is still waiting (it may now be redundant).
483
232
  if (state === "installed" && registration.waiting === sw) {
484
233
  this.dispatchEvent(new SerwistEvent("waiting", eventProps));
485
234
  if (process.env.NODE_ENV !== "production") {
@@ -526,16 +275,9 @@ const SKIP_WAITING_MESSAGE = {
526
275
  }
527
276
  }
528
277
  };
529
- /**
530
- * @private
531
- * @param originalEvent
532
- */ _onControllerChange = (originalEvent)=>{
278
+ _onControllerChange = (originalEvent)=>{
533
279
  const sw = this._sw;
534
280
  const isExternal = sw !== navigator.serviceWorker.controller;
535
- // Unconditionally dispatch the controlling event, with isExternal set
536
- // to distinguish between controller changes due to the initial registration
537
- // vs. an update-check or other tab's registration.
538
- // See https://github.com/GoogleChrome/workbox/issues/2786
539
281
  this.dispatchEvent(new SerwistEvent("controlling", {
540
282
  isExternal,
541
283
  originalEvent,
@@ -549,26 +291,11 @@ const SKIP_WAITING_MESSAGE = {
549
291
  this._controllingDeferred.resolve(sw);
550
292
  }
551
293
  };
552
- /**
553
- * @private
554
- * @param originalEvent
555
- */ _onMessage = async (originalEvent)=>{
556
- // Can't change type 'any' of data.
557
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
294
+ _onMessage = async (originalEvent)=>{
558
295
  const { data, ports, source } = originalEvent;
559
- // Wait until there's an "own" service worker. This is used to buffer
560
- // `message` events that may be received prior to calling `register()`.
561
296
  await this.getSW();
562
- // If the service worker that sent the message is in the list of own
563
- // service workers for this instance, dispatch a `message` event.
564
- // NOTE: we check for all previously owned service workers rather than
565
- // just the current one because some messages (e.g. cache updates) use
566
- // a timeout when sent and may be delayed long enough for a service worker
567
- // update to be found.
568
297
  if (this._ownSWs.has(source)) {
569
298
  this.dispatchEvent(new SerwistEvent("message", {
570
- // Can't change type 'any' of data.
571
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
572
299
  data,
573
300
  originalEvent,
574
301
  ports,
@@ -576,131 +303,6 @@ const SKIP_WAITING_MESSAGE = {
576
303
  }));
577
304
  }
578
305
  };
579
- } // The jsdoc comments below outline the events this instance may dispatch:
580
- // -----------------------------------------------------------------------
581
- /**
582
- * The `message` event is dispatched any time a `postMessage` is received.
583
- *
584
- * @event workbox-window.Workbox#message
585
- * @type {SerwistEvent}
586
- * @property {*} data The `data` property from the original `message` event.
587
- * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}
588
- * event.
589
- * @property {string} type `message`.
590
- * @property {MessagePort[]} ports The `ports` value from `originalEvent`.
591
- * @property {Workbox} target The `Workbox` instance.
592
- */ /**
593
- * The `installed` event is dispatched if the state of a
594
- * {@link workbox-window.Workbox} instance's
595
- * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}
596
- * changes to `installed`.
597
- *
598
- * Then can happen either the very first time a service worker is installed,
599
- * or after an update to the current service worker is found. In the case
600
- * of an update being found, the event's `isUpdate` property will be `true`.
601
- *
602
- * @event workbox-window.Workbox#installed
603
- * @type {SerwistEvent}
604
- * @property {ServiceWorker} sw The service worker instance.
605
- * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
606
- * event.
607
- * @property {boolean|undefined} isUpdate True if a service worker was already
608
- * controlling when this `Workbox` instance called `register()`.
609
- * @property {boolean|undefined} isExternal True if this event is associated
610
- * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
611
- * @property {string} type `installed`.
612
- * @property {Workbox} target The `Workbox` instance.
613
- */ /**
614
- * The `waiting` event is dispatched if the state of a
615
- * {@link workbox-window.Workbox} instance's
616
- * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
617
- * changes to `installed` and then doesn't immediately change to `activating`.
618
- * It may also be dispatched if a service worker with the same
619
- * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
620
- * was already waiting when the {@link workbox-window.Workbox#register}
621
- * method was called.
622
- *
623
- * @event workbox-window.Workbox#waiting
624
- * @type {SerwistEvent}
625
- * @property {ServiceWorker} sw The service worker instance.
626
- * @property {Event|undefined} originalEvent The original
627
- * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
628
- * event, or `undefined` in the case where the service worker was waiting
629
- * to before `.register()` was called.
630
- * @property {boolean|undefined} isUpdate True if a service worker was already
631
- * controlling when this `Workbox` instance called `register()`.
632
- * @property {boolean|undefined} isExternal True if this event is associated
633
- * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
634
- * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with
635
- * a matching `scriptURL` was already waiting when this `Workbox`
636
- * instance called `register()`.
637
- * @property {string} type `waiting`.
638
- * @property {Workbox} target The `Workbox` instance.
639
- */ /**
640
- * The `controlling` event is dispatched if a
641
- * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
642
- * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}
643
- * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
644
- * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}
645
- * matches the `scriptURL` of the `Workbox` instance's
646
- * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.
647
- *
648
- * @event workbox-window.Workbox#controlling
649
- * @type {SerwistEvent}
650
- * @property {ServiceWorker} sw The service worker instance.
651
- * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
652
- * event.
653
- * @property {boolean|undefined} isUpdate True if a service worker was already
654
- * controlling when this service worker was registered.
655
- * @property {boolean|undefined} isExternal True if this event is associated
656
- * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
657
- * @property {string} type `controlling`.
658
- * @property {Workbox} target The `Workbox` instance.
659
- */ /**
660
- * The `activated` event is dispatched if the state of a
661
- * {@link workbox-window.Workbox} instance's
662
- * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}
663
- * changes to `activated`.
664
- *
665
- * @event workbox-window.Workbox#activated
666
- * @type {SerwistEvent}
667
- * @property {ServiceWorker} sw The service worker instance.
668
- * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
669
- * event.
670
- * @property {boolean|undefined} isUpdate True if a service worker was already
671
- * controlling when this `Workbox` instance called `register()`.
672
- * @property {boolean|undefined} isExternal True if this event is associated
673
- * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
674
- * @property {string} type `activated`.
675
- * @property {Workbox} target The `Workbox` instance.
676
- */ /**
677
- * The `redundant` event is dispatched if the state of a
678
- * {@link workbox-window.Workbox} instance's
679
- * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
680
- * changes to `redundant`.
681
- *
682
- * @event workbox-window.Workbox#redundant
683
- * @type {SerwistEvent}
684
- * @property {ServiceWorker} sw The service worker instance.
685
- * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
686
- * event.
687
- * @property {boolean|undefined} isUpdate True if a service worker was already
688
- * controlling when this `Workbox` instance called `register()`.
689
- * @property {string} type `redundant`.
690
- * @property {Workbox} target The `Workbox` instance.
691
- */ /**
692
- * The `installing` event is dispatched if the service worker
693
- * finds the new version and starts installing.
694
- *
695
- * @event workbox-window.Workbox#installing
696
- * @type {SerwistEvent}
697
- * @property {ServiceWorker} sw The installing service worker instance.
698
- * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
699
- * event.
700
- * @property {boolean|undefined} isUpdate True if a service worker was already
701
- * controlling when this `Workbox` instance called `register()`.
702
- * @property {string} type `installing`.
703
- * @property {Workbox} target The `Workbox` instance.
704
- */
306
+ }
705
307
 
706
308
  export { Serwist, SerwistEvent, messageSW };
@@ -11,6 +11,5 @@
11
11
  * @param data An object to send to the service worker.
12
12
  * @returns
13
13
  */
14
- declare function messageSW(sw: ServiceWorker, data: {}): Promise<any>;
15
- export { messageSW };
14
+ export declare const messageSW: (sw: ServiceWorker, data: any) => Promise<any>;
16
15
  //# sourceMappingURL=messageSW.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"messageSW.d.ts","sourceRoot":"","sources":["../src/messageSW.ts"],"names":[],"mappings":"AAQA;;;;;;;;;;;;GAYG;AAEH,iBAAS,SAAS,CAAC,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,CAQ5D;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
1
+ {"version":3,"file":"messageSW.d.ts","sourceRoot":"","sources":["../src/messageSW.ts"],"names":[],"mappings":"AAQA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,OAAQ,aAAa,QAAQ,GAAG,KAAG,QAAQ,GAAG,CAQnE,CAAC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Returns true if two URLs have the same `.href` property. The URLS can be
2
+ * Returns true if two URLs have the same `.href` property. The URLs can be
3
3
  * relative, and if they are the current location href is used to resolve URLs.
4
4
  *
5
5
  * @private
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serwist/window",
3
- "version": "9.0.0-preview.0",
3
+ "version": "9.0.0-preview.10",
4
4
  "type": "module",
5
5
  "description": "Simplifies communications with Serwist packages running in the service worker",
6
6
  "files": [
@@ -32,12 +32,12 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "@types/trusted-types": "2.0.7",
35
- "@serwist/core": "9.0.0-preview.0"
35
+ "@serwist/core": "9.0.0-preview.10"
36
36
  },
37
37
  "devDependencies": {
38
38
  "rollup": "4.9.6",
39
- "typescript": "5.4.0-dev.20240203",
40
- "@serwist/constants": "9.0.0-preview.0"
39
+ "typescript": "5.4.0-dev.20240206",
40
+ "@serwist/constants": "9.0.0-preview.10"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "typescript": ">=5.0.0"
package/src/Serwist.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  https://opensource.org/licenses/MIT.
7
7
  */
8
8
 
9
- import { Deferred, dontWaitFor, logger } from "@serwist/core/internal";
9
+ import { Deferred, logger } from "@serwist/core/internal";
10
10
  import type { TrustedScriptURL } from "trusted-types/lib";
11
11
 
12
12
  import { messageSW } from "./messageSW.js";
@@ -26,7 +26,7 @@ const REGISTRATION_TIMEOUT_DURATION = 60000;
26
26
 
27
27
  // The de facto standard message that a service worker should be listening for
28
28
  // to trigger a call to skipWaiting().
29
- const SKIP_WAITING_MESSAGE = { type: "SKIP_WAITING" };
29
+ const SKIP_WAITING_MESSAGE = { type: "SKIP_WAITING" } as const;
30
30
 
31
31
  /**
32
32
  * A class to aid in handling service worker registration, updates, and
@@ -63,14 +63,11 @@ export class Serwist extends SerwistEventTarget {
63
63
  * options. The script URL and options are the same as those used when
64
64
  * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).
65
65
  *
66
- * @param scriptURL The service worker script
67
- * associated with this instance. Using a
68
- * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.
69
- * @param registerOptions The service worker options associated
70
- * with this instance.
66
+ * @param scriptURL The service worker script associated with this instance. Using a
67
+ * [`TrustedScriptURL`](https://developer.mozilla.org/en-US/docs/Web/API/TrustedScriptURL) is supported.
68
+ * @param registerOptions The service worker options associated with this instance.
71
69
  */
72
- // biome-ignore lint/complexity/noBannedTypes: Unknown reason
73
- constructor(scriptURL: string | TrustedScriptURL, registerOptions: {} = {}) {
70
+ constructor(scriptURL: string | TrustedScriptURL, registerOptions: RegistrationOptions = {}) {
74
71
  super();
75
72
 
76
73
  this._scriptURL = scriptURL;
@@ -100,7 +97,7 @@ export class Serwist extends SerwistEventTarget {
100
97
  } = {}): Promise<ServiceWorkerRegistration | undefined> {
101
98
  if (process.env.NODE_ENV !== "production") {
102
99
  if (this._registrationTime) {
103
- logger.error("Cannot re-register a Serwist instance after it has " + "been registered. Create a new instance instead.");
100
+ logger.error("Cannot re-register a Serwist instance after it has been registered. Create a new instance instead.");
104
101
  return;
105
102
  }
106
103
  }
@@ -114,7 +111,7 @@ export class Serwist extends SerwistEventTarget {
114
111
  this._isUpdate = Boolean(navigator.serviceWorker.controller);
115
112
 
116
113
  // Before registering, attempt to determine if a SW is already controlling
117
- // the page, and if that SW script (and version, if specified) matches this
114
+ // the page and if that SW script (and version, if specified) matches this
118
115
  // instance's script.
119
116
  this._compatibleControllingSW = this._getControllingSWIfCompatible();
120
117
 
@@ -137,25 +134,23 @@ export class Serwist extends SerwistEventTarget {
137
134
  // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting
138
135
  const waitingSW = this._registration.waiting;
139
136
  if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {
140
- // Store the waiting SW as the "own" Sw, even if it means overwriting
137
+ // Store the waiting SW as the "own" SW, even if it means overwriting
141
138
  // a compatible controller.
142
139
  this._sw = waitingSW;
143
140
 
144
141
  // Run this in the next microtask, so any code that adds an event
145
142
  // listener after awaiting `register()` will get this event.
146
- dontWaitFor(
147
- Promise.resolve().then(() => {
148
- this.dispatchEvent(
149
- new SerwistEvent("waiting", {
150
- sw: waitingSW,
151
- wasWaitingBeforeRegister: true,
152
- }),
153
- );
154
- if (process.env.NODE_ENV !== "production") {
155
- logger.warn("A service worker was already waiting to activate " + "before this script was registered...");
156
- }
157
- }),
158
- );
143
+ void Promise.resolve().then(() => {
144
+ this.dispatchEvent(
145
+ new SerwistEvent("waiting", {
146
+ sw: waitingSW,
147
+ wasWaitingBeforeRegister: true,
148
+ }),
149
+ );
150
+ if (process.env.NODE_ENV !== "production") {
151
+ logger.warn("A service worker was already waiting to activate before this script was registered...");
152
+ }
153
+ });
159
154
  }
160
155
 
161
156
  // If an "own" SW is already set, resolve the deferred.
@@ -169,12 +164,10 @@ export class Serwist extends SerwistEventTarget {
169
164
 
170
165
  if (navigator.serviceWorker.controller) {
171
166
  if (this._compatibleControllingSW) {
172
- logger.debug("A service worker with the same script URL " + "is already controlling this page.");
167
+ logger.debug("A service worker with the same script URL is already controlling this page.");
173
168
  } else {
174
169
  logger.debug(
175
- "A service worker with a different script URL is " +
176
- "currently controlling the page. The browser is now fetching " +
177
- "the new script now...",
170
+ "A service worker with a different script URL is currently controlling the page. The browser is now fetching the new script now...",
178
171
  );
179
172
  }
180
173
  }
@@ -185,7 +178,7 @@ export class Serwist extends SerwistEventTarget {
185
178
  return !location.pathname.startsWith(scopeURLBasePath);
186
179
  };
187
180
  if (currentPageIsOutOfScope()) {
188
- logger.warn("The current page is not in scope for the registered " + "service worker. Was this a mistake?");
181
+ logger.warn("The current page is not in scope for the registered service worker. Was this a mistake?");
189
182
  }
190
183
  }
191
184
 
@@ -201,7 +194,7 @@ export class Serwist extends SerwistEventTarget {
201
194
  async update(): Promise<void> {
202
195
  if (!this._registration) {
203
196
  if (process.env.NODE_ENV !== "production") {
204
- logger.error("Cannot update a Serwist instance without " + "being registered. Register the Serwist instance first.");
197
+ logger.error("Cannot update a Serwist instance without being registered. Register the Serwist instance first.");
205
198
  }
206
199
  return;
207
200
  }
@@ -274,8 +267,7 @@ export class Serwist extends SerwistEventTarget {
274
267
  * @returns
275
268
  */
276
269
  // We might be able to change the 'data' type to Record<string, unknown> in the future.
277
- // eslint-disable-next-line @typescript-eslint/ban-types
278
- async messageSW(data: object): Promise<any> {
270
+ async messageSW(data: any): Promise<any> {
279
271
  const sw = await this.getSW();
280
272
  return messageSW(sw, data);
281
273
  }
@@ -370,11 +362,9 @@ export class Serwist extends SerwistEventTarget {
370
362
  // If all of the above are false, then we use a time-based heuristic:
371
363
  // Any `updatefound` event that occurs long after our registration is
372
364
  // assumed to be external.
373
- performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION
374
- ? // If any of the above are not true, we assume the update was
375
- // triggered by this instance.
376
- true
377
- : false;
365
+ performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION;
366
+ // If any of the above are not true, we assume the update was
367
+ // triggered by this instance.
378
368
 
379
369
  if (updateLikelyTriggeredExternally) {
380
370
  this._externalSW = installingSW;
@@ -539,8 +529,6 @@ export class Serwist extends SerwistEventTarget {
539
529
  * @param originalEvent
540
530
  */
541
531
  private readonly _onMessage = async (originalEvent: MessageEvent) => {
542
- // Can't change type 'any' of data.
543
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
544
532
  const { data, ports, source } = originalEvent;
545
533
 
546
534
  // Wait until there's an "own" service worker. This is used to buffer
@@ -556,8 +544,6 @@ export class Serwist extends SerwistEventTarget {
556
544
  if (this._ownSWs.has(source as ServiceWorker)) {
557
545
  this.dispatchEvent(
558
546
  new SerwistEvent("message", {
559
- // Can't change type 'any' of data.
560
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
561
547
  data,
562
548
  originalEvent,
563
549
  ports,
package/src/messageSW.ts CHANGED
@@ -19,8 +19,7 @@
19
19
  * @param data An object to send to the service worker.
20
20
  * @returns
21
21
  */
22
- // biome-ignore lint/complexity/noBannedTypes: Better not change type of data.
23
- function messageSW(sw: ServiceWorker, data: {}): Promise<any> {
22
+ export const messageSW = (sw: ServiceWorker, data: any): Promise<any> => {
24
23
  return new Promise((resolve) => {
25
24
  const messageChannel = new MessageChannel();
26
25
  messageChannel.port1.onmessage = (event: MessageEvent) => {
@@ -28,6 +27,4 @@ function messageSW(sw: ServiceWorker, data: {}): Promise<any> {
28
27
  };
29
28
  sw.postMessage(data, [messageChannel.port2]);
30
29
  });
31
- }
32
-
33
- export { messageSW };
30
+ };
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  /**
10
- * Returns true if two URLs have the same `.href` property. The URLS can be
10
+ * Returns true if two URLs have the same `.href` property. The URLs can be
11
11
  * relative, and if they are the current location href is used to resolve URLs.
12
12
  *
13
13
  * @private