web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1210 lines
40 KiB

  1. this.workbox = this.workbox || {};
  2. this.workbox.precaching = (function (exports, cacheNames_js, getFriendlyURL_js, logger_js, assert_js, cacheWrapper_js, fetchWrapper_js, WorkboxError_js, copyResponse_js) {
  3. 'use strict';
  4. try {
  5. self['workbox:precaching:5.1.4'] && _();
  6. } catch (e) {}
  7. /*
  8. Copyright 2019 Google LLC
  9. Use of this source code is governed by an MIT-style
  10. license that can be found in the LICENSE file or at
  11. https://opensource.org/licenses/MIT.
  12. */
  13. const plugins = [];
  14. const precachePlugins = {
  15. /*
  16. * @return {Array}
  17. * @private
  18. */
  19. get() {
  20. return plugins;
  21. },
  22. /*
  23. * @param {Array} newPlugins
  24. * @private
  25. */
  26. add(newPlugins) {
  27. plugins.push(...newPlugins);
  28. }
  29. };
  30. /*
  31. Copyright 2019 Google LLC
  32. Use of this source code is governed by an MIT-style
  33. license that can be found in the LICENSE file or at
  34. https://opensource.org/licenses/MIT.
  35. */
  36. /**
  37. * Adds plugins to precaching.
  38. *
  39. * @param {Array<Object>} newPlugins
  40. *
  41. * @memberof module:workbox-precaching
  42. */
  43. function addPlugins(newPlugins) {
  44. precachePlugins.add(newPlugins);
  45. }
  46. /*
  47. Copyright 2018 Google LLC
  48. Use of this source code is governed by an MIT-style
  49. license that can be found in the LICENSE file or at
  50. https://opensource.org/licenses/MIT.
  51. */
  52. const REVISION_SEARCH_PARAM = '__WB_REVISION__';
  53. /**
  54. * Converts a manifest entry into a versioned URL suitable for precaching.
  55. *
  56. * @param {Object|string} entry
  57. * @return {string} A URL with versioning info.
  58. *
  59. * @private
  60. * @memberof module:workbox-precaching
  61. */
  62. function createCacheKey(entry) {
  63. if (!entry) {
  64. throw new WorkboxError_js.WorkboxError('add-to-cache-list-unexpected-type', {
  65. entry
  66. });
  67. } // If a precache manifest entry is a string, it's assumed to be a versioned
  68. // URL, like '/app.abcd1234.js'. Return as-is.
  69. if (typeof entry === 'string') {
  70. const urlObject = new URL(entry, location.href);
  71. return {
  72. cacheKey: urlObject.href,
  73. url: urlObject.href
  74. };
  75. }
  76. const {
  77. revision,
  78. url
  79. } = entry;
  80. if (!url) {
  81. throw new WorkboxError_js.WorkboxError('add-to-cache-list-unexpected-type', {
  82. entry
  83. });
  84. } // If there's just a URL and no revision, then it's also assumed to be a
  85. // versioned URL.
  86. if (!revision) {
  87. const urlObject = new URL(url, location.href);
  88. return {
  89. cacheKey: urlObject.href,
  90. url: urlObject.href
  91. };
  92. } // Otherwise, construct a properly versioned URL using the custom Workbox
  93. // search parameter along with the revision info.
  94. const cacheKeyURL = new URL(url, location.href);
  95. const originalURL = new URL(url, location.href);
  96. cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
  97. return {
  98. cacheKey: cacheKeyURL.href,
  99. url: originalURL.href
  100. };
  101. }
  102. /*
  103. Copyright 2018 Google LLC
  104. Use of this source code is governed by an MIT-style
  105. license that can be found in the LICENSE file or at
  106. https://opensource.org/licenses/MIT.
  107. */
  108. /**
  109. * @param {string} groupTitle
  110. * @param {Array<string>} deletedURLs
  111. *
  112. * @private
  113. */
  114. const logGroup = (groupTitle, deletedURLs) => {
  115. logger_js.logger.groupCollapsed(groupTitle);
  116. for (const url of deletedURLs) {
  117. logger_js.logger.log(url);
  118. }
  119. logger_js.logger.groupEnd();
  120. };
  121. /**
  122. * @param {Array<string>} deletedURLs
  123. *
  124. * @private
  125. * @memberof module:workbox-precaching
  126. */
  127. function printCleanupDetails(deletedURLs) {
  128. const deletionCount = deletedURLs.length;
  129. if (deletionCount > 0) {
  130. logger_js.logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`);
  131. logGroup('Deleted Cache Requests', deletedURLs);
  132. logger_js.logger.groupEnd();
  133. }
  134. }
  135. /*
  136. Copyright 2018 Google LLC
  137. Use of this source code is governed by an MIT-style
  138. license that can be found in the LICENSE file or at
  139. https://opensource.org/licenses/MIT.
  140. */
  141. /**
  142. * @param {string} groupTitle
  143. * @param {Array<string>} urls
  144. *
  145. * @private
  146. */
  147. function _nestedGroup(groupTitle, urls) {
  148. if (urls.length === 0) {
  149. return;
  150. }
  151. logger_js.logger.groupCollapsed(groupTitle);
  152. for (const url of urls) {
  153. logger_js.logger.log(url);
  154. }
  155. logger_js.logger.groupEnd();
  156. }
  157. /**
  158. * @param {Array<string>} urlsToPrecache
  159. * @param {Array<string>} urlsAlreadyPrecached
  160. *
  161. * @private
  162. * @memberof module:workbox-precaching
  163. */
  164. function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
  165. const precachedCount = urlsToPrecache.length;
  166. const alreadyPrecachedCount = urlsAlreadyPrecached.length;
  167. if (precachedCount || alreadyPrecachedCount) {
  168. let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`;
  169. if (alreadyPrecachedCount > 0) {
  170. message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`;
  171. }
  172. logger_js.logger.groupCollapsed(message);
  173. _nestedGroup(`View newly precached URLs.`, urlsToPrecache);
  174. _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);
  175. logger_js.logger.groupEnd();
  176. }
  177. }
  178. /*
  179. Copyright 2019 Google LLC
  180. Use of this source code is governed by an MIT-style
  181. license that can be found in the LICENSE file or at
  182. https://opensource.org/licenses/MIT.
  183. */
  184. /**
  185. * Performs efficient precaching of assets.
  186. *
  187. * @memberof module:workbox-precaching
  188. */
  189. class PrecacheController {
  190. /**
  191. * Create a new PrecacheController.
  192. *
  193. * @param {string} [cacheName] An optional name for the cache, to override
  194. * the default precache name.
  195. */
  196. constructor(cacheName) {
  197. this._cacheName = cacheNames_js.cacheNames.getPrecacheName(cacheName);
  198. this._urlsToCacheKeys = new Map();
  199. this._urlsToCacheModes = new Map();
  200. this._cacheKeysToIntegrities = new Map();
  201. }
  202. /**
  203. * This method will add items to the precache list, removing duplicates
  204. * and ensuring the information is valid.
  205. *
  206. * @param {
  207. * Array<module:workbox-precaching.PrecacheController.PrecacheEntry|string>
  208. * } entries Array of entries to precache.
  209. */
  210. addToCacheList(entries) {
  211. {
  212. assert_js.assert.isArray(entries, {
  213. moduleName: 'workbox-precaching',
  214. className: 'PrecacheController',
  215. funcName: 'addToCacheList',
  216. paramName: 'entries'
  217. });
  218. }
  219. const urlsToWarnAbout = [];
  220. for (const entry of entries) {
  221. // See https://github.com/GoogleChrome/workbox/issues/2259
  222. if (typeof entry === 'string') {
  223. urlsToWarnAbout.push(entry);
  224. } else if (entry && entry.revision === undefined) {
  225. urlsToWarnAbout.push(entry.url);
  226. }
  227. const {
  228. cacheKey,
  229. url
  230. } = createCacheKey(entry);
  231. const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';
  232. if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
  233. throw new WorkboxError_js.WorkboxError('add-to-cache-list-conflicting-entries', {
  234. firstEntry: this._urlsToCacheKeys.get(url),
  235. secondEntry: cacheKey
  236. });
  237. }
  238. if (typeof entry !== 'string' && entry.integrity) {
  239. if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
  240. throw new WorkboxError_js.WorkboxError('add-to-cache-list-conflicting-integrities', {
  241. url
  242. });
  243. }
  244. this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
  245. }
  246. this._urlsToCacheKeys.set(url, cacheKey);
  247. this._urlsToCacheModes.set(url, cacheMode);
  248. if (urlsToWarnAbout.length > 0) {
  249. const warningMessage = `Workbox is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`;
  250. {
  251. logger_js.logger.warn(warningMessage);
  252. }
  253. }
  254. }
  255. }
  256. /**
  257. * Precaches new and updated assets. Call this method from the service worker
  258. * install event.
  259. *
  260. * @param {Object} options
  261. * @param {Event} [options.event] The install event (if needed).
  262. * @param {Array<Object>} [options.plugins] Plugins to be used for fetching
  263. * and caching during install.
  264. * @return {Promise<module:workbox-precaching.InstallResult>}
  265. */
  266. async install({
  267. event,
  268. plugins
  269. } = {}) {
  270. {
  271. if (plugins) {
  272. assert_js.assert.isArray(plugins, {
  273. moduleName: 'workbox-precaching',
  274. className: 'PrecacheController',
  275. funcName: 'install',
  276. paramName: 'plugins'
  277. });
  278. }
  279. }
  280. const toBePrecached = [];
  281. const alreadyPrecached = [];
  282. const cache = await self.caches.open(this._cacheName);
  283. const alreadyCachedRequests = await cache.keys();
  284. const existingCacheKeys = new Set(alreadyCachedRequests.map(request => request.url));
  285. for (const [url, cacheKey] of this._urlsToCacheKeys) {
  286. if (existingCacheKeys.has(cacheKey)) {
  287. alreadyPrecached.push(url);
  288. } else {
  289. toBePrecached.push({
  290. cacheKey,
  291. url
  292. });
  293. }
  294. }
  295. const precacheRequests = toBePrecached.map(({
  296. cacheKey,
  297. url
  298. }) => {
  299. const integrity = this._cacheKeysToIntegrities.get(cacheKey);
  300. const cacheMode = this._urlsToCacheModes.get(url);
  301. return this._addURLToCache({
  302. cacheKey,
  303. cacheMode,
  304. event,
  305. integrity,
  306. plugins,
  307. url
  308. });
  309. });
  310. await Promise.all(precacheRequests);
  311. const updatedURLs = toBePrecached.map(item => item.url);
  312. {
  313. printInstallDetails(updatedURLs, alreadyPrecached);
  314. }
  315. return {
  316. updatedURLs,
  317. notUpdatedURLs: alreadyPrecached
  318. };
  319. }
  320. /**
  321. * Deletes assets that are no longer present in the current precache manifest.
  322. * Call this method from the service worker activate event.
  323. *
  324. * @return {Promise<module:workbox-precaching.CleanupResult>}
  325. */
  326. async activate() {
  327. const cache = await self.caches.open(this._cacheName);
  328. const currentlyCachedRequests = await cache.keys();
  329. const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
  330. const deletedURLs = [];
  331. for (const request of currentlyCachedRequests) {
  332. if (!expectedCacheKeys.has(request.url)) {
  333. await cache.delete(request);
  334. deletedURLs.push(request.url);
  335. }
  336. }
  337. {
  338. printCleanupDetails(deletedURLs);
  339. }
  340. return {
  341. deletedURLs
  342. };
  343. }
  344. /**
  345. * Requests the entry and saves it to the cache if the response is valid.
  346. * By default, any response with a status code of less than 400 (including
  347. * opaque responses) is considered valid.
  348. *
  349. * If you need to use custom criteria to determine what's valid and what
  350. * isn't, then pass in an item in `options.plugins` that implements the
  351. * `cacheWillUpdate()` lifecycle event.
  352. *
  353. * @private
  354. * @param {Object} options
  355. * @param {string} options.cacheKey The string to use a cache key.
  356. * @param {string} options.url The URL to fetch and cache.
  357. * @param {string} [options.cacheMode] The cache mode for the network request.
  358. * @param {Event} [options.event] The install event (if passed).
  359. * @param {Array<Object>} [options.plugins] An array of plugins to apply to
  360. * fetch and caching.
  361. * @param {string} [options.integrity] The value to use for the `integrity`
  362. * field when making the request.
  363. */
  364. async _addURLToCache({
  365. cacheKey,
  366. url,
  367. cacheMode,
  368. event,
  369. plugins,
  370. integrity
  371. }) {
  372. const request = new Request(url, {
  373. integrity,
  374. cache: cacheMode,
  375. credentials: 'same-origin'
  376. });
  377. let response = await fetchWrapper_js.fetchWrapper.fetch({
  378. event,
  379. plugins,
  380. request
  381. }); // Allow developers to override the default logic about what is and isn't
  382. // valid by passing in a plugin implementing cacheWillUpdate(), e.g.
  383. // a `CacheableResponsePlugin` instance.
  384. let cacheWillUpdatePlugin;
  385. for (const plugin of plugins || []) {
  386. if ('cacheWillUpdate' in plugin) {
  387. cacheWillUpdatePlugin = plugin;
  388. }
  389. }
  390. const isValidResponse = cacheWillUpdatePlugin ? // Use a callback if provided. It returns a truthy value if valid.
  391. // NOTE: invoke the method on the plugin instance so the `this` context
  392. // is correct.
  393. await cacheWillUpdatePlugin.cacheWillUpdate({
  394. event,
  395. request,
  396. response
  397. }) : // Otherwise, default to considering any response status under 400 valid.
  398. // This includes, by default, considering opaque responses valid.
  399. response.status < 400; // Consider this a failure, leading to the `install` handler failing, if
  400. // we get back an invalid response.
  401. if (!isValidResponse) {
  402. throw new WorkboxError_js.WorkboxError('bad-precaching-response', {
  403. url,
  404. status: response.status
  405. });
  406. } // Redirected responses cannot be used to satisfy a navigation request, so
  407. // any redirected response must be "copied" rather than cloned, so the new
  408. // response doesn't contain the `redirected` flag. See:
  409. // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
  410. if (response.redirected) {
  411. response = await copyResponse_js.copyResponse(response);
  412. }
  413. await cacheWrapper_js.cacheWrapper.put({
  414. event,
  415. plugins,
  416. response,
  417. // `request` already uses `url`. We may be able to reuse it.
  418. request: cacheKey === url ? request : new Request(cacheKey),
  419. cacheName: this._cacheName,
  420. matchOptions: {
  421. ignoreSearch: true
  422. }
  423. });
  424. }
  425. /**
  426. * Returns a mapping of a precached URL to the corresponding cache key, taking
  427. * into account the revision information for the URL.
  428. *
  429. * @return {Map<string, string>} A URL to cache key mapping.
  430. */
  431. getURLsToCacheKeys() {
  432. return this._urlsToCacheKeys;
  433. }
  434. /**
  435. * Returns a list of all the URLs that have been precached by the current
  436. * service worker.
  437. *
  438. * @return {Array<string>} The precached URLs.
  439. */
  440. getCachedURLs() {
  441. return [...this._urlsToCacheKeys.keys()];
  442. }
  443. /**
  444. * Returns the cache key used for storing a given URL. If that URL is
  445. * unversioned, like `/index.html', then the cache key will be the original
  446. * URL with a search parameter appended to it.
  447. *
  448. * @param {string} url A URL whose cache key you want to look up.
  449. * @return {string} The versioned URL that corresponds to a cache key
  450. * for the original URL, or undefined if that URL isn't precached.
  451. */
  452. getCacheKeyForURL(url) {
  453. const urlObject = new URL(url, location.href);
  454. return this._urlsToCacheKeys.get(urlObject.href);
  455. }
  456. /**
  457. * This acts as a drop-in replacement for [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
  458. * with the following differences:
  459. *
  460. * - It knows what the name of the precache is, and only checks in that cache.
  461. * - It allows you to pass in an "original" URL without versioning parameters,
  462. * and it will automatically look up the correct cache key for the currently
  463. * active revision of that URL.
  464. *
  465. * E.g., `matchPrecache('index.html')` will find the correct precached
  466. * response for the currently active service worker, even if the actual cache
  467. * key is `'/index.html?__WB_REVISION__=1234abcd'`.
  468. *
  469. * @param {string|Request} request The key (without revisioning parameters)
  470. * to look up in the precache.
  471. * @return {Promise<Response|undefined>}
  472. */
  473. async matchPrecache(request) {
  474. const url = request instanceof Request ? request.url : request;
  475. const cacheKey = this.getCacheKeyForURL(url);
  476. if (cacheKey) {
  477. const cache = await self.caches.open(this._cacheName);
  478. return cache.match(cacheKey);
  479. }
  480. return undefined;
  481. }
  482. /**
  483. * Returns a function that can be used within a
  484. * {@link module:workbox-routing.Route} that will find a response for the
  485. * incoming request against the precache.
  486. *
  487. * If for an unexpected reason there is a cache miss for the request,
  488. * this will fall back to retrieving the `Response` via `fetch()` when
  489. * `fallbackToNetwork` is `true`.
  490. *
  491. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  492. * response from the network if there's a precache miss.
  493. * @return {module:workbox-routing~handlerCallback}
  494. */
  495. createHandler(fallbackToNetwork = true) {
  496. return async ({
  497. request
  498. }) => {
  499. try {
  500. const response = await this.matchPrecache(request);
  501. if (response) {
  502. return response;
  503. } // This shouldn't normally happen, but there are edge cases:
  504. // https://github.com/GoogleChrome/workbox/issues/1441
  505. throw new WorkboxError_js.WorkboxError('missing-precache-entry', {
  506. cacheName: this._cacheName,
  507. url: request instanceof Request ? request.url : request
  508. });
  509. } catch (error) {
  510. if (fallbackToNetwork) {
  511. {
  512. logger_js.logger.debug(`Unable to respond with precached response. ` + `Falling back to network.`, error);
  513. }
  514. return fetch(request);
  515. }
  516. throw error;
  517. }
  518. };
  519. }
  520. /**
  521. * Returns a function that looks up `url` in the precache (taking into
  522. * account revision information), and returns the corresponding `Response`.
  523. *
  524. * If for an unexpected reason there is a cache miss when looking up `url`,
  525. * this will fall back to retrieving the `Response` via `fetch()` when
  526. * `fallbackToNetwork` is `true`.
  527. *
  528. * @param {string} url The precached URL which will be used to lookup the
  529. * `Response`.
  530. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  531. * response from the network if there's a precache miss.
  532. * @return {module:workbox-routing~handlerCallback}
  533. */
  534. createHandlerBoundToURL(url, fallbackToNetwork = true) {
  535. const cacheKey = this.getCacheKeyForURL(url);
  536. if (!cacheKey) {
  537. throw new WorkboxError_js.WorkboxError('non-precached-url', {
  538. url
  539. });
  540. }
  541. const handler = this.createHandler(fallbackToNetwork);
  542. const request = new Request(url);
  543. return () => handler({
  544. request
  545. });
  546. }
  547. }
  548. /*
  549. Copyright 2019 Google LLC
  550. Use of this source code is governed by an MIT-style
  551. license that can be found in the LICENSE file or at
  552. https://opensource.org/licenses/MIT.
  553. */
  554. let precacheController;
  555. /**
  556. * @return {PrecacheController}
  557. * @private
  558. */
  559. const getOrCreatePrecacheController = () => {
  560. if (!precacheController) {
  561. precacheController = new PrecacheController();
  562. }
  563. return precacheController;
  564. };
  565. /*
  566. Copyright 2018 Google LLC
  567. Use of this source code is governed by an MIT-style
  568. license that can be found in the LICENSE file or at
  569. https://opensource.org/licenses/MIT.
  570. */
  571. /**
  572. * Removes any URL search parameters that should be ignored.
  573. *
  574. * @param {URL} urlObject The original URL.
  575. * @param {Array<RegExp>} ignoreURLParametersMatching RegExps to test against
  576. * each search parameter name. Matches mean that the search parameter should be
  577. * ignored.
  578. * @return {URL} The URL with any ignored search parameters removed.
  579. *
  580. * @private
  581. * @memberof module:workbox-precaching
  582. */
  583. function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {
  584. // Convert the iterable into an array at the start of the loop to make sure
  585. // deletion doesn't mess up iteration.
  586. for (const paramName of [...urlObject.searchParams.keys()]) {
  587. if (ignoreURLParametersMatching.some(regExp => regExp.test(paramName))) {
  588. urlObject.searchParams.delete(paramName);
  589. }
  590. }
  591. return urlObject;
  592. }
  593. /*
  594. Copyright 2019 Google LLC
  595. Use of this source code is governed by an MIT-style
  596. license that can be found in the LICENSE file or at
  597. https://opensource.org/licenses/MIT.
  598. */
  599. /**
  600. * Generator function that yields possible variations on the original URL to
  601. * check, one at a time.
  602. *
  603. * @param {string} url
  604. * @param {Object} options
  605. *
  606. * @private
  607. * @memberof module:workbox-precaching
  608. */
  609. function* generateURLVariations(url, {
  610. ignoreURLParametersMatching,
  611. directoryIndex,
  612. cleanURLs,
  613. urlManipulation
  614. } = {}) {
  615. const urlObject = new URL(url, location.href);
  616. urlObject.hash = '';
  617. yield urlObject.href;
  618. const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
  619. yield urlWithoutIgnoredParams.href;
  620. if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {
  621. const directoryURL = new URL(urlWithoutIgnoredParams.href);
  622. directoryURL.pathname += directoryIndex;
  623. yield directoryURL.href;
  624. }
  625. if (cleanURLs) {
  626. const cleanURL = new URL(urlWithoutIgnoredParams.href);
  627. cleanURL.pathname += '.html';
  628. yield cleanURL.href;
  629. }
  630. if (urlManipulation) {
  631. const additionalURLs = urlManipulation({
  632. url: urlObject
  633. });
  634. for (const urlToAttempt of additionalURLs) {
  635. yield urlToAttempt.href;
  636. }
  637. }
  638. }
  639. /*
  640. Copyright 2019 Google LLC
  641. Use of this source code is governed by an MIT-style
  642. license that can be found in the LICENSE file or at
  643. https://opensource.org/licenses/MIT.
  644. */
  645. /**
  646. * This function will take the request URL and manipulate it based on the
  647. * configuration options.
  648. *
  649. * @param {string} url
  650. * @param {Object} options
  651. * @return {string} Returns the URL in the cache that matches the request,
  652. * if possible.
  653. *
  654. * @private
  655. */
  656. const getCacheKeyForURL = (url, options) => {
  657. const precacheController = getOrCreatePrecacheController();
  658. const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
  659. for (const possibleURL of generateURLVariations(url, options)) {
  660. const possibleCacheKey = urlsToCacheKeys.get(possibleURL);
  661. if (possibleCacheKey) {
  662. return possibleCacheKey;
  663. }
  664. }
  665. };
  666. /*
  667. Copyright 2019 Google LLC
  668. Use of this source code is governed by an MIT-style
  669. license that can be found in the LICENSE file or at
  670. https://opensource.org/licenses/MIT.
  671. */
  672. /**
  673. * Adds a `fetch` listener to the service worker that will
  674. * respond to
  675. * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
  676. * with precached assets.
  677. *
  678. * Requests for assets that aren't precached, the `FetchEvent` will not be
  679. * responded to, allowing the event to fall through to other `fetch` event
  680. * listeners.
  681. *
  682. * NOTE: when called more than once this method will replace the previously set
  683. * configuration options. Calling it more than once is not recommended outside
  684. * of tests.
  685. *
  686. * @private
  687. * @param {Object} [options]
  688. * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
  689. * check cache entries for a URLs ending with '/' to see if there is a hit when
  690. * appending the `directoryIndex` value.
  691. * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/]] An
  692. * array of regex's to remove search params when looking for a cache match.
  693. * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
  694. * check the cache for the URL with a `.html` added to the end of the end.
  695. * @param {workbox.precaching~urlManipulation} [options.urlManipulation]
  696. * This is a function that should take a URL and return an array of
  697. * alternative URLs that should be checked for precache matches.
  698. */
  699. const addFetchListener = ({
  700. ignoreURLParametersMatching = [/^utm_/],
  701. directoryIndex = 'index.html',
  702. cleanURLs = true,
  703. urlManipulation
  704. } = {}) => {
  705. const cacheName = cacheNames_js.cacheNames.getPrecacheName(); // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  706. self.addEventListener('fetch', event => {
  707. const precachedURL = getCacheKeyForURL(event.request.url, {
  708. cleanURLs,
  709. directoryIndex,
  710. ignoreURLParametersMatching,
  711. urlManipulation
  712. });
  713. if (!precachedURL) {
  714. {
  715. logger_js.logger.debug(`Precaching did not find a match for ` + getFriendlyURL_js.getFriendlyURL(event.request.url));
  716. }
  717. return;
  718. }
  719. let responsePromise = self.caches.open(cacheName).then(cache => {
  720. return cache.match(precachedURL);
  721. }).then(cachedResponse => {
  722. if (cachedResponse) {
  723. return cachedResponse;
  724. } // Fall back to the network if we don't have a cached response
  725. // (perhaps due to manual cache cleanup).
  726. {
  727. logger_js.logger.warn(`The precached response for ` + `${getFriendlyURL_js.getFriendlyURL(precachedURL)} in ${cacheName} was not found. ` + `Falling back to the network instead.`);
  728. }
  729. return fetch(precachedURL);
  730. });
  731. {
  732. responsePromise = responsePromise.then(response => {
  733. // Workbox is going to handle the route.
  734. // print the routing details to the console.
  735. logger_js.logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL_js.getFriendlyURL(event.request.url));
  736. logger_js.logger.log(`Serving the precached url: ${precachedURL}`);
  737. logger_js.logger.groupCollapsed(`View request details here.`);
  738. logger_js.logger.log(event.request);
  739. logger_js.logger.groupEnd();
  740. logger_js.logger.groupCollapsed(`View response details here.`);
  741. logger_js.logger.log(response);
  742. logger_js.logger.groupEnd();
  743. logger_js.logger.groupEnd();
  744. return response;
  745. });
  746. }
  747. event.respondWith(responsePromise);
  748. });
  749. };
  750. /*
  751. Copyright 2019 Google LLC
  752. Use of this source code is governed by an MIT-style
  753. license that can be found in the LICENSE file or at
  754. https://opensource.org/licenses/MIT.
  755. */
  756. let listenerAdded = false;
  757. /**
  758. * Add a `fetch` listener to the service worker that will
  759. * respond to
  760. * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
  761. * with precached assets.
  762. *
  763. * Requests for assets that aren't precached, the `FetchEvent` will not be
  764. * responded to, allowing the event to fall through to other `fetch` event
  765. * listeners.
  766. *
  767. * @param {Object} [options]
  768. * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
  769. * check cache entries for a URLs ending with '/' to see if there is a hit when
  770. * appending the `directoryIndex` value.
  771. * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/]] An
  772. * array of regex's to remove search params when looking for a cache match.
  773. * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
  774. * check the cache for the URL with a `.html` added to the end of the end.
  775. * @param {module:workbox-precaching~urlManipulation} [options.urlManipulation]
  776. * This is a function that should take a URL and return an array of
  777. * alternative URLs that should be checked for precache matches.
  778. *
  779. * @memberof module:workbox-precaching
  780. */
  781. function addRoute(options) {
  782. if (!listenerAdded) {
  783. addFetchListener(options);
  784. listenerAdded = true;
  785. }
  786. }
  787. /*
  788. Copyright 2018 Google LLC
  789. Use of this source code is governed by an MIT-style
  790. license that can be found in the LICENSE file or at
  791. https://opensource.org/licenses/MIT.
  792. */
  793. const SUBSTRING_TO_FIND = '-precache-';
  794. /**
  795. * Cleans up incompatible precaches that were created by older versions of
  796. * Workbox, by a service worker registered under the current scope.
  797. *
  798. * This is meant to be called as part of the `activate` event.
  799. *
  800. * This should be safe to use as long as you don't include `substringToFind`
  801. * (defaulting to `-precache-`) in your non-precache cache names.
  802. *
  803. * @param {string} currentPrecacheName The cache name currently in use for
  804. * precaching. This cache won't be deleted.
  805. * @param {string} [substringToFind='-precache-'] Cache names which include this
  806. * substring will be deleted (excluding `currentPrecacheName`).
  807. * @return {Array<string>} A list of all the cache names that were deleted.
  808. *
  809. * @private
  810. * @memberof module:workbox-precaching
  811. */
  812. const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {
  813. const cacheNames = await self.caches.keys();
  814. const cacheNamesToDelete = cacheNames.filter(cacheName => {
  815. return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
  816. });
  817. await Promise.all(cacheNamesToDelete.map(cacheName => self.caches.delete(cacheName)));
  818. return cacheNamesToDelete;
  819. };
  820. /*
  821. Copyright 2019 Google LLC
  822. Use of this source code is governed by an MIT-style
  823. license that can be found in the LICENSE file or at
  824. https://opensource.org/licenses/MIT.
  825. */
  826. /**
  827. * Adds an `activate` event listener which will clean up incompatible
  828. * precaches that were created by older versions of Workbox.
  829. *
  830. * @memberof module:workbox-precaching
  831. */
  832. function cleanupOutdatedCaches() {
  833. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  834. self.addEventListener('activate', event => {
  835. const cacheName = cacheNames_js.cacheNames.getPrecacheName();
  836. event.waitUntil(deleteOutdatedCaches(cacheName).then(cachesDeleted => {
  837. {
  838. if (cachesDeleted.length > 0) {
  839. logger_js.logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted);
  840. }
  841. }
  842. }));
  843. });
  844. }
  845. /*
  846. Copyright 2019 Google LLC
  847. Use of this source code is governed by an MIT-style
  848. license that can be found in the LICENSE file or at
  849. https://opensource.org/licenses/MIT.
  850. */
  851. /**
  852. * Helper function that calls
  853. * {@link PrecacheController#createHandler} on the default
  854. * {@link PrecacheController} instance.
  855. *
  856. * If you are creating your own {@link PrecacheController}, then call the
  857. * {@link PrecacheController#createHandler} on that instance,
  858. * instead of using this function.
  859. *
  860. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  861. * response from the network if there's a precache miss.
  862. * @return {module:workbox-routing~handlerCallback}
  863. *
  864. * @memberof module:workbox-precaching
  865. */
  866. function createHandler(fallbackToNetwork = true) {
  867. const precacheController = getOrCreatePrecacheController();
  868. return precacheController.createHandler(fallbackToNetwork);
  869. }
  870. /*
  871. Copyright 2019 Google LLC
  872. Use of this source code is governed by an MIT-style
  873. license that can be found in the LICENSE file or at
  874. https://opensource.org/licenses/MIT.
  875. */
  876. /**
  877. * Helper function that calls
  878. * {@link PrecacheController#createHandlerBoundToURL} on the default
  879. * {@link PrecacheController} instance.
  880. *
  881. * If you are creating your own {@link PrecacheController}, then call the
  882. * {@link PrecacheController#createHandlerBoundToURL} on that instance,
  883. * instead of using this function.
  884. *
  885. * @param {string} url The precached URL which will be used to lookup the
  886. * `Response`.
  887. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  888. * response from the network if there's a precache miss.
  889. * @return {module:workbox-routing~handlerCallback}
  890. *
  891. * @memberof module:workbox-precaching
  892. */
  893. function createHandlerBoundToURL(url) {
  894. const precacheController = getOrCreatePrecacheController();
  895. return precacheController.createHandlerBoundToURL(url);
  896. }
  897. /*
  898. Copyright 2019 Google LLC
  899. Use of this source code is governed by an MIT-style
  900. license that can be found in the LICENSE file or at
  901. https://opensource.org/licenses/MIT.
  902. */
  903. /**
  904. * Takes in a URL, and returns the corresponding URL that could be used to
  905. * lookup the entry in the precache.
  906. *
  907. * If a relative URL is provided, the location of the service worker file will
  908. * be used as the base.
  909. *
  910. * For precached entries without revision information, the cache key will be the
  911. * same as the original URL.
  912. *
  913. * For precached entries with revision information, the cache key will be the
  914. * original URL with the addition of a query parameter used for keeping track of
  915. * the revision info.
  916. *
  917. * @param {string} url The URL whose cache key to look up.
  918. * @return {string} The cache key that corresponds to that URL.
  919. *
  920. * @memberof module:workbox-precaching
  921. */
  922. function getCacheKeyForURL$1(url) {
  923. const precacheController = getOrCreatePrecacheController();
  924. return precacheController.getCacheKeyForURL(url);
  925. }
  926. /*
  927. Copyright 2019 Google LLC
  928. Use of this source code is governed by an MIT-style
  929. license that can be found in the LICENSE file or at
  930. https://opensource.org/licenses/MIT.
  931. */
  932. /**
  933. * Helper function that calls
  934. * {@link PrecacheController#matchPrecache} on the default
  935. * {@link PrecacheController} instance.
  936. *
  937. * If you are creating your own {@link PrecacheController}, then call
  938. * {@link PrecacheController#matchPrecache} on that instance,
  939. * instead of using this function.
  940. *
  941. * @param {string|Request} request The key (without revisioning parameters)
  942. * to look up in the precache.
  943. * @return {Promise<Response|undefined>}
  944. *
  945. * @memberof module:workbox-precaching
  946. */
  947. function matchPrecache(request) {
  948. const precacheController = getOrCreatePrecacheController();
  949. return precacheController.matchPrecache(request);
  950. }
  951. /*
  952. Copyright 2019 Google LLC
  953. Use of this source code is governed by an MIT-style
  954. license that can be found in the LICENSE file or at
  955. https://opensource.org/licenses/MIT.
  956. */
  957. const installListener = event => {
  958. const precacheController = getOrCreatePrecacheController();
  959. const plugins = precachePlugins.get();
  960. event.waitUntil(precacheController.install({
  961. event,
  962. plugins
  963. }).catch(error => {
  964. {
  965. logger_js.logger.error(`Service worker installation failed. It will ` + `be retried automatically during the next navigation.`);
  966. } // Re-throw the error to ensure installation fails.
  967. throw error;
  968. }));
  969. };
  970. const activateListener = event => {
  971. const precacheController = getOrCreatePrecacheController();
  972. event.waitUntil(precacheController.activate());
  973. };
  974. /**
  975. * Adds items to the precache list, removing any duplicates and
  976. * stores the files in the
  977. * ["precache cache"]{@link module:workbox-core.cacheNames} when the service
  978. * worker installs.
  979. *
  980. * This method can be called multiple times.
  981. *
  982. * Please note: This method **will not** serve any of the cached files for you.
  983. * It only precaches files. To respond to a network request you call
  984. * [addRoute()]{@link module:workbox-precaching.addRoute}.
  985. *
  986. * If you have a single array of files to precache, you can just call
  987. * [precacheAndRoute()]{@link module:workbox-precaching.precacheAndRoute}.
  988. *
  989. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  990. *
  991. * @memberof module:workbox-precaching
  992. */
  993. function precache(entries) {
  994. const precacheController = getOrCreatePrecacheController();
  995. precacheController.addToCacheList(entries);
  996. if (entries.length > 0) {
  997. // NOTE: these listeners will only be added once (even if the `precache()`
  998. // method is called multiple times) because event listeners are implemented
  999. // as a set, where each listener must be unique.
  1000. // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
  1001. self.addEventListener('install', installListener);
  1002. self.addEventListener('activate', activateListener);
  1003. }
  1004. }
  1005. /*
  1006. Copyright 2019 Google LLC
  1007. Use of this source code is governed by an MIT-style
  1008. license that can be found in the LICENSE file or at
  1009. https://opensource.org/licenses/MIT.
  1010. */
  1011. /**
  1012. * This method will add entries to the precache list and add a route to
  1013. * respond to fetch events.
  1014. *
  1015. * This is a convenience method that will call
  1016. * [precache()]{@link module:workbox-precaching.precache} and
  1017. * [addRoute()]{@link module:workbox-precaching.addRoute} in a single call.
  1018. *
  1019. * @param {Array<Object|string>} entries Array of entries to precache.
  1020. * @param {Object} [options] See
  1021. * [addRoute() options]{@link module:workbox-precaching.addRoute}.
  1022. *
  1023. * @memberof module:workbox-precaching
  1024. */
  1025. function precacheAndRoute(entries, options) {
  1026. precache(entries);
  1027. addRoute(options);
  1028. }
  1029. exports.PrecacheController = PrecacheController;
  1030. exports.addPlugins = addPlugins;
  1031. exports.addRoute = addRoute;
  1032. exports.cleanupOutdatedCaches = cleanupOutdatedCaches;
  1033. exports.createHandler = createHandler;
  1034. exports.createHandlerBoundToURL = createHandlerBoundToURL;
  1035. exports.getCacheKeyForURL = getCacheKeyForURL$1;
  1036. exports.matchPrecache = matchPrecache;
  1037. exports.precache = precache;
  1038. exports.precacheAndRoute = precacheAndRoute;
  1039. return exports;
  1040. }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core));
  1041. //# sourceMappingURL=workbox-precaching.dev.js.map