createCacheKey.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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.js';
  8. import '../_version.js';
  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|string} 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.href);
  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.href);
  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 cacheKeyURL = new URL(url, location.href);
  49. const originalURL = new URL(url, location.href);
  50. cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
  51. return {
  52. cacheKey: cacheKeyURL.href,
  53. url: originalURL.href,
  54. };
  55. }