createCacheKey.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. Copyright 2018 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
  8. import '../_version.mjs';
  9. // Name of the search parameter used to store revision info.
  10. const REVISION_SEARCH_PARAM = '__WB_REVISION__';
  11. /**
  12. * Converts a manifest entry into a versioned URL suitable for precaching.
  13. *
  14. * @param {Object} entry
  15. * @return {string} A URL with versioning info.
  16. *
  17. * @private
  18. * @memberof module:workbox-precaching
  19. */
  20. export function createCacheKey(entry) {
  21. if (!entry) {
  22. throw new WorkboxError('add-to-cache-list-unexpected-type', {entry});
  23. }
  24. // If a precache manifest entry is a string, it's assumed to be a versioned
  25. // URL, like '/app.abcd1234.js'. Return as-is.
  26. if (typeof entry === 'string') {
  27. const urlObject = new URL(entry, location);
  28. return {
  29. cacheKey: urlObject.href,
  30. url: urlObject.href,
  31. };
  32. }
  33. const {revision, url} = entry;
  34. if (!url) {
  35. throw new WorkboxError('add-to-cache-list-unexpected-type', {entry});
  36. }
  37. // If there's just a URL and no revision, then it's also assumed to be a
  38. // versioned URL.
  39. if (!revision) {
  40. const urlObject = new URL(url, location);
  41. return {
  42. cacheKey: urlObject.href,
  43. url: urlObject.href,
  44. };
  45. }
  46. // Otherwise, construct a properly versioned URL using the custom Workbox
  47. // search parameter along with the revision info.
  48. const originalURL = new URL(url, location);
  49. const cacheKeyURL = new URL(url, location);
  50. cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
  51. return {
  52. cacheKey: cacheKeyURL.href,
  53. url: originalURL.href,
  54. };
  55. }