workbox-window.dev.mjs 34 KB

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