UNPKG

20.4 kBJavaScriptView Raw
1this.workbox = this.workbox || {};
2this.workbox.expiration = (function (exports, DBWrapper_mjs, deleteDatabase_mjs, WorkboxError_mjs, assert_mjs, logger_mjs, cacheNames_mjs, getFriendlyURL_mjs, registerQuotaErrorCallback_mjs) {
3 'use strict';
4
5 try {
6 self['workbox:expiration:4.1.1'] && _();
7 } catch (e) {} // eslint-disable-line
8
9 /*
10 Copyright 2018 Google LLC
11
12 Use of this source code is governed by an MIT-style
13 license that can be found in the LICENSE file or at
14 https://opensource.org/licenses/MIT.
15 */
16 const DB_NAME = 'workbox-expiration';
17 const OBJECT_STORE_NAME = 'cache-entries';
18
19 const normalizeURL = unNormalizedUrl => {
20 const url = new URL(unNormalizedUrl, location);
21 url.hash = '';
22 return url.href;
23 };
24 /**
25 * Returns the timestamp model.
26 *
27 * @private
28 */
29
30
31 class CacheTimestampsModel {
32 /**
33 *
34 * @param {string} cacheName
35 *
36 * @private
37 */
38 constructor(cacheName) {
39 this._cacheName = cacheName;
40 this._db = new DBWrapper_mjs.DBWrapper(DB_NAME, 1, {
41 onupgradeneeded: event => this._handleUpgrade(event)
42 });
43 }
44 /**
45 * Should perform an upgrade of indexedDB.
46 *
47 * @param {Event} event
48 *
49 * @private
50 */
51
52
53 _handleUpgrade(event) {
54 const db = event.target.result; // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we
55 // have to use the `id` keyPath here and create our own values (a
56 // concatenation of `url + cacheName`) instead of simply using
57 // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.
58
59 const objStore = db.createObjectStore(OBJECT_STORE_NAME, {
60 keyPath: 'id'
61 }); // TODO(philipwalton): once we don't have to support EdgeHTML, we can
62 // create a single index with the keyPath `['cacheName', 'timestamp']`
63 // instead of doing both these indexes.
64
65 objStore.createIndex('cacheName', 'cacheName', {
66 unique: false
67 });
68 objStore.createIndex('timestamp', 'timestamp', {
69 unique: false
70 }); // Previous versions of `workbox-expiration` used `this._cacheName`
71 // as the IDBDatabase name.
72
73 deleteDatabase_mjs.deleteDatabase(this._cacheName);
74 }
75 /**
76 * @param {string} url
77 * @param {number} timestamp
78 *
79 * @private
80 */
81
82
83 async setTimestamp(url, timestamp) {
84 url = normalizeURL(url);
85 await this._db.put(OBJECT_STORE_NAME, {
86 url,
87 timestamp,
88 cacheName: this._cacheName,
89 // Creating an ID from the URL and cache name won't be necessary once
90 // Edge switches to Chromium and all browsers we support work with
91 // array keyPaths.
92 id: this._getId(url)
93 });
94 }
95 /**
96 * Returns the timestamp stored for a given URL.
97 *
98 * @param {string} url
99 * @return {number}
100 *
101 * @private
102 */
103
104
105 async getTimestamp(url) {
106 const entry = await this._db.get(OBJECT_STORE_NAME, this._getId(url));
107 return entry.timestamp;
108 }
109 /**
110 * Iterates through all the entries in the object store (from newest to
111 * oldest) and removes entries once either `maxCount` is reached or the
112 * entry's timestamp is less than `minTimestamp`.
113 *
114 * @param {number} minTimestamp
115 * @param {number} maxCount
116 *
117 * @private
118 */
119
120
121 async expireEntries(minTimestamp, maxCount) {
122 return await this._db.transaction(OBJECT_STORE_NAME, 'readwrite', (txn, done) => {
123 const store = txn.objectStore(OBJECT_STORE_NAME);
124 const entriesDeleted = [];
125 let entriesNotDeletedCount = 0;
126
127 store.index('timestamp').openCursor(null, 'prev').onsuccess = ({
128 target
129 }) => {
130 const cursor = target.result;
131
132 if (cursor) {
133 const result = cursor.value; // TODO(philipwalton): once we can use a multi-key index, we
134 // won't have to check `cacheName` here.
135
136 if (result.cacheName === this._cacheName) {
137 // Delete an entry if it's older than the max age or
138 // if we already have the max number allowed.
139 if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
140 cursor.delete(); // We only need to return the URL, not the whole entry.
141
142 entriesDeleted.push(cursor.value.url);
143 } else {
144 entriesNotDeletedCount++;
145 }
146 }
147
148 cursor.continue();
149 } else {
150 done(entriesDeleted);
151 }
152 };
153 });
154 }
155 /**
156 * Takes a URL and returns an ID that will be unique in the object store.
157 *
158 * @param {string} url
159 * @return {string}
160 */
161
162
163 _getId(url) {
164 // Creating an ID from the URL and cache name won't be necessary once
165 // Edge switches to Chromium and all browsers we support work with
166 // array keyPaths.
167 return this._cacheName + '|' + normalizeURL(url);
168 }
169
170 }
171
172 /*
173 Copyright 2018 Google LLC
174
175 Use of this source code is governed by an MIT-style
176 license that can be found in the LICENSE file or at
177 https://opensource.org/licenses/MIT.
178 */
179 /**
180 * The `CacheExpiration` class allows you define an expiration and / or
181 * limit on the number of responses stored in a
182 * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
183 *
184 * @memberof workbox.expiration
185 */
186
187 class CacheExpiration {
188 /**
189 * To construct a new CacheExpiration instance you must provide at least
190 * one of the `config` properties.
191 *
192 * @param {string} cacheName Name of the cache to apply restrictions to.
193 * @param {Object} config
194 * @param {number} [config.maxEntries] The maximum number of entries to cache.
195 * Entries used the least will be removed as the maximum is reached.
196 * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
197 * it's treated as stale and removed.
198 */
199 constructor(cacheName, config = {}) {
200 {
201 assert_mjs.assert.isType(cacheName, 'string', {
202 moduleName: 'workbox-expiration',
203 className: 'CacheExpiration',
204 funcName: 'constructor',
205 paramName: 'cacheName'
206 });
207
208 if (!(config.maxEntries || config.maxAgeSeconds)) {
209 throw new WorkboxError_mjs.WorkboxError('max-entries-or-age-required', {
210 moduleName: 'workbox-expiration',
211 className: 'CacheExpiration',
212 funcName: 'constructor'
213 });
214 }
215
216 if (config.maxEntries) {
217 assert_mjs.assert.isType(config.maxEntries, 'number', {
218 moduleName: 'workbox-expiration',
219 className: 'CacheExpiration',
220 funcName: 'constructor',
221 paramName: 'config.maxEntries'
222 }); // TODO: Assert is positive
223 }
224
225 if (config.maxAgeSeconds) {
226 assert_mjs.assert.isType(config.maxAgeSeconds, 'number', {
227 moduleName: 'workbox-expiration',
228 className: 'CacheExpiration',
229 funcName: 'constructor',
230 paramName: 'config.maxAgeSeconds'
231 }); // TODO: Assert is positive
232 }
233 }
234
235 this._isRunning = false;
236 this._rerunRequested = false;
237 this._maxEntries = config.maxEntries;
238 this._maxAgeSeconds = config.maxAgeSeconds;
239 this._cacheName = cacheName;
240 this._timestampModel = new CacheTimestampsModel(cacheName);
241 }
242 /**
243 * Expires entries for the given cache and given criteria.
244 */
245
246
247 async expireEntries() {
248 if (this._isRunning) {
249 this._rerunRequested = true;
250 return;
251 }
252
253 this._isRunning = true;
254 const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : undefined;
255 const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries); // Delete URLs from the cache
256
257 const cache = await caches.open(this._cacheName);
258
259 for (const url of urlsExpired) {
260 await cache.delete(url);
261 }
262
263 {
264 if (urlsExpired.length > 0) {
265 logger_mjs.logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + `'${this._cacheName}' cache.`);
266 logger_mjs.logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);
267 urlsExpired.forEach(url => logger_mjs.logger.log(` ${url}`));
268 logger_mjs.logger.groupEnd();
269 } else {
270 logger_mjs.logger.debug(`Cache expiration ran and found no entries to remove.`);
271 }
272 }
273
274 this._isRunning = false;
275
276 if (this._rerunRequested) {
277 this._rerunRequested = false;
278 this.expireEntries();
279 }
280 }
281 /**
282 * Update the timestamp for the given URL. This ensures the when
283 * removing entries based on maximum entries, most recently used
284 * is accurate or when expiring, the timestamp is up-to-date.
285 *
286 * @param {string} url
287 */
288
289
290 async updateTimestamp(url) {
291 {
292 assert_mjs.assert.isType(url, 'string', {
293 moduleName: 'workbox-expiration',
294 className: 'CacheExpiration',
295 funcName: 'updateTimestamp',
296 paramName: 'url'
297 });
298 }
299
300 await this._timestampModel.setTimestamp(url, Date.now());
301 }
302 /**
303 * Can be used to check if a URL has expired or not before it's used.
304 *
305 * This requires a look up from IndexedDB, so can be slow.
306 *
307 * Note: This method will not remove the cached entry, call
308 * `expireEntries()` to remove indexedDB and Cache entries.
309 *
310 * @param {string} url
311 * @return {boolean}
312 */
313
314
315 async isURLExpired(url) {
316 {
317 if (!this._maxAgeSeconds) {
318 throw new WorkboxError_mjs.WorkboxError(`expired-test-without-max-age`, {
319 methodName: 'isURLExpired',
320 paramName: 'maxAgeSeconds'
321 });
322 }
323 }
324
325 const timestamp = await this._timestampModel.getTimestamp(url);
326 const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
327 return timestamp < expireOlderThan;
328 }
329 /**
330 * Removes the IndexedDB object store used to keep track of cache expiration
331 * metadata.
332 */
333
334
335 async delete() {
336 // Make sure we don't attempt another rerun if we're called in the middle of
337 // a cache expiration.
338 this._rerunRequested = false;
339 await this._timestampModel.expireEntries(Infinity); // Expires all.
340 }
341
342 }
343
344 /*
345 Copyright 2018 Google LLC
346
347 Use of this source code is governed by an MIT-style
348 license that can be found in the LICENSE file or at
349 https://opensource.org/licenses/MIT.
350 */
351 /**
352 * This plugin can be used in the Workbox APIs to regularly enforce a
353 * limit on the age and / or the number of cached requests.
354 *
355 * Whenever a cached request is used or updated, this plugin will look
356 * at the used Cache and remove any old or extra requests.
357 *
358 * When using `maxAgeSeconds`, requests may be used *once* after expiring
359 * because the expiration clean up will not have occurred until *after* the
360 * cached request has been used. If the request has a "Date" header, then
361 * a light weight expiration check is performed and the request will not be
362 * used immediately.
363 *
364 * When using `maxEntries`, the last request to be used will be the request
365 * that is removed from the Cache.
366 *
367 * @memberof workbox.expiration
368 */
369
370 class Plugin {
371 /**
372 * @param {Object} config
373 * @param {number} [config.maxEntries] The maximum number of entries to cache.
374 * Entries used the least will be removed as the maximum is reached.
375 * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
376 * it's treated as stale and removed.
377 * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to
378 * automatic deletion if the available storage quota has been exceeded.
379 */
380 constructor(config = {}) {
381 {
382 if (!(config.maxEntries || config.maxAgeSeconds)) {
383 throw new WorkboxError_mjs.WorkboxError('max-entries-or-age-required', {
384 moduleName: 'workbox-expiration',
385 className: 'Plugin',
386 funcName: 'constructor'
387 });
388 }
389
390 if (config.maxEntries) {
391 assert_mjs.assert.isType(config.maxEntries, 'number', {
392 moduleName: 'workbox-expiration',
393 className: 'Plugin',
394 funcName: 'constructor',
395 paramName: 'config.maxEntries'
396 });
397 }
398
399 if (config.maxAgeSeconds) {
400 assert_mjs.assert.isType(config.maxAgeSeconds, 'number', {
401 moduleName: 'workbox-expiration',
402 className: 'Plugin',
403 funcName: 'constructor',
404 paramName: 'config.maxAgeSeconds'
405 });
406 }
407 }
408
409 this._config = config;
410 this._maxAgeSeconds = config.maxAgeSeconds;
411 this._cacheExpirations = new Map();
412
413 if (config.purgeOnQuotaError) {
414 registerQuotaErrorCallback_mjs.registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
415 }
416 }
417 /**
418 * A simple helper method to return a CacheExpiration instance for a given
419 * cache name.
420 *
421 * @param {string} cacheName
422 * @return {CacheExpiration}
423 *
424 * @private
425 */
426
427
428 _getCacheExpiration(cacheName) {
429 if (cacheName === cacheNames_mjs.cacheNames.getRuntimeName()) {
430 throw new WorkboxError_mjs.WorkboxError('expire-custom-caches-only');
431 }
432
433 let cacheExpiration = this._cacheExpirations.get(cacheName);
434
435 if (!cacheExpiration) {
436 cacheExpiration = new CacheExpiration(cacheName, this._config);
437
438 this._cacheExpirations.set(cacheName, cacheExpiration);
439 }
440
441 return cacheExpiration;
442 }
443 /**
444 * A "lifecycle" callback that will be triggered automatically by the
445 * `workbox.strategies` handlers when a `Response` is about to be returned
446 * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
447 * the handler. It allows the `Response` to be inspected for freshness and
448 * prevents it from being used if the `Response`'s `Date` header value is
449 * older than the configured `maxAgeSeconds`.
450 *
451 * @param {Object} options
452 * @param {string} options.cacheName Name of the cache the response is in.
453 * @param {Response} options.cachedResponse The `Response` object that's been
454 * read from a cache and whose freshness should be checked.
455 * @return {Response} Either the `cachedResponse`, if it's
456 * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
457 *
458 * @private
459 */
460
461
462 cachedResponseWillBeUsed({
463 event,
464 request,
465 cacheName,
466 cachedResponse
467 }) {
468 if (!cachedResponse) {
469 return null;
470 }
471
472 let isFresh = this._isResponseDateFresh(cachedResponse); // Expire entries to ensure that even if the expiration date has
473 // expired, it'll only be used once.
474
475
476 const cacheExpiration = this._getCacheExpiration(cacheName);
477
478 cacheExpiration.expireEntries(); // Update the metadata for the request URL to the current timestamp,
479 // but don't `await` it as we don't want to block the response.
480
481 const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
482
483 if (event) {
484 try {
485 event.waitUntil(updateTimestampDone);
486 } catch (error) {
487 {
488 logger_mjs.logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for '${getFriendlyURL_mjs.getFriendlyURL(event.request.url)}'.`);
489 }
490 }
491 }
492
493 return isFresh ? cachedResponse : null;
494 }
495 /**
496 * @param {Response} cachedResponse
497 * @return {boolean}
498 *
499 * @private
500 */
501
502
503 _isResponseDateFresh(cachedResponse) {
504 if (!this._maxAgeSeconds) {
505 // We aren't expiring by age, so return true, it's fresh
506 return true;
507 } // Check if the 'date' header will suffice a quick expiration check.
508 // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
509 // discussion.
510
511
512 const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
513
514 if (dateHeaderTimestamp === null) {
515 // Unable to parse date, so assume it's fresh.
516 return true;
517 } // If we have a valid headerTime, then our response is fresh iff the
518 // headerTime plus maxAgeSeconds is greater than the current time.
519
520
521 const now = Date.now();
522 return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
523 }
524 /**
525 * This method will extract the data header and parse it into a useful
526 * value.
527 *
528 * @param {Response} cachedResponse
529 * @return {number}
530 *
531 * @private
532 */
533
534
535 _getDateHeaderTimestamp(cachedResponse) {
536 if (!cachedResponse.headers.has('date')) {
537 return null;
538 }
539
540 const dateHeader = cachedResponse.headers.get('date');
541 const parsedDate = new Date(dateHeader);
542 const headerTime = parsedDate.getTime(); // If the Date header was invalid for some reason, parsedDate.getTime()
543 // will return NaN.
544
545 if (isNaN(headerTime)) {
546 return null;
547 }
548
549 return headerTime;
550 }
551 /**
552 * A "lifecycle" callback that will be triggered automatically by the
553 * `workbox.strategies` handlers when an entry is added to a cache.
554 *
555 * @param {Object} options
556 * @param {string} options.cacheName Name of the cache that was updated.
557 * @param {string} options.request The Request for the cached entry.
558 *
559 * @private
560 */
561
562
563 async cacheDidUpdate({
564 cacheName,
565 request
566 }) {
567 {
568 assert_mjs.assert.isType(cacheName, 'string', {
569 moduleName: 'workbox-expiration',
570 className: 'Plugin',
571 funcName: 'cacheDidUpdate',
572 paramName: 'cacheName'
573 });
574 assert_mjs.assert.isInstance(request, Request, {
575 moduleName: 'workbox-expiration',
576 className: 'Plugin',
577 funcName: 'cacheDidUpdate',
578 paramName: 'request'
579 });
580 }
581
582 const cacheExpiration = this._getCacheExpiration(cacheName);
583
584 await cacheExpiration.updateTimestamp(request.url);
585 await cacheExpiration.expireEntries();
586 }
587 /**
588 * This is a helper method that performs two operations:
589 *
590 * - Deletes *all* the underlying Cache instances associated with this plugin
591 * instance, by calling caches.delete() on your behalf.
592 * - Deletes the metadata from IndexedDB used to keep track of expiration
593 * details for each Cache instance.
594 *
595 * When using cache expiration, calling this method is preferable to calling
596 * `caches.delete()` directly, since this will ensure that the IndexedDB
597 * metadata is also cleanly removed and open IndexedDB instances are deleted.
598 *
599 * Note that if you're *not* using cache expiration for a given cache, calling
600 * `caches.delete()` and passing in the cache's name should be sufficient.
601 * There is no Workbox-specific method needed for cleanup in that case.
602 */
603
604
605 async deleteCacheAndMetadata() {
606 // Do this one at a time instead of all at once via `Promise.all()` to
607 // reduce the chance of inconsistency if a promise rejects.
608 for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
609 await caches.delete(cacheName);
610 await cacheExpiration.delete();
611 } // Reset this._cacheExpirations to its initial state.
612
613
614 this._cacheExpirations = new Map();
615 }
616
617 }
618
619 /*
620 Copyright 2018 Google LLC
621
622 Use of this source code is governed by an MIT-style
623 license that can be found in the LICENSE file or at
624 https://opensource.org/licenses/MIT.
625 */
626
627 exports.CacheExpiration = CacheExpiration;
628 exports.Plugin = Plugin;
629
630 return exports;
631
632}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core));
633