PageSourceSearch

https://brain-beats.in/js/workbox/workbox-v7.3.0/workbox-window.dev.es5.mjs

js brain-beats.in collected 2026-10-09 22:11:18 UTC 41,303 bytes, 1,012 lines download raw bytes

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

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.