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