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