UNPKG

24.1 kBJavaScriptView Raw
1try {
2 self['workbox:window:4.1.1'] && _();
3} catch (e) {} // eslint-disable-line
4
5/*
6 Copyright 2019 Google LLC
7
8 Use of this source code is governed by an MIT-style
9 license that can be found in the LICENSE file or at
10 https://opensource.org/licenses/MIT.
11*/
12/**
13 * Sends a data object to a service worker via `postMessage` and resolves with
14 * a response (if any).
15 *
16 * A response can be set in a message handler in the service worker by
17 * calling `event.ports[0].postMessage(...)`, which will resolve the promise
18 * returned by `messageSW()`. If no response is set, the promise will not
19 * resolve.
20 *
21 * @param {ServiceWorker} sw The service worker to send the message to.
22 * @param {Object} data An object to send to the service worker.
23 * @return {Promise<Object|undefined>}
24 *
25 * @memberof module:workbox-window
26 */
27
28const messageSW = (sw, data) => {
29 return new Promise(resolve => {
30 let messageChannel = new MessageChannel();
31
32 messageChannel.port1.onmessage = evt => resolve(evt.data);
33
34 sw.postMessage(data, [messageChannel.port2]);
35 });
36};
37
38try {
39 self['workbox:core:4.1.1'] && _();
40} catch (e) {} // eslint-disable-line
41
42/*
43 Copyright 2018 Google LLC
44
45 Use of this source code is governed by an MIT-style
46 license that can be found in the LICENSE file or at
47 https://opensource.org/licenses/MIT.
48*/
49/**
50 * The Deferred class composes Promises in a way that allows for them to be
51 * resolved or rejected from outside the constructor. In most cases promises
52 * should be used directly, but Deferreds can be necessary when the logic to
53 * resolve a promise must be separate.
54 *
55 * @private
56 */
57
58class Deferred {
59 /**
60 * Creates a promise and exposes its resolve and reject functions as methods.
61 */
62 constructor() {
63 this.promise = new Promise((resolve, reject) => {
64 this.resolve = resolve;
65 this.reject = reject;
66 });
67 }
68
69}
70
71/*
72 Copyright 2019 Google LLC
73 Use of this source code is governed by an MIT-style
74 license that can be found in the LICENSE file or at
75 https://opensource.org/licenses/MIT.
76*/
77const logger = (() => {
78 let inGroup = false;
79 const methodToColorMap = {
80 debug: `#7f8c8d`,
81 // Gray
82 log: `#2ecc71`,
83 // Green
84 warn: `#f39c12`,
85 // Yellow
86 error: `#c0392b`,
87 // Red
88 groupCollapsed: `#3498db`,
89 // Blue
90 groupEnd: null // No colored prefix on groupEnd
91
92 };
93
94 const print = function (method, args) {
95 if (method === 'groupCollapsed') {
96 // Safari doesn't print all console.groupCollapsed() arguments:
97 // https://bugs.webkit.org/show_bug.cgi?id=182754
98 if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
99 console[method](...args);
100 return;
101 }
102 }
103
104 const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`]; // When in a group, the workbox prefix is not displayed.
105
106 const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
107 console[method](...logPrefix, ...args);
108
109 if (method === 'groupCollapsed') {
110 inGroup = true;
111 }
112
113 if (method === 'groupEnd') {
114 inGroup = false;
115 }
116 };
117
118 const api = {};
119
120 for (const method of Object.keys(methodToColorMap)) {
121 api[method] = (...args) => {
122 print(method, args);
123 };
124 }
125
126 return api;
127})();
128
129/*
130 Copyright 2019 Google LLC
131
132 Use of this source code is governed by an MIT-style
133 license that can be found in the LICENSE file or at
134 https://opensource.org/licenses/MIT.
135*/
136/**
137 * A minimal `EventTarget` shim.
138 * This is necessary because not all browsers support constructable
139 * `EventTarget`, so using a real `EventTarget` will error.
140 * @private
141 */
142
143class EventTargetShim {
144 /**
145 * Creates an event listener registry
146 */
147 constructor() {
148 // A registry of event types to listeners.
149 this._eventListenerRegistry = {};
150 }
151 /**
152 * @param {string} type
153 * @param {Function} listener
154 */
155
156
157 addEventListener(type, listener) {
158 this._getEventListenersByType(type).add(listener);
159 }
160 /**
161 * @param {string} type
162 * @param {Function} listener
163 */
164
165
166 removeEventListener(type, listener) {
167 this._getEventListenersByType(type).delete(listener);
168 }
169 /**
170 * @param {Event} event
171 */
172
173
174 dispatchEvent(event) {
175 event.target = this;
176
177 this._getEventListenersByType(event.type).forEach(listener => listener(event));
178 }
179 /**
180 * Returns a Set of listeners associated with the passed event type.
181 * If no handlers have been registered, an empty Set is returned.
182 *
183 * @param {string} type The event type.
184 * @return {Set} An array of handler functions.
185 */
186
187
188 _getEventListenersByType(type) {
189 return this._eventListenerRegistry[type] = this._eventListenerRegistry[type] || new Set();
190 }
191
192}
193
194/*
195 Copyright 2019 Google LLC
196
197 Use of this source code is governed by an MIT-style
198 license that can be found in the LICENSE file or at
199 https://opensource.org/licenses/MIT.
200*/
201/**
202 * Returns true if two URLs have the same `.href` property. The URLS can be
203 * relative, and if they are the current location href is used to resolve URLs.
204 *
205 * @private
206 * @param {string} url1
207 * @param {string} url2
208 * @return {boolean}
209 */
210
211const urlsMatch = (url1, url2) => {
212 return new URL(url1, location).href === new URL(url2, location).href;
213};
214
215/*
216 Copyright 2019 Google LLC
217
218 Use of this source code is governed by an MIT-style
219 license that can be found in the LICENSE file or at
220 https://opensource.org/licenses/MIT.
221*/
222/**
223 * A minimal `Event` subclass shim.
224 * This doesn't *actually* subclass `Event` because not all browsers support
225 * constructable `EventTarget`, and using a real `Event` will error.
226 * @private
227 */
228
229class WorkboxEvent {
230 /**
231 * @param {string} type
232 * @param {Object} props
233 */
234 constructor(type, props) {
235 Object.assign(this, props, {
236 type
237 });
238 }
239
240}
241
242/*
243 Copyright 2019 Google LLC
244
245 Use of this source code is governed by an MIT-style
246 license that can be found in the LICENSE file or at
247 https://opensource.org/licenses/MIT.
248*/
249// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically
250// chosen, but it seems to avoid false positives in my testing.
251
252const WAITING_TIMEOUT_DURATION = 200; // The amount of time after a registration that we can reasonably conclude
253// that the registration didn't trigger an update.
254
255const REGISTRATION_TIMEOUT_DURATION = 60000;
256/**
257 * A class to aid in handling service worker registration, updates, and
258 * reacting to service worker lifecycle events.
259 *
260 * @fires [message]{@link module:workbox-window.Workbox#message}
261 * @fires [installed]{@link module:workbox-window.Workbox#installed}
262 * @fires [waiting]{@link module:workbox-window.Workbox#waiting}
263 * @fires [controlling]{@link module:workbox-window.Workbox#controlling}
264 * @fires [activated]{@link module:workbox-window.Workbox#activated}
265 * @fires [redundant]{@link module:workbox-window.Workbox#redundant}
266 * @fires [externalinstalled]{@link module:workbox-window.Workbox#externalinstalled}
267 * @fires [externalwaiting]{@link module:workbox-window.Workbox#externalwaiting}
268 * @fires [externalactivated]{@link module:workbox-window.Workbox#externalactivated}
269 *
270 * @memberof module:workbox-window
271 */
272
273class Workbox extends EventTargetShim {
274 /**
275 * Creates a new Workbox instance with a script URL and service worker
276 * options. The script URL and options are the same as those used when
277 * calling `navigator.serviceWorker.register(scriptURL, options)`. See:
278 * https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register
279 *
280 * @param {string} scriptURL The service worker script associated with this
281 * instance.
282 * @param {Object} [registerOptions] The service worker options associated
283 * with this instance.
284 */
285 constructor(scriptURL, registerOptions = {}) {
286 super();
287 this._scriptURL = scriptURL;
288 this._registerOptions = registerOptions;
289 this._updateFoundCount = 0; // Deferreds we can resolve later.
290
291 this._swDeferred = new Deferred();
292 this._activeDeferred = new Deferred();
293 this._controllingDeferred = new Deferred(); // Bind event handler callbacks.
294
295 this._onMessage = this._onMessage.bind(this);
296 this._onStateChange = this._onStateChange.bind(this);
297 this._onUpdateFound = this._onUpdateFound.bind(this);
298 this._onControllerChange = this._onControllerChange.bind(this);
299 }
300 /**
301 * Registers a service worker for this instances script URL and service
302 * worker options. By default this method delays registration until after
303 * the window has loaded.
304 *
305 * @param {Object} [options]
306 * @param {Function} [options.immediate=false] Setting this to true will
307 * register the service worker immediately, even if the window has
308 * not loaded (not recommended).
309 */
310
311
312 async register({
313 immediate = false
314 } = {}) {
315 {
316 if (this._registrationTime) {
317 logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.');
318 return;
319 }
320 }
321
322 if (!immediate && document.readyState !== 'complete') {
323 await new Promise(res => addEventListener('load', res));
324 } // Set this flag to true if any service worker was controlling the page
325 // at registration time.
326
327
328 this._isUpdate = Boolean(navigator.serviceWorker.controller); // Before registering, attempt to determine if a SW is already controlling
329 // the page, and if that SW script (and version, if specified) matches this
330 // instance's script.
331
332 this._compatibleControllingSW = this._getControllingSWIfCompatible();
333 this._registration = await this._registerScript(); // If we have a compatible controller, store the controller as the "own"
334 // SW, resolve active/controlling deferreds and add necessary listeners.
335
336 if (this._compatibleControllingSW) {
337 this._sw = this._compatibleControllingSW;
338
339 this._activeDeferred.resolve(this._compatibleControllingSW);
340
341 this._controllingDeferred.resolve(this._compatibleControllingSW);
342
343 this._reportWindowReady(this._compatibleControllingSW);
344
345 this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, {
346 once: true
347 });
348 } // If there's a waiting service worker with a matching URL before the
349 // `updatefound` event fires, it likely means that this site is open
350 // in another tab, or the user refreshed the page (and thus the prevoius
351 // page wasn't fully unloaded before this page started loading).
352 // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting
353
354
355 const waitingSW = this._registration.waiting;
356
357 if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL)) {
358 // Store the waiting SW as the "own" Sw, even if it means overwriting
359 // a compatible controller.
360 this._sw = waitingSW; // Run this in the next microtask, so any code that adds an event
361 // listener after awaiting `register()` will get this event.
362
363 Promise.resolve().then(() => {
364 this.dispatchEvent(new WorkboxEvent('waiting', {
365 sw: waitingSW,
366 wasWaitingBeforeRegister: true
367 }));
368
369 {
370 logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...');
371 }
372 });
373 } // If an "own" SW is already set, resolve the deferred.
374
375
376 if (this._sw) {
377 this._swDeferred.resolve(this._sw);
378 }
379
380 {
381 logger.log('Successfully registered service worker.', this._scriptURL);
382
383 if (navigator.serviceWorker.controller) {
384 if (this._compatibleControllingSW) {
385 logger.debug('A service worker with the same script URL ' + 'is already controlling this page.');
386 } else {
387 logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...');
388 }
389 }
390
391 const currentPageIsOutOfScope = () => {
392 const scopeURL = new URL(this._registerOptions.scope || this._scriptURL, document.baseURI);
393 const scopeURLBasePath = new URL('./', scopeURL.href).pathname;
394 return !location.pathname.startsWith(scopeURLBasePath);
395 };
396
397 if (currentPageIsOutOfScope()) {
398 logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?');
399 }
400 }
401
402 this._registration.addEventListener('updatefound', this._onUpdateFound);
403
404 navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange, {
405 once: true
406 }); // Add message listeners.
407
408 if ('BroadcastChannel' in self) {
409 this._broadcastChannel = new BroadcastChannel('workbox');
410
411 this._broadcastChannel.addEventListener('message', this._onMessage);
412 }
413
414 navigator.serviceWorker.addEventListener('message', this._onMessage);
415 return this._registration;
416 }
417 /**
418 * Resolves to the service worker registered by this instance as soon as it
419 * is active. If a service worker was already controlling at registration
420 * time then it will resolve to that if the script URLs (and optionally
421 * script versions) match, otherwise it will wait until an update is found
422 * and activates.
423 *
424 * @return {Promise<ServiceWorker>}
425 */
426
427
428 get active() {
429 return this._activeDeferred.promise;
430 }
431 /**
432 * Resolves to the service worker registered by this instance as soon as it
433 * is controlling the page. If a service worker was already controlling at
434 * registration time then it will resolve to that if the script URLs (and
435 * optionally script versions) match, otherwise it will wait until an update
436 * is found and starts controlling the page.
437 * Note: the first time a service worker is installed it will active but
438 * not start controlling the page unless `clients.claim()` is called in the
439 * service worker.
440 *
441 * @return {Promise<ServiceWorker>}
442 */
443
444
445 get controlling() {
446 return this._controllingDeferred.promise;
447 }
448 /**
449 * Resolves with a reference to a service worker that matches the script URL
450 * of this instance, as soon as it's available.
451 *
452 * If, at registration time, there's already an active or waiting service
453 * worker with a matching script URL, it will be used (with the waiting
454 * service worker taking precedence over the active service worker if both
455 * match, since the waiting service worker would have been registered more
456 * recently).
457 * If there's no matching active or waiting service worker at registration
458 * time then the promise will not resolve until an update is found and starts
459 * installing, at which point the installing service worker is used.
460 *
461 * @return {Promise<ServiceWorker>}
462 */
463
464
465 async getSW() {
466 // If `this._sw` is set, resolve with that as we want `getSW()` to
467 // return the correct (new) service worker if an update is found.
468 return this._sw || this._swDeferred.promise;
469 }
470 /**
471 * Sends the passed data object to the service worker registered by this
472 * instance (via [`getSW()`]{@link module:workbox-window.Workbox#getSW}) and resolves
473 * with a response (if any).
474 *
475 * A response can be set in a message handler in the service worker by
476 * calling `event.ports[0].postMessage(...)`, which will resolve the promise
477 * returned by `messageSW()`. If no response is set, the promise will never
478 * resolve.
479 *
480 * @param {Object} data An object to send to the service worker
481 * @return {Promise<Object>}
482 */
483
484
485 async messageSW(data) {
486 const sw = await this.getSW();
487 return messageSW(sw, data);
488 }
489 /**
490 * Checks for a service worker already controlling the page and returns
491 * it if its script URL matchs.
492 *
493 * @private
494 * @return {ServiceWorker|undefined}
495 */
496
497
498 _getControllingSWIfCompatible() {
499 const controller = navigator.serviceWorker.controller;
500
501 if (controller && urlsMatch(controller.scriptURL, this._scriptURL)) {
502 return controller;
503 }
504 }
505 /**
506 * Registers a service worker for this instances script URL and register
507 * options and tracks the time registration was complete.
508 *
509 * @private
510 */
511
512
513 async _registerScript() {
514 try {
515 const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions); // Keep track of when registration happened, so it can be used in the
516 // `this._onUpdateFound` heuristic. Also use the presence of this
517 // property as a way to see if `.register()` has been called.
518
519 this._registrationTime = performance.now();
520 return reg;
521 } catch (error) {
522 {
523 logger.error(error);
524 } // Re-throw the error.
525
526
527 throw error;
528 }
529 }
530 /**
531 * Sends a message to the passed service worker that the window is ready.
532 *
533 * @param {ServiceWorker} sw
534 * @private
535 */
536
537
538 _reportWindowReady(sw) {
539 messageSW(sw, {
540 type: 'WINDOW_READY',
541 meta: 'workbox-window'
542 });
543 }
544 /**
545 * @private
546 */
547
548
549 _onUpdateFound() {
550 const installingSW = this._registration.installing; // If the script URL passed to `navigator.serviceWorker.register()` is
551 // different from the current controlling SW's script URL, we know any
552 // successful registration calls will trigger an `updatefound` event.
553 // But if the registered script URL is the same as the current controlling
554 // SW's script URL, we'll only get an `updatefound` event if the file
555 // changed since it was last registered. This can be a problem if the user
556 // opens up the same page in a different tab, and that page registers
557 // a SW that triggers an update. It's a problem because this page has no
558 // good way of knowing whether the `updatefound` event came from the SW
559 // script it registered or from a registration attempt made by a newer
560 // version of the page running in another tab.
561 // To minimize the possibility of a false positive, we use the logic here:
562
563 let updateLikelyTriggeredExternally = // Since we enforce only calling `register()` once, and since we don't
564 // add the `updatefound` event listener until the `register()` call, if
565 // `_updateFoundCount` is > 0 then it means this method has already
566 // been called, thus this SW must be external
567 this._updateFoundCount > 0 || // If the script URL of the installing SW is different from this
568 // instance's script URL, we know it's definitely not from our
569 // registration.
570 !urlsMatch(installingSW.scriptURL, this._scriptURL) || // If all of the above are false, then we use a time-based heuristic:
571 // Any `updatefound` event that occurs long after our registration is
572 // assumed to be external.
573 performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? // If any of the above are not true, we assume the update was
574 // triggered by this instance.
575 true : false;
576
577 if (updateLikelyTriggeredExternally) {
578 this._externalSW = installingSW;
579
580 this._registration.removeEventListener('updatefound', this._onUpdateFound);
581 } else {
582 // If the update was not triggered externally we know the installing
583 // SW is the one we registered, so we set it.
584 this._sw = installingSW;
585
586 this._swDeferred.resolve(installingSW); // The `installing` state isn't something we have a dedicated
587 // callback for, but we do log messages for it in development.
588
589
590 {
591 if (navigator.serviceWorker.controller) {
592 logger.log('Updated service worker found. Installing now...');
593 } else {
594 logger.log('Service worker is installing...');
595 }
596 }
597 } // Increment the `updatefound` count, so future invocations of this
598 // method can be sure they were triggered externally.
599
600
601 ++this._updateFoundCount; // Add a `statechange` listener regardless of whether this update was
602 // triggered externally, since we have callbacks for both.
603
604 installingSW.addEventListener('statechange', this._onStateChange);
605 }
606 /**
607 * @private
608 * @param {Event} originalEvent
609 */
610
611
612 _onStateChange(originalEvent) {
613 const sw = originalEvent.target;
614 const {
615 state
616 } = sw;
617 const isExternal = sw === this._externalSW;
618 const eventPrefix = isExternal ? 'external' : '';
619 const eventProps = {
620 sw,
621 originalEvent
622 };
623
624 if (!isExternal && this._isUpdate) {
625 eventProps.isUpdate = true;
626 }
627
628 this.dispatchEvent(new WorkboxEvent(eventPrefix + state, eventProps));
629
630 if (state === 'installed') {
631 // This timeout is used to ignore cases where the service worker calls
632 // `skipWaiting()` in the install event, thus moving it directly in the
633 // activating state. (Since all service workers *must* go through the
634 // waiting phase, the only way to detect `skipWaiting()` called in the
635 // install event is to observe that the time spent in the waiting phase
636 // is very short.)
637 // NOTE: we don't need separate timeouts for the own and external SWs
638 // since they can't go through these phases at the same time.
639 this._waitingTimeout = setTimeout(() => {
640 // Ensure the SW is still waiting (it may now be redundant).
641 if (state === 'installed' && this._registration.waiting === sw) {
642 this.dispatchEvent(new WorkboxEvent(eventPrefix + 'waiting', eventProps));
643
644 {
645 if (isExternal) {
646 logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...');
647 } else {
648 logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...');
649 }
650 }
651 }
652 }, WAITING_TIMEOUT_DURATION);
653 } else if (state === 'activating') {
654 clearTimeout(this._waitingTimeout);
655
656 if (!isExternal) {
657 this._activeDeferred.resolve(sw);
658 }
659 }
660
661 {
662 switch (state) {
663 case 'installed':
664 if (isExternal) {
665 logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.');
666 } else {
667 logger.log('Registered service worker installed.');
668 }
669
670 break;
671
672 case 'activated':
673 if (isExternal) {
674 logger.warn('An external service worker has activated.');
675 } else {
676 logger.log('Registered service worker activated.');
677
678 if (sw !== navigator.serviceWorker.controller) {
679 logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.');
680 }
681 }
682
683 break;
684
685 case 'redundant':
686 if (sw === this._compatibleControllingSW) {
687 logger.log('Previously controlling service worker now redundant!');
688 } else if (!isExternal) {
689 logger.log('Registered service worker now redundant!');
690 }
691
692 break;
693 }
694 }
695 }
696 /**
697 * @private
698 * @param {Event} originalEvent
699 */
700
701
702 _onControllerChange(originalEvent) {
703 const sw = this._sw;
704
705 if (sw === navigator.serviceWorker.controller) {
706 this.dispatchEvent(new WorkboxEvent('controlling', {
707 sw,
708 originalEvent
709 }));
710
711 {
712 logger.log('Registered service worker now controlling this page.');
713 }
714
715 this._controllingDeferred.resolve(sw);
716 }
717 }
718 /**
719 * @private
720 * @param {Event} originalEvent
721 */
722
723
724 _onMessage(originalEvent) {
725 const {
726 data
727 } = originalEvent;
728 this.dispatchEvent(new WorkboxEvent('message', {
729 data,
730 originalEvent
731 }));
732 }
733
734} // The jsdoc comments below outline the events this instance may dispatch:
735
736/*
737 Copyright 2019 Google LLC
738
739 Use of this source code is governed by an MIT-style
740 license that can be found in the LICENSE file or at
741 https://opensource.org/licenses/MIT.
742*/
743
744export { Workbox, messageSW };
745