workbox-window.dev.es5.mjs 40 KB

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