UNPKG

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