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