123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649 |
- this.workbox = this.workbox || {};
- this.workbox.expiration = (function (exports, assert_js, dontWaitFor_js, logger_js, WorkboxError_js, DBWrapper_js, deleteDatabase_js, cacheNames_js, getFriendlyURL_js, registerQuotaErrorCallback_js) {
- 'use strict';
- try {
- self['workbox:expiration:5.1.4'] && _();
- } catch (e) {}
-
- const DB_NAME = 'workbox-expiration';
- const OBJECT_STORE_NAME = 'cache-entries';
- const normalizeURL = unNormalizedUrl => {
- const url = new URL(unNormalizedUrl, location.href);
- url.hash = '';
- return url.href;
- };
-
- class CacheTimestampsModel {
-
- constructor(cacheName) {
- this._cacheName = cacheName;
- this._db = new DBWrapper_js.DBWrapper(DB_NAME, 1, {
- onupgradeneeded: event => this._handleUpgrade(event)
- });
- }
-
- _handleUpgrade(event) {
- const db = event.target.result;
-
-
-
- const objStore = db.createObjectStore(OBJECT_STORE_NAME, {
- keyPath: 'id'
- });
-
-
- objStore.createIndex('cacheName', 'cacheName', {
- unique: false
- });
- objStore.createIndex('timestamp', 'timestamp', {
- unique: false
- });
-
- deleteDatabase_js.deleteDatabase(this._cacheName);
- }
-
- async setTimestamp(url, timestamp) {
- url = normalizeURL(url);
- const entry = {
- url,
- timestamp,
- cacheName: this._cacheName,
-
-
-
- id: this._getId(url)
- };
- await this._db.put(OBJECT_STORE_NAME, entry);
- }
-
- async getTimestamp(url) {
- const entry = await this._db.get(OBJECT_STORE_NAME, this._getId(url));
- return entry.timestamp;
- }
-
- async expireEntries(minTimestamp, maxCount) {
- const entriesToDelete = await this._db.transaction(OBJECT_STORE_NAME, 'readwrite', (txn, done) => {
- const store = txn.objectStore(OBJECT_STORE_NAME);
- const request = store.index('timestamp').openCursor(null, 'prev');
- const entriesToDelete = [];
- let entriesNotDeletedCount = 0;
- request.onsuccess = () => {
- const cursor = request.result;
- if (cursor) {
- const result = cursor.value;
-
- if (result.cacheName === this._cacheName) {
-
-
- if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
-
-
-
-
-
-
-
-
- entriesToDelete.push(cursor.value);
- } else {
- entriesNotDeletedCount++;
- }
- }
- cursor.continue();
- } else {
- done(entriesToDelete);
- }
- };
- });
-
-
-
- const urlsDeleted = [];
- for (const entry of entriesToDelete) {
- await this._db.delete(OBJECT_STORE_NAME, entry.id);
- urlsDeleted.push(entry.url);
- }
- return urlsDeleted;
- }
-
- _getId(url) {
-
-
-
- return this._cacheName + '|' + normalizeURL(url);
- }
- }
-
-
- class CacheExpiration {
-
- constructor(cacheName, config = {}) {
- this._isRunning = false;
- this._rerunRequested = false;
- {
- assert_js.assert.isType(cacheName, 'string', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'constructor',
- paramName: 'cacheName'
- });
- if (!(config.maxEntries || config.maxAgeSeconds)) {
- throw new WorkboxError_js.WorkboxError('max-entries-or-age-required', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'constructor'
- });
- }
- if (config.maxEntries) {
- assert_js.assert.isType(config.maxEntries, 'number', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'constructor',
- paramName: 'config.maxEntries'
- });
- }
- if (config.maxAgeSeconds) {
- assert_js.assert.isType(config.maxAgeSeconds, 'number', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'constructor',
- paramName: 'config.maxAgeSeconds'
- });
- }
- }
- this._maxEntries = config.maxEntries;
- this._maxAgeSeconds = config.maxAgeSeconds;
- this._cacheName = cacheName;
- this._timestampModel = new CacheTimestampsModel(cacheName);
- }
-
- async expireEntries() {
- if (this._isRunning) {
- this._rerunRequested = true;
- return;
- }
- this._isRunning = true;
- const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0;
- const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
- const cache = await self.caches.open(this._cacheName);
- for (const url of urlsExpired) {
- await cache.delete(url);
- }
- {
- if (urlsExpired.length > 0) {
- logger_js.logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + `'${this._cacheName}' cache.`);
- logger_js.logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);
- urlsExpired.forEach(url => logger_js.logger.log(` ${url}`));
- logger_js.logger.groupEnd();
- } else {
- logger_js.logger.debug(`Cache expiration ran and found no entries to remove.`);
- }
- }
- this._isRunning = false;
- if (this._rerunRequested) {
- this._rerunRequested = false;
- dontWaitFor_js.dontWaitFor(this.expireEntries());
- }
- }
-
- async updateTimestamp(url) {
- {
- assert_js.assert.isType(url, 'string', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'updateTimestamp',
- paramName: 'url'
- });
- }
- await this._timestampModel.setTimestamp(url, Date.now());
- }
-
- async isURLExpired(url) {
- if (!this._maxAgeSeconds) {
- {
- throw new WorkboxError_js.WorkboxError(`expired-test-without-max-age`, {
- methodName: 'isURLExpired',
- paramName: 'maxAgeSeconds'
- });
- }
- } else {
- const timestamp = await this._timestampModel.getTimestamp(url);
- const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
- return timestamp < expireOlderThan;
- }
- }
-
- async delete() {
-
-
- this._rerunRequested = false;
- await this._timestampModel.expireEntries(Infinity);
- }
- }
-
-
- class ExpirationPlugin {
-
- constructor(config = {}) {
-
- this.cachedResponseWillBeUsed = async ({
- event,
- request,
- cacheName,
- cachedResponse
- }) => {
- if (!cachedResponse) {
- return null;
- }
- const isFresh = this._isResponseDateFresh(cachedResponse);
-
- const cacheExpiration = this._getCacheExpiration(cacheName);
- dontWaitFor_js.dontWaitFor(cacheExpiration.expireEntries());
-
- const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
- if (event) {
- try {
- event.waitUntil(updateTimestampDone);
- } catch (error) {
- {
-
- if ('request' in event) {
- logger_js.logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for ` + `'${getFriendlyURL_js.getFriendlyURL(event.request.url)}'.`);
- }
- }
- }
- }
- return isFresh ? cachedResponse : null;
- };
-
- this.cacheDidUpdate = async ({
- cacheName,
- request
- }) => {
- {
- assert_js.assert.isType(cacheName, 'string', {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'cacheDidUpdate',
- paramName: 'cacheName'
- });
- assert_js.assert.isInstance(request, Request, {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'cacheDidUpdate',
- paramName: 'request'
- });
- }
- const cacheExpiration = this._getCacheExpiration(cacheName);
- await cacheExpiration.updateTimestamp(request.url);
- await cacheExpiration.expireEntries();
- };
- {
- if (!(config.maxEntries || config.maxAgeSeconds)) {
- throw new WorkboxError_js.WorkboxError('max-entries-or-age-required', {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'constructor'
- });
- }
- if (config.maxEntries) {
- assert_js.assert.isType(config.maxEntries, 'number', {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'constructor',
- paramName: 'config.maxEntries'
- });
- }
- if (config.maxAgeSeconds) {
- assert_js.assert.isType(config.maxAgeSeconds, 'number', {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'constructor',
- paramName: 'config.maxAgeSeconds'
- });
- }
- }
- this._config = config;
- this._maxAgeSeconds = config.maxAgeSeconds;
- this._cacheExpirations = new Map();
- if (config.purgeOnQuotaError) {
- registerQuotaErrorCallback_js.registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
- }
- }
-
- _getCacheExpiration(cacheName) {
- if (cacheName === cacheNames_js.cacheNames.getRuntimeName()) {
- throw new WorkboxError_js.WorkboxError('expire-custom-caches-only');
- }
- let cacheExpiration = this._cacheExpirations.get(cacheName);
- if (!cacheExpiration) {
- cacheExpiration = new CacheExpiration(cacheName, this._config);
- this._cacheExpirations.set(cacheName, cacheExpiration);
- }
- return cacheExpiration;
- }
-
- _isResponseDateFresh(cachedResponse) {
- if (!this._maxAgeSeconds) {
-
- return true;
- }
-
-
- const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
- if (dateHeaderTimestamp === null) {
-
- return true;
- }
-
- const now = Date.now();
- return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
- }
-
- _getDateHeaderTimestamp(cachedResponse) {
- if (!cachedResponse.headers.has('date')) {
- return null;
- }
- const dateHeader = cachedResponse.headers.get('date');
- const parsedDate = new Date(dateHeader);
- const headerTime = parsedDate.getTime();
-
- if (isNaN(headerTime)) {
- return null;
- }
- return headerTime;
- }
-
- async deleteCacheAndMetadata() {
-
-
- for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
- await self.caches.delete(cacheName);
- await cacheExpiration.delete();
- }
- this._cacheExpirations = new Map();
- }
- }
- exports.CacheExpiration = CacheExpiration;
- exports.ExpirationPlugin = ExpirationPlugin;
- return exports;
- }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core));
|