1 | try {
|
2 | self['workbox:window:5.1.4'] && _();
|
3 | } catch (e) {}
|
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 | * @memberof module:workbox-window
|
25 | */
|
26 |
|
27 | function messageSW(sw, data) {
|
28 | return new Promise(function (resolve) {
|
29 | var messageChannel = new MessageChannel();
|
30 |
|
31 | messageChannel.port1.onmessage = function (event) {
|
32 | resolve(event.data);
|
33 | };
|
34 |
|
35 | sw.postMessage(data, [messageChannel.port2]);
|
36 | });
|
37 | }
|
38 |
|
39 | function _defineProperties(target, props) {
|
40 | for (var i = 0; i < props.length; i++) {
|
41 | var descriptor = props[i];
|
42 | descriptor.enumerable = descriptor.enumerable || false;
|
43 | descriptor.configurable = true;
|
44 | if ("value" in descriptor) descriptor.writable = true;
|
45 | Object.defineProperty(target, descriptor.key, descriptor);
|
46 | }
|
47 | }
|
48 |
|
49 | function _createClass(Constructor, protoProps, staticProps) {
|
50 | if (protoProps) _defineProperties(Constructor.prototype, protoProps);
|
51 | if (staticProps) _defineProperties(Constructor, staticProps);
|
52 | return Constructor;
|
53 | }
|
54 |
|
55 | function _inheritsLoose(subClass, superClass) {
|
56 | subClass.prototype = Object.create(superClass.prototype);
|
57 | subClass.prototype.constructor = subClass;
|
58 | subClass.__proto__ = superClass;
|
59 | }
|
60 |
|
61 | function _unsupportedIterableToArray(o, minLen) {
|
62 | if (!o) return;
|
63 | if (typeof o === "string") return _arrayLikeToArray(o, minLen);
|
64 | var n = Object.prototype.toString.call(o).slice(8, -1);
|
65 | if (n === "Object" && o.constructor) n = o.constructor.name;
|
66 | if (n === "Map" || n === "Set") return Array.from(o);
|
67 | if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
|
68 | }
|
69 |
|
70 | function _arrayLikeToArray(arr, len) {
|
71 | if (len == null || len > arr.length) len = arr.length;
|
72 |
|
73 | for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
|
74 |
|
75 | return arr2;
|
76 | }
|
77 |
|
78 | function _createForOfIteratorHelperLoose(o, allowArrayLike) {
|
79 | var it;
|
80 |
|
81 | if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
|
82 | if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
|
83 | if (it) o = it;
|
84 | var i = 0;
|
85 | return function () {
|
86 | if (i >= o.length) return {
|
87 | done: true
|
88 | };
|
89 | return {
|
90 | done: false,
|
91 | value: o[i++]
|
92 | };
|
93 | };
|
94 | }
|
95 |
|
96 | throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
97 | }
|
98 |
|
99 | it = o[Symbol.iterator]();
|
100 | return it.next.bind(it);
|
101 | }
|
102 |
|
103 | try {
|
104 | self['workbox:core:5.1.4'] && _();
|
105 | } catch (e) {}
|
106 |
|
107 | /*
|
108 | Copyright 2018 Google LLC
|
109 |
|
110 | Use of this source code is governed by an MIT-style
|
111 | license that can be found in the LICENSE file or at
|
112 | https://opensource.org/licenses/MIT.
|
113 | */
|
114 | /**
|
115 | * The Deferred class composes Promises in a way that allows for them to be
|
116 | * resolved or rejected from outside the constructor. In most cases promises
|
117 | * should be used directly, but Deferreds can be necessary when the logic to
|
118 | * resolve a promise must be separate.
|
119 | *
|
120 | * @private
|
121 | */
|
122 |
|
123 | var Deferred =
|
124 | /**
|
125 | * Creates a promise and exposes its resolve and reject functions as methods.
|
126 | */
|
127 | function Deferred() {
|
128 | var _this = this;
|
129 |
|
130 | this.promise = new Promise(function (resolve, reject) {
|
131 | _this.resolve = resolve;
|
132 | _this.reject = reject;
|
133 | });
|
134 | };
|
135 |
|
136 | /*
|
137 | Copyright 2019 Google LLC
|
138 | Use of this source code is governed by an MIT-style
|
139 | license that can be found in the LICENSE file or at
|
140 | https://opensource.org/licenses/MIT.
|
141 | */
|
142 | /**
|
143 | * A helper function that prevents a promise from being flagged as unused.
|
144 | *
|
145 | * @private
|
146 | **/
|
147 |
|
148 | function dontWaitFor(promise) {
|
149 | // Effective no-op.
|
150 | promise.then(function () {});
|
151 | }
|
152 |
|
153 | /*
|
154 | Copyright 2019 Google LLC
|
155 | Use of this source code is governed by an MIT-style
|
156 | license that can be found in the LICENSE file or at
|
157 | https://opensource.org/licenses/MIT.
|
158 | */
|
159 | var logger = function () {
|
160 | // Don't overwrite this value if it's already set.
|
161 | // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
|
162 | if (!('__WB_DISABLE_DEV_LOGS' in self)) {
|
163 | self.__WB_DISABLE_DEV_LOGS = false;
|
164 | }
|
165 |
|
166 | var inGroup = false;
|
167 | var methodToColorMap = {
|
168 | debug: "#7f8c8d",
|
169 | log: "#2ecc71",
|
170 | warn: "#f39c12",
|
171 | error: "#c0392b",
|
172 | groupCollapsed: "#3498db",
|
173 | groupEnd: null
|
174 | };
|
175 |
|
176 | var print = function print(method, args) {
|
177 | var _console2;
|
178 |
|
179 | if (self.__WB_DISABLE_DEV_LOGS) {
|
180 | return;
|
181 | }
|
182 |
|
183 | if (method === 'groupCollapsed') {
|
184 | // Safari doesn't print all console.groupCollapsed() arguments:
|
185 | // https://bugs.webkit.org/show_bug.cgi?id=182754
|
186 | if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
|
187 | var _console;
|
188 |
|
189 | (_console = console)[method].apply(_console, args);
|
190 |
|
191 | return;
|
192 | }
|
193 | }
|
194 |
|
195 | 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.
|
196 |
|
197 | var logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
|
198 |
|
199 | (_console2 = console)[method].apply(_console2, logPrefix.concat(args));
|
200 |
|
201 | if (method === 'groupCollapsed') {
|
202 | inGroup = true;
|
203 | }
|
204 |
|
205 | if (method === 'groupEnd') {
|
206 | inGroup = false;
|
207 | }
|
208 | };
|
209 |
|
210 | var api = {};
|
211 | var loggerMethods = Object.keys(methodToColorMap);
|
212 |
|
213 | var _loop = function _loop() {
|
214 | var key = _loggerMethods[_i];
|
215 | var method = key;
|
216 |
|
217 | api[method] = function () {
|
218 | for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
219 | args[_key] = arguments[_key];
|
220 | }
|
221 |
|
222 | print(method, args);
|
223 | };
|
224 | };
|
225 |
|
226 | for (var _i = 0, _loggerMethods = loggerMethods; _i < _loggerMethods.length; _i++) {
|
227 | _loop();
|
228 | }
|
229 |
|
230 | return api;
|
231 | }();
|
232 |
|
233 | /*
|
234 | Copyright 2019 Google LLC
|
235 |
|
236 | Use of this source code is governed by an MIT-style
|
237 | license that can be found in the LICENSE file or at
|
238 | https://opensource.org/licenses/MIT.
|
239 | */
|
240 |
|
241 | /**
|
242 | * A minimal `EventTarget` shim.
|
243 | * This is necessary because not all browsers support constructable
|
244 | * `EventTarget`, so using a real `EventTarget` will error.
|
245 | * @private
|
246 | */
|
247 | var WorkboxEventTarget = /*#__PURE__*/function () {
|
248 | function WorkboxEventTarget() {
|
249 | this._eventListenerRegistry = new Map();
|
250 | }
|
251 | /**
|
252 | * @param {string} type
|
253 | * @param {Function} listener
|
254 | * @private
|
255 | */
|
256 |
|
257 |
|
258 | var _proto = WorkboxEventTarget.prototype;
|
259 |
|
260 | _proto.addEventListener = function addEventListener(type, listener) {
|
261 | var foo = this._getEventListenersByType(type);
|
262 |
|
263 | foo.add(listener);
|
264 | }
|
265 | /**
|
266 | * @param {string} type
|
267 | * @param {Function} listener
|
268 | * @private
|
269 | */
|
270 | ;
|
271 |
|
272 | _proto.removeEventListener = function removeEventListener(type, listener) {
|
273 | this._getEventListenersByType(type).delete(listener);
|
274 | }
|
275 | /**
|
276 | * @param {Object} event
|
277 | * @private
|
278 | */
|
279 | ;
|
280 |
|
281 | _proto.dispatchEvent = function dispatchEvent(event) {
|
282 | event.target = this;
|
283 |
|
284 | var listeners = this._getEventListenersByType(event.type);
|
285 |
|
286 | for (var _iterator = _createForOfIteratorHelperLoose(listeners), _step; !(_step = _iterator()).done;) {
|
287 | var listener = _step.value;
|
288 | listener(event);
|
289 | }
|
290 | }
|
291 | /**
|
292 | * Returns a Set of listeners associated with the passed event type.
|
293 | * If no handlers have been registered, an empty Set is returned.
|
294 | *
|
295 | * @param {string} type The event type.
|
296 | * @return {Set<ListenerCallback>} An array of handler functions.
|
297 | * @private
|
298 | */
|
299 | ;
|
300 |
|
301 | _proto._getEventListenersByType = function _getEventListenersByType(type) {
|
302 | if (!this._eventListenerRegistry.has(type)) {
|
303 | this._eventListenerRegistry.set(type, new Set());
|
304 | }
|
305 |
|
306 | return this._eventListenerRegistry.get(type);
|
307 | };
|
308 |
|
309 | return WorkboxEventTarget;
|
310 | }();
|
311 |
|
312 | /*
|
313 | Copyright 2019 Google LLC
|
314 |
|
315 | Use of this source code is governed by an MIT-style
|
316 | license that can be found in the LICENSE file or at
|
317 | https://opensource.org/licenses/MIT.
|
318 | */
|
319 | /**
|
320 | * Returns true if two URLs have the same `.href` property. The URLS can be
|
321 | * relative, and if they are the current location href is used to resolve URLs.
|
322 | *
|
323 | * @private
|
324 | * @param {string} url1
|
325 | * @param {string} url2
|
326 | * @return {boolean}
|
327 | */
|
328 |
|
329 | function urlsMatch(url1, url2) {
|
330 | var _location = location,
|
331 | href = _location.href;
|
332 | return new URL(url1, href).href === new URL(url2, href).href;
|
333 | }
|
334 |
|
335 | /*
|
336 | Copyright 2019 Google LLC
|
337 |
|
338 | Use of this source code is governed by an MIT-style
|
339 | license that can be found in the LICENSE file or at
|
340 | https://opensource.org/licenses/MIT.
|
341 | */
|
342 | /**
|
343 | * A minimal `Event` subclass shim.
|
344 | * This doesn't *actually* subclass `Event` because not all browsers support
|
345 | * constructable `EventTarget`, and using a real `Event` will error.
|
346 | * @private
|
347 | */
|
348 |
|
349 | var WorkboxEvent = function WorkboxEvent(type, props) {
|
350 | this.type = type;
|
351 | Object.assign(this, props);
|
352 | };
|
353 |
|
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 | function _await(value, then, direct) {
|
358 | if (direct) {
|
359 | return then ? then(value) : value;
|
360 | }
|
361 |
|
362 | if (!value || !value.then) {
|
363 | value = Promise.resolve(value);
|
364 | }
|
365 |
|
366 | return then ? value.then(then) : value;
|
367 | }
|
368 |
|
369 | var WAITING_TIMEOUT_DURATION = 200; // The amount of time after a registration that we can reasonably conclude
|
370 | // that the registration didn't trigger an update.
|
371 |
|
372 | function _async(f) {
|
373 | return function () {
|
374 | for (var args = [], i = 0; i < arguments.length; i++) {
|
375 | args[i] = arguments[i];
|
376 | }
|
377 |
|
378 | try {
|
379 | return Promise.resolve(f.apply(this, args));
|
380 | } catch (e) {
|
381 | return Promise.reject(e);
|
382 | }
|
383 | };
|
384 | }
|
385 |
|
386 | var REGISTRATION_TIMEOUT_DURATION = 60000;
|
387 | /**
|
388 | * A class to aid in handling service worker registration, updates, and
|
389 | * reacting to service worker lifecycle events.
|
390 | *
|
391 | * @fires [message]{@link module:workbox-window.Workbox#message}
|
392 | * @fires [installed]{@link module:workbox-window.Workbox#installed}
|
393 | * @fires [waiting]{@link module:workbox-window.Workbox#waiting}
|
394 | * @fires [controlling]{@link module:workbox-window.Workbox#controlling}
|
395 | * @fires [activated]{@link module:workbox-window.Workbox#activated}
|
396 | * @fires [redundant]{@link module:workbox-window.Workbox#redundant}
|
397 | * @fires [externalinstalled]{@link module:workbox-window.Workbox#externalinstalled}
|
398 | * @fires [externalwaiting]{@link module:workbox-window.Workbox#externalwaiting}
|
399 | * @fires [externalactivated]{@link module:workbox-window.Workbox#externalactivated}
|
400 | * @memberof module:workbox-window
|
401 | */
|
402 |
|
403 | function _empty() {}
|
404 |
|
405 | var Workbox = /*#__PURE__*/function (_WorkboxEventTarget) {
|
406 | _inheritsLoose(Workbox, _WorkboxEventTarget);
|
407 |
|
408 | /**
|
409 | * Creates a new Workbox instance with a script URL and service worker
|
410 | * options. The script URL and options are the same as those used when
|
411 | * calling `navigator.serviceWorker.register(scriptURL, options)`. See:
|
412 | * https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register
|
413 | *
|
414 | * @param {string} scriptURL The service worker script associated with this
|
415 | * instance.
|
416 | * @param {Object} [registerOptions] The service worker options associated
|
417 | * with this instance.
|
418 | */
|
419 | function Workbox(scriptURL, registerOptions) {
|
420 | var _this;
|
421 |
|
422 | if (registerOptions === void 0) {
|
423 | registerOptions = {};
|
424 | }
|
425 |
|
426 | _this = _WorkboxEventTarget.call(this) || this;
|
427 | _this._registerOptions = {};
|
428 | _this._updateFoundCount = 0; // Deferreds we can resolve later.
|
429 |
|
430 | _this._swDeferred = new Deferred();
|
431 | _this._activeDeferred = new Deferred();
|
432 | _this._controllingDeferred = new Deferred();
|
433 | _this._registrationTime = 0;
|
434 | _this._ownSWs = new Set();
|
435 | /**
|
436 | * @private
|
437 | */
|
438 |
|
439 | _this._onUpdateFound = function () {
|
440 | // `this._registration` will never be `undefined` after an update is found.
|
441 | var registration = _this._registration;
|
442 | var installingSW = registration.installing; // If the script URL passed to `navigator.serviceWorker.register()` is
|
443 | // different from the current controlling SW's script URL, we know any
|
444 | // successful registration calls will trigger an `updatefound` event.
|
445 | // But if the registered script URL is the same as the current controlling
|
446 | // SW's script URL, we'll only get an `updatefound` event if the file
|
447 | // changed since it was last registered. This can be a problem if the user
|
448 | // opens up the same page in a different tab, and that page registers
|
449 | // a SW that triggers an update. It's a problem because this page has no
|
450 | // good way of knowing whether the `updatefound` event came from the SW
|
451 | // script it registered or from a registration attempt made by a newer
|
452 | // version of the page running in another tab.
|
453 | // To minimize the possibility of a false positive, we use the logic here:
|
454 |
|
455 | var updateLikelyTriggeredExternally = // Since we enforce only calling `register()` once, and since we don't
|
456 | // add the `updatefound` event listener until the `register()` call, if
|
457 | // `_updateFoundCount` is > 0 then it means this method has already
|
458 | // been called, thus this SW must be external
|
459 | _this._updateFoundCount > 0 || // If the script URL of the installing SW is different from this
|
460 | // instance's script URL, we know it's definitely not from our
|
461 | // registration.
|
462 | !urlsMatch(installingSW.scriptURL, _this._scriptURL) || // If all of the above are false, then we use a time-based heuristic:
|
463 | // Any `updatefound` event that occurs long after our registration is
|
464 | // assumed to be external.
|
465 | performance.now() > _this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? // If any of the above are not true, we assume the update was
|
466 | // triggered by this instance.
|
467 | true : false;
|
468 |
|
469 | if (updateLikelyTriggeredExternally) {
|
470 | _this._externalSW = installingSW;
|
471 | registration.removeEventListener('updatefound', _this._onUpdateFound);
|
472 | } else {
|
473 | // If the update was not triggered externally we know the installing
|
474 | // SW is the one we registered, so we set it.
|
475 | _this._sw = installingSW;
|
476 |
|
477 | _this._ownSWs.add(installingSW);
|
478 |
|
479 | _this._swDeferred.resolve(installingSW); // The `installing` state isn't something we have a dedicated
|
480 | // callback for, but we do log messages for it in development.
|
481 |
|
482 |
|
483 | {
|
484 | if (navigator.serviceWorker.controller) {
|
485 | logger.log('Updated service worker found. Installing now...');
|
486 | } else {
|
487 | logger.log('Service worker is installing...');
|
488 | }
|
489 | }
|
490 | } // Increment the `updatefound` count, so future invocations of this
|
491 | // method can be sure they were triggered externally.
|
492 |
|
493 |
|
494 | ++_this._updateFoundCount; // Add a `statechange` listener regardless of whether this update was
|
495 | // triggered externally, since we have callbacks for both.
|
496 |
|
497 | installingSW.addEventListener('statechange', _this._onStateChange);
|
498 | };
|
499 | /**
|
500 | * @private
|
501 | * @param {Event} originalEvent
|
502 | */
|
503 |
|
504 |
|
505 | _this._onStateChange = function (originalEvent) {
|
506 | // `this._registration` will never be `undefined` after an update is found.
|
507 | var registration = _this._registration;
|
508 | var sw = originalEvent.target;
|
509 | var state = sw.state;
|
510 | var isExternal = sw === _this._externalSW;
|
511 | var eventPrefix = isExternal ? 'external' : '';
|
512 | var eventProps = {
|
513 | sw: sw,
|
514 | originalEvent: originalEvent
|
515 | };
|
516 |
|
517 | if (!isExternal && _this._isUpdate) {
|
518 | eventProps.isUpdate = true;
|
519 | }
|
520 |
|
521 | _this.dispatchEvent(new WorkboxEvent(eventPrefix + state, eventProps));
|
522 |
|
523 | if (state === 'installed') {
|
524 | // This timeout is used to ignore cases where the service worker calls
|
525 | // `skipWaiting()` in the install event, thus moving it directly in the
|
526 | // activating state. (Since all service workers *must* go through the
|
527 | // waiting phase, the only way to detect `skipWaiting()` called in the
|
528 | // install event is to observe that the time spent in the waiting phase
|
529 | // is very short.)
|
530 | // NOTE: we don't need separate timeouts for the own and external SWs
|
531 | // since they can't go through these phases at the same time.
|
532 | _this._waitingTimeout = self.setTimeout(function () {
|
533 | // Ensure the SW is still waiting (it may now be redundant).
|
534 | if (state === 'installed' && registration.waiting === sw) {
|
535 | _this.dispatchEvent(new WorkboxEvent(eventPrefix + 'waiting', eventProps));
|
536 |
|
537 | {
|
538 | if (isExternal) {
|
539 | logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...');
|
540 | } else {
|
541 | logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...');
|
542 | }
|
543 | }
|
544 | }
|
545 | }, WAITING_TIMEOUT_DURATION);
|
546 | } else if (state === 'activating') {
|
547 | clearTimeout(_this._waitingTimeout);
|
548 |
|
549 | if (!isExternal) {
|
550 | _this._activeDeferred.resolve(sw);
|
551 | }
|
552 | }
|
553 |
|
554 | {
|
555 | switch (state) {
|
556 | case 'installed':
|
557 | if (isExternal) {
|
558 | logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.');
|
559 | } else {
|
560 | logger.log('Registered service worker installed.');
|
561 | }
|
562 |
|
563 | break;
|
564 |
|
565 | case 'activated':
|
566 | if (isExternal) {
|
567 | logger.warn('An external service worker has activated.');
|
568 | } else {
|
569 | logger.log('Registered service worker activated.');
|
570 |
|
571 | if (sw !== navigator.serviceWorker.controller) {
|
572 | logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.');
|
573 | }
|
574 | }
|
575 |
|
576 | break;
|
577 |
|
578 | case 'redundant':
|
579 | if (sw === _this._compatibleControllingSW) {
|
580 | logger.log('Previously controlling service worker now redundant!');
|
581 | } else if (!isExternal) {
|
582 | logger.log('Registered service worker now redundant!');
|
583 | }
|
584 |
|
585 | break;
|
586 | }
|
587 | }
|
588 | };
|
589 | /**
|
590 | * @private
|
591 | * @param {Event} originalEvent
|
592 | */
|
593 |
|
594 |
|
595 | _this._onControllerChange = function (originalEvent) {
|
596 | var sw = _this._sw;
|
597 |
|
598 | if (sw === navigator.serviceWorker.controller) {
|
599 | _this.dispatchEvent(new WorkboxEvent('controlling', {
|
600 | sw: sw,
|
601 | originalEvent: originalEvent,
|
602 | isUpdate: _this._isUpdate
|
603 | }));
|
604 |
|
605 | {
|
606 | logger.log('Registered service worker now controlling this page.');
|
607 | }
|
608 |
|
609 | _this._controllingDeferred.resolve(sw);
|
610 | }
|
611 | };
|
612 | /**
|
613 | * @private
|
614 | * @param {Event} originalEvent
|
615 | */
|
616 |
|
617 |
|
618 | _this._onMessage = _async(function (originalEvent) {
|
619 | var data = originalEvent.data,
|
620 | source = originalEvent.source; // Wait until there's an "own" service worker. This is used to buffer
|
621 | // `message` events that may be received prior to calling `register()`.
|
622 |
|
623 | return _await(_this.getSW(), function () {
|
624 | if (_this._ownSWs.has(source)) {
|
625 | _this.dispatchEvent(new WorkboxEvent('message', {
|
626 | data: data,
|
627 | sw: source,
|
628 | originalEvent: originalEvent
|
629 | }));
|
630 | }
|
631 | }); // If the service worker that sent the message is in the list of own
|
632 | // service workers for this instance, dispatch a `message` event.
|
633 | // NOTE: we check for all previously owned service workers rather than
|
634 | // just the current one because some messages (e.g. cache updates) use
|
635 | // a timeout when sent and may be delayed long enough for a service worker
|
636 | // update to be found.
|
637 | });
|
638 | _this._scriptURL = scriptURL;
|
639 | _this._registerOptions = registerOptions; // Add a message listener immediately since messages received during
|
640 | // page load are buffered only until the DOMContentLoaded event:
|
641 | // https://github.com/GoogleChrome/workbox/issues/2202
|
642 |
|
643 | navigator.serviceWorker.addEventListener('message', _this._onMessage);
|
644 | return _this;
|
645 | }
|
646 | /**
|
647 | * Registers a service worker for this instances script URL and service
|
648 | * worker options. By default this method delays registration until after
|
649 | * the window has loaded.
|
650 | *
|
651 | * @param {Object} [options]
|
652 | * @param {Function} [options.immediate=false] Setting this to true will
|
653 | * register the service worker immediately, even if the window has
|
654 | * not loaded (not recommended).
|
655 | */
|
656 |
|
657 |
|
658 | var _proto = Workbox.prototype;
|
659 |
|
660 | _proto.register = function register(_temp) {
|
661 | var _ref = _temp === void 0 ? {} : _temp,
|
662 | _ref$immediate = _ref.immediate,
|
663 | immediate = _ref$immediate === void 0 ? false : _ref$immediate;
|
664 |
|
665 | try {
|
666 | var _this3 = this;
|
667 |
|
668 | if ("dev" !== 'production') {
|
669 | if (_this3._registrationTime) {
|
670 | logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.');
|
671 | return;
|
672 | }
|
673 | }
|
674 |
|
675 | return _invoke(function () {
|
676 | if (!immediate && document.readyState !== 'complete') {
|
677 | return _awaitIgnored(new Promise(function (res) {
|
678 | return window.addEventListener('load', res);
|
679 | }));
|
680 | }
|
681 | }, function () {
|
682 | // Set this flag to true if any service worker was controlling the page
|
683 | // at registration time.
|
684 | _this3._isUpdate = Boolean(navigator.serviceWorker.controller); // Before registering, attempt to determine if a SW is already controlling
|
685 | // the page, and if that SW script (and version, if specified) matches this
|
686 | // instance's script.
|
687 |
|
688 | _this3._compatibleControllingSW = _this3._getControllingSWIfCompatible();
|
689 | return _await(_this3._registerScript(), function (_this2$_registerScrip) {
|
690 | _this3._registration = _this2$_registerScrip;
|
691 |
|
692 | // If we have a compatible controller, store the controller as the "own"
|
693 | // SW, resolve active/controlling deferreds and add necessary listeners.
|
694 | if (_this3._compatibleControllingSW) {
|
695 | _this3._sw = _this3._compatibleControllingSW;
|
696 |
|
697 | _this3._activeDeferred.resolve(_this3._compatibleControllingSW);
|
698 |
|
699 | _this3._controllingDeferred.resolve(_this3._compatibleControllingSW);
|
700 |
|
701 | _this3._compatibleControllingSW.addEventListener('statechange', _this3._onStateChange, {
|
702 | once: true
|
703 | });
|
704 | } // If there's a waiting service worker with a matching URL before the
|
705 | // `updatefound` event fires, it likely means that this site is open
|
706 | // in another tab, or the user refreshed the page (and thus the previous
|
707 | // page wasn't fully unloaded before this page started loading).
|
708 | // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting
|
709 |
|
710 |
|
711 | var waitingSW = _this3._registration.waiting;
|
712 |
|
713 | if (waitingSW && urlsMatch(waitingSW.scriptURL, _this3._scriptURL)) {
|
714 | // Store the waiting SW as the "own" Sw, even if it means overwriting
|
715 | // a compatible controller.
|
716 | _this3._sw = waitingSW; // Run this in the next microtask, so any code that adds an event
|
717 | // listener after awaiting `register()` will get this event.
|
718 |
|
719 | dontWaitFor(Promise.resolve().then(function () {
|
720 | _this3.dispatchEvent(new WorkboxEvent('waiting', {
|
721 | sw: waitingSW,
|
722 | wasWaitingBeforeRegister: true
|
723 | }));
|
724 |
|
725 | if ("dev" !== 'production') {
|
726 | logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...');
|
727 | }
|
728 | }));
|
729 | } // If an "own" SW is already set, resolve the deferred.
|
730 |
|
731 |
|
732 | if (_this3._sw) {
|
733 | _this3._swDeferred.resolve(_this3._sw);
|
734 |
|
735 | _this3._ownSWs.add(_this3._sw);
|
736 | }
|
737 |
|
738 | if ("dev" !== 'production') {
|
739 | logger.log('Successfully registered service worker.', _this3._scriptURL);
|
740 |
|
741 | if (navigator.serviceWorker.controller) {
|
742 | if (_this3._compatibleControllingSW) {
|
743 | logger.debug('A service worker with the same script URL ' + 'is already controlling this page.');
|
744 | } else {
|
745 | logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...');
|
746 | }
|
747 | }
|
748 |
|
749 | var currentPageIsOutOfScope = function currentPageIsOutOfScope() {
|
750 | var scopeURL = new URL(_this3._registerOptions.scope || _this3._scriptURL, document.baseURI);
|
751 | var scopeURLBasePath = new URL('./', scopeURL.href).pathname;
|
752 | return !location.pathname.startsWith(scopeURLBasePath);
|
753 | };
|
754 |
|
755 | if (currentPageIsOutOfScope()) {
|
756 | logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?');
|
757 | }
|
758 | }
|
759 |
|
760 | _this3._registration.addEventListener('updatefound', _this3._onUpdateFound);
|
761 |
|
762 | navigator.serviceWorker.addEventListener('controllerchange', _this3._onControllerChange, {
|
763 | once: true
|
764 | });
|
765 | return _this3._registration;
|
766 | });
|
767 | });
|
768 | } catch (e) {
|
769 | return Promise.reject(e);
|
770 | }
|
771 | }
|
772 | /**
|
773 | * Checks for updates of the registered service worker.
|
774 | */
|
775 | ;
|
776 |
|
777 | _proto.update = function update() {
|
778 | try {
|
779 | var _this5 = this;
|
780 |
|
781 | if (!_this5._registration) {
|
782 | if ("dev" !== 'production') {
|
783 | logger.error('Cannot update a Workbox instance without ' + 'being registered. Register the Workbox instance first.');
|
784 | }
|
785 |
|
786 | return;
|
787 | } // Try to update registration
|
788 |
|
789 |
|
790 | return _awaitIgnored(_this5._registration.update());
|
791 | } catch (e) {
|
792 | return Promise.reject(e);
|
793 | }
|
794 | }
|
795 | /**
|
796 | * Resolves to the service worker registered by this instance as soon as it
|
797 | * is active. If a service worker was already controlling at registration
|
798 | * time then it will resolve to that if the script URLs (and optionally
|
799 | * script versions) match, otherwise it will wait until an update is found
|
800 | * and activates.
|
801 | *
|
802 | * @return {Promise<ServiceWorker>}
|
803 | */
|
804 | ;
|
805 |
|
806 | /**
|
807 | * Resolves with a reference to a service worker that matches the script URL
|
808 | * of this instance, as soon as it's available.
|
809 | *
|
810 | * If, at registration time, there's already an active or waiting service
|
811 | * worker with a matching script URL, it will be used (with the waiting
|
812 | * service worker taking precedence over the active service worker if both
|
813 | * match, since the waiting service worker would have been registered more
|
814 | * recently).
|
815 | * If there's no matching active or waiting service worker at registration
|
816 | * time then the promise will not resolve until an update is found and starts
|
817 | * installing, at which point the installing service worker is used.
|
818 | *
|
819 | * @return {Promise<ServiceWorker>}
|
820 | */
|
821 | _proto.getSW = function getSW() {
|
822 | try {
|
823 | var _this7 = this;
|
824 |
|
825 | // If `this._sw` is set, resolve with that as we want `getSW()` to
|
826 | // return the correct (new) service worker if an update is found.
|
827 | return _this7._sw !== undefined ? _this7._sw : _this7._swDeferred.promise;
|
828 | } catch (e) {
|
829 | return Promise.reject(e);
|
830 | }
|
831 | }
|
832 | /**
|
833 | * Sends the passed data object to the service worker registered by this
|
834 | * instance (via [`getSW()`]{@link module:workbox-window.Workbox#getSW}) and resolves
|
835 | * with a response (if any).
|
836 | *
|
837 | * A response can be set in a message handler in the service worker by
|
838 | * calling `event.ports[0].postMessage(...)`, which will resolve the promise
|
839 | * returned by `messageSW()`. If no response is set, the promise will never
|
840 | * resolve.
|
841 | *
|
842 | * @param {Object} data An object to send to the service worker
|
843 | * @return {Promise<Object>}
|
844 | */
|
845 | ;
|
846 |
|
847 | _proto.messageSW = function messageSW$1(data) {
|
848 | try {
|
849 | var _this9 = this;
|
850 |
|
851 | return _await(_this9.getSW(), function (sw) {
|
852 | return messageSW(sw, data);
|
853 | });
|
854 | } catch (e) {
|
855 | return Promise.reject(e);
|
856 | }
|
857 | }
|
858 | /**
|
859 | * Checks for a service worker already controlling the page and returns
|
860 | * it if its script URL matches.
|
861 | *
|
862 | * @private
|
863 | * @return {ServiceWorker|undefined}
|
864 | */
|
865 | ;
|
866 |
|
867 | _proto._getControllingSWIfCompatible = function _getControllingSWIfCompatible() {
|
868 | var controller = navigator.serviceWorker.controller;
|
869 |
|
870 | if (controller && urlsMatch(controller.scriptURL, this._scriptURL)) {
|
871 | return controller;
|
872 | } else {
|
873 | return undefined;
|
874 | }
|
875 | }
|
876 | /**
|
877 | * Registers a service worker for this instances script URL and register
|
878 | * options and tracks the time registration was complete.
|
879 | *
|
880 | * @private
|
881 | */
|
882 | ;
|
883 |
|
884 | _proto._registerScript = function _registerScript() {
|
885 | try {
|
886 | var _this11 = this;
|
887 |
|
888 | return _catch(function () {
|
889 | return _await(navigator.serviceWorker.register(_this11._scriptURL, _this11._registerOptions), function (reg) {
|
890 | // Keep track of when registration happened, so it can be used in the
|
891 | // `this._onUpdateFound` heuristic. Also use the presence of this
|
892 | // property as a way to see if `.register()` has been called.
|
893 | _this11._registrationTime = performance.now();
|
894 | return reg;
|
895 | });
|
896 | }, function (error) {
|
897 | if ("dev" !== 'production') {
|
898 | logger.error(error);
|
899 | } // Re-throw the error.
|
900 |
|
901 |
|
902 | throw error;
|
903 | });
|
904 | } catch (e) {
|
905 | return Promise.reject(e);
|
906 | }
|
907 | };
|
908 |
|
909 | _createClass(Workbox, [{
|
910 | key: "active",
|
911 | get: function get() {
|
912 | return this._activeDeferred.promise;
|
913 | }
|
914 | /**
|
915 | * Resolves to the service worker registered by this instance as soon as it
|
916 | * is controlling the page. If a service worker was already controlling at
|
917 | * registration time then it will resolve to that if the script URLs (and
|
918 | * optionally script versions) match, otherwise it will wait until an update
|
919 | * is found and starts controlling the page.
|
920 | * Note: the first time a service worker is installed it will active but
|
921 | * not start controlling the page unless `clients.claim()` is called in the
|
922 | * service worker.
|
923 | *
|
924 | * @return {Promise<ServiceWorker>}
|
925 | */
|
926 |
|
927 | }, {
|
928 | key: "controlling",
|
929 | get: function get() {
|
930 | return this._controllingDeferred.promise;
|
931 | }
|
932 | }]);
|
933 |
|
934 | return Workbox;
|
935 | }(WorkboxEventTarget);
|
936 |
|
937 | function _awaitIgnored(value, direct) {
|
938 | if (!direct) {
|
939 | return value && value.then ? value.then(_empty) : Promise.resolve();
|
940 | }
|
941 | } // The jsdoc comments below outline the events this instance may dispatch:
|
942 | // -----------------------------------------------------------------------
|
943 |
|
944 | /**
|
945 | * The `message` event is dispatched any time a `postMessage` is received.
|
946 | *
|
947 | * @event module:workbox-window.Workbox#message
|
948 | * @type {WorkboxEvent}
|
949 | * @property {*} data The `data` property from the original `message` event.
|
950 | * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}
|
951 | * event.
|
952 | * @property {string} type `message`.
|
953 | * @property {Workbox} target The `Workbox` instance.
|
954 | */
|
955 |
|
956 | /**
|
957 | * The `installed` event is dispatched if the state of a
|
958 | * [`Workbox`]{@link module:workbox-window.Workbox} instance's
|
959 | * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
|
960 | * changes to `installed`.
|
961 | *
|
962 | * Then can happen either the very first time a service worker is installed,
|
963 | * or after an update to the current service worker is found. In the case
|
964 | * of an update being found, the event's `isUpdate` property will be `true`.
|
965 | *
|
966 | * @event module:workbox-window.Workbox#installed
|
967 | * @type {WorkboxEvent}
|
968 | * @property {ServiceWorker} sw The service worker instance.
|
969 | * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
|
970 | * event.
|
971 | * @property {boolean|undefined} isUpdate True if a service worker was already
|
972 | * controlling when this `Workbox` instance called `register()`.
|
973 | * @property {string} type `installed`.
|
974 | * @property {Workbox} target The `Workbox` instance.
|
975 | */
|
976 |
|
977 | /**
|
978 | * The `waiting` event is dispatched if the state of a
|
979 | * [`Workbox`]{@link module:workbox-window.Workbox} instance's
|
980 | * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
|
981 | * changes to `installed` and then doesn't immediately change to `activating`.
|
982 | * It may also be dispatched if a service worker with the same
|
983 | * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
|
984 | * was already waiting when the [`register()`]{@link module:workbox-window.Workbox#register}
|
985 | * method was called.
|
986 | *
|
987 | * @event module:workbox-window.Workbox#waiting
|
988 | * @type {WorkboxEvent}
|
989 | * @property {ServiceWorker} sw The service worker instance.
|
990 | * @property {Event|undefined} originalEvent The original
|
991 | * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
|
992 | * event, or `undefined` in the case where the service worker was waiting
|
993 | * to before `.register()` was called.
|
994 | * @property {boolean|undefined} isUpdate True if a service worker was already
|
995 | * controlling when this `Workbox` instance called `register()`.
|
996 | * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with
|
997 | * a matching `scriptURL` was already waiting when this `Workbox`
|
998 | * instance called `register()`.
|
999 | * @property {string} type `waiting`.
|
1000 | * @property {Workbox} target The `Workbox` instance.
|
1001 | */
|
1002 |
|
1003 | /**
|
1004 | * The `controlling` event is dispatched if a
|
1005 | * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
|
1006 | * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}
|
1007 | * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
|
1008 | * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}
|
1009 | * matches the `scriptURL` of the `Workbox` instance's
|
1010 | * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.
|
1011 | *
|
1012 | * @event module:workbox-window.Workbox#controlling
|
1013 | * @type {WorkboxEvent}
|
1014 | * @property {ServiceWorker} sw The service worker instance.
|
1015 | * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
|
1016 | * event.
|
1017 | * @property {boolean|undefined} isUpdate True if a service worker was already
|
1018 | * controlling when this service worker was registered.
|
1019 | * @property {string} type `controlling`.
|
1020 | * @property {Workbox} target The `Workbox` instance.
|
1021 | */
|
1022 |
|
1023 | /**
|
1024 | * The `activated` event is dispatched if the state of a
|
1025 | * [`Workbox`]{@link module:workbox-window.Workbox} instance's
|
1026 | * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
|
1027 | * changes to `activated`.
|
1028 | *
|
1029 | * @event module:workbox-window.Workbox#activated
|
1030 | * @type {WorkboxEvent}
|
1031 | * @property {ServiceWorker} sw The service worker instance.
|
1032 | * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
|
1033 | * event.
|
1034 | * @property {boolean|undefined} isUpdate True if a service worker was already
|
1035 | * controlling when this `Workbox` instance called `register()`.
|
1036 | * @property {string} type `activated`.
|
1037 | * @property {Workbox} target The `Workbox` instance.
|
1038 | */
|
1039 |
|
1040 | /**
|
1041 | * The `redundant` event is dispatched if the state of a
|
1042 | * [`Workbox`]{@link module:workbox-window.Workbox} instance's
|
1043 | * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
|
1044 | * changes to `redundant`.
|
1045 | *
|
1046 | * @event module:workbox-window.Workbox#redundant
|
1047 | * @type {WorkboxEvent}
|
1048 | * @property {ServiceWorker} sw The service worker instance.
|
1049 | * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
|
1050 | * event.
|
1051 | * @property {boolean|undefined} isUpdate True if a service worker was already
|
1052 | * controlling when this `Workbox` instance called `register()`.
|
1053 | * @property {string} type `redundant`.
|
1054 | * @property {Workbox} target The `Workbox` instance.
|
1055 | */
|
1056 |
|
1057 | /**
|
1058 | * The `externalinstalled` event is dispatched if the state of an
|
1059 | * [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}
|
1060 | * changes to `installed`.
|
1061 | *
|
1062 | * @event module:workbox-window.Workbox#externalinstalled
|
1063 | * @type {WorkboxEvent}
|
1064 | * @property {ServiceWorker} sw The service worker instance.
|
1065 | * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
|
1066 | * event.
|
1067 | * @property {string} type `externalinstalled`.
|
1068 | * @property {Workbox} target The `Workbox` instance.
|
1069 | */
|
1070 |
|
1071 | /**
|
1072 | * The `externalwaiting` event is dispatched if the state of an
|
1073 | * [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}
|
1074 | * changes to `waiting`.
|
1075 | *
|
1076 | * @event module:workbox-window.Workbox#externalwaiting
|
1077 | * @type {WorkboxEvent}
|
1078 | * @property {ServiceWorker} sw The service worker instance.
|
1079 | * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
|
1080 | * event.
|
1081 | * @property {string} type `externalwaiting`.
|
1082 | * @property {Workbox} target The `Workbox` instance.
|
1083 | */
|
1084 |
|
1085 | /**
|
1086 | * The `externalactivated` event is dispatched if the state of an
|
1087 | * [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}
|
1088 | * changes to `activated`.
|
1089 | *
|
1090 | * @event module:workbox-window.Workbox#externalactivated
|
1091 | * @type {WorkboxEvent}
|
1092 | * @property {ServiceWorker} sw The service worker instance.
|
1093 | * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
|
1094 | * event.
|
1095 | * @property {string} type `externalactivated`.
|
1096 | * @property {Workbox} target The `Workbox` instance.
|
1097 | */
|
1098 |
|
1099 |
|
1100 | function _invoke(body, then) {
|
1101 | var result = body();
|
1102 |
|
1103 | if (result && result.then) {
|
1104 | return result.then(then);
|
1105 | }
|
1106 |
|
1107 | return then(result);
|
1108 | }
|
1109 |
|
1110 | function _catch(body, recover) {
|
1111 | try {
|
1112 | var result = body();
|
1113 | } catch (e) {
|
1114 | return recover(e);
|
1115 | }
|
1116 |
|
1117 | if (result && result.then) {
|
1118 | return result.then(void 0, recover);
|
1119 | }
|
1120 |
|
1121 | return result;
|
1122 | }
|
1123 |
|
1124 | export { Workbox, messageSW };
|
1125 |
|