workbox-window.dev.umd.js 44 KB

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