diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 0a2d073..12546d0 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -235,28 +235,13 @@ parameters: count: 1 path: src/Dto/ServiceWorker.php - - - message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\ServiceWorker has an uninitialized property \\$offlineFallbackPlaceholder\\. Give it default value or assign it in the constructor\\.$#" - count: 1 - path: src/Dto/ServiceWorker.php - - - - message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\ServiceWorker has an uninitialized property \\$precachingPlaceholder\\. Give it default value or assign it in the constructor\\.$#" - count: 1 - path: src/Dto/ServiceWorker.php - - message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\ServiceWorker has an uninitialized property \\$src\\. Give it default value or assign it in the constructor\\.$#" count: 1 path: src/Dto/ServiceWorker.php - - message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\ServiceWorker has an uninitialized property \\$warmCachePlaceholder\\. Give it default value or assign it in the constructor\\.$#" - count: 1 - path: src/Dto/ServiceWorker.php - - - - message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\ServiceWorker has an uninitialized property \\$widgetsPlaceholder\\. Give it default value or assign it in the constructor\\.$#" + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\ServiceWorker has an uninitialized property \\$workbox\\. Give it default value or assign it in the constructor\\.$#" count: 1 path: src/Dto/ServiceWorker.php @@ -330,6 +315,51 @@ parameters: count: 1 path: src/Dto/Widget.php + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$enabled\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$offlineFallbackPlaceholder\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$precachingPlaceholder\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$useCDN\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$version\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$warmCachePlaceholder\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$widgetsPlaceholder\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$workboxImportPlaceholder\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + + - + message: "#^Class SpomkyLabs\\\\PwaBundle\\\\Dto\\\\Workbox has an uninitialized property \\$workboxPublicUrl\\. Give it default value or assign it in the constructor\\.$#" + count: 1 + path: src/Dto/Workbox.php + - message: "#^Method SpomkyLabs\\\\PwaBundle\\\\ImageProcessor\\\\GDImageProcessor\\:\\:process\\(\\) should return string but returns string\\|false\\.$#" count: 1 @@ -444,3 +474,8 @@ parameters: message: "#^Method SpomkyLabs\\\\PwaBundle\\\\Normalizer\\\\UrlNormalizer\\:\\:supportsNormalization\\(\\) has parameter \\$context with no value type specified in iterable type array\\.$#" count: 1 path: src/Normalizer/UrlNormalizer.php + + - + message: "#^Parameter \\#1 \\$string of function mb_strlen expects string, string\\|null given\\.$#" + count: 1 + path: src/Subscriber/PwaDevServerSubscriber.php diff --git a/src/Command/CreateServiceWorkerCommand.php b/src/Command/CreateServiceWorkerCommand.php index cbaa2f1..50bc38c 100644 --- a/src/Command/CreateServiceWorkerCommand.php +++ b/src/Command/CreateServiceWorkerCommand.php @@ -55,7 +55,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int return self::SUCCESS; } - $resourcePath = $this->fileLocator->locate('@SpomkyLabsPwaBundle/Resources/workbox.js', null, false); + $resourcePath = $this->fileLocator->locate('@SpomkyLabsPwaBundle/Resources/sw-skeleton.js', null, false); if (count($resourcePath) !== 1) { $io->error('Unable to find the Workbox resource.'); return Command::FAILURE; diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 0d6830f..78b2eda 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -468,32 +468,91 @@ private function setupServiceWorker(ArrayNodeDefinition $node): void ->info('The public URL to the service worker.') ->example('/sw.js') ->end() - ->scalarNode('precaching_placeholder') - ->defaultValue('//PRECACHING_PLACEHOLDER') - ->info('The placeholder for the precaching. Will be replaced by the assets and versions.') - ->example('//PRECACHING_PLACEHOLDER') - ->end() - ->scalarNode('warm_cache_placeholder') - ->defaultValue('//WARM_CACHE_URLS_PLACEHOLDER') - ->info('The placeholder for the warm cache. Will be replaced by the URLs.') - ->example('//WARM_CACHE_URLS_PLACEHOLDER') - ->end() - ->scalarNode('offline_fallback_placeholder') - ->defaultValue('//OFFLINE_FALLBACK_PLACEHOLDER') - ->info('The placeholder for the offline fallback. Will be replaced by the URL.') - ->example('//OFFLINE_FALLBACK_PLACEHOLDER') - ->end() - ->scalarNode('widgets_placeholder') - ->defaultValue('//WIDGETS_PLACEHOLDER') - ->info('The placeholder for the widgets. Will be replaced by the widgets management events.') - ->example('//WIDGETS_PLACEHOLDER') + ->arrayNode('workbox') + ->info('The configuration of the workbox.') + ->canBeDisabled() + ->children() + ->booleanNode('use_cdn') + ->defaultFalse() + ->info('Whether to use the local workbox or the CDN.') + ->end() + ->scalarNode('version') + ->defaultValue('7.0.0') + ->info( + 'The version of the workbox. When using local files, the version is ignored shall be 7.0.0.' + ) + ->end() + ->scalarNode('workbox_public_url') + ->defaultValue('/workbox') + ->info('The public path to the local workbox. Only used if use_cdn is false.') + ->end() + ->scalarNode('workbox_import_placeholder') + ->defaultValue('//WORKBOX_IMPORT_PLACEHOLDER') + ->info( + 'The placeholder for the workbox import. Will be replaced by the workbox import.' + ) + ->example('//WORKBOX_IMPORT_PLACEHOLDER') + ->end() + ->scalarNode('precaching_placeholder') + ->defaultValue('//PRECACHING_PLACEHOLDER') + ->info( + 'The placeholder for the precaching. Will be replaced by the assets and versions.' + ) + ->example('//PRECACHING_PLACEHOLDER') + ->end() + ->scalarNode('warm_cache_placeholder') + ->defaultValue('//WARM_CACHE_URLS_PLACEHOLDER') + ->info('The placeholder for the warm cache. Will be replaced by the URLs.') + ->example('//WARM_CACHE_URLS_PLACEHOLDER') + ->end() + ->scalarNode('offline_fallback_placeholder') + ->defaultValue('//OFFLINE_FALLBACK_PLACEHOLDER') + ->info('The placeholder for the offline fallback. Will be replaced by the URL.') + ->example('//OFFLINE_FALLBACK_PLACEHOLDER') + ->end() + ->scalarNode('widgets_placeholder') + ->defaultValue('//WIDGETS_PLACEHOLDER') + ->info( + 'The placeholder for the widgets. Will be replaced by the widgets management events.' + ) + ->example('//WIDGETS_PLACEHOLDER') + ->end() + ->append( + $this->getUrlNode( + 'offline_fallback', + 'The URL of the offline fallback. If not set, the offline fallback will be disabled.' + ) + ) + ->arrayNode('warm_cache_urls') + ->treatNullLike([]) + ->treatFalseLike([]) + ->treatTrueLike([]) + ->info('The URLs to warm the cache. The URLs shall be served by the application.') + ->arrayPrototype() + ->beforeNormalization() + ->ifString() + ->then(static fn (string $v): array => [ + 'path' => $v, + ]) + ->end() + ->children() + ->scalarNode('path') + ->isRequired() + ->info('The URL of the shortcut.') + ->example('app_homepage') + ->end() + ->arrayNode('params') + ->treatFalseLike([]) + ->treatTrueLike([]) + ->treatNullLike([]) + ->prototype('variable')->end() + ->info('The parameters of the action.') + ->end() + ->end() + ->end() + ->end() + ->end() ->end() - ->append( - $this->getUrlNode( - 'offline_fallback', - 'The URL of the offline fallback. If not set, the offline fallback will be disabled.' - ) - ) ->scalarNode('scope') ->cannotBeEmpty() ->defaultValue('/') @@ -504,34 +563,6 @@ private function setupServiceWorker(ArrayNodeDefinition $node): void ->defaultTrue() ->info('Whether the service worker should use the cache.') ->end() - ->arrayNode('warm_cache_urls') - ->treatNullLike([]) - ->treatFalseLike([]) - ->treatTrueLike([]) - ->info('The URLs to warm the cache. The URLs shall be served by the application.') - ->arrayPrototype() - ->beforeNormalization() - ->ifString() - ->then(static fn (string $v): array => [ - 'path' => $v, - ]) - ->end() - ->children() - ->scalarNode('path') - ->isRequired() - ->info('The URL of the shortcut.') - ->example('app_homepage') - ->end() - ->arrayNode('params') - ->treatFalseLike([]) - ->treatTrueLike([]) - ->treatNullLike([]) - ->prototype('variable')->end() - ->info('The parameters of the action.') - ->end() - ->end() - ->end() - ->end() ->end() ->end() ->end(); diff --git a/src/Dto/ServiceWorker.php b/src/Dto/ServiceWorker.php index 3df233a..2f065cc 100644 --- a/src/Dto/ServiceWorker.php +++ b/src/Dto/ServiceWorker.php @@ -17,24 +17,5 @@ final class ServiceWorker #[SerializedName('use_cache')] public null|bool $useCache = null; - #[SerializedName('warm_cache_placeholder')] - public string $warmCachePlaceholder; - - #[SerializedName('precaching_placeholder')] - public string $precachingPlaceholder; - - #[SerializedName('offline_fallback_placeholder')] - public string $offlineFallbackPlaceholder; - - #[SerializedName('widgets_placeholder')] - public string $widgetsPlaceholder; - - #[SerializedName('offline_fallback')] - public null|Url $offlineFallback = null; - - /** - * @var array - */ - #[SerializedName('warm_cache_urls')] - public array $warmCacheUrls = []; + public Workbox $workbox; } diff --git a/src/Dto/Workbox.php b/src/Dto/Workbox.php new file mode 100644 index 0000000..fac3ed6 --- /dev/null +++ b/src/Dto/Workbox.php @@ -0,0 +1,44 @@ + + */ + #[SerializedName('warm_cache_urls')] + public array $warmCacheUrls = []; +} diff --git a/src/Resources/config/services.php b/src/Resources/config/services.php index 59de6ee..fca6870 100644 --- a/src/Resources/config/services.php +++ b/src/Resources/config/services.php @@ -14,6 +14,7 @@ use SpomkyLabs\PwaBundle\Subscriber\AssetsCompileEventListener; use SpomkyLabs\PwaBundle\Subscriber\PwaDevServerSubscriber; use SpomkyLabs\PwaBundle\Subscriber\ServiceWorkerCompileEventListener; +use SpomkyLabs\PwaBundle\Subscriber\WorkboxCompileEventListener; use SpomkyLabs\PwaBundle\Twig\PwaExtension; use SpomkyLabs\PwaBundle\Twig\PwaRuntime; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; @@ -65,6 +66,7 @@ ; } + $container->set(WorkboxCompileEventListener::class); $container->set(AssetsCompileEventListener::class); $container->set(ServiceWorkerCompileEventListener::class); $container->set(ServiceWorkerBuilder::class); diff --git a/src/Resources/workbox.js b/src/Resources/sw-skeleton.js similarity index 93% rename from src/Resources/workbox.js rename to src/Resources/sw-skeleton.js index 5fb0e5d..3cdb367 100644 --- a/src/Resources/workbox.js +++ b/src/Resources/sw-skeleton.js @@ -1,6 +1,6 @@ -importScripts( - 'https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js' -); +// *** Workbox *** +// Workbox is imported from a CDN or local files. +//WORKBOX_IMPORT_PLACEHOLDER // *** Recipes *** // You are free to change or remove any of these presets as you wish. diff --git a/src/Resources/workbox-v7.0.0/workbox-background-sync.dev.js b/src/Resources/workbox-v7.0.0/workbox-background-sync.dev.js new file mode 100644 index 0000000..086bcc6 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-background-sync.dev.js @@ -0,0 +1,1250 @@ +this.workbox = this.workbox || {}; +this.workbox.backgroundSync = (function (exports, WorkboxError_js, logger_js, assert_js, getFriendlyURL_js) { + 'use strict'; + + function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); + } + + const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c); + + let idbProxyableTypes; + let cursorAdvanceMethods; // This is a function to prevent it throwing up in node environments. + + function getIdbProxyableTypes() { + return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]); + } // This is a function to prevent it throwing up in node environments. + + + function getCursorAdvanceMethods() { + return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]); + } + + const cursorRequestMap = new WeakMap(); + const transactionDoneMap = new WeakMap(); + const transactionStoreNamesMap = new WeakMap(); + const transformCache = new WeakMap(); + const reverseTransformCache = new WeakMap(); + + function promisifyRequest(request) { + const promise = new Promise((resolve, reject) => { + const unlisten = () => { + request.removeEventListener('success', success); + request.removeEventListener('error', error); + }; + + const success = () => { + resolve(wrap(request.result)); + unlisten(); + }; + + const error = () => { + reject(request.error); + unlisten(); + }; + + request.addEventListener('success', success); + request.addEventListener('error', error); + }); + promise.then(value => { + // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval + // (see wrapFunction). + if (value instanceof IDBCursor) { + cursorRequestMap.set(value, request); + } // Catching to avoid "Uncaught Promise exceptions" + + }).catch(() => {}); // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This + // is because we create many promises from a single IDBRequest. + + reverseTransformCache.set(promise, request); + return promise; + } + + function cacheDonePromiseForTransaction(tx) { + // Early bail if we've already created a done promise for this transaction. + if (transactionDoneMap.has(tx)) return; + const done = new Promise((resolve, reject) => { + const unlisten = () => { + tx.removeEventListener('complete', complete); + tx.removeEventListener('error', error); + tx.removeEventListener('abort', error); + }; + + const complete = () => { + resolve(); + unlisten(); + }; + + const error = () => { + reject(tx.error || new DOMException('AbortError', 'AbortError')); + unlisten(); + }; + + tx.addEventListener('complete', complete); + tx.addEventListener('error', error); + tx.addEventListener('abort', error); + }); // Cache it for later retrieval. + + transactionDoneMap.set(tx, done); + } + + let idbProxyTraps = { + get(target, prop, receiver) { + if (target instanceof IDBTransaction) { + // Special handling for transaction.done. + if (prop === 'done') return transactionDoneMap.get(target); // Polyfill for objectStoreNames because of Edge. + + if (prop === 'objectStoreNames') { + return target.objectStoreNames || transactionStoreNamesMap.get(target); + } // Make tx.store return the only store in the transaction, or undefined if there are many. + + + if (prop === 'store') { + return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]); + } + } // Else transform whatever we get back. + + + return wrap(target[prop]); + }, + + set(target, prop, value) { + target[prop] = value; + return true; + }, + + has(target, prop) { + if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) { + return true; + } + + return prop in target; + } + + }; + + function replaceTraps(callback) { + idbProxyTraps = callback(idbProxyTraps); + } + + function wrapFunction(func) { + // Due to expected object equality (which is enforced by the caching in `wrap`), we + // only create one new func per func. + // Edge doesn't support objectStoreNames (booo), so we polyfill it here. + if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) { + return function (storeNames, ...args) { + const tx = func.call(unwrap(this), storeNames, ...args); + transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); + return wrap(tx); + }; + } // Cursor methods are special, as the behaviour is a little more different to standard IDB. In + // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the + // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense + // with real promises, so each advance methods returns a new promise for the cursor object, or + // undefined if the end of the cursor has been reached. + + + if (getCursorAdvanceMethods().includes(func)) { + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + func.apply(unwrap(this), args); + return wrap(cursorRequestMap.get(this)); + }; + } + + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + return wrap(func.apply(unwrap(this), args)); + }; + } + + function transformCachableValue(value) { + if (typeof value === 'function') return wrapFunction(value); // This doesn't return, it just creates a 'done' promise for the transaction, + // which is later returned for transaction.done (see idbObjectHandler). + + if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value); + if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps); // Return the same value back if we're not going to transform it. + + return value; + } + + function wrap(value) { + // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because + // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached. + if (value instanceof IDBRequest) return promisifyRequest(value); // If we've already transformed this value before, reuse the transformed value. + // This is faster, but it also provides object equality. + + if (transformCache.has(value)) return transformCache.get(value); + const newValue = transformCachableValue(value); // Not all types are transformed. + // These may be primitive types, so they can't be WeakMap keys. + + if (newValue !== value) { + transformCache.set(value, newValue); + reverseTransformCache.set(newValue, value); + } + + return newValue; + } + + const unwrap = value => reverseTransformCache.get(value); + + /** + * Open a database. + * + * @param name Name of the database. + * @param version Schema version. + * @param callbacks Additional callbacks. + */ + + function openDB(name, version, { + blocked, + upgrade, + blocking, + terminated + } = {}) { + const request = indexedDB.open(name, version); + const openPromise = wrap(request); + + if (upgrade) { + request.addEventListener('upgradeneeded', event => { + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction)); + }); + } + + if (blocked) request.addEventListener('blocked', () => blocked()); + openPromise.then(db => { + if (terminated) db.addEventListener('close', () => terminated()); + if (blocking) db.addEventListener('versionchange', () => blocking()); + }).catch(() => {}); + return openPromise; + } + + const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; + const writeMethods = ['put', 'add', 'delete', 'clear']; + const cachedMethods = new Map(); + + function getMethod(target, prop) { + if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) { + return; + } + + if (cachedMethods.get(prop)) return cachedMethods.get(prop); + const targetFuncName = prop.replace(/FromIndex$/, ''); + const useIndex = prop !== targetFuncName; + const isWrite = writeMethods.includes(targetFuncName); + + if ( // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. + !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) { + return; + } + + const method = async function (storeName, ...args) { + // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :( + const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly'); + let target = tx.store; + if (useIndex) target = target.index(args.shift()); // Must reject if op rejects. + // If it's a write operation, must reject if tx.done rejects. + // Must reject with op rejection first. + // Must resolve with op value. + // Must handle both promises (no unhandled rejections) + + return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0]; + }; + + cachedMethods.set(prop, method); + return method; + } + + replaceTraps(oldTraps => _extends({}, oldTraps, { + get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), + has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop) + })); + + try { + self['workbox:background-sync:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2021 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const DB_VERSION = 3; + const DB_NAME = 'workbox-background-sync'; + const REQUEST_OBJECT_STORE_NAME = 'requests'; + const QUEUE_NAME_INDEX = 'queueName'; + /** + * A class to interact directly an IndexedDB created specifically to save and + * retrieve QueueStoreEntries. This class encapsulates all the schema details + * to store the representation of a Queue. + * + * @private + */ + + class QueueDb { + constructor() { + this._db = null; + } + /** + * Add QueueStoreEntry to underlying db. + * + * @param {UnidentifiedQueueStoreEntry} entry + */ + + + async addEntry(entry) { + const db = await this.getDb(); + const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, 'readwrite', { + durability: 'relaxed' + }); + await tx.store.add(entry); + await tx.done; + } + /** + * Returns the first entry id in the ObjectStore. + * + * @return {number | undefined} + */ + + + async getFirstEntryId() { + const db = await this.getDb(); + const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.openCursor(); + return cursor === null || cursor === void 0 ? void 0 : cursor.value.id; + } + /** + * Get all the entries filtered by index + * + * @param queueName + * @return {Promise} + */ + + + async getAllEntriesByQueueName(queueName) { + const db = await this.getDb(); + const results = await db.getAllFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName)); + return results ? results : new Array(); + } + /** + * Returns the number of entries filtered by index + * + * @param queueName + * @return {Promise} + */ + + + async getEntryCountByQueueName(queueName) { + const db = await this.getDb(); + return db.countFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName)); + } + /** + * Deletes a single entry by id. + * + * @param {number} id the id of the entry to be deleted + */ + + + async deleteEntry(id) { + const db = await this.getDb(); + await db.delete(REQUEST_OBJECT_STORE_NAME, id); + } + /** + * + * @param queueName + * @returns {Promise} + */ + + + async getFirstEntryByQueueName(queueName) { + return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'next'); + } + /** + * + * @param queueName + * @returns {Promise} + */ + + + async getLastEntryByQueueName(queueName) { + return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'prev'); + } + /** + * Returns either the first or the last entries, depending on direction. + * Filtered by index. + * + * @param {IDBCursorDirection} direction + * @param {IDBKeyRange} query + * @return {Promise} + * @private + */ + + + async getEndEntryFromIndex(query, direction) { + const db = await this.getDb(); + const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.index(QUEUE_NAME_INDEX).openCursor(query, direction); + return cursor === null || cursor === void 0 ? void 0 : cursor.value; + } + /** + * Returns an open connection to the database. + * + * @private + */ + + + async getDb() { + if (!this._db) { + this._db = await openDB(DB_NAME, DB_VERSION, { + upgrade: this._upgradeDb + }); + } + + return this._db; + } + /** + * Upgrades QueueDB + * + * @param {IDBPDatabase} db + * @param {number} oldVersion + * @private + */ + + + _upgradeDb(db, oldVersion) { + if (oldVersion > 0 && oldVersion < DB_VERSION) { + if (db.objectStoreNames.contains(REQUEST_OBJECT_STORE_NAME)) { + db.deleteObjectStore(REQUEST_OBJECT_STORE_NAME); + } + } + + const objStore = db.createObjectStore(REQUEST_OBJECT_STORE_NAME, { + autoIncrement: true, + keyPath: 'id' + }); + objStore.createIndex(QUEUE_NAME_INDEX, QUEUE_NAME_INDEX, { + unique: false + }); + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A class to manage storing requests from a Queue in IndexedDB, + * indexed by their queue name for easier access. + * + * Most developers will not need to access this class directly; + * it is exposed for advanced use cases. + */ + + class QueueStore { + /** + * Associates this instance with a Queue instance, so entries added can be + * identified by their queue name. + * + * @param {string} queueName + */ + constructor(queueName) { + this._queueName = queueName; + this._queueDb = new QueueDb(); + } + /** + * Append an entry last in the queue. + * + * @param {Object} entry + * @param {Object} entry.requestData + * @param {number} [entry.timestamp] + * @param {Object} [entry.metadata] + */ + + + async pushEntry(entry) { + { + assert_js.assert.isType(entry, 'object', { + moduleName: 'workbox-background-sync', + className: 'QueueStore', + funcName: 'pushEntry', + paramName: 'entry' + }); + assert_js.assert.isType(entry.requestData, 'object', { + moduleName: 'workbox-background-sync', + className: 'QueueStore', + funcName: 'pushEntry', + paramName: 'entry.requestData' + }); + } // Don't specify an ID since one is automatically generated. + + + delete entry.id; + entry.queueName = this._queueName; + await this._queueDb.addEntry(entry); + } + /** + * Prepend an entry first in the queue. + * + * @param {Object} entry + * @param {Object} entry.requestData + * @param {number} [entry.timestamp] + * @param {Object} [entry.metadata] + */ + + + async unshiftEntry(entry) { + { + assert_js.assert.isType(entry, 'object', { + moduleName: 'workbox-background-sync', + className: 'QueueStore', + funcName: 'unshiftEntry', + paramName: 'entry' + }); + assert_js.assert.isType(entry.requestData, 'object', { + moduleName: 'workbox-background-sync', + className: 'QueueStore', + funcName: 'unshiftEntry', + paramName: 'entry.requestData' + }); + } + + const firstId = await this._queueDb.getFirstEntryId(); + + if (firstId) { + // Pick an ID one less than the lowest ID in the object store. + entry.id = firstId - 1; + } else { + // Otherwise let the auto-incrementor assign the ID. + delete entry.id; + } + + entry.queueName = this._queueName; + await this._queueDb.addEntry(entry); + } + /** + * Removes and returns the last entry in the queue matching the `queueName`. + * + * @return {Promise} + */ + + + async popEntry() { + return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName)); + } + /** + * Removes and returns the first entry in the queue matching the `queueName`. + * + * @return {Promise} + */ + + + async shiftEntry() { + return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName)); + } + /** + * Returns all entries in the store matching the `queueName`. + * + * @param {Object} options See {@link workbox-background-sync.Queue~getAll} + * @return {Promise>} + */ + + + async getAll() { + return await this._queueDb.getAllEntriesByQueueName(this._queueName); + } + /** + * Returns the number of entries in the store matching the `queueName`. + * + * @param {Object} options See {@link workbox-background-sync.Queue~size} + * @return {Promise} + */ + + + async size() { + return await this._queueDb.getEntryCountByQueueName(this._queueName); + } + /** + * Deletes the entry for the given ID. + * + * WARNING: this method does not ensure the deleted entry belongs to this + * queue (i.e. matches the `queueName`). But this limitation is acceptable + * as this class is not publicly exposed. An additional check would make + * this method slower than it needs to be. + * + * @param {number} id + */ + + + async deleteEntry(id) { + await this._queueDb.deleteEntry(id); + } + /** + * Removes and returns the first or last entry in the queue (based on the + * `direction` argument) matching the `queueName`. + * + * @return {Promise} + * @private + */ + + + async _removeEntry(entry) { + if (entry) { + await this.deleteEntry(entry.id); + } + + return entry; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const serializableProperties = ['method', 'referrer', 'referrerPolicy', 'mode', 'credentials', 'cache', 'redirect', 'integrity', 'keepalive']; + /** + * A class to make it easier to serialize and de-serialize requests so they + * can be stored in IndexedDB. + * + * Most developers will not need to access this class directly; + * it is exposed for advanced use cases. + */ + + class StorableRequest { + /** + * Converts a Request object to a plain object that can be structured + * cloned or JSON-stringified. + * + * @param {Request} request + * @return {Promise} + */ + static async fromRequest(request) { + const requestData = { + url: request.url, + headers: {} + }; // Set the body if present. + + if (request.method !== 'GET') { + // Use ArrayBuffer to support non-text request bodies. + // NOTE: we can't use Blobs becuse Safari doesn't support storing + // Blobs in IndexedDB in some cases: + // https://github.com/dfahlander/Dexie.js/issues/618#issuecomment-398348457 + requestData.body = await request.clone().arrayBuffer(); + } // Convert the headers from an iterable to an object. + + + for (const [key, value] of request.headers.entries()) { + requestData.headers[key] = value; + } // Add all other serializable request properties + + + for (const prop of serializableProperties) { + if (request[prop] !== undefined) { + requestData[prop] = request[prop]; + } + } + + return new StorableRequest(requestData); + } + /** + * Accepts an object of request data that can be used to construct a + * `Request` but can also be stored in IndexedDB. + * + * @param {Object} requestData An object of request data that includes the + * `url` plus any relevant properties of + * [requestInit]{@link https://fetch.spec.whatwg.org/#requestinit}. + */ + + + constructor(requestData) { + { + assert_js.assert.isType(requestData, 'object', { + moduleName: 'workbox-background-sync', + className: 'StorableRequest', + funcName: 'constructor', + paramName: 'requestData' + }); + assert_js.assert.isType(requestData.url, 'string', { + moduleName: 'workbox-background-sync', + className: 'StorableRequest', + funcName: 'constructor', + paramName: 'requestData.url' + }); + } // If the request's mode is `navigate`, convert it to `same-origin` since + // navigation requests can't be constructed via script. + + + if (requestData['mode'] === 'navigate') { + requestData['mode'] = 'same-origin'; + } + + this._requestData = requestData; + } + /** + * Returns a deep clone of the instances `_requestData` object. + * + * @return {Object} + */ + + + toObject() { + const requestData = Object.assign({}, this._requestData); + requestData.headers = Object.assign({}, this._requestData.headers); + + if (requestData.body) { + requestData.body = requestData.body.slice(0); + } + + return requestData; + } + /** + * Converts this instance to a Request. + * + * @return {Request} + */ + + + toRequest() { + return new Request(this._requestData.url, this._requestData); + } + /** + * Creates and returns a deep clone of the instance. + * + * @return {StorableRequest} + */ + + + clone() { + return new StorableRequest(this.toObject()); + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const TAG_PREFIX = 'workbox-background-sync'; + const MAX_RETENTION_TIME = 60 * 24 * 7; // 7 days in minutes + + const queueNames = new Set(); + /** + * Converts a QueueStore entry into the format exposed by Queue. This entails + * converting the request data into a real request and omitting the `id` and + * `queueName` properties. + * + * @param {UnidentifiedQueueStoreEntry} queueStoreEntry + * @return {Queue} + * @private + */ + + const convertEntry = queueStoreEntry => { + const queueEntry = { + request: new StorableRequest(queueStoreEntry.requestData).toRequest(), + timestamp: queueStoreEntry.timestamp + }; + + if (queueStoreEntry.metadata) { + queueEntry.metadata = queueStoreEntry.metadata; + } + + return queueEntry; + }; + /** + * A class to manage storing failed requests in IndexedDB and retrying them + * later. All parts of the storing and replaying process are observable via + * callbacks. + * + * @memberof workbox-background-sync + */ + + + class Queue { + /** + * Creates an instance of Queue with the given options + * + * @param {string} name The unique name for this queue. This name must be + * unique as it's used to register sync events and store requests + * in IndexedDB specific to this instance. An error will be thrown if + * a duplicate name is detected. + * @param {Object} [options] + * @param {Function} [options.onSync] A function that gets invoked whenever + * the 'sync' event fires. The function is invoked with an object + * containing the `queue` property (referencing this instance), and you + * can use the callback to customize the replay behavior of the queue. + * When not set the `replayRequests()` method is called. + * Note: if the replay fails after a sync event, make sure you throw an + * error, so the browser knows to retry the sync event later. + * @param {number} [options.maxRetentionTime=7 days] The amount of time (in + * minutes) a request may be retried. After this amount of time has + * passed, the request will be deleted from the queue. + * @param {boolean} [options.forceSyncFallback=false] If `true`, instead + * of attempting to use background sync events, always attempt to replay + * queued request at service worker startup. Most folks will not need + * this, unless you explicitly target a runtime like Electron that + * exposes the interfaces for background sync, but does not have a working + * implementation. + */ + constructor(name, { + forceSyncFallback, + onSync, + maxRetentionTime + } = {}) { + this._syncInProgress = false; + this._requestsAddedDuringSync = false; // Ensure the store name is not already being used + + if (queueNames.has(name)) { + throw new WorkboxError_js.WorkboxError('duplicate-queue-name', { + name + }); + } else { + queueNames.add(name); + } + + this._name = name; + this._onSync = onSync || this.replayRequests; + this._maxRetentionTime = maxRetentionTime || MAX_RETENTION_TIME; + this._forceSyncFallback = Boolean(forceSyncFallback); + this._queueStore = new QueueStore(this._name); + + this._addSyncListener(); + } + /** + * @return {string} + */ + + + get name() { + return this._name; + } + /** + * Stores the passed request in IndexedDB (with its timestamp and any + * metadata) at the end of the queue. + * + * @param {QueueEntry} entry + * @param {Request} entry.request The request to store in the queue. + * @param {Object} [entry.metadata] Any metadata you want associated with the + * stored request. When requests are replayed you'll have access to this + * metadata object in case you need to modify the request beforehand. + * @param {number} [entry.timestamp] The timestamp (Epoch time in + * milliseconds) when the request was first added to the queue. This is + * used along with `maxRetentionTime` to remove outdated requests. In + * general you don't need to set this value, as it's automatically set + * for you (defaulting to `Date.now()`), but you can update it if you + * don't want particular requests to expire. + */ + + + async pushRequest(entry) { + { + assert_js.assert.isType(entry, 'object', { + moduleName: 'workbox-background-sync', + className: 'Queue', + funcName: 'pushRequest', + paramName: 'entry' + }); + assert_js.assert.isInstance(entry.request, Request, { + moduleName: 'workbox-background-sync', + className: 'Queue', + funcName: 'pushRequest', + paramName: 'entry.request' + }); + } + + await this._addRequest(entry, 'push'); + } + /** + * Stores the passed request in IndexedDB (with its timestamp and any + * metadata) at the beginning of the queue. + * + * @param {QueueEntry} entry + * @param {Request} entry.request The request to store in the queue. + * @param {Object} [entry.metadata] Any metadata you want associated with the + * stored request. When requests are replayed you'll have access to this + * metadata object in case you need to modify the request beforehand. + * @param {number} [entry.timestamp] The timestamp (Epoch time in + * milliseconds) when the request was first added to the queue. This is + * used along with `maxRetentionTime` to remove outdated requests. In + * general you don't need to set this value, as it's automatically set + * for you (defaulting to `Date.now()`), but you can update it if you + * don't want particular requests to expire. + */ + + + async unshiftRequest(entry) { + { + assert_js.assert.isType(entry, 'object', { + moduleName: 'workbox-background-sync', + className: 'Queue', + funcName: 'unshiftRequest', + paramName: 'entry' + }); + assert_js.assert.isInstance(entry.request, Request, { + moduleName: 'workbox-background-sync', + className: 'Queue', + funcName: 'unshiftRequest', + paramName: 'entry.request' + }); + } + + await this._addRequest(entry, 'unshift'); + } + /** + * Removes and returns the last request in the queue (along with its + * timestamp and any metadata). The returned object takes the form: + * `{request, timestamp, metadata}`. + * + * @return {Promise} + */ + + + async popRequest() { + return this._removeRequest('pop'); + } + /** + * Removes and returns the first request in the queue (along with its + * timestamp and any metadata). The returned object takes the form: + * `{request, timestamp, metadata}`. + * + * @return {Promise} + */ + + + async shiftRequest() { + return this._removeRequest('shift'); + } + /** + * Returns all the entries that have not expired (per `maxRetentionTime`). + * Any expired entries are removed from the queue. + * + * @return {Promise>} + */ + + + async getAll() { + const allEntries = await this._queueStore.getAll(); + const now = Date.now(); + const unexpiredEntries = []; + + for (const entry of allEntries) { + // Ignore requests older than maxRetentionTime. Call this function + // recursively until an unexpired request is found. + const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000; + + if (now - entry.timestamp > maxRetentionTimeInMs) { + await this._queueStore.deleteEntry(entry.id); + } else { + unexpiredEntries.push(convertEntry(entry)); + } + } + + return unexpiredEntries; + } + /** + * Returns the number of entries present in the queue. + * Note that expired entries (per `maxRetentionTime`) are also included in this count. + * + * @return {Promise} + */ + + + async size() { + return await this._queueStore.size(); + } + /** + * Adds the entry to the QueueStore and registers for a sync event. + * + * @param {Object} entry + * @param {Request} entry.request + * @param {Object} [entry.metadata] + * @param {number} [entry.timestamp=Date.now()] + * @param {string} operation ('push' or 'unshift') + * @private + */ + + + async _addRequest({ + request, + metadata, + timestamp = Date.now() + }, operation) { + const storableRequest = await StorableRequest.fromRequest(request.clone()); + const entry = { + requestData: storableRequest.toObject(), + timestamp + }; // Only include metadata if it's present. + + if (metadata) { + entry.metadata = metadata; + } + + switch (operation) { + case 'push': + await this._queueStore.pushEntry(entry); + break; + + case 'unshift': + await this._queueStore.unshiftEntry(entry); + break; + } + + { + logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(request.url)}' has ` + `been added to background sync queue '${this._name}'.`); + } // Don't register for a sync if we're in the middle of a sync. Instead, + // we wait until the sync is complete and call register if + // `this._requestsAddedDuringSync` is true. + + + if (this._syncInProgress) { + this._requestsAddedDuringSync = true; + } else { + await this.registerSync(); + } + } + /** + * Removes and returns the first or last (depending on `operation`) entry + * from the QueueStore that's not older than the `maxRetentionTime`. + * + * @param {string} operation ('pop' or 'shift') + * @return {Object|undefined} + * @private + */ + + + async _removeRequest(operation) { + const now = Date.now(); + let entry; + + switch (operation) { + case 'pop': + entry = await this._queueStore.popEntry(); + break; + + case 'shift': + entry = await this._queueStore.shiftEntry(); + break; + } + + if (entry) { + // Ignore requests older than maxRetentionTime. Call this function + // recursively until an unexpired request is found. + const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000; + + if (now - entry.timestamp > maxRetentionTimeInMs) { + return this._removeRequest(operation); + } + + return convertEntry(entry); + } else { + return undefined; + } + } + /** + * Loops through each request in the queue and attempts to re-fetch it. + * If any request fails to re-fetch, it's put back in the same position in + * the queue (which registers a retry for the next sync event). + */ + + + async replayRequests() { + let entry; + + while (entry = await this.shiftRequest()) { + try { + await fetch(entry.request.clone()); + + if ("dev" !== 'production') { + logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(entry.request.url)}' ` + `has been replayed in queue '${this._name}'`); + } + } catch (error) { + await this.unshiftRequest(entry); + + { + logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(entry.request.url)}' ` + `failed to replay, putting it back in queue '${this._name}'`); + } + + throw new WorkboxError_js.WorkboxError('queue-replay-failed', { + name: this._name + }); + } + } + + { + logger_js.logger.log(`All requests in queue '${this.name}' have successfully ` + `replayed; the queue is now empty!`); + } + } + /** + * Registers a sync event with a tag unique to this instance. + */ + + + async registerSync() { + // See https://github.com/GoogleChrome/workbox/issues/2393 + if ('sync' in self.registration && !this._forceSyncFallback) { + try { + await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`); + } catch (err) { + // This means the registration failed for some reason, possibly due to + // the user disabling it. + { + logger_js.logger.warn(`Unable to register sync event for '${this._name}'.`, err); + } + } + } + } + /** + * In sync-supporting browsers, this adds a listener for the sync event. + * In non-sync-supporting browsers, or if _forceSyncFallback is true, this + * will retry the queue on service worker startup. + * + * @private + */ + + + _addSyncListener() { + // See https://github.com/GoogleChrome/workbox/issues/2393 + if ('sync' in self.registration && !this._forceSyncFallback) { + self.addEventListener('sync', event => { + if (event.tag === `${TAG_PREFIX}:${this._name}`) { + { + logger_js.logger.log(`Background sync for tag '${event.tag}' ` + `has been received`); + } + + const syncComplete = async () => { + this._syncInProgress = true; + let syncError; + + try { + await this._onSync({ + queue: this + }); + } catch (error) { + if (error instanceof Error) { + syncError = error; // Rethrow the error. Note: the logic in the finally clause + // will run before this gets rethrown. + + throw syncError; + } + } finally { + // New items may have been added to the queue during the sync, + // so we need to register for a new sync if that's happened... + // Unless there was an error during the sync, in which + // case the browser will automatically retry later, as long + // as `event.lastChance` is not true. + if (this._requestsAddedDuringSync && !(syncError && !event.lastChance)) { + await this.registerSync(); + } + + this._syncInProgress = false; + this._requestsAddedDuringSync = false; + } + }; + + event.waitUntil(syncComplete()); + } + }); + } else { + { + logger_js.logger.log(`Background sync replaying without background sync event`); + } // If the browser doesn't support background sync, or the developer has + // opted-in to not using it, retry every time the service worker starts up + // as a fallback. + + + void this._onSync({ + queue: this + }); + } + } + /** + * Returns the set of queue names. This is primarily used to reset the list + * of queue names in tests. + * + * @return {Set} + * + * @private + */ + + + static get _queueNames() { + return queueNames; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A class implementing the `fetchDidFail` lifecycle callback. This makes it + * easier to add failed requests to a background sync Queue. + * + * @memberof workbox-background-sync + */ + + class BackgroundSyncPlugin { + /** + * @param {string} name See the {@link workbox-background-sync.Queue} + * documentation for parameter details. + * @param {Object} [options] See the + * {@link workbox-background-sync.Queue} documentation for + * parameter details. + */ + constructor(name, options) { + /** + * @param {Object} options + * @param {Request} options.request + * @private + */ + this.fetchDidFail = async ({ + request + }) => { + await this._queue.pushRequest({ + request + }); + }; + + this._queue = new Queue(name, options); + } + + } + + exports.BackgroundSyncPlugin = BackgroundSyncPlugin; + exports.Queue = Queue; + exports.QueueStore = QueueStore; + exports.StorableRequest = StorableRequest; + + return exports; + +}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private)); +//# sourceMappingURL=workbox-background-sync.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-background-sync.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-background-sync.dev.js.map new file mode 100644 index 0000000..6bd6db0 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-background-sync.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-background-sync.dev.js","sources":["../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../_version.js","../lib/QueueDb.js","../lib/QueueStore.js","../lib/StorableRequest.js","../Queue.js","../BackgroundSyncPlugin.js"],"sourcesContent":["const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:background-sync:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2021 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { openDB } from 'idb';\nimport '../_version.js';\nconst DB_VERSION = 3;\nconst DB_NAME = 'workbox-background-sync';\nconst REQUEST_OBJECT_STORE_NAME = 'requests';\nconst QUEUE_NAME_INDEX = 'queueName';\n/**\n * A class to interact directly an IndexedDB created specifically to save and\n * retrieve QueueStoreEntries. This class encapsulates all the schema details\n * to store the representation of a Queue.\n *\n * @private\n */\nexport class QueueDb {\n constructor() {\n this._db = null;\n }\n /**\n * Add QueueStoreEntry to underlying db.\n *\n * @param {UnidentifiedQueueStoreEntry} entry\n */\n async addEntry(entry) {\n const db = await this.getDb();\n const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, 'readwrite', {\n durability: 'relaxed',\n });\n await tx.store.add(entry);\n await tx.done;\n }\n /**\n * Returns the first entry id in the ObjectStore.\n *\n * @return {number | undefined}\n */\n async getFirstEntryId() {\n const db = await this.getDb();\n const cursor = await db\n .transaction(REQUEST_OBJECT_STORE_NAME)\n .store.openCursor();\n return cursor === null || cursor === void 0 ? void 0 : cursor.value.id;\n }\n /**\n * Get all the entries filtered by index\n *\n * @param queueName\n * @return {Promise}\n */\n async getAllEntriesByQueueName(queueName) {\n const db = await this.getDb();\n const results = await db.getAllFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));\n return results ? results : new Array();\n }\n /**\n * Returns the number of entries filtered by index\n *\n * @param queueName\n * @return {Promise}\n */\n async getEntryCountByQueueName(queueName) {\n const db = await this.getDb();\n return db.countFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));\n }\n /**\n * Deletes a single entry by id.\n *\n * @param {number} id the id of the entry to be deleted\n */\n async deleteEntry(id) {\n const db = await this.getDb();\n await db.delete(REQUEST_OBJECT_STORE_NAME, id);\n }\n /**\n *\n * @param queueName\n * @returns {Promise}\n */\n async getFirstEntryByQueueName(queueName) {\n return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'next');\n }\n /**\n *\n * @param queueName\n * @returns {Promise}\n */\n async getLastEntryByQueueName(queueName) {\n return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'prev');\n }\n /**\n * Returns either the first or the last entries, depending on direction.\n * Filtered by index.\n *\n * @param {IDBCursorDirection} direction\n * @param {IDBKeyRange} query\n * @return {Promise}\n * @private\n */\n async getEndEntryFromIndex(query, direction) {\n const db = await this.getDb();\n const cursor = await db\n .transaction(REQUEST_OBJECT_STORE_NAME)\n .store.index(QUEUE_NAME_INDEX)\n .openCursor(query, direction);\n return cursor === null || cursor === void 0 ? void 0 : cursor.value;\n }\n /**\n * Returns an open connection to the database.\n *\n * @private\n */\n async getDb() {\n if (!this._db) {\n this._db = await openDB(DB_NAME, DB_VERSION, {\n upgrade: this._upgradeDb,\n });\n }\n return this._db;\n }\n /**\n * Upgrades QueueDB\n *\n * @param {IDBPDatabase} db\n * @param {number} oldVersion\n * @private\n */\n _upgradeDb(db, oldVersion) {\n if (oldVersion > 0 && oldVersion < DB_VERSION) {\n if (db.objectStoreNames.contains(REQUEST_OBJECT_STORE_NAME)) {\n db.deleteObjectStore(REQUEST_OBJECT_STORE_NAME);\n }\n }\n const objStore = db.createObjectStore(REQUEST_OBJECT_STORE_NAME, {\n autoIncrement: true,\n keyPath: 'id',\n });\n objStore.createIndex(QUEUE_NAME_INDEX, QUEUE_NAME_INDEX, { unique: false });\n }\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { QueueDb, } from './QueueDb.js';\nimport '../_version.js';\n/**\n * A class to manage storing requests from a Queue in IndexedDB,\n * indexed by their queue name for easier access.\n *\n * Most developers will not need to access this class directly;\n * it is exposed for advanced use cases.\n */\nexport class QueueStore {\n /**\n * Associates this instance with a Queue instance, so entries added can be\n * identified by their queue name.\n *\n * @param {string} queueName\n */\n constructor(queueName) {\n this._queueName = queueName;\n this._queueDb = new QueueDb();\n }\n /**\n * Append an entry last in the queue.\n *\n * @param {Object} entry\n * @param {Object} entry.requestData\n * @param {number} [entry.timestamp]\n * @param {Object} [entry.metadata]\n */\n async pushEntry(entry) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(entry, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'QueueStore',\n funcName: 'pushEntry',\n paramName: 'entry',\n });\n assert.isType(entry.requestData, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'QueueStore',\n funcName: 'pushEntry',\n paramName: 'entry.requestData',\n });\n }\n // Don't specify an ID since one is automatically generated.\n delete entry.id;\n entry.queueName = this._queueName;\n await this._queueDb.addEntry(entry);\n }\n /**\n * Prepend an entry first in the queue.\n *\n * @param {Object} entry\n * @param {Object} entry.requestData\n * @param {number} [entry.timestamp]\n * @param {Object} [entry.metadata]\n */\n async unshiftEntry(entry) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(entry, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'QueueStore',\n funcName: 'unshiftEntry',\n paramName: 'entry',\n });\n assert.isType(entry.requestData, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'QueueStore',\n funcName: 'unshiftEntry',\n paramName: 'entry.requestData',\n });\n }\n const firstId = await this._queueDb.getFirstEntryId();\n if (firstId) {\n // Pick an ID one less than the lowest ID in the object store.\n entry.id = firstId - 1;\n }\n else {\n // Otherwise let the auto-incrementor assign the ID.\n delete entry.id;\n }\n entry.queueName = this._queueName;\n await this._queueDb.addEntry(entry);\n }\n /**\n * Removes and returns the last entry in the queue matching the `queueName`.\n *\n * @return {Promise}\n */\n async popEntry() {\n return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));\n }\n /**\n * Removes and returns the first entry in the queue matching the `queueName`.\n *\n * @return {Promise}\n */\n async shiftEntry() {\n return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));\n }\n /**\n * Returns all entries in the store matching the `queueName`.\n *\n * @param {Object} options See {@link workbox-background-sync.Queue~getAll}\n * @return {Promise>}\n */\n async getAll() {\n return await this._queueDb.getAllEntriesByQueueName(this._queueName);\n }\n /**\n * Returns the number of entries in the store matching the `queueName`.\n *\n * @param {Object} options See {@link workbox-background-sync.Queue~size}\n * @return {Promise}\n */\n async size() {\n return await this._queueDb.getEntryCountByQueueName(this._queueName);\n }\n /**\n * Deletes the entry for the given ID.\n *\n * WARNING: this method does not ensure the deleted entry belongs to this\n * queue (i.e. matches the `queueName`). But this limitation is acceptable\n * as this class is not publicly exposed. An additional check would make\n * this method slower than it needs to be.\n *\n * @param {number} id\n */\n async deleteEntry(id) {\n await this._queueDb.deleteEntry(id);\n }\n /**\n * Removes and returns the first or last entry in the queue (based on the\n * `direction` argument) matching the `queueName`.\n *\n * @return {Promise}\n * @private\n */\n async _removeEntry(entry) {\n if (entry) {\n await this.deleteEntry(entry.id);\n }\n return entry;\n }\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\nconst serializableProperties = [\n 'method',\n 'referrer',\n 'referrerPolicy',\n 'mode',\n 'credentials',\n 'cache',\n 'redirect',\n 'integrity',\n 'keepalive',\n];\n/**\n * A class to make it easier to serialize and de-serialize requests so they\n * can be stored in IndexedDB.\n *\n * Most developers will not need to access this class directly;\n * it is exposed for advanced use cases.\n */\nclass StorableRequest {\n /**\n * Converts a Request object to a plain object that can be structured\n * cloned or JSON-stringified.\n *\n * @param {Request} request\n * @return {Promise}\n */\n static async fromRequest(request) {\n const requestData = {\n url: request.url,\n headers: {},\n };\n // Set the body if present.\n if (request.method !== 'GET') {\n // Use ArrayBuffer to support non-text request bodies.\n // NOTE: we can't use Blobs becuse Safari doesn't support storing\n // Blobs in IndexedDB in some cases:\n // https://github.com/dfahlander/Dexie.js/issues/618#issuecomment-398348457\n requestData.body = await request.clone().arrayBuffer();\n }\n // Convert the headers from an iterable to an object.\n for (const [key, value] of request.headers.entries()) {\n requestData.headers[key] = value;\n }\n // Add all other serializable request properties\n for (const prop of serializableProperties) {\n if (request[prop] !== undefined) {\n requestData[prop] = request[prop];\n }\n }\n return new StorableRequest(requestData);\n }\n /**\n * Accepts an object of request data that can be used to construct a\n * `Request` but can also be stored in IndexedDB.\n *\n * @param {Object} requestData An object of request data that includes the\n * `url` plus any relevant properties of\n * [requestInit]{@link https://fetch.spec.whatwg.org/#requestinit}.\n */\n constructor(requestData) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(requestData, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'StorableRequest',\n funcName: 'constructor',\n paramName: 'requestData',\n });\n assert.isType(requestData.url, 'string', {\n moduleName: 'workbox-background-sync',\n className: 'StorableRequest',\n funcName: 'constructor',\n paramName: 'requestData.url',\n });\n }\n // If the request's mode is `navigate`, convert it to `same-origin` since\n // navigation requests can't be constructed via script.\n if (requestData['mode'] === 'navigate') {\n requestData['mode'] = 'same-origin';\n }\n this._requestData = requestData;\n }\n /**\n * Returns a deep clone of the instances `_requestData` object.\n *\n * @return {Object}\n */\n toObject() {\n const requestData = Object.assign({}, this._requestData);\n requestData.headers = Object.assign({}, this._requestData.headers);\n if (requestData.body) {\n requestData.body = requestData.body.slice(0);\n }\n return requestData;\n }\n /**\n * Converts this instance to a Request.\n *\n * @return {Request}\n */\n toRequest() {\n return new Request(this._requestData.url, this._requestData);\n }\n /**\n * Creates and returns a deep clone of the instance.\n *\n * @return {StorableRequest}\n */\n clone() {\n return new StorableRequest(this.toObject());\n }\n}\nexport { StorableRequest };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { QueueStore } from './lib/QueueStore.js';\nimport { StorableRequest } from './lib/StorableRequest.js';\nimport './_version.js';\nconst TAG_PREFIX = 'workbox-background-sync';\nconst MAX_RETENTION_TIME = 60 * 24 * 7; // 7 days in minutes\nconst queueNames = new Set();\n/**\n * Converts a QueueStore entry into the format exposed by Queue. This entails\n * converting the request data into a real request and omitting the `id` and\n * `queueName` properties.\n *\n * @param {UnidentifiedQueueStoreEntry} queueStoreEntry\n * @return {Queue}\n * @private\n */\nconst convertEntry = (queueStoreEntry) => {\n const queueEntry = {\n request: new StorableRequest(queueStoreEntry.requestData).toRequest(),\n timestamp: queueStoreEntry.timestamp,\n };\n if (queueStoreEntry.metadata) {\n queueEntry.metadata = queueStoreEntry.metadata;\n }\n return queueEntry;\n};\n/**\n * A class to manage storing failed requests in IndexedDB and retrying them\n * later. All parts of the storing and replaying process are observable via\n * callbacks.\n *\n * @memberof workbox-background-sync\n */\nclass Queue {\n /**\n * Creates an instance of Queue with the given options\n *\n * @param {string} name The unique name for this queue. This name must be\n * unique as it's used to register sync events and store requests\n * in IndexedDB specific to this instance. An error will be thrown if\n * a duplicate name is detected.\n * @param {Object} [options]\n * @param {Function} [options.onSync] A function that gets invoked whenever\n * the 'sync' event fires. The function is invoked with an object\n * containing the `queue` property (referencing this instance), and you\n * can use the callback to customize the replay behavior of the queue.\n * When not set the `replayRequests()` method is called.\n * Note: if the replay fails after a sync event, make sure you throw an\n * error, so the browser knows to retry the sync event later.\n * @param {number} [options.maxRetentionTime=7 days] The amount of time (in\n * minutes) a request may be retried. After this amount of time has\n * passed, the request will be deleted from the queue.\n * @param {boolean} [options.forceSyncFallback=false] If `true`, instead\n * of attempting to use background sync events, always attempt to replay\n * queued request at service worker startup. Most folks will not need\n * this, unless you explicitly target a runtime like Electron that\n * exposes the interfaces for background sync, but does not have a working\n * implementation.\n */\n constructor(name, { forceSyncFallback, onSync, maxRetentionTime } = {}) {\n this._syncInProgress = false;\n this._requestsAddedDuringSync = false;\n // Ensure the store name is not already being used\n if (queueNames.has(name)) {\n throw new WorkboxError('duplicate-queue-name', { name });\n }\n else {\n queueNames.add(name);\n }\n this._name = name;\n this._onSync = onSync || this.replayRequests;\n this._maxRetentionTime = maxRetentionTime || MAX_RETENTION_TIME;\n this._forceSyncFallback = Boolean(forceSyncFallback);\n this._queueStore = new QueueStore(this._name);\n this._addSyncListener();\n }\n /**\n * @return {string}\n */\n get name() {\n return this._name;\n }\n /**\n * Stores the passed request in IndexedDB (with its timestamp and any\n * metadata) at the end of the queue.\n *\n * @param {QueueEntry} entry\n * @param {Request} entry.request The request to store in the queue.\n * @param {Object} [entry.metadata] Any metadata you want associated with the\n * stored request. When requests are replayed you'll have access to this\n * metadata object in case you need to modify the request beforehand.\n * @param {number} [entry.timestamp] The timestamp (Epoch time in\n * milliseconds) when the request was first added to the queue. This is\n * used along with `maxRetentionTime` to remove outdated requests. In\n * general you don't need to set this value, as it's automatically set\n * for you (defaulting to `Date.now()`), but you can update it if you\n * don't want particular requests to expire.\n */\n async pushRequest(entry) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(entry, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'pushRequest',\n paramName: 'entry',\n });\n assert.isInstance(entry.request, Request, {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'pushRequest',\n paramName: 'entry.request',\n });\n }\n await this._addRequest(entry, 'push');\n }\n /**\n * Stores the passed request in IndexedDB (with its timestamp and any\n * metadata) at the beginning of the queue.\n *\n * @param {QueueEntry} entry\n * @param {Request} entry.request The request to store in the queue.\n * @param {Object} [entry.metadata] Any metadata you want associated with the\n * stored request. When requests are replayed you'll have access to this\n * metadata object in case you need to modify the request beforehand.\n * @param {number} [entry.timestamp] The timestamp (Epoch time in\n * milliseconds) when the request was first added to the queue. This is\n * used along with `maxRetentionTime` to remove outdated requests. In\n * general you don't need to set this value, as it's automatically set\n * for you (defaulting to `Date.now()`), but you can update it if you\n * don't want particular requests to expire.\n */\n async unshiftRequest(entry) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(entry, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'unshiftRequest',\n paramName: 'entry',\n });\n assert.isInstance(entry.request, Request, {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'unshiftRequest',\n paramName: 'entry.request',\n });\n }\n await this._addRequest(entry, 'unshift');\n }\n /**\n * Removes and returns the last request in the queue (along with its\n * timestamp and any metadata). The returned object takes the form:\n * `{request, timestamp, metadata}`.\n *\n * @return {Promise}\n */\n async popRequest() {\n return this._removeRequest('pop');\n }\n /**\n * Removes and returns the first request in the queue (along with its\n * timestamp and any metadata). The returned object takes the form:\n * `{request, timestamp, metadata}`.\n *\n * @return {Promise}\n */\n async shiftRequest() {\n return this._removeRequest('shift');\n }\n /**\n * Returns all the entries that have not expired (per `maxRetentionTime`).\n * Any expired entries are removed from the queue.\n *\n * @return {Promise>}\n */\n async getAll() {\n const allEntries = await this._queueStore.getAll();\n const now = Date.now();\n const unexpiredEntries = [];\n for (const entry of allEntries) {\n // Ignore requests older than maxRetentionTime. Call this function\n // recursively until an unexpired request is found.\n const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000;\n if (now - entry.timestamp > maxRetentionTimeInMs) {\n await this._queueStore.deleteEntry(entry.id);\n }\n else {\n unexpiredEntries.push(convertEntry(entry));\n }\n }\n return unexpiredEntries;\n }\n /**\n * Returns the number of entries present in the queue.\n * Note that expired entries (per `maxRetentionTime`) are also included in this count.\n *\n * @return {Promise}\n */\n async size() {\n return await this._queueStore.size();\n }\n /**\n * Adds the entry to the QueueStore and registers for a sync event.\n *\n * @param {Object} entry\n * @param {Request} entry.request\n * @param {Object} [entry.metadata]\n * @param {number} [entry.timestamp=Date.now()]\n * @param {string} operation ('push' or 'unshift')\n * @private\n */\n async _addRequest({ request, metadata, timestamp = Date.now() }, operation) {\n const storableRequest = await StorableRequest.fromRequest(request.clone());\n const entry = {\n requestData: storableRequest.toObject(),\n timestamp,\n };\n // Only include metadata if it's present.\n if (metadata) {\n entry.metadata = metadata;\n }\n switch (operation) {\n case 'push':\n await this._queueStore.pushEntry(entry);\n break;\n case 'unshift':\n await this._queueStore.unshiftEntry(entry);\n break;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(request.url)}' has ` +\n `been added to background sync queue '${this._name}'.`);\n }\n // Don't register for a sync if we're in the middle of a sync. Instead,\n // we wait until the sync is complete and call register if\n // `this._requestsAddedDuringSync` is true.\n if (this._syncInProgress) {\n this._requestsAddedDuringSync = true;\n }\n else {\n await this.registerSync();\n }\n }\n /**\n * Removes and returns the first or last (depending on `operation`) entry\n * from the QueueStore that's not older than the `maxRetentionTime`.\n *\n * @param {string} operation ('pop' or 'shift')\n * @return {Object|undefined}\n * @private\n */\n async _removeRequest(operation) {\n const now = Date.now();\n let entry;\n switch (operation) {\n case 'pop':\n entry = await this._queueStore.popEntry();\n break;\n case 'shift':\n entry = await this._queueStore.shiftEntry();\n break;\n }\n if (entry) {\n // Ignore requests older than maxRetentionTime. Call this function\n // recursively until an unexpired request is found.\n const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000;\n if (now - entry.timestamp > maxRetentionTimeInMs) {\n return this._removeRequest(operation);\n }\n return convertEntry(entry);\n }\n else {\n return undefined;\n }\n }\n /**\n * Loops through each request in the queue and attempts to re-fetch it.\n * If any request fails to re-fetch, it's put back in the same position in\n * the queue (which registers a retry for the next sync event).\n */\n async replayRequests() {\n let entry;\n while ((entry = await this.shiftRequest())) {\n try {\n await fetch(entry.request.clone());\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` +\n `has been replayed in queue '${this._name}'`);\n }\n }\n catch (error) {\n await this.unshiftRequest(entry);\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` +\n `failed to replay, putting it back in queue '${this._name}'`);\n }\n throw new WorkboxError('queue-replay-failed', { name: this._name });\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`All requests in queue '${this.name}' have successfully ` +\n `replayed; the queue is now empty!`);\n }\n }\n /**\n * Registers a sync event with a tag unique to this instance.\n */\n async registerSync() {\n // See https://github.com/GoogleChrome/workbox/issues/2393\n if ('sync' in self.registration && !this._forceSyncFallback) {\n try {\n await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`);\n }\n catch (err) {\n // This means the registration failed for some reason, possibly due to\n // the user disabling it.\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to register sync event for '${this._name}'.`, err);\n }\n }\n }\n }\n /**\n * In sync-supporting browsers, this adds a listener for the sync event.\n * In non-sync-supporting browsers, or if _forceSyncFallback is true, this\n * will retry the queue on service worker startup.\n *\n * @private\n */\n _addSyncListener() {\n // See https://github.com/GoogleChrome/workbox/issues/2393\n if ('sync' in self.registration && !this._forceSyncFallback) {\n self.addEventListener('sync', (event) => {\n if (event.tag === `${TAG_PREFIX}:${this._name}`) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Background sync for tag '${event.tag}' ` + `has been received`);\n }\n const syncComplete = async () => {\n this._syncInProgress = true;\n let syncError;\n try {\n await this._onSync({ queue: this });\n }\n catch (error) {\n if (error instanceof Error) {\n syncError = error;\n // Rethrow the error. Note: the logic in the finally clause\n // will run before this gets rethrown.\n throw syncError;\n }\n }\n finally {\n // New items may have been added to the queue during the sync,\n // so we need to register for a new sync if that's happened...\n // Unless there was an error during the sync, in which\n // case the browser will automatically retry later, as long\n // as `event.lastChance` is not true.\n if (this._requestsAddedDuringSync &&\n !(syncError && !event.lastChance)) {\n await this.registerSync();\n }\n this._syncInProgress = false;\n this._requestsAddedDuringSync = false;\n }\n };\n event.waitUntil(syncComplete());\n }\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Background sync replaying without background sync event`);\n }\n // If the browser doesn't support background sync, or the developer has\n // opted-in to not using it, retry every time the service worker starts up\n // as a fallback.\n void this._onSync({ queue: this });\n }\n }\n /**\n * Returns the set of queue names. This is primarily used to reset the list\n * of queue names in tests.\n *\n * @return {Set}\n *\n * @private\n */\n static get _queueNames() {\n return queueNames;\n }\n}\nexport { Queue };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Queue } from './Queue.js';\nimport './_version.js';\n/**\n * A class implementing the `fetchDidFail` lifecycle callback. This makes it\n * easier to add failed requests to a background sync Queue.\n *\n * @memberof workbox-background-sync\n */\nclass BackgroundSyncPlugin {\n /**\n * @param {string} name See the {@link workbox-background-sync.Queue}\n * documentation for parameter details.\n * @param {Object} [options] See the\n * {@link workbox-background-sync.Queue} documentation for\n * parameter details.\n */\n constructor(name, options) {\n /**\n * @param {Object} options\n * @param {Request} options.request\n * @private\n */\n this.fetchDidFail = async ({ request }) => {\n await this._queue.pushRequest({ request });\n };\n this._queue = new Queue(name, options);\n }\n}\nexport { BackgroundSyncPlugin };\n"],"names":["instanceOfAny","object","constructors","some","c","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","IDBDatabase","IDBObjectStore","IDBIndex","IDBCursor","IDBTransaction","getCursorAdvanceMethods","prototype","advance","continue","continuePrimaryKey","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","promisifyRequest","request","promise","Promise","resolve","reject","unlisten","removeEventListener","success","error","wrap","result","addEventListener","then","value","set","catch","cacheDonePromiseForTransaction","tx","has","done","complete","DOMException","idbProxyTraps","get","target","prop","receiver","objectStoreNames","undefined","objectStore","replaceTraps","callback","wrapFunction","func","transaction","storeNames","args","call","unwrap","sort","includes","apply","transformCachableValue","Proxy","IDBRequest","newValue","openDB","name","version","blocked","upgrade","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","db","readMethods","writeMethods","cachedMethods","Map","getMethod","targetFuncName","replace","useIndex","isWrite","method","storeName","store","index","shift","all","oldTraps","self","_","e","DB_VERSION","DB_NAME","REQUEST_OBJECT_STORE_NAME","QUEUE_NAME_INDEX","QueueDb","constructor","_db","addEntry","entry","getDb","durability","add","getFirstEntryId","cursor","openCursor","id","getAllEntriesByQueueName","queueName","results","getAllFromIndex","IDBKeyRange","only","Array","getEntryCountByQueueName","countFromIndex","deleteEntry","delete","getFirstEntryByQueueName","getEndEntryFromIndex","getLastEntryByQueueName","query","direction","_upgradeDb","contains","deleteObjectStore","objStore","createObjectStore","autoIncrement","keyPath","createIndex","unique","QueueStore","_queueName","_queueDb","pushEntry","assert","isType","moduleName","className","funcName","paramName","requestData","unshiftEntry","firstId","popEntry","_removeEntry","shiftEntry","getAll","size","serializableProperties","StorableRequest","fromRequest","url","headers","body","clone","arrayBuffer","key","entries","_requestData","toObject","Object","assign","slice","toRequest","Request","TAG_PREFIX","MAX_RETENTION_TIME","queueNames","Set","convertEntry","queueStoreEntry","queueEntry","timestamp","metadata","Queue","forceSyncFallback","onSync","maxRetentionTime","_syncInProgress","_requestsAddedDuringSync","WorkboxError","_name","_onSync","replayRequests","_maxRetentionTime","_forceSyncFallback","Boolean","_queueStore","_addSyncListener","pushRequest","isInstance","_addRequest","unshiftRequest","popRequest","_removeRequest","shiftRequest","allEntries","now","Date","unexpiredEntries","maxRetentionTimeInMs","push","operation","storableRequest","logger","log","getFriendlyURL","registerSync","fetch","process","registration","sync","register","err","warn","tag","syncComplete","syncError","queue","Error","lastChance","waitUntil","_queueNames","BackgroundSyncPlugin","options","fetchDidFail","_queue"],"mappings":";;;;;;;;;;;;;;;;;;;;;;EAAA,MAAMA,aAAa,GAAG,CAACC,MAAD,EAASC,YAAT,KAA0BA,YAAY,CAACC,IAAb,CAAmBC,CAAD,IAAOH,MAAM,YAAYG,CAA3C,CAAhD;;EAEA,IAAIC,iBAAJ;EACA,IAAIC,oBAAJ;;EAEA,SAASC,oBAAT,GAAgC;EAC5B,SAAQF,iBAAiB,KACpBA,iBAAiB,GAAG,CACjBG,WADiB,EAEjBC,cAFiB,EAGjBC,QAHiB,EAIjBC,SAJiB,EAKjBC,cALiB,CADA,CAAzB;EAQH;;;EAED,SAASC,uBAAT,GAAmC;EAC/B,SAAQP,oBAAoB,KACvBA,oBAAoB,GAAG,CACpBK,SAAS,CAACG,SAAV,CAAoBC,OADA,EAEpBJ,SAAS,CAACG,SAAV,CAAoBE,QAFA,EAGpBL,SAAS,CAACG,SAAV,CAAoBG,kBAHA,CADA,CAA5B;EAMH;;EACD,MAAMC,gBAAgB,GAAG,IAAIC,OAAJ,EAAzB;EACA,MAAMC,kBAAkB,GAAG,IAAID,OAAJ,EAA3B;EACA,MAAME,wBAAwB,GAAG,IAAIF,OAAJ,EAAjC;EACA,MAAMG,cAAc,GAAG,IAAIH,OAAJ,EAAvB;EACA,MAAMI,qBAAq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,KAAZ,CADwB;EAGxB;;EACA,sBAAMuM,SAAN;EACH;EACJ,aAVD,SAWQ;EACJ;EACA;EACA;EACA;EACA;EACA,kBAAI,KAAKtC,wBAAL,IACA,EAAEsC,SAAS,IAAI,CAACvJ,KAAK,CAAC0J,UAAtB,CADJ,EACuC;EACnC,sBAAM,KAAKb,YAAL,EAAN;EACH;;EACD,mBAAK7B,eAAL,GAAuB,KAAvB;EACA,mBAAKC,wBAAL,GAAgC,KAAhC;EACH;EACJ,WA3BD;;EA4BAjH,UAAAA,KAAK,CAAC2J,SAAN,CAAgBL,YAAY,EAA5B;EACH;EACJ,OAnCD;EAoCH,KArCD,MAsCK;EACD,MAA2C;EACvCZ,QAAAA,gBAAM,CAACC,GAAP,CAAY,yDAAZ;EACH,OAHA;EAKD;EACA;;;EACA,WAAK,KAAKvB,OAAL,CAAa;EAAEoC,QAAAA,KAAK,EAAE;EAAT,OAAb,CAAL;EACH;EACJ;EACD;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;;;EACI,aAAWI,WAAX,GAAyB;EACrB,WAAOvD,UAAP;EACH;;EAnWO;;EC3CZ;EACA;AACA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;EACA;EACA;EACA;;EACA,MAAMwD,oBAAN,CAA2B;EACvB;EACJ;EACA;EACA;EACA;EACA;EACA;EACIjI,EAAAA,WAAW,CAACrC,IAAD,EAAOuK,OAAP,EAAgB;EACvB;EACR;EACA;EACA;EACA;EACQ,SAAKC,YAAL,GAAoB,OAAO;EAAEvN,MAAAA;EAAF,KAAP,KAAuB;EACvC,YAAM,KAAKwN,MAAL,CAAYrC,WAAZ,CAAwB;EAAEnL,QAAAA;EAAF,OAAxB,CAAN;EACH,KAFD;;EAGA,SAAKwN,MAAL,GAAc,IAAIpD,KAAJ,CAAUrH,IAAV,EAAgBuK,OAAhB,CAAd;EACH;;EAlBsB;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-background-sync.prod.js b/src/Resources/workbox-v7.0.0/workbox-background-sync.prod.js new file mode 100644 index 0000000..fd1ace2 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-background-sync.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.backgroundSync=function(t,e,s,n){"use strict";function r(){return r=Object.assign||function(t){for(var e=1;ee.some((e=>t instanceof e));let i,c;const o=new WeakMap,u=new WeakMap,h=new WeakMap,y=new WeakMap,w=new WeakMap;let f={get(t,e,s){if(t instanceof IDBTransaction){if("done"===e)return u.get(t);if("objectStoreNames"===e)return t.objectStoreNames||h.get(t);if("store"===e)return s.objectStoreNames[1]?void 0:s.objectStore(s.objectStoreNames[0])}return m(t[e])},set:(t,e,s)=>(t[e]=s,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function l(t){return t!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(c||(c=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(p(this),e),m(o.get(this))}:function(...e){return m(t.apply(p(this),e))}:function(e,...s){const n=t.call(p(this),e,...s);return h.set(n,e.sort?e.sort():[e]),m(n)}}function d(t){return"function"==typeof t?l(t):(t instanceof IDBTransaction&&function(t){if(u.has(t))return;const e=new Promise(((e,s)=>{const n=()=>{t.removeEventListener("complete",r),t.removeEventListener("error",a),t.removeEventListener("abort",a)},r=()=>{e(),n()},a=()=>{s(t.error||new DOMException("AbortError","AbortError")),n()};t.addEventListener("complete",r),t.addEventListener("error",a),t.addEventListener("abort",a)}));u.set(t,e)}(t),a(t,i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,f):t)}function m(t){if(t instanceof IDBRequest)return function(t){const e=new Promise(((e,s)=>{const n=()=>{t.removeEventListener("success",r),t.removeEventListener("error",a)},r=()=>{e(m(t.result)),n()},a=()=>{s(t.error),n()};t.addEventListener("success",r),t.addEventListener("error",a)}));return e.then((e=>{e instanceof IDBCursor&&o.set(e,t)})).catch((()=>{})),w.set(e,t),e}(t);if(y.has(t))return y.get(t);const e=d(t);return e!==t&&(y.set(t,e),w.set(e,t)),e}const p=t=>w.get(t);const g=["get","getKey","getAll","getAllKeys","count"],D=["put","add","delete","clear"],b=new Map;function B(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(b.get(e))return b.get(e);const s=e.replace(/FromIndex$/,""),n=e!==s,r=D.includes(s);if(!(s in(n?IDBIndex:IDBObjectStore).prototype)||!r&&!g.includes(s))return;const a=async function(t,...e){const a=this.transaction(t,r?"readwrite":"readonly");let i=a.store;return n&&(i=i.index(e.shift())),(await Promise.all([i[s](...e),r&&a.done]))[0]};return b.set(e,a),a}f=(t=>r({},t,{get:(e,s,n)=>B(e,s)||t.get(e,s,n),has:(e,s)=>!!B(e,s)||t.has(e,s)}))(f);try{self["workbox:background-sync:7.0.0"]&&_()}catch(t){}const I="requests",q="queueName";class k{constructor(){this.t=null}async addEntry(t){const e=(await this.getDb()).transaction(I,"readwrite",{durability:"relaxed"});await e.store.add(t),await e.done}async getFirstEntryId(){const t=await this.getDb(),e=await t.transaction(I).store.openCursor();return null==e?void 0:e.value.id}async getAllEntriesByQueueName(t){const e=await this.getDb(),s=await e.getAllFromIndex(I,q,IDBKeyRange.only(t));return s||new Array}async getEntryCountByQueueName(t){return(await this.getDb()).countFromIndex(I,q,IDBKeyRange.only(t))}async deleteEntry(t){const e=await this.getDb();await e.delete(I,t)}async getFirstEntryByQueueName(t){return await this.getEndEntryFromIndex(IDBKeyRange.only(t),"next")}async getLastEntryByQueueName(t){return await this.getEndEntryFromIndex(IDBKeyRange.only(t),"prev")}async getEndEntryFromIndex(t,e){const s=await this.getDb(),n=await s.transaction(I).store.index(q).openCursor(t,e);return null==n?void 0:n.value}async getDb(){return this.t||(this.t=await function(t,e,{blocked:s,upgrade:n,blocking:r,terminated:a}={}){const i=indexedDB.open(t,e),c=m(i);return n&&i.addEventListener("upgradeneeded",(t=>{n(m(i.result),t.oldVersion,t.newVersion,m(i.transaction))})),s&&i.addEventListener("blocked",(()=>s())),c.then((t=>{a&&t.addEventListener("close",(()=>a())),r&&t.addEventListener("versionchange",(()=>r()))})).catch((()=>{})),c}("workbox-background-sync",3,{upgrade:this.i})),this.t}i(t,e){e>0&&e<3&&t.objectStoreNames.contains(I)&&t.deleteObjectStore(I);t.createObjectStore(I,{autoIncrement:!0,keyPath:"id"}).createIndex(q,q,{unique:!1})}}class E{constructor(t){this.o=t,this.u=new k}async pushEntry(t){delete t.id,t.queueName=this.o,await this.u.addEntry(t)}async unshiftEntry(t){const e=await this.u.getFirstEntryId();e?t.id=e-1:delete t.id,t.queueName=this.o,await this.u.addEntry(t)}async popEntry(){return this.h(await this.u.getLastEntryByQueueName(this.o))}async shiftEntry(){return this.h(await this.u.getFirstEntryByQueueName(this.o))}async getAll(){return await this.u.getAllEntriesByQueueName(this.o)}async size(){return await this.u.getEntryCountByQueueName(this.o)}async deleteEntry(t){await this.u.deleteEntry(t)}async h(t){return t&&await this.deleteEntry(t.id),t}}const R=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];class x{static async fromRequest(t){const e={url:t.url,headers:{}};"GET"!==t.method&&(e.body=await t.clone().arrayBuffer());for(const[s,n]of t.headers.entries())e.headers[s]=n;for(const s of R)void 0!==t[s]&&(e[s]=t[s]);return new x(e)}constructor(t){"navigate"===t.mode&&(t.mode="same-origin"),this.l=t}toObject(){const t=Object.assign({},this.l);return t.headers=Object.assign({},this.l.headers),t.body&&(t.body=t.body.slice(0)),t}toRequest(){return new Request(this.l.url,this.l)}clone(){return new x(this.toObject())}}const v="workbox-background-sync",j=new Set,S=t=>{const e={request:new x(t.requestData).toRequest(),timestamp:t.timestamp};return t.metadata&&(e.metadata=t.metadata),e};class A{constructor(t,{forceSyncFallback:s,onSync:n,maxRetentionTime:r}={}){if(this.m=!1,this.p=!1,j.has(t))throw new e.WorkboxError("duplicate-queue-name",{name:t});j.add(t),this.g=t,this.D=n||this.replayRequests,this.B=r||10080,this.I=Boolean(s),this.q=new E(this.g),this.k()}get name(){return this.g}async pushRequest(t){await this.R(t,"push")}async unshiftRequest(t){await this.R(t,"unshift")}async popRequest(){return this.v("pop")}async shiftRequest(){return this.v("shift")}async getAll(){const t=await this.q.getAll(),e=Date.now(),s=[];for(const n of t){const t=60*this.B*1e3;e-n.timestamp>t?await this.q.deleteEntry(n.id):s.push(S(n))}return s}async size(){return await this.q.size()}async R({request:t,metadata:e,timestamp:s=Date.now()},n){const r={requestData:(await x.fromRequest(t.clone())).toObject(),timestamp:s};switch(e&&(r.metadata=e),n){case"push":await this.q.pushEntry(r);break;case"unshift":await this.q.unshiftEntry(r)}this.m?this.p=!0:await this.registerSync()}async v(t){const e=Date.now();let s;switch(t){case"pop":s=await this.q.popEntry();break;case"shift":s=await this.q.shiftEntry()}if(s){const n=60*this.B*1e3;return e-s.timestamp>n?this.v(t):S(s)}}async replayRequests(){let t;for(;t=await this.shiftRequest();)try{await fetch(t.request.clone())}catch(s){throw await this.unshiftRequest(t),new e.WorkboxError("queue-replay-failed",{name:this.g})}}async registerSync(){if("sync"in self.registration&&!this.I)try{await self.registration.sync.register(`${v}:${this.g}`)}catch(t){}}k(){"sync"in self.registration&&!this.I?self.addEventListener("sync",(t=>{if(t.tag===`${v}:${this.g}`){const e=async()=>{let e;this.m=!0;try{await this.D({queue:this})}catch(t){if(t instanceof Error)throw e=t,e}finally{!this.p||e&&!t.lastChance||await this.registerSync(),this.m=!1,this.p=!1}};t.waitUntil(e())}})):this.D({queue:this})}static get j(){return j}}return t.BackgroundSyncPlugin=class{constructor(t,e){this.fetchDidFail=async({request:t})=>{await this.S.pushRequest({request:t})},this.S=new A(t,e)}},t.Queue=A,t.QueueStore=E,t.StorableRequest=x,t}({},workbox.core._private,workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-background-sync.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-background-sync.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-background-sync.prod.js.map new file mode 100644 index 0000000..05e29d0 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-background-sync.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-background-sync.prod.js","sources":["../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../_version.js","../lib/QueueDb.js","../lib/QueueStore.js","../lib/StorableRequest.js","../Queue.js","../BackgroundSyncPlugin.js"],"sourcesContent":["const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:background-sync:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2021 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { openDB } from 'idb';\nimport '../_version.js';\nconst DB_VERSION = 3;\nconst DB_NAME = 'workbox-background-sync';\nconst REQUEST_OBJECT_STORE_NAME = 'requests';\nconst QUEUE_NAME_INDEX = 'queueName';\n/**\n * A class to interact directly an IndexedDB created specifically to save and\n * retrieve QueueStoreEntries. This class encapsulates all the schema details\n * to store the representation of a Queue.\n *\n * @private\n */\nexport class QueueDb {\n constructor() {\n this._db = null;\n }\n /**\n * Add QueueStoreEntry to underlying db.\n *\n * @param {UnidentifiedQueueStoreEntry} entry\n */\n async addEntry(entry) {\n const db = await this.getDb();\n const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, 'readwrite', {\n durability: 'relaxed',\n });\n await tx.store.add(entry);\n await tx.done;\n }\n /**\n * Returns the first entry id in the ObjectStore.\n *\n * @return {number | undefined}\n */\n async getFirstEntryId() {\n const db = await this.getDb();\n const cursor = await db\n .transaction(REQUEST_OBJECT_STORE_NAME)\n .store.openCursor();\n return cursor === null || cursor === void 0 ? void 0 : cursor.value.id;\n }\n /**\n * Get all the entries filtered by index\n *\n * @param queueName\n * @return {Promise}\n */\n async getAllEntriesByQueueName(queueName) {\n const db = await this.getDb();\n const results = await db.getAllFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));\n return results ? results : new Array();\n }\n /**\n * Returns the number of entries filtered by index\n *\n * @param queueName\n * @return {Promise}\n */\n async getEntryCountByQueueName(queueName) {\n const db = await this.getDb();\n return db.countFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));\n }\n /**\n * Deletes a single entry by id.\n *\n * @param {number} id the id of the entry to be deleted\n */\n async deleteEntry(id) {\n const db = await this.getDb();\n await db.delete(REQUEST_OBJECT_STORE_NAME, id);\n }\n /**\n *\n * @param queueName\n * @returns {Promise}\n */\n async getFirstEntryByQueueName(queueName) {\n return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'next');\n }\n /**\n *\n * @param queueName\n * @returns {Promise}\n */\n async getLastEntryByQueueName(queueName) {\n return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'prev');\n }\n /**\n * Returns either the first or the last entries, depending on direction.\n * Filtered by index.\n *\n * @param {IDBCursorDirection} direction\n * @param {IDBKeyRange} query\n * @return {Promise}\n * @private\n */\n async getEndEntryFromIndex(query, direction) {\n const db = await this.getDb();\n const cursor = await db\n .transaction(REQUEST_OBJECT_STORE_NAME)\n .store.index(QUEUE_NAME_INDEX)\n .openCursor(query, direction);\n return cursor === null || cursor === void 0 ? void 0 : cursor.value;\n }\n /**\n * Returns an open connection to the database.\n *\n * @private\n */\n async getDb() {\n if (!this._db) {\n this._db = await openDB(DB_NAME, DB_VERSION, {\n upgrade: this._upgradeDb,\n });\n }\n return this._db;\n }\n /**\n * Upgrades QueueDB\n *\n * @param {IDBPDatabase} db\n * @param {number} oldVersion\n * @private\n */\n _upgradeDb(db, oldVersion) {\n if (oldVersion > 0 && oldVersion < DB_VERSION) {\n if (db.objectStoreNames.contains(REQUEST_OBJECT_STORE_NAME)) {\n db.deleteObjectStore(REQUEST_OBJECT_STORE_NAME);\n }\n }\n const objStore = db.createObjectStore(REQUEST_OBJECT_STORE_NAME, {\n autoIncrement: true,\n keyPath: 'id',\n });\n objStore.createIndex(QUEUE_NAME_INDEX, QUEUE_NAME_INDEX, { unique: false });\n }\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { QueueDb, } from './QueueDb.js';\nimport '../_version.js';\n/**\n * A class to manage storing requests from a Queue in IndexedDB,\n * indexed by their queue name for easier access.\n *\n * Most developers will not need to access this class directly;\n * it is exposed for advanced use cases.\n */\nexport class QueueStore {\n /**\n * Associates this instance with a Queue instance, so entries added can be\n * identified by their queue name.\n *\n * @param {string} queueName\n */\n constructor(queueName) {\n this._queueName = queueName;\n this._queueDb = new QueueDb();\n }\n /**\n * Append an entry last in the queue.\n *\n * @param {Object} entry\n * @param {Object} entry.requestData\n * @param {number} [entry.timestamp]\n * @param {Object} [entry.metadata]\n */\n async pushEntry(entry) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(entry, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'QueueStore',\n funcName: 'pushEntry',\n paramName: 'entry',\n });\n assert.isType(entry.requestData, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'QueueStore',\n funcName: 'pushEntry',\n paramName: 'entry.requestData',\n });\n }\n // Don't specify an ID since one is automatically generated.\n delete entry.id;\n entry.queueName = this._queueName;\n await this._queueDb.addEntry(entry);\n }\n /**\n * Prepend an entry first in the queue.\n *\n * @param {Object} entry\n * @param {Object} entry.requestData\n * @param {number} [entry.timestamp]\n * @param {Object} [entry.metadata]\n */\n async unshiftEntry(entry) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(entry, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'QueueStore',\n funcName: 'unshiftEntry',\n paramName: 'entry',\n });\n assert.isType(entry.requestData, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'QueueStore',\n funcName: 'unshiftEntry',\n paramName: 'entry.requestData',\n });\n }\n const firstId = await this._queueDb.getFirstEntryId();\n if (firstId) {\n // Pick an ID one less than the lowest ID in the object store.\n entry.id = firstId - 1;\n }\n else {\n // Otherwise let the auto-incrementor assign the ID.\n delete entry.id;\n }\n entry.queueName = this._queueName;\n await this._queueDb.addEntry(entry);\n }\n /**\n * Removes and returns the last entry in the queue matching the `queueName`.\n *\n * @return {Promise}\n */\n async popEntry() {\n return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));\n }\n /**\n * Removes and returns the first entry in the queue matching the `queueName`.\n *\n * @return {Promise}\n */\n async shiftEntry() {\n return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));\n }\n /**\n * Returns all entries in the store matching the `queueName`.\n *\n * @param {Object} options See {@link workbox-background-sync.Queue~getAll}\n * @return {Promise>}\n */\n async getAll() {\n return await this._queueDb.getAllEntriesByQueueName(this._queueName);\n }\n /**\n * Returns the number of entries in the store matching the `queueName`.\n *\n * @param {Object} options See {@link workbox-background-sync.Queue~size}\n * @return {Promise}\n */\n async size() {\n return await this._queueDb.getEntryCountByQueueName(this._queueName);\n }\n /**\n * Deletes the entry for the given ID.\n *\n * WARNING: this method does not ensure the deleted entry belongs to this\n * queue (i.e. matches the `queueName`). But this limitation is acceptable\n * as this class is not publicly exposed. An additional check would make\n * this method slower than it needs to be.\n *\n * @param {number} id\n */\n async deleteEntry(id) {\n await this._queueDb.deleteEntry(id);\n }\n /**\n * Removes and returns the first or last entry in the queue (based on the\n * `direction` argument) matching the `queueName`.\n *\n * @return {Promise}\n * @private\n */\n async _removeEntry(entry) {\n if (entry) {\n await this.deleteEntry(entry.id);\n }\n return entry;\n }\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\nconst serializableProperties = [\n 'method',\n 'referrer',\n 'referrerPolicy',\n 'mode',\n 'credentials',\n 'cache',\n 'redirect',\n 'integrity',\n 'keepalive',\n];\n/**\n * A class to make it easier to serialize and de-serialize requests so they\n * can be stored in IndexedDB.\n *\n * Most developers will not need to access this class directly;\n * it is exposed for advanced use cases.\n */\nclass StorableRequest {\n /**\n * Converts a Request object to a plain object that can be structured\n * cloned or JSON-stringified.\n *\n * @param {Request} request\n * @return {Promise}\n */\n static async fromRequest(request) {\n const requestData = {\n url: request.url,\n headers: {},\n };\n // Set the body if present.\n if (request.method !== 'GET') {\n // Use ArrayBuffer to support non-text request bodies.\n // NOTE: we can't use Blobs becuse Safari doesn't support storing\n // Blobs in IndexedDB in some cases:\n // https://github.com/dfahlander/Dexie.js/issues/618#issuecomment-398348457\n requestData.body = await request.clone().arrayBuffer();\n }\n // Convert the headers from an iterable to an object.\n for (const [key, value] of request.headers.entries()) {\n requestData.headers[key] = value;\n }\n // Add all other serializable request properties\n for (const prop of serializableProperties) {\n if (request[prop] !== undefined) {\n requestData[prop] = request[prop];\n }\n }\n return new StorableRequest(requestData);\n }\n /**\n * Accepts an object of request data that can be used to construct a\n * `Request` but can also be stored in IndexedDB.\n *\n * @param {Object} requestData An object of request data that includes the\n * `url` plus any relevant properties of\n * [requestInit]{@link https://fetch.spec.whatwg.org/#requestinit}.\n */\n constructor(requestData) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(requestData, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'StorableRequest',\n funcName: 'constructor',\n paramName: 'requestData',\n });\n assert.isType(requestData.url, 'string', {\n moduleName: 'workbox-background-sync',\n className: 'StorableRequest',\n funcName: 'constructor',\n paramName: 'requestData.url',\n });\n }\n // If the request's mode is `navigate`, convert it to `same-origin` since\n // navigation requests can't be constructed via script.\n if (requestData['mode'] === 'navigate') {\n requestData['mode'] = 'same-origin';\n }\n this._requestData = requestData;\n }\n /**\n * Returns a deep clone of the instances `_requestData` object.\n *\n * @return {Object}\n */\n toObject() {\n const requestData = Object.assign({}, this._requestData);\n requestData.headers = Object.assign({}, this._requestData.headers);\n if (requestData.body) {\n requestData.body = requestData.body.slice(0);\n }\n return requestData;\n }\n /**\n * Converts this instance to a Request.\n *\n * @return {Request}\n */\n toRequest() {\n return new Request(this._requestData.url, this._requestData);\n }\n /**\n * Creates and returns a deep clone of the instance.\n *\n * @return {StorableRequest}\n */\n clone() {\n return new StorableRequest(this.toObject());\n }\n}\nexport { StorableRequest };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { QueueStore } from './lib/QueueStore.js';\nimport { StorableRequest } from './lib/StorableRequest.js';\nimport './_version.js';\nconst TAG_PREFIX = 'workbox-background-sync';\nconst MAX_RETENTION_TIME = 60 * 24 * 7; // 7 days in minutes\nconst queueNames = new Set();\n/**\n * Converts a QueueStore entry into the format exposed by Queue. This entails\n * converting the request data into a real request and omitting the `id` and\n * `queueName` properties.\n *\n * @param {UnidentifiedQueueStoreEntry} queueStoreEntry\n * @return {Queue}\n * @private\n */\nconst convertEntry = (queueStoreEntry) => {\n const queueEntry = {\n request: new StorableRequest(queueStoreEntry.requestData).toRequest(),\n timestamp: queueStoreEntry.timestamp,\n };\n if (queueStoreEntry.metadata) {\n queueEntry.metadata = queueStoreEntry.metadata;\n }\n return queueEntry;\n};\n/**\n * A class to manage storing failed requests in IndexedDB and retrying them\n * later. All parts of the storing and replaying process are observable via\n * callbacks.\n *\n * @memberof workbox-background-sync\n */\nclass Queue {\n /**\n * Creates an instance of Queue with the given options\n *\n * @param {string} name The unique name for this queue. This name must be\n * unique as it's used to register sync events and store requests\n * in IndexedDB specific to this instance. An error will be thrown if\n * a duplicate name is detected.\n * @param {Object} [options]\n * @param {Function} [options.onSync] A function that gets invoked whenever\n * the 'sync' event fires. The function is invoked with an object\n * containing the `queue` property (referencing this instance), and you\n * can use the callback to customize the replay behavior of the queue.\n * When not set the `replayRequests()` method is called.\n * Note: if the replay fails after a sync event, make sure you throw an\n * error, so the browser knows to retry the sync event later.\n * @param {number} [options.maxRetentionTime=7 days] The amount of time (in\n * minutes) a request may be retried. After this amount of time has\n * passed, the request will be deleted from the queue.\n * @param {boolean} [options.forceSyncFallback=false] If `true`, instead\n * of attempting to use background sync events, always attempt to replay\n * queued request at service worker startup. Most folks will not need\n * this, unless you explicitly target a runtime like Electron that\n * exposes the interfaces for background sync, but does not have a working\n * implementation.\n */\n constructor(name, { forceSyncFallback, onSync, maxRetentionTime } = {}) {\n this._syncInProgress = false;\n this._requestsAddedDuringSync = false;\n // Ensure the store name is not already being used\n if (queueNames.has(name)) {\n throw new WorkboxError('duplicate-queue-name', { name });\n }\n else {\n queueNames.add(name);\n }\n this._name = name;\n this._onSync = onSync || this.replayRequests;\n this._maxRetentionTime = maxRetentionTime || MAX_RETENTION_TIME;\n this._forceSyncFallback = Boolean(forceSyncFallback);\n this._queueStore = new QueueStore(this._name);\n this._addSyncListener();\n }\n /**\n * @return {string}\n */\n get name() {\n return this._name;\n }\n /**\n * Stores the passed request in IndexedDB (with its timestamp and any\n * metadata) at the end of the queue.\n *\n * @param {QueueEntry} entry\n * @param {Request} entry.request The request to store in the queue.\n * @param {Object} [entry.metadata] Any metadata you want associated with the\n * stored request. When requests are replayed you'll have access to this\n * metadata object in case you need to modify the request beforehand.\n * @param {number} [entry.timestamp] The timestamp (Epoch time in\n * milliseconds) when the request was first added to the queue. This is\n * used along with `maxRetentionTime` to remove outdated requests. In\n * general you don't need to set this value, as it's automatically set\n * for you (defaulting to `Date.now()`), but you can update it if you\n * don't want particular requests to expire.\n */\n async pushRequest(entry) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(entry, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'pushRequest',\n paramName: 'entry',\n });\n assert.isInstance(entry.request, Request, {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'pushRequest',\n paramName: 'entry.request',\n });\n }\n await this._addRequest(entry, 'push');\n }\n /**\n * Stores the passed request in IndexedDB (with its timestamp and any\n * metadata) at the beginning of the queue.\n *\n * @param {QueueEntry} entry\n * @param {Request} entry.request The request to store in the queue.\n * @param {Object} [entry.metadata] Any metadata you want associated with the\n * stored request. When requests are replayed you'll have access to this\n * metadata object in case you need to modify the request beforehand.\n * @param {number} [entry.timestamp] The timestamp (Epoch time in\n * milliseconds) when the request was first added to the queue. This is\n * used along with `maxRetentionTime` to remove outdated requests. In\n * general you don't need to set this value, as it's automatically set\n * for you (defaulting to `Date.now()`), but you can update it if you\n * don't want particular requests to expire.\n */\n async unshiftRequest(entry) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(entry, 'object', {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'unshiftRequest',\n paramName: 'entry',\n });\n assert.isInstance(entry.request, Request, {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'unshiftRequest',\n paramName: 'entry.request',\n });\n }\n await this._addRequest(entry, 'unshift');\n }\n /**\n * Removes and returns the last request in the queue (along with its\n * timestamp and any metadata). The returned object takes the form:\n * `{request, timestamp, metadata}`.\n *\n * @return {Promise}\n */\n async popRequest() {\n return this._removeRequest('pop');\n }\n /**\n * Removes and returns the first request in the queue (along with its\n * timestamp and any metadata). The returned object takes the form:\n * `{request, timestamp, metadata}`.\n *\n * @return {Promise}\n */\n async shiftRequest() {\n return this._removeRequest('shift');\n }\n /**\n * Returns all the entries that have not expired (per `maxRetentionTime`).\n * Any expired entries are removed from the queue.\n *\n * @return {Promise>}\n */\n async getAll() {\n const allEntries = await this._queueStore.getAll();\n const now = Date.now();\n const unexpiredEntries = [];\n for (const entry of allEntries) {\n // Ignore requests older than maxRetentionTime. Call this function\n // recursively until an unexpired request is found.\n const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000;\n if (now - entry.timestamp > maxRetentionTimeInMs) {\n await this._queueStore.deleteEntry(entry.id);\n }\n else {\n unexpiredEntries.push(convertEntry(entry));\n }\n }\n return unexpiredEntries;\n }\n /**\n * Returns the number of entries present in the queue.\n * Note that expired entries (per `maxRetentionTime`) are also included in this count.\n *\n * @return {Promise}\n */\n async size() {\n return await this._queueStore.size();\n }\n /**\n * Adds the entry to the QueueStore and registers for a sync event.\n *\n * @param {Object} entry\n * @param {Request} entry.request\n * @param {Object} [entry.metadata]\n * @param {number} [entry.timestamp=Date.now()]\n * @param {string} operation ('push' or 'unshift')\n * @private\n */\n async _addRequest({ request, metadata, timestamp = Date.now() }, operation) {\n const storableRequest = await StorableRequest.fromRequest(request.clone());\n const entry = {\n requestData: storableRequest.toObject(),\n timestamp,\n };\n // Only include metadata if it's present.\n if (metadata) {\n entry.metadata = metadata;\n }\n switch (operation) {\n case 'push':\n await this._queueStore.pushEntry(entry);\n break;\n case 'unshift':\n await this._queueStore.unshiftEntry(entry);\n break;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(request.url)}' has ` +\n `been added to background sync queue '${this._name}'.`);\n }\n // Don't register for a sync if we're in the middle of a sync. Instead,\n // we wait until the sync is complete and call register if\n // `this._requestsAddedDuringSync` is true.\n if (this._syncInProgress) {\n this._requestsAddedDuringSync = true;\n }\n else {\n await this.registerSync();\n }\n }\n /**\n * Removes and returns the first or last (depending on `operation`) entry\n * from the QueueStore that's not older than the `maxRetentionTime`.\n *\n * @param {string} operation ('pop' or 'shift')\n * @return {Object|undefined}\n * @private\n */\n async _removeRequest(operation) {\n const now = Date.now();\n let entry;\n switch (operation) {\n case 'pop':\n entry = await this._queueStore.popEntry();\n break;\n case 'shift':\n entry = await this._queueStore.shiftEntry();\n break;\n }\n if (entry) {\n // Ignore requests older than maxRetentionTime. Call this function\n // recursively until an unexpired request is found.\n const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000;\n if (now - entry.timestamp > maxRetentionTimeInMs) {\n return this._removeRequest(operation);\n }\n return convertEntry(entry);\n }\n else {\n return undefined;\n }\n }\n /**\n * Loops through each request in the queue and attempts to re-fetch it.\n * If any request fails to re-fetch, it's put back in the same position in\n * the queue (which registers a retry for the next sync event).\n */\n async replayRequests() {\n let entry;\n while ((entry = await this.shiftRequest())) {\n try {\n await fetch(entry.request.clone());\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` +\n `has been replayed in queue '${this._name}'`);\n }\n }\n catch (error) {\n await this.unshiftRequest(entry);\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(entry.request.url)}' ` +\n `failed to replay, putting it back in queue '${this._name}'`);\n }\n throw new WorkboxError('queue-replay-failed', { name: this._name });\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`All requests in queue '${this.name}' have successfully ` +\n `replayed; the queue is now empty!`);\n }\n }\n /**\n * Registers a sync event with a tag unique to this instance.\n */\n async registerSync() {\n // See https://github.com/GoogleChrome/workbox/issues/2393\n if ('sync' in self.registration && !this._forceSyncFallback) {\n try {\n await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`);\n }\n catch (err) {\n // This means the registration failed for some reason, possibly due to\n // the user disabling it.\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to register sync event for '${this._name}'.`, err);\n }\n }\n }\n }\n /**\n * In sync-supporting browsers, this adds a listener for the sync event.\n * In non-sync-supporting browsers, or if _forceSyncFallback is true, this\n * will retry the queue on service worker startup.\n *\n * @private\n */\n _addSyncListener() {\n // See https://github.com/GoogleChrome/workbox/issues/2393\n if ('sync' in self.registration && !this._forceSyncFallback) {\n self.addEventListener('sync', (event) => {\n if (event.tag === `${TAG_PREFIX}:${this._name}`) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Background sync for tag '${event.tag}' ` + `has been received`);\n }\n const syncComplete = async () => {\n this._syncInProgress = true;\n let syncError;\n try {\n await this._onSync({ queue: this });\n }\n catch (error) {\n if (error instanceof Error) {\n syncError = error;\n // Rethrow the error. Note: the logic in the finally clause\n // will run before this gets rethrown.\n throw syncError;\n }\n }\n finally {\n // New items may have been added to the queue during the sync,\n // so we need to register for a new sync if that's happened...\n // Unless there was an error during the sync, in which\n // case the browser will automatically retry later, as long\n // as `event.lastChance` is not true.\n if (this._requestsAddedDuringSync &&\n !(syncError && !event.lastChance)) {\n await this.registerSync();\n }\n this._syncInProgress = false;\n this._requestsAddedDuringSync = false;\n }\n };\n event.waitUntil(syncComplete());\n }\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Background sync replaying without background sync event`);\n }\n // If the browser doesn't support background sync, or the developer has\n // opted-in to not using it, retry every time the service worker starts up\n // as a fallback.\n void this._onSync({ queue: this });\n }\n }\n /**\n * Returns the set of queue names. This is primarily used to reset the list\n * of queue names in tests.\n *\n * @return {Set}\n *\n * @private\n */\n static get _queueNames() {\n return queueNames;\n }\n}\nexport { Queue };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Queue } from './Queue.js';\nimport './_version.js';\n/**\n * A class implementing the `fetchDidFail` lifecycle callback. This makes it\n * easier to add failed requests to a background sync Queue.\n *\n * @memberof workbox-background-sync\n */\nclass BackgroundSyncPlugin {\n /**\n * @param {string} name See the {@link workbox-background-sync.Queue}\n * documentation for parameter details.\n * @param {Object} [options] See the\n * {@link workbox-background-sync.Queue} documentation for\n * parameter details.\n */\n constructor(name, options) {\n /**\n * @param {Object} options\n * @param {Request} options.request\n * @private\n */\n this.fetchDidFail = async ({ request }) => {\n await this._queue.pushRequest({ request });\n };\n this._queue = new Queue(name, options);\n }\n}\nexport { BackgroundSyncPlugin };\n"],"names":["instanceOfAny","object","constructors","some","c","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","get","target","prop","receiver","IDBTransaction","objectStoreNames","undefined","objectStore","wrap","set","value","has","wrapFunction","func","IDBDatabase","prototype","transaction","IDBCursor","advance","continue","continuePrimaryKey","includes","args","apply","unwrap","this","storeNames","tx","call","sort","transformCachableValue","done","Promise","resolve","reject","unlisten","removeEventListener","complete","error","DOMException","addEventListener","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","request","promise","success","result","then","catch","promisifyRequest","newValue","readMethods","writeMethods","cachedMethods","Map","getMethod","targetFuncName","replace","useIndex","isWrite","method","async","storeName","store","index","shift","all","oldTraps","callback","self","_","e","REQUEST_OBJECT_STORE_NAME","QUEUE_NAME_INDEX","QueueDb","constructor","_db","entry","getDb","durability","add","db","cursor","openCursor","id","queueName","results","getAllFromIndex","IDBKeyRange","only","Array","countFromIndex","delete","getEndEntryFromIndex","query","direction","name","version","blocked","upgrade","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","openDB","_upgradeDb","contains","deleteObjectStore","createObjectStore","autoIncrement","keyPath","createIndex","unique","QueueStore","_queueName","_queueDb","addEntry","firstId","getFirstEntryId","_removeEntry","getLastEntryByQueueName","getFirstEntryByQueueName","getAllEntriesByQueueName","getEntryCountByQueueName","deleteEntry","serializableProperties","StorableRequest","requestData","url","headers","body","clone","arrayBuffer","key","entries","_requestData","toObject","Object","assign","slice","toRequest","Request","TAG_PREFIX","queueNames","Set","convertEntry","queueStoreEntry","queueEntry","timestamp","metadata","Queue","forceSyncFallback","onSync","maxRetentionTime","_syncInProgress","_requestsAddedDuringSync","WorkboxError","_name","_onSync","replayRequests","_maxRetentionTime","_forceSyncFallback","Boolean","_queueStore","_addSyncListener","_addRequest","_removeRequest","allEntries","getAll","now","Date","unexpiredEntries","maxRetentionTimeInMs","push","size","operation","fromRequest","pushEntry","unshiftEntry","registerSync","popEntry","shiftEntry","shiftRequest","fetch","unshiftRequest","registration","sync","register","err","tag","syncComplete","syncError","queue","Error","lastChance","waitUntil","_queueNames","options","fetchDidFail","_queue","pushRequest"],"mappings":"ySAAA,MAAMA,EA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,OAWxBkL,sBACArD,iCC9Xf,MAQIxE,YAAYqB,EAAMyG,QAMTC,aAAe7I,OAASlB,oBACnBrB,KAAKqL,EAAOC,YAAY,CAAEjK,WAAhC,OAECgK,EAAS,IAAIjD,EAAM1D,EAAMyG"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-broadcast-update.dev.js b/src/Resources/workbox-v7.0.0/workbox-broadcast-update.dev.js new file mode 100644 index 0000000..d95b922 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-broadcast-update.dev.js @@ -0,0 +1,302 @@ +this.workbox = this.workbox || {}; +this.workbox.broadcastUpdate = (function (exports, assert_js, timeout_js, resultingClientExists_js, logger_js, WorkboxError_js, dontWaitFor_js) { + 'use strict'; + + try { + self['workbox:broadcast-update:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Given two `Response's`, compares several header values to see if they are + * the same or not. + * + * @param {Response} firstResponse + * @param {Response} secondResponse + * @param {Array} headersToCheck + * @return {boolean} + * + * @memberof workbox-broadcast-update + */ + + const responsesAreSame = (firstResponse, secondResponse, headersToCheck) => { + { + if (!(firstResponse instanceof Response && secondResponse instanceof Response)) { + throw new WorkboxError_js.WorkboxError('invalid-responses-are-same-args'); + } + } + + const atLeastOneHeaderAvailable = headersToCheck.some(header => { + return firstResponse.headers.has(header) && secondResponse.headers.has(header); + }); + + if (!atLeastOneHeaderAvailable) { + { + logger_js.logger.warn(`Unable to determine where the response has been updated ` + `because none of the headers that would be checked are present.`); + logger_js.logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck); + } // Just return true, indicating the that responses are the same, since we + // can't determine otherwise. + + + return true; + } + + return headersToCheck.every(header => { + const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header); + const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header); + return headerStateComparison && headerValueComparison; + }); + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED'; + const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update'; + const NOTIFY_ALL_CLIENTS = true; + const DEFAULT_HEADERS_TO_CHECK = ['content-length', 'etag', 'last-modified']; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + // TODO(philipwalton): remove once this Safari bug fix has been released. + // https://bugs.webkit.org/show_bug.cgi?id=201169 + + const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + /** + * Generates the default payload used in update messages. By default the + * payload includes the `cacheName` and `updatedURL` fields. + * + * @return Object + * @private + */ + + function defaultPayloadGenerator(data) { + return { + cacheName: data.cacheName, + updatedURL: data.request.url + }; + } + /** + * Uses the `postMessage()` API to inform any open windows/tabs when a cached + * response has been updated. + * + * For efficiency's sake, the underlying response bodies are not compared; + * only specific response headers are checked. + * + * @memberof workbox-broadcast-update + */ + + + class BroadcastCacheUpdate { + /** + * Construct a BroadcastCacheUpdate instance with a specific `channelName` to + * broadcast messages on + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + * @param {boolean} [options.notifyAllClients=true] If true (the default) then + * all open clients will receive a message. If false, then only the client + * that make the original request will be notified of the update. + */ + constructor({ + generatePayload, + headersToCheck, + notifyAllClients + } = {}) { + this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK; + this._generatePayload = generatePayload || defaultPayloadGenerator; + this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS; + } + /** + * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * and sends a message (via `postMessage()`) to all window clients if the + * responses differ. Neither of the Responses can be + * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * + * The message that's posted has the following format (where `payload` can + * be customized via the `generatePayload` option the instance is created + * with): + * + * ``` + * { + * type: 'CACHE_UPDATED', + * meta: 'workbox-broadcast-update', + * payload: { + * cacheName: 'the-cache-name', + * updatedURL: 'https://example.com/' + * } + * } + * ``` + * + * @param {Object} options + * @param {Response} [options.oldResponse] Cached response to compare. + * @param {Response} options.newResponse Possibly updated response to compare. + * @param {Request} options.request The request. + * @param {string} options.cacheName Name of the cache the responses belong + * to. This is included in the broadcast message. + * @param {Event} options.event event The event that triggered + * this possible cache update. + * @return {Promise} Resolves once the update is sent. + */ + + + async notifyIfUpdated(options) { + { + assert_js.assert.isType(options.cacheName, 'string', { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'cacheName' + }); + assert_js.assert.isInstance(options.newResponse, Response, { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'newResponse' + }); + assert_js.assert.isInstance(options.request, Request, { + moduleName: 'workbox-broadcast-update', + className: 'BroadcastCacheUpdate', + funcName: 'notifyIfUpdated', + paramName: 'request' + }); + } // Without two responses there is nothing to compare. + + + if (!options.oldResponse) { + return; + } + + if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) { + { + logger_js.logger.log(`Newer response found (and cached) for:`, options.request.url); + } + + const messageData = { + type: CACHE_UPDATED_MESSAGE_TYPE, + meta: CACHE_UPDATED_MESSAGE_META, + payload: this._generatePayload(options) + }; // For navigation requests, wait until the new window client exists + // before sending the message + + if (options.request.mode === 'navigate') { + let resultingClientId; + + if (options.event instanceof FetchEvent) { + resultingClientId = options.event.resultingClientId; + } + + const resultingWin = await resultingClientExists_js.resultingClientExists(resultingClientId); // Safari does not currently implement postMessage buffering and + // there's no good way to feature detect that, so to increase the + // chances of the message being delivered in Safari, we add a timeout. + // We also do this if `resultingClientExists()` didn't return a client, + // which means it timed out, so it's worth waiting a bit longer. + + if (!resultingWin || isSafari) { + // 3500 is chosen because (according to CrUX data) 80% of mobile + // websites hit the DOMContentLoaded event in less than 3.5 seconds. + // And presumably sites implementing service worker are on the + // higher end of the performance spectrum. + await timeout_js.timeout(3500); + } + } + + if (this._notifyAllClients) { + const windows = await self.clients.matchAll({ + type: 'window' + }); + + for (const win of windows) { + win.postMessage(messageData); + } + } else { + // See https://github.com/GoogleChrome/workbox/issues/2895 + if (options.event instanceof FetchEvent) { + const client = await self.clients.get(options.event.clientId); + client === null || client === void 0 ? void 0 : client.postMessage(messageData); + } + } + } + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This plugin will automatically broadcast a message whenever a cached response + * is updated. + * + * @memberof workbox-broadcast-update + */ + + class BroadcastUpdatePlugin { + /** + * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with + * the passed options and calls its `notifyIfUpdated` method whenever the + * plugin's `cacheDidUpdate` callback is invoked. + * + * @param {Object} [options] + * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']] + * A list of headers that will be used to determine whether the responses + * differ. + * @param {string} [options.generatePayload] A function whose return value + * will be used as the `payload` field in any cache update messages sent + * to the window clients. + */ + constructor(options) { + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is + * added to a cache. + * + * @private + * @param {Object} options The input object to this function. + * @param {string} options.cacheName Name of the cache being updated. + * @param {Response} [options.oldResponse] The previous cached value, if any. + * @param {Response} options.newResponse The new value in the cache. + * @param {Request} options.request The request that triggered the update. + * @param {Request} options.event The event that triggered the update. + */ + this.cacheDidUpdate = async options => { + dontWaitFor_js.dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options)); + }; + + this._broadcastUpdate = new BroadcastCacheUpdate(options); + } + + } + + exports.BroadcastCacheUpdate = BroadcastCacheUpdate; + exports.BroadcastUpdatePlugin = BroadcastUpdatePlugin; + exports.responsesAreSame = responsesAreSame; + + return exports; + +}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private)); +//# sourceMappingURL=workbox-broadcast-update.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-broadcast-update.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-broadcast-update.dev.js.map new file mode 100644 index 0000000..42ac9e6 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-broadcast-update.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-broadcast-update.dev.js","sources":["../_version.js","../responsesAreSame.js","../utils/constants.js","../BroadcastCacheUpdate.js","../BroadcastUpdatePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:broadcast-update:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * Given two `Response's`, compares several header values to see if they are\n * the same or not.\n *\n * @param {Response} firstResponse\n * @param {Response} secondResponse\n * @param {Array} headersToCheck\n * @return {boolean}\n *\n * @memberof workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(firstResponse instanceof Response && secondResponse instanceof Response)) {\n throw new WorkboxError('invalid-responses-are-same-args');\n }\n }\n const atLeastOneHeaderAvailable = headersToCheck.some((header) => {\n return (firstResponse.headers.has(header) && secondResponse.headers.has(header));\n });\n if (!atLeastOneHeaderAvailable) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to determine where the response has been updated ` +\n `because none of the headers that would be checked are present.`);\n logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);\n }\n // Just return true, indicating the that responses are the same, since we\n // can't determine otherwise.\n return true;\n }\n return headersToCheck.every((header) => {\n const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header);\n const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header);\n return headerStateComparison && headerValueComparison;\n });\n};\nexport { responsesAreSame };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nexport const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED';\nexport const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update';\nexport const NOTIFY_ALL_CLIENTS = true;\nexport const DEFAULT_HEADERS_TO_CHECK = [\n 'content-length',\n 'etag',\n 'last-modified',\n];\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { responsesAreSame } from './responsesAreSame.js';\nimport { CACHE_UPDATED_MESSAGE_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS, } from './utils/constants.js';\nimport './_version.js';\n// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser\n// TODO(philipwalton): remove once this Safari bug fix has been released.\n// https://bugs.webkit.org/show_bug.cgi?id=201169\nconst isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n/**\n * Generates the default payload used in update messages. By default the\n * payload includes the `cacheName` and `updatedURL` fields.\n *\n * @return Object\n * @private\n */\nfunction defaultPayloadGenerator(data) {\n return {\n cacheName: data.cacheName,\n updatedURL: data.request.url,\n };\n}\n/**\n * Uses the `postMessage()` API to inform any open windows/tabs when a cached\n * response has been updated.\n *\n * For efficiency's sake, the underlying response bodies are not compared;\n * only specific response headers are checked.\n *\n * @memberof workbox-broadcast-update\n */\nclass BroadcastCacheUpdate {\n /**\n * Construct a BroadcastCacheUpdate instance with a specific `channelName` to\n * broadcast messages on\n *\n * @param {Object} [options]\n * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n * @param {boolean} [options.notifyAllClients=true] If true (the default) then\n * all open clients will receive a message. If false, then only the client\n * that make the original request will be notified of the update.\n */\n constructor({ generatePayload, headersToCheck, notifyAllClients, } = {}) {\n this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n this._generatePayload = generatePayload || defaultPayloadGenerator;\n this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS;\n }\n /**\n * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * and sends a message (via `postMessage()`) to all window clients if the\n * responses differ. Neither of the Responses can be\n * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n *\n * The message that's posted has the following format (where `payload` can\n * be customized via the `generatePayload` option the instance is created\n * with):\n *\n * ```\n * {\n * type: 'CACHE_UPDATED',\n * meta: 'workbox-broadcast-update',\n * payload: {\n * cacheName: 'the-cache-name',\n * updatedURL: 'https://example.com/'\n * }\n * }\n * ```\n *\n * @param {Object} options\n * @param {Response} [options.oldResponse] Cached response to compare.\n * @param {Response} options.newResponse Possibly updated response to compare.\n * @param {Request} options.request The request.\n * @param {string} options.cacheName Name of the cache the responses belong\n * to. This is included in the broadcast message.\n * @param {Event} options.event event The event that triggered\n * this possible cache update.\n * @return {Promise} Resolves once the update is sent.\n */\n async notifyIfUpdated(options) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(options.cacheName, 'string', {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'cacheName',\n });\n assert.isInstance(options.newResponse, Response, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'newResponse',\n });\n assert.isInstance(options.request, Request, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'request',\n });\n }\n // Without two responses there is nothing to compare.\n if (!options.oldResponse) {\n return;\n }\n if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Newer response found (and cached) for:`, options.request.url);\n }\n const messageData = {\n type: CACHE_UPDATED_MESSAGE_TYPE,\n meta: CACHE_UPDATED_MESSAGE_META,\n payload: this._generatePayload(options),\n };\n // For navigation requests, wait until the new window client exists\n // before sending the message\n if (options.request.mode === 'navigate') {\n let resultingClientId;\n if (options.event instanceof FetchEvent) {\n resultingClientId = options.event.resultingClientId;\n }\n const resultingWin = await resultingClientExists(resultingClientId);\n // Safari does not currently implement postMessage buffering and\n // there's no good way to feature detect that, so to increase the\n // chances of the message being delivered in Safari, we add a timeout.\n // We also do this if `resultingClientExists()` didn't return a client,\n // which means it timed out, so it's worth waiting a bit longer.\n if (!resultingWin || isSafari) {\n // 3500 is chosen because (according to CrUX data) 80% of mobile\n // websites hit the DOMContentLoaded event in less than 3.5 seconds.\n // And presumably sites implementing service worker are on the\n // higher end of the performance spectrum.\n await timeout(3500);\n }\n }\n if (this._notifyAllClients) {\n const windows = await self.clients.matchAll({ type: 'window' });\n for (const win of windows) {\n win.postMessage(messageData);\n }\n }\n else {\n // See https://github.com/GoogleChrome/workbox/issues/2895\n if (options.event instanceof FetchEvent) {\n const client = await self.clients.get(options.event.clientId);\n client === null || client === void 0 ? void 0 : client.postMessage(messageData);\n }\n }\n }\n }\n}\nexport { BroadcastCacheUpdate };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { BroadcastCacheUpdate, } from './BroadcastCacheUpdate.js';\nimport './_version.js';\n/**\n * This plugin will automatically broadcast a message whenever a cached response\n * is updated.\n *\n * @memberof workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n /**\n * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with\n * the passed options and calls its `notifyIfUpdated` method whenever the\n * plugin's `cacheDidUpdate` callback is invoked.\n *\n * @param {Object} [options]\n * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor(options) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is\n * added to a cache.\n *\n * @private\n * @param {Object} options The input object to this function.\n * @param {string} options.cacheName Name of the cache being updated.\n * @param {Response} [options.oldResponse] The previous cached value, if any.\n * @param {Response} options.newResponse The new value in the cache.\n * @param {Request} options.request The request that triggered the update.\n * @param {Request} options.event The event that triggered the update.\n */\n this.cacheDidUpdate = async (options) => {\n dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));\n };\n this._broadcastUpdate = new BroadcastCacheUpdate(options);\n }\n}\nexport { BroadcastUpdatePlugin };\n"],"names":["self","_","e","responsesAreSame","firstResponse","secondResponse","headersToCheck","Response","WorkboxError","atLeastOneHeaderAvailable","some","header","headers","has","logger","warn","debug","every","headerStateComparison","headerValueComparison","get","CACHE_UPDATED_MESSAGE_TYPE","CACHE_UPDATED_MESSAGE_META","NOTIFY_ALL_CLIENTS","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","notifyAllClients","_headersToCheck","_generatePayload","_notifyAllClients","notifyIfUpdated","options","assert","isType","moduleName","className","funcName","paramName","isInstance","newResponse","Request","oldResponse","log","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingWin","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","client","clientId","BroadcastUpdatePlugin","cacheDidUpdate","dontWaitFor","_broadcastUpdate"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,gCAAD,CAAJ,IAA0CC,CAAC,EAA3C;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;UACMC,gBAAgB,GAAG,CAACC,aAAD,EAAgBC,cAAhB,EAAgCC,cAAhC,KAAmD;IACxE,EAA2C;IACvC,QAAI,EAAEF,aAAa,YAAYG,QAAzB,IAAqCF,cAAc,YAAYE,QAAjE,CAAJ,EAAgF;IAC5E,YAAM,IAAIC,4BAAJ,CAAiB,iCAAjB,CAAN;IACH;IACJ;;IACD,QAAMC,yBAAyB,GAAGH,cAAc,CAACI,IAAf,CAAqBC,MAAD,IAAY;IAC9D,WAAQP,aAAa,CAACQ,OAAd,CAAsBC,GAAtB,CAA0BF,MAA1B,KAAqCN,cAAc,CAACO,OAAf,CAAuBC,GAAvB,CAA2BF,MAA3B,CAA7C;IACH,GAFiC,CAAlC;;IAGA,MAAI,CAACF,yBAAL,EAAgC;IAC5B,IAA2C;IACvCK,MAAAA,gBAAM,CAACC,IAAP,CAAa,0DAAD,GACP,gEADL;IAEAD,MAAAA,gBAAM,CAACE,KAAP,CAAc,uCAAd,EAAsDZ,aAAtD,EAAqEC,cAArE,EAA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ACmE,OAAL,CAAa/C,GAAb,CAAiBuB,OAAO,CAACkB,KAAR,CAAcW,QAA/B,CAArB;IACAD,UAAAA,MAAM,KAAK,IAAX,IAAmBA,MAAM,KAAK,KAAK,CAAnC,GAAuC,KAAK,CAA5C,GAAgDA,MAAM,CAACD,WAAP,CAAmBf,WAAnB,CAAhD;IACH;IACJ;IACJ;IACJ;;IAzHsB;;ICxC3B;IACA;AACA;IACA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;;IACA,MAAMkB,qBAAN,CAA4B;IACxB;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACIrC,EAAAA,WAAW,CAACO,OAAD,EAAU;IACjB;IACR;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACQ,SAAK+B,cAAL,GAAsB,MAAO/B,OAAP,IAAmB;IACrCgC,MAAAA,0BAAW,CAAC,KAAKC,gBAAL,CAAsBlC,eAAtB,CAAsCC,OAAtC,CAAD,CAAX;IACH,KAFD;;IAGA,SAAKiC,gBAAL,GAAwB,IAAIzC,oBAAJ,CAAyBQ,OAAzB,CAAxB;IACH;;IAhCuB;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-broadcast-update.prod.js b/src/Resources/workbox-v7.0.0/workbox-broadcast-update.prod.js new file mode 100644 index 0000000..cfcc416 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-broadcast-update.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.broadcastUpdate=function(t,s,a,e){"use strict";try{self["workbox:broadcast-update:7.0.0"]&&_()}catch(t){}const n=(t,s,a)=>!a.some((a=>t.headers.has(a)&&s.headers.has(a)))||a.every((a=>{const e=t.headers.has(a)===s.headers.has(a),n=t.headers.get(a)===s.headers.get(a);return e&&n})),i=["content-length","etag","last-modified"],o=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);function c(t){return{cacheName:t.cacheName,updatedURL:t.request.url}}class r{constructor({generatePayload:t,headersToCheck:s,notifyAllClients:a}={}){this.C=s||i,this.A=t||c,this.U=null==a||a}async notifyIfUpdated(t){if(t.oldResponse&&!n(t.oldResponse,t.newResponse,this.C)){const e={type:"CACHE_UPDATED",meta:"workbox-broadcast-update",payload:this.A(t)};if("navigate"===t.request.mode){let e;t.event instanceof FetchEvent&&(e=t.event.resultingClientId);await a.resultingClientExists(e)&&!o||await s.timeout(3500)}if(this.U){const t=await self.clients.matchAll({type:"window"});for(const s of t)s.postMessage(e)}else if(t.event instanceof FetchEvent){const s=await self.clients.get(t.event.clientId);null==s||s.postMessage(e)}}}}return t.BroadcastCacheUpdate=r,t.BroadcastUpdatePlugin=class{constructor(t){this.cacheDidUpdate=async t=>{e.dontWaitFor(this.F.notifyIfUpdated(t))},this.F=new r(t)}},t.responsesAreSame=n,t}({},workbox.core._private,workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-broadcast-update.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-broadcast-update.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-broadcast-update.prod.js.map new file mode 100644 index 0000000..0630d55 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-broadcast-update.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-broadcast-update.prod.js","sources":["../_version.js","../responsesAreSame.js","../utils/constants.js","../BroadcastCacheUpdate.js","../BroadcastUpdatePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:broadcast-update:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * Given two `Response's`, compares several header values to see if they are\n * the same or not.\n *\n * @param {Response} firstResponse\n * @param {Response} secondResponse\n * @param {Array} headersToCheck\n * @return {boolean}\n *\n * @memberof workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(firstResponse instanceof Response && secondResponse instanceof Response)) {\n throw new WorkboxError('invalid-responses-are-same-args');\n }\n }\n const atLeastOneHeaderAvailable = headersToCheck.some((header) => {\n return (firstResponse.headers.has(header) && secondResponse.headers.has(header));\n });\n if (!atLeastOneHeaderAvailable) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to determine where the response has been updated ` +\n `because none of the headers that would be checked are present.`);\n logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);\n }\n // Just return true, indicating the that responses are the same, since we\n // can't determine otherwise.\n return true;\n }\n return headersToCheck.every((header) => {\n const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header);\n const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header);\n return headerStateComparison && headerValueComparison;\n });\n};\nexport { responsesAreSame };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nexport const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED';\nexport const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update';\nexport const NOTIFY_ALL_CLIENTS = true;\nexport const DEFAULT_HEADERS_TO_CHECK = [\n 'content-length',\n 'etag',\n 'last-modified',\n];\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { responsesAreSame } from './responsesAreSame.js';\nimport { CACHE_UPDATED_MESSAGE_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS, } from './utils/constants.js';\nimport './_version.js';\n// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser\n// TODO(philipwalton): remove once this Safari bug fix has been released.\n// https://bugs.webkit.org/show_bug.cgi?id=201169\nconst isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n/**\n * Generates the default payload used in update messages. By default the\n * payload includes the `cacheName` and `updatedURL` fields.\n *\n * @return Object\n * @private\n */\nfunction defaultPayloadGenerator(data) {\n return {\n cacheName: data.cacheName,\n updatedURL: data.request.url,\n };\n}\n/**\n * Uses the `postMessage()` API to inform any open windows/tabs when a cached\n * response has been updated.\n *\n * For efficiency's sake, the underlying response bodies are not compared;\n * only specific response headers are checked.\n *\n * @memberof workbox-broadcast-update\n */\nclass BroadcastCacheUpdate {\n /**\n * Construct a BroadcastCacheUpdate instance with a specific `channelName` to\n * broadcast messages on\n *\n * @param {Object} [options]\n * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n * @param {boolean} [options.notifyAllClients=true] If true (the default) then\n * all open clients will receive a message. If false, then only the client\n * that make the original request will be notified of the update.\n */\n constructor({ generatePayload, headersToCheck, notifyAllClients, } = {}) {\n this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n this._generatePayload = generatePayload || defaultPayloadGenerator;\n this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS;\n }\n /**\n * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * and sends a message (via `postMessage()`) to all window clients if the\n * responses differ. Neither of the Responses can be\n * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n *\n * The message that's posted has the following format (where `payload` can\n * be customized via the `generatePayload` option the instance is created\n * with):\n *\n * ```\n * {\n * type: 'CACHE_UPDATED',\n * meta: 'workbox-broadcast-update',\n * payload: {\n * cacheName: 'the-cache-name',\n * updatedURL: 'https://example.com/'\n * }\n * }\n * ```\n *\n * @param {Object} options\n * @param {Response} [options.oldResponse] Cached response to compare.\n * @param {Response} options.newResponse Possibly updated response to compare.\n * @param {Request} options.request The request.\n * @param {string} options.cacheName Name of the cache the responses belong\n * to. This is included in the broadcast message.\n * @param {Event} options.event event The event that triggered\n * this possible cache update.\n * @return {Promise} Resolves once the update is sent.\n */\n async notifyIfUpdated(options) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(options.cacheName, 'string', {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'cacheName',\n });\n assert.isInstance(options.newResponse, Response, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'newResponse',\n });\n assert.isInstance(options.request, Request, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'request',\n });\n }\n // Without two responses there is nothing to compare.\n if (!options.oldResponse) {\n return;\n }\n if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Newer response found (and cached) for:`, options.request.url);\n }\n const messageData = {\n type: CACHE_UPDATED_MESSAGE_TYPE,\n meta: CACHE_UPDATED_MESSAGE_META,\n payload: this._generatePayload(options),\n };\n // For navigation requests, wait until the new window client exists\n // before sending the message\n if (options.request.mode === 'navigate') {\n let resultingClientId;\n if (options.event instanceof FetchEvent) {\n resultingClientId = options.event.resultingClientId;\n }\n const resultingWin = await resultingClientExists(resultingClientId);\n // Safari does not currently implement postMessage buffering and\n // there's no good way to feature detect that, so to increase the\n // chances of the message being delivered in Safari, we add a timeout.\n // We also do this if `resultingClientExists()` didn't return a client,\n // which means it timed out, so it's worth waiting a bit longer.\n if (!resultingWin || isSafari) {\n // 3500 is chosen because (according to CrUX data) 80% of mobile\n // websites hit the DOMContentLoaded event in less than 3.5 seconds.\n // And presumably sites implementing service worker are on the\n // higher end of the performance spectrum.\n await timeout(3500);\n }\n }\n if (this._notifyAllClients) {\n const windows = await self.clients.matchAll({ type: 'window' });\n for (const win of windows) {\n win.postMessage(messageData);\n }\n }\n else {\n // See https://github.com/GoogleChrome/workbox/issues/2895\n if (options.event instanceof FetchEvent) {\n const client = await self.clients.get(options.event.clientId);\n client === null || client === void 0 ? void 0 : client.postMessage(messageData);\n }\n }\n }\n }\n}\nexport { BroadcastCacheUpdate };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { BroadcastCacheUpdate, } from './BroadcastCacheUpdate.js';\nimport './_version.js';\n/**\n * This plugin will automatically broadcast a message whenever a cached response\n * is updated.\n *\n * @memberof workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n /**\n * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with\n * the passed options and calls its `notifyIfUpdated` method whenever the\n * plugin's `cacheDidUpdate` callback is invoked.\n *\n * @param {Object} [options]\n * @param {Array} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor(options) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is\n * added to a cache.\n *\n * @private\n * @param {Object} options The input object to this function.\n * @param {string} options.cacheName Name of the cache being updated.\n * @param {Response} [options.oldResponse] The previous cached value, if any.\n * @param {Response} options.newResponse The new value in the cache.\n * @param {Request} options.request The request that triggered the update.\n * @param {Request} options.event The event that triggered the update.\n */\n this.cacheDidUpdate = async (options) => {\n dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));\n };\n this._broadcastUpdate = new BroadcastCacheUpdate(options);\n }\n}\nexport { BroadcastUpdatePlugin };\n"],"names":["self","_","e","responsesAreSame","firstResponse","secondResponse","headersToCheck","some","header","headers","has","every","headerStateComparison","headerValueComparison","get","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","notifyAllClients","_headersToCheck","_generatePayload","_notifyAllClients","options","oldResponse","newResponse","this","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","client","clientId","cacheDidUpdate","async","dontWaitFor","_broadcastUpdate","notifyIfUpdated"],"mappings":"0FAEA,IACIA,KAAK,mCAAqCC,GAC7C,CACD,MAAOC,UCgBDC,EAAmB,CAACC,EAAeC,EAAgBC,KAMnBA,EAAeC,MAAMC,GAC3CJ,EAAcK,QAAQC,IAAIF,IAAWH,EAAeI,QAAQC,IAAIF,MAYrEF,EAAeK,OAAOH,UACnBI,EAAwBR,EAAcK,QAAQC,IAAIF,KAAYH,EAAeI,QAAQC,IAAIF,GACzFK,EAAwBT,EAAcK,QAAQK,IAAIN,KAAYH,EAAeI,QAAQK,IAAIN,UACxFI,GAAyBC,CAAhC,IChCKE,EAA2B,CACpC,iBACA,OACA,iBCGEC,EAAW,iCAAiCC,KAAKC,UAAUC,WAQjE,SAASC,EAAwBC,SACtB,CACHC,UAAWD,EAAKC,UAChBC,WAAYF,EAAKG,QAAQC,IAEhC,CAUD,MAAMC,EAgBFC,aAAYC,gBAAEA,EAAFtB,eAAmBA,EAAnBuB,iBAAmCA,GAAsB,SAC5DC,EAAkBxB,GAAkBS,OACpCgB,EAAmBH,GAAmBR,OACtCY,EAAoBH,SAA2DA,wBAiClEI,MAsBbA,EAAQC,cAGR/B,EAAiB8B,EAAQC,YAAaD,EAAQE,YAAaC,KAAKN,GAAkB,OAI7EO,EAAc,CAChBC,KDlH0B,gBCmH1BC,KDlH0B,2BCmH1BC,QAASJ,KAAKL,EAAiBE,OAIN,aAAzBA,EAAQT,QAAQiB,KAAqB,KACjCC,EACAT,EAAQU,iBAAiBC,aACzBF,EAAoBT,EAAQU,MAAMD,yBAEXG,wBAAsBH,KAM5B1B,SAKX8B,UAAQ,SAGlBV,KAAKJ,EAAmB,OAClBe,QAAgB/C,KAAKgD,QAAQC,SAAS,CAAEX,KAAM,eAC/C,MAAMY,KAAOH,EACdG,EAAIC,YAAYd,WAKhBJ,EAAQU,iBAAiBC,WAAY,OAC/BQ,QAAepD,KAAKgD,QAAQlC,IAAImB,EAAQU,MAAMU,UACpDD,SAAgDA,EAAOD,YAAYd,8DC7IvF,MAcIV,YAAYM,QAcHqB,eAAiBC,UAClBC,cAAYpB,KAAKqB,EAAiBC,gBAAgBzB,GAAlD,OAECwB,EAAmB,IAAI/B,EAAqBO"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-cacheable-response.dev.js b/src/Resources/workbox-v7.0.0/workbox-cacheable-response.dev.js new file mode 100644 index 0000000..7fb9f62 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-cacheable-response.dev.js @@ -0,0 +1,191 @@ +this.workbox = this.workbox || {}; +this.workbox.cacheableResponse = (function (exports, assert_js, WorkboxError_js, getFriendlyURL_js, logger_js) { + 'use strict'; + + try { + self['workbox:cacheable-response:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This class allows you to set up rules determining what + * status codes and/or headers need to be present in order for a + * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) + * to be considered cacheable. + * + * @memberof workbox-cacheable-response + */ + + class CacheableResponse { + /** + * To construct a new CacheableResponse instance you must provide at least + * one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config = {}) { + { + if (!(config.statuses || config.headers)) { + throw new WorkboxError_js.WorkboxError('statuses-or-headers-required', { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor' + }); + } + + if (config.statuses) { + assert_js.assert.isArray(config.statuses, { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + paramName: 'config.statuses' + }); + } + + if (config.headers) { + assert_js.assert.isType(config.headers, 'object', { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'constructor', + paramName: 'config.headers' + }); + } + } + + this._statuses = config.statuses; + this._headers = config.headers; + } + /** + * Checks a response to see whether it's cacheable or not, based on this + * object's configuration. + * + * @param {Response} response The response whose cacheability is being + * checked. + * @return {boolean} `true` if the `Response` is cacheable, and `false` + * otherwise. + */ + + + isResponseCacheable(response) { + { + assert_js.assert.isInstance(response, Response, { + moduleName: 'workbox-cacheable-response', + className: 'CacheableResponse', + funcName: 'isResponseCacheable', + paramName: 'response' + }); + } + + let cacheable = true; + + if (this._statuses) { + cacheable = this._statuses.includes(response.status); + } + + if (this._headers && cacheable) { + cacheable = Object.keys(this._headers).some(headerName => { + return response.headers.get(headerName) === this._headers[headerName]; + }); + } + + { + if (!cacheable) { + logger_js.logger.groupCollapsed(`The request for ` + `'${getFriendlyURL_js.getFriendlyURL(response.url)}' returned a response that does ` + `not meet the criteria for being cached.`); + logger_js.logger.groupCollapsed(`View cacheability criteria here.`); + logger_js.logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses)); + logger_js.logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2)); + logger_js.logger.groupEnd(); + const logFriendlyHeaders = {}; + response.headers.forEach((value, key) => { + logFriendlyHeaders[key] = value; + }); + logger_js.logger.groupCollapsed(`View response status and headers here.`); + logger_js.logger.log(`Response status: ${response.status}`); + logger_js.logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2)); + logger_js.logger.groupEnd(); + logger_js.logger.groupCollapsed(`View full response details here.`); + logger_js.logger.log(response.headers); + logger_js.logger.log(response); + logger_js.logger.groupEnd(); + logger_js.logger.groupEnd(); + } + } + + return cacheable; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it + * easier to add in cacheability checks to requests made via Workbox's built-in + * strategies. + * + * @memberof workbox-cacheable-response + */ + + class CacheableResponsePlugin { + /** + * To construct a new CacheableResponsePlugin instance you must provide at + * least one of the `config` properties. + * + * If both `statuses` and `headers` are specified, then both conditions must + * be met for the `Response` to be considered cacheable. + * + * @param {Object} config + * @param {Array} [config.statuses] One or more status codes that a + * `Response` can have and be considered cacheable. + * @param {Object} [config.headers] A mapping of header names + * and expected values that a `Response` can have and be considered cacheable. + * If multiple headers are provided, only one needs to be present. + */ + constructor(config) { + /** + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * @private + */ + this.cacheWillUpdate = async ({ + response + }) => { + if (this._cacheableResponse.isResponseCacheable(response)) { + return response; + } + + return null; + }; + + this._cacheableResponse = new CacheableResponse(config); + } + + } + + exports.CacheableResponse = CacheableResponse; + exports.CacheableResponsePlugin = CacheableResponsePlugin; + + return exports; + +}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private)); +//# sourceMappingURL=workbox-cacheable-response.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-cacheable-response.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-cacheable-response.dev.js.map new file mode 100644 index 0000000..a91f586 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-cacheable-response.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-cacheable-response.dev.js","sources":["../_version.js","../CacheableResponse.js","../CacheableResponsePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:cacheable-response:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * This class allows you to set up rules determining what\n * status codes and/or headers need to be present in order for a\n * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * to be considered cacheable.\n *\n * @memberof workbox-cacheable-response\n */\nclass CacheableResponse {\n /**\n * To construct a new CacheableResponse instance you must provide at least\n * one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.statuses || config.headers)) {\n throw new WorkboxError('statuses-or-headers-required', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n });\n }\n if (config.statuses) {\n assert.isArray(config.statuses, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.statuses',\n });\n }\n if (config.headers) {\n assert.isType(config.headers, 'object', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.headers',\n });\n }\n }\n this._statuses = config.statuses;\n this._headers = config.headers;\n }\n /**\n * Checks a response to see whether it's cacheable or not, based on this\n * object's configuration.\n *\n * @param {Response} response The response whose cacheability is being\n * checked.\n * @return {boolean} `true` if the `Response` is cacheable, and `false`\n * otherwise.\n */\n isResponseCacheable(response) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(response, Response, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'isResponseCacheable',\n paramName: 'response',\n });\n }\n let cacheable = true;\n if (this._statuses) {\n cacheable = this._statuses.includes(response.status);\n }\n if (this._headers && cacheable) {\n cacheable = Object.keys(this._headers).some((headerName) => {\n return response.headers.get(headerName) === this._headers[headerName];\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n if (!cacheable) {\n logger.groupCollapsed(`The request for ` +\n `'${getFriendlyURL(response.url)}' returned a response that does ` +\n `not meet the criteria for being cached.`);\n logger.groupCollapsed(`View cacheability criteria here.`);\n logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses));\n logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2));\n logger.groupEnd();\n const logFriendlyHeaders = {};\n response.headers.forEach((value, key) => {\n logFriendlyHeaders[key] = value;\n });\n logger.groupCollapsed(`View response status and headers here.`);\n logger.log(`Response status: ${response.status}`);\n logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2));\n logger.groupEnd();\n logger.groupCollapsed(`View full response details here.`);\n logger.log(response.headers);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n }\n return cacheable;\n }\n}\nexport { CacheableResponse };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { CacheableResponse, } from './CacheableResponse.js';\nimport './_version.js';\n/**\n * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it\n * easier to add in cacheability checks to requests made via Workbox's built-in\n * strategies.\n *\n * @memberof workbox-cacheable-response\n */\nclass CacheableResponsePlugin {\n /**\n * To construct a new CacheableResponsePlugin instance you must provide at\n * least one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config) {\n /**\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n * @private\n */\n this.cacheWillUpdate = async ({ response }) => {\n if (this._cacheableResponse.isResponseCacheable(response)) {\n return response;\n }\n return null;\n };\n this._cacheableResponse = new CacheableResponse(config);\n }\n}\nexport { CacheableResponsePlugin };\n"],"names":["self","_","e","CacheableResponse","constructor","config","statuses","headers","WorkboxError","moduleName","className","funcName","assert","isArray","paramName","isType","_statuses","_headers","isResponseCacheable","response","isInstance","Response","cacheable","includes","status","Object","keys","some","headerName","get","logger","groupCollapsed","getFriendlyURL","url","log","JSON","stringify","groupEnd","logFriendlyHeaders","forEach","value","key","CacheableResponsePlugin","cacheWillUpdate","_cacheableResponse"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,kCAAD,CAAJ,IAA4CC,CAAC,EAA7C;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAMA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,MAAMC,iBAAN,CAAwB;IACpB;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACIC,EAAAA,WAAW,CAACC,MAAM,GAAG,EAAV,EAAc;IACrB,IAA2C;IACvC,UAAI,EAAEA,MAAM,CAACC,QAAP,IAAmBD,MAAM,CAACE,OAA5B,CAAJ,EAA0C;IACtC,cAAM,IAAIC,4BA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AAzC,CAAlC;IACAR,QAAAA,gBAAM,CAACO,QAAP;IACAP,QAAAA,gBAAM,CAACC,cAAP,CAAuB,kCAAvB;IACAD,QAAAA,gBAAM,CAACI,GAAP,CAAWf,QAAQ,CAACZ,OAApB;IACAuB,QAAAA,gBAAM,CAACI,GAAP,CAAWf,QAAX;IACAW,QAAAA,gBAAM,CAACO,QAAP;IACAP,QAAAA,gBAAM,CAACO,QAAP;IACH;IACJ;;IACD,WAAOf,SAAP;IACH;;IAhGmB;;ICpBxB;IACA;AACA;IACA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,MAAMoB,uBAAN,CAA8B;IAC1B;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACItC,EAAAA,WAAW,CAACC,MAAD,EAAS;IAChB;IACR;IACA;IACA;IACA;IACA;IACQ,SAAKsC,eAAL,GAAuB,OAAO;IAAExB,MAAAA;IAAF,KAAP,KAAwB;IAC3C,UAAI,KAAKyB,kBAAL,CAAwB1B,mBAAxB,CAA4CC,QAA5C,CAAJ,EAA2D;IACvD,eAAOA,QAAP;IACH;;IACD,aAAO,IAAP;IACH,KALD;;IAMA,SAAKyB,kBAAL,GAA0B,IAAIzC,iBAAJ,CAAsBE,MAAtB,CAA1B;IACH;;IA7ByB;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-cacheable-response.prod.js b/src/Resources/workbox-v7.0.0/workbox-cacheable-response.prod.js new file mode 100644 index 0000000..ac93b5b --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-cacheable-response.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.cacheableResponse=function(s){"use strict";try{self["workbox:cacheable-response:7.0.0"]&&_()}catch(s){}class t{constructor(s={}){this.O=s.statuses,this._=s.headers}isResponseCacheable(s){let t=!0;return this.O&&(t=this.O.includes(s.status)),this._&&t&&(t=Object.keys(this._).some((t=>s.headers.get(t)===this._[t]))),t}}return s.CacheableResponse=t,s.CacheableResponsePlugin=class{constructor(s){this.cacheWillUpdate=async({response:s})=>this.G.isResponseCacheable(s)?s:null,this.G=new t(s)}},s}({}); +//# sourceMappingURL=workbox-cacheable-response.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-cacheable-response.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-cacheable-response.prod.js.map new file mode 100644 index 0000000..bc998ca --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-cacheable-response.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-cacheable-response.prod.js","sources":["../_version.js","../CacheableResponse.js","../CacheableResponsePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:cacheable-response:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * This class allows you to set up rules determining what\n * status codes and/or headers need to be present in order for a\n * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * to be considered cacheable.\n *\n * @memberof workbox-cacheable-response\n */\nclass CacheableResponse {\n /**\n * To construct a new CacheableResponse instance you must provide at least\n * one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.statuses || config.headers)) {\n throw new WorkboxError('statuses-or-headers-required', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n });\n }\n if (config.statuses) {\n assert.isArray(config.statuses, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.statuses',\n });\n }\n if (config.headers) {\n assert.isType(config.headers, 'object', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.headers',\n });\n }\n }\n this._statuses = config.statuses;\n this._headers = config.headers;\n }\n /**\n * Checks a response to see whether it's cacheable or not, based on this\n * object's configuration.\n *\n * @param {Response} response The response whose cacheability is being\n * checked.\n * @return {boolean} `true` if the `Response` is cacheable, and `false`\n * otherwise.\n */\n isResponseCacheable(response) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(response, Response, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'isResponseCacheable',\n paramName: 'response',\n });\n }\n let cacheable = true;\n if (this._statuses) {\n cacheable = this._statuses.includes(response.status);\n }\n if (this._headers && cacheable) {\n cacheable = Object.keys(this._headers).some((headerName) => {\n return response.headers.get(headerName) === this._headers[headerName];\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n if (!cacheable) {\n logger.groupCollapsed(`The request for ` +\n `'${getFriendlyURL(response.url)}' returned a response that does ` +\n `not meet the criteria for being cached.`);\n logger.groupCollapsed(`View cacheability criteria here.`);\n logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses));\n logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2));\n logger.groupEnd();\n const logFriendlyHeaders = {};\n response.headers.forEach((value, key) => {\n logFriendlyHeaders[key] = value;\n });\n logger.groupCollapsed(`View response status and headers here.`);\n logger.log(`Response status: ${response.status}`);\n logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2));\n logger.groupEnd();\n logger.groupCollapsed(`View full response details here.`);\n logger.log(response.headers);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n }\n return cacheable;\n }\n}\nexport { CacheableResponse };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { CacheableResponse, } from './CacheableResponse.js';\nimport './_version.js';\n/**\n * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it\n * easier to add in cacheability checks to requests made via Workbox's built-in\n * strategies.\n *\n * @memberof workbox-cacheable-response\n */\nclass CacheableResponsePlugin {\n /**\n * To construct a new CacheableResponsePlugin instance you must provide at\n * least one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config) {\n /**\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n * @private\n */\n this.cacheWillUpdate = async ({ response }) => {\n if (this._cacheableResponse.isResponseCacheable(response)) {\n return response;\n }\n return null;\n };\n this._cacheableResponse = new CacheableResponse(config);\n }\n}\nexport { CacheableResponsePlugin };\n"],"names":["self","_","e","CacheableResponse","constructor","config","_statuses","statuses","_headers","headers","isResponseCacheable","response","cacheable","this","includes","status","Object","keys","some","headerName","get","cacheWillUpdate","async","_cacheableResponse"],"mappings":"sFAEA,IACIA,KAAK,qCAAuCC,GAC/C,CACD,MAAOC,ICeP,MAAMC,EAeFC,YAAYC,EAAS,SA0BZC,EAAYD,EAAOE,cACnBC,EAAWH,EAAOI,QAW3BC,oBAAoBC,OASZC,GAAY,SACZC,KAAKP,IACLM,EAAYC,KAAKP,EAAUQ,SAASH,EAASI,SAE7CF,KAAKL,GAAYI,IACjBA,EAAYI,OAAOC,KAAKJ,KAAKL,GAAUU,MAAMC,GAClCR,EAASF,QAAQW,IAAID,KAAgBN,KAAKL,EAASW,MA2B3DP,0DCnGf,MAeIR,YAAYC,QAOHgB,gBAAkBC,OAASX,cACxBE,KAAKU,EAAmBb,oBAAoBC,GACrCA,EAEJ,UAENY,EAAqB,IAAIpB,EAAkBE"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-core.dev.js b/src/Resources/workbox-v7.0.0/workbox-core.dev.js new file mode 100644 index 0000000..a0f975d --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-core.dev.js @@ -0,0 +1,1155 @@ +this.workbox = this.workbox || {}; +this.workbox.core = (function (exports) { + 'use strict'; + + try { + self['workbox:core:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const logger = (() => { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + + let inGroup = false; + const methodToColorMap = { + debug: `#7f8c8d`, + log: `#2ecc71`, + warn: `#f39c12`, + error: `#c0392b`, + groupCollapsed: `#3498db`, + groupEnd: null // No colored prefix on groupEnd + + }; + + const print = function (method, args) { + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + console[method](...args); + return; + } + } + + const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`]; // When in a group, the workbox prefix is not displayed. + + const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + console[method](...logPrefix, ...args); + + if (method === 'groupCollapsed') { + inGroup = true; + } + + if (method === 'groupEnd') { + inGroup = false; + } + }; // eslint-disable-next-line @typescript-eslint/ban-types + + + const api = {}; + const loggerMethods = Object.keys(methodToColorMap); + + for (const key of loggerMethods) { + const method = key; + + api[method] = (...args) => { + print(method, args); + }; + } + + return api; + })(); + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const messages = { + 'invalid-value': ({ + paramName, + validValueDescription, + value + }) => { + if (!paramName || !validValueDescription) { + throw new Error(`Unexpected input to 'invalid-value' error.`); + } + + return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`; + }, + 'not-an-array': ({ + moduleName, + className, + funcName, + paramName + }) => { + if (!moduleName || !className || !funcName || !paramName) { + throw new Error(`Unexpected input to 'not-an-array' error.`); + } + + return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`; + }, + 'incorrect-type': ({ + expectedType, + paramName, + moduleName, + className, + funcName + }) => { + if (!expectedType || !paramName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'incorrect-type' error.`); + } + + const classNameStr = className ? `${className}.` : ''; + return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.`; + }, + 'incorrect-class': ({ + expectedClassName, + paramName, + moduleName, + className, + funcName, + isReturnValueProblem + }) => { + if (!expectedClassName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'incorrect-class' error.`); + } + + const classNameStr = className ? `${className}.` : ''; + + if (isReturnValueProblem) { + return `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`; + } + + return `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.`; + }, + 'missing-a-method': ({ + expectedMethod, + paramName, + moduleName, + className, + funcName + }) => { + if (!expectedMethod || !paramName || !moduleName || !className || !funcName) { + throw new Error(`Unexpected input to 'missing-a-method' error.`); + } + + return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`; + }, + 'add-to-cache-list-unexpected-type': ({ + entry + }) => { + return `An unexpected entry was passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`; + }, + 'add-to-cache-list-conflicting-entries': ({ + firstEntry, + secondEntry + }) => { + if (!firstEntry || !secondEntry) { + throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`); + } + + return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry} but different revision details. Workbox is ` + `unable to cache and version the asset correctly. Please remove one ` + `of the entries.`; + }, + 'plugin-error-request-will-fetch': ({ + thrownErrorMessage + }) => { + if (!thrownErrorMessage) { + throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`); + } + + return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.`; + }, + 'invalid-cache-name': ({ + cacheNameId, + value + }) => { + if (!cacheNameId) { + throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`); + } + + return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`; + }, + 'unregister-route-but-not-found-with-method': ({ + method + }) => { + if (!method) { + throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`); + } + + return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`; + }, + 'unregister-route-route-not-registered': () => { + return `The route you're trying to unregister was not previously ` + `registered.`; + }, + 'queue-replay-failed': ({ + name + }) => { + return `Replaying the background sync queue '${name}' failed.`; + }, + 'duplicate-queue-name': ({ + name + }) => { + return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`; + }, + 'expired-test-without-max-age': ({ + methodName, + paramName + }) => { + return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`; + }, + 'unsupported-route-type': ({ + moduleName, + className, + funcName, + paramName + }) => { + return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`; + }, + 'not-array-of-class': ({ + value, + expectedClass, + moduleName, + className, + funcName, + paramName + }) => { + return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`; + }, + 'max-entries-or-age-required': ({ + moduleName, + className, + funcName + }) => { + return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`; + }, + 'statuses-or-headers-required': ({ + moduleName, + className, + funcName + }) => { + return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`; + }, + 'invalid-string': ({ + moduleName, + funcName, + paramName + }) => { + if (!paramName || !moduleName || !funcName) { + throw new Error(`Unexpected input to 'invalid-string' error.`); + } + + return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.`; + }, + 'channel-name-required': () => { + return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`; + }, + 'invalid-responses-are-same-args': () => { + return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`; + }, + 'expire-custom-caches-only': () => { + return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`; + }, + 'unit-must-be-bytes': ({ + normalizedRangeHeader + }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`); + } + + return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`; + }, + 'single-range-only': ({ + normalizedRangeHeader + }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'single-range-only' error.`); + } + + return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`; + }, + 'invalid-range-values': ({ + normalizedRangeHeader + }) => { + if (!normalizedRangeHeader) { + throw new Error(`Unexpected input to 'invalid-range-values' error.`); + } + + return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`; + }, + 'no-range-header': () => { + return `No Range header was found in the Request provided.`; + }, + 'range-not-satisfiable': ({ + size, + start, + end + }) => { + return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`; + }, + 'attempt-to-cache-non-get-request': ({ + url, + method + }) => { + return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`; + }, + 'cache-put-with-no-response': ({ + url + }) => { + return `There was an attempt to cache '${url}' but the response was not ` + `defined.`; + }, + 'no-response': ({ + url, + error + }) => { + let message = `The strategy could not generate a response for '${url}'.`; + + if (error) { + message += ` The underlying error is ${error}.`; + } + + return message; + }, + 'bad-precaching-response': ({ + url, + status + }) => { + return `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`); + }, + 'non-precached-url': ({ + url + }) => { + return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`; + }, + 'add-to-cache-list-conflicting-integrities': ({ + url + }) => { + return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`; + }, + 'missing-precache-entry': ({ + cacheName, + url + }) => { + return `Unable to find a precached response in ${cacheName} for ${url}.`; + }, + 'cross-origin-copy-response': ({ + origin + }) => { + return `workbox-core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.`; + }, + 'opaque-streams-source': ({ + type + }) => { + const message = `One of the workbox-streams sources resulted in an ` + `'${type}' response.`; + + if (type === 'opaqueredirect') { + return `${message} Please do not use a navigation request that results ` + `in a redirect as a source.`; + } + + return `${message} Please ensure your sources are CORS-enabled.`; + } + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + + const generatorFunction = (code, details = {}) => { + const message = messages[code]; + + if (!message) { + throw new Error(`Unable to find message for code '${code}'.`); + } + + return message(details); + }; + + const messageGenerator = generatorFunction; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Workbox errors should be thrown with this class. + * This allows use to ensure the type easily in tests, + * helps developers identify errors from workbox + * easily and allows use to optimise error + * messages correctly. + * + * @private + */ + + class WorkboxError extends Error { + /** + * + * @param {string} errorCode The error code that + * identifies this particular error. + * @param {Object=} details Any relevant arguments + * that will help developers identify issues should + * be added as a key on the context object. + */ + constructor(errorCode, details) { + const message = messageGenerator(errorCode, details); + super(message); + this.name = errorCode; + this.details = details; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /* + * This method throws if the supplied value is not an array. + * The destructed values are required to produce a meaningful error for users. + * The destructed and restructured object is so it's clear what is + * needed. + */ + + const isArray = (value, details) => { + if (!Array.isArray(value)) { + throw new WorkboxError('not-an-array', details); + } + }; + + const hasMethod = (object, expectedMethod, details) => { + const type = typeof object[expectedMethod]; + + if (type !== 'function') { + details['expectedMethod'] = expectedMethod; + throw new WorkboxError('missing-a-method', details); + } + }; + + const isType = (object, expectedType, details) => { + if (typeof object !== expectedType) { + details['expectedType'] = expectedType; + throw new WorkboxError('incorrect-type', details); + } + }; + + const isInstance = (object, // Need the general type to do the check later. + // eslint-disable-next-line @typescript-eslint/ban-types + expectedClass, details) => { + if (!(object instanceof expectedClass)) { + details['expectedClassName'] = expectedClass.name; + throw new WorkboxError('incorrect-class', details); + } + }; + + const isOneOf = (value, validValues, details) => { + if (!validValues.includes(value)) { + details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`; + throw new WorkboxError('invalid-value', details); + } + }; + + const isArrayOfClass = (value, // Need general type to do check later. + expectedClass, // eslint-disable-line + details) => { + const error = new WorkboxError('not-array-of-class', details); + + if (!Array.isArray(value)) { + throw error; + } + + for (const item of value) { + if (!(item instanceof expectedClass)) { + throw error; + } + } + }; + + const finalAssertExports = { + hasMethod, + isArray, + isInstance, + isOneOf, + isType, + isArrayOfClass + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + // Can't change Function type right now. + // eslint-disable-next-line @typescript-eslint/ban-types + + const quotaErrorCallbacks = new Set(); + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Adds a function to the set of quotaErrorCallbacks that will be executed if + * there's a quota error. + * + * @param {Function} callback + * @memberof workbox-core + */ + // Can't change Function type + // eslint-disable-next-line @typescript-eslint/ban-types + + function registerQuotaErrorCallback(callback) { + { + finalAssertExports.isType(callback, 'function', { + moduleName: 'workbox-core', + funcName: 'register', + paramName: 'callback' + }); + } + + quotaErrorCallbacks.add(callback); + + { + logger.log('Registered a callback to respond to quota errors.', callback); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const _cacheNameDetails = { + googleAnalytics: 'googleAnalytics', + precache: 'precache-v2', + prefix: 'workbox', + runtime: 'runtime', + suffix: typeof registration !== 'undefined' ? registration.scope : '' + }; + + const _createCacheName = cacheName => { + return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-'); + }; + + const eachCacheNameDetail = fn => { + for (const key of Object.keys(_cacheNameDetails)) { + fn(key); + } + }; + + const cacheNames$1 = { + updateDetails: details => { + eachCacheNameDetail(key => { + if (typeof details[key] === 'string') { + _cacheNameDetails[key] = details[key]; + } + }); + }, + getGoogleAnalyticsName: userCacheName => { + return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics); + }, + getPrecacheName: userCacheName => { + return userCacheName || _createCacheName(_cacheNameDetails.precache); + }, + getPrefix: () => { + return _cacheNameDetails.prefix; + }, + getRuntimeName: userCacheName => { + return userCacheName || _createCacheName(_cacheNameDetails.runtime); + }, + getSuffix: () => { + return _cacheNameDetails.suffix; + } + }; + + /* + Copyright 2020 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + + function stripParams(fullURL, ignoreParams) { + const strippedURL = new URL(fullURL); + + for (const param of ignoreParams) { + strippedURL.searchParams.delete(param); + } + + return strippedURL.href; + } + /** + * Matches an item in the cache, ignoring specific URL params. This is similar + * to the `ignoreSearch` option, but it allows you to ignore just specific + * params (while continuing to match on the others). + * + * @private + * @param {Cache} cache + * @param {Request} request + * @param {Object} matchOptions + * @param {Array} ignoreParams + * @return {Promise} + */ + + + async function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) { + const strippedRequestURL = stripParams(request.url, ignoreParams); // If the request doesn't include any ignored params, match as normal. + + if (request.url === strippedRequestURL) { + return cache.match(request, matchOptions); + } // Otherwise, match by comparing keys + + + const keysOptions = Object.assign(Object.assign({}, matchOptions), { + ignoreSearch: true + }); + const cacheKeys = await cache.keys(request, keysOptions); + + for (const cacheKey of cacheKeys) { + const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams); + + if (strippedRequestURL === strippedCacheKeyURL) { + return cache.match(cacheKey, matchOptions); + } + } + + return; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + let supportStatus$1; + /** + * A utility function that determines whether the current browser supports + * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * object. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `ReadableStream`, `false` otherwise. + * + * @private + */ + + function canConstructReadableStream() { + if (supportStatus$1 === undefined) { + // See https://github.com/GoogleChrome/workbox/issues/1473 + try { + new ReadableStream({ + start() {} + + }); + supportStatus$1 = true; + } catch (error) { + supportStatus$1 = false; + } + } + + return supportStatus$1; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + let supportStatus; + /** + * A utility function that determines whether the current browser supports + * constructing a new `Response` from a `response.body` stream. + * + * @return {boolean} `true`, if the current browser can successfully + * construct a `Response` from a `response.body` stream, `false` otherwise. + * + * @private + */ + + function canConstructResponseFromBodyStream() { + if (supportStatus === undefined) { + const testResponse = new Response(''); + + if ('body' in testResponse) { + try { + new Response(testResponse.body); + supportStatus = true; + } catch (error) { + supportStatus = false; + } + } + + supportStatus = false; + } + + return supportStatus; + } + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ + + function dontWaitFor(promise) { + // Effective no-op. + void promise.then(() => {}); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ + + class Deferred { + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Runs all of the callback functions, one at a time sequentially, in the order + * in which they were registered. + * + * @memberof workbox-core + * @private + */ + + async function executeQuotaErrorCallbacks() { + { + logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`); + } + + for (const callback of quotaErrorCallbacks) { + await callback(); + + { + logger.log(callback, 'is complete.'); + } + } + + { + logger.log('Finished running callbacks.'); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + + const getFriendlyURL = url => { + const urlObj = new URL(String(url), location.href); // See https://github.com/GoogleChrome/workbox/issues/2323 + // We want to include everything, except for the origin if it's same-origin. + + return urlObj.href.replace(new RegExp(`^${location.origin}`), ''); + }; + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Returns a promise that resolves and the passed number of milliseconds. + * This utility is an async/await-friendly version of `setTimeout`. + * + * @param {number} ms + * @return {Promise} + * @private + */ + + function timeout(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const MAX_RETRY_TIME = 2000; + /** + * Returns a promise that resolves to a window client matching the passed + * `resultingClientId`. For browsers that don't support `resultingClientId` + * or if waiting for the resulting client to apper takes too long, resolve to + * `undefined`. + * + * @param {string} [resultingClientId] + * @return {Promise} + * @private + */ + + async function resultingClientExists(resultingClientId) { + if (!resultingClientId) { + return; + } + + let existingWindows = await self.clients.matchAll({ + type: 'window' + }); + const existingWindowIds = new Set(existingWindows.map(w => w.id)); + let resultingWindow; + const startTime = performance.now(); // Only wait up to `MAX_RETRY_TIME` to find a matching client. + + while (performance.now() - startTime < MAX_RETRY_TIME) { + existingWindows = await self.clients.matchAll({ + type: 'window' + }); + resultingWindow = existingWindows.find(w => { + if (resultingClientId) { + // If we have a `resultingClientId`, we can match on that. + return w.id === resultingClientId; + } else { + // Otherwise match on finding a window not in `existingWindowIds`. + return !existingWindowIds.has(w.id); + } + }); + + if (resultingWindow) { + break; + } // Sleep for 100ms and retry. + + + await timeout(100); + } + + return resultingWindow; + } + + /* + Copyright 2020 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A utility method that makes it easier to use `event.waitUntil` with + * async functions and return the result. + * + * @param {ExtendableEvent} event + * @param {Function} asyncFn + * @return {Function} + * @private + */ + + function waitUntil(event, asyncFn) { + const returnPromise = asyncFn(); + event.waitUntil(returnPromise); + return returnPromise; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + + var _private = /*#__PURE__*/Object.freeze({ + __proto__: null, + assert: finalAssertExports, + cacheMatchIgnoreParams: cacheMatchIgnoreParams, + cacheNames: cacheNames$1, + canConstructReadableStream: canConstructReadableStream, + canConstructResponseFromBodyStream: canConstructResponseFromBodyStream, + dontWaitFor: dontWaitFor, + Deferred: Deferred, + executeQuotaErrorCallbacks: executeQuotaErrorCallbacks, + getFriendlyURL: getFriendlyURL, + logger: logger, + resultingClientExists: resultingClientExists, + timeout: timeout, + waitUntil: waitUntil, + WorkboxError: WorkboxError + }); + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Get the current cache names and prefix/suffix used by Workbox. + * + * `cacheNames.precache` is used for precached assets, + * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to + * store `analytics.js`, and `cacheNames.runtime` is used for everything else. + * + * `cacheNames.prefix` can be used to retrieve just the current prefix value. + * `cacheNames.suffix` can be used to retrieve just the current suffix value. + * + * @return {Object} An object with `precache`, `runtime`, `prefix`, and + * `googleAnalytics` properties. + * + * @memberof workbox-core + */ + + const cacheNames = { + get googleAnalytics() { + return cacheNames$1.getGoogleAnalyticsName(); + }, + + get precache() { + return cacheNames$1.getPrecacheName(); + }, + + get prefix() { + return cacheNames$1.getPrefix(); + }, + + get runtime() { + return cacheNames$1.getRuntimeName(); + }, + + get suffix() { + return cacheNames$1.getSuffix(); + } + + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Allows developers to copy a response and modify its `headers`, `status`, + * or `statusText` values (the values settable via a + * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax} + * object in the constructor). + * To modify these values, pass a function as the second argument. That + * function will be invoked with a single object with the response properties + * `{headers, status, statusText}`. The return value of this function will + * be used as the `ResponseInit` for the new `Response`. To change the values + * either modify the passed parameter(s) and return it, or return a totally + * new object. + * + * This method is intentionally limited to same-origin responses, regardless of + * whether CORS was used or not. + * + * @param {Response} response + * @param {Function} modifier + * @memberof workbox-core + */ + + async function copyResponse(response, modifier) { + let origin = null; // If response.url isn't set, assume it's cross-origin and keep origin null. + + if (response.url) { + const responseURL = new URL(response.url); + origin = responseURL.origin; + } + + if (origin !== self.location.origin) { + throw new WorkboxError('cross-origin-copy-response', { + origin + }); + } + + const clonedResponse = response.clone(); // Create a fresh `ResponseInit` object by cloning the headers. + + const responseInit = { + headers: new Headers(clonedResponse.headers), + status: clonedResponse.status, + statusText: clonedResponse.statusText + }; // Apply any user modifications. + + const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit; // Create the new response from the body stream and `ResponseInit` + // modifications. Note: not all browsers support the Response.body stream, + // so fall back to reading the entire body into memory as a blob. + + const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob(); + return new Response(body, modifiedResponseInit); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Claim any currently available clients once the service worker + * becomes active. This is normally used in conjunction with `skipWaiting()`. + * + * @memberof workbox-core + */ + + function clientsClaim() { + self.addEventListener('activate', () => self.clients.claim()); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Modifies the default cache names used by the Workbox packages. + * Cache names are generated as `--`. + * + * @param {Object} details + * @param {Object} [details.prefix] The string to add to the beginning of + * the precache and runtime cache names. + * @param {Object} [details.suffix] The string to add to the end of + * the precache and runtime cache names. + * @param {Object} [details.precache] The cache name to use for precache + * caching. + * @param {Object} [details.runtime] The cache name to use for runtime caching. + * @param {Object} [details.googleAnalytics] The cache name to use for + * `workbox-google-analytics` caching. + * + * @memberof workbox-core + */ + + function setCacheNameDetails(details) { + { + Object.keys(details).forEach(key => { + finalAssertExports.isType(details[key], 'string', { + moduleName: 'workbox-core', + funcName: 'setCacheNameDetails', + paramName: `details.${key}` + }); + }); + + if ('precache' in details && details['precache'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'precache', + value: details['precache'] + }); + } + + if ('runtime' in details && details['runtime'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'runtime', + value: details['runtime'] + }); + } + + if ('googleAnalytics' in details && details['googleAnalytics'].length === 0) { + throw new WorkboxError('invalid-cache-name', { + cacheNameId: 'googleAnalytics', + value: details['googleAnalytics'] + }); + } + } + + cacheNames$1.updateDetails(details); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This method is deprecated, and will be removed in Workbox v7. + * + * Calling self.skipWaiting() is equivalent, and should be used instead. + * + * @memberof workbox-core + */ + + function skipWaiting() { + // Just call self.skipWaiting() directly. + // See https://github.com/GoogleChrome/workbox/issues/2525 + { + logger.warn(`skipWaiting() from workbox-core is no longer recommended ` + `and will be removed in Workbox v7. Using self.skipWaiting() instead ` + `is equivalent.`); + } + + void self.skipWaiting(); + } + + exports._private = _private; + exports.cacheNames = cacheNames; + exports.clientsClaim = clientsClaim; + exports.copyResponse = copyResponse; + exports.registerQuotaErrorCallback = registerQuotaErrorCallback; + exports.setCacheNameDetails = setCacheNameDetails; + exports.skipWaiting = skipWaiting; + + return exports; + +}({})); +//# sourceMappingURL=workbox-core.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-core.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-core.dev.js.map new file mode 100644 index 0000000..0157a97 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-core.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-core.dev.js","sources":["../_version.js","../_private/logger.js","../models/messages/messages.js","../models/messages/messageGenerator.js","../_private/WorkboxError.js","../_private/assert.js","../models/quotaErrorCallbacks.js","../registerQuotaErrorCallback.js","../_private/cacheNames.js","../_private/cacheMatchIgnoreParams.js","../_private/canConstructReadableStream.js","../_private/canConstructResponseFromBodyStream.js","../_private/dontWaitFor.js","../_private/Deferred.js","../_private/executeQuotaErrorCallbacks.js","../_private/getFriendlyURL.js","../_private/timeout.js","../_private/resultingClientExists.js","../_private/waitUntil.js","../_private.js","../cacheNames.js","../copyResponse.js","../clientsClaim.js","../setCacheNameDetails.js","../skipWaiting.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../../_version.js';\nexport const messages = {\n 'invalid-value': ({ paramName, validValueDescription, value }) => {\n if (!paramName || !validValueDescription) {\n throw new Error(`Unexpected input to 'invalid-value' error.`);\n }\n return (`The '${paramName}' parameter was given a value with an ` +\n `unexpected value. ${validValueDescription} Received a value of ` +\n `${JSON.stringify(value)}.`);\n },\n 'not-an-array': ({ moduleName, className, funcName, paramName }) => {\n if (!moduleName || !className || !funcName || !paramName) {\n throw new Error(`Unexpected input to 'not-an-array' error.`);\n }\n return (`The parameter '${paramName}' passed into ` +\n `'${moduleName}.${className}.${funcName}()' must be an array.`);\n },\n 'incorrect-type': ({ expectedType, paramName, moduleName, className, funcName, }) => {\n if (!expectedType || !paramName || !moduleName || !funcName) {\n throw new Error(`Unexpected input to 'incorrect-type' error.`);\n }\n const classNameStr = className ? `${className}.` : '';\n return (`The parameter '${paramName}' passed into ` +\n `'${moduleName}.${classNameStr}` +\n `${funcName}()' must be of type ${expectedType}.`);\n },\n 'incorrect-class': ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem, }) => {\n if (!expectedClassName || !moduleName || !funcName) {\n throw new Error(`Unexpected input to 'incorrect-class' error.`);\n }\n const classNameStr = className ? `${className}.` : '';\n if (isReturnValueProblem) {\n return (`The return value from ` +\n `'${moduleName}.${classNameStr}${funcName}()' ` +\n `must be an instance of class ${expectedClassName}.`);\n }\n return (`The parameter '${paramName}' passed into ` +\n `'${moduleName}.${classNameStr}${funcName}()' ` +\n `must be an instance of class ${expectedClassName}.`);\n },\n 'missing-a-method': ({ expectedMethod, paramName, moduleName, className, funcName, }) => {\n if (!expectedMethod ||\n !paramName ||\n !moduleName ||\n !className ||\n !funcName) {\n throw new Error(`Unexpected input to 'missing-a-method' error.`);\n }\n return (`${moduleName}.${className}.${funcName}() expected the ` +\n `'${paramName}' parameter to expose a '${expectedMethod}' method.`);\n },\n 'add-to-cache-list-unexpected-type': ({ entry }) => {\n return (`An unexpected entry was passed to ` +\n `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` +\n `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` +\n `strings with one or more characters, objects with a url property or ` +\n `Request objects.`);\n },\n 'add-to-cache-list-conflicting-entries': ({ firstEntry, secondEntry }) => {\n if (!firstEntry || !secondEntry) {\n throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);\n }\n return (`Two of the entries passed to ` +\n `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` +\n `${firstEntry} but different revision details. Workbox is ` +\n `unable to cache and version the asset correctly. Please remove one ` +\n `of the entries.`);\n },\n 'plugin-error-request-will-fetch': ({ thrownErrorMessage }) => {\n if (!thrownErrorMessage) {\n throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);\n }\n return (`An error was thrown by a plugins 'requestWillFetch()' method. ` +\n `The thrown error message was: '${thrownErrorMessage}'.`);\n },\n 'invalid-cache-name': ({ cacheNameId, value }) => {\n if (!cacheNameId) {\n throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);\n }\n return (`You must provide a name containing at least one character for ` +\n `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` +\n `'${JSON.stringify(value)}'`);\n },\n 'unregister-route-but-not-found-with-method': ({ method }) => {\n if (!method) {\n throw new Error(`Unexpected input to ` +\n `'unregister-route-but-not-found-with-method' error.`);\n }\n return (`The route you're trying to unregister was not previously ` +\n `registered for the method type '${method}'.`);\n },\n 'unregister-route-route-not-registered': () => {\n return (`The route you're trying to unregister was not previously ` +\n `registered.`);\n },\n 'queue-replay-failed': ({ name }) => {\n return `Replaying the background sync queue '${name}' failed.`;\n },\n 'duplicate-queue-name': ({ name }) => {\n return (`The Queue name '${name}' is already being used. ` +\n `All instances of backgroundSync.Queue must be given unique names.`);\n },\n 'expired-test-without-max-age': ({ methodName, paramName }) => {\n return (`The '${methodName}()' method can only be used when the ` +\n `'${paramName}' is used in the constructor.`);\n },\n 'unsupported-route-type': ({ moduleName, className, funcName, paramName }) => {\n return (`The supplied '${paramName}' parameter was an unsupported type. ` +\n `Please check the docs for ${moduleName}.${className}.${funcName} for ` +\n `valid input types.`);\n },\n 'not-array-of-class': ({ value, expectedClass, moduleName, className, funcName, paramName, }) => {\n return (`The supplied '${paramName}' parameter must be an array of ` +\n `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` +\n `Please check the call to ${moduleName}.${className}.${funcName}() ` +\n `to fix the issue.`);\n },\n 'max-entries-or-age-required': ({ moduleName, className, funcName }) => {\n return (`You must define either config.maxEntries or config.maxAgeSeconds` +\n `in ${moduleName}.${className}.${funcName}`);\n },\n 'statuses-or-headers-required': ({ moduleName, className, funcName }) => {\n return (`You must define either config.statuses or config.headers` +\n `in ${moduleName}.${className}.${funcName}`);\n },\n 'invalid-string': ({ moduleName, funcName, paramName }) => {\n if (!paramName || !moduleName || !funcName) {\n throw new Error(`Unexpected input to 'invalid-string' error.`);\n }\n return (`When using strings, the '${paramName}' parameter must start with ` +\n `'http' (for cross-origin matches) or '/' (for same-origin matches). ` +\n `Please see the docs for ${moduleName}.${funcName}() for ` +\n `more info.`);\n },\n 'channel-name-required': () => {\n return (`You must provide a channelName to construct a ` +\n `BroadcastCacheUpdate instance.`);\n },\n 'invalid-responses-are-same-args': () => {\n return (`The arguments passed into responsesAreSame() appear to be ` +\n `invalid. Please ensure valid Responses are used.`);\n },\n 'expire-custom-caches-only': () => {\n return (`You must provide a 'cacheName' property when using the ` +\n `expiration plugin with a runtime caching strategy.`);\n },\n 'unit-must-be-bytes': ({ normalizedRangeHeader }) => {\n if (!normalizedRangeHeader) {\n throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);\n }\n return (`The 'unit' portion of the Range header must be set to 'bytes'. ` +\n `The Range header provided was \"${normalizedRangeHeader}\"`);\n },\n 'single-range-only': ({ normalizedRangeHeader }) => {\n if (!normalizedRangeHeader) {\n throw new Error(`Unexpected input to 'single-range-only' error.`);\n }\n return (`Multiple ranges are not supported. Please use a single start ` +\n `value, and optional end value. The Range header provided was ` +\n `\"${normalizedRangeHeader}\"`);\n },\n 'invalid-range-values': ({ normalizedRangeHeader }) => {\n if (!normalizedRangeHeader) {\n throw new Error(`Unexpected input to 'invalid-range-values' error.`);\n }\n return (`The Range header is missing both start and end values. At least ` +\n `one of those values is needed. The Range header provided was ` +\n `\"${normalizedRangeHeader}\"`);\n },\n 'no-range-header': () => {\n return `No Range header was found in the Request provided.`;\n },\n 'range-not-satisfiable': ({ size, start, end }) => {\n return (`The start (${start}) and end (${end}) values in the Range are ` +\n `not satisfiable by the cached response, which is ${size} bytes.`);\n },\n 'attempt-to-cache-non-get-request': ({ url, method }) => {\n return (`Unable to cache '${url}' because it is a '${method}' request and ` +\n `only 'GET' requests can be cached.`);\n },\n 'cache-put-with-no-response': ({ url }) => {\n return (`There was an attempt to cache '${url}' but the response was not ` +\n `defined.`);\n },\n 'no-response': ({ url, error }) => {\n let message = `The strategy could not generate a response for '${url}'.`;\n if (error) {\n message += ` The underlying error is ${error}.`;\n }\n return message;\n },\n 'bad-precaching-response': ({ url, status }) => {\n return (`The precaching request for '${url}' failed` +\n (status ? ` with an HTTP status of ${status}.` : `.`));\n },\n 'non-precached-url': ({ url }) => {\n return (`createHandlerBoundToURL('${url}') was called, but that URL is ` +\n `not precached. Please pass in a URL that is precached instead.`);\n },\n 'add-to-cache-list-conflicting-integrities': ({ url }) => {\n return (`Two of the entries passed to ` +\n `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` +\n `${url} with different integrity values. Please remove one of them.`);\n },\n 'missing-precache-entry': ({ cacheName, url }) => {\n return `Unable to find a precached response in ${cacheName} for ${url}.`;\n },\n 'cross-origin-copy-response': ({ origin }) => {\n return (`workbox-core.copyResponse() can only be used with same-origin ` +\n `responses. It was passed a response with origin ${origin}.`);\n },\n 'opaque-streams-source': ({ type }) => {\n const message = `One of the workbox-streams sources resulted in an ` +\n `'${type}' response.`;\n if (type === 'opaqueredirect') {\n return (`${message} Please do not use a navigation request that results ` +\n `in a redirect as a source.`);\n }\n return `${message} Please ensure your sources are CORS-enabled.`;\n },\n};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { messages } from './messages.js';\nimport '../../_version.js';\nconst fallback = (code, ...args) => {\n let msg = code;\n if (args.length > 0) {\n msg += ` :: ${JSON.stringify(args)}`;\n }\n return msg;\n};\nconst generatorFunction = (code, details = {}) => {\n const message = messages[code];\n if (!message) {\n throw new Error(`Unable to find message for code '${code}'.`);\n }\n return message(details);\n};\nexport const messageGenerator = process.env.NODE_ENV === 'production' ? fallback : generatorFunction;\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { messageGenerator } from '../models/messages/messageGenerator.js';\nimport '../_version.js';\n/**\n * Workbox errors should be thrown with this class.\n * This allows use to ensure the type easily in tests,\n * helps developers identify errors from workbox\n * easily and allows use to optimise error\n * messages correctly.\n *\n * @private\n */\nclass WorkboxError extends Error {\n /**\n *\n * @param {string} errorCode The error code that\n * identifies this particular error.\n * @param {Object=} details Any relevant arguments\n * that will help developers identify issues should\n * be added as a key on the context object.\n */\n constructor(errorCode, details) {\n const message = messageGenerator(errorCode, details);\n super(message);\n this.name = errorCode;\n this.details = details;\n }\n}\nexport { WorkboxError };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from '../_private/WorkboxError.js';\nimport '../_version.js';\n/*\n * This method throws if the supplied value is not an array.\n * The destructed values are required to produce a meaningful error for users.\n * The destructed and restructured object is so it's clear what is\n * needed.\n */\nconst isArray = (value, details) => {\n if (!Array.isArray(value)) {\n throw new WorkboxError('not-an-array', details);\n }\n};\nconst hasMethod = (object, expectedMethod, details) => {\n const type = typeof object[expectedMethod];\n if (type !== 'function') {\n details['expectedMethod'] = expectedMethod;\n throw new WorkboxError('missing-a-method', details);\n }\n};\nconst isType = (object, expectedType, details) => {\n if (typeof object !== expectedType) {\n details['expectedType'] = expectedType;\n throw new WorkboxError('incorrect-type', details);\n }\n};\nconst isInstance = (object, \n// Need the general type to do the check later.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexpectedClass, details) => {\n if (!(object instanceof expectedClass)) {\n details['expectedClassName'] = expectedClass.name;\n throw new WorkboxError('incorrect-class', details);\n }\n};\nconst isOneOf = (value, validValues, details) => {\n if (!validValues.includes(value)) {\n details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;\n throw new WorkboxError('invalid-value', details);\n }\n};\nconst isArrayOfClass = (value, \n// Need general type to do check later.\nexpectedClass, // eslint-disable-line\ndetails) => {\n const error = new WorkboxError('not-array-of-class', details);\n if (!Array.isArray(value)) {\n throw error;\n }\n for (const item of value) {\n if (!(item instanceof expectedClass)) {\n throw error;\n }\n }\n};\nconst finalAssertExports = process.env.NODE_ENV === 'production'\n ? null\n : {\n hasMethod,\n isArray,\n isInstance,\n isOneOf,\n isType,\n isArrayOfClass,\n };\nexport { finalAssertExports as assert };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n// Callbacks to be executed whenever there's a quota error.\n// Can't change Function type right now.\n// eslint-disable-next-line @typescript-eslint/ban-types\nconst quotaErrorCallbacks = new Set();\nexport { quotaErrorCallbacks };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from './_private/logger.js';\nimport { assert } from './_private/assert.js';\nimport { quotaErrorCallbacks } from './models/quotaErrorCallbacks.js';\nimport './_version.js';\n/**\n * Adds a function to the set of quotaErrorCallbacks that will be executed if\n * there's a quota error.\n *\n * @param {Function} callback\n * @memberof workbox-core\n */\n// Can't change Function type\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction registerQuotaErrorCallback(callback) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(callback, 'function', {\n moduleName: 'workbox-core',\n funcName: 'register',\n paramName: 'callback',\n });\n }\n quotaErrorCallbacks.add(callback);\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered a callback to respond to quota errors.', callback);\n }\n}\nexport { registerQuotaErrorCallback };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst _cacheNameDetails = {\n googleAnalytics: 'googleAnalytics',\n precache: 'precache-v2',\n prefix: 'workbox',\n runtime: 'runtime',\n suffix: typeof registration !== 'undefined' ? registration.scope : '',\n};\nconst _createCacheName = (cacheName) => {\n return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix]\n .filter((value) => value && value.length > 0)\n .join('-');\n};\nconst eachCacheNameDetail = (fn) => {\n for (const key of Object.keys(_cacheNameDetails)) {\n fn(key);\n }\n};\nexport const cacheNames = {\n updateDetails: (details) => {\n eachCacheNameDetail((key) => {\n if (typeof details[key] === 'string') {\n _cacheNameDetails[key] = details[key];\n }\n });\n },\n getGoogleAnalyticsName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);\n },\n getPrecacheName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.precache);\n },\n getPrefix: () => {\n return _cacheNameDetails.prefix;\n },\n getRuntimeName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.runtime);\n },\n getSuffix: () => {\n return _cacheNameDetails.suffix;\n },\n};\n","/*\n Copyright 2020 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nfunction stripParams(fullURL, ignoreParams) {\n const strippedURL = new URL(fullURL);\n for (const param of ignoreParams) {\n strippedURL.searchParams.delete(param);\n }\n return strippedURL.href;\n}\n/**\n * Matches an item in the cache, ignoring specific URL params. This is similar\n * to the `ignoreSearch` option, but it allows you to ignore just specific\n * params (while continuing to match on the others).\n *\n * @private\n * @param {Cache} cache\n * @param {Request} request\n * @param {Object} matchOptions\n * @param {Array} ignoreParams\n * @return {Promise}\n */\nasync function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {\n const strippedRequestURL = stripParams(request.url, ignoreParams);\n // If the request doesn't include any ignored params, match as normal.\n if (request.url === strippedRequestURL) {\n return cache.match(request, matchOptions);\n }\n // Otherwise, match by comparing keys\n const keysOptions = Object.assign(Object.assign({}, matchOptions), { ignoreSearch: true });\n const cacheKeys = await cache.keys(request, keysOptions);\n for (const cacheKey of cacheKeys) {\n const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);\n if (strippedRequestURL === strippedCacheKeyURL) {\n return cache.match(cacheKey, matchOptions);\n }\n }\n return;\n}\nexport { cacheMatchIgnoreParams };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nlet supportStatus;\n/**\n * A utility function that determines whether the current browser supports\n * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * object.\n *\n * @return {boolean} `true`, if the current browser can successfully\n * construct a `ReadableStream`, `false` otherwise.\n *\n * @private\n */\nfunction canConstructReadableStream() {\n if (supportStatus === undefined) {\n // See https://github.com/GoogleChrome/workbox/issues/1473\n try {\n new ReadableStream({ start() { } });\n supportStatus = true;\n }\n catch (error) {\n supportStatus = false;\n }\n }\n return supportStatus;\n}\nexport { canConstructReadableStream };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nlet supportStatus;\n/**\n * A utility function that determines whether the current browser supports\n * constructing a new `Response` from a `response.body` stream.\n *\n * @return {boolean} `true`, if the current browser can successfully\n * construct a `Response` from a `response.body` stream, `false` otherwise.\n *\n * @private\n */\nfunction canConstructResponseFromBodyStream() {\n if (supportStatus === undefined) {\n const testResponse = new Response('');\n if ('body' in testResponse) {\n try {\n new Response(testResponse.body);\n supportStatus = true;\n }\n catch (error) {\n supportStatus = false;\n }\n }\n supportStatus = false;\n }\n return supportStatus;\n}\nexport { canConstructResponseFromBodyStream };\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from '../_private/logger.js';\nimport { quotaErrorCallbacks } from '../models/quotaErrorCallbacks.js';\nimport '../_version.js';\n/**\n * Runs all of the callback functions, one at a time sequentially, in the order\n * in which they were registered.\n *\n * @memberof workbox-core\n * @private\n */\nasync function executeQuotaErrorCallbacks() {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`About to run ${quotaErrorCallbacks.size} ` +\n `callbacks to clean up caches.`);\n }\n for (const callback of quotaErrorCallbacks) {\n await callback();\n if (process.env.NODE_ENV !== 'production') {\n logger.log(callback, 'is complete.');\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Finished running callbacks.');\n }\n}\nexport { executeQuotaErrorCallbacks };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst getFriendlyURL = (url) => {\n const urlObj = new URL(String(url), location.href);\n // See https://github.com/GoogleChrome/workbox/issues/2323\n // We want to include everything, except for the origin if it's same-origin.\n return urlObj.href.replace(new RegExp(`^${location.origin}`), '');\n};\nexport { getFriendlyURL };\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns a promise that resolves and the passed number of milliseconds.\n * This utility is an async/await-friendly version of `setTimeout`.\n *\n * @param {number} ms\n * @return {Promise}\n * @private\n */\nexport function timeout(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { timeout } from './timeout.js';\nimport '../_version.js';\nconst MAX_RETRY_TIME = 2000;\n/**\n * Returns a promise that resolves to a window client matching the passed\n * `resultingClientId`. For browsers that don't support `resultingClientId`\n * or if waiting for the resulting client to apper takes too long, resolve to\n * `undefined`.\n *\n * @param {string} [resultingClientId]\n * @return {Promise}\n * @private\n */\nexport async function resultingClientExists(resultingClientId) {\n if (!resultingClientId) {\n return;\n }\n let existingWindows = await self.clients.matchAll({ type: 'window' });\n const existingWindowIds = new Set(existingWindows.map((w) => w.id));\n let resultingWindow;\n const startTime = performance.now();\n // Only wait up to `MAX_RETRY_TIME` to find a matching client.\n while (performance.now() - startTime < MAX_RETRY_TIME) {\n existingWindows = await self.clients.matchAll({ type: 'window' });\n resultingWindow = existingWindows.find((w) => {\n if (resultingClientId) {\n // If we have a `resultingClientId`, we can match on that.\n return w.id === resultingClientId;\n }\n else {\n // Otherwise match on finding a window not in `existingWindowIds`.\n return !existingWindowIds.has(w.id);\n }\n });\n if (resultingWindow) {\n break;\n }\n // Sleep for 100ms and retry.\n await timeout(100);\n }\n return resultingWindow;\n}\n","/*\n Copyright 2020 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A utility method that makes it easier to use `event.waitUntil` with\n * async functions and return the result.\n *\n * @param {ExtendableEvent} event\n * @param {Function} asyncFn\n * @return {Function}\n * @private\n */\nfunction waitUntil(event, asyncFn) {\n const returnPromise = asyncFn();\n event.waitUntil(returnPromise);\n return returnPromise;\n}\nexport { waitUntil };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n// We either expose defaults or we expose every named export.\nimport { assert } from './_private/assert.js';\nimport { cacheNames } from './_private/cacheNames.js';\nimport { cacheMatchIgnoreParams } from './_private/cacheMatchIgnoreParams.js';\nimport { canConstructReadableStream } from './_private/canConstructReadableStream.js';\nimport { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js';\nimport { dontWaitFor } from './_private/dontWaitFor.js';\nimport { Deferred } from './_private/Deferred.js';\nimport { executeQuotaErrorCallbacks } from './_private/executeQuotaErrorCallbacks.js';\nimport { getFriendlyURL } from './_private/getFriendlyURL.js';\nimport { logger } from './_private/logger.js';\nimport { resultingClientExists } from './_private/resultingClientExists.js';\nimport { timeout } from './_private/timeout.js';\nimport { waitUntil } from './_private/waitUntil.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\nexport { assert, cacheMatchIgnoreParams, cacheNames, canConstructReadableStream, canConstructResponseFromBodyStream, dontWaitFor, Deferred, executeQuotaErrorCallbacks, getFriendlyURL, logger, resultingClientExists, timeout, waitUntil, WorkboxError, };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames as _cacheNames } from './_private/cacheNames.js';\nimport './_version.js';\n/**\n * Get the current cache names and prefix/suffix used by Workbox.\n *\n * `cacheNames.precache` is used for precached assets,\n * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to\n * store `analytics.js`, and `cacheNames.runtime` is used for everything else.\n *\n * `cacheNames.prefix` can be used to retrieve just the current prefix value.\n * `cacheNames.suffix` can be used to retrieve just the current suffix value.\n *\n * @return {Object} An object with `precache`, `runtime`, `prefix`, and\n * `googleAnalytics` properties.\n *\n * @memberof workbox-core\n */\nconst cacheNames = {\n get googleAnalytics() {\n return _cacheNames.getGoogleAnalyticsName();\n },\n get precache() {\n return _cacheNames.getPrecacheName();\n },\n get prefix() {\n return _cacheNames.getPrefix();\n },\n get runtime() {\n return _cacheNames.getRuntimeName();\n },\n get suffix() {\n return _cacheNames.getSuffix();\n },\n};\nexport { cacheNames };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Allows developers to copy a response and modify its `headers`, `status`,\n * or `statusText` values (the values settable via a\n * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}\n * object in the constructor).\n * To modify these values, pass a function as the second argument. That\n * function will be invoked with a single object with the response properties\n * `{headers, status, statusText}`. The return value of this function will\n * be used as the `ResponseInit` for the new `Response`. To change the values\n * either modify the passed parameter(s) and return it, or return a totally\n * new object.\n *\n * This method is intentionally limited to same-origin responses, regardless of\n * whether CORS was used or not.\n *\n * @param {Response} response\n * @param {Function} modifier\n * @memberof workbox-core\n */\nasync function copyResponse(response, modifier) {\n let origin = null;\n // If response.url isn't set, assume it's cross-origin and keep origin null.\n if (response.url) {\n const responseURL = new URL(response.url);\n origin = responseURL.origin;\n }\n if (origin !== self.location.origin) {\n throw new WorkboxError('cross-origin-copy-response', { origin });\n }\n const clonedResponse = response.clone();\n // Create a fresh `ResponseInit` object by cloning the headers.\n const responseInit = {\n headers: new Headers(clonedResponse.headers),\n status: clonedResponse.status,\n statusText: clonedResponse.statusText,\n };\n // Apply any user modifications.\n const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;\n // Create the new response from the body stream and `ResponseInit`\n // modifications. Note: not all browsers support the Response.body stream,\n // so fall back to reading the entire body into memory as a blob.\n const body = canConstructResponseFromBodyStream()\n ? clonedResponse.body\n : await clonedResponse.blob();\n return new Response(body, modifiedResponseInit);\n}\nexport { copyResponse };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Claim any currently available clients once the service worker\n * becomes active. This is normally used in conjunction with `skipWaiting()`.\n *\n * @memberof workbox-core\n */\nfunction clientsClaim() {\n self.addEventListener('activate', () => self.clients.claim());\n}\nexport { clientsClaim };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from './_private/assert.js';\nimport { cacheNames } from './_private/cacheNames.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Modifies the default cache names used by the Workbox packages.\n * Cache names are generated as `--`.\n *\n * @param {Object} details\n * @param {Object} [details.prefix] The string to add to the beginning of\n * the precache and runtime cache names.\n * @param {Object} [details.suffix] The string to add to the end of\n * the precache and runtime cache names.\n * @param {Object} [details.precache] The cache name to use for precache\n * caching.\n * @param {Object} [details.runtime] The cache name to use for runtime caching.\n * @param {Object} [details.googleAnalytics] The cache name to use for\n * `workbox-google-analytics` caching.\n *\n * @memberof workbox-core\n */\nfunction setCacheNameDetails(details) {\n if (process.env.NODE_ENV !== 'production') {\n Object.keys(details).forEach((key) => {\n assert.isType(details[key], 'string', {\n moduleName: 'workbox-core',\n funcName: 'setCacheNameDetails',\n paramName: `details.${key}`,\n });\n });\n if ('precache' in details && details['precache'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'precache',\n value: details['precache'],\n });\n }\n if ('runtime' in details && details['runtime'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'runtime',\n value: details['runtime'],\n });\n }\n if ('googleAnalytics' in details &&\n details['googleAnalytics'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'googleAnalytics',\n value: details['googleAnalytics'],\n });\n }\n }\n cacheNames.updateDetails(details);\n}\nexport { setCacheNameDetails };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from './_private/logger.js';\nimport './_version.js';\n/**\n * This method is deprecated, and will be removed in Workbox v7.\n *\n * Calling self.skipWaiting() is equivalent, and should be used instead.\n *\n * @memberof workbox-core\n */\nfunction skipWaiting() {\n // Just call self.skipWaiting() directly.\n // See https://github.com/GoogleChrome/workbox/issues/2525\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`skipWaiting() from workbox-core is no longer recommended ` +\n `and will be removed in Workbox v7. Using self.skipWaiting() instead ` +\n `is equivalent.`);\n }\n void self.skipWaiting();\n}\nexport { skipWaiting };\n"],"names":["self","_","e","logger","globalThis","__WB_DISABLE_DEV_LOGS","inGroup","methodToColorMap","debug","log","warn","error","groupCollapsed","groupEnd","print","method","args","test","navigator","userAgent","console","styles","logPrefix","join","api","loggerMethods","Object","keys","key","messages","paramName","validValueDescription","value","Error","JSON","stringify","moduleName","className","funcName","expectedType","classNameStr","expectedClassName","isReturnValueProblem","expectedMethod","entry","firstEntry","secondEntry","thrownErrorMessage","cacheNameId","name","methodName","expectedClass","normalizedRangeHeader","size","start","end","url","message","status","cacheName","origin","type","generatorFunction","code","details","messageGenerator","WorkboxError","constructor","errorCode","isArray","Array","hasMethod","object","isType","isInstance","isOneOf","validValues","includes","isArrayOfClass","item","finalAssertExports","quotaErrorCallbacks","Set","registerQuotaErrorCallback","callback","assert","add","_cacheNameDetails","googleAnalytics","precache","prefix","runtime","suffix","registration","scope","_createCacheName","filter","length","eachCacheNameDetail","fn","cacheNames","updateDetails","getGoogleAnalyticsName","userCacheName","getPrecacheName","getPrefix","getRuntimeName","getSuffix","stripParams","fullURL","ignoreParams","strippedURL","URL","param","searchParams","delete","href","cacheMatchIgnoreParams","cache","request","matchOptions","strippedRequestURL","match","keysOptions","assign","ignoreSearch","cacheKeys","cacheKey","strippedCacheKeyURL","supportStatus","canConstructReadableStream","undefined","ReadableStream","canConstructResponseFromBodyStream","testResponse","Response","body","dontWaitFor","promise","then","Deferred","Promise","resolve","reject","executeQuotaErrorCallbacks","getFriendlyURL","urlObj","String","location","replace","RegExp","timeout","ms","setTimeout","MAX_RETRY_TIME","resultingClientExists","resultingClientId","existingWindows","clients","matchAll","existingWindowIds","map","w","id","resultingWindow","startTime","performance","now","find","has","waitUntil","event","asyncFn","returnPromise","_cacheNames","copyResponse","response","modifier","responseURL","clonedResponse","clone","responseInit","headers","Headers","statusText","modifiedResponseInit","blob","clientsClaim","addEventListener","claim","setCacheNameDetails","forEach","skipWaiting"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,oBAAD,CAAJ,IAA8BC,CAAC,EAA/B;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;IACA;IACA;IACA;IACA;IAEA,MAAMC,MAAM,GAEN,CAAC,MAAM;IACL;IACA;IACA,MAAI,EAAE,2BAA2BC,UAA7B,CAAJ,EAA8C;IAC1CJ,IAAAA,IAAI,CAACK,qBAAL,GAA6B,KAA7B;IACH;;IACD,MAAIC,OAAO,GAAG,KAAd;IACA,QAAMC,gBAAgB,GAAG;IACrBC,IAAAA,KAAK,EAAG,SADa;IAErBC,IAAAA,GAAG,EAAG,SAFe;IAGrBC,IAAAA,IAAI,EAAG,SAHc;IAIrBC,IAAAA,KAAK,EAAG,SAJa;IAKrBC,IAAAA,cAAc,EAAG,SALI;IAMrBC,IAAAA,QAAQ,EAAE,IANW;;IAAA,GAAzB;;IAQA,QAAMC,KAAK,GAAG,UAAUC,MAAV,EAAkBC,IAAlB,EAAwB;IAClC,QAAIhB,IAAI,CAACK,qBAAT,EAAgC;IAC5B;IACH;;IACD,QAAIU,MAAM,KAAK,gBAAf,EAAiC;IAC7B;IACA;IACA,UAAI,iCAAiCE,IAAjC,CAAsCC,SAAS,CAACC,SAAhD,CAAJ,EAAgE;IAC5DC,QAAAA,OAAO,CAACL,MAAD,CAAP,CAAgB,GAAGC,IAAn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OAAd,IAAyBA,OAAO,CAAC,UAAD,CAAP,CAAoBiC,MAApB,KAA+B,CAA5D,EAA+D;IAC3D,YAAM,IAAI/B,YAAJ,CAAiB,oBAAjB,EAAuC;IACzClB,QAAAA,WAAW,EAAE,UAD4B;IAEzChB,QAAAA,KAAK,EAAEgC,OAAO,CAAC,UAAD;IAF2B,OAAvC,CAAN;IAIH;;IACD,QAAI,aAAaA,OAAb,IAAwBA,OAAO,CAAC,SAAD,CAAP,CAAmBiC,MAAnB,KAA8B,CAA1D,EAA6D;IACzD,YAAM,IAAI/B,YAAJ,CAAiB,oBAAjB,EAAuC;IACzClB,QAAAA,WAAW,EAAE,SAD4B;IAEzChB,QAAAA,KAAK,EAAEgC,OAAO,CAAC,SAAD;IAF2B,OAAvC,CAAN;IAIH;;IACD,QAAI,qBAAqBA,OAArB,IACAA,OAAO,CAAC,iBAAD,CAAP,CAA2BiC,MAA3B,KAAsC,CAD1C,EAC6C;IACzC,YAAM,IAAI/B,YAAJ,CAAiB,oBAAjB,EAAuC;IACzClB,QAAAA,WAAW,EAAE,iBAD4B;IAEzChB,QAAAA,KAAK,EAAEgC,OAAO,CAAC,iBAAD;IAF2B,OAAvC,CAAN;IAIH;IACJ;;IACDoC,EAAAA,YAAU,CAACC,aAAX,CAAyBrC,OAAzB;IACH;;IC1DD;IACA;AACA;IACA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASgI,WAAT,GAAuB;IACnB;IACA;IACA,EAA2C;IACvC7L,IAAAA,MAAM,CAACO,IAAP,CAAa,2DAAD,GACP,sEADO,GAEP,gBAFL;IAGH;;IACD,OAAKV,IAAI,CAACgM,WAAL,EAAL;IACH;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-core.prod.js b/src/Resources/workbox-v7.0.0/workbox-core.prod.js new file mode 100644 index 0000000..a985557 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-core.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.core=function(t){"use strict";try{self["workbox:core:7.0.0"]&&_()}catch(t){}const e=(t,...e)=>{let n=t;return e.length>0&&(n+=` :: ${JSON.stringify(e)}`),n};class n extends Error{constructor(t,n){super(e(t,n)),this.name=t,this.details=n}}const r=new Set;const o={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"workbox",runtime:"runtime",suffix:"undefined"!=typeof registration?registration.scope:""},s=t=>[o.prefix,t,o.suffix].filter((t=>t&&t.length>0)).join("-"),i={updateDetails:t=>{(t=>{for(const e of Object.keys(o))t(e)})((e=>{"string"==typeof t[e]&&(o[e]=t[e])}))},getGoogleAnalyticsName:t=>t||s(o.googleAnalytics),getPrecacheName:t=>t||s(o.precache),getPrefix:()=>o.prefix,getRuntimeName:t=>t||s(o.runtime),getSuffix:()=>o.suffix};function c(t,e){const n=new URL(t);for(const t of e)n.searchParams.delete(t);return n.href}let a,u;function f(){if(void 0===u){const t=new Response("");if("body"in t)try{new Response(t.body),u=!0}catch(t){u=!1}u=!1}return u}function l(t){return new Promise((e=>setTimeout(e,t)))}var g=Object.freeze({__proto__:null,assert:null,cacheMatchIgnoreParams:async function(t,e,n,r){const o=c(e.url,n);if(e.url===o)return t.match(e,r);const s=Object.assign(Object.assign({},r),{ignoreSearch:!0}),i=await t.keys(e,s);for(const e of i){if(o===c(e.url,n))return t.match(e,r)}},cacheNames:i,canConstructReadableStream:function(){if(void 0===a)try{new ReadableStream({start(){}}),a=!0}catch(t){a=!1}return a},canConstructResponseFromBodyStream:f,dontWaitFor:function(t){t.then((()=>{}))},Deferred:class{constructor(){this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}},executeQuotaErrorCallbacks:async function(){for(const t of r)await t()},getFriendlyURL:t=>new URL(String(t),location.href).href.replace(new RegExp(`^${location.origin}`),""),logger:null,resultingClientExists:async function(t){if(!t)return;let e=await self.clients.matchAll({type:"window"});const n=new Set(e.map((t=>t.id)));let r;const o=performance.now();for(;performance.now()-o<2e3&&(e=await self.clients.matchAll({type:"window"}),r=e.find((e=>t?e.id===t:!n.has(e.id))),!r);)await l(100);return r},timeout:l,waitUntil:function(t,e){const n=e();return t.waitUntil(n),n},WorkboxError:n});const w={get googleAnalytics(){return i.getGoogleAnalyticsName()},get precache(){return i.getPrecacheName()},get prefix(){return i.getPrefix()},get runtime(){return i.getRuntimeName()},get suffix(){return i.getSuffix()}};return t._private=g,t.cacheNames=w,t.clientsClaim=function(){self.addEventListener("activate",(()=>self.clients.claim()))},t.copyResponse=async function(t,e){let r=null;if(t.url){r=new URL(t.url).origin}if(r!==self.location.origin)throw new n("cross-origin-copy-response",{origin:r});const o=t.clone(),s={headers:new Headers(o.headers),status:o.status,statusText:o.statusText},i=e?e(s):s,c=f()?o.body:await o.blob();return new Response(c,i)},t.registerQuotaErrorCallback=function(t){r.add(t)},t.setCacheNameDetails=function(t){i.updateDetails(t)},t.skipWaiting=function(){self.skipWaiting()},t}({}); +//# sourceMappingURL=workbox-core.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-core.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-core.prod.js.map new file mode 100644 index 0000000..ad510ab --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-core.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-core.prod.js","sources":["../_version.js","../_private/logger.js","../models/messages/messageGenerator.js","../_private/WorkboxError.js","../_private/assert.js","../models/quotaErrorCallbacks.js","../_private/cacheNames.js","../_private/cacheMatchIgnoreParams.js","../_private/canConstructReadableStream.js","../_private/canConstructResponseFromBodyStream.js","../_private/timeout.js","../_private/dontWaitFor.js","../_private/Deferred.js","../_private/executeQuotaErrorCallbacks.js","../_private/getFriendlyURL.js","../_private/resultingClientExists.js","../_private/waitUntil.js","../cacheNames.js","../clientsClaim.js","../copyResponse.js","../registerQuotaErrorCallback.js","../setCacheNameDetails.js","../skipWaiting.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { messages } from './messages.js';\nimport '../../_version.js';\nconst fallback = (code, ...args) => {\n let msg = code;\n if (args.length > 0) {\n msg += ` :: ${JSON.stringify(args)}`;\n }\n return msg;\n};\nconst generatorFunction = (code, details = {}) => {\n const message = messages[code];\n if (!message) {\n throw new Error(`Unable to find message for code '${code}'.`);\n }\n return message(details);\n};\nexport const messageGenerator = process.env.NODE_ENV === 'production' ? fallback : generatorFunction;\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { messageGenerator } from '../models/messages/messageGenerator.js';\nimport '../_version.js';\n/**\n * Workbox errors should be thrown with this class.\n * This allows use to ensure the type easily in tests,\n * helps developers identify errors from workbox\n * easily and allows use to optimise error\n * messages correctly.\n *\n * @private\n */\nclass WorkboxError extends Error {\n /**\n *\n * @param {string} errorCode The error code that\n * identifies this particular error.\n * @param {Object=} details Any relevant arguments\n * that will help developers identify issues should\n * be added as a key on the context object.\n */\n constructor(errorCode, details) {\n const message = messageGenerator(errorCode, details);\n super(message);\n this.name = errorCode;\n this.details = details;\n }\n}\nexport { WorkboxError };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from '../_private/WorkboxError.js';\nimport '../_version.js';\n/*\n * This method throws if the supplied value is not an array.\n * The destructed values are required to produce a meaningful error for users.\n * The destructed and restructured object is so it's clear what is\n * needed.\n */\nconst isArray = (value, details) => {\n if (!Array.isArray(value)) {\n throw new WorkboxError('not-an-array', details);\n }\n};\nconst hasMethod = (object, expectedMethod, details) => {\n const type = typeof object[expectedMethod];\n if (type !== 'function') {\n details['expectedMethod'] = expectedMethod;\n throw new WorkboxError('missing-a-method', details);\n }\n};\nconst isType = (object, expectedType, details) => {\n if (typeof object !== expectedType) {\n details['expectedType'] = expectedType;\n throw new WorkboxError('incorrect-type', details);\n }\n};\nconst isInstance = (object, \n// Need the general type to do the check later.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexpectedClass, details) => {\n if (!(object instanceof expectedClass)) {\n details['expectedClassName'] = expectedClass.name;\n throw new WorkboxError('incorrect-class', details);\n }\n};\nconst isOneOf = (value, validValues, details) => {\n if (!validValues.includes(value)) {\n details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;\n throw new WorkboxError('invalid-value', details);\n }\n};\nconst isArrayOfClass = (value, \n// Need general type to do check later.\nexpectedClass, // eslint-disable-line\ndetails) => {\n const error = new WorkboxError('not-array-of-class', details);\n if (!Array.isArray(value)) {\n throw error;\n }\n for (const item of value) {\n if (!(item instanceof expectedClass)) {\n throw error;\n }\n }\n};\nconst finalAssertExports = process.env.NODE_ENV === 'production'\n ? null\n : {\n hasMethod,\n isArray,\n isInstance,\n isOneOf,\n isType,\n isArrayOfClass,\n };\nexport { finalAssertExports as assert };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n// Callbacks to be executed whenever there's a quota error.\n// Can't change Function type right now.\n// eslint-disable-next-line @typescript-eslint/ban-types\nconst quotaErrorCallbacks = new Set();\nexport { quotaErrorCallbacks };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst _cacheNameDetails = {\n googleAnalytics: 'googleAnalytics',\n precache: 'precache-v2',\n prefix: 'workbox',\n runtime: 'runtime',\n suffix: typeof registration !== 'undefined' ? registration.scope : '',\n};\nconst _createCacheName = (cacheName) => {\n return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix]\n .filter((value) => value && value.length > 0)\n .join('-');\n};\nconst eachCacheNameDetail = (fn) => {\n for (const key of Object.keys(_cacheNameDetails)) {\n fn(key);\n }\n};\nexport const cacheNames = {\n updateDetails: (details) => {\n eachCacheNameDetail((key) => {\n if (typeof details[key] === 'string') {\n _cacheNameDetails[key] = details[key];\n }\n });\n },\n getGoogleAnalyticsName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);\n },\n getPrecacheName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.precache);\n },\n getPrefix: () => {\n return _cacheNameDetails.prefix;\n },\n getRuntimeName: (userCacheName) => {\n return userCacheName || _createCacheName(_cacheNameDetails.runtime);\n },\n getSuffix: () => {\n return _cacheNameDetails.suffix;\n },\n};\n","/*\n Copyright 2020 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nfunction stripParams(fullURL, ignoreParams) {\n const strippedURL = new URL(fullURL);\n for (const param of ignoreParams) {\n strippedURL.searchParams.delete(param);\n }\n return strippedURL.href;\n}\n/**\n * Matches an item in the cache, ignoring specific URL params. This is similar\n * to the `ignoreSearch` option, but it allows you to ignore just specific\n * params (while continuing to match on the others).\n *\n * @private\n * @param {Cache} cache\n * @param {Request} request\n * @param {Object} matchOptions\n * @param {Array} ignoreParams\n * @return {Promise}\n */\nasync function cacheMatchIgnoreParams(cache, request, ignoreParams, matchOptions) {\n const strippedRequestURL = stripParams(request.url, ignoreParams);\n // If the request doesn't include any ignored params, match as normal.\n if (request.url === strippedRequestURL) {\n return cache.match(request, matchOptions);\n }\n // Otherwise, match by comparing keys\n const keysOptions = Object.assign(Object.assign({}, matchOptions), { ignoreSearch: true });\n const cacheKeys = await cache.keys(request, keysOptions);\n for (const cacheKey of cacheKeys) {\n const strippedCacheKeyURL = stripParams(cacheKey.url, ignoreParams);\n if (strippedRequestURL === strippedCacheKeyURL) {\n return cache.match(cacheKey, matchOptions);\n }\n }\n return;\n}\nexport { cacheMatchIgnoreParams };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nlet supportStatus;\n/**\n * A utility function that determines whether the current browser supports\n * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * object.\n *\n * @return {boolean} `true`, if the current browser can successfully\n * construct a `ReadableStream`, `false` otherwise.\n *\n * @private\n */\nfunction canConstructReadableStream() {\n if (supportStatus === undefined) {\n // See https://github.com/GoogleChrome/workbox/issues/1473\n try {\n new ReadableStream({ start() { } });\n supportStatus = true;\n }\n catch (error) {\n supportStatus = false;\n }\n }\n return supportStatus;\n}\nexport { canConstructReadableStream };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nlet supportStatus;\n/**\n * A utility function that determines whether the current browser supports\n * constructing a new `Response` from a `response.body` stream.\n *\n * @return {boolean} `true`, if the current browser can successfully\n * construct a `Response` from a `response.body` stream, `false` otherwise.\n *\n * @private\n */\nfunction canConstructResponseFromBodyStream() {\n if (supportStatus === undefined) {\n const testResponse = new Response('');\n if ('body' in testResponse) {\n try {\n new Response(testResponse.body);\n supportStatus = true;\n }\n catch (error) {\n supportStatus = false;\n }\n }\n supportStatus = false;\n }\n return supportStatus;\n}\nexport { canConstructResponseFromBodyStream };\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns a promise that resolves and the passed number of milliseconds.\n * This utility is an async/await-friendly version of `setTimeout`.\n *\n * @param {number} ms\n * @return {Promise}\n * @private\n */\nexport function timeout(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from '../_private/logger.js';\nimport { quotaErrorCallbacks } from '../models/quotaErrorCallbacks.js';\nimport '../_version.js';\n/**\n * Runs all of the callback functions, one at a time sequentially, in the order\n * in which they were registered.\n *\n * @memberof workbox-core\n * @private\n */\nasync function executeQuotaErrorCallbacks() {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`About to run ${quotaErrorCallbacks.size} ` +\n `callbacks to clean up caches.`);\n }\n for (const callback of quotaErrorCallbacks) {\n await callback();\n if (process.env.NODE_ENV !== 'production') {\n logger.log(callback, 'is complete.');\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Finished running callbacks.');\n }\n}\nexport { executeQuotaErrorCallbacks };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst getFriendlyURL = (url) => {\n const urlObj = new URL(String(url), location.href);\n // See https://github.com/GoogleChrome/workbox/issues/2323\n // We want to include everything, except for the origin if it's same-origin.\n return urlObj.href.replace(new RegExp(`^${location.origin}`), '');\n};\nexport { getFriendlyURL };\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { timeout } from './timeout.js';\nimport '../_version.js';\nconst MAX_RETRY_TIME = 2000;\n/**\n * Returns a promise that resolves to a window client matching the passed\n * `resultingClientId`. For browsers that don't support `resultingClientId`\n * or if waiting for the resulting client to apper takes too long, resolve to\n * `undefined`.\n *\n * @param {string} [resultingClientId]\n * @return {Promise}\n * @private\n */\nexport async function resultingClientExists(resultingClientId) {\n if (!resultingClientId) {\n return;\n }\n let existingWindows = await self.clients.matchAll({ type: 'window' });\n const existingWindowIds = new Set(existingWindows.map((w) => w.id));\n let resultingWindow;\n const startTime = performance.now();\n // Only wait up to `MAX_RETRY_TIME` to find a matching client.\n while (performance.now() - startTime < MAX_RETRY_TIME) {\n existingWindows = await self.clients.matchAll({ type: 'window' });\n resultingWindow = existingWindows.find((w) => {\n if (resultingClientId) {\n // If we have a `resultingClientId`, we can match on that.\n return w.id === resultingClientId;\n }\n else {\n // Otherwise match on finding a window not in `existingWindowIds`.\n return !existingWindowIds.has(w.id);\n }\n });\n if (resultingWindow) {\n break;\n }\n // Sleep for 100ms and retry.\n await timeout(100);\n }\n return resultingWindow;\n}\n","/*\n Copyright 2020 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A utility method that makes it easier to use `event.waitUntil` with\n * async functions and return the result.\n *\n * @param {ExtendableEvent} event\n * @param {Function} asyncFn\n * @return {Function}\n * @private\n */\nfunction waitUntil(event, asyncFn) {\n const returnPromise = asyncFn();\n event.waitUntil(returnPromise);\n return returnPromise;\n}\nexport { waitUntil };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames as _cacheNames } from './_private/cacheNames.js';\nimport './_version.js';\n/**\n * Get the current cache names and prefix/suffix used by Workbox.\n *\n * `cacheNames.precache` is used for precached assets,\n * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to\n * store `analytics.js`, and `cacheNames.runtime` is used for everything else.\n *\n * `cacheNames.prefix` can be used to retrieve just the current prefix value.\n * `cacheNames.suffix` can be used to retrieve just the current suffix value.\n *\n * @return {Object} An object with `precache`, `runtime`, `prefix`, and\n * `googleAnalytics` properties.\n *\n * @memberof workbox-core\n */\nconst cacheNames = {\n get googleAnalytics() {\n return _cacheNames.getGoogleAnalyticsName();\n },\n get precache() {\n return _cacheNames.getPrecacheName();\n },\n get prefix() {\n return _cacheNames.getPrefix();\n },\n get runtime() {\n return _cacheNames.getRuntimeName();\n },\n get suffix() {\n return _cacheNames.getSuffix();\n },\n};\nexport { cacheNames };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Claim any currently available clients once the service worker\n * becomes active. This is normally used in conjunction with `skipWaiting()`.\n *\n * @memberof workbox-core\n */\nfunction clientsClaim() {\n self.addEventListener('activate', () => self.clients.claim());\n}\nexport { clientsClaim };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Allows developers to copy a response and modify its `headers`, `status`,\n * or `statusText` values (the values settable via a\n * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}\n * object in the constructor).\n * To modify these values, pass a function as the second argument. That\n * function will be invoked with a single object with the response properties\n * `{headers, status, statusText}`. The return value of this function will\n * be used as the `ResponseInit` for the new `Response`. To change the values\n * either modify the passed parameter(s) and return it, or return a totally\n * new object.\n *\n * This method is intentionally limited to same-origin responses, regardless of\n * whether CORS was used or not.\n *\n * @param {Response} response\n * @param {Function} modifier\n * @memberof workbox-core\n */\nasync function copyResponse(response, modifier) {\n let origin = null;\n // If response.url isn't set, assume it's cross-origin and keep origin null.\n if (response.url) {\n const responseURL = new URL(response.url);\n origin = responseURL.origin;\n }\n if (origin !== self.location.origin) {\n throw new WorkboxError('cross-origin-copy-response', { origin });\n }\n const clonedResponse = response.clone();\n // Create a fresh `ResponseInit` object by cloning the headers.\n const responseInit = {\n headers: new Headers(clonedResponse.headers),\n status: clonedResponse.status,\n statusText: clonedResponse.statusText,\n };\n // Apply any user modifications.\n const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;\n // Create the new response from the body stream and `ResponseInit`\n // modifications. Note: not all browsers support the Response.body stream,\n // so fall back to reading the entire body into memory as a blob.\n const body = canConstructResponseFromBodyStream()\n ? clonedResponse.body\n : await clonedResponse.blob();\n return new Response(body, modifiedResponseInit);\n}\nexport { copyResponse };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from './_private/logger.js';\nimport { assert } from './_private/assert.js';\nimport { quotaErrorCallbacks } from './models/quotaErrorCallbacks.js';\nimport './_version.js';\n/**\n * Adds a function to the set of quotaErrorCallbacks that will be executed if\n * there's a quota error.\n *\n * @param {Function} callback\n * @memberof workbox-core\n */\n// Can't change Function type\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction registerQuotaErrorCallback(callback) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(callback, 'function', {\n moduleName: 'workbox-core',\n funcName: 'register',\n paramName: 'callback',\n });\n }\n quotaErrorCallbacks.add(callback);\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered a callback to respond to quota errors.', callback);\n }\n}\nexport { registerQuotaErrorCallback };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from './_private/assert.js';\nimport { cacheNames } from './_private/cacheNames.js';\nimport { WorkboxError } from './_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Modifies the default cache names used by the Workbox packages.\n * Cache names are generated as `--`.\n *\n * @param {Object} details\n * @param {Object} [details.prefix] The string to add to the beginning of\n * the precache and runtime cache names.\n * @param {Object} [details.suffix] The string to add to the end of\n * the precache and runtime cache names.\n * @param {Object} [details.precache] The cache name to use for precache\n * caching.\n * @param {Object} [details.runtime] The cache name to use for runtime caching.\n * @param {Object} [details.googleAnalytics] The cache name to use for\n * `workbox-google-analytics` caching.\n *\n * @memberof workbox-core\n */\nfunction setCacheNameDetails(details) {\n if (process.env.NODE_ENV !== 'production') {\n Object.keys(details).forEach((key) => {\n assert.isType(details[key], 'string', {\n moduleName: 'workbox-core',\n funcName: 'setCacheNameDetails',\n paramName: `details.${key}`,\n });\n });\n if ('precache' in details && details['precache'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'precache',\n value: details['precache'],\n });\n }\n if ('runtime' in details && details['runtime'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'runtime',\n value: details['runtime'],\n });\n }\n if ('googleAnalytics' in details &&\n details['googleAnalytics'].length === 0) {\n throw new WorkboxError('invalid-cache-name', {\n cacheNameId: 'googleAnalytics',\n value: details['googleAnalytics'],\n });\n }\n }\n cacheNames.updateDetails(details);\n}\nexport { setCacheNameDetails };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from './_private/logger.js';\nimport './_version.js';\n/**\n * This method is deprecated, and will be removed in Workbox v7.\n *\n * Calling self.skipWaiting() is equivalent, and should be used instead.\n *\n * @memberof workbox-core\n */\nfunction skipWaiting() {\n // Just call self.skipWaiting() directly.\n // See https://github.com/GoogleChrome/workbox/issues/2525\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`skipWaiting() from workbox-core is no longer recommended ` +\n `and will be removed in Workbox v7. Using self.skipWaiting() instead ` +\n `is equivalent.`);\n }\n void self.skipWaiting();\n}\nexport { skipWaiting };\n"],"names":["self","_","e","messageGenerator","code","args","msg","length","JSON","stringify","WorkboxError","Error","constructor","errorCode","details","name","quotaErrorCallbacks","Set","_cacheNameDetails","googleAnalytics","precache","prefix","runtime","suffix","registration","scope","_createCacheName","cacheName","filter","value","join","cacheNames","updateDetails","fn","key","Object","keys","eachCacheNameDetail","getGoogleAnalyticsName","userCacheName","getPrecacheName","getPrefix","getRuntimeName","getSuffix","stripParams","fullURL","ignoreParams","strippedURL","URL","param","searchParams","delete","href","supportStatus","canConstructResponseFromBodyStream","undefined","testResponse","Response","body","error","timeout","ms","Promise","resolve","setTimeout","async","cache","request","matchOptions","strippedRequestURL","url","match","keysOptions","assign","ignoreSearch","cacheKeys","cacheKey","ReadableStream","start","promise","then","reject","callback","String","location","replace","RegExp","origin","resultingClientId","existingWindows","clients","matchAll","type","existingWindowIds","map","w","id","resultingWindow","startTime","performance","now","find","has","event","asyncFn","returnPromise","waitUntil","_cacheNames","addEventListener","claim","response","modifier","clonedResponse","clone","responseInit","headers","Headers","status","statusText","modifiedResponseInit","blob","add","skipWaiting"],"mappings":"yEAEA,IACIA,KAAK,uBAAyBC,GACjC,CACD,MAAOC,ICEP,MCgBaC,EAdI,CAACC,KAASC,SACnBC,EAAMF,SACNC,EAAKE,OAAS,IACdD,GAAQ,OAAME,KAAKC,UAAUJ,MAE1BC,CAAP,ECIJ,MAAMI,UAAqBC,MASvBC,YAAYC,EAAWC,SACHX,EAAiBU,EAAWC,SAEvCC,KAAOF,OACPC,QAAUA,GC+BvB,MCnDME,EAAsB,IAAIC,ICHhC,MAAMC,EAAoB,CACtBC,gBAAiB,kBACjBC,SAAU,cACVC,OAAQ,UACRC,QAAS,UACTC,OAAgC,oBAAjBC,aAA+BA,aAAaC,MAAQ,IAEjEC,EAAoBC,GACf,CAACT,EAAkBG,OAAQM,EAAWT,EAAkBK,QAC1DK,QAAQC,GAAUA,G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,IAAIC,QAAQJ,EAAeG,SACpCE,OAAQL,EAAeK,OACvBC,WAAYN,EAAeM,YAGzBC,EAAuBR,EAAWA,EAASG,GAAgBA,EAI3DxD,EAAOJ,IACP0D,EAAetD,WACTsD,EAAeQ,cACpB,IAAI/D,SAASC,EAAM6D,EAC7B,+BCnCD,SAAoCrC,GAQhClE,EAAoByG,IAAIvC,EAI3B,wBCJD,SAA6BpE,GA6BzBiB,EAAWC,cAAclB,EAC5B,gBC1CD,WAQSd,KAAK0H,aACb"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-expiration.dev.js b/src/Resources/workbox-v7.0.0/workbox-expiration.dev.js new file mode 100644 index 0000000..bc75a7a --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-expiration.dev.js @@ -0,0 +1,972 @@ +this.workbox = this.workbox || {}; +this.workbox.expiration = (function (exports, assert_js, dontWaitFor_js, logger_js, WorkboxError_js, cacheNames_js, getFriendlyURL_js, registerQuotaErrorCallback_js) { + 'use strict'; + + function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); + } + + const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c); + + let idbProxyableTypes; + let cursorAdvanceMethods; // This is a function to prevent it throwing up in node environments. + + function getIdbProxyableTypes() { + return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]); + } // This is a function to prevent it throwing up in node environments. + + + function getCursorAdvanceMethods() { + return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]); + } + + const cursorRequestMap = new WeakMap(); + const transactionDoneMap = new WeakMap(); + const transactionStoreNamesMap = new WeakMap(); + const transformCache = new WeakMap(); + const reverseTransformCache = new WeakMap(); + + function promisifyRequest(request) { + const promise = new Promise((resolve, reject) => { + const unlisten = () => { + request.removeEventListener('success', success); + request.removeEventListener('error', error); + }; + + const success = () => { + resolve(wrap(request.result)); + unlisten(); + }; + + const error = () => { + reject(request.error); + unlisten(); + }; + + request.addEventListener('success', success); + request.addEventListener('error', error); + }); + promise.then(value => { + // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval + // (see wrapFunction). + if (value instanceof IDBCursor) { + cursorRequestMap.set(value, request); + } // Catching to avoid "Uncaught Promise exceptions" + + }).catch(() => {}); // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This + // is because we create many promises from a single IDBRequest. + + reverseTransformCache.set(promise, request); + return promise; + } + + function cacheDonePromiseForTransaction(tx) { + // Early bail if we've already created a done promise for this transaction. + if (transactionDoneMap.has(tx)) return; + const done = new Promise((resolve, reject) => { + const unlisten = () => { + tx.removeEventListener('complete', complete); + tx.removeEventListener('error', error); + tx.removeEventListener('abort', error); + }; + + const complete = () => { + resolve(); + unlisten(); + }; + + const error = () => { + reject(tx.error || new DOMException('AbortError', 'AbortError')); + unlisten(); + }; + + tx.addEventListener('complete', complete); + tx.addEventListener('error', error); + tx.addEventListener('abort', error); + }); // Cache it for later retrieval. + + transactionDoneMap.set(tx, done); + } + + let idbProxyTraps = { + get(target, prop, receiver) { + if (target instanceof IDBTransaction) { + // Special handling for transaction.done. + if (prop === 'done') return transactionDoneMap.get(target); // Polyfill for objectStoreNames because of Edge. + + if (prop === 'objectStoreNames') { + return target.objectStoreNames || transactionStoreNamesMap.get(target); + } // Make tx.store return the only store in the transaction, or undefined if there are many. + + + if (prop === 'store') { + return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]); + } + } // Else transform whatever we get back. + + + return wrap(target[prop]); + }, + + set(target, prop, value) { + target[prop] = value; + return true; + }, + + has(target, prop) { + if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) { + return true; + } + + return prop in target; + } + + }; + + function replaceTraps(callback) { + idbProxyTraps = callback(idbProxyTraps); + } + + function wrapFunction(func) { + // Due to expected object equality (which is enforced by the caching in `wrap`), we + // only create one new func per func. + // Edge doesn't support objectStoreNames (booo), so we polyfill it here. + if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) { + return function (storeNames, ...args) { + const tx = func.call(unwrap(this), storeNames, ...args); + transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); + return wrap(tx); + }; + } // Cursor methods are special, as the behaviour is a little more different to standard IDB. In + // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the + // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense + // with real promises, so each advance methods returns a new promise for the cursor object, or + // undefined if the end of the cursor has been reached. + + + if (getCursorAdvanceMethods().includes(func)) { + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + func.apply(unwrap(this), args); + return wrap(cursorRequestMap.get(this)); + }; + } + + return function (...args) { + // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use + // the original object. + return wrap(func.apply(unwrap(this), args)); + }; + } + + function transformCachableValue(value) { + if (typeof value === 'function') return wrapFunction(value); // This doesn't return, it just creates a 'done' promise for the transaction, + // which is later returned for transaction.done (see idbObjectHandler). + + if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value); + if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps); // Return the same value back if we're not going to transform it. + + return value; + } + + function wrap(value) { + // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because + // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached. + if (value instanceof IDBRequest) return promisifyRequest(value); // If we've already transformed this value before, reuse the transformed value. + // This is faster, but it also provides object equality. + + if (transformCache.has(value)) return transformCache.get(value); + const newValue = transformCachableValue(value); // Not all types are transformed. + // These may be primitive types, so they can't be WeakMap keys. + + if (newValue !== value) { + transformCache.set(value, newValue); + reverseTransformCache.set(newValue, value); + } + + return newValue; + } + + const unwrap = value => reverseTransformCache.get(value); + + /** + * Open a database. + * + * @param name Name of the database. + * @param version Schema version. + * @param callbacks Additional callbacks. + */ + + function openDB(name, version, { + blocked, + upgrade, + blocking, + terminated + } = {}) { + const request = indexedDB.open(name, version); + const openPromise = wrap(request); + + if (upgrade) { + request.addEventListener('upgradeneeded', event => { + upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction)); + }); + } + + if (blocked) request.addEventListener('blocked', () => blocked()); + openPromise.then(db => { + if (terminated) db.addEventListener('close', () => terminated()); + if (blocking) db.addEventListener('versionchange', () => blocking()); + }).catch(() => {}); + return openPromise; + } + /** + * Delete a database. + * + * @param name Name of the database. + */ + + + function deleteDB(name, { + blocked + } = {}) { + const request = indexedDB.deleteDatabase(name); + if (blocked) request.addEventListener('blocked', () => blocked()); + return wrap(request).then(() => undefined); + } + + const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; + const writeMethods = ['put', 'add', 'delete', 'clear']; + const cachedMethods = new Map(); + + function getMethod(target, prop) { + if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) { + return; + } + + if (cachedMethods.get(prop)) return cachedMethods.get(prop); + const targetFuncName = prop.replace(/FromIndex$/, ''); + const useIndex = prop !== targetFuncName; + const isWrite = writeMethods.includes(targetFuncName); + + if ( // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. + !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) { + return; + } + + const method = async function (storeName, ...args) { + // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :( + const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly'); + let target = tx.store; + if (useIndex) target = target.index(args.shift()); // Must reject if op rejects. + // If it's a write operation, must reject if tx.done rejects. + // Must reject with op rejection first. + // Must resolve with op value. + // Must handle both promises (no unhandled rejections) + + return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0]; + }; + + cachedMethods.set(prop, method); + return method; + } + + replaceTraps(oldTraps => _extends({}, oldTraps, { + get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), + has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop) + })); + + try { + self['workbox:expiration:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const DB_NAME = 'workbox-expiration'; + const CACHE_OBJECT_STORE = 'cache-entries'; + + const normalizeURL = unNormalizedUrl => { + const url = new URL(unNormalizedUrl, location.href); + url.hash = ''; + return url.href; + }; + /** + * Returns the timestamp model. + * + * @private + */ + + + class CacheTimestampsModel { + /** + * + * @param {string} cacheName + * + * @private + */ + constructor(cacheName) { + this._db = null; + this._cacheName = cacheName; + } + /** + * Performs an upgrade of indexedDB. + * + * @param {IDBPDatabase} db + * + * @private + */ + + + _upgradeDb(db) { + // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we + // have to use the `id` keyPath here and create our own values (a + // concatenation of `url + cacheName`) instead of simply using + // `keyPath: ['url', 'cacheName']`, which is supported in other browsers. + const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { + keyPath: 'id' + }); // TODO(philipwalton): once we don't have to support EdgeHTML, we can + // create a single index with the keyPath `['cacheName', 'timestamp']` + // instead of doing both these indexes. + + objStore.createIndex('cacheName', 'cacheName', { + unique: false + }); + objStore.createIndex('timestamp', 'timestamp', { + unique: false + }); + } + /** + * Performs an upgrade of indexedDB and deletes deprecated DBs. + * + * @param {IDBPDatabase} db + * + * @private + */ + + + _upgradeDbAndDeleteOldDbs(db) { + this._upgradeDb(db); + + if (this._cacheName) { + void deleteDB(this._cacheName); + } + } + /** + * @param {string} url + * @param {number} timestamp + * + * @private + */ + + + async setTimestamp(url, timestamp) { + url = normalizeURL(url); + const entry = { + url, + timestamp, + cacheName: this._cacheName, + // Creating an ID from the URL and cache name won't be necessary once + // Edge switches to Chromium and all browsers we support work with + // array keyPaths. + id: this._getId(url) + }; + const db = await this.getDb(); + const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', { + durability: 'relaxed' + }); + await tx.store.put(entry); + await tx.done; + } + /** + * Returns the timestamp stored for a given URL. + * + * @param {string} url + * @return {number | undefined} + * + * @private + */ + + + async getTimestamp(url) { + const db = await this.getDb(); + const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url)); + return entry === null || entry === void 0 ? void 0 : entry.timestamp; + } + /** + * Iterates through all the entries in the object store (from newest to + * oldest) and removes entries once either `maxCount` is reached or the + * entry's timestamp is less than `minTimestamp`. + * + * @param {number} minTimestamp + * @param {number} maxCount + * @return {Array} + * + * @private + */ + + + async expireEntries(minTimestamp, maxCount) { + const db = await this.getDb(); + let cursor = await db.transaction(CACHE_OBJECT_STORE).store.index('timestamp').openCursor(null, 'prev'); + const entriesToDelete = []; + let entriesNotDeletedCount = 0; + + while (cursor) { + const result = cursor.value; // TODO(philipwalton): once we can use a multi-key index, we + // won't have to check `cacheName` here. + + if (result.cacheName === this._cacheName) { + // Delete an entry if it's older than the max age or + // if we already have the max number allowed. + if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) { + // TODO(philipwalton): we should be able to delete the + // entry right here, but doing so causes an iteration + // bug in Safari stable (fixed in TP). Instead we can + // store the keys of the entries to delete, and then + // delete the separate transactions. + // https://github.com/GoogleChrome/workbox/issues/1978 + // cursor.delete(); + // We only need to return the URL, not the whole entry. + entriesToDelete.push(cursor.value); + } else { + entriesNotDeletedCount++; + } + } + + cursor = await cursor.continue(); + } // TODO(philipwalton): once the Safari bug in the following issue is fixed, + // we should be able to remove this loop and do the entry deletion in the + // cursor loop above: + // https://github.com/GoogleChrome/workbox/issues/1978 + + + const urlsDeleted = []; + + for (const entry of entriesToDelete) { + await db.delete(CACHE_OBJECT_STORE, entry.id); + urlsDeleted.push(entry.url); + } + + return urlsDeleted; + } + /** + * Takes a URL and returns an ID that will be unique in the object store. + * + * @param {string} url + * @return {string} + * + * @private + */ + + + _getId(url) { + // Creating an ID from the URL and cache name won't be necessary once + // Edge switches to Chromium and all browsers we support work with + // array keyPaths. + return this._cacheName + '|' + normalizeURL(url); + } + /** + * Returns an open connection to the database. + * + * @private + */ + + + async getDb() { + if (!this._db) { + this._db = await openDB(DB_NAME, 1, { + upgrade: this._upgradeDbAndDeleteOldDbs.bind(this) + }); + } + + return this._db; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The `CacheExpiration` class allows you define an expiration and / or + * limit on the number of responses stored in a + * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + * + * @memberof workbox-expiration + */ + + class CacheExpiration { + /** + * To construct a new CacheExpiration instance you must provide at least + * one of the `config` properties. + * + * @param {string} cacheName Name of the cache to apply restrictions to. + * @param {Object} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + */ + 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._matchOptions = config.matchOptions; + this._cacheName = cacheName; + this._timestampModel = new CacheTimestampsModel(cacheName); + } + /** + * Expires entries for the given cache and given criteria. + */ + + + 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); // Delete URLs from the cache + + const cache = await self.caches.open(this._cacheName); + + for (const url of urlsExpired) { + await cache.delete(url, this._matchOptions); + } + + { + 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()); + } + } + /** + * Update the timestamp for the given URL. This ensures the when + * removing entries based on maximum entries, most recently used + * is accurate or when expiring, the timestamp is up-to-date. + * + * @param {string} url + */ + + + 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()); + } + /** + * Can be used to check if a URL has expired or not before it's used. + * + * This requires a look up from IndexedDB, so can be slow. + * + * Note: This method will not remove the cached entry, call + * `expireEntries()` to remove indexedDB and Cache entries. + * + * @param {string} url + * @return {boolean} + */ + + + 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 !== undefined ? timestamp < expireOlderThan : true; + } + } + /** + * Removes the IndexedDB object store used to keep track of cache expiration + * metadata. + */ + + + async delete() { + // Make sure we don't attempt another rerun if we're called in the middle of + // a cache expiration. + this._rerunRequested = false; + await this._timestampModel.expireEntries(Infinity); // Expires all. + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This plugin can be used in a `workbox-strategy` to regularly enforce a + * limit on the age and / or the number of cached requests. + * + * It can only be used with `workbox-strategy` instances that have a + * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies). + * In other words, it can't be used to expire entries in strategy that uses the + * default runtime cache name. + * + * Whenever a cached response is used or updated, this plugin will look + * at the associated cache and remove any old or extra responses. + * + * When using `maxAgeSeconds`, responses may be used *once* after expiring + * because the expiration clean up will not have occurred until *after* the + * cached response has been used. If the response has a "Date" header, then + * a light weight expiration check is performed and the response will not be + * used immediately. + * + * When using `maxEntries`, the entry least-recently requested will be removed + * from the cache first. + * + * @memberof workbox-expiration + */ + + class ExpirationPlugin { + /** + * @param {ExpirationPluginOptions} config + * @param {number} [config.maxEntries] The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. + * @param {number} [config.maxAgeSeconds] The maximum age of an entry before + * it's treated as stale and removed. + * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters) + * that will be used when calling `delete()` on the cache. + * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to + * automatic deletion if the available storage quota has been exceeded. + */ + constructor(config = {}) { + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when a `Response` is about to be returned + * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to + * the handler. It allows the `Response` to be inspected for freshness and + * prevents it from being used if the `Response`'s `Date` header value is + * older than the configured `maxAgeSeconds`. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache the response is in. + * @param {Response} options.cachedResponse The `Response` object that's been + * read from a cache and whose freshness should be checked. + * @return {Response} Either the `cachedResponse`, if it's + * fresh, or `null` if the `Response` is older than `maxAgeSeconds`. + * + * @private + */ + this.cachedResponseWillBeUsed = async ({ + event, + request, + cacheName, + cachedResponse + }) => { + if (!cachedResponse) { + return null; + } + + const isFresh = this._isResponseDateFresh(cachedResponse); // Expire entries to ensure that even if the expiration date has + // expired, it'll only be used once. + + + const cacheExpiration = this._getCacheExpiration(cacheName); + + dontWaitFor_js.dontWaitFor(cacheExpiration.expireEntries()); // Update the metadata for the request URL to the current timestamp, + // but don't `await` it as we don't want to block the response. + + const updateTimestampDone = cacheExpiration.updateTimestamp(request.url); + + if (event) { + try { + event.waitUntil(updateTimestampDone); + } catch (error) { + { + // The event may not be a fetch event; only log the URL if it is. + 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; + }; + /** + * A "lifecycle" callback that will be triggered automatically by the + * `workbox-strategies` handlers when an entry is added to a cache. + * + * @param {Object} options + * @param {string} options.cacheName Name of the cache that was updated. + * @param {string} options.request The Request for the cached entry. + * + * @private + */ + + + 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()); + } + } + /** + * A simple helper method to return a CacheExpiration instance for a given + * cache name. + * + * @param {string} cacheName + * @return {CacheExpiration} + * + * @private + */ + + + _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; + } + /** + * @param {Response} cachedResponse + * @return {boolean} + * + * @private + */ + + + _isResponseDateFresh(cachedResponse) { + if (!this._maxAgeSeconds) { + // We aren't expiring by age, so return true, it's fresh + return true; + } // Check if the 'date' header will suffice a quick expiration check. + // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for + // discussion. + + + const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse); + + if (dateHeaderTimestamp === null) { + // Unable to parse date, so assume it's fresh. + return true; + } // If we have a valid headerTime, then our response is fresh iff the + // headerTime plus maxAgeSeconds is greater than the current time. + + + const now = Date.now(); + return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000; + } + /** + * This method will extract the data header and parse it into a useful + * value. + * + * @param {Response} cachedResponse + * @return {number|null} + * + * @private + */ + + + _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 the Date header was invalid for some reason, parsedDate.getTime() + // will return NaN. + + if (isNaN(headerTime)) { + return null; + } + + return headerTime; + } + /** + * This is a helper method that performs two operations: + * + * - Deletes *all* the underlying Cache instances associated with this plugin + * instance, by calling caches.delete() on your behalf. + * - Deletes the metadata from IndexedDB used to keep track of expiration + * details for each Cache instance. + * + * When using cache expiration, calling this method is preferable to calling + * `caches.delete()` directly, since this will ensure that the IndexedDB + * metadata is also cleanly removed and open IndexedDB instances are deleted. + * + * Note that if you're *not* using cache expiration for a given cache, calling + * `caches.delete()` and passing in the cache's name should be sufficient. + * There is no Workbox-specific method needed for cleanup in that case. + */ + + + async deleteCacheAndMetadata() { + // Do this one at a time instead of all at once via `Promise.all()` to + // reduce the chance of inconsistency if a promise rejects. + for (const [cacheName, cacheExpiration] of this._cacheExpirations) { + await self.caches.delete(cacheName); + await cacheExpiration.delete(); + } // Reset this._cacheExpirations to its initial state. + + + 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)); +//# sourceMappingURL=workbox-expiration.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-expiration.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-expiration.dev.js.map new file mode 100644 index 0000000..7095cd1 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-expiration.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-expiration.dev.js","sources":["../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../_version.js","../models/CacheTimestampsModel.js","../CacheExpiration.js","../ExpirationPlugin.js"],"sourcesContent":["const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:expiration:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { openDB, deleteDB } from 'idb';\nimport '../_version.js';\nconst DB_NAME = 'workbox-expiration';\nconst CACHE_OBJECT_STORE = 'cache-entries';\nconst normalizeURL = (unNormalizedUrl) => {\n const url = new URL(unNormalizedUrl, location.href);\n url.hash = '';\n return url.href;\n};\n/**\n * Returns the timestamp model.\n *\n * @private\n */\nclass CacheTimestampsModel {\n /**\n *\n * @param {string} cacheName\n *\n * @private\n */\n constructor(cacheName) {\n this._db = null;\n this._cacheName = cacheName;\n }\n /**\n * Performs an upgrade of indexedDB.\n *\n * @param {IDBPDatabase} db\n *\n * @private\n */\n _upgradeDb(db) {\n // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we\n // have to use the `id` keyPath here and create our own values (a\n // concatenation of `url + cacheName`) instead of simply using\n // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.\n const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { keyPath: 'id' });\n // TODO(philipwalton): once we don't have to support EdgeHTML, we can\n // create a single index with the keyPath `['cacheName', 'timestamp']`\n // instead of doing both these indexes.\n objStore.createIndex('cacheName', 'cacheName', { unique: false });\n objStore.createIndex('timestamp', 'timestamp', { unique: false });\n }\n /**\n * Performs an upgrade of indexedDB and deletes deprecated DBs.\n *\n * @param {IDBPDatabase} db\n *\n * @private\n */\n _upgradeDbAndDeleteOldDbs(db) {\n this._upgradeDb(db);\n if (this._cacheName) {\n void deleteDB(this._cacheName);\n }\n }\n /**\n * @param {string} url\n * @param {number} timestamp\n *\n * @private\n */\n async setTimestamp(url, timestamp) {\n url = normalizeURL(url);\n const entry = {\n url,\n timestamp,\n cacheName: this._cacheName,\n // Creating an ID from the URL and cache name won't be necessary once\n // Edge switches to Chromium and all browsers we support work with\n // array keyPaths.\n id: this._getId(url),\n };\n const db = await this.getDb();\n const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', {\n durability: 'relaxed',\n });\n await tx.store.put(entry);\n await tx.done;\n }\n /**\n * Returns the timestamp stored for a given URL.\n *\n * @param {string} url\n * @return {number | undefined}\n *\n * @private\n */\n async getTimestamp(url) {\n const db = await this.getDb();\n const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));\n return entry === null || entry === void 0 ? void 0 : entry.timestamp;\n }\n /**\n * Iterates through all the entries in the object store (from newest to\n * oldest) and removes entries once either `maxCount` is reached or the\n * entry's timestamp is less than `minTimestamp`.\n *\n * @param {number} minTimestamp\n * @param {number} maxCount\n * @return {Array}\n *\n * @private\n */\n async expireEntries(minTimestamp, maxCount) {\n const db = await this.getDb();\n let cursor = await db\n .transaction(CACHE_OBJECT_STORE)\n .store.index('timestamp')\n .openCursor(null, 'prev');\n const entriesToDelete = [];\n let entriesNotDeletedCount = 0;\n while (cursor) {\n const result = cursor.value;\n // TODO(philipwalton): once we can use a multi-key index, we\n // won't have to check `cacheName` here.\n if (result.cacheName === this._cacheName) {\n // Delete an entry if it's older than the max age or\n // if we already have the max number allowed.\n if ((minTimestamp && result.timestamp < minTimestamp) ||\n (maxCount && entriesNotDeletedCount >= maxCount)) {\n // TODO(philipwalton): we should be able to delete the\n // entry right here, but doing so causes an iteration\n // bug in Safari stable (fixed in TP). Instead we can\n // store the keys of the entries to delete, and then\n // delete the separate transactions.\n // https://github.com/GoogleChrome/workbox/issues/1978\n // cursor.delete();\n // We only need to return the URL, not the whole entry.\n entriesToDelete.push(cursor.value);\n }\n else {\n entriesNotDeletedCount++;\n }\n }\n cursor = await cursor.continue();\n }\n // TODO(philipwalton): once the Safari bug in the following issue is fixed,\n // we should be able to remove this loop and do the entry deletion in the\n // cursor loop above:\n // https://github.com/GoogleChrome/workbox/issues/1978\n const urlsDeleted = [];\n for (const entry of entriesToDelete) {\n await db.delete(CACHE_OBJECT_STORE, entry.id);\n urlsDeleted.push(entry.url);\n }\n return urlsDeleted;\n }\n /**\n * Takes a URL and returns an ID that will be unique in the object store.\n *\n * @param {string} url\n * @return {string}\n *\n * @private\n */\n _getId(url) {\n // Creating an ID from the URL and cache name won't be necessary once\n // Edge switches to Chromium and all browsers we support work with\n // array keyPaths.\n return this._cacheName + '|' + normalizeURL(url);\n }\n /**\n * Returns an open connection to the database.\n *\n * @private\n */\n async getDb() {\n if (!this._db) {\n this._db = await openDB(DB_NAME, 1, {\n upgrade: this._upgradeDbAndDeleteOldDbs.bind(this),\n });\n }\n return this._db;\n }\n}\nexport { CacheTimestampsModel };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { CacheTimestampsModel } from './models/CacheTimestampsModel.js';\nimport './_version.js';\n/**\n * The `CacheExpiration` class allows you define an expiration and / or\n * limit on the number of responses stored in a\n * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).\n *\n * @memberof workbox-expiration\n */\nclass CacheExpiration {\n /**\n * To construct a new CacheExpiration instance you must provide at least\n * one of the `config` properties.\n *\n * @param {string} cacheName Name of the cache to apply restrictions to.\n * @param {Object} config\n * @param {number} [config.maxEntries] The maximum number of entries to cache.\n * Entries used the least will be removed as the maximum is reached.\n * @param {number} [config.maxAgeSeconds] The maximum age of an entry before\n * it's treated as stale and removed.\n * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)\n * that will be used when calling `delete()` on the cache.\n */\n constructor(cacheName, config = {}) {\n this._isRunning = false;\n this._rerunRequested = false;\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(cacheName, 'string', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'cacheName',\n });\n if (!(config.maxEntries || config.maxAgeSeconds)) {\n throw new WorkboxError('max-entries-or-age-required', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n });\n }\n if (config.maxEntries) {\n assert.isType(config.maxEntries, 'number', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'config.maxEntries',\n });\n }\n if (config.maxAgeSeconds) {\n assert.isType(config.maxAgeSeconds, 'number', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'config.maxAgeSeconds',\n });\n }\n }\n this._maxEntries = config.maxEntries;\n this._maxAgeSeconds = config.maxAgeSeconds;\n this._matchOptions = config.matchOptions;\n this._cacheName = cacheName;\n this._timestampModel = new CacheTimestampsModel(cacheName);\n }\n /**\n * Expires entries for the given cache and given criteria.\n */\n async expireEntries() {\n if (this._isRunning) {\n this._rerunRequested = true;\n return;\n }\n this._isRunning = true;\n const minTimestamp = this._maxAgeSeconds\n ? Date.now() - this._maxAgeSeconds * 1000\n : 0;\n const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);\n // Delete URLs from the cache\n const cache = await self.caches.open(this._cacheName);\n for (const url of urlsExpired) {\n await cache.delete(url, this._matchOptions);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (urlsExpired.length > 0) {\n logger.groupCollapsed(`Expired ${urlsExpired.length} ` +\n `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` +\n `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` +\n `'${this._cacheName}' cache.`);\n logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);\n urlsExpired.forEach((url) => logger.log(` ${url}`));\n logger.groupEnd();\n }\n else {\n logger.debug(`Cache expiration ran and found no entries to remove.`);\n }\n }\n this._isRunning = false;\n if (this._rerunRequested) {\n this._rerunRequested = false;\n dontWaitFor(this.expireEntries());\n }\n }\n /**\n * Update the timestamp for the given URL. This ensures the when\n * removing entries based on maximum entries, most recently used\n * is accurate or when expiring, the timestamp is up-to-date.\n *\n * @param {string} url\n */\n async updateTimestamp(url) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(url, 'string', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'updateTimestamp',\n paramName: 'url',\n });\n }\n await this._timestampModel.setTimestamp(url, Date.now());\n }\n /**\n * Can be used to check if a URL has expired or not before it's used.\n *\n * This requires a look up from IndexedDB, so can be slow.\n *\n * Note: This method will not remove the cached entry, call\n * `expireEntries()` to remove indexedDB and Cache entries.\n *\n * @param {string} url\n * @return {boolean}\n */\n async isURLExpired(url) {\n if (!this._maxAgeSeconds) {\n if (process.env.NODE_ENV !== 'production') {\n throw new WorkboxError(`expired-test-without-max-age`, {\n methodName: 'isURLExpired',\n paramName: 'maxAgeSeconds',\n });\n }\n return false;\n }\n else {\n const timestamp = await this._timestampModel.getTimestamp(url);\n const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;\n return timestamp !== undefined ? timestamp < expireOlderThan : true;\n }\n }\n /**\n * Removes the IndexedDB object store used to keep track of cache expiration\n * metadata.\n */\n async delete() {\n // Make sure we don't attempt another rerun if we're called in the middle of\n // a cache expiration.\n this._rerunRequested = false;\n await this._timestampModel.expireEntries(Infinity); // Expires all.\n }\n}\nexport { CacheExpiration };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { registerQuotaErrorCallback } from 'workbox-core/registerQuotaErrorCallback.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { CacheExpiration } from './CacheExpiration.js';\nimport './_version.js';\n/**\n * This plugin can be used in a `workbox-strategy` to regularly enforce a\n * limit on the age and / or the number of cached requests.\n *\n * It can only be used with `workbox-strategy` instances that have a\n * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies).\n * In other words, it can't be used to expire entries in strategy that uses the\n * default runtime cache name.\n *\n * Whenever a cached response is used or updated, this plugin will look\n * at the associated cache and remove any old or extra responses.\n *\n * When using `maxAgeSeconds`, responses may be used *once* after expiring\n * because the expiration clean up will not have occurred until *after* the\n * cached response has been used. If the response has a \"Date\" header, then\n * a light weight expiration check is performed and the response will not be\n * used immediately.\n *\n * When using `maxEntries`, the entry least-recently requested will be removed\n * from the cache first.\n *\n * @memberof workbox-expiration\n */\nclass ExpirationPlugin {\n /**\n * @param {ExpirationPluginOptions} config\n * @param {number} [config.maxEntries] The maximum number of entries to cache.\n * Entries used the least will be removed as the maximum is reached.\n * @param {number} [config.maxAgeSeconds] The maximum age of an entry before\n * it's treated as stale and removed.\n * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)\n * that will be used when calling `delete()` on the cache.\n * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to\n * automatic deletion if the available storage quota has been exceeded.\n */\n constructor(config = {}) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-strategies` handlers when a `Response` is about to be returned\n * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to\n * the handler. It allows the `Response` to be inspected for freshness and\n * prevents it from being used if the `Response`'s `Date` header value is\n * older than the configured `maxAgeSeconds`.\n *\n * @param {Object} options\n * @param {string} options.cacheName Name of the cache the response is in.\n * @param {Response} options.cachedResponse The `Response` object that's been\n * read from a cache and whose freshness should be checked.\n * @return {Response} Either the `cachedResponse`, if it's\n * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.\n *\n * @private\n */\n this.cachedResponseWillBeUsed = async ({ event, request, cacheName, cachedResponse, }) => {\n if (!cachedResponse) {\n return null;\n }\n const isFresh = this._isResponseDateFresh(cachedResponse);\n // Expire entries to ensure that even if the expiration date has\n // expired, it'll only be used once.\n const cacheExpiration = this._getCacheExpiration(cacheName);\n dontWaitFor(cacheExpiration.expireEntries());\n // Update the metadata for the request URL to the current timestamp,\n // but don't `await` it as we don't want to block the response.\n const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);\n if (event) {\n try {\n event.waitUntil(updateTimestampDone);\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n // The event may not be a fetch event; only log the URL if it is.\n if ('request' in event) {\n logger.warn(`Unable to ensure service worker stays alive when ` +\n `updating cache entry for ` +\n `'${getFriendlyURL(event.request.url)}'.`);\n }\n }\n }\n }\n return isFresh ? cachedResponse : null;\n };\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-strategies` handlers when an entry is added to a cache.\n *\n * @param {Object} options\n * @param {string} options.cacheName Name of the cache that was updated.\n * @param {string} options.request The Request for the cached entry.\n *\n * @private\n */\n this.cacheDidUpdate = async ({ cacheName, request, }) => {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(cacheName, 'string', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'cacheDidUpdate',\n paramName: 'cacheName',\n });\n assert.isInstance(request, Request, {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'cacheDidUpdate',\n paramName: 'request',\n });\n }\n const cacheExpiration = this._getCacheExpiration(cacheName);\n await cacheExpiration.updateTimestamp(request.url);\n await cacheExpiration.expireEntries();\n };\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.maxEntries || config.maxAgeSeconds)) {\n throw new WorkboxError('max-entries-or-age-required', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n });\n }\n if (config.maxEntries) {\n assert.isType(config.maxEntries, 'number', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n paramName: 'config.maxEntries',\n });\n }\n if (config.maxAgeSeconds) {\n assert.isType(config.maxAgeSeconds, 'number', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n paramName: 'config.maxAgeSeconds',\n });\n }\n }\n this._config = config;\n this._maxAgeSeconds = config.maxAgeSeconds;\n this._cacheExpirations = new Map();\n if (config.purgeOnQuotaError) {\n registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());\n }\n }\n /**\n * A simple helper method to return a CacheExpiration instance for a given\n * cache name.\n *\n * @param {string} cacheName\n * @return {CacheExpiration}\n *\n * @private\n */\n _getCacheExpiration(cacheName) {\n if (cacheName === cacheNames.getRuntimeName()) {\n throw new WorkboxError('expire-custom-caches-only');\n }\n let cacheExpiration = this._cacheExpirations.get(cacheName);\n if (!cacheExpiration) {\n cacheExpiration = new CacheExpiration(cacheName, this._config);\n this._cacheExpirations.set(cacheName, cacheExpiration);\n }\n return cacheExpiration;\n }\n /**\n * @param {Response} cachedResponse\n * @return {boolean}\n *\n * @private\n */\n _isResponseDateFresh(cachedResponse) {\n if (!this._maxAgeSeconds) {\n // We aren't expiring by age, so return true, it's fresh\n return true;\n }\n // Check if the 'date' header will suffice a quick expiration check.\n // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for\n // discussion.\n const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);\n if (dateHeaderTimestamp === null) {\n // Unable to parse date, so assume it's fresh.\n return true;\n }\n // If we have a valid headerTime, then our response is fresh iff the\n // headerTime plus maxAgeSeconds is greater than the current time.\n const now = Date.now();\n return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;\n }\n /**\n * This method will extract the data header and parse it into a useful\n * value.\n *\n * @param {Response} cachedResponse\n * @return {number|null}\n *\n * @private\n */\n _getDateHeaderTimestamp(cachedResponse) {\n if (!cachedResponse.headers.has('date')) {\n return null;\n }\n const dateHeader = cachedResponse.headers.get('date');\n const parsedDate = new Date(dateHeader);\n const headerTime = parsedDate.getTime();\n // If the Date header was invalid for some reason, parsedDate.getTime()\n // will return NaN.\n if (isNaN(headerTime)) {\n return null;\n }\n return headerTime;\n }\n /**\n * This is a helper method that performs two operations:\n *\n * - Deletes *all* the underlying Cache instances associated with this plugin\n * instance, by calling caches.delete() on your behalf.\n * - Deletes the metadata from IndexedDB used to keep track of expiration\n * details for each Cache instance.\n *\n * When using cache expiration, calling this method is preferable to calling\n * `caches.delete()` directly, since this will ensure that the IndexedDB\n * metadata is also cleanly removed and open IndexedDB instances are deleted.\n *\n * Note that if you're *not* using cache expiration for a given cache, calling\n * `caches.delete()` and passing in the cache's name should be sufficient.\n * There is no Workbox-specific method needed for cleanup in that case.\n */\n async deleteCacheAndMetadata() {\n // Do this one at a time instead of all at once via `Promise.all()` to\n // reduce the chance of inconsistency if a promise rejects.\n for (const [cacheName, cacheExpiration] of this._cacheExpirations) {\n await self.caches.delete(cacheName);\n await cacheExpiration.delete();\n }\n // Reset this._cacheExpirations to its initial state.\n this._cacheExpirations = new Map();\n }\n}\nexport { ExpirationPlugin };\n"],"names":["instanceOfAny","object","constructors","some","c","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","IDBDatabase","IDBObjectStore","IDBIndex","IDBCursor","IDBTransaction","getCursorAdvanceMethods","prototype","advance","continue","continuePrimaryKey","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","promisifyRequest","request","promise","Promise","resolve","reject","unlisten","removeEventListener","success","error","wrap","result","addEventListener","then","value","set","catch","cacheDonePromiseForTransaction","tx","has","done","complete","DOMException","idbProxyTraps","get","target","prop","receiver","objectStoreNames","undefined","objectStore","replaceTraps","callback","wrapFunction","func","transaction","storeNames","args","call","unwrap","sort","includes","apply","transformCachableValue","Proxy","IDBRequest","newValue","openDB","name","version","blocked","upgrade","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","db","deleteDB","deleteDatabase","readMethods","writeMethods","cachedMethods","Map","getMethod","targetFuncName","replace","useIndex","isWrite","method","storeName","store","index","shift","all","oldTraps","self","_","e","DB_NAME","CACHE_OBJECT_STORE","normalizeURL","unNormalizedUrl","url","URL","location","href","hash","CacheTimestampsModel","constructor","cacheName","_db","_cacheName","_upgradeDb","objStore","createObjectStore","keyPath","createIndex","unique","_upgradeDbAndDeleteOldDbs","setTimestamp","timestamp","entry","id","_getId","getDb","durability","put","getTimestamp","expireEntries","minTimestamp","maxCount","cursor","openCursor","entriesToDelete","entriesNotDeletedCount","push","urlsDeleted","delete","bind","CacheExpiration","config","_isRunning","_rerunRequested","assert","isType","moduleName","className","funcName","paramName","maxEntries","maxAgeSeconds","WorkboxError","_maxEntries","_maxAgeSeconds","_matchOptions","matchOptions","_timestampModel","Date","now","urlsExpired","cache","caches","length","logger","groupCollapsed","log","forEach","groupEnd","debug","dontWaitFor","updateTimestamp","isURLExpired","methodName","expireOlderThan","Infinity","ExpirationPlugin","cachedResponseWillBeUsed","cachedResponse","isFresh","_isResponseDateFresh","cacheExpiration","_getCacheExpiration","updateTimestampDone","waitUntil","warn","getFriendlyURL","cacheDidUpdate","isInstance","Request","_config","_cacheExpirations","purgeOnQuotaError","registerQuotaErrorCallback","deleteCacheAndMetadata","cacheNames","getRuntimeName","dateHeaderTimestamp","_getDateHeaderTimestamp","headers","dateHeader","parsedDate","headerTime","getTime","isNaN"],"mappings":";;;;;;;;;;;;;;;;;;;;;;EAAA,MAAMA,aAAa,GAAG,CAACC,MAAD,EAASC,YAAT,KAA0BA,YAAY,CAACC,IAAb,CAAmBC,CAAD,IAAOH,MAAM,YAAYG,CAA3C,CAAhD;;EAEA,IAAIC,iBAAJ;EACA,IAAIC,oBAAJ;;EAEA,SAASC,o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AzB;EACH;;EApNkB;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-expiration.prod.js b/src/Resources/workbox-v7.0.0/workbox-expiration.prod.js new file mode 100644 index 0000000..ef83f36 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-expiration.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.expiration=function(t,e,n,s,i){"use strict";function r(){return r=Object.assign||function(t){for(var e=1;ee.some((e=>t instanceof e));let o,c;const u=new WeakMap,h=new WeakMap,f=new WeakMap,l=new WeakMap,d=new WeakMap;let w={get(t,e,n){if(t instanceof IDBTransaction){if("done"===e)return h.get(t);if("objectStoreNames"===e)return t.objectStoreNames||f.get(t);if("store"===e)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return m(t[e])},set:(t,e,n)=>(t[e]=n,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function p(t){return t!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(c||(c=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(b(this),e),m(u.get(this))}:function(...e){return m(t.apply(b(this),e))}:function(e,...n){const s=t.call(b(this),e,...n);return f.set(s,e.sort?e.sort():[e]),m(s)}}function D(t){return"function"==typeof t?p(t):(t instanceof IDBTransaction&&function(t){if(h.has(t))return;const e=new Promise(((e,n)=>{const s=()=>{t.removeEventListener("complete",i),t.removeEventListener("error",r),t.removeEventListener("abort",r)},i=()=>{e(),s()},r=()=>{n(t.error||new DOMException("AbortError","AbortError")),s()};t.addEventListener("complete",i),t.addEventListener("error",r),t.addEventListener("abort",r)}));h.set(t,e)}(t),a(t,o||(o=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,w):t)}function m(t){if(t instanceof IDBRequest)return function(t){const e=new Promise(((e,n)=>{const s=()=>{t.removeEventListener("success",i),t.removeEventListener("error",r)},i=()=>{e(m(t.result)),s()},r=()=>{n(t.error),s()};t.addEventListener("success",i),t.addEventListener("error",r)}));return e.then((e=>{e instanceof IDBCursor&&u.set(e,t)})).catch((()=>{})),d.set(e,t),e}(t);if(l.has(t))return l.get(t);const e=D(t);return e!==t&&(l.set(t,e),d.set(e,t)),e}const b=t=>d.get(t);const y=["get","getKey","getAll","getAllKeys","count"],I=["put","add","delete","clear"],B=new Map;function g(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(B.get(e))return B.get(e);const n=e.replace(/FromIndex$/,""),s=e!==n,i=I.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!i&&!y.includes(n))return;const r=async function(t,...e){const r=this.transaction(t,i?"readwrite":"readonly");let a=r.store;return s&&(a=a.index(e.shift())),(await Promise.all([a[n](...e),i&&r.done]))[0]};return B.set(e,r),r}w=(t=>r({},t,{get:(e,n,s)=>g(e,n)||t.get(e,n,s),has:(e,n)=>!!g(e,n)||t.has(e,n)}))(w);try{self["workbox:expiration:7.0.0"]&&_()}catch(t){}const x="cache-entries",k=t=>{const e=new URL(t,location.href);return e.hash="",e.href};class v{constructor(t){this.t=null,this.M=t}i(t){const e=t.createObjectStore(x,{keyPath:"id"});e.createIndex("cacheName","cacheName",{unique:!1}),e.createIndex("timestamp","timestamp",{unique:!1})}N(t){this.i(t),this.M&&function(t,{blocked:e}={}){const n=indexedDB.deleteDatabase(t);e&&n.addEventListener("blocked",(()=>e())),m(n).then((()=>{}))}(this.M)}async setTimestamp(t,e){const n={url:t=k(t),timestamp:e,cacheName:this.M,id:this.T(t)},s=(await this.getDb()).transaction(x,"readwrite",{durability:"relaxed"});await s.store.put(n),await s.done}async getTimestamp(t){const e=await this.getDb(),n=await e.get(x,this.T(t));return null==n?void 0:n.timestamp}async expireEntries(t,e){const n=await this.getDb();let s=await n.transaction(x).store.index("timestamp").openCursor(null,"prev");const i=[];let r=0;for(;s;){const n=s.value;n.cacheName===this.M&&(t&&n.timestamp=e?i.push(s.value):r++),s=await s.continue()}const a=[];for(const t of i)await n.delete(x,t.id),a.push(t.url);return a}T(t){return this.M+"|"+k(t)}async getDb(){return this.t||(this.t=await function(t,e,{blocked:n,upgrade:s,blocking:i,terminated:r}={}){const a=indexedDB.open(t,e),o=m(a);return s&&a.addEventListener("upgradeneeded",(t=>{s(m(a.result),t.oldVersion,t.newVersion,m(a.transaction))})),n&&a.addEventListener("blocked",(()=>n())),o.then((t=>{r&&t.addEventListener("close",(()=>r())),i&&t.addEventListener("versionchange",(()=>i()))})).catch((()=>{})),o}("workbox-expiration",1,{upgrade:this.N.bind(this)})),this.t}}class M{constructor(t,e={}){this.P=!1,this.W=!1,this.K=e.maxEntries,this.L=e.maxAgeSeconds,this.H=e.matchOptions,this.M=t,this.$=new v(t)}async expireEntries(){if(this.P)return void(this.W=!0);this.P=!0;const t=this.L?Date.now()-1e3*this.L:0,n=await this.$.expireEntries(t,this.K),s=await self.caches.open(this.M);for(const t of n)await s.delete(t,this.H);this.P=!1,this.W&&(this.W=!1,e.dontWaitFor(this.expireEntries()))}async updateTimestamp(t){await this.$.setTimestamp(t,Date.now())}async isURLExpired(t){if(this.L){const e=await this.$.getTimestamp(t),n=Date.now()-1e3*this.L;return void 0===e||e{if(!i)return null;const r=this.J(i),a=this.V(s);e.dontWaitFor(a.expireEntries());const o=a.updateTimestamp(n.url);if(t)try{t.waitUntil(o)}catch(t){}return r?i:null},this.cacheDidUpdate=async({cacheName:t,request:e})=>{const n=this.V(t);await n.updateTimestamp(e.url),await n.expireEntries()},this.X=t,this.L=t.maxAgeSeconds,this.Y=new Map,t.purgeOnQuotaError&&s.registerQuotaErrorCallback((()=>this.deleteCacheAndMetadata()))}V(t){if(t===n.cacheNames.getRuntimeName())throw new i.WorkboxError("expire-custom-caches-only");let e=this.Y.get(t);return e||(e=new M(t,this.X),this.Y.set(t,e)),e}J(t){if(!this.L)return!0;const e=this.Z(t);if(null===e)return!0;return e>=Date.now()-1e3*this.L}Z(t){if(!t.headers.has("date"))return null;const e=t.headers.get("date"),n=new Date(e).getTime();return isNaN(n)?null:n}async deleteCacheAndMetadata(){for(const[t,e]of this.Y)await self.caches.delete(t),await e.delete();this.Y=new Map}},t}({},workbox.core._private,workbox.core._private,workbox.core,workbox.core._private); +//# sourceMappingURL=workbox-expiration.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-expiration.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-expiration.prod.js.map new file mode 100644 index 0000000..20f1cee --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-expiration.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-expiration.prod.js","sources":["../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../_version.js","../models/CacheTimestampsModel.js","../CacheExpiration.js","../ExpirationPlugin.js"],"sourcesContent":["const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:expiration:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { openDB, deleteDB } from 'idb';\nimport '../_version.js';\nconst DB_NAME = 'workbox-expiration';\nconst CACHE_OBJECT_STORE = 'cache-entries';\nconst normalizeURL = (unNormalizedUrl) => {\n const url = new URL(unNormalizedUrl, location.href);\n url.hash = '';\n return url.href;\n};\n/**\n * Returns the timestamp model.\n *\n * @private\n */\nclass CacheTimestampsModel {\n /**\n *\n * @param {string} cacheName\n *\n * @private\n */\n constructor(cacheName) {\n this._db = null;\n this._cacheName = cacheName;\n }\n /**\n * Performs an upgrade of indexedDB.\n *\n * @param {IDBPDatabase} db\n *\n * @private\n */\n _upgradeDb(db) {\n // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we\n // have to use the `id` keyPath here and create our own values (a\n // concatenation of `url + cacheName`) instead of simply using\n // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.\n const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { keyPath: 'id' });\n // TODO(philipwalton): once we don't have to support EdgeHTML, we can\n // create a single index with the keyPath `['cacheName', 'timestamp']`\n // instead of doing both these indexes.\n objStore.createIndex('cacheName', 'cacheName', { unique: false });\n objStore.createIndex('timestamp', 'timestamp', { unique: false });\n }\n /**\n * Performs an upgrade of indexedDB and deletes deprecated DBs.\n *\n * @param {IDBPDatabase} db\n *\n * @private\n */\n _upgradeDbAndDeleteOldDbs(db) {\n this._upgradeDb(db);\n if (this._cacheName) {\n void deleteDB(this._cacheName);\n }\n }\n /**\n * @param {string} url\n * @param {number} timestamp\n *\n * @private\n */\n async setTimestamp(url, timestamp) {\n url = normalizeURL(url);\n const entry = {\n url,\n timestamp,\n cacheName: this._cacheName,\n // Creating an ID from the URL and cache name won't be necessary once\n // Edge switches to Chromium and all browsers we support work with\n // array keyPaths.\n id: this._getId(url),\n };\n const db = await this.getDb();\n const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', {\n durability: 'relaxed',\n });\n await tx.store.put(entry);\n await tx.done;\n }\n /**\n * Returns the timestamp stored for a given URL.\n *\n * @param {string} url\n * @return {number | undefined}\n *\n * @private\n */\n async getTimestamp(url) {\n const db = await this.getDb();\n const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));\n return entry === null || entry === void 0 ? void 0 : entry.timestamp;\n }\n /**\n * Iterates through all the entries in the object store (from newest to\n * oldest) and removes entries once either `maxCount` is reached or the\n * entry's timestamp is less than `minTimestamp`.\n *\n * @param {number} minTimestamp\n * @param {number} maxCount\n * @return {Array}\n *\n * @private\n */\n async expireEntries(minTimestamp, maxCount) {\n const db = await this.getDb();\n let cursor = await db\n .transaction(CACHE_OBJECT_STORE)\n .store.index('timestamp')\n .openCursor(null, 'prev');\n const entriesToDelete = [];\n let entriesNotDeletedCount = 0;\n while (cursor) {\n const result = cursor.value;\n // TODO(philipwalton): once we can use a multi-key index, we\n // won't have to check `cacheName` here.\n if (result.cacheName === this._cacheName) {\n // Delete an entry if it's older than the max age or\n // if we already have the max number allowed.\n if ((minTimestamp && result.timestamp < minTimestamp) ||\n (maxCount && entriesNotDeletedCount >= maxCount)) {\n // TODO(philipwalton): we should be able to delete the\n // entry right here, but doing so causes an iteration\n // bug in Safari stable (fixed in TP). Instead we can\n // store the keys of the entries to delete, and then\n // delete the separate transactions.\n // https://github.com/GoogleChrome/workbox/issues/1978\n // cursor.delete();\n // We only need to return the URL, not the whole entry.\n entriesToDelete.push(cursor.value);\n }\n else {\n entriesNotDeletedCount++;\n }\n }\n cursor = await cursor.continue();\n }\n // TODO(philipwalton): once the Safari bug in the following issue is fixed,\n // we should be able to remove this loop and do the entry deletion in the\n // cursor loop above:\n // https://github.com/GoogleChrome/workbox/issues/1978\n const urlsDeleted = [];\n for (const entry of entriesToDelete) {\n await db.delete(CACHE_OBJECT_STORE, entry.id);\n urlsDeleted.push(entry.url);\n }\n return urlsDeleted;\n }\n /**\n * Takes a URL and returns an ID that will be unique in the object store.\n *\n * @param {string} url\n * @return {string}\n *\n * @private\n */\n _getId(url) {\n // Creating an ID from the URL and cache name won't be necessary once\n // Edge switches to Chromium and all browsers we support work with\n // array keyPaths.\n return this._cacheName + '|' + normalizeURL(url);\n }\n /**\n * Returns an open connection to the database.\n *\n * @private\n */\n async getDb() {\n if (!this._db) {\n this._db = await openDB(DB_NAME, 1, {\n upgrade: this._upgradeDbAndDeleteOldDbs.bind(this),\n });\n }\n return this._db;\n }\n}\nexport { CacheTimestampsModel };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { CacheTimestampsModel } from './models/CacheTimestampsModel.js';\nimport './_version.js';\n/**\n * The `CacheExpiration` class allows you define an expiration and / or\n * limit on the number of responses stored in a\n * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).\n *\n * @memberof workbox-expiration\n */\nclass CacheExpiration {\n /**\n * To construct a new CacheExpiration instance you must provide at least\n * one of the `config` properties.\n *\n * @param {string} cacheName Name of the cache to apply restrictions to.\n * @param {Object} config\n * @param {number} [config.maxEntries] The maximum number of entries to cache.\n * Entries used the least will be removed as the maximum is reached.\n * @param {number} [config.maxAgeSeconds] The maximum age of an entry before\n * it's treated as stale and removed.\n * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)\n * that will be used when calling `delete()` on the cache.\n */\n constructor(cacheName, config = {}) {\n this._isRunning = false;\n this._rerunRequested = false;\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(cacheName, 'string', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'cacheName',\n });\n if (!(config.maxEntries || config.maxAgeSeconds)) {\n throw new WorkboxError('max-entries-or-age-required', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n });\n }\n if (config.maxEntries) {\n assert.isType(config.maxEntries, 'number', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'config.maxEntries',\n });\n }\n if (config.maxAgeSeconds) {\n assert.isType(config.maxAgeSeconds, 'number', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'constructor',\n paramName: 'config.maxAgeSeconds',\n });\n }\n }\n this._maxEntries = config.maxEntries;\n this._maxAgeSeconds = config.maxAgeSeconds;\n this._matchOptions = config.matchOptions;\n this._cacheName = cacheName;\n this._timestampModel = new CacheTimestampsModel(cacheName);\n }\n /**\n * Expires entries for the given cache and given criteria.\n */\n async expireEntries() {\n if (this._isRunning) {\n this._rerunRequested = true;\n return;\n }\n this._isRunning = true;\n const minTimestamp = this._maxAgeSeconds\n ? Date.now() - this._maxAgeSeconds * 1000\n : 0;\n const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);\n // Delete URLs from the cache\n const cache = await self.caches.open(this._cacheName);\n for (const url of urlsExpired) {\n await cache.delete(url, this._matchOptions);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (urlsExpired.length > 0) {\n logger.groupCollapsed(`Expired ${urlsExpired.length} ` +\n `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` +\n `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` +\n `'${this._cacheName}' cache.`);\n logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);\n urlsExpired.forEach((url) => logger.log(` ${url}`));\n logger.groupEnd();\n }\n else {\n logger.debug(`Cache expiration ran and found no entries to remove.`);\n }\n }\n this._isRunning = false;\n if (this._rerunRequested) {\n this._rerunRequested = false;\n dontWaitFor(this.expireEntries());\n }\n }\n /**\n * Update the timestamp for the given URL. This ensures the when\n * removing entries based on maximum entries, most recently used\n * is accurate or when expiring, the timestamp is up-to-date.\n *\n * @param {string} url\n */\n async updateTimestamp(url) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(url, 'string', {\n moduleName: 'workbox-expiration',\n className: 'CacheExpiration',\n funcName: 'updateTimestamp',\n paramName: 'url',\n });\n }\n await this._timestampModel.setTimestamp(url, Date.now());\n }\n /**\n * Can be used to check if a URL has expired or not before it's used.\n *\n * This requires a look up from IndexedDB, so can be slow.\n *\n * Note: This method will not remove the cached entry, call\n * `expireEntries()` to remove indexedDB and Cache entries.\n *\n * @param {string} url\n * @return {boolean}\n */\n async isURLExpired(url) {\n if (!this._maxAgeSeconds) {\n if (process.env.NODE_ENV !== 'production') {\n throw new WorkboxError(`expired-test-without-max-age`, {\n methodName: 'isURLExpired',\n paramName: 'maxAgeSeconds',\n });\n }\n return false;\n }\n else {\n const timestamp = await this._timestampModel.getTimestamp(url);\n const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;\n return timestamp !== undefined ? timestamp < expireOlderThan : true;\n }\n }\n /**\n * Removes the IndexedDB object store used to keep track of cache expiration\n * metadata.\n */\n async delete() {\n // Make sure we don't attempt another rerun if we're called in the middle of\n // a cache expiration.\n this._rerunRequested = false;\n await this._timestampModel.expireEntries(Infinity); // Expires all.\n }\n}\nexport { CacheExpiration };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { registerQuotaErrorCallback } from 'workbox-core/registerQuotaErrorCallback.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { CacheExpiration } from './CacheExpiration.js';\nimport './_version.js';\n/**\n * This plugin can be used in a `workbox-strategy` to regularly enforce a\n * limit on the age and / or the number of cached requests.\n *\n * It can only be used with `workbox-strategy` instances that have a\n * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies).\n * In other words, it can't be used to expire entries in strategy that uses the\n * default runtime cache name.\n *\n * Whenever a cached response is used or updated, this plugin will look\n * at the associated cache and remove any old or extra responses.\n *\n * When using `maxAgeSeconds`, responses may be used *once* after expiring\n * because the expiration clean up will not have occurred until *after* the\n * cached response has been used. If the response has a \"Date\" header, then\n * a light weight expiration check is performed and the response will not be\n * used immediately.\n *\n * When using `maxEntries`, the entry least-recently requested will be removed\n * from the cache first.\n *\n * @memberof workbox-expiration\n */\nclass ExpirationPlugin {\n /**\n * @param {ExpirationPluginOptions} config\n * @param {number} [config.maxEntries] The maximum number of entries to cache.\n * Entries used the least will be removed as the maximum is reached.\n * @param {number} [config.maxAgeSeconds] The maximum age of an entry before\n * it's treated as stale and removed.\n * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)\n * that will be used when calling `delete()` on the cache.\n * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to\n * automatic deletion if the available storage quota has been exceeded.\n */\n constructor(config = {}) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-strategies` handlers when a `Response` is about to be returned\n * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to\n * the handler. It allows the `Response` to be inspected for freshness and\n * prevents it from being used if the `Response`'s `Date` header value is\n * older than the configured `maxAgeSeconds`.\n *\n * @param {Object} options\n * @param {string} options.cacheName Name of the cache the response is in.\n * @param {Response} options.cachedResponse The `Response` object that's been\n * read from a cache and whose freshness should be checked.\n * @return {Response} Either the `cachedResponse`, if it's\n * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.\n *\n * @private\n */\n this.cachedResponseWillBeUsed = async ({ event, request, cacheName, cachedResponse, }) => {\n if (!cachedResponse) {\n return null;\n }\n const isFresh = this._isResponseDateFresh(cachedResponse);\n // Expire entries to ensure that even if the expiration date has\n // expired, it'll only be used once.\n const cacheExpiration = this._getCacheExpiration(cacheName);\n dontWaitFor(cacheExpiration.expireEntries());\n // Update the metadata for the request URL to the current timestamp,\n // but don't `await` it as we don't want to block the response.\n const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);\n if (event) {\n try {\n event.waitUntil(updateTimestampDone);\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n // The event may not be a fetch event; only log the URL if it is.\n if ('request' in event) {\n logger.warn(`Unable to ensure service worker stays alive when ` +\n `updating cache entry for ` +\n `'${getFriendlyURL(event.request.url)}'.`);\n }\n }\n }\n }\n return isFresh ? cachedResponse : null;\n };\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-strategies` handlers when an entry is added to a cache.\n *\n * @param {Object} options\n * @param {string} options.cacheName Name of the cache that was updated.\n * @param {string} options.request The Request for the cached entry.\n *\n * @private\n */\n this.cacheDidUpdate = async ({ cacheName, request, }) => {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(cacheName, 'string', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'cacheDidUpdate',\n paramName: 'cacheName',\n });\n assert.isInstance(request, Request, {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'cacheDidUpdate',\n paramName: 'request',\n });\n }\n const cacheExpiration = this._getCacheExpiration(cacheName);\n await cacheExpiration.updateTimestamp(request.url);\n await cacheExpiration.expireEntries();\n };\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.maxEntries || config.maxAgeSeconds)) {\n throw new WorkboxError('max-entries-or-age-required', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n });\n }\n if (config.maxEntries) {\n assert.isType(config.maxEntries, 'number', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n paramName: 'config.maxEntries',\n });\n }\n if (config.maxAgeSeconds) {\n assert.isType(config.maxAgeSeconds, 'number', {\n moduleName: 'workbox-expiration',\n className: 'Plugin',\n funcName: 'constructor',\n paramName: 'config.maxAgeSeconds',\n });\n }\n }\n this._config = config;\n this._maxAgeSeconds = config.maxAgeSeconds;\n this._cacheExpirations = new Map();\n if (config.purgeOnQuotaError) {\n registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());\n }\n }\n /**\n * A simple helper method to return a CacheExpiration instance for a given\n * cache name.\n *\n * @param {string} cacheName\n * @return {CacheExpiration}\n *\n * @private\n */\n _getCacheExpiration(cacheName) {\n if (cacheName === cacheNames.getRuntimeName()) {\n throw new WorkboxError('expire-custom-caches-only');\n }\n let cacheExpiration = this._cacheExpirations.get(cacheName);\n if (!cacheExpiration) {\n cacheExpiration = new CacheExpiration(cacheName, this._config);\n this._cacheExpirations.set(cacheName, cacheExpiration);\n }\n return cacheExpiration;\n }\n /**\n * @param {Response} cachedResponse\n * @return {boolean}\n *\n * @private\n */\n _isResponseDateFresh(cachedResponse) {\n if (!this._maxAgeSeconds) {\n // We aren't expiring by age, so return true, it's fresh\n return true;\n }\n // Check if the 'date' header will suffice a quick expiration check.\n // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for\n // discussion.\n const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);\n if (dateHeaderTimestamp === null) {\n // Unable to parse date, so assume it's fresh.\n return true;\n }\n // If we have a valid headerTime, then our response is fresh iff the\n // headerTime plus maxAgeSeconds is greater than the current time.\n const now = Date.now();\n return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;\n }\n /**\n * This method will extract the data header and parse it into a useful\n * value.\n *\n * @param {Response} cachedResponse\n * @return {number|null}\n *\n * @private\n */\n _getDateHeaderTimestamp(cachedResponse) {\n if (!cachedResponse.headers.has('date')) {\n return null;\n }\n const dateHeader = cachedResponse.headers.get('date');\n const parsedDate = new Date(dateHeader);\n const headerTime = parsedDate.getTime();\n // If the Date header was invalid for some reason, parsedDate.getTime()\n // will return NaN.\n if (isNaN(headerTime)) {\n return null;\n }\n return headerTime;\n }\n /**\n * This is a helper method that performs two operations:\n *\n * - Deletes *all* the underlying Cache instances associated with this plugin\n * instance, by calling caches.delete() on your behalf.\n * - Deletes the metadata from IndexedDB used to keep track of expiration\n * details for each Cache instance.\n *\n * When using cache expiration, calling this method is preferable to calling\n * `caches.delete()` directly, since this will ensure that the IndexedDB\n * metadata is also cleanly removed and open IndexedDB instances are deleted.\n *\n * Note that if you're *not* using cache expiration for a given cache, calling\n * `caches.delete()` and passing in the cache's name should be sufficient.\n * There is no Workbox-specific method needed for cleanup in that case.\n */\n async deleteCacheAndMetadata() {\n // Do this one at a time instead of all at once via `Promise.all()` to\n // reduce the chance of inconsistency if a promise rejects.\n for (const [cacheName, cacheExpiration] of this._cacheExpirations) {\n await self.caches.delete(cacheName);\n await cacheExpiration.delete();\n }\n // Reset this._cacheExpirations to its initial state.\n this._cacheExpirations = new Map();\n }\n}\nexport { ExpirationPlugin };\n"],"names":["instanceOfAny","object","constructors","some","c","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","get","target","prop","receiver","IDBTransaction","objectStoreNames","undefined","objectStore","wrap","set","value","has","wrapFunction","func","IDBDatabase","prototype","transaction","IDBCursor","advance","continue","continuePrimaryKey","includes","args","apply","unwrap","this","storeNames","tx","call","sort","transformCachableValue","done","Promise","resolve","reject","unlisten","removeEventListener","complete","error","DOMException","addEventListener","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","request","promise","success","result","then","catch","promisifyRequest","newValue","readMethods","writeMethods","cachedMethods","Map","getMethod","targetFuncName","replace","useIndex","isWrite","method","async","storeName","store","index","shift","all","oldTraps","callback","self","_","e","CACHE_OBJECT_STORE","normalizeURL","unNormalizedUrl","url","URL","location","href","hash","CacheTimestampsModel","constructor","cacheName","_db","_cacheName","_upgradeDb","db","objStore","createObjectStore","keyPath","createIndex","unique","_upgradeDbAndDeleteOldDbs","name","blocked","indexedDB","deleteDatabase","deleteDB","timestamp","entry","id","_getId","getDb","durability","put","minTimestamp","maxCount","cursor","openCursor","entriesToDelete","entriesNotDeletedCount","push","urlsDeleted","delete","version","upgrade","blocking","terminated","open","openPromise","event","oldVersion","newVersion","openDB","bind","CacheExpiration","config","_isRunning","_rerunRequested","_maxEntries","maxEntries","_maxAgeSeconds","maxAgeSeconds","_matchOptions","matchOptions","_timestampModel","Date","now","urlsExpired","expireEntries","cache","caches","dontWaitFor","setTimestamp","getTimestamp","expireOlderThan","Infinity","cachedResponseWillBeUsed","cachedResponse","isFresh","_isResponseDateFresh","cacheExpiration","_getCacheExpiration","updateTimestampDone","updateTimestamp","waitUntil","cacheDidUpdate","_config","_cacheExpirations","purgeOnQuotaError","registerQuotaErrorCallback","deleteCacheAndMetadata","cacheNames","getRuntimeName","WorkboxError","dateHeaderTimestamp","_getDateHeaderTimestamp","headers","dateHeader","headerTime","getTime","isNaN"],"mappings":"uSAAA,MAAMA,EAAgB,CAACC,EAAQC,IAAiBA,EAA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.0.0/workbox-navigation-preload.dev.js b/src/Resources/workbox-v7.0.0/workbox-navigation-preload.dev.js new file mode 100644 index 0000000..4967cf6 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-navigation-preload.dev.js @@ -0,0 +1,102 @@ +this.workbox = this.workbox || {}; +this.workbox.navigationPreload = (function (exports, logger_js) { + 'use strict'; + + try { + self['workbox:navigation-preload:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @return {boolean} Whether or not the current browser supports enabling + * navigation preload. + * + * @memberof workbox-navigation-preload + */ + + function isSupported() { + return Boolean(self.registration && self.registration.navigationPreload); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * If the browser supports Navigation Preload, then this will disable it. + * + * @memberof workbox-navigation-preload + */ + + function disable() { + if (isSupported()) { + self.addEventListener('activate', event => { + event.waitUntil(self.registration.navigationPreload.disable().then(() => { + { + logger_js.logger.log(`Navigation preload is disabled.`); + } + })); + }); + } else { + { + logger_js.logger.log(`Navigation preload is not supported in this browser.`); + } + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * If the browser supports Navigation Preload, then this will enable it. + * + * @param {string} [headerValue] Optionally, allows developers to + * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header) + * the value of the `Service-Worker-Navigation-Preload` header which will be + * sent to the server when making the navigation request. + * + * @memberof workbox-navigation-preload + */ + + function enable(headerValue) { + if (isSupported()) { + self.addEventListener('activate', event => { + event.waitUntil(self.registration.navigationPreload.enable().then(() => { + // Defaults to Service-Worker-Navigation-Preload: true if not set. + if (headerValue) { + void self.registration.navigationPreload.setHeaderValue(headerValue); + } + + { + logger_js.logger.log(`Navigation preload is enabled.`); + } + })); + }); + } else { + { + logger_js.logger.log(`Navigation preload is not supported in this browser.`); + } + } + } + + exports.disable = disable; + exports.enable = enable; + exports.isSupported = isSupported; + + return exports; + +}({}, workbox.core._private)); +//# sourceMappingURL=workbox-navigation-preload.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-navigation-preload.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-navigation-preload.dev.js.map new file mode 100644 index 0000000..00b51dc --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-navigation-preload.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-navigation-preload.dev.js","sources":["../_version.js","../isSupported.js","../disable.js","../enable.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:navigation-preload:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * @return {boolean} Whether or not the current browser supports enabling\n * navigation preload.\n *\n * @memberof workbox-navigation-preload\n */\nfunction isSupported() {\n return Boolean(self.registration && self.registration.navigationPreload);\n}\nexport { isSupported };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * If the browser supports Navigation Preload, then this will disable it.\n *\n * @memberof workbox-navigation-preload\n */\nfunction disable() {\n if (isSupported()) {\n self.addEventListener('activate', (event) => {\n event.waitUntil(self.registration.navigationPreload.disable().then(() => {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is disabled.`);\n }\n }));\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is not supported in this browser.`);\n }\n }\n}\nexport { disable };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * If the browser supports Navigation Preload, then this will enable it.\n *\n * @param {string} [headerValue] Optionally, allows developers to\n * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header)\n * the value of the `Service-Worker-Navigation-Preload` header which will be\n * sent to the server when making the navigation request.\n *\n * @memberof workbox-navigation-preload\n */\nfunction enable(headerValue) {\n if (isSupported()) {\n self.addEventListener('activate', (event) => {\n event.waitUntil(self.registration.navigationPreload.enable().then(() => {\n // Defaults to Service-Worker-Navigation-Preload: true if not set.\n if (headerValue) {\n void self.registration.navigationPreload.setHeaderValue(headerValue);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is enabled.`);\n }\n }));\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is not supported in this browser.`);\n }\n }\n}\nexport { enable };\n"],"names":["self","_","e","isSupported","Boolean","registration","navigationPreload","disable","addEventListener","event","waitUntil","then","logger","log","enable","headerValue","setHeaderValue"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,kCAAD,CAAJ,IAA4CC,CAAC,EAA7C;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASC,WAAT,GAAuB;IACnB,SAAOC,OAAO,CAACJ,IAAI,CAACK,YAAL,IAAqBL,IAAI,CAACK,YAAL,CAAkBC,iBAAxC,CAAd;IACH;;IChBD;IACA;AACA;IACA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;;IACA,SAASC,OAAT,GAAmB;IACf,MAAIJ,WAAW,EAAf,EAAmB;IACfH,IAAAA,IAAI,CAACQ,gBAAL,CAAsB,UAAtB,EAAmCC,KAAD,IAAW;IACzCA,MAAAA,KAAK,CAACC,SAAN,CAAgBV,IAAI,CAACK,YAAL,CAAkBC,iBAAlB,CAAoCC,OAApC,GAA8CI,IAA9C,CAAmD,MAAM;IACrE,QAA2C;IACvCC,UAAAA,gBAAM,CAACC,GAAP,CAAY,iCAAZ;IACH;IACJ,OAJe,CAAhB;IAKH,KAND;IAOH,GARD,MASK;IACD,IAA2C;IACvCD,MAAAA,gBAAM,CAACC,GAAP,CAAY,sDAAZ;IACH;IACJ;IACJ;;IC9BD;IACA;AACA;IACA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASC,MAAT,CAAgBC,WAAhB,EAA6B;IACzB,MAAIZ,WAAW,EAAf,EAAmB;IACfH,IAAAA,IAAI,CAACQ,gBAAL,CAAsB,UAAtB,EAAmCC,KAAD,IAAW;IACzCA,MAAAA,KAAK,CAACC,SAAN,CAAgBV,IAAI,CAACK,YAAL,CAAkBC,iBAAlB,CAAoCQ,MAApC,GAA6CH,IAA7C,CAAkD,MAAM;IACpE;IACA,YAAII,WAAJ,EAAiB;IACb,eAAKf,IAAI,CAACK,YAAL,CAAkBC,iBAAlB,CAAoCU,cAApC,CAAmDD,WAAnD,CAAL;IACH;;IACD,QAA2C;IACvCH,UAAAA,gBAAM,CAACC,GAAP,CAAY,gCAAZ;IACH;IACJ,OARe,CAAhB;IASH,KAVD;IAWH,GAZD,MAaK;IACD,IAA2C;IACvCD,MAAAA,gBAAM,CAACC,GAAP,CAAY,sDAAZ;IACH;IACJ;IACJ;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-navigation-preload.prod.js b/src/Resources/workbox-v7.0.0/workbox-navigation-preload.prod.js new file mode 100644 index 0000000..7911ce7 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-navigation-preload.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.navigationPreload=function(t){"use strict";try{self["workbox:navigation-preload:7.0.0"]&&_()}catch(t){}function e(){return Boolean(self.registration&&self.registration.navigationPreload)}return t.disable=function(){e()&&self.addEventListener("activate",(t=>{t.waitUntil(self.registration.navigationPreload.disable().then((()=>{})))}))},t.enable=function(t){e()&&self.addEventListener("activate",(e=>{e.waitUntil(self.registration.navigationPreload.enable().then((()=>{t&&self.registration.navigationPreload.setHeaderValue(t)})))}))},t.isSupported=e,t}({}); +//# sourceMappingURL=workbox-navigation-preload.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-navigation-preload.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-navigation-preload.prod.js.map new file mode 100644 index 0000000..e46038e --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-navigation-preload.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-navigation-preload.prod.js","sources":["../_version.js","../isSupported.js","../disable.js","../enable.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:navigation-preload:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * @return {boolean} Whether or not the current browser supports enabling\n * navigation preload.\n *\n * @memberof workbox-navigation-preload\n */\nfunction isSupported() {\n return Boolean(self.registration && self.registration.navigationPreload);\n}\nexport { isSupported };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * If the browser supports Navigation Preload, then this will disable it.\n *\n * @memberof workbox-navigation-preload\n */\nfunction disable() {\n if (isSupported()) {\n self.addEventListener('activate', (event) => {\n event.waitUntil(self.registration.navigationPreload.disable().then(() => {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is disabled.`);\n }\n }));\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is not supported in this browser.`);\n }\n }\n}\nexport { disable };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * If the browser supports Navigation Preload, then this will enable it.\n *\n * @param {string} [headerValue] Optionally, allows developers to\n * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header)\n * the value of the `Service-Worker-Navigation-Preload` header which will be\n * sent to the server when making the navigation request.\n *\n * @memberof workbox-navigation-preload\n */\nfunction enable(headerValue) {\n if (isSupported()) {\n self.addEventListener('activate', (event) => {\n event.waitUntil(self.registration.navigationPreload.enable().then(() => {\n // Defaults to Service-Worker-Navigation-Preload: true if not set.\n if (headerValue) {\n void self.registration.navigationPreload.setHeaderValue(headerValue);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is enabled.`);\n }\n }));\n });\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Navigation preload is not supported in this browser.`);\n }\n }\n}\nexport { enable };\n"],"names":["self","_","e","isSupported","Boolean","registration","navigationPreload","addEventListener","event","waitUntil","disable","then","headerValue","enable","setHeaderValue"],"mappings":"sFAEA,IACIA,KAAK,qCAAuCC,GAC/C,CACD,MAAOC,ICSP,SAASC,WACEC,QAAQJ,KAAKK,cAAgBL,KAAKK,aAAaC,kBACzD,kBCDD,WACQH,KACAH,KAAKO,iBAAiB,YAAaC,IAC/BA,EAAMC,UAAUT,KAAKK,aAAaC,kBAAkBI,UAAUC,MAAK,YAY9E,WCVD,SAAgBC,GACRT,KACAH,KAAKO,iBAAiB,YAAaC,IAC/BA,EAAMC,UAAUT,KAAKK,aAAaC,kBAAkBO,SAASF,MAAK,KAE1DC,GACKZ,KAAKK,aAAaC,kBAAkBQ,eAAeF,SAa3E"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-offline-ga.dev.js b/src/Resources/workbox-v7.0.0/workbox-offline-ga.dev.js new file mode 100644 index 0000000..dd7a505 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-offline-ga.dev.js @@ -0,0 +1,235 @@ +this.workbox = this.workbox || {}; +this.workbox.googleAnalytics = (function (exports, BackgroundSyncPlugin_js, cacheNames_js, getFriendlyURL_js, logger_js, Route_js, Router_js, NetworkFirst_js, NetworkOnly_js) { + 'use strict'; + + try { + self['workbox:google-analytics:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const QUEUE_NAME = 'workbox-google-analytics'; + const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes + + const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com'; + const GTM_HOST = 'www.googletagmanager.com'; + const ANALYTICS_JS_PATH = '/analytics.js'; + const GTAG_JS_PATH = '/gtag/js'; + const GTM_JS_PATH = '/gtm.js'; + // endpoints. Most of the time the default path (/collect) is used, but + // occasionally an experimental endpoint is used when testing new features, + // (e.g. /r/collect or /j/collect) + + const COLLECT_PATHS_REGEX = /^\/(\w+\/)?collect/; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Creates the requestWillDequeue callback to be used with the background + * sync plugin. The callback takes the failed request and adds the + * `qt` param based on the current time, as well as applies any other + * user-defined hit modifications. + * + * @param {Object} config See {@link workbox-google-analytics.initialize}. + * @return {Function} The requestWillDequeue callback function. + * + * @private + */ + + const createOnSyncCallback = config => { + return async ({ + queue + }) => { + let entry; + + while (entry = await queue.shiftRequest()) { + const { + request, + timestamp + } = entry; + const url = new URL(request.url); + + try { + // Measurement protocol requests can set their payload parameters in + // either the URL query string (for GET requests) or the POST body. + const params = request.method === 'POST' ? new URLSearchParams(await request.clone().text()) : url.searchParams; // Calculate the qt param, accounting for the fact that an existing + // qt param may be present and should be updated rather than replaced. + + const originalHitTime = timestamp - (Number(params.get('qt')) || 0); + const queueTime = Date.now() - originalHitTime; // Set the qt param prior to applying hitFilter or parameterOverrides. + + params.set('qt', String(queueTime)); // Apply `parameterOverrides`, if set. + + if (config.parameterOverrides) { + for (const param of Object.keys(config.parameterOverrides)) { + const value = config.parameterOverrides[param]; + params.set(param, value); + } + } // Apply `hitFilter`, if set. + + + if (typeof config.hitFilter === 'function') { + config.hitFilter.call(null, params); + } // Retry the fetch. Ignore URL search params from the URL as they're + // now in the post body. + + + await fetch(new Request(url.origin + url.pathname, { + body: params.toString(), + method: 'POST', + mode: 'cors', + credentials: 'omit', + headers: { + 'Content-Type': 'text/plain' + } + })); + + if ("dev" !== 'production') { + logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(url.href)}' ` + `has been replayed`); + } + } catch (err) { + await queue.unshiftRequest(entry); + + { + logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(url.href)}' ` + `failed to replay, putting it back in the queue.`); + } + + throw err; + } + } + + { + logger_js.logger.log(`All Google Analytics request successfully replayed; ` + `the queue is now empty!`); + } + }; + }; + /** + * Creates GET and POST routes to catch failed Measurement Protocol hits. + * + * @param {BackgroundSyncPlugin} bgSyncPlugin + * @return {Array} The created routes. + * + * @private + */ + + + const createCollectRoutes = bgSyncPlugin => { + const match = ({ + url + }) => url.hostname === GOOGLE_ANALYTICS_HOST && COLLECT_PATHS_REGEX.test(url.pathname); + + const handler = new NetworkOnly_js.NetworkOnly({ + plugins: [bgSyncPlugin] + }); + return [new Route_js.Route(match, handler, 'GET'), new Route_js.Route(match, handler, 'POST')]; + }; + /** + * Creates a route with a network first strategy for the analytics.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ + + + const createAnalyticsJsRoute = cacheName => { + const match = ({ + url + }) => url.hostname === GOOGLE_ANALYTICS_HOST && url.pathname === ANALYTICS_JS_PATH; + + const handler = new NetworkFirst_js.NetworkFirst({ + cacheName + }); + return new Route_js.Route(match, handler, 'GET'); + }; + /** + * Creates a route with a network first strategy for the gtag.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ + + + const createGtagJsRoute = cacheName => { + const match = ({ + url + }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH; + + const handler = new NetworkFirst_js.NetworkFirst({ + cacheName + }); + return new Route_js.Route(match, handler, 'GET'); + }; + /** + * Creates a route with a network first strategy for the gtm.js script. + * + * @param {string} cacheName + * @return {Route} The created route. + * + * @private + */ + + + const createGtmJsRoute = cacheName => { + const match = ({ + url + }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH; + + const handler = new NetworkFirst_js.NetworkFirst({ + cacheName + }); + return new Route_js.Route(match, handler, 'GET'); + }; + /** + * @param {Object=} [options] + * @param {Object} [options.cacheName] The cache name to store and retrieve + * analytics.js. Defaults to the cache names provided by `workbox-core`. + * @param {Object} [options.parameterOverrides] + * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters), + * expressed as key/value pairs, to be added to replayed Google Analytics + * requests. This can be used to, e.g., set a custom dimension indicating + * that the request was replayed. + * @param {Function} [options.hitFilter] A function that allows you to modify + * the hit parameters prior to replaying + * the hit. The function is invoked with the original hit's URLSearchParams + * object as its only argument. + * + * @memberof workbox-google-analytics + */ + + + const initialize = (options = {}) => { + const cacheName = cacheNames_js.cacheNames.getGoogleAnalyticsName(options.cacheName); + const bgSyncPlugin = new BackgroundSyncPlugin_js.BackgroundSyncPlugin(QUEUE_NAME, { + maxRetentionTime: MAX_RETENTION_TIME, + onSync: createOnSyncCallback(options) + }); + const routes = [createGtmJsRoute(cacheName), createAnalyticsJsRoute(cacheName), createGtagJsRoute(cacheName), ...createCollectRoutes(bgSyncPlugin)]; + const router = new Router_js.Router(); + + for (const route of routes) { + router.registerRoute(route); + } + + router.addFetchListener(); + }; + + exports.initialize = initialize; + + return exports; + +}({}, workbox.backgroundSync, workbox.core._private, workbox.core._private, workbox.core._private, workbox.routing, workbox.routing, workbox.strategies, workbox.strategies)); +//# sourceMappingURL=workbox-offline-ga.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-offline-ga.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-offline-ga.dev.js.map new file mode 100644 index 0000000..6d66b17 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-offline-ga.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-offline-ga.dev.js","sources":["../_version.js","../utils/constants.js","../initialize.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:google-analytics:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nexport const QUEUE_NAME = 'workbox-google-analytics';\nexport const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes\nexport const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com';\nexport const GTM_HOST = 'www.googletagmanager.com';\nexport const ANALYTICS_JS_PATH = '/analytics.js';\nexport const GTAG_JS_PATH = '/gtag/js';\nexport const GTM_JS_PATH = '/gtm.js';\nexport const COLLECT_DEFAULT_PATH = '/collect';\n// This RegExp matches all known Measurement Protocol single-hit collect\n// endpoints. Most of the time the default path (/collect) is used, but\n// occasionally an experimental endpoint is used when testing new features,\n// (e.g. /r/collect or /j/collect)\nexport const COLLECT_PATHS_REGEX = /^\\/(\\w+\\/)?collect/;\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { BackgroundSyncPlugin } from 'workbox-background-sync/BackgroundSyncPlugin.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { Router } from 'workbox-routing/Router.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { NetworkOnly } from 'workbox-strategies/NetworkOnly.js';\nimport { QUEUE_NAME, MAX_RETENTION_TIME, GOOGLE_ANALYTICS_HOST, GTM_HOST, ANALYTICS_JS_PATH, GTAG_JS_PATH, GTM_JS_PATH, COLLECT_PATHS_REGEX, } from './utils/constants.js';\nimport './_version.js';\n/**\n * Creates the requestWillDequeue callback to be used with the background\n * sync plugin. The callback takes the failed request and adds the\n * `qt` param based on the current time, as well as applies any other\n * user-defined hit modifications.\n *\n * @param {Object} config See {@link workbox-google-analytics.initialize}.\n * @return {Function} The requestWillDequeue callback function.\n *\n * @private\n */\nconst createOnSyncCallback = (config) => {\n return async ({ queue }) => {\n let entry;\n while ((entry = await queue.shiftRequest())) {\n const { request, timestamp } = entry;\n const url = new URL(request.url);\n try {\n // Measurement protocol requests can set their payload parameters in\n // either the URL query string (for GET requests) or the POST body.\n const params = request.method === 'POST'\n ? new URLSearchParams(await request.clone().text())\n : url.searchParams;\n // Calculate the qt param, accounting for the fact that an existing\n // qt param may be present and should be updated rather than replaced.\n const originalHitTime = timestamp - (Number(params.get('qt')) || 0);\n const queueTime = Date.now() - originalHitTime;\n // Set the qt param prior to applying hitFilter or parameterOverrides.\n params.set('qt', String(queueTime));\n // Apply `parameterOverrides`, if set.\n if (config.parameterOverrides) {\n for (const param of Object.keys(config.parameterOverrides)) {\n const value = config.parameterOverrides[param];\n params.set(param, value);\n }\n }\n // Apply `hitFilter`, if set.\n if (typeof config.hitFilter === 'function') {\n config.hitFilter.call(null, params);\n }\n // Retry the fetch. Ignore URL search params from the URL as they're\n // now in the post body.\n await fetch(new Request(url.origin + url.pathname, {\n body: params.toString(),\n method: 'POST',\n mode: 'cors',\n credentials: 'omit',\n headers: { 'Content-Type': 'text/plain' },\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`);\n }\n }\n catch (err) {\n await queue.unshiftRequest(entry);\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}' ` +\n `failed to replay, putting it back in the queue.`);\n }\n throw err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`All Google Analytics request successfully replayed; ` +\n `the queue is now empty!`);\n }\n };\n};\n/**\n * Creates GET and POST routes to catch failed Measurement Protocol hits.\n *\n * @param {BackgroundSyncPlugin} bgSyncPlugin\n * @return {Array} The created routes.\n *\n * @private\n */\nconst createCollectRoutes = (bgSyncPlugin) => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n COLLECT_PATHS_REGEX.test(url.pathname);\n const handler = new NetworkOnly({\n plugins: [bgSyncPlugin],\n });\n return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')];\n};\n/**\n * Creates a route with a network first strategy for the analytics.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createAnalyticsJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n url.pathname === ANALYTICS_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * Creates a route with a network first strategy for the gtag.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtagJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * Creates a route with a network first strategy for the gtm.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtmJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * @param {Object=} [options]\n * @param {Object} [options.cacheName] The cache name to store and retrieve\n * analytics.js. Defaults to the cache names provided by `workbox-core`.\n * @param {Object} [options.parameterOverrides]\n * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),\n * expressed as key/value pairs, to be added to replayed Google Analytics\n * requests. This can be used to, e.g., set a custom dimension indicating\n * that the request was replayed.\n * @param {Function} [options.hitFilter] A function that allows you to modify\n * the hit parameters prior to replaying\n * the hit. The function is invoked with the original hit's URLSearchParams\n * object as its only argument.\n *\n * @memberof workbox-google-analytics\n */\nconst initialize = (options = {}) => {\n const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);\n const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {\n maxRetentionTime: MAX_RETENTION_TIME,\n onSync: createOnSyncCallback(options),\n });\n const routes = [\n createGtmJsRoute(cacheName),\n createAnalyticsJsRoute(cacheName),\n createGtagJsRoute(cacheName),\n ...createCollectRoutes(bgSyncPlugin),\n ];\n const router = new Router();\n for (const route of routes) {\n router.registerRoute(route);\n }\n router.addFetchListener();\n};\nexport { initialize };\n"],"names":["self","_","e","QUEUE_NAME","MAX_RETENTION_TIME","GOOGLE_ANALYTICS_HOST","GTM_HOST","ANALYTICS_JS_PATH","GTAG_JS_PATH","GTM_JS_PATH","COLLECT_PATHS_REGEX","createOnSyncCallback","config","queue","entry","shiftRequest","request","timestamp","url","URL","params","method","URLSearchParams","clone","text","searchParams","originalHitTime","Number","get","queueTime","Date","now","set","String","parameterOverrides","param","Object","keys","value","hitFilter","call","fetch","Request","origin","pathname","body","toString","mode","credentials","headers","process","logger","log","getFriendlyURL","href","err","unshiftRequest","createCollectRoutes","bgSyncPlugin","match","hostname","test","handler","NetworkOnly","plugins","Route","createAnalyticsJsRoute","cacheName","NetworkFirst","createGtagJsRoute","createGtmJsRoute","initialize","options","cacheNames","getGoogleAnalyticsName","BackgroundSyncPlugin","maxRetentionTime","onSync","routes","router","Router","route","registerRoute","addFetchListener"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,gCAAD,CAAJ,IAA0CC,CAAC,EAA3C;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAEO,MAAMC,UAAU,GAAG,0BAAnB;IACA,MAAMC,kBAAkB,GAAG,KAAK,EAAhC;;IACA,MAAMC,qBAAqB,GAAG,0BAA9B;IACA,MAAMC,QAAQ,GAAG,0BAAjB;IACA,MAAMC,iBAAiB,GAAG,eAA1B;IACA,MAAMC,YAAY,GAAG,UAArB;IACA,MAAMC,WAAW,GAAG,SAApB;IAGP;IACA;IACA;;IACO,MAAMC,mBAAmB,GAAG,oBAA5B;;ICpBP;IACA;AACA;IACA;IACA;IACA;IACA;IAWA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,MAAMC,oBAAoB,GAAIC,MAAD,IAAY;IACrC,SAAO,OAAO;IAAEC,IAAAA;IAAF,GAAP,KAAqB;IACxB,QAAIC,KAAJ;;IACA,WAAQA,KAAK,GAAG,MAAMD,KAAK,CAACE,YAAN,EAAtB,EAA6C;IACzC,YAAM;IAAEC,QAAAA,OAAF;IAAWC,QAAAA;IAAX,UAAyBH,KAA/B;IACA,YAAMI,GAAG,GAAG,IAAIC,GAAJ,CAAQH,OAAO,CAACE,GAAhB,CAAZ;;IACA,UAAI;IACA;IACA;IACA,cAAME,MAAM,GAAGJ,OAAO,CAACK,MAAR,KAAmB,MAAnB,GACT,IAAIC,eAAJ,CAAoB,MAAMN,OAAO,CAACO,KAAR,GAAgBC,IAAhB,EAA1B,CADS,GAETN,GAAG,CAACO,YAFV,CAHA;IAOA;;IACA,cAAMC,eAAe,GAAGT,SAAS,IAAIU,MAAM,CAACP,MAAM,CAACQ,GAAP,CAAW,IAAX,CAAD,CAAN,IAA4B,CAAhC,CAAjC;IACA,cAAMC,SAAS,GAAGC,IAAI,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X,GAAGV,mBAAmB,CAACC,YAAD,CAJX,CAAf;IAMA,QAAMqB,MAAM,GAAG,IAAIC,gBAAJ,EAAf;;IACA,OAAK,MAAMC,KAAX,IAAoBH,MAApB,EAA4B;IACxBC,IAAAA,MAAM,CAACG,aAAP,CAAqBD,KAArB;IACH;;IACDF,EAAAA,MAAM,CAACI,gBAAP;IACH;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-offline-ga.prod.js b/src/Resources/workbox-v7.0.0/workbox-offline-ga.prod.js new file mode 100644 index 0000000..bc1cb1e --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-offline-ga.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.googleAnalytics=function(t,e,o,n,r,c,a,w,s){"use strict";try{self["workbox:google-analytics:7.0.0"]&&_()}catch(t){}const i="www.google-analytics.com",l="www.googletagmanager.com",u=/^\/(\w+\/)?collect/,m=t=>{const e=({url:t})=>t.hostname===i&&u.test(t.pathname),o=new s.NetworkOnly({plugins:[t]});return[new c.Route(e,o,"GET"),new c.Route(e,o,"POST")]},g=t=>{const e=new w.NetworkFirst({cacheName:t});return new c.Route((({url:t})=>t.hostname===i&&"/analytics.js"===t.pathname),e,"GET")},h=t=>{const e=new w.NetworkFirst({cacheName:t});return new c.Route((({url:t})=>t.hostname===l&&"/gtag/js"===t.pathname),e,"GET")},b=t=>{const e=new w.NetworkFirst({cacheName:t});return new c.Route((({url:t})=>t.hostname===l&&"/gtm.js"===t.pathname),e,"GET")};return t.initialize=(t={})=>{const n=o.cacheNames.getGoogleAnalyticsName(t.cacheName),r=new e.BackgroundSyncPlugin("workbox-google-analytics",{maxRetentionTime:2880,onSync:(c=t,async({queue:t})=>{let e;for(;e=await t.shiftRequest();){const{request:o,timestamp:n}=e,r=new URL(o.url);try{const t="POST"===o.method?new URLSearchParams(await o.clone().text()):r.searchParams,e=n-(Number(t.get("qt"))||0),a=Date.now()-e;if(t.set("qt",String(a)),c.parameterOverrides)for(const e of Object.keys(c.parameterOverrides)){const o=c.parameterOverrides[e];t.set(e,o)}"function"==typeof c.hitFilter&&c.hitFilter.call(null,t),await fetch(new Request(r.origin+r.pathname,{body:t.toString(),method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"text/plain"}}))}catch(o){throw await t.unshiftRequest(e),o}}})});var c;const w=[b(n),g(n),h(n),...m(r)],s=new a.Router;for(const t of w)s.registerRoute(t);s.addFetchListener()},t}({},workbox.backgroundSync,workbox.core._private,workbox.core._private,workbox.core._private,workbox.routing,workbox.routing,workbox.strategies,workbox.strategies); +//# sourceMappingURL=workbox-offline-ga.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-offline-ga.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-offline-ga.prod.js.map new file mode 100644 index 0000000..90b7f7d --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-offline-ga.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-offline-ga.prod.js","sources":["../_version.js","../utils/constants.js","../initialize.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:google-analytics:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nexport const QUEUE_NAME = 'workbox-google-analytics';\nexport const MAX_RETENTION_TIME = 60 * 48; // Two days in minutes\nexport const GOOGLE_ANALYTICS_HOST = 'www.google-analytics.com';\nexport const GTM_HOST = 'www.googletagmanager.com';\nexport const ANALYTICS_JS_PATH = '/analytics.js';\nexport const GTAG_JS_PATH = '/gtag/js';\nexport const GTM_JS_PATH = '/gtm.js';\nexport const COLLECT_DEFAULT_PATH = '/collect';\n// This RegExp matches all known Measurement Protocol single-hit collect\n// endpoints. Most of the time the default path (/collect) is used, but\n// occasionally an experimental endpoint is used when testing new features,\n// (e.g. /r/collect or /j/collect)\nexport const COLLECT_PATHS_REGEX = /^\\/(\\w+\\/)?collect/;\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { BackgroundSyncPlugin } from 'workbox-background-sync/BackgroundSyncPlugin.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { Router } from 'workbox-routing/Router.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { NetworkOnly } from 'workbox-strategies/NetworkOnly.js';\nimport { QUEUE_NAME, MAX_RETENTION_TIME, GOOGLE_ANALYTICS_HOST, GTM_HOST, ANALYTICS_JS_PATH, GTAG_JS_PATH, GTM_JS_PATH, COLLECT_PATHS_REGEX, } from './utils/constants.js';\nimport './_version.js';\n/**\n * Creates the requestWillDequeue callback to be used with the background\n * sync plugin. The callback takes the failed request and adds the\n * `qt` param based on the current time, as well as applies any other\n * user-defined hit modifications.\n *\n * @param {Object} config See {@link workbox-google-analytics.initialize}.\n * @return {Function} The requestWillDequeue callback function.\n *\n * @private\n */\nconst createOnSyncCallback = (config) => {\n return async ({ queue }) => {\n let entry;\n while ((entry = await queue.shiftRequest())) {\n const { request, timestamp } = entry;\n const url = new URL(request.url);\n try {\n // Measurement protocol requests can set their payload parameters in\n // either the URL query string (for GET requests) or the POST body.\n const params = request.method === 'POST'\n ? new URLSearchParams(await request.clone().text())\n : url.searchParams;\n // Calculate the qt param, accounting for the fact that an existing\n // qt param may be present and should be updated rather than replaced.\n const originalHitTime = timestamp - (Number(params.get('qt')) || 0);\n const queueTime = Date.now() - originalHitTime;\n // Set the qt param prior to applying hitFilter or parameterOverrides.\n params.set('qt', String(queueTime));\n // Apply `parameterOverrides`, if set.\n if (config.parameterOverrides) {\n for (const param of Object.keys(config.parameterOverrides)) {\n const value = config.parameterOverrides[param];\n params.set(param, value);\n }\n }\n // Apply `hitFilter`, if set.\n if (typeof config.hitFilter === 'function') {\n config.hitFilter.call(null, params);\n }\n // Retry the fetch. Ignore URL search params from the URL as they're\n // now in the post body.\n await fetch(new Request(url.origin + url.pathname, {\n body: params.toString(),\n method: 'POST',\n mode: 'cors',\n credentials: 'omit',\n headers: { 'Content-Type': 'text/plain' },\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}' ` + `has been replayed`);\n }\n }\n catch (err) {\n await queue.unshiftRequest(entry);\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(url.href)}' ` +\n `failed to replay, putting it back in the queue.`);\n }\n throw err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`All Google Analytics request successfully replayed; ` +\n `the queue is now empty!`);\n }\n };\n};\n/**\n * Creates GET and POST routes to catch failed Measurement Protocol hits.\n *\n * @param {BackgroundSyncPlugin} bgSyncPlugin\n * @return {Array} The created routes.\n *\n * @private\n */\nconst createCollectRoutes = (bgSyncPlugin) => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n COLLECT_PATHS_REGEX.test(url.pathname);\n const handler = new NetworkOnly({\n plugins: [bgSyncPlugin],\n });\n return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')];\n};\n/**\n * Creates a route with a network first strategy for the analytics.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createAnalyticsJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&\n url.pathname === ANALYTICS_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * Creates a route with a network first strategy for the gtag.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtagJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * Creates a route with a network first strategy for the gtm.js script.\n *\n * @param {string} cacheName\n * @return {Route} The created route.\n *\n * @private\n */\nconst createGtmJsRoute = (cacheName) => {\n const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;\n const handler = new NetworkFirst({ cacheName });\n return new Route(match, handler, 'GET');\n};\n/**\n * @param {Object=} [options]\n * @param {Object} [options.cacheName] The cache name to store and retrieve\n * analytics.js. Defaults to the cache names provided by `workbox-core`.\n * @param {Object} [options.parameterOverrides]\n * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),\n * expressed as key/value pairs, to be added to replayed Google Analytics\n * requests. This can be used to, e.g., set a custom dimension indicating\n * that the request was replayed.\n * @param {Function} [options.hitFilter] A function that allows you to modify\n * the hit parameters prior to replaying\n * the hit. The function is invoked with the original hit's URLSearchParams\n * object as its only argument.\n *\n * @memberof workbox-google-analytics\n */\nconst initialize = (options = {}) => {\n const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);\n const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {\n maxRetentionTime: MAX_RETENTION_TIME,\n onSync: createOnSyncCallback(options),\n });\n const routes = [\n createGtmJsRoute(cacheName),\n createAnalyticsJsRoute(cacheName),\n createGtagJsRoute(cacheName),\n ...createCollectRoutes(bgSyncPlugin),\n ];\n const router = new Router();\n for (const route of routes) {\n router.registerRoute(route);\n }\n router.addFetchListener();\n};\nexport { initialize };\n"],"names":["self","_","e","GOOGLE_ANALYTICS_HOST","GTM_HOST","COLLECT_PATHS_REGEX","createCollectRoutes","bgSyncPlugin","match","url","hostname","test","pathname","handler","NetworkOnly","plugins","Route","createAnalyticsJsRoute","cacheName","NetworkFirst","createGtagJsRoute","createGtmJsRoute","options","cacheNames","getGoogleAnalyticsName","BackgroundSyncPlugin","maxRetentionTime","onSync","config","async","queue","entry","shiftRequest","request","timestamp","URL","params","method","URLSearchParams","clone","text","searchParams","originalHitTime","Number","get","queueTime","Date","now","set","String","parameterOverrides","param","Object","keys","value","hitFilter","call","fetch","Request","origin","body","toString","mode","credentials","headers","err","unshiftRequest","routes","router","Router","route","registerRoute","addFetchListener"],"mappings":"oGAEA,IACIA,KAAK,mCAAqCC,GAC7C,CACD,MAAOC,ICGA,MAEMC,EAAwB,2BACxBC,EAAW,2BASXC,EAAsB,qBCyE7BC,EAAuBC,UACnBC,EAAQ,EAAGC,SAAUA,EAAIC,WAAaP,GACxCE,EAAoBM,KAAKF,EAAIG,UAC3BC,EAAU,IAAIC,cAAY,CAC5BC,QAAS,CAACR,WAEP,CAAC,IAAIS,QAAMR,EAAOK,EAAS,OAAQ,IAAIG,QAAMR,EAAOK,EAAS,QAApE,EAUEI,EAA0BC,UAGtBL,EAAU,IAAIM,eAAa,CAAED,qBAC5B,IAAIF,SAHG,EAAGP,SAAUA,EAAIC,WAAaP,GDlGf,kBCmGzBM,EAAIG,UAEgBC,EAAS,MAAjC,EAUEO,EAAqBF,UAEjBL,EAAU,IAAIM,eAAa,CAAED,qBAC5B,IAAIF,SAFG,EAAGP,SAAUA,EAAIC,WAAaN,GD/GpB,aC+GgCK,EAAIG,UAEpCC,EAAS,MAAjC,EAUEQ,EAAoBH,UAEhBL,EAAU,IAAIM,eAAa,CAAED,qBAC5B,IAAIF,SAFG,EAAGP,SAAUA,EAAIC,WAAaN,GD3HrB,YC2HiCK,EAAIG,UAEpCC,EAAS,MAAjC,sBAkBe,CAACS,EAAU,YACpBJ,EAAYK,aAAWC,uBAAuBF,EAAQJ,WACtDX,EAAe,IAAIkB,uBDvJH,2BCuJoC,CACtDC,iBDvJ0B,KCwJ1BC,QArIsBC,EAqION,EApI1BO,OAASC,gBACRC,OACIA,QAAcD,EAAME,gBAAiB,OACnCC,QAAEA,EAAFC,UAAWA,GAAcH,EACzBtB,EAAM,IAAI0B,IAAIF,EAAQxB,eAIlB2B,EAA4B,SAAnBH,EAAQI,OACjB,IAAIC,sBAAsBL,EAAQM,QAAQC,QAC1C/B,EAAIgC,aAGJC,EAAkBR,GAAaS,OAAOP,EAAOQ,IAAI,QAAU,GAC3DC,EAAYC,KAAKC,MAAQL,KAE/BN,EAAOY,IAAI,KAAMC,OAAOJ,IAEpBjB,EAAOsB,uBACF,MAAMC,KAASC,OAAOC,KAAKzB,EAAOsB,oBAAqB,OAClDI,EAAQ1B,EAAOsB,mBAAmBC,GACxCf,EAAOY,IAAIG,EAAOG,GAIM,mBAArB1B,EAAO2B,WACd3B,EAAO2B,UAAUC,KAAK,KAAMpB,SAI1BqB,MAAM,IAAIC,QAAQjD,EAAIkD,OAASlD,EAAIG,SAAU,CAC/CgD,KAAMxB,EAAOyB,WACbxB,OAAQ,OACRyB,KAAM,OACNC,YAAa,OACbC,QAAS,gBAAkB,iBAMnC,MAAOC,eACGnC,EAAMoC,eAAenC,GAKrBkC,QAhDQrC,YAuIpBuC,EAAS,CACX9C,EAAiBH,GACjBD,EAAuBC,GACvBE,EAAkBF,MACfZ,EAAoBC,IAErB6D,EAAS,IAAIC,aACd,MAAMC,KAASH,EAChBC,EAAOG,cAAcD,GAEzBF,EAAOI"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-precaching.dev.js b/src/Resources/workbox-v7.0.0/workbox-precaching.dev.js new file mode 100644 index 0000000..5baf793 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-precaching.dev.js @@ -0,0 +1,1338 @@ +this.workbox = this.workbox || {}; +this.workbox.precaching = (function (exports, assert_js, cacheNames_js, logger_js, WorkboxError_js, waitUntil_js, copyResponse_js, getFriendlyURL_js, Strategy_js, registerRoute_js, Route_js) { + 'use strict'; + + try { + self['workbox:precaching:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + + const REVISION_SEARCH_PARAM = '__WB_REVISION__'; + /** + * Converts a manifest entry into a versioned URL suitable for precaching. + * + * @param {Object|string} entry + * @return {string} A URL with versioning info. + * + * @private + * @memberof workbox-precaching + */ + + function createCacheKey(entry) { + if (!entry) { + throw new WorkboxError_js.WorkboxError('add-to-cache-list-unexpected-type', { + entry + }); + } // If a precache manifest entry is a string, it's assumed to be a versioned + // URL, like '/app.abcd1234.js'. Return as-is. + + + if (typeof entry === 'string') { + const urlObject = new URL(entry, location.href); + return { + cacheKey: urlObject.href, + url: urlObject.href + }; + } + + const { + revision, + url + } = entry; + + if (!url) { + throw new WorkboxError_js.WorkboxError('add-to-cache-list-unexpected-type', { + entry + }); + } // If there's just a URL and no revision, then it's also assumed to be a + // versioned URL. + + + if (!revision) { + const urlObject = new URL(url, location.href); + return { + cacheKey: urlObject.href, + url: urlObject.href + }; + } // Otherwise, construct a properly versioned URL using the custom Workbox + // search parameter along with the revision info. + + + const cacheKeyURL = new URL(url, location.href); + const originalURL = new URL(url, location.href); + cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision); + return { + cacheKey: cacheKeyURL.href, + url: originalURL.href + }; + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A plugin, designed to be used with PrecacheController, to determine the + * of assets that were updated (or not updated) during the install event. + * + * @private + */ + + class PrecacheInstallReportPlugin { + constructor() { + this.updatedURLs = []; + this.notUpdatedURLs = []; + + this.handlerWillStart = async ({ + request, + state + }) => { + // TODO: `state` should never be undefined... + if (state) { + state.originalRequest = request; + } + }; + + this.cachedResponseWillBeUsed = async ({ + event, + state, + cachedResponse + }) => { + if (event.type === 'install') { + if (state && state.originalRequest && state.originalRequest instanceof Request) { + // TODO: `state` should never be undefined... + const url = state.originalRequest.url; + + if (cachedResponse) { + this.notUpdatedURLs.push(url); + } else { + this.updatedURLs.push(url); + } + } + } + + return cachedResponse; + }; + } + + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A plugin, designed to be used with PrecacheController, to translate URLs into + * the corresponding cache key, based on the current revision info. + * + * @private + */ + + class PrecacheCacheKeyPlugin { + constructor({ + precacheController + }) { + this.cacheKeyWillBeUsed = async ({ + request, + params + }) => { + // Params is type any, can't change right now. + + /* eslint-disable */ + const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) || this._precacheController.getCacheKeyForURL(request.url); + /* eslint-enable */ + + + return cacheKey ? new Request(cacheKey, { + headers: request.headers + }) : request; + }; + + this._precacheController = precacheController; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {string} groupTitle + * @param {Array} deletedURLs + * + * @private + */ + + const logGroup = (groupTitle, deletedURLs) => { + logger_js.logger.groupCollapsed(groupTitle); + + for (const url of deletedURLs) { + logger_js.logger.log(url); + } + + logger_js.logger.groupEnd(); + }; + /** + * @param {Array} deletedURLs + * + * @private + * @memberof workbox-precaching + */ + + + function printCleanupDetails(deletedURLs) { + const deletionCount = deletedURLs.length; + + if (deletionCount > 0) { + logger_js.logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`); + logGroup('Deleted Cache Requests', deletedURLs); + logger_js.logger.groupEnd(); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {string} groupTitle + * @param {Array} urls + * + * @private + */ + + function _nestedGroup(groupTitle, urls) { + if (urls.length === 0) { + return; + } + + logger_js.logger.groupCollapsed(groupTitle); + + for (const url of urls) { + logger_js.logger.log(url); + } + + logger_js.logger.groupEnd(); + } + /** + * @param {Array} urlsToPrecache + * @param {Array} urlsAlreadyPrecached + * + * @private + * @memberof workbox-precaching + */ + + + function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) { + const precachedCount = urlsToPrecache.length; + const alreadyPrecachedCount = urlsAlreadyPrecached.length; + + if (precachedCount || alreadyPrecachedCount) { + let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`; + + if (alreadyPrecachedCount > 0) { + message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`; + } + + logger_js.logger.groupCollapsed(message); + + _nestedGroup(`View newly precached URLs.`, urlsToPrecache); + + _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached); + + logger_js.logger.groupEnd(); + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A {@link workbox-strategies.Strategy} implementation + * specifically designed to work with + * {@link workbox-precaching.PrecacheController} + * to both cache and fetch precached assets. + * + * Note: an instance of this class is created automatically when creating a + * `PrecacheController`; it's generally not necessary to create this yourself. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-precaching + */ + + class PrecacheStrategy extends Strategy_js.Strategy { + /** + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init} + * of all fetch() requests made by this strategy. + * @param {Object} [options.matchOptions] The + * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor(options = {}) { + options.cacheName = cacheNames_js.cacheNames.getPrecacheName(options.cacheName); + super(options); + this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true; // Redirected responses cannot be used to satisfy a navigation request, so + // any redirected response must be "copied" rather than cloned, so the new + // response doesn't contain the `redirected` flag. See: + // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1 + + this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin); + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + + + async _handle(request, handler) { + const response = await handler.cacheMatch(request); + + if (response) { + return response; + } // If this is an `install` event for an entry that isn't already cached, + // then populate the cache. + + + if (handler.event && handler.event.type === 'install') { + return await this._handleInstall(request, handler); + } // Getting here means something went wrong. An entry that should have been + // precached wasn't found in the cache. + + + return await this._handleFetch(request, handler); + } + + async _handleFetch(request, handler) { + let response; + const params = handler.params || {}; // Fall back to the network if we're configured to do so. + + if (this._fallbackToNetwork) { + { + logger_js.logger.warn(`The precached response for ` + `${getFriendlyURL_js.getFriendlyURL(request.url)} in ${this.cacheName} was not ` + `found. Falling back to the network.`); + } + + const integrityInManifest = params.integrity; + const integrityInRequest = request.integrity; + const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest; // Do not add integrity if the original request is no-cors + // See https://github.com/GoogleChrome/workbox/issues/3096 + + response = await handler.fetch(new Request(request, { + integrity: request.mode !== 'no-cors' ? integrityInRequest || integrityInManifest : undefined + })); // It's only "safe" to repair the cache if we're using SRI to guarantee + // that the response matches the precache manifest's expectations, + // and there's either a) no integrity property in the incoming request + // or b) there is an integrity, and it matches the precache manifest. + // See https://github.com/GoogleChrome/workbox/issues/2858 + // Also if the original request users no-cors we don't use integrity. + // See https://github.com/GoogleChrome/workbox/issues/3096 + + if (integrityInManifest && noIntegrityConflict && request.mode !== 'no-cors') { + this._useDefaultCacheabilityPluginIfNeeded(); + + const wasCached = await handler.cachePut(request, response.clone()); + + { + if (wasCached) { + logger_js.logger.log(`A response for ${getFriendlyURL_js.getFriendlyURL(request.url)} ` + `was used to "repair" the precache.`); + } + } + } + } else { + // This shouldn't normally happen, but there are edge cases: + // https://github.com/GoogleChrome/workbox/issues/1441 + throw new WorkboxError_js.WorkboxError('missing-precache-entry', { + cacheName: this.cacheName, + url: request.url + }); + } + + { + const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read')); // Workbox is going to handle the route. + // print the routing details to the console. + + logger_js.logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL_js.getFriendlyURL(request.url)); + logger_js.logger.log(`Serving the precached url: ${getFriendlyURL_js.getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`); + logger_js.logger.groupCollapsed(`View request details here.`); + logger_js.logger.log(request); + logger_js.logger.groupEnd(); + logger_js.logger.groupCollapsed(`View response details here.`); + logger_js.logger.log(response); + logger_js.logger.groupEnd(); + logger_js.logger.groupEnd(); + } + + return response; + } + + async _handleInstall(request, handler) { + this._useDefaultCacheabilityPluginIfNeeded(); + + const response = await handler.fetch(request); // Make sure we defer cachePut() until after we know the response + // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737 + + const wasCached = await handler.cachePut(request, response.clone()); + + if (!wasCached) { + // Throwing here will lead to the `install` handler failing, which + // we want to do if *any* of the responses aren't safe to cache. + throw new WorkboxError_js.WorkboxError('bad-precaching-response', { + url: request.url, + status: response.status + }); + } + + return response; + } + /** + * This method is complex, as there a number of things to account for: + * + * The `plugins` array can be set at construction, and/or it might be added to + * to at any time before the strategy is used. + * + * At the time the strategy is used (i.e. during an `install` event), there + * needs to be at least one plugin that implements `cacheWillUpdate` in the + * array, other than `copyRedirectedCacheableResponsesPlugin`. + * + * - If this method is called and there are no suitable `cacheWillUpdate` + * plugins, we need to add `defaultPrecacheCacheabilityPlugin`. + * + * - If this method is called and there is exactly one `cacheWillUpdate`, then + * we don't have to do anything (this might be a previously added + * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin). + * + * - If this method is called and there is more than one `cacheWillUpdate`, + * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so, + * we need to remove it. (This situation is unlikely, but it could happen if + * the strategy is used multiple times, the first without a `cacheWillUpdate`, + * and then later on after manually adding a custom `cacheWillUpdate`.) + * + * See https://github.com/GoogleChrome/workbox/issues/2737 for more context. + * + * @private + */ + + + _useDefaultCacheabilityPluginIfNeeded() { + let defaultPluginIndex = null; + let cacheWillUpdatePluginCount = 0; + + for (const [index, plugin] of this.plugins.entries()) { + // Ignore the copy redirected plugin when determining what to do. + if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) { + continue; + } // Save the default plugin's index, in case it needs to be removed. + + + if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) { + defaultPluginIndex = index; + } + + if (plugin.cacheWillUpdate) { + cacheWillUpdatePluginCount++; + } + } + + if (cacheWillUpdatePluginCount === 0) { + this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin); + } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) { + // Only remove the default plugin; multiple custom plugins are allowed. + this.plugins.splice(defaultPluginIndex, 1); + } // Nothing needs to be done if cacheWillUpdatePluginCount is 1 + + } + + } + + PrecacheStrategy.defaultPrecacheCacheabilityPlugin = { + async cacheWillUpdate({ + response + }) { + if (!response || response.status >= 400) { + return null; + } + + return response; + } + + }; + PrecacheStrategy.copyRedirectedCacheableResponsesPlugin = { + async cacheWillUpdate({ + response + }) { + return response.redirected ? await copyResponse_js.copyResponse(response) : response; + } + + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Performs efficient precaching of assets. + * + * @memberof workbox-precaching + */ + + class PrecacheController { + /** + * Create a new PrecacheController. + * + * @param {Object} [options] + * @param {string} [options.cacheName] The cache to use for precaching. + * @param {string} [options.plugins] Plugins to use when precaching as well + * as responding to fetch events for precached assets. + * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to + * get the response from the network if there's a precache miss. + */ + constructor({ + cacheName, + plugins = [], + fallbackToNetwork = true + } = {}) { + this._urlsToCacheKeys = new Map(); + this._urlsToCacheModes = new Map(); + this._cacheKeysToIntegrities = new Map(); + this._strategy = new PrecacheStrategy({ + cacheName: cacheNames_js.cacheNames.getPrecacheName(cacheName), + plugins: [...plugins, new PrecacheCacheKeyPlugin({ + precacheController: this + })], + fallbackToNetwork + }); // Bind the install and activate methods to the instance. + + this.install = this.install.bind(this); + this.activate = this.activate.bind(this); + } + /** + * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and + * used to cache assets and respond to fetch events. + */ + + + get strategy() { + return this._strategy; + } + /** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * @param {Array} [entries=[]] Array of entries to precache. + */ + + + precache(entries) { + this.addToCacheList(entries); + + if (!this._installAndActiveListenersAdded) { + self.addEventListener('install', this.install); + self.addEventListener('activate', this.activate); + this._installAndActiveListenersAdded = true; + } + } + /** + * This method will add items to the precache list, removing duplicates + * and ensuring the information is valid. + * + * @param {Array} entries + * Array of entries to precache. + */ + + + addToCacheList(entries) { + { + assert_js.assert.isArray(entries, { + moduleName: 'workbox-precaching', + className: 'PrecacheController', + funcName: 'addToCacheList', + paramName: 'entries' + }); + } + + const urlsToWarnAbout = []; + + for (const entry of entries) { + // See https://github.com/GoogleChrome/workbox/issues/2259 + if (typeof entry === 'string') { + urlsToWarnAbout.push(entry); + } else if (entry && entry.revision === undefined) { + urlsToWarnAbout.push(entry.url); + } + + const { + cacheKey, + url + } = createCacheKey(entry); + const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default'; + + if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) { + throw new WorkboxError_js.WorkboxError('add-to-cache-list-conflicting-entries', { + firstEntry: this._urlsToCacheKeys.get(url), + secondEntry: cacheKey + }); + } + + if (typeof entry !== 'string' && entry.integrity) { + if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) { + throw new WorkboxError_js.WorkboxError('add-to-cache-list-conflicting-integrities', { + url + }); + } + + this._cacheKeysToIntegrities.set(cacheKey, entry.integrity); + } + + this._urlsToCacheKeys.set(url, cacheKey); + + this._urlsToCacheModes.set(url, cacheMode); + + if (urlsToWarnAbout.length > 0) { + const warningMessage = `Workbox is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`; + + { + logger_js.logger.warn(warningMessage); + } + } + } + } + /** + * Precaches new and updated assets. Call this method from the service worker + * install event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + + + install(event) { + // waitUntil returns Promise + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return waitUntil_js.waitUntil(event, async () => { + const installReportPlugin = new PrecacheInstallReportPlugin(); + this.strategy.plugins.push(installReportPlugin); // Cache entries one at a time. + // See https://github.com/GoogleChrome/workbox/issues/2528 + + for (const [url, cacheKey] of this._urlsToCacheKeys) { + const integrity = this._cacheKeysToIntegrities.get(cacheKey); + + const cacheMode = this._urlsToCacheModes.get(url); + + const request = new Request(url, { + integrity, + cache: cacheMode, + credentials: 'same-origin' + }); + await Promise.all(this.strategy.handleAll({ + params: { + cacheKey + }, + request, + event + })); + } + + const { + updatedURLs, + notUpdatedURLs + } = installReportPlugin; + + { + printInstallDetails(updatedURLs, notUpdatedURLs); + } + + return { + updatedURLs, + notUpdatedURLs + }; + }); + } + /** + * Deletes assets that are no longer present in the current precache manifest. + * Call this method from the service worker activate event. + * + * Note: this method calls `event.waitUntil()` for you, so you do not need + * to call it yourself in your event handlers. + * + * @param {ExtendableEvent} event + * @return {Promise} + */ + + + activate(event) { + // waitUntil returns Promise + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return waitUntil_js.waitUntil(event, async () => { + const cache = await self.caches.open(this.strategy.cacheName); + const currentlyCachedRequests = await cache.keys(); + const expectedCacheKeys = new Set(this._urlsToCacheKeys.values()); + const deletedURLs = []; + + for (const request of currentlyCachedRequests) { + if (!expectedCacheKeys.has(request.url)) { + await cache.delete(request); + deletedURLs.push(request.url); + } + } + + { + printCleanupDetails(deletedURLs); + } + + return { + deletedURLs + }; + }); + } + /** + * Returns a mapping of a precached URL to the corresponding cache key, taking + * into account the revision information for the URL. + * + * @return {Map} A URL to cache key mapping. + */ + + + getURLsToCacheKeys() { + return this._urlsToCacheKeys; + } + /** + * Returns a list of all the URLs that have been precached by the current + * service worker. + * + * @return {Array} The precached URLs. + */ + + + getCachedURLs() { + return [...this._urlsToCacheKeys.keys()]; + } + /** + * Returns the cache key used for storing a given URL. If that URL is + * unversioned, like `/index.html', then the cache key will be the original + * URL with a search parameter appended to it. + * + * @param {string} url A URL whose cache key you want to look up. + * @return {string} The versioned URL that corresponds to a cache key + * for the original URL, or undefined if that URL isn't precached. + */ + + + getCacheKeyForURL(url) { + const urlObject = new URL(url, location.href); + return this._urlsToCacheKeys.get(urlObject.href); + } + /** + * @param {string} url A cache key whose SRI you want to look up. + * @return {string} The subresource integrity associated with the cache key, + * or undefined if it's not set. + */ + + + getIntegrityForCacheKey(cacheKey) { + return this._cacheKeysToIntegrities.get(cacheKey); + } + /** + * This acts as a drop-in replacement for + * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match) + * with the following differences: + * + * - It knows what the name of the precache is, and only checks in that cache. + * - It allows you to pass in an "original" URL without versioning parameters, + * and it will automatically look up the correct cache key for the currently + * active revision of that URL. + * + * E.g., `matchPrecache('index.html')` will find the correct precached + * response for the currently active service worker, even if the actual cache + * key is `'/index.html?__WB_REVISION__=1234abcd'`. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + */ + + + async matchPrecache(request) { + const url = request instanceof Request ? request.url : request; + const cacheKey = this.getCacheKeyForURL(url); + + if (cacheKey) { + const cache = await self.caches.open(this.strategy.cacheName); + return cache.match(cacheKey); + } + + return undefined; + } + /** + * Returns a function that looks up `url` in the precache (taking into + * account revision information), and returns the corresponding `Response`. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @return {workbox-routing~handlerCallback} + */ + + + createHandlerBoundToURL(url) { + const cacheKey = this.getCacheKeyForURL(url); + + if (!cacheKey) { + throw new WorkboxError_js.WorkboxError('non-precached-url', { + url + }); + } + + return options => { + options.request = new Request(url); + options.params = Object.assign({ + cacheKey + }, options.params); + return this.strategy.handle(options); + }; + } + + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + let precacheController; + /** + * @return {PrecacheController} + * @private + */ + + const getOrCreatePrecacheController = () => { + if (!precacheController) { + precacheController = new PrecacheController(); + } + + return precacheController; + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Adds plugins to the precaching strategy. + * + * @param {Array} plugins + * + * @memberof workbox-precaching + */ + + function addPlugins(plugins) { + const precacheController = getOrCreatePrecacheController(); + precacheController.strategy.plugins.push(...plugins); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Removes any URL search parameters that should be ignored. + * + * @param {URL} urlObject The original URL. + * @param {Array} ignoreURLParametersMatching RegExps to test against + * each search parameter name. Matches mean that the search parameter should be + * ignored. + * @return {URL} The URL with any ignored search parameters removed. + * + * @private + * @memberof workbox-precaching + */ + + function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) { + // Convert the iterable into an array at the start of the loop to make sure + // deletion doesn't mess up iteration. + for (const paramName of [...urlObject.searchParams.keys()]) { + if (ignoreURLParametersMatching.some(regExp => regExp.test(paramName))) { + urlObject.searchParams.delete(paramName); + } + } + + return urlObject; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Generator function that yields possible variations on the original URL to + * check, one at a time. + * + * @param {string} url + * @param {Object} options + * + * @private + * @memberof workbox-precaching + */ + + function* generateURLVariations(url, { + ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], + directoryIndex = 'index.html', + cleanURLs = true, + urlManipulation + } = {}) { + const urlObject = new URL(url, location.href); + urlObject.hash = ''; + yield urlObject.href; + const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching); + yield urlWithoutIgnoredParams.href; + + if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) { + const directoryURL = new URL(urlWithoutIgnoredParams.href); + directoryURL.pathname += directoryIndex; + yield directoryURL.href; + } + + if (cleanURLs) { + const cleanURL = new URL(urlWithoutIgnoredParams.href); + cleanURL.pathname += '.html'; + yield cleanURL.href; + } + + if (urlManipulation) { + const additionalURLs = urlManipulation({ + url: urlObject + }); + + for (const urlToAttempt of additionalURLs) { + yield urlToAttempt.href; + } + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A subclass of {@link workbox-routing.Route} that takes a + * {@link workbox-precaching.PrecacheController} + * instance and uses it to match incoming requests and handle fetching + * responses from the precache. + * + * @memberof workbox-precaching + * @extends workbox-routing.Route + */ + + class PrecacheRoute extends Route_js.Route { + /** + * @param {PrecacheController} precacheController A `PrecacheController` + * instance used to both match requests and respond to fetch events. + * @param {Object} [options] Options to control how requests are matched + * against the list of precached URLs. + * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will + * check cache entries for a URLs ending with '/' to see if there is a hit when + * appending the `directoryIndex` value. + * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An + * array of regex's to remove search params when looking for a cache match. + * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will + * check the cache for the URL with a `.html` added to the end of the end. + * @param {workbox-precaching~urlManipulation} [options.urlManipulation] + * This is a function that should take a URL and return an array of + * alternative URLs that should be checked for precache matches. + */ + constructor(precacheController, options) { + const match = ({ + request + }) => { + const urlsToCacheKeys = precacheController.getURLsToCacheKeys(); + + for (const possibleURL of generateURLVariations(request.url, options)) { + const cacheKey = urlsToCacheKeys.get(possibleURL); + + if (cacheKey) { + const integrity = precacheController.getIntegrityForCacheKey(cacheKey); + return { + cacheKey, + integrity + }; + } + } + + { + logger_js.logger.debug(`Precaching did not find a match for ` + getFriendlyURL_js.getFriendlyURL(request.url)); + } + + return; + }; + + super(match, precacheController.strategy); + } + + } + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Add a `fetch` listener to the service worker that will + * respond to + * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests} + * with precached assets. + * + * Requests for assets that aren't precached, the `FetchEvent` will not be + * responded to, allowing the event to fall through to other `fetch` event + * listeners. + * + * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute} + * options. + * + * @memberof workbox-precaching + */ + + function addRoute(options) { + const precacheController = getOrCreatePrecacheController(); + const precacheRoute = new PrecacheRoute(precacheController, options); + registerRoute_js.registerRoute(precacheRoute); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const SUBSTRING_TO_FIND = '-precache-'; + /** + * Cleans up incompatible precaches that were created by older versions of + * Workbox, by a service worker registered under the current scope. + * + * This is meant to be called as part of the `activate` event. + * + * This should be safe to use as long as you don't include `substringToFind` + * (defaulting to `-precache-`) in your non-precache cache names. + * + * @param {string} currentPrecacheName The cache name currently in use for + * precaching. This cache won't be deleted. + * @param {string} [substringToFind='-precache-'] Cache names which include this + * substring will be deleted (excluding `currentPrecacheName`). + * @return {Array} A list of all the cache names that were deleted. + * + * @private + * @memberof workbox-precaching + */ + + const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => { + const cacheNames = await self.caches.keys(); + const cacheNamesToDelete = cacheNames.filter(cacheName => { + return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName; + }); + await Promise.all(cacheNamesToDelete.map(cacheName => self.caches.delete(cacheName))); + return cacheNamesToDelete; + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Adds an `activate` event listener which will clean up incompatible + * precaches that were created by older versions of Workbox. + * + * @memberof workbox-precaching + */ + + function cleanupOutdatedCaches() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('activate', event => { + const cacheName = cacheNames_js.cacheNames.getPrecacheName(); + event.waitUntil(deleteOutdatedCaches(cacheName).then(cachesDeleted => { + { + if (cachesDeleted.length > 0) { + logger_js.logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted); + } + } + })); + }); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Helper function that calls + * {@link PrecacheController#createHandlerBoundToURL} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call the + * {@link PrecacheController#createHandlerBoundToURL} on that instance, + * instead of using this function. + * + * @param {string} url The precached URL which will be used to lookup the + * `Response`. + * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the + * response from the network if there's a precache miss. + * @return {workbox-routing~handlerCallback} + * + * @memberof workbox-precaching + */ + + function createHandlerBoundToURL(url) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.createHandlerBoundToURL(url); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Takes in a URL, and returns the corresponding URL that could be used to + * lookup the entry in the precache. + * + * If a relative URL is provided, the location of the service worker file will + * be used as the base. + * + * For precached entries without revision information, the cache key will be the + * same as the original URL. + * + * For precached entries with revision information, the cache key will be the + * original URL with the addition of a query parameter used for keeping track of + * the revision info. + * + * @param {string} url The URL whose cache key to look up. + * @return {string} The cache key that corresponds to that URL. + * + * @memberof workbox-precaching + */ + + function getCacheKeyForURL(url) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.getCacheKeyForURL(url); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Helper function that calls + * {@link PrecacheController#matchPrecache} on the default + * {@link PrecacheController} instance. + * + * If you are creating your own {@link PrecacheController}, then call + * {@link PrecacheController#matchPrecache} on that instance, + * instead of using this function. + * + * @param {string|Request} request The key (without revisioning parameters) + * to look up in the precache. + * @return {Promise} + * + * @memberof workbox-precaching + */ + + function matchPrecache(request) { + const precacheController = getOrCreatePrecacheController(); + return precacheController.matchPrecache(request); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * {@link workbox-core.cacheNames|"precache cache"} when the service + * worker installs. + * + * This method can be called multiple times. + * + * Please note: This method **will not** serve any of the cached files for you. + * It only precaches files. To respond to a network request you call + * {@link workbox-precaching.addRoute}. + * + * If you have a single array of files to precache, you can just call + * {@link workbox-precaching.precacheAndRoute}. + * + * @param {Array} [entries=[]] Array of entries to precache. + * + * @memberof workbox-precaching + */ + + function precache(entries) { + const precacheController = getOrCreatePrecacheController(); + precacheController.precache(entries); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This method will add entries to the precache list and add a route to + * respond to fetch events. + * + * This is a convenience method that will call + * {@link workbox-precaching.precache} and + * {@link workbox-precaching.addRoute} in a single call. + * + * @param {Array} entries Array of entries to precache. + * @param {Object} [options] See the + * {@link workbox-precaching.PrecacheRoute} options. + * + * @memberof workbox-precaching + */ + + function precacheAndRoute(entries, options) { + precache(entries); + addRoute(options); + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * `PrecacheFallbackPlugin` allows you to specify an "offline fallback" + * response to be used when a given strategy is unable to generate a response. + * + * It does this by intercepting the `handlerDidError` plugin callback + * and returning a precached response, taking the expected revision parameter + * into account automatically. + * + * Unless you explicitly pass in a `PrecacheController` instance to the + * constructor, the default instance will be used. Generally speaking, most + * developers will end up using the default. + * + * @memberof workbox-precaching + */ + + class PrecacheFallbackPlugin { + /** + * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL. + * + * @param {Object} config + * @param {string} config.fallbackURL A precached URL to use as the fallback + * if the associated strategy can't generate a response. + * @param {PrecacheController} [config.precacheController] An optional + * PrecacheController instance. If not provided, the default + * PrecacheController will be used. + */ + constructor({ + fallbackURL, + precacheController + }) { + /** + * @return {Promise} The precache response for the fallback URL. + * + * @private + */ + this.handlerDidError = () => this._precacheController.matchPrecache(this._fallbackURL); + + this._fallbackURL = fallbackURL; + this._precacheController = precacheController || getOrCreatePrecacheController(); + } + + } + + exports.PrecacheController = PrecacheController; + exports.PrecacheFallbackPlugin = PrecacheFallbackPlugin; + exports.PrecacheRoute = PrecacheRoute; + exports.PrecacheStrategy = PrecacheStrategy; + exports.addPlugins = addPlugins; + exports.addRoute = addRoute; + exports.cleanupOutdatedCaches = cleanupOutdatedCaches; + exports.createHandlerBoundToURL = createHandlerBoundToURL; + exports.getCacheKeyForURL = getCacheKeyForURL; + exports.matchPrecache = matchPrecache; + exports.precache = precache; + exports.precacheAndRoute = precacheAndRoute; + + return exports; + +}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core, workbox.core._private, workbox.strategies, workbox.routing, workbox.routing)); +//# sourceMappingURL=workbox-precaching.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-precaching.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-precaching.dev.js.map new file mode 100644 index 0000000..cba5c99 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-precaching.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-precaching.dev.js","sources":["../_version.js","../utils/createCacheKey.js","../utils/PrecacheInstallReportPlugin.js","../utils/PrecacheCacheKeyPlugin.js","../utils/printCleanupDetails.js","../utils/printInstallDetails.js","../PrecacheStrategy.js","../PrecacheController.js","../utils/getOrCreatePrecacheController.js","../addPlugins.js","../utils/removeIgnoredSearchParams.js","../utils/generateURLVariations.js","../PrecacheRoute.js","../addRoute.js","../utils/deleteOutdatedCaches.js","../cleanupOutdatedCaches.js","../createHandlerBoundToURL.js","../getCacheKeyForURL.js","../matchPrecache.js","../precache.js","../precacheAndRoute.js","../PrecacheFallbackPlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:precaching:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport '../_version.js';\n// Name of the search parameter used to store revision info.\nconst REVISION_SEARCH_PARAM = '__WB_REVISION__';\n/**\n * Converts a manifest entry into a versioned URL suitable for precaching.\n *\n * @param {Object|string} entry\n * @return {string} A URL with versioning info.\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function createCacheKey(entry) {\n if (!entry) {\n throw new WorkboxError('add-to-cache-list-unexpected-type', { entry });\n }\n // If a precache manifest entry is a string, it's assumed to be a versioned\n // URL, like '/app.abcd1234.js'. Return as-is.\n if (typeof entry === 'string') {\n const urlObject = new URL(entry, location.href);\n return {\n cacheKey: urlObject.href,\n url: urlObject.href,\n };\n }\n const { revision, url } = entry;\n if (!url) {\n throw new WorkboxError('add-to-cache-list-unexpected-type', { entry });\n }\n // If there's just a URL and no revision, then it's also assumed to be a\n // versioned URL.\n if (!revision) {\n const urlObject = new URL(url, location.href);\n return {\n cacheKey: urlObject.href,\n url: urlObject.href,\n };\n }\n // Otherwise, construct a properly versioned URL using the custom Workbox\n // search parameter along with the revision info.\n const cacheKeyURL = new URL(url, location.href);\n const originalURL = new URL(url, location.href);\n cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);\n return {\n cacheKey: cacheKeyURL.href,\n url: originalURL.href,\n };\n}\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A plugin, designed to be used with PrecacheController, to determine the\n * of assets that were updated (or not updated) during the install event.\n *\n * @private\n */\nclass PrecacheInstallReportPlugin {\n constructor() {\n this.updatedURLs = [];\n this.notUpdatedURLs = [];\n this.handlerWillStart = async ({ request, state, }) => {\n // TODO: `state` should never be undefined...\n if (state) {\n state.originalRequest = request;\n }\n };\n this.cachedResponseWillBeUsed = async ({ event, state, cachedResponse, }) => {\n if (event.type === 'install') {\n if (state &&\n state.originalRequest &&\n state.originalRequest instanceof Request) {\n // TODO: `state` should never be undefined...\n const url = state.originalRequest.url;\n if (cachedResponse) {\n this.notUpdatedURLs.push(url);\n }\n else {\n this.updatedURLs.push(url);\n }\n }\n }\n return cachedResponse;\n };\n }\n}\nexport { PrecacheInstallReportPlugin };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A plugin, designed to be used with PrecacheController, to translate URLs into\n * the corresponding cache key, based on the current revision info.\n *\n * @private\n */\nclass PrecacheCacheKeyPlugin {\n constructor({ precacheController }) {\n this.cacheKeyWillBeUsed = async ({ request, params, }) => {\n // Params is type any, can't change right now.\n /* eslint-disable */\n const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) ||\n this._precacheController.getCacheKeyForURL(request.url);\n /* eslint-enable */\n return cacheKey\n ? new Request(cacheKey, { headers: request.headers })\n : request;\n };\n this._precacheController = precacheController;\n }\n}\nexport { PrecacheCacheKeyPlugin };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport '../_version.js';\n/**\n * @param {string} groupTitle\n * @param {Array} deletedURLs\n *\n * @private\n */\nconst logGroup = (groupTitle, deletedURLs) => {\n logger.groupCollapsed(groupTitle);\n for (const url of deletedURLs) {\n logger.log(url);\n }\n logger.groupEnd();\n};\n/**\n * @param {Array} deletedURLs\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function printCleanupDetails(deletedURLs) {\n const deletionCount = deletedURLs.length;\n if (deletionCount > 0) {\n logger.groupCollapsed(`During precaching cleanup, ` +\n `${deletionCount} cached ` +\n `request${deletionCount === 1 ? ' was' : 's were'} deleted.`);\n logGroup('Deleted Cache Requests', deletedURLs);\n logger.groupEnd();\n }\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport '../_version.js';\n/**\n * @param {string} groupTitle\n * @param {Array} urls\n *\n * @private\n */\nfunction _nestedGroup(groupTitle, urls) {\n if (urls.length === 0) {\n return;\n }\n logger.groupCollapsed(groupTitle);\n for (const url of urls) {\n logger.log(url);\n }\n logger.groupEnd();\n}\n/**\n * @param {Array} urlsToPrecache\n * @param {Array} urlsAlreadyPrecached\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {\n const precachedCount = urlsToPrecache.length;\n const alreadyPrecachedCount = urlsAlreadyPrecached.length;\n if (precachedCount || alreadyPrecachedCount) {\n let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`;\n if (alreadyPrecachedCount > 0) {\n message +=\n ` ${alreadyPrecachedCount} ` +\n `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`;\n }\n logger.groupCollapsed(message);\n _nestedGroup(`View newly precached URLs.`, urlsToPrecache);\n _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);\n logger.groupEnd();\n }\n}\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { copyResponse } from 'workbox-core/copyResponse.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from 'workbox-strategies/Strategy.js';\nimport './_version.js';\n/**\n * A {@link workbox-strategies.Strategy} implementation\n * specifically designed to work with\n * {@link workbox-precaching.PrecacheController}\n * to both cache and fetch precached assets.\n *\n * Note: an instance of this class is created automatically when creating a\n * `PrecacheController`; it's generally not necessary to create this yourself.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-precaching\n */\nclass PrecacheStrategy extends Strategy {\n /**\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}\n * of all fetch() requests made by this strategy.\n * @param {Object} [options.matchOptions] The\n * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to\n * get the response from the network if there's a precache miss.\n */\n constructor(options = {}) {\n options.cacheName = cacheNames.getPrecacheName(options.cacheName);\n super(options);\n this._fallbackToNetwork =\n options.fallbackToNetwork === false ? false : true;\n // Redirected responses cannot be used to satisfy a navigation request, so\n // any redirected response must be \"copied\" rather than cloned, so the new\n // response doesn't contain the `redirected` flag. See:\n // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1\n this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const response = await handler.cacheMatch(request);\n if (response) {\n return response;\n }\n // If this is an `install` event for an entry that isn't already cached,\n // then populate the cache.\n if (handler.event && handler.event.type === 'install') {\n return await this._handleInstall(request, handler);\n }\n // Getting here means something went wrong. An entry that should have been\n // precached wasn't found in the cache.\n return await this._handleFetch(request, handler);\n }\n async _handleFetch(request, handler) {\n let response;\n const params = (handler.params || {});\n // Fall back to the network if we're configured to do so.\n if (this._fallbackToNetwork) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`The precached response for ` +\n `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` +\n `found. Falling back to the network.`);\n }\n const integrityInManifest = params.integrity;\n const integrityInRequest = request.integrity;\n const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;\n // Do not add integrity if the original request is no-cors\n // See https://github.com/GoogleChrome/workbox/issues/3096\n response = await handler.fetch(new Request(request, {\n integrity: request.mode !== 'no-cors'\n ? integrityInRequest || integrityInManifest\n : undefined,\n }));\n // It's only \"safe\" to repair the cache if we're using SRI to guarantee\n // that the response matches the precache manifest's expectations,\n // and there's either a) no integrity property in the incoming request\n // or b) there is an integrity, and it matches the precache manifest.\n // See https://github.com/GoogleChrome/workbox/issues/2858\n // Also if the original request users no-cors we don't use integrity.\n // See https://github.com/GoogleChrome/workbox/issues/3096\n if (integrityInManifest &&\n noIntegrityConflict &&\n request.mode !== 'no-cors') {\n this._useDefaultCacheabilityPluginIfNeeded();\n const wasCached = await handler.cachePut(request, response.clone());\n if (process.env.NODE_ENV !== 'production') {\n if (wasCached) {\n logger.log(`A response for ${getFriendlyURL(request.url)} ` +\n `was used to \"repair\" the precache.`);\n }\n }\n }\n }\n else {\n // This shouldn't normally happen, but there are edge cases:\n // https://github.com/GoogleChrome/workbox/issues/1441\n throw new WorkboxError('missing-precache-entry', {\n cacheName: this.cacheName,\n url: request.url,\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read'));\n // Workbox is going to handle the route.\n // print the routing details to the console.\n logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));\n logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);\n logger.groupCollapsed(`View request details here.`);\n logger.log(request);\n logger.groupEnd();\n logger.groupCollapsed(`View response details here.`);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n return response;\n }\n async _handleInstall(request, handler) {\n this._useDefaultCacheabilityPluginIfNeeded();\n const response = await handler.fetch(request);\n // Make sure we defer cachePut() until after we know the response\n // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737\n const wasCached = await handler.cachePut(request, response.clone());\n if (!wasCached) {\n // Throwing here will lead to the `install` handler failing, which\n // we want to do if *any* of the responses aren't safe to cache.\n throw new WorkboxError('bad-precaching-response', {\n url: request.url,\n status: response.status,\n });\n }\n return response;\n }\n /**\n * This method is complex, as there a number of things to account for:\n *\n * The `plugins` array can be set at construction, and/or it might be added to\n * to at any time before the strategy is used.\n *\n * At the time the strategy is used (i.e. during an `install` event), there\n * needs to be at least one plugin that implements `cacheWillUpdate` in the\n * array, other than `copyRedirectedCacheableResponsesPlugin`.\n *\n * - If this method is called and there are no suitable `cacheWillUpdate`\n * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.\n *\n * - If this method is called and there is exactly one `cacheWillUpdate`, then\n * we don't have to do anything (this might be a previously added\n * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).\n *\n * - If this method is called and there is more than one `cacheWillUpdate`,\n * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,\n * we need to remove it. (This situation is unlikely, but it could happen if\n * the strategy is used multiple times, the first without a `cacheWillUpdate`,\n * and then later on after manually adding a custom `cacheWillUpdate`.)\n *\n * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.\n *\n * @private\n */\n _useDefaultCacheabilityPluginIfNeeded() {\n let defaultPluginIndex = null;\n let cacheWillUpdatePluginCount = 0;\n for (const [index, plugin] of this.plugins.entries()) {\n // Ignore the copy redirected plugin when determining what to do.\n if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {\n continue;\n }\n // Save the default plugin's index, in case it needs to be removed.\n if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {\n defaultPluginIndex = index;\n }\n if (plugin.cacheWillUpdate) {\n cacheWillUpdatePluginCount++;\n }\n }\n if (cacheWillUpdatePluginCount === 0) {\n this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);\n }\n else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {\n // Only remove the default plugin; multiple custom plugins are allowed.\n this.plugins.splice(defaultPluginIndex, 1);\n }\n // Nothing needs to be done if cacheWillUpdatePluginCount is 1\n }\n}\nPrecacheStrategy.defaultPrecacheCacheabilityPlugin = {\n async cacheWillUpdate({ response }) {\n if (!response || response.status >= 400) {\n return null;\n }\n return response;\n },\n};\nPrecacheStrategy.copyRedirectedCacheableResponsesPlugin = {\n async cacheWillUpdate({ response }) {\n return response.redirected ? await copyResponse(response) : response;\n },\n};\nexport { PrecacheStrategy };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { waitUntil } from 'workbox-core/_private/waitUntil.js';\nimport { createCacheKey } from './utils/createCacheKey.js';\nimport { PrecacheInstallReportPlugin } from './utils/PrecacheInstallReportPlugin.js';\nimport { PrecacheCacheKeyPlugin } from './utils/PrecacheCacheKeyPlugin.js';\nimport { printCleanupDetails } from './utils/printCleanupDetails.js';\nimport { printInstallDetails } from './utils/printInstallDetails.js';\nimport { PrecacheStrategy } from './PrecacheStrategy.js';\nimport './_version.js';\n/**\n * Performs efficient precaching of assets.\n *\n * @memberof workbox-precaching\n */\nclass PrecacheController {\n /**\n * Create a new PrecacheController.\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] The cache to use for precaching.\n * @param {string} [options.plugins] Plugins to use when precaching as well\n * as responding to fetch events for precached assets.\n * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to\n * get the response from the network if there's a precache miss.\n */\n constructor({ cacheName, plugins = [], fallbackToNetwork = true, } = {}) {\n this._urlsToCacheKeys = new Map();\n this._urlsToCacheModes = new Map();\n this._cacheKeysToIntegrities = new Map();\n this._strategy = new PrecacheStrategy({\n cacheName: cacheNames.getPrecacheName(cacheName),\n plugins: [\n ...plugins,\n new PrecacheCacheKeyPlugin({ precacheController: this }),\n ],\n fallbackToNetwork,\n });\n // Bind the install and activate methods to the instance.\n this.install = this.install.bind(this);\n this.activate = this.activate.bind(this);\n }\n /**\n * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and\n * used to cache assets and respond to fetch events.\n */\n get strategy() {\n return this._strategy;\n }\n /**\n * Adds items to the precache list, removing any duplicates and\n * stores the files in the\n * {@link workbox-core.cacheNames|\"precache cache\"} when the service\n * worker installs.\n *\n * This method can be called multiple times.\n *\n * @param {Array} [entries=[]] Array of entries to precache.\n */\n precache(entries) {\n this.addToCacheList(entries);\n if (!this._installAndActiveListenersAdded) {\n self.addEventListener('install', this.install);\n self.addEventListener('activate', this.activate);\n this._installAndActiveListenersAdded = true;\n }\n }\n /**\n * This method will add items to the precache list, removing duplicates\n * and ensuring the information is valid.\n *\n * @param {Array} entries\n * Array of entries to precache.\n */\n addToCacheList(entries) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(entries, {\n moduleName: 'workbox-precaching',\n className: 'PrecacheController',\n funcName: 'addToCacheList',\n paramName: 'entries',\n });\n }\n const urlsToWarnAbout = [];\n for (const entry of entries) {\n // See https://github.com/GoogleChrome/workbox/issues/2259\n if (typeof entry === 'string') {\n urlsToWarnAbout.push(entry);\n }\n else if (entry && entry.revision === undefined) {\n urlsToWarnAbout.push(entry.url);\n }\n const { cacheKey, url } = createCacheKey(entry);\n const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';\n if (this._urlsToCacheKeys.has(url) &&\n this._urlsToCacheKeys.get(url) !== cacheKey) {\n throw new WorkboxError('add-to-cache-list-conflicting-entries', {\n firstEntry: this._urlsToCacheKeys.get(url),\n secondEntry: cacheKey,\n });\n }\n if (typeof entry !== 'string' && entry.integrity) {\n if (this._cacheKeysToIntegrities.has(cacheKey) &&\n this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {\n throw new WorkboxError('add-to-cache-list-conflicting-integrities', {\n url,\n });\n }\n this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);\n }\n this._urlsToCacheKeys.set(url, cacheKey);\n this._urlsToCacheModes.set(url, cacheMode);\n if (urlsToWarnAbout.length > 0) {\n const warningMessage = `Workbox is precaching URLs without revision ` +\n `info: ${urlsToWarnAbout.join(', ')}\\nThis is generally NOT safe. ` +\n `Learn more at https://bit.ly/wb-precache`;\n if (process.env.NODE_ENV === 'production') {\n // Use console directly to display this warning without bloating\n // bundle sizes by pulling in all of the logger codebase in prod.\n console.warn(warningMessage);\n }\n else {\n logger.warn(warningMessage);\n }\n }\n }\n }\n /**\n * Precaches new and updated assets. Call this method from the service worker\n * install event.\n *\n * Note: this method calls `event.waitUntil()` for you, so you do not need\n * to call it yourself in your event handlers.\n *\n * @param {ExtendableEvent} event\n * @return {Promise}\n */\n install(event) {\n // waitUntil returns Promise\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return waitUntil(event, async () => {\n const installReportPlugin = new PrecacheInstallReportPlugin();\n this.strategy.plugins.push(installReportPlugin);\n // Cache entries one at a time.\n // See https://github.com/GoogleChrome/workbox/issues/2528\n for (const [url, cacheKey] of this._urlsToCacheKeys) {\n const integrity = this._cacheKeysToIntegrities.get(cacheKey);\n const cacheMode = this._urlsToCacheModes.get(url);\n const request = new Request(url, {\n integrity,\n cache: cacheMode,\n credentials: 'same-origin',\n });\n await Promise.all(this.strategy.handleAll({\n params: { cacheKey },\n request,\n event,\n }));\n }\n const { updatedURLs, notUpdatedURLs } = installReportPlugin;\n if (process.env.NODE_ENV !== 'production') {\n printInstallDetails(updatedURLs, notUpdatedURLs);\n }\n return { updatedURLs, notUpdatedURLs };\n });\n }\n /**\n * Deletes assets that are no longer present in the current precache manifest.\n * Call this method from the service worker activate event.\n *\n * Note: this method calls `event.waitUntil()` for you, so you do not need\n * to call it yourself in your event handlers.\n *\n * @param {ExtendableEvent} event\n * @return {Promise}\n */\n activate(event) {\n // waitUntil returns Promise\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return waitUntil(event, async () => {\n const cache = await self.caches.open(this.strategy.cacheName);\n const currentlyCachedRequests = await cache.keys();\n const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());\n const deletedURLs = [];\n for (const request of currentlyCachedRequests) {\n if (!expectedCacheKeys.has(request.url)) {\n await cache.delete(request);\n deletedURLs.push(request.url);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n printCleanupDetails(deletedURLs);\n }\n return { deletedURLs };\n });\n }\n /**\n * Returns a mapping of a precached URL to the corresponding cache key, taking\n * into account the revision information for the URL.\n *\n * @return {Map} A URL to cache key mapping.\n */\n getURLsToCacheKeys() {\n return this._urlsToCacheKeys;\n }\n /**\n * Returns a list of all the URLs that have been precached by the current\n * service worker.\n *\n * @return {Array} The precached URLs.\n */\n getCachedURLs() {\n return [...this._urlsToCacheKeys.keys()];\n }\n /**\n * Returns the cache key used for storing a given URL. If that URL is\n * unversioned, like `/index.html', then the cache key will be the original\n * URL with a search parameter appended to it.\n *\n * @param {string} url A URL whose cache key you want to look up.\n * @return {string} The versioned URL that corresponds to a cache key\n * for the original URL, or undefined if that URL isn't precached.\n */\n getCacheKeyForURL(url) {\n const urlObject = new URL(url, location.href);\n return this._urlsToCacheKeys.get(urlObject.href);\n }\n /**\n * @param {string} url A cache key whose SRI you want to look up.\n * @return {string} The subresource integrity associated with the cache key,\n * or undefined if it's not set.\n */\n getIntegrityForCacheKey(cacheKey) {\n return this._cacheKeysToIntegrities.get(cacheKey);\n }\n /**\n * This acts as a drop-in replacement for\n * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)\n * with the following differences:\n *\n * - It knows what the name of the precache is, and only checks in that cache.\n * - It allows you to pass in an \"original\" URL without versioning parameters,\n * and it will automatically look up the correct cache key for the currently\n * active revision of that URL.\n *\n * E.g., `matchPrecache('index.html')` will find the correct precached\n * response for the currently active service worker, even if the actual cache\n * key is `'/index.html?__WB_REVISION__=1234abcd'`.\n *\n * @param {string|Request} request The key (without revisioning parameters)\n * to look up in the precache.\n * @return {Promise}\n */\n async matchPrecache(request) {\n const url = request instanceof Request ? request.url : request;\n const cacheKey = this.getCacheKeyForURL(url);\n if (cacheKey) {\n const cache = await self.caches.open(this.strategy.cacheName);\n return cache.match(cacheKey);\n }\n return undefined;\n }\n /**\n * Returns a function that looks up `url` in the precache (taking into\n * account revision information), and returns the corresponding `Response`.\n *\n * @param {string} url The precached URL which will be used to lookup the\n * `Response`.\n * @return {workbox-routing~handlerCallback}\n */\n createHandlerBoundToURL(url) {\n const cacheKey = this.getCacheKeyForURL(url);\n if (!cacheKey) {\n throw new WorkboxError('non-precached-url', { url });\n }\n return (options) => {\n options.request = new Request(url);\n options.params = Object.assign({ cacheKey }, options.params);\n return this.strategy.handle(options);\n };\n }\n}\nexport { PrecacheController };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { PrecacheController } from '../PrecacheController.js';\nimport '../_version.js';\nlet precacheController;\n/**\n * @return {PrecacheController}\n * @private\n */\nexport const getOrCreatePrecacheController = () => {\n if (!precacheController) {\n precacheController = new PrecacheController();\n }\n return precacheController;\n};\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Adds plugins to the precaching strategy.\n *\n * @param {Array} plugins\n *\n * @memberof workbox-precaching\n */\nfunction addPlugins(plugins) {\n const precacheController = getOrCreatePrecacheController();\n precacheController.strategy.plugins.push(...plugins);\n}\nexport { addPlugins };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Removes any URL search parameters that should be ignored.\n *\n * @param {URL} urlObject The original URL.\n * @param {Array} ignoreURLParametersMatching RegExps to test against\n * each search parameter name. Matches mean that the search parameter should be\n * ignored.\n * @return {URL} The URL with any ignored search parameters removed.\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {\n // Convert the iterable into an array at the start of the loop to make sure\n // deletion doesn't mess up iteration.\n for (const paramName of [...urlObject.searchParams.keys()]) {\n if (ignoreURLParametersMatching.some((regExp) => regExp.test(paramName))) {\n urlObject.searchParams.delete(paramName);\n }\n }\n return urlObject;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { removeIgnoredSearchParams } from './removeIgnoredSearchParams.js';\nimport '../_version.js';\n/**\n * Generator function that yields possible variations on the original URL to\n * check, one at a time.\n *\n * @param {string} url\n * @param {Object} options\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function* generateURLVariations(url, { ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], directoryIndex = 'index.html', cleanURLs = true, urlManipulation, } = {}) {\n const urlObject = new URL(url, location.href);\n urlObject.hash = '';\n yield urlObject.href;\n const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);\n yield urlWithoutIgnoredParams.href;\n if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {\n const directoryURL = new URL(urlWithoutIgnoredParams.href);\n directoryURL.pathname += directoryIndex;\n yield directoryURL.href;\n }\n if (cleanURLs) {\n const cleanURL = new URL(urlWithoutIgnoredParams.href);\n cleanURL.pathname += '.html';\n yield cleanURL.href;\n }\n if (urlManipulation) {\n const additionalURLs = urlManipulation({ url: urlObject });\n for (const urlToAttempt of additionalURLs) {\n yield urlToAttempt.href;\n }\n }\n}\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { generateURLVariations } from './utils/generateURLVariations.js';\nimport './_version.js';\n/**\n * A subclass of {@link workbox-routing.Route} that takes a\n * {@link workbox-precaching.PrecacheController}\n * instance and uses it to match incoming requests and handle fetching\n * responses from the precache.\n *\n * @memberof workbox-precaching\n * @extends workbox-routing.Route\n */\nclass PrecacheRoute extends Route {\n /**\n * @param {PrecacheController} precacheController A `PrecacheController`\n * instance used to both match requests and respond to fetch events.\n * @param {Object} [options] Options to control how requests are matched\n * against the list of precached URLs.\n * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will\n * check cache entries for a URLs ending with '/' to see if there is a hit when\n * appending the `directoryIndex` value.\n * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An\n * array of regex's to remove search params when looking for a cache match.\n * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will\n * check the cache for the URL with a `.html` added to the end of the end.\n * @param {workbox-precaching~urlManipulation} [options.urlManipulation]\n * This is a function that should take a URL and return an array of\n * alternative URLs that should be checked for precache matches.\n */\n constructor(precacheController, options) {\n const match = ({ request, }) => {\n const urlsToCacheKeys = precacheController.getURLsToCacheKeys();\n for (const possibleURL of generateURLVariations(request.url, options)) {\n const cacheKey = urlsToCacheKeys.get(possibleURL);\n if (cacheKey) {\n const integrity = precacheController.getIntegrityForCacheKey(cacheKey);\n return { cacheKey, integrity };\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));\n }\n return;\n };\n super(match, precacheController.strategy);\n }\n}\nexport { PrecacheRoute };\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport { PrecacheRoute } from './PrecacheRoute.js';\nimport './_version.js';\n/**\n * Add a `fetch` listener to the service worker that will\n * respond to\n * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}\n * with precached assets.\n *\n * Requests for assets that aren't precached, the `FetchEvent` will not be\n * responded to, allowing the event to fall through to other `fetch` event\n * listeners.\n *\n * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute}\n * options.\n *\n * @memberof workbox-precaching\n */\nfunction addRoute(options) {\n const precacheController = getOrCreatePrecacheController();\n const precacheRoute = new PrecacheRoute(precacheController, options);\n registerRoute(precacheRoute);\n}\nexport { addRoute };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst SUBSTRING_TO_FIND = '-precache-';\n/**\n * Cleans up incompatible precaches that were created by older versions of\n * Workbox, by a service worker registered under the current scope.\n *\n * This is meant to be called as part of the `activate` event.\n *\n * This should be safe to use as long as you don't include `substringToFind`\n * (defaulting to `-precache-`) in your non-precache cache names.\n *\n * @param {string} currentPrecacheName The cache name currently in use for\n * precaching. This cache won't be deleted.\n * @param {string} [substringToFind='-precache-'] Cache names which include this\n * substring will be deleted (excluding `currentPrecacheName`).\n * @return {Array} A list of all the cache names that were deleted.\n *\n * @private\n * @memberof workbox-precaching\n */\nconst deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {\n const cacheNames = await self.caches.keys();\n const cacheNamesToDelete = cacheNames.filter((cacheName) => {\n return (cacheName.includes(substringToFind) &&\n cacheName.includes(self.registration.scope) &&\n cacheName !== currentPrecacheName);\n });\n await Promise.all(cacheNamesToDelete.map((cacheName) => self.caches.delete(cacheName)));\n return cacheNamesToDelete;\n};\nexport { deleteOutdatedCaches };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { deleteOutdatedCaches } from './utils/deleteOutdatedCaches.js';\nimport './_version.js';\n/**\n * Adds an `activate` event listener which will clean up incompatible\n * precaches that were created by older versions of Workbox.\n *\n * @memberof workbox-precaching\n */\nfunction cleanupOutdatedCaches() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('activate', ((event) => {\n const cacheName = cacheNames.getPrecacheName();\n event.waitUntil(deleteOutdatedCaches(cacheName).then((cachesDeleted) => {\n if (process.env.NODE_ENV !== 'production') {\n if (cachesDeleted.length > 0) {\n logger.log(`The following out-of-date precaches were cleaned up ` +\n `automatically:`, cachesDeleted);\n }\n }\n }));\n }));\n}\nexport { cleanupOutdatedCaches };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Helper function that calls\n * {@link PrecacheController#createHandlerBoundToURL} on the default\n * {@link PrecacheController} instance.\n *\n * If you are creating your own {@link PrecacheController}, then call the\n * {@link PrecacheController#createHandlerBoundToURL} on that instance,\n * instead of using this function.\n *\n * @param {string} url The precached URL which will be used to lookup the\n * `Response`.\n * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the\n * response from the network if there's a precache miss.\n * @return {workbox-routing~handlerCallback}\n *\n * @memberof workbox-precaching\n */\nfunction createHandlerBoundToURL(url) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.createHandlerBoundToURL(url);\n}\nexport { createHandlerBoundToURL };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Takes in a URL, and returns the corresponding URL that could be used to\n * lookup the entry in the precache.\n *\n * If a relative URL is provided, the location of the service worker file will\n * be used as the base.\n *\n * For precached entries without revision information, the cache key will be the\n * same as the original URL.\n *\n * For precached entries with revision information, the cache key will be the\n * original URL with the addition of a query parameter used for keeping track of\n * the revision info.\n *\n * @param {string} url The URL whose cache key to look up.\n * @return {string} The cache key that corresponds to that URL.\n *\n * @memberof workbox-precaching\n */\nfunction getCacheKeyForURL(url) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.getCacheKeyForURL(url);\n}\nexport { getCacheKeyForURL };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Helper function that calls\n * {@link PrecacheController#matchPrecache} on the default\n * {@link PrecacheController} instance.\n *\n * If you are creating your own {@link PrecacheController}, then call\n * {@link PrecacheController#matchPrecache} on that instance,\n * instead of using this function.\n *\n * @param {string|Request} request The key (without revisioning parameters)\n * to look up in the precache.\n * @return {Promise}\n *\n * @memberof workbox-precaching\n */\nfunction matchPrecache(request) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.matchPrecache(request);\n}\nexport { matchPrecache };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Adds items to the precache list, removing any duplicates and\n * stores the files in the\n * {@link workbox-core.cacheNames|\"precache cache\"} when the service\n * worker installs.\n *\n * This method can be called multiple times.\n *\n * Please note: This method **will not** serve any of the cached files for you.\n * It only precaches files. To respond to a network request you call\n * {@link workbox-precaching.addRoute}.\n *\n * If you have a single array of files to precache, you can just call\n * {@link workbox-precaching.precacheAndRoute}.\n *\n * @param {Array} [entries=[]] Array of entries to precache.\n *\n * @memberof workbox-precaching\n */\nfunction precache(entries) {\n const precacheController = getOrCreatePrecacheController();\n precacheController.precache(entries);\n}\nexport { precache };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { addRoute } from './addRoute.js';\nimport { precache } from './precache.js';\nimport './_version.js';\n/**\n * This method will add entries to the precache list and add a route to\n * respond to fetch events.\n *\n * This is a convenience method that will call\n * {@link workbox-precaching.precache} and\n * {@link workbox-precaching.addRoute} in a single call.\n *\n * @param {Array} entries Array of entries to precache.\n * @param {Object} [options] See the\n * {@link workbox-precaching.PrecacheRoute} options.\n *\n * @memberof workbox-precaching\n */\nfunction precacheAndRoute(entries, options) {\n precache(entries);\n addRoute(options);\n}\nexport { precacheAndRoute };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * `PrecacheFallbackPlugin` allows you to specify an \"offline fallback\"\n * response to be used when a given strategy is unable to generate a response.\n *\n * It does this by intercepting the `handlerDidError` plugin callback\n * and returning a precached response, taking the expected revision parameter\n * into account automatically.\n *\n * Unless you explicitly pass in a `PrecacheController` instance to the\n * constructor, the default instance will be used. Generally speaking, most\n * developers will end up using the default.\n *\n * @memberof workbox-precaching\n */\nclass PrecacheFallbackPlugin {\n /**\n * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL.\n *\n * @param {Object} config\n * @param {string} config.fallbackURL A precached URL to use as the fallback\n * if the associated strategy can't generate a response.\n * @param {PrecacheController} [config.precacheController] An optional\n * PrecacheController instance. If not provided, the default\n * PrecacheController will be used.\n */\n constructor({ fallbackURL, precacheController, }) {\n /**\n * @return {Promise} The precache response for the fallback URL.\n *\n * @private\n */\n this.handlerDidError = () => this._precacheController.matchPrecache(this._fallbackURL);\n this._fallbackURL = fallbackURL;\n this._precacheController =\n precacheController || getOrCreatePrecacheController();\n }\n}\nexport { PrecacheFallbackPlugin };\n"],"names":["self","_","e","REVISION_SEARCH_PARAM","createCacheKey","entry","WorkboxError","urlObject","URL","location","href","cacheKey","url","revision","cacheKeyURL","originalURL","searchParams","set","PrecacheInstallReportPlugin","constructor","updatedURLs","notUpdatedURLs","handlerWillStart","request","state","originalRequest","cachedResponseWillBeUsed","event","cachedResponse","type","Request","push","PrecacheCacheKeyPlugin","precacheController","cacheKeyWillBeUsed","params","_precacheController","getCacheKeyForURL","headers","logGroup","groupTitle","deletedURLs","logger","groupCollapsed","log","groupEnd","printCleanupDetails","deletionCount","length","_nestedGroup","urls","printInstallDetails","urlsToPrecache","urlsAlreadyPrecached","precachedCount","alreadyPrecachedCount","message","PrecacheStrategy","Strategy","options","cacheName","cacheNames","getPrecacheName","_fallbackToNetwork","fallbackToNetwork","plugins","copyRedirectedCacheableResponsesPlugin","_handle","handler","response","cacheMatch","_handleInstall","_handleFetch","warn","getFriendlyURL","integrityInManifest","integrity","integrityInRequest","noIntegrityConflict","fetch","mode","undefined","_useDefaultCacheabilityPluginIfNeeded","wasCached","cachePut","clone","getCacheKey","status","defaultPluginIndex","cacheWillUpdatePluginCount","index","plugin","entries","defaultPrecacheCacheabilityPlugin","cacheWillUpdate","splice","redirected","copyResponse","PrecacheController","_urlsToCacheKeys","Map","_urlsToCacheModes","_cacheKeysToIntegrities","_strategy","install","bind","activate","strategy","precache","addToCacheList","_installAndActiveListenersAdded","addEventListener","assert","isArray","moduleName","className","funcName","paramName","urlsToWarnAbout","cacheMode","has","get","firstEntry","secondEntry","warningMessage","join","waitUntil","installReportPlugin","cache","credentials","Promise","all","handleAll","caches","open","currentlyCachedRequests","keys","expectedCacheKeys","Set","values","delete","getURLsToCacheKeys","getCachedURLs","getIntegrityForCacheKey","matchPrecache","match","createHandlerBoundToURL","Object","assign","handle","getOrCreatePrecacheController","addPlugins","removeIgnoredSearchParams","ignoreURLParametersMatching","some","regExp","test","generateURLVariations","directoryIndex","cleanURLs","urlManipulation","hash","urlWithoutIgnoredParams","pathname","endsWith","directoryURL","cleanURL","additionalURLs","urlToAttempt","PrecacheRoute","Route","urlsToCacheKeys","possibleURL","debug","addRoute","precacheRoute","registerRoute","SUBSTRING_TO_FIND","deleteOutdatedCaches","currentPrecacheName","substringToFind","cacheNamesToDelete","filter","includes","registration","scope","map","cleanupOutdatedCaches","then","cachesDeleted","precacheAndRoute","PrecacheFallbackPlugin","fallbackURL","handlerDidError","_fallbackURL"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,0BAAD,CAAJ,IAAoCC,CAAC,EAArC;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;;IAIA,MAAMC,qBAAqB,GAAG,iBAA9B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACO,SAASC,cAAT,CAAwBC,KAAxB,EAA+B;IAClC,MAAI,CAACA,KAAL,EAAY;IACR,UAAM,IAAIC,4BAAJ,CAAiB,mCAAjB,EAAsD;IAAED,MAAAA;IAAF,KAAtD,CAAN;IACH,GAHiC;IAKlC;;;IACA,MAAI,OAAOA,KAAP,KAAiB,QAArB,EAA+B;IAC3B,UAAME,SAAS,GAAG,IAAIC,GAAJ,CAAQH,KAAR,EAAeI,QAAQ,CAACC,IAAxB,CAAlB;IACA,WAAO;IACHC,MAAAA,QAAQ,EAAEJ,SAAS,CAACG,IADjB;IAEHE,MAAAA,GAAG,EAAEL,SAAS,CAACG;IAFZ,KAAP;IAIH;;IACD,QAAM;IAAEG,IAAAA,QAAF;IAAYD,IAAAA;IAAZ,MAAoBP,KAA1B;;IACA,MAAI,CAACO,GAAL,EAAU;IACN,UAAM,IAAIN,4BAAJ,CAAiB,mCAAjB,EAAsD;IAAED,MAAAA;IAAF,KAAtD,CAAN;IACH,GAhBiC;IAkBlC;;;IACA,MAAI,CAACQ,QAAL,EAAe;IACX,UAAMN,SAAS,GAAG,IAAIC,GAAJ,CAAQI,GAAR,EAAaH,QAAQ,CAACC,IAAtB,CAAlB;IACA,WAAO;IACHC,MAAAA,QAAQ,EAAEJ,SAAS,CAACG,IADjB;IAEHE,MAAAA,GAAG,EAAEL,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IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASyB,iBAAT,CAA2BzB,GAA3B,EAAgC;IAC5B,QAAMqB,kBAAkB,GAAGqH,6BAA6B,EAAxD;IACA,SAAOrH,kBAAkB,CAACI,iBAAnB,CAAqCzB,GAArC,CAAP;IACH;;IC/BD;IACA;AACA;IACA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASoI,aAAT,CAAuBzH,OAAvB,EAAgC;IAC5B,QAAMU,kBAAkB,GAAGqH,6BAA6B,EAAxD;IACA,SAAOrH,kBAAkB,CAAC+G,aAAnB,CAAiCzH,OAAjC,CAAP;IACH;;IC3BD;IACA;AACA;IACA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASqF,QAAT,CAAkBhB,OAAlB,EAA2B;IACvB,QAAM3D,kBAAkB,GAAGqH,6BAA6B,EAAxD;IACArH,EAAAA,kBAAkB,CAAC2E,QAAnB,CAA4BhB,OAA5B;IACH;;IC/BD;IACA;AACA;IACA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASkG,gBAAT,CAA0BlG,OAA1B,EAAmCjC,OAAnC,EAA4C;IACxCiD,EAAAA,QAAQ,CAAChB,OAAD,CAAR;IACAkF,EAAAA,QAAQ,CAACnH,OAAD,CAAR;IACH;;IC3BD;IACA;AACA;IACA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,MAAMoI,sBAAN,CAA6B;IACzB;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACI5K,EAAAA,WAAW,CAAC;IAAE6K,IAAAA,WAAF;IAAe/J,IAAAA;IAAf,GAAD,EAAuC;IAC9C;IACR;IACA;IACA;IACA;IACQ,SAAKgK,eAAL,GAAuB,MAAM,KAAK7J,mBAAL,CAAyB4G,aAAzB,CAAuC,KAAKkD,YAA5C,CAA7B;;IACA,SAAKA,YAAL,GAAoBF,WAApB;IACA,SAAK5J,mBAAL,GACIH,kBAAkB,IAAIqH,6BAA6B,EADvD;IAEH;;IArBwB;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-precaching.prod.js b/src/Resources/workbox-v7.0.0/workbox-precaching.prod.js new file mode 100644 index 0000000..42cfb80 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-precaching.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.precaching=function(t,e,s,n,i,c,r,o){"use strict";try{self["workbox:precaching:7.0.0"]&&_()}catch(t){}function a(t){if(!t)throw new s.WorkboxError("add-to-cache-list-unexpected-type",{entry:t});if("string"==typeof t){const e=new URL(t,location.href);return{cacheKey:e.href,url:e.href}}const{revision:e,url:n}=t;if(!n)throw new s.WorkboxError("add-to-cache-list-unexpected-type",{entry:t});if(!e){const t=new URL(n,location.href);return{cacheKey:t.href,url:t.href}}const i=new URL(n,location.href),c=new URL(n,location.href);return i.searchParams.set("__WB_REVISION__",e),{cacheKey:i.href,url:c.href}}class h{constructor(){this.updatedURLs=[],this.notUpdatedURLs=[],this.handlerWillStart=async({request:t,state:e})=>{e&&(e.originalRequest=t)},this.cachedResponseWillBeUsed=async({event:t,state:e,cachedResponse:s})=>{if("install"===t.type&&e&&e.originalRequest&&e.originalRequest instanceof Request){const t=e.originalRequest.url;s?this.notUpdatedURLs.push(t):this.updatedURLs.push(t)}return s}}}class l{constructor({precacheController:t}){this.cacheKeyWillBeUsed=async({request:t,params:e})=>{const s=(null==e?void 0:e.cacheKey)||this.tt.getCacheKeyForURL(t.url);return s?new Request(s,{headers:t.headers}):t},this.tt=t}}class u extends c.Strategy{constructor(t={}){t.cacheName=e.cacheNames.getPrecacheName(t.cacheName),super(t),this.et=!1!==t.fallbackToNetwork,this.plugins.push(u.copyRedirectedCacheableResponsesPlugin)}async _handle(t,e){const s=await e.cacheMatch(t);return s||(e.event&&"install"===e.event.type?await this.st(t,e):await this.nt(t,e))}async nt(t,e){let n;const i=e.params||{};if(!this.et)throw new s.WorkboxError("missing-precache-entry",{cacheName:this.cacheName,url:t.url});{const s=i.integrity,c=t.integrity,r=!c||c===s;n=await e.fetch(new Request(t,{integrity:"no-cors"!==t.mode?c||s:void 0})),s&&r&&"no-cors"!==t.mode&&(this.it(),await e.cachePut(t,n.clone()))}return n}async st(t,e){this.it();const n=await e.fetch(t);if(!await e.cachePut(t,n.clone()))throw new s.WorkboxError("bad-precaching-response",{url:t.url,status:n.status});return n}it(){let t=null,e=0;for(const[s,n]of this.plugins.entries())n!==u.copyRedirectedCacheableResponsesPlugin&&(n===u.defaultPrecacheCacheabilityPlugin&&(t=s),n.cacheWillUpdate&&e++);0===e?this.plugins.push(u.defaultPrecacheCacheabilityPlugin):e>1&&null!==t&&this.plugins.splice(t,1)}}u.defaultPrecacheCacheabilityPlugin={cacheWillUpdate:async({response:t})=>!t||t.status>=400?null:t},u.copyRedirectedCacheableResponsesPlugin={cacheWillUpdate:async({response:t})=>t.redirected?await i.copyResponse(t):t};class f{constructor({cacheName:t,plugins:s=[],fallbackToNetwork:n=!0}={}){this.ct=new Map,this.rt=new Map,this.ot=new Map,this.ht=new u({cacheName:e.cacheNames.getPrecacheName(t),plugins:[...s,new l({precacheController:this})],fallbackToNetwork:n}),this.install=this.install.bind(this),this.activate=this.activate.bind(this)}get strategy(){return this.ht}precache(t){this.addToCacheList(t),this.lt||(self.addEventListener("install",this.install),self.addEventListener("activate",this.activate),this.lt=!0)}addToCacheList(t){const e=[];for(const n of t){"string"==typeof n?e.push(n):n&&void 0===n.revision&&e.push(n.url);const{cacheKey:t,url:i}=a(n),c="string"!=typeof n&&n.revision?"reload":"default";if(this.ct.has(i)&&this.ct.get(i)!==t)throw new s.WorkboxError("add-to-cache-list-conflicting-entries",{firstEntry:this.ct.get(i),secondEntry:t});if("string"!=typeof n&&n.integrity){if(this.ot.has(t)&&this.ot.get(t)!==n.integrity)throw new s.WorkboxError("add-to-cache-list-conflicting-integrities",{url:i});this.ot.set(t,n.integrity)}if(this.ct.set(i,t),this.rt.set(i,c),e.length>0){const t=`Workbox is precaching URLs without revision info: ${e.join(", ")}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;console.warn(t)}}}install(t){return n.waitUntil(t,(async()=>{const e=new h;this.strategy.plugins.push(e);for(const[e,s]of this.ct){const n=this.ot.get(s),i=this.rt.get(e),c=new Request(e,{integrity:n,cache:i,credentials:"same-origin"});await Promise.all(this.strategy.handleAll({params:{cacheKey:s},request:c,event:t}))}const{updatedURLs:s,notUpdatedURLs:n}=e;return{updatedURLs:s,notUpdatedURLs:n}}))}activate(t){return n.waitUntil(t,(async()=>{const t=await self.caches.open(this.strategy.cacheName),e=await t.keys(),s=new Set(this.ct.values()),n=[];for(const i of e)s.has(i.url)||(await t.delete(i),n.push(i.url));return{deletedURLs:n}}))}getURLsToCacheKeys(){return this.ct}getCachedURLs(){return[...this.ct.keys()]}getCacheKeyForURL(t){const e=new URL(t,location.href);return this.ct.get(e.href)}getIntegrityForCacheKey(t){return this.ot.get(t)}async matchPrecache(t){const e=t instanceof Request?t.url:t,s=this.getCacheKeyForURL(e);if(s){return(await self.caches.open(this.strategy.cacheName)).match(s)}}createHandlerBoundToURL(t){const e=this.getCacheKeyForURL(t);if(!e)throw new s.WorkboxError("non-precached-url",{url:t});return s=>(s.request=new Request(t),s.params=Object.assign({cacheKey:e},s.params),this.strategy.handle(s))}}let w;const d=()=>(w||(w=new f),w);class y extends o.Route{constructor(t,e){super((({request:s})=>{const n=t.getURLsToCacheKeys();for(const i of function*(t,{ignoreURLParametersMatching:e=[/^utm_/,/^fbclid$/],directoryIndex:s="index.html",cleanURLs:n=!0,urlManipulation:i}={}){const c=new URL(t,location.href);c.hash="",yield c.href;const r=function(t,e=[]){for(const s of[...t.searchParams.keys()])e.some((t=>t.test(s)))&&t.searchParams.delete(s);return t}(c,e);if(yield r.href,s&&r.pathname.endsWith("/")){const t=new URL(r.href);t.pathname+=s,yield t.href}if(n){const t=new URL(r.href);t.pathname+=".html",yield t.href}if(i){const t=i({url:c});for(const e of t)yield e.href}}(s.url,e)){const e=n.get(i);if(e){return{cacheKey:e,integrity:t.getIntegrityForCacheKey(e)}}}}),t.strategy)}}function p(t){const e=d(),s=new y(e,t);r.registerRoute(s)}function R(t){d().precache(t)}return t.PrecacheController=f,t.PrecacheFallbackPlugin=class{constructor({fallbackURL:t,precacheController:e}){this.handlerDidError=()=>this.tt.matchPrecache(this.ut),this.ut=t,this.tt=e||d()}},t.PrecacheRoute=y,t.PrecacheStrategy=u,t.addPlugins=function(t){d().strategy.plugins.push(...t)},t.addRoute=p,t.cleanupOutdatedCaches=function(){self.addEventListener("activate",(t=>{const s=e.cacheNames.getPrecacheName();t.waitUntil((async(t,e="-precache-")=>{const s=(await self.caches.keys()).filter((s=>s.includes(e)&&s.includes(self.registration.scope)&&s!==t));return await Promise.all(s.map((t=>self.caches.delete(t)))),s})(s).then((t=>{})))}))},t.createHandlerBoundToURL=function(t){return d().createHandlerBoundToURL(t)},t.getCacheKeyForURL=function(t){return d().getCacheKeyForURL(t)},t.matchPrecache=function(t){return d().matchPrecache(t)},t.precache=R,t.precacheAndRoute=function(t,e){R(t),p(e)},t}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core,workbox.strategies,workbox.routing,workbox.routing); +//# sourceMappingURL=workbox-precaching.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-precaching.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-precaching.prod.js.map new file mode 100644 index 0000000..234e346 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-precaching.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-precaching.prod.js","sources":["../_version.js","../utils/createCacheKey.js","../utils/PrecacheInstallReportPlugin.js","../utils/PrecacheCacheKeyPlugin.js","../PrecacheStrategy.js","../PrecacheController.js","../utils/getOrCreatePrecacheController.js","../PrecacheRoute.js","../utils/generateURLVariations.js","../utils/removeIgnoredSearchParams.js","../addRoute.js","../precache.js","../PrecacheFallbackPlugin.js","../addPlugins.js","../cleanupOutdatedCaches.js","../utils/deleteOutdatedCaches.js","../createHandlerBoundToURL.js","../getCacheKeyForURL.js","../matchPrecache.js","../precacheAndRoute.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:precaching:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport '../_version.js';\n// Name of the search parameter used to store revision info.\nconst REVISION_SEARCH_PARAM = '__WB_REVISION__';\n/**\n * Converts a manifest entry into a versioned URL suitable for precaching.\n *\n * @param {Object|string} entry\n * @return {string} A URL with versioning info.\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function createCacheKey(entry) {\n if (!entry) {\n throw new WorkboxError('add-to-cache-list-unexpected-type', { entry });\n }\n // If a precache manifest entry is a string, it's assumed to be a versioned\n // URL, like '/app.abcd1234.js'. Return as-is.\n if (typeof entry === 'string') {\n const urlObject = new URL(entry, location.href);\n return {\n cacheKey: urlObject.href,\n url: urlObject.href,\n };\n }\n const { revision, url } = entry;\n if (!url) {\n throw new WorkboxError('add-to-cache-list-unexpected-type', { entry });\n }\n // If there's just a URL and no revision, then it's also assumed to be a\n // versioned URL.\n if (!revision) {\n const urlObject = new URL(url, location.href);\n return {\n cacheKey: urlObject.href,\n url: urlObject.href,\n };\n }\n // Otherwise, construct a properly versioned URL using the custom Workbox\n // search parameter along with the revision info.\n const cacheKeyURL = new URL(url, location.href);\n const originalURL = new URL(url, location.href);\n cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);\n return {\n cacheKey: cacheKeyURL.href,\n url: originalURL.href,\n };\n}\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A plugin, designed to be used with PrecacheController, to determine the\n * of assets that were updated (or not updated) during the install event.\n *\n * @private\n */\nclass PrecacheInstallReportPlugin {\n constructor() {\n this.updatedURLs = [];\n this.notUpdatedURLs = [];\n this.handlerWillStart = async ({ request, state, }) => {\n // TODO: `state` should never be undefined...\n if (state) {\n state.originalRequest = request;\n }\n };\n this.cachedResponseWillBeUsed = async ({ event, state, cachedResponse, }) => {\n if (event.type === 'install') {\n if (state &&\n state.originalRequest &&\n state.originalRequest instanceof Request) {\n // TODO: `state` should never be undefined...\n const url = state.originalRequest.url;\n if (cachedResponse) {\n this.notUpdatedURLs.push(url);\n }\n else {\n this.updatedURLs.push(url);\n }\n }\n }\n return cachedResponse;\n };\n }\n}\nexport { PrecacheInstallReportPlugin };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A plugin, designed to be used with PrecacheController, to translate URLs into\n * the corresponding cache key, based on the current revision info.\n *\n * @private\n */\nclass PrecacheCacheKeyPlugin {\n constructor({ precacheController }) {\n this.cacheKeyWillBeUsed = async ({ request, params, }) => {\n // Params is type any, can't change right now.\n /* eslint-disable */\n const cacheKey = (params === null || params === void 0 ? void 0 : params.cacheKey) ||\n this._precacheController.getCacheKeyForURL(request.url);\n /* eslint-enable */\n return cacheKey\n ? new Request(cacheKey, { headers: request.headers })\n : request;\n };\n this._precacheController = precacheController;\n }\n}\nexport { PrecacheCacheKeyPlugin };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { copyResponse } from 'workbox-core/copyResponse.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from 'workbox-strategies/Strategy.js';\nimport './_version.js';\n/**\n * A {@link workbox-strategies.Strategy} implementation\n * specifically designed to work with\n * {@link workbox-precaching.PrecacheController}\n * to both cache and fetch precached assets.\n *\n * Note: an instance of this class is created automatically when creating a\n * `PrecacheController`; it's generally not necessary to create this yourself.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-precaching\n */\nclass PrecacheStrategy extends Strategy {\n /**\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}\n * of all fetch() requests made by this strategy.\n * @param {Object} [options.matchOptions] The\n * {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to\n * get the response from the network if there's a precache miss.\n */\n constructor(options = {}) {\n options.cacheName = cacheNames.getPrecacheName(options.cacheName);\n super(options);\n this._fallbackToNetwork =\n options.fallbackToNetwork === false ? false : true;\n // Redirected responses cannot be used to satisfy a navigation request, so\n // any redirected response must be \"copied\" rather than cloned, so the new\n // response doesn't contain the `redirected` flag. See:\n // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1\n this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const response = await handler.cacheMatch(request);\n if (response) {\n return response;\n }\n // If this is an `install` event for an entry that isn't already cached,\n // then populate the cache.\n if (handler.event && handler.event.type === 'install') {\n return await this._handleInstall(request, handler);\n }\n // Getting here means something went wrong. An entry that should have been\n // precached wasn't found in the cache.\n return await this._handleFetch(request, handler);\n }\n async _handleFetch(request, handler) {\n let response;\n const params = (handler.params || {});\n // Fall back to the network if we're configured to do so.\n if (this._fallbackToNetwork) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`The precached response for ` +\n `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` +\n `found. Falling back to the network.`);\n }\n const integrityInManifest = params.integrity;\n const integrityInRequest = request.integrity;\n const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;\n // Do not add integrity if the original request is no-cors\n // See https://github.com/GoogleChrome/workbox/issues/3096\n response = await handler.fetch(new Request(request, {\n integrity: request.mode !== 'no-cors'\n ? integrityInRequest || integrityInManifest\n : undefined,\n }));\n // It's only \"safe\" to repair the cache if we're using SRI to guarantee\n // that the response matches the precache manifest's expectations,\n // and there's either a) no integrity property in the incoming request\n // or b) there is an integrity, and it matches the precache manifest.\n // See https://github.com/GoogleChrome/workbox/issues/2858\n // Also if the original request users no-cors we don't use integrity.\n // See https://github.com/GoogleChrome/workbox/issues/3096\n if (integrityInManifest &&\n noIntegrityConflict &&\n request.mode !== 'no-cors') {\n this._useDefaultCacheabilityPluginIfNeeded();\n const wasCached = await handler.cachePut(request, response.clone());\n if (process.env.NODE_ENV !== 'production') {\n if (wasCached) {\n logger.log(`A response for ${getFriendlyURL(request.url)} ` +\n `was used to \"repair\" the precache.`);\n }\n }\n }\n }\n else {\n // This shouldn't normally happen, but there are edge cases:\n // https://github.com/GoogleChrome/workbox/issues/1441\n throw new WorkboxError('missing-precache-entry', {\n cacheName: this.cacheName,\n url: request.url,\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n const cacheKey = params.cacheKey || (await handler.getCacheKey(request, 'read'));\n // Workbox is going to handle the route.\n // print the routing details to the console.\n logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));\n logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);\n logger.groupCollapsed(`View request details here.`);\n logger.log(request);\n logger.groupEnd();\n logger.groupCollapsed(`View response details here.`);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n return response;\n }\n async _handleInstall(request, handler) {\n this._useDefaultCacheabilityPluginIfNeeded();\n const response = await handler.fetch(request);\n // Make sure we defer cachePut() until after we know the response\n // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737\n const wasCached = await handler.cachePut(request, response.clone());\n if (!wasCached) {\n // Throwing here will lead to the `install` handler failing, which\n // we want to do if *any* of the responses aren't safe to cache.\n throw new WorkboxError('bad-precaching-response', {\n url: request.url,\n status: response.status,\n });\n }\n return response;\n }\n /**\n * This method is complex, as there a number of things to account for:\n *\n * The `plugins` array can be set at construction, and/or it might be added to\n * to at any time before the strategy is used.\n *\n * At the time the strategy is used (i.e. during an `install` event), there\n * needs to be at least one plugin that implements `cacheWillUpdate` in the\n * array, other than `copyRedirectedCacheableResponsesPlugin`.\n *\n * - If this method is called and there are no suitable `cacheWillUpdate`\n * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.\n *\n * - If this method is called and there is exactly one `cacheWillUpdate`, then\n * we don't have to do anything (this might be a previously added\n * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).\n *\n * - If this method is called and there is more than one `cacheWillUpdate`,\n * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,\n * we need to remove it. (This situation is unlikely, but it could happen if\n * the strategy is used multiple times, the first without a `cacheWillUpdate`,\n * and then later on after manually adding a custom `cacheWillUpdate`.)\n *\n * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.\n *\n * @private\n */\n _useDefaultCacheabilityPluginIfNeeded() {\n let defaultPluginIndex = null;\n let cacheWillUpdatePluginCount = 0;\n for (const [index, plugin] of this.plugins.entries()) {\n // Ignore the copy redirected plugin when determining what to do.\n if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {\n continue;\n }\n // Save the default plugin's index, in case it needs to be removed.\n if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {\n defaultPluginIndex = index;\n }\n if (plugin.cacheWillUpdate) {\n cacheWillUpdatePluginCount++;\n }\n }\n if (cacheWillUpdatePluginCount === 0) {\n this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);\n }\n else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {\n // Only remove the default plugin; multiple custom plugins are allowed.\n this.plugins.splice(defaultPluginIndex, 1);\n }\n // Nothing needs to be done if cacheWillUpdatePluginCount is 1\n }\n}\nPrecacheStrategy.defaultPrecacheCacheabilityPlugin = {\n async cacheWillUpdate({ response }) {\n if (!response || response.status >= 400) {\n return null;\n }\n return response;\n },\n};\nPrecacheStrategy.copyRedirectedCacheableResponsesPlugin = {\n async cacheWillUpdate({ response }) {\n return response.redirected ? await copyResponse(response) : response;\n },\n};\nexport { PrecacheStrategy };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { waitUntil } from 'workbox-core/_private/waitUntil.js';\nimport { createCacheKey } from './utils/createCacheKey.js';\nimport { PrecacheInstallReportPlugin } from './utils/PrecacheInstallReportPlugin.js';\nimport { PrecacheCacheKeyPlugin } from './utils/PrecacheCacheKeyPlugin.js';\nimport { printCleanupDetails } from './utils/printCleanupDetails.js';\nimport { printInstallDetails } from './utils/printInstallDetails.js';\nimport { PrecacheStrategy } from './PrecacheStrategy.js';\nimport './_version.js';\n/**\n * Performs efficient precaching of assets.\n *\n * @memberof workbox-precaching\n */\nclass PrecacheController {\n /**\n * Create a new PrecacheController.\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] The cache to use for precaching.\n * @param {string} [options.plugins] Plugins to use when precaching as well\n * as responding to fetch events for precached assets.\n * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to\n * get the response from the network if there's a precache miss.\n */\n constructor({ cacheName, plugins = [], fallbackToNetwork = true, } = {}) {\n this._urlsToCacheKeys = new Map();\n this._urlsToCacheModes = new Map();\n this._cacheKeysToIntegrities = new Map();\n this._strategy = new PrecacheStrategy({\n cacheName: cacheNames.getPrecacheName(cacheName),\n plugins: [\n ...plugins,\n new PrecacheCacheKeyPlugin({ precacheController: this }),\n ],\n fallbackToNetwork,\n });\n // Bind the install and activate methods to the instance.\n this.install = this.install.bind(this);\n this.activate = this.activate.bind(this);\n }\n /**\n * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and\n * used to cache assets and respond to fetch events.\n */\n get strategy() {\n return this._strategy;\n }\n /**\n * Adds items to the precache list, removing any duplicates and\n * stores the files in the\n * {@link workbox-core.cacheNames|\"precache cache\"} when the service\n * worker installs.\n *\n * This method can be called multiple times.\n *\n * @param {Array} [entries=[]] Array of entries to precache.\n */\n precache(entries) {\n this.addToCacheList(entries);\n if (!this._installAndActiveListenersAdded) {\n self.addEventListener('install', this.install);\n self.addEventListener('activate', this.activate);\n this._installAndActiveListenersAdded = true;\n }\n }\n /**\n * This method will add items to the precache list, removing duplicates\n * and ensuring the information is valid.\n *\n * @param {Array} entries\n * Array of entries to precache.\n */\n addToCacheList(entries) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(entries, {\n moduleName: 'workbox-precaching',\n className: 'PrecacheController',\n funcName: 'addToCacheList',\n paramName: 'entries',\n });\n }\n const urlsToWarnAbout = [];\n for (const entry of entries) {\n // See https://github.com/GoogleChrome/workbox/issues/2259\n if (typeof entry === 'string') {\n urlsToWarnAbout.push(entry);\n }\n else if (entry && entry.revision === undefined) {\n urlsToWarnAbout.push(entry.url);\n }\n const { cacheKey, url } = createCacheKey(entry);\n const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';\n if (this._urlsToCacheKeys.has(url) &&\n this._urlsToCacheKeys.get(url) !== cacheKey) {\n throw new WorkboxError('add-to-cache-list-conflicting-entries', {\n firstEntry: this._urlsToCacheKeys.get(url),\n secondEntry: cacheKey,\n });\n }\n if (typeof entry !== 'string' && entry.integrity) {\n if (this._cacheKeysToIntegrities.has(cacheKey) &&\n this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {\n throw new WorkboxError('add-to-cache-list-conflicting-integrities', {\n url,\n });\n }\n this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);\n }\n this._urlsToCacheKeys.set(url, cacheKey);\n this._urlsToCacheModes.set(url, cacheMode);\n if (urlsToWarnAbout.length > 0) {\n const warningMessage = `Workbox is precaching URLs without revision ` +\n `info: ${urlsToWarnAbout.join(', ')}\\nThis is generally NOT safe. ` +\n `Learn more at https://bit.ly/wb-precache`;\n if (process.env.NODE_ENV === 'production') {\n // Use console directly to display this warning without bloating\n // bundle sizes by pulling in all of the logger codebase in prod.\n console.warn(warningMessage);\n }\n else {\n logger.warn(warningMessage);\n }\n }\n }\n }\n /**\n * Precaches new and updated assets. Call this method from the service worker\n * install event.\n *\n * Note: this method calls `event.waitUntil()` for you, so you do not need\n * to call it yourself in your event handlers.\n *\n * @param {ExtendableEvent} event\n * @return {Promise}\n */\n install(event) {\n // waitUntil returns Promise\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return waitUntil(event, async () => {\n const installReportPlugin = new PrecacheInstallReportPlugin();\n this.strategy.plugins.push(installReportPlugin);\n // Cache entries one at a time.\n // See https://github.com/GoogleChrome/workbox/issues/2528\n for (const [url, cacheKey] of this._urlsToCacheKeys) {\n const integrity = this._cacheKeysToIntegrities.get(cacheKey);\n const cacheMode = this._urlsToCacheModes.get(url);\n const request = new Request(url, {\n integrity,\n cache: cacheMode,\n credentials: 'same-origin',\n });\n await Promise.all(this.strategy.handleAll({\n params: { cacheKey },\n request,\n event,\n }));\n }\n const { updatedURLs, notUpdatedURLs } = installReportPlugin;\n if (process.env.NODE_ENV !== 'production') {\n printInstallDetails(updatedURLs, notUpdatedURLs);\n }\n return { updatedURLs, notUpdatedURLs };\n });\n }\n /**\n * Deletes assets that are no longer present in the current precache manifest.\n * Call this method from the service worker activate event.\n *\n * Note: this method calls `event.waitUntil()` for you, so you do not need\n * to call it yourself in your event handlers.\n *\n * @param {ExtendableEvent} event\n * @return {Promise}\n */\n activate(event) {\n // waitUntil returns Promise\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return waitUntil(event, async () => {\n const cache = await self.caches.open(this.strategy.cacheName);\n const currentlyCachedRequests = await cache.keys();\n const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());\n const deletedURLs = [];\n for (const request of currentlyCachedRequests) {\n if (!expectedCacheKeys.has(request.url)) {\n await cache.delete(request);\n deletedURLs.push(request.url);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n printCleanupDetails(deletedURLs);\n }\n return { deletedURLs };\n });\n }\n /**\n * Returns a mapping of a precached URL to the corresponding cache key, taking\n * into account the revision information for the URL.\n *\n * @return {Map} A URL to cache key mapping.\n */\n getURLsToCacheKeys() {\n return this._urlsToCacheKeys;\n }\n /**\n * Returns a list of all the URLs that have been precached by the current\n * service worker.\n *\n * @return {Array} The precached URLs.\n */\n getCachedURLs() {\n return [...this._urlsToCacheKeys.keys()];\n }\n /**\n * Returns the cache key used for storing a given URL. If that URL is\n * unversioned, like `/index.html', then the cache key will be the original\n * URL with a search parameter appended to it.\n *\n * @param {string} url A URL whose cache key you want to look up.\n * @return {string} The versioned URL that corresponds to a cache key\n * for the original URL, or undefined if that URL isn't precached.\n */\n getCacheKeyForURL(url) {\n const urlObject = new URL(url, location.href);\n return this._urlsToCacheKeys.get(urlObject.href);\n }\n /**\n * @param {string} url A cache key whose SRI you want to look up.\n * @return {string} The subresource integrity associated with the cache key,\n * or undefined if it's not set.\n */\n getIntegrityForCacheKey(cacheKey) {\n return this._cacheKeysToIntegrities.get(cacheKey);\n }\n /**\n * This acts as a drop-in replacement for\n * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)\n * with the following differences:\n *\n * - It knows what the name of the precache is, and only checks in that cache.\n * - It allows you to pass in an \"original\" URL without versioning parameters,\n * and it will automatically look up the correct cache key for the currently\n * active revision of that URL.\n *\n * E.g., `matchPrecache('index.html')` will find the correct precached\n * response for the currently active service worker, even if the actual cache\n * key is `'/index.html?__WB_REVISION__=1234abcd'`.\n *\n * @param {string|Request} request The key (without revisioning parameters)\n * to look up in the precache.\n * @return {Promise}\n */\n async matchPrecache(request) {\n const url = request instanceof Request ? request.url : request;\n const cacheKey = this.getCacheKeyForURL(url);\n if (cacheKey) {\n const cache = await self.caches.open(this.strategy.cacheName);\n return cache.match(cacheKey);\n }\n return undefined;\n }\n /**\n * Returns a function that looks up `url` in the precache (taking into\n * account revision information), and returns the corresponding `Response`.\n *\n * @param {string} url The precached URL which will be used to lookup the\n * `Response`.\n * @return {workbox-routing~handlerCallback}\n */\n createHandlerBoundToURL(url) {\n const cacheKey = this.getCacheKeyForURL(url);\n if (!cacheKey) {\n throw new WorkboxError('non-precached-url', { url });\n }\n return (options) => {\n options.request = new Request(url);\n options.params = Object.assign({ cacheKey }, options.params);\n return this.strategy.handle(options);\n };\n }\n}\nexport { PrecacheController };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { PrecacheController } from '../PrecacheController.js';\nimport '../_version.js';\nlet precacheController;\n/**\n * @return {PrecacheController}\n * @private\n */\nexport const getOrCreatePrecacheController = () => {\n if (!precacheController) {\n precacheController = new PrecacheController();\n }\n return precacheController;\n};\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { Route } from 'workbox-routing/Route.js';\nimport { generateURLVariations } from './utils/generateURLVariations.js';\nimport './_version.js';\n/**\n * A subclass of {@link workbox-routing.Route} that takes a\n * {@link workbox-precaching.PrecacheController}\n * instance and uses it to match incoming requests and handle fetching\n * responses from the precache.\n *\n * @memberof workbox-precaching\n * @extends workbox-routing.Route\n */\nclass PrecacheRoute extends Route {\n /**\n * @param {PrecacheController} precacheController A `PrecacheController`\n * instance used to both match requests and respond to fetch events.\n * @param {Object} [options] Options to control how requests are matched\n * against the list of precached URLs.\n * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will\n * check cache entries for a URLs ending with '/' to see if there is a hit when\n * appending the `directoryIndex` value.\n * @param {Array} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An\n * array of regex's to remove search params when looking for a cache match.\n * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will\n * check the cache for the URL with a `.html` added to the end of the end.\n * @param {workbox-precaching~urlManipulation} [options.urlManipulation]\n * This is a function that should take a URL and return an array of\n * alternative URLs that should be checked for precache matches.\n */\n constructor(precacheController, options) {\n const match = ({ request, }) => {\n const urlsToCacheKeys = precacheController.getURLsToCacheKeys();\n for (const possibleURL of generateURLVariations(request.url, options)) {\n const cacheKey = urlsToCacheKeys.get(possibleURL);\n if (cacheKey) {\n const integrity = precacheController.getIntegrityForCacheKey(cacheKey);\n return { cacheKey, integrity };\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));\n }\n return;\n };\n super(match, precacheController.strategy);\n }\n}\nexport { PrecacheRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { removeIgnoredSearchParams } from './removeIgnoredSearchParams.js';\nimport '../_version.js';\n/**\n * Generator function that yields possible variations on the original URL to\n * check, one at a time.\n *\n * @param {string} url\n * @param {Object} options\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function* generateURLVariations(url, { ignoreURLParametersMatching = [/^utm_/, /^fbclid$/], directoryIndex = 'index.html', cleanURLs = true, urlManipulation, } = {}) {\n const urlObject = new URL(url, location.href);\n urlObject.hash = '';\n yield urlObject.href;\n const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);\n yield urlWithoutIgnoredParams.href;\n if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {\n const directoryURL = new URL(urlWithoutIgnoredParams.href);\n directoryURL.pathname += directoryIndex;\n yield directoryURL.href;\n }\n if (cleanURLs) {\n const cleanURL = new URL(urlWithoutIgnoredParams.href);\n cleanURL.pathname += '.html';\n yield cleanURL.href;\n }\n if (urlManipulation) {\n const additionalURLs = urlManipulation({ url: urlObject });\n for (const urlToAttempt of additionalURLs) {\n yield urlToAttempt.href;\n }\n }\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Removes any URL search parameters that should be ignored.\n *\n * @param {URL} urlObject The original URL.\n * @param {Array} ignoreURLParametersMatching RegExps to test against\n * each search parameter name. Matches mean that the search parameter should be\n * ignored.\n * @return {URL} The URL with any ignored search parameters removed.\n *\n * @private\n * @memberof workbox-precaching\n */\nexport function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {\n // Convert the iterable into an array at the start of the loop to make sure\n // deletion doesn't mess up iteration.\n for (const paramName of [...urlObject.searchParams.keys()]) {\n if (ignoreURLParametersMatching.some((regExp) => regExp.test(paramName))) {\n urlObject.searchParams.delete(paramName);\n }\n }\n return urlObject;\n}\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport { PrecacheRoute } from './PrecacheRoute.js';\nimport './_version.js';\n/**\n * Add a `fetch` listener to the service worker that will\n * respond to\n * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}\n * with precached assets.\n *\n * Requests for assets that aren't precached, the `FetchEvent` will not be\n * responded to, allowing the event to fall through to other `fetch` event\n * listeners.\n *\n * @param {Object} [options] See the {@link workbox-precaching.PrecacheRoute}\n * options.\n *\n * @memberof workbox-precaching\n */\nfunction addRoute(options) {\n const precacheController = getOrCreatePrecacheController();\n const precacheRoute = new PrecacheRoute(precacheController, options);\n registerRoute(precacheRoute);\n}\nexport { addRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Adds items to the precache list, removing any duplicates and\n * stores the files in the\n * {@link workbox-core.cacheNames|\"precache cache\"} when the service\n * worker installs.\n *\n * This method can be called multiple times.\n *\n * Please note: This method **will not** serve any of the cached files for you.\n * It only precaches files. To respond to a network request you call\n * {@link workbox-precaching.addRoute}.\n *\n * If you have a single array of files to precache, you can just call\n * {@link workbox-precaching.precacheAndRoute}.\n *\n * @param {Array} [entries=[]] Array of entries to precache.\n *\n * @memberof workbox-precaching\n */\nfunction precache(entries) {\n const precacheController = getOrCreatePrecacheController();\n precacheController.precache(entries);\n}\nexport { precache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * `PrecacheFallbackPlugin` allows you to specify an \"offline fallback\"\n * response to be used when a given strategy is unable to generate a response.\n *\n * It does this by intercepting the `handlerDidError` plugin callback\n * and returning a precached response, taking the expected revision parameter\n * into account automatically.\n *\n * Unless you explicitly pass in a `PrecacheController` instance to the\n * constructor, the default instance will be used. Generally speaking, most\n * developers will end up using the default.\n *\n * @memberof workbox-precaching\n */\nclass PrecacheFallbackPlugin {\n /**\n * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL.\n *\n * @param {Object} config\n * @param {string} config.fallbackURL A precached URL to use as the fallback\n * if the associated strategy can't generate a response.\n * @param {PrecacheController} [config.precacheController] An optional\n * PrecacheController instance. If not provided, the default\n * PrecacheController will be used.\n */\n constructor({ fallbackURL, precacheController, }) {\n /**\n * @return {Promise} The precache response for the fallback URL.\n *\n * @private\n */\n this.handlerDidError = () => this._precacheController.matchPrecache(this._fallbackURL);\n this._fallbackURL = fallbackURL;\n this._precacheController =\n precacheController || getOrCreatePrecacheController();\n }\n}\nexport { PrecacheFallbackPlugin };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Adds plugins to the precaching strategy.\n *\n * @param {Array} plugins\n *\n * @memberof workbox-precaching\n */\nfunction addPlugins(plugins) {\n const precacheController = getOrCreatePrecacheController();\n precacheController.strategy.plugins.push(...plugins);\n}\nexport { addPlugins };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { deleteOutdatedCaches } from './utils/deleteOutdatedCaches.js';\nimport './_version.js';\n/**\n * Adds an `activate` event listener which will clean up incompatible\n * precaches that were created by older versions of Workbox.\n *\n * @memberof workbox-precaching\n */\nfunction cleanupOutdatedCaches() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('activate', ((event) => {\n const cacheName = cacheNames.getPrecacheName();\n event.waitUntil(deleteOutdatedCaches(cacheName).then((cachesDeleted) => {\n if (process.env.NODE_ENV !== 'production') {\n if (cachesDeleted.length > 0) {\n logger.log(`The following out-of-date precaches were cleaned up ` +\n `automatically:`, cachesDeleted);\n }\n }\n }));\n }));\n}\nexport { cleanupOutdatedCaches };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst SUBSTRING_TO_FIND = '-precache-';\n/**\n * Cleans up incompatible precaches that were created by older versions of\n * Workbox, by a service worker registered under the current scope.\n *\n * This is meant to be called as part of the `activate` event.\n *\n * This should be safe to use as long as you don't include `substringToFind`\n * (defaulting to `-precache-`) in your non-precache cache names.\n *\n * @param {string} currentPrecacheName The cache name currently in use for\n * precaching. This cache won't be deleted.\n * @param {string} [substringToFind='-precache-'] Cache names which include this\n * substring will be deleted (excluding `currentPrecacheName`).\n * @return {Array} A list of all the cache names that were deleted.\n *\n * @private\n * @memberof workbox-precaching\n */\nconst deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {\n const cacheNames = await self.caches.keys();\n const cacheNamesToDelete = cacheNames.filter((cacheName) => {\n return (cacheName.includes(substringToFind) &&\n cacheName.includes(self.registration.scope) &&\n cacheName !== currentPrecacheName);\n });\n await Promise.all(cacheNamesToDelete.map((cacheName) => self.caches.delete(cacheName)));\n return cacheNamesToDelete;\n};\nexport { deleteOutdatedCaches };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Helper function that calls\n * {@link PrecacheController#createHandlerBoundToURL} on the default\n * {@link PrecacheController} instance.\n *\n * If you are creating your own {@link PrecacheController}, then call the\n * {@link PrecacheController#createHandlerBoundToURL} on that instance,\n * instead of using this function.\n *\n * @param {string} url The precached URL which will be used to lookup the\n * `Response`.\n * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the\n * response from the network if there's a precache miss.\n * @return {workbox-routing~handlerCallback}\n *\n * @memberof workbox-precaching\n */\nfunction createHandlerBoundToURL(url) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.createHandlerBoundToURL(url);\n}\nexport { createHandlerBoundToURL };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Takes in a URL, and returns the corresponding URL that could be used to\n * lookup the entry in the precache.\n *\n * If a relative URL is provided, the location of the service worker file will\n * be used as the base.\n *\n * For precached entries without revision information, the cache key will be the\n * same as the original URL.\n *\n * For precached entries with revision information, the cache key will be the\n * original URL with the addition of a query parameter used for keeping track of\n * the revision info.\n *\n * @param {string} url The URL whose cache key to look up.\n * @return {string} The cache key that corresponds to that URL.\n *\n * @memberof workbox-precaching\n */\nfunction getCacheKeyForURL(url) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.getCacheKeyForURL(url);\n}\nexport { getCacheKeyForURL };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';\nimport './_version.js';\n/**\n * Helper function that calls\n * {@link PrecacheController#matchPrecache} on the default\n * {@link PrecacheController} instance.\n *\n * If you are creating your own {@link PrecacheController}, then call\n * {@link PrecacheController#matchPrecache} on that instance,\n * instead of using this function.\n *\n * @param {string|Request} request The key (without revisioning parameters)\n * to look up in the precache.\n * @return {Promise}\n *\n * @memberof workbox-precaching\n */\nfunction matchPrecache(request) {\n const precacheController = getOrCreatePrecacheController();\n return precacheController.matchPrecache(request);\n}\nexport { matchPrecache };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { addRoute } from './addRoute.js';\nimport { precache } from './precache.js';\nimport './_version.js';\n/**\n * This method will add entries to the precache list and add a route to\n * respond to fetch events.\n *\n * This is a convenience method that will call\n * {@link workbox-precaching.precache} and\n * {@link workbox-precaching.addRoute} in a single call.\n *\n * @param {Array} entries Array of entries to precache.\n * @param {Object} [options] See the\n * {@link workbox-precaching.PrecacheRoute} options.\n *\n * @memberof workbox-precaching\n */\nfunction precacheAndRoute(entries, options) {\n precache(entries);\n addRoute(options);\n}\nexport { precacheAndRoute };\n"],"names":["self","_","e","createCacheKey","entry","WorkboxError","urlObject","URL","location","href","cacheKey","url","revision","cacheKeyURL","originalURL","searchParams","set","PrecacheInstallReportPlugin","constructor","updatedURLs","notUpdatedURLs","handlerWillStart","async","request","state","originalRequest","cachedResponseWillBeUsed","event","cachedResponse","type","Request","push","PrecacheCacheKeyPlugin","precacheController","cacheKeyWillBeUsed","params","this","_precacheController","getCacheKeyForURL","headers","PrecacheStrategy","Strategy","options","cacheName","cacheNames","getPrecacheName","_fallbackToNetwork","fallbackToNetwork","plugins","copyRedirectedCacheableResponsesPlugin","handler","response","cacheMatch","_handleInstall","_handleFetch","integrityInManifest","integrity","integrityInRequest","noIntegrityConflict","fetch","mode","undefined","_useDefaultCacheabilityPluginIfNeeded","cachePut","clone","status","defaultPluginIndex","cacheWillUpdatePluginCount","index","plugin","entries","defaultPrecacheCacheabilityPlugin","cacheWillUpdate","splice","redirected","copyResponse","PrecacheController","_urlsToCacheKeys","Map","_urlsToCacheModes","_cacheKeysToIntegrities","_strategy","install","bind","activate","strategy","precache","addToCacheList","_installAndActiveListenersAdded","addEventListener","urlsToWarnAbout","cacheMode","has","get","firstEntry","secondEntry","length","warningMessage","join","console","warn","waitUntil","installReportPlugin","cache","credentials","Promise","all","handleAll","caches","open","currentlyCachedRequests","keys","expectedCacheKeys","Set","values","deletedURLs","delete","getURLsToCacheKeys","getCachedURLs","getIntegrityForCacheKey","match","createHandlerBoundToURL","Object","assign","handle","getOrCreatePrecacheController","PrecacheRoute","Route","urlsToCacheKeys","possibleURL","ignoreURLParametersMatching","directoryIndex","cleanURLs","urlManipulation","hash","urlWithoutIgnoredParams","paramName","some","regExp","test","removeIgnoredSearchParams","pathname","endsWith","directoryURL","cleanURL","additionalURLs","urlToAttempt","generateURLVariations","addRoute","precacheRoute","registerRoute","fallbackURL","handlerDidError","matchPrecache","_fallbackURL","currentPrecacheName","substringToFind","cacheNamesToDelete","filter","includes","registration","scope","map","deleteOutdatedCaches","then","cachesDeleted"],"mappings":"6FAEA,IACIA,KAAK,6BAA+BC,GACvC,CACD,MAAOC,ICeA,SAASC,EAAeC,OACtBA,QACK,IAAIC,eAAa,oCAAqC,CAAED,aAI7C,iBAAVA,EAAoB,OACrBE,EAAY,IAAIC,IAAIH,EAAOI,SAASC,YACnC,CACHC,SAAUJ,EAAUG,KACpBE,IAAKL,EAAUG,YAGjBG,SAAEA,EAAFD,IAAYA,GAAQP,MACrBO,QACK,IAAIN,eAAa,oCAAqC,CAAED,cAI7DQ,EAAU,OACLN,EAAY,IAAIC,IAAII,EAAKH,SAASC,YACjC,CACHC,SAAUJ,EAAUG,KACpBE,IAAKL,EAAUG,YAKjBI,EAAc,IAAIN,IAAII,EAAKH,SAASC,MACpCK,EAAc,IAAIP,IAAII,EAAKH,SAASC,aAC1CI,EAAYE,aAAaC,IAxCC,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W6E,IACRxC,SAASrC,QAAQjB,QAAQiB,EAC/C,uCCFD,WAEIhD,KAAKyF,iBAAiB,YAAc9D,UAC1BgB,EAAYC,aAAWC,kBAC7BlB,EAAM0E,UCMe/E,OAAOqI,EAAqBC,EAnB/B,sBAqBhBC,SADmB7J,KAAK4G,OAAOG,QACC+C,QAAQnH,GAClCA,EAAUoH,SAASH,IACvBjH,EAAUoH,SAAS/J,KAAKgK,aAAaC,QACrCtH,IAAcgH,iBAEhBlD,QAAQC,IAAImD,EAAmBK,KAAKvH,GAAc3C,KAAK4G,OAAOQ,OAAOzE,MACpEkH,CAAP,EDdoBM,CAAqBxH,GAAWyH,MAAMC,WAS7D,4BEJD,SAAiC1J,UACFkH,IACDJ,wBAAwB9G,EACrD,sBCDD,SAA2BA,UACIkH,IACDvF,kBAAkB3B,EAC/C,kBCPD,SAAuBY,UACQsG,IACD4B,cAAclI,EAC3C,kCCHD,SAA0B+C,EAAS5B,GAC/B4C,EAAShB,GACT8E,EAAS1G,EACZ"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-range-requests.dev.js b/src/Resources/workbox-v7.0.0/workbox-range-requests.dev.js new file mode 100644 index 0000000..d6db34c --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-range-requests.dev.js @@ -0,0 +1,262 @@ +this.workbox = this.workbox || {}; +this.workbox.rangeRequests = (function (exports, WorkboxError_js, assert_js, logger_js) { + 'use strict'; + + try { + self['workbox:range-requests:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {Blob} blob A source blob. + * @param {number} [start] The offset to use as the start of the + * slice. + * @param {number} [end] The offset to use as the end of the slice. + * @return {Object} An object with `start` and `end` properties, reflecting + * the effective boundaries to use given the size of the blob. + * + * @private + */ + + function calculateEffectiveBoundaries(blob, start, end) { + { + assert_js.assert.isInstance(blob, Blob, { + moduleName: 'workbox-range-requests', + funcName: 'calculateEffectiveBoundaries', + paramName: 'blob' + }); + } + + const blobSize = blob.size; + + if (end && end > blobSize || start && start < 0) { + throw new WorkboxError_js.WorkboxError('range-not-satisfiable', { + size: blobSize, + end, + start + }); + } + + let effectiveStart; + let effectiveEnd; + + if (start !== undefined && end !== undefined) { + effectiveStart = start; // Range values are inclusive, so add 1 to the value. + + effectiveEnd = end + 1; + } else if (start !== undefined && end === undefined) { + effectiveStart = start; + effectiveEnd = blobSize; + } else if (end !== undefined && start === undefined) { + effectiveStart = blobSize - end; + effectiveEnd = blobSize; + } + + return { + start: effectiveStart, + end: effectiveEnd + }; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {string} rangeHeader A Range: header value. + * @return {Object} An object with `start` and `end` properties, reflecting + * the parsed value of the Range: header. If either the `start` or `end` are + * omitted, then `null` will be returned. + * + * @private + */ + + function parseRangeHeader(rangeHeader) { + { + assert_js.assert.isType(rangeHeader, 'string', { + moduleName: 'workbox-range-requests', + funcName: 'parseRangeHeader', + paramName: 'rangeHeader' + }); + } + + const normalizedRangeHeader = rangeHeader.trim().toLowerCase(); + + if (!normalizedRangeHeader.startsWith('bytes=')) { + throw new WorkboxError_js.WorkboxError('unit-must-be-bytes', { + normalizedRangeHeader + }); + } // Specifying multiple ranges separate by commas is valid syntax, but this + // library only attempts to handle a single, contiguous sequence of bytes. + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax + + + if (normalizedRangeHeader.includes(',')) { + throw new WorkboxError_js.WorkboxError('single-range-only', { + normalizedRangeHeader + }); + } + + const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader); // We need either at least one of the start or end values. + + if (!rangeParts || !(rangeParts[1] || rangeParts[2])) { + throw new WorkboxError_js.WorkboxError('invalid-range-values', { + normalizedRangeHeader + }); + } + + return { + start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]), + end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]) + }; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Given a `Request` and `Response` objects as input, this will return a + * promise for a new `Response`. + * + * If the original `Response` already contains partial content (i.e. it has + * a status of 206), then this assumes it already fulfills the `Range:` + * requirements, and will return it as-is. + * + * @param {Request} request A request, which should contain a Range: + * header. + * @param {Response} originalResponse A response. + * @return {Promise} Either a `206 Partial Content` response, with + * the response body set to the slice of content specified by the request's + * `Range:` header, or a `416 Range Not Satisfiable` response if the + * conditions of the `Range:` header can't be met. + * + * @memberof workbox-range-requests + */ + + async function createPartialResponse(request, originalResponse) { + try { + if ("dev" !== 'production') { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-range-requests', + funcName: 'createPartialResponse', + paramName: 'request' + }); + assert_js.assert.isInstance(originalResponse, Response, { + moduleName: 'workbox-range-requests', + funcName: 'createPartialResponse', + paramName: 'originalResponse' + }); + } + + if (originalResponse.status === 206) { + // If we already have a 206, then just pass it through as-is; + // see https://github.com/GoogleChrome/workbox/issues/1720 + return originalResponse; + } + + const rangeHeader = request.headers.get('range'); + + if (!rangeHeader) { + throw new WorkboxError_js.WorkboxError('no-range-header'); + } + + const boundaries = parseRangeHeader(rangeHeader); + const originalBlob = await originalResponse.blob(); + const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end); + const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end); + const slicedBlobSize = slicedBlob.size; + const slicedResponse = new Response(slicedBlob, { + // Status code 206 is for a Partial Content response. + // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206 + status: 206, + statusText: 'Partial Content', + headers: originalResponse.headers + }); + slicedResponse.headers.set('Content-Length', String(slicedBlobSize)); + slicedResponse.headers.set('Content-Range', `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + `${originalBlob.size}`); + return slicedResponse; + } catch (error) { + { + logger_js.logger.warn(`Unable to construct a partial response; returning a ` + `416 Range Not Satisfiable response instead.`); + logger_js.logger.groupCollapsed(`View details here.`); + logger_js.logger.log(error); + logger_js.logger.log(request); + logger_js.logger.log(originalResponse); + logger_js.logger.groupEnd(); + } + + return new Response('', { + status: 416, + statusText: 'Range Not Satisfiable' + }); + } + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The range request plugin makes it easy for a request with a 'Range' header to + * be fulfilled by a cached response. + * + * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback + * and returning the appropriate subset of the cached response body. + * + * @memberof workbox-range-requests + */ + + class RangeRequestsPlugin { + constructor() { + /** + * @param {Object} options + * @param {Request} options.request The original request, which may or may not + * contain a Range: header. + * @param {Response} options.cachedResponse The complete cached response. + * @return {Promise} If request contains a 'Range' header, then a + * new response with status 206 whose body is a subset of `cachedResponse` is + * returned. Otherwise, `cachedResponse` is returned as-is. + * + * @private + */ + this.cachedResponseWillBeUsed = async ({ + request, + cachedResponse + }) => { + // Only return a sliced response if there's something valid in the cache, + // and there's a Range: header in the request. + if (cachedResponse && request.headers.has('range')) { + return await createPartialResponse(request, cachedResponse); + } // If there was no Range: header, or if cachedResponse wasn't valid, just + // pass it through as-is. + + + return cachedResponse; + }; + } + + } + + exports.RangeRequestsPlugin = RangeRequestsPlugin; + exports.createPartialResponse = createPartialResponse; + + return exports; + +}({}, workbox.core._private, workbox.core._private, workbox.core._private)); +//# sourceMappingURL=workbox-range-requests.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-range-requests.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-range-requests.dev.js.map new file mode 100644 index 0000000..e83a47a --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-range-requests.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-range-requests.dev.js","sources":["../_version.js","../utils/calculateEffectiveBoundaries.js","../utils/parseRangeHeader.js","../createPartialResponse.js","../RangeRequestsPlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:range-requests:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {Blob} blob A source blob.\n * @param {number} [start] The offset to use as the start of the\n * slice.\n * @param {number} [end] The offset to use as the end of the slice.\n * @return {Object} An object with `start` and `end` properties, reflecting\n * the effective boundaries to use given the size of the blob.\n *\n * @private\n */\nfunction calculateEffectiveBoundaries(blob, start, end) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(blob, Blob, {\n moduleName: 'workbox-range-requests',\n funcName: 'calculateEffectiveBoundaries',\n paramName: 'blob',\n });\n }\n const blobSize = blob.size;\n if ((end && end > blobSize) || (start && start < 0)) {\n throw new WorkboxError('range-not-satisfiable', {\n size: blobSize,\n end,\n start,\n });\n }\n let effectiveStart;\n let effectiveEnd;\n if (start !== undefined && end !== undefined) {\n effectiveStart = start;\n // Range values are inclusive, so add 1 to the value.\n effectiveEnd = end + 1;\n }\n else if (start !== undefined && end === undefined) {\n effectiveStart = start;\n effectiveEnd = blobSize;\n }\n else if (end !== undefined && start === undefined) {\n effectiveStart = blobSize - end;\n effectiveEnd = blobSize;\n }\n return {\n start: effectiveStart,\n end: effectiveEnd,\n };\n}\nexport { calculateEffectiveBoundaries };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {string} rangeHeader A Range: header value.\n * @return {Object} An object with `start` and `end` properties, reflecting\n * the parsed value of the Range: header. If either the `start` or `end` are\n * omitted, then `null` will be returned.\n *\n * @private\n */\nfunction parseRangeHeader(rangeHeader) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(rangeHeader, 'string', {\n moduleName: 'workbox-range-requests',\n funcName: 'parseRangeHeader',\n paramName: 'rangeHeader',\n });\n }\n const normalizedRangeHeader = rangeHeader.trim().toLowerCase();\n if (!normalizedRangeHeader.startsWith('bytes=')) {\n throw new WorkboxError('unit-must-be-bytes', { normalizedRangeHeader });\n }\n // Specifying multiple ranges separate by commas is valid syntax, but this\n // library only attempts to handle a single, contiguous sequence of bytes.\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax\n if (normalizedRangeHeader.includes(',')) {\n throw new WorkboxError('single-range-only', { normalizedRangeHeader });\n }\n const rangeParts = /(\\d*)-(\\d*)/.exec(normalizedRangeHeader);\n // We need either at least one of the start or end values.\n if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {\n throw new WorkboxError('invalid-range-values', { normalizedRangeHeader });\n }\n return {\n start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]),\n end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]),\n };\n}\nexport { parseRangeHeader };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { calculateEffectiveBoundaries } from './utils/calculateEffectiveBoundaries.js';\nimport { parseRangeHeader } from './utils/parseRangeHeader.js';\nimport './_version.js';\n/**\n * Given a `Request` and `Response` objects as input, this will return a\n * promise for a new `Response`.\n *\n * If the original `Response` already contains partial content (i.e. it has\n * a status of 206), then this assumes it already fulfills the `Range:`\n * requirements, and will return it as-is.\n *\n * @param {Request} request A request, which should contain a Range:\n * header.\n * @param {Response} originalResponse A response.\n * @return {Promise} Either a `206 Partial Content` response, with\n * the response body set to the slice of content specified by the request's\n * `Range:` header, or a `416 Range Not Satisfiable` response if the\n * conditions of the `Range:` header can't be met.\n *\n * @memberof workbox-range-requests\n */\nasync function createPartialResponse(request, originalResponse) {\n try {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-range-requests',\n funcName: 'createPartialResponse',\n paramName: 'request',\n });\n assert.isInstance(originalResponse, Response, {\n moduleName: 'workbox-range-requests',\n funcName: 'createPartialResponse',\n paramName: 'originalResponse',\n });\n }\n if (originalResponse.status === 206) {\n // If we already have a 206, then just pass it through as-is;\n // see https://github.com/GoogleChrome/workbox/issues/1720\n return originalResponse;\n }\n const rangeHeader = request.headers.get('range');\n if (!rangeHeader) {\n throw new WorkboxError('no-range-header');\n }\n const boundaries = parseRangeHeader(rangeHeader);\n const originalBlob = await originalResponse.blob();\n const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end);\n const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end);\n const slicedBlobSize = slicedBlob.size;\n const slicedResponse = new Response(slicedBlob, {\n // Status code 206 is for a Partial Content response.\n // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206\n status: 206,\n statusText: 'Partial Content',\n headers: originalResponse.headers,\n });\n slicedResponse.headers.set('Content-Length', String(slicedBlobSize));\n slicedResponse.headers.set('Content-Range', `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` +\n `${originalBlob.size}`);\n return slicedResponse;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to construct a partial response; returning a ` +\n `416 Range Not Satisfiable response instead.`);\n logger.groupCollapsed(`View details here.`);\n logger.log(error);\n logger.log(request);\n logger.log(originalResponse);\n logger.groupEnd();\n }\n return new Response('', {\n status: 416,\n statusText: 'Range Not Satisfiable',\n });\n }\n}\nexport { createPartialResponse };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { createPartialResponse } from './createPartialResponse.js';\nimport './_version.js';\n/**\n * The range request plugin makes it easy for a request with a 'Range' header to\n * be fulfilled by a cached response.\n *\n * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback\n * and returning the appropriate subset of the cached response body.\n *\n * @memberof workbox-range-requests\n */\nclass RangeRequestsPlugin {\n constructor() {\n /**\n * @param {Object} options\n * @param {Request} options.request The original request, which may or may not\n * contain a Range: header.\n * @param {Response} options.cachedResponse The complete cached response.\n * @return {Promise} If request contains a 'Range' header, then a\n * new response with status 206 whose body is a subset of `cachedResponse` is\n * returned. Otherwise, `cachedResponse` is returned as-is.\n *\n * @private\n */\n this.cachedResponseWillBeUsed = async ({ request, cachedResponse, }) => {\n // Only return a sliced response if there's something valid in the cache,\n // and there's a Range: header in the request.\n if (cachedResponse && request.headers.has('range')) {\n return await createPartialResponse(request, cachedResponse);\n }\n // If there was no Range: header, or if cachedResponse wasn't valid, just\n // pass it through as-is.\n return cachedResponse;\n };\n }\n}\nexport { RangeRequestsPlugin };\n"],"names":["self","_","e","calculateEffectiveBoundaries","blob","start","end","assert","isInstance","Blob","moduleName","funcName","paramName","blobSize","size","WorkboxError","effectiveStart","effectiveEnd","undefined","parseRangeHeader","rangeHeader","isType","normalizedRangeHeader","trim","toLowerCase","startsWith","includes","rangeParts","exec","Number","createPartialResponse","request","originalResponse","process","Request","Response","status","headers","get","boundaries","originalBlob","effectiveBoundaries","slicedBlob","slice","slicedBlobSize","slicedResponse","statusText","set","String","error","logger","warn","groupCollapsed","log","groupEnd","RangeRequestsPlugin","constructor","cachedResponseWillBeUsed","cachedResponse","has"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,8BAAD,CAAJ,IAAwCC,CAAC,EAAzC;IACH,CAFD,CAGA,OAAOC,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S,mBAAN,CAA0B;IACtBC,EAAAA,WAAW,GAAG;IACV;IACR;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACQ,SAAKC,wBAAL,GAAgC,OAAO;IAAE1B,MAAAA,OAAF;IAAW2B,MAAAA;IAAX,KAAP,KAAwC;IACpE;IACA;IACA,UAAIA,cAAc,IAAI3B,OAAO,CAACM,OAAR,CAAgBsB,GAAhB,CAAoB,OAApB,CAAtB,EAAoD;IAChD,eAAO,MAAM7B,qBAAqB,CAACC,OAAD,EAAU2B,cAAV,CAAlC;IACH,OALmE;IAOpE;;;IACA,aAAOA,cAAP;IACH,KATD;IAUH;;IAvBqB;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-range-requests.prod.js b/src/Resources/workbox-v7.0.0/workbox-range-requests.prod.js new file mode 100644 index 0000000..05f6b80 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-range-requests.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.rangeRequests=function(t,e,n){"use strict";try{self["workbox:range-requests:7.0.0"]&&_()}catch(t){}async function r(t,n){try{if(206===n.status)return n;const r=t.headers.get("range");if(!r)throw new e.WorkboxError("no-range-header");const s=function(t){const n=t.trim().toLowerCase();if(!n.startsWith("bytes="))throw new e.WorkboxError("unit-must-be-bytes",{normalizedRangeHeader:n});if(n.includes(","))throw new e.WorkboxError("single-range-only",{normalizedRangeHeader:n});const r=/(\d*)-(\d*)/.exec(n);if(!r||!r[1]&&!r[2])throw new e.WorkboxError("invalid-range-values",{normalizedRangeHeader:n});return{start:""===r[1]?void 0:Number(r[1]),end:""===r[2]?void 0:Number(r[2])}}(r),a=await n.blob(),o=function(t,n,r){const s=t.size;if(r&&r>s||n&&n<0)throw new e.WorkboxError("range-not-satisfiable",{size:s,end:r,start:n});let a,o;return void 0!==n&&void 0!==r?(a=n,o=r+1):void 0!==n&&void 0===r?(a=n,o=s):void 0!==r&&void 0===n&&(a=s-r,o=s),{start:a,end:o}}(a,s.start,s.end),i=a.slice(o.start,o.end),d=i.size,u=new Response(i,{status:206,statusText:"Partial Content",headers:n.headers});return u.headers.set("Content-Length",String(d)),u.headers.set("Content-Range",`bytes ${o.start}-${o.end-1}/${a.size}`),u}catch(t){return new Response("",{status:416,statusText:"Range Not Satisfiable"})}}return t.RangeRequestsPlugin=class{constructor(){this.cachedResponseWillBeUsed=async({request:t,cachedResponse:e})=>e&&t.headers.has("range")?await r(t,e):e}},t.createPartialResponse=r,t}({},workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-range-requests.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-range-requests.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-range-requests.prod.js.map new file mode 100644 index 0000000..d6d233d --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-range-requests.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-range-requests.prod.js","sources":["../_version.js","../createPartialResponse.js","../utils/parseRangeHeader.js","../utils/calculateEffectiveBoundaries.js","../RangeRequestsPlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:range-requests:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { calculateEffectiveBoundaries } from './utils/calculateEffectiveBoundaries.js';\nimport { parseRangeHeader } from './utils/parseRangeHeader.js';\nimport './_version.js';\n/**\n * Given a `Request` and `Response` objects as input, this will return a\n * promise for a new `Response`.\n *\n * If the original `Response` already contains partial content (i.e. it has\n * a status of 206), then this assumes it already fulfills the `Range:`\n * requirements, and will return it as-is.\n *\n * @param {Request} request A request, which should contain a Range:\n * header.\n * @param {Response} originalResponse A response.\n * @return {Promise} Either a `206 Partial Content` response, with\n * the response body set to the slice of content specified by the request's\n * `Range:` header, or a `416 Range Not Satisfiable` response if the\n * conditions of the `Range:` header can't be met.\n *\n * @memberof workbox-range-requests\n */\nasync function createPartialResponse(request, originalResponse) {\n try {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-range-requests',\n funcName: 'createPartialResponse',\n paramName: 'request',\n });\n assert.isInstance(originalResponse, Response, {\n moduleName: 'workbox-range-requests',\n funcName: 'createPartialResponse',\n paramName: 'originalResponse',\n });\n }\n if (originalResponse.status === 206) {\n // If we already have a 206, then just pass it through as-is;\n // see https://github.com/GoogleChrome/workbox/issues/1720\n return originalResponse;\n }\n const rangeHeader = request.headers.get('range');\n if (!rangeHeader) {\n throw new WorkboxError('no-range-header');\n }\n const boundaries = parseRangeHeader(rangeHeader);\n const originalBlob = await originalResponse.blob();\n const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end);\n const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end);\n const slicedBlobSize = slicedBlob.size;\n const slicedResponse = new Response(slicedBlob, {\n // Status code 206 is for a Partial Content response.\n // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206\n status: 206,\n statusText: 'Partial Content',\n headers: originalResponse.headers,\n });\n slicedResponse.headers.set('Content-Length', String(slicedBlobSize));\n slicedResponse.headers.set('Content-Range', `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` +\n `${originalBlob.size}`);\n return slicedResponse;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to construct a partial response; returning a ` +\n `416 Range Not Satisfiable response instead.`);\n logger.groupCollapsed(`View details here.`);\n logger.log(error);\n logger.log(request);\n logger.log(originalResponse);\n logger.groupEnd();\n }\n return new Response('', {\n status: 416,\n statusText: 'Range Not Satisfiable',\n });\n }\n}\nexport { createPartialResponse };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {string} rangeHeader A Range: header value.\n * @return {Object} An object with `start` and `end` properties, reflecting\n * the parsed value of the Range: header. If either the `start` or `end` are\n * omitted, then `null` will be returned.\n *\n * @private\n */\nfunction parseRangeHeader(rangeHeader) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(rangeHeader, 'string', {\n moduleName: 'workbox-range-requests',\n funcName: 'parseRangeHeader',\n paramName: 'rangeHeader',\n });\n }\n const normalizedRangeHeader = rangeHeader.trim().toLowerCase();\n if (!normalizedRangeHeader.startsWith('bytes=')) {\n throw new WorkboxError('unit-must-be-bytes', { normalizedRangeHeader });\n }\n // Specifying multiple ranges separate by commas is valid syntax, but this\n // library only attempts to handle a single, contiguous sequence of bytes.\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax\n if (normalizedRangeHeader.includes(',')) {\n throw new WorkboxError('single-range-only', { normalizedRangeHeader });\n }\n const rangeParts = /(\\d*)-(\\d*)/.exec(normalizedRangeHeader);\n // We need either at least one of the start or end values.\n if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {\n throw new WorkboxError('invalid-range-values', { normalizedRangeHeader });\n }\n return {\n start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]),\n end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]),\n };\n}\nexport { parseRangeHeader };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {Blob} blob A source blob.\n * @param {number} [start] The offset to use as the start of the\n * slice.\n * @param {number} [end] The offset to use as the end of the slice.\n * @return {Object} An object with `start` and `end` properties, reflecting\n * the effective boundaries to use given the size of the blob.\n *\n * @private\n */\nfunction calculateEffectiveBoundaries(blob, start, end) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(blob, Blob, {\n moduleName: 'workbox-range-requests',\n funcName: 'calculateEffectiveBoundaries',\n paramName: 'blob',\n });\n }\n const blobSize = blob.size;\n if ((end && end > blobSize) || (start && start < 0)) {\n throw new WorkboxError('range-not-satisfiable', {\n size: blobSize,\n end,\n start,\n });\n }\n let effectiveStart;\n let effectiveEnd;\n if (start !== undefined && end !== undefined) {\n effectiveStart = start;\n // Range values are inclusive, so add 1 to the value.\n effectiveEnd = end + 1;\n }\n else if (start !== undefined && end === undefined) {\n effectiveStart = start;\n effectiveEnd = blobSize;\n }\n else if (end !== undefined && start === undefined) {\n effectiveStart = blobSize - end;\n effectiveEnd = blobSize;\n }\n return {\n start: effectiveStart,\n end: effectiveEnd,\n };\n}\nexport { calculateEffectiveBoundaries };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { createPartialResponse } from './createPartialResponse.js';\nimport './_version.js';\n/**\n * The range request plugin makes it easy for a request with a 'Range' header to\n * be fulfilled by a cached response.\n *\n * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback\n * and returning the appropriate subset of the cached response body.\n *\n * @memberof workbox-range-requests\n */\nclass RangeRequestsPlugin {\n constructor() {\n /**\n * @param {Object} options\n * @param {Request} options.request The original request, which may or may not\n * contain a Range: header.\n * @param {Response} options.cachedResponse The complete cached response.\n * @return {Promise} If request contains a 'Range' header, then a\n * new response with status 206 whose body is a subset of `cachedResponse` is\n * returned. Otherwise, `cachedResponse` is returned as-is.\n *\n * @private\n */\n this.cachedResponseWillBeUsed = async ({ request, cachedResponse, }) => {\n // Only return a sliced response if there's something valid in the cache,\n // and there's a Range: header in the request.\n if (cachedResponse && request.headers.has('range')) {\n return await createPartialResponse(request, cachedResponse);\n }\n // If there was no Range: header, or if cachedResponse wasn't valid, just\n // pass it through as-is.\n return cachedResponse;\n };\n }\n}\nexport { RangeRequestsPlugin };\n"],"names":["self","_","e","async","createPartialResponse","request","originalResponse","status","rangeHeader","headers","get","WorkboxError","boundaries","normalizedRangeHeader","trim","toLowerCase","startsWith","includes","rangeParts","exec","start","undefined","Number","end","parseRangeHeader","originalBlob","blob","effectiveBoundaries","blobSize","size","effectiveStart","effectiveEnd","calculateEffectiveBoundaries","slicedBlob","slice","slicedBlobSize","slicedResponse","Response","statusText","set","String","error","constructor","cachedResponseWillBeUsed","cachedResponse","has"],"mappings":"sFAEA,IACIA,KAAK,iCAAmCC,GAC3C,CACD,MAAOC,IC0BPC,eAAeC,EAAsBC,EAASC,UAcN,MAA5BA,EAAiBC,cAGVD,QAELE,EAAcH,EAAQI,QAAQC,IAAI,aACnCF,QACK,IAAIG,eAAa,yBAErBC,ECpCd,SAA0BJ,SAQhBK,EAAwBL,EAAYM,OAAOC,kBAC5CF,EAAsBG,WAAW,gBAC5B,IAAIL,eAAa,qBAAsB,CAAEE,6BAK/CA,EAAsBI,SAAS,WACzB,IAAIN,eAAa,oBAAqB,CAAEE,gCAE5CK,EAAa,cAAcC,KAAKN,OAEjCK,IAAgBA,EAAW,KAAMA,EAAW,SACvC,IAAIP,eAAa,uBAAwB,CAAEE,gCAE9C,CACHO,MAAyB,KAAlBF,EAAW,QAAYG,EAAYC,OAAOJ,EAAW,IAC5DK,IAAuB,KAAlBL,EAAW,QAAYG,EAAYC,OAAOJ,EAAW,IAEjE,CDS0BM,CAAiBhB,GAC9BiB,QAAqBnB,EAAiBoB,OACtCC,EEpCd,SAAsCD,EAAMN,EAAOG,SAQzCK,EAAWF,EAAKG,QACjBN,GAAOA,EAAMK,GAAcR,GAASA,EAAQ,QACvC,IAAIT,eAAa,wBAAyB,CAC5CkB,KAAMD,EACNL,MACAH,cAGJU,EACAC,cACUV,IAAVD,QAA+BC,IAARE,GACvBO,EAAiBV,EAEjBW,EAAeR,EAAM,QAENF,IAAVD,QAA+BC,IAARE,GAC5BO,EAAiBV,EACjBW,EAAeH,QAEFP,IAARE,QAA+BF,IAAVD,IAC1BU,EAAiBF,EAAWL,EAC5BQ,EAAeH,GAEZ,CACHR,MAAOU,EACPP,IAAKQ,EAEZ,CFCmCC,CAA6BP,EAAcb,EAAWQ,MAAOR,EAAWW,KAC9FU,EAAaR,EAAaS,MAAMP,EAAoBP,MAAOO,EAAoBJ,KAC/EY,EAAiBF,EAAWJ,KAC5BO,EAAiB,IAAIC,SAASJ,EAAY,CAG5C1B,OAAQ,IACR+B,WAAY,kBACZ7B,QAASH,EAAiBG,iBAE9B2B,EAAe3B,QAAQ8B,IAAI,iBAAkBC,OAAOL,IACpDC,EAAe3B,QAAQ8B,IAAI,gBAAkB,SAAQZ,EAAoBP,SAASO,EAAoBJ,IAAM,KACrGE,EAAaI,QACbO,EAEX,MAAOK,UAUI,IAAIJ,SAAS,GAAI,CACpB9B,OAAQ,IACR+B,WAAY,0BAGvB,8BGpED,MACII,mBAYSC,yBAA2BxC,OAASE,UAASuC,oBAG1CA,GAAkBvC,EAAQI,QAAQoC,IAAI,eACzBzC,EAAsBC,EAASuC,GAIzCA"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-recipes.dev.js b/src/Resources/workbox-v7.0.0/workbox-recipes.dev.js new file mode 100644 index 0000000..3defb42 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-recipes.dev.js @@ -0,0 +1,285 @@ +this.workbox = this.workbox || {}; +this.workbox.recipes = (function (exports, registerRoute_js, StaleWhileRevalidate_js, CacheFirst_js, CacheableResponsePlugin_js, ExpirationPlugin_js, NetworkFirst_js, setCatchHandler_js, matchPrecache_js) { + 'use strict'; + + try { + self['workbox:recipes:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year + * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30 + */ + + function googleFontsCache(options = {}) { + const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`; + const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`; + const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365; + const maxEntries = options.maxEntries || 30; // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy. + + registerRoute_js.registerRoute(({ + url + }) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate_js.StaleWhileRevalidate({ + cacheName: sheetCacheName + })); // Cache the underlying font files with a cache-first strategy for 1 year. + + registerRoute_js.registerRoute(({ + url + }) => url.origin === 'https://fonts.gstatic.com', new CacheFirst_js.CacheFirst({ + cacheName: fontCacheName, + plugins: [new CacheableResponsePlugin_js.CacheableResponsePlugin({ + statuses: [0, 200] + }), new ExpirationPlugin_js.ExpirationPlugin({ + maxAgeSeconds, + maxEntries + })] + })); + } + + /** + * @memberof workbox-recipes + + * @param {Object} options + * @param {string[]} options.urls Paths to warm the strategy's cache with + * @param {Strategy} options.strategy Strategy to use + */ + + function warmStrategyCache(options) { + self.addEventListener('install', event => { + const done = options.urls.map(path => options.strategy.handleAll({ + event, + request: new Request(path) + })[1]); + event.waitUntil(Promise.all(done)); + }); + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to images + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image'; + * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days + * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ + + function imageCache(options = {}) { + const defaultMatchCallback = ({ + request + }) => request.destination === 'image'; + + const cacheName = options.cacheName || 'images'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60; + const maxEntries = options.maxEntries || 60; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin_js.CacheableResponsePlugin({ + statuses: [0, 200] + })); + plugins.push(new ExpirationPlugin_js.ExpirationPlugin({ + maxEntries, + maxAgeSeconds + })); + const strategy = new CacheFirst_js.CacheFirst({ + cacheName, + plugins + }); + registerRoute_js.registerRoute(matchCallback, strategy); // Warms the cache + + if (options.warmCache) { + warmStrategyCache({ + urls: options.warmCache, + strategy + }); + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files} + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to static-resources + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker'; + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ + + function staticResourceCache(options = {}) { + const defaultMatchCallback = ({ + request + }) => request.destination === 'style' || request.destination === 'script' || request.destination === 'worker'; + + const cacheName = options.cacheName || 'static-resources'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin_js.CacheableResponsePlugin({ + statuses: [0, 200] + })); + const strategy = new StaleWhileRevalidate_js.StaleWhileRevalidate({ + cacheName, + plugins + }); + registerRoute_js.registerRoute(matchCallback, strategy); // Warms the cache + + if (options.warmCache) { + warmStrategyCache({ + urls: options.warmCache, + strategy + }); + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a page caching recipe with a network timeout + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.cacheName] Name for cache. Defaults to pages + * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate'; + * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3 + * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe + * @param {string[]} [options.warmCache] Paths to call to use to warm this cache + */ + + function pageCache(options = {}) { + const defaultMatchCallback = ({ + request + }) => request.mode === 'navigate'; + + const cacheName = options.cacheName || 'pages'; + const matchCallback = options.matchCallback || defaultMatchCallback; + const networkTimeoutSeconds = options.networkTimeoutSeconds || 3; + const plugins = options.plugins || []; + plugins.push(new CacheableResponsePlugin_js.CacheableResponsePlugin({ + statuses: [0, 200] + })); + const strategy = new NetworkFirst_js.NetworkFirst({ + networkTimeoutSeconds, + cacheName, + plugins + }); // Registers the route + + registerRoute_js.registerRoute(matchCallback, strategy); // Warms the cache + + if (options.warmCache) { + warmStrategyCache({ + urls: options.warmCache, + strategy + }); + } + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection + * + * @memberof workbox-recipes + * + * @param {Object} [options] + * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html + * @param {string} [options.imageFallback] Precache name to match for image fallbacks. + * @param {string} [options.fontFallback] Precache name to match for font fallbacks. + */ + + function offlineFallback(options = {}) { + const pageFallback = options.pageFallback || 'offline.html'; + const imageFallback = options.imageFallback || false; + const fontFallback = options.fontFallback || false; + self.addEventListener('install', event => { + const files = [pageFallback]; + + if (imageFallback) { + files.push(imageFallback); + } + + if (fontFallback) { + files.push(fontFallback); + } + + event.waitUntil(self.caches.open('workbox-offline-fallbacks').then(cache => cache.addAll(files))); + }); + + const handler = async options => { + const dest = options.request.destination; + const cache = await self.caches.open('workbox-offline-fallbacks'); + + if (dest === 'document') { + const match = (await matchPrecache_js.matchPrecache(pageFallback)) || (await cache.match(pageFallback)); + return match || Response.error(); + } + + if (dest === 'image' && imageFallback !== false) { + const match = (await matchPrecache_js.matchPrecache(imageFallback)) || (await cache.match(imageFallback)); + return match || Response.error(); + } + + if (dest === 'font' && fontFallback !== false) { + const match = (await matchPrecache_js.matchPrecache(fontFallback)) || (await cache.match(fontFallback)); + return match || Response.error(); + } + + return Response.error(); + }; + + setCatchHandler_js.setCatchHandler(handler); + } + + exports.googleFontsCache = googleFontsCache; + exports.imageCache = imageCache; + exports.offlineFallback = offlineFallback; + exports.pageCache = pageCache; + exports.staticResourceCache = staticResourceCache; + exports.warmStrategyCache = warmStrategyCache; + + return exports; + +}({}, workbox.routing, workbox.strategies, workbox.strategies, workbox.cacheableResponse, workbox.expiration, workbox.strategies, workbox.routing, workbox.precaching)); +//# sourceMappingURL=workbox-recipes.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-recipes.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-recipes.dev.js.map new file mode 100644 index 0000000..1b1f574 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-recipes.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-recipes.dev.js","sources":["../_version.js","../googleFontsCache.js","../warmStrategyCache.js","../imageCache.js","../staticResourceCache.js","../pageCache.js","../offlineFallback.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:recipes:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';\nimport { CacheFirst } from 'workbox-strategies/CacheFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts\n * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year\n * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30\n */\nfunction googleFontsCache(options = {}) {\n const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`;\n const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`;\n const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365;\n const maxEntries = options.maxEntries || 30;\n // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.\n registerRoute(({ url }) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate({\n cacheName: sheetCacheName,\n }));\n // Cache the underlying font files with a cache-first strategy for 1 year.\n registerRoute(({ url }) => url.origin === 'https://fonts.gstatic.com', new CacheFirst({\n cacheName: fontCacheName,\n plugins: [\n new CacheableResponsePlugin({\n statuses: [0, 200],\n }),\n new ExpirationPlugin({\n maxAgeSeconds,\n maxEntries,\n }),\n ],\n }));\n}\nexport { googleFontsCache };\n","import './_version.js';\n/**\n * @memberof workbox-recipes\n \n * @param {Object} options\n * @param {string[]} options.urls Paths to warm the strategy's cache with\n * @param {Strategy} options.strategy Strategy to use\n */\nfunction warmStrategyCache(options) {\n self.addEventListener('install', (event) => {\n const done = options.urls.map((path) => options.strategy.handleAll({\n event,\n request: new Request(path),\n })[1]);\n event.waitUntil(Promise.all(done));\n });\n}\nexport { warmStrategyCache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { CacheFirst } from 'workbox-strategies/CacheFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images}\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to images\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image';\n * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days\n * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction imageCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.destination === 'image';\n const cacheName = options.cacheName || 'images';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60;\n const maxEntries = options.maxEntries || 60;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n plugins.push(new ExpirationPlugin({\n maxEntries,\n maxAgeSeconds,\n }));\n const strategy = new CacheFirst({\n cacheName,\n plugins,\n });\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { imageCache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files}\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to static-resources\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker';\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction staticResourceCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.destination === 'style' ||\n request.destination === 'script' ||\n request.destination === 'worker';\n const cacheName = options.cacheName || 'static-resources';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n const strategy = new StaleWhileRevalidate({\n cacheName,\n plugins,\n });\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { staticResourceCache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport './_version.js';\n/**\n * An implementation of a page caching recipe with a network timeout\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to pages\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate';\n * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction pageCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.mode === 'navigate';\n const cacheName = options.cacheName || 'pages';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const networkTimeoutSeconds = options.networkTimeoutSeconds || 3;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n const strategy = new NetworkFirst({\n networkTimeoutSeconds,\n cacheName,\n plugins,\n });\n // Registers the route\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { pageCache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { setCatchHandler } from 'workbox-routing/setCatchHandler.js';\nimport { matchPrecache } from 'workbox-precaching/matchPrecache.js';\nimport './_version.js';\n/**\n * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html\n * @param {string} [options.imageFallback] Precache name to match for image fallbacks.\n * @param {string} [options.fontFallback] Precache name to match for font fallbacks.\n */\nfunction offlineFallback(options = {}) {\n const pageFallback = options.pageFallback || 'offline.html';\n const imageFallback = options.imageFallback || false;\n const fontFallback = options.fontFallback || false;\n self.addEventListener('install', (event) => {\n const files = [pageFallback];\n if (imageFallback) {\n files.push(imageFallback);\n }\n if (fontFallback) {\n files.push(fontFallback);\n }\n event.waitUntil(self.caches\n .open('workbox-offline-fallbacks')\n .then((cache) => cache.addAll(files)));\n });\n const handler = async (options) => {\n const dest = options.request.destination;\n const cache = await self.caches.open('workbox-offline-fallbacks');\n if (dest === 'document') {\n const match = (await matchPrecache(pageFallback)) ||\n (await cache.match(pageFallback));\n return match || Response.error();\n }\n if (dest === 'image' && imageFallback !== false) {\n const match = (await matchPrecache(imageFallback)) ||\n (await cache.match(imageFallback));\n return match || Response.error();\n }\n if (dest === 'font' && fontFallback !== false) {\n const match = (await matchPrecache(fontFallback)) ||\n (await cache.match(fontFallback));\n return match || Response.error();\n }\n return Response.error();\n };\n setCatchHandler(handler);\n}\nexport { offlineFallback };\n"],"names":["self","_","e","googleFontsCache","options","sheetCacheName","cachePrefix","fontCacheName","maxAgeSeconds","maxEntries","registerRoute","url","origin","StaleWhileRevalidate","cacheName","CacheFirst","plugins","CacheableResponsePlugin","statuses","ExpirationPlugin","warmStrategyCache","addEventListener","event","done","urls","map","path","strategy","handleAll","request","Request","waitUntil","Promise","all","imageCache","defaultMatchCallback","destination","matchCallback","push","warmCache","staticResourceCache","pageCache","mode","networkTimeoutSeconds","NetworkFirst","offlineFallback","pageFallback","imageFallback","fontFallback","files","caches","open","then","cache","addAll","handler","dest","match","matchPrecache","Response","error","setCatchHandler"],"mappings":";;;;IAEA,IAAI;IACAA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AMM,KAAK,CAACI,KAAN,CAAYV,aAAZ,CADG,CAAd;IAEA,aAAOU,KAAK,IAAIE,QAAQ,CAACC,KAAT,EAAhB;IACH;;IACD,QAAIJ,IAAI,KAAK,MAAT,IAAmBR,YAAY,KAAK,KAAxC,EAA+C;IAC3C,YAAMS,KAAK,GAAG,CAAC,MAAMC,8BAAa,CAACV,YAAD,CAApB,MACT,MAAMK,KAAK,CAACI,KAAN,CAAYT,YAAZ,CADG,CAAd;IAEA,aAAOS,KAAK,IAAIE,QAAQ,CAACC,KAAT,EAAhB;IACH;;IACD,WAAOD,QAAQ,CAACC,KAAT,EAAP;IACH,GAnBD;;IAoBAC,EAAAA,kCAAe,CAACN,OAAD,CAAf;IACH;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-recipes.prod.js b/src/Resources/workbox-v7.0.0/workbox-recipes.prod.js new file mode 100644 index 0000000..a923bda --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-recipes.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.recipes=function(e,s,t,n,o,a,c,r,i){"use strict";try{self["workbox:recipes:7.0.0"]&&_()}catch(e){}function u(e){self.addEventListener("install",(s=>{const t=e.urls.map((t=>e.strategy.handleAll({event:s,request:new Request(t)})[1]));s.waitUntil(Promise.all(t))}))}return e.googleFontsCache=function(e={}){const c=`${e.cachePrefix||"google-fonts"}-stylesheets`,r=`${e.cachePrefix||"google-fonts"}-webfonts`,i=e.maxAgeSeconds||31536e3,u=e.maxEntries||30;s.registerRoute((({url:e})=>"https://fonts.googleapis.com"===e.origin),new t.StaleWhileRevalidate({cacheName:c})),s.registerRoute((({url:e})=>"https://fonts.gstatic.com"===e.origin),new n.CacheFirst({cacheName:r,plugins:[new o.CacheableResponsePlugin({statuses:[0,200]}),new a.ExpirationPlugin({maxAgeSeconds:i,maxEntries:u})]}))},e.imageCache=function(e={}){const t=e.cacheName||"images",c=e.matchCallback||(({request:e})=>"image"===e.destination),r=e.maxAgeSeconds||2592e3,i=e.maxEntries||60,w=e.plugins||[];w.push(new o.CacheableResponsePlugin({statuses:[0,200]})),w.push(new a.ExpirationPlugin({maxEntries:i,maxAgeSeconds:r}));const l=new n.CacheFirst({cacheName:t,plugins:w});s.registerRoute(c,l),e.warmCache&&u({urls:e.warmCache,strategy:l})},e.offlineFallback=function(e={}){const s=e.pageFallback||"offline.html",t=e.imageFallback||!1,n=e.fontFallback||!1;self.addEventListener("install",(e=>{const o=[s];t&&o.push(t),n&&o.push(n),e.waitUntil(self.caches.open("workbox-offline-fallbacks").then((e=>e.addAll(o))))})),r.setCatchHandler((async e=>{const o=e.request.destination,a=await self.caches.open("workbox-offline-fallbacks");if("document"===o){return await i.matchPrecache(s)||await a.match(s)||Response.error()}if("image"===o&&!1!==t){return await i.matchPrecache(t)||await a.match(t)||Response.error()}if("font"===o&&!1!==n){return await i.matchPrecache(n)||await a.match(n)||Response.error()}return Response.error()}))},e.pageCache=function(e={}){const t=e.cacheName||"pages",n=e.matchCallback||(({request:e})=>"navigate"===e.mode),a=e.networkTimeoutSeconds||3,r=e.plugins||[];r.push(new o.CacheableResponsePlugin({statuses:[0,200]}));const i=new c.NetworkFirst({networkTimeoutSeconds:a,cacheName:t,plugins:r});s.registerRoute(n,i),e.warmCache&&u({urls:e.warmCache,strategy:i})},e.staticResourceCache=function(e={}){const n=e.cacheName||"static-resources",a=e.matchCallback||(({request:e})=>"style"===e.destination||"script"===e.destination||"worker"===e.destination),c=e.plugins||[];c.push(new o.CacheableResponsePlugin({statuses:[0,200]}));const r=new t.StaleWhileRevalidate({cacheName:n,plugins:c});s.registerRoute(a,r),e.warmCache&&u({urls:e.warmCache,strategy:r})},e.warmStrategyCache=u,e}({},workbox.routing,workbox.strategies,workbox.strategies,workbox.cacheableResponse,workbox.expiration,workbox.strategies,workbox.routing,workbox.precaching); +//# sourceMappingURL=workbox-recipes.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-recipes.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-recipes.prod.js.map new file mode 100644 index 0000000..2659f30 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-recipes.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-recipes.prod.js","sources":["../_version.js","../warmStrategyCache.js","../googleFontsCache.js","../imageCache.js","../offlineFallback.js","../pageCache.js","../staticResourceCache.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:recipes:7.0.0'] && _();\n}\ncatch (e) { }\n","import './_version.js';\n/**\n * @memberof workbox-recipes\n \n * @param {Object} options\n * @param {string[]} options.urls Paths to warm the strategy's cache with\n * @param {Strategy} options.strategy Strategy to use\n */\nfunction warmStrategyCache(options) {\n self.addEventListener('install', (event) => {\n const done = options.urls.map((path) => options.strategy.handleAll({\n event,\n request: new Request(path),\n })[1]);\n event.waitUntil(Promise.all(done));\n });\n}\nexport { warmStrategyCache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';\nimport { CacheFirst } from 'workbox-strategies/CacheFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts\n * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year\n * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30\n */\nfunction googleFontsCache(options = {}) {\n const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`;\n const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`;\n const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365;\n const maxEntries = options.maxEntries || 30;\n // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.\n registerRoute(({ url }) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate({\n cacheName: sheetCacheName,\n }));\n // Cache the underlying font files with a cache-first strategy for 1 year.\n registerRoute(({ url }) => url.origin === 'https://fonts.gstatic.com', new CacheFirst({\n cacheName: fontCacheName,\n plugins: [\n new CacheableResponsePlugin({\n statuses: [0, 200],\n }),\n new ExpirationPlugin({\n maxAgeSeconds,\n maxEntries,\n }),\n ],\n }));\n}\nexport { googleFontsCache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { CacheFirst } from 'workbox-strategies/CacheFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [image caching recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images}\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to images\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'image';\n * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 30 days\n * @param {number} [options.maxEntries] Maximum number of images that will be cached. Defaults to 60\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction imageCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.destination === 'image';\n const cacheName = options.cacheName || 'images';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const maxAgeSeconds = options.maxAgeSeconds || 30 * 24 * 60 * 60;\n const maxEntries = options.maxEntries || 60;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n plugins.push(new ExpirationPlugin({\n maxEntries,\n maxAgeSeconds,\n }));\n const strategy = new CacheFirst({\n cacheName,\n plugins,\n });\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { imageCache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { setCatchHandler } from 'workbox-routing/setCatchHandler.js';\nimport { matchPrecache } from 'workbox-precaching/matchPrecache.js';\nimport './_version.js';\n/**\n * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html\n * @param {string} [options.imageFallback] Precache name to match for image fallbacks.\n * @param {string} [options.fontFallback] Precache name to match for font fallbacks.\n */\nfunction offlineFallback(options = {}) {\n const pageFallback = options.pageFallback || 'offline.html';\n const imageFallback = options.imageFallback || false;\n const fontFallback = options.fontFallback || false;\n self.addEventListener('install', (event) => {\n const files = [pageFallback];\n if (imageFallback) {\n files.push(imageFallback);\n }\n if (fontFallback) {\n files.push(fontFallback);\n }\n event.waitUntil(self.caches\n .open('workbox-offline-fallbacks')\n .then((cache) => cache.addAll(files)));\n });\n const handler = async (options) => {\n const dest = options.request.destination;\n const cache = await self.caches.open('workbox-offline-fallbacks');\n if (dest === 'document') {\n const match = (await matchPrecache(pageFallback)) ||\n (await cache.match(pageFallback));\n return match || Response.error();\n }\n if (dest === 'image' && imageFallback !== false) {\n const match = (await matchPrecache(imageFallback)) ||\n (await cache.match(imageFallback));\n return match || Response.error();\n }\n if (dest === 'font' && fontFallback !== false) {\n const match = (await matchPrecache(fontFallback)) ||\n (await cache.match(fontFallback));\n return match || Response.error();\n }\n return Response.error();\n };\n setCatchHandler(handler);\n}\nexport { offlineFallback };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport './_version.js';\n/**\n * An implementation of a page caching recipe with a network timeout\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to pages\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate';\n * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction pageCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.mode === 'navigate';\n const cacheName = options.cacheName || 'pages';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const networkTimeoutSeconds = options.networkTimeoutSeconds || 3;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n const strategy = new NetworkFirst({\n networkTimeoutSeconds,\n cacheName,\n plugins,\n });\n // Registers the route\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { pageCache };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { warmStrategyCache } from './warmStrategyCache';\nimport { registerRoute } from 'workbox-routing/registerRoute.js';\nimport { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';\nimport { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';\nimport './_version.js';\n/**\n * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files}\n *\n * @memberof workbox-recipes\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Name for cache. Defaults to static-resources\n * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker';\n * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe\n * @param {string[]} [options.warmCache] Paths to call to use to warm this cache\n */\nfunction staticResourceCache(options = {}) {\n const defaultMatchCallback = ({ request }) => request.destination === 'style' ||\n request.destination === 'script' ||\n request.destination === 'worker';\n const cacheName = options.cacheName || 'static-resources';\n const matchCallback = options.matchCallback || defaultMatchCallback;\n const plugins = options.plugins || [];\n plugins.push(new CacheableResponsePlugin({\n statuses: [0, 200],\n }));\n const strategy = new StaleWhileRevalidate({\n cacheName,\n plugins,\n });\n registerRoute(matchCallback, strategy);\n // Warms the cache\n if (options.warmCache) {\n warmStrategyCache({ urls: options.warmCache, strategy });\n }\n}\nexport { staticResourceCache };\n"],"names":["self","_","e","warmStrategyCache","options","addEventListener","event","done","urls","map","path","strategy","handleAll","request","Request","waitUntil","Promise","all","sheetCacheName","cachePrefix","fontCacheName","maxAgeSeconds","maxEntries","registerRoute","url","origin","StaleWhileRevalidate","cacheName","CacheFirst","plugins","CacheableResponsePlugin","statuses","ExpirationPlugin","matchCallback","destination","push","warmCache","pageFallback","imageFallback","fontFallback","files","caches","open","then","cache","addAll","setCatchHandler","async","dest","mat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IAAIL,0BAAwB,CACrCC,SAAU,CAAC,EAAG,cAEZpB,EAAW,IAAIe,uBAAqB,CACtCC,YACAE,YAEJN,gBAAcU,EAAetB,GAEzBP,EAAQgC,WACRjC,EAAkB,CAAEK,KAAMJ,EAAQgC,UAAWzB,YAEpD"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-routing.dev.js b/src/Resources/workbox-v7.0.0/workbox-routing.dev.js new file mode 100644 index 0000000..4a48b92 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-routing.dev.js @@ -0,0 +1,980 @@ +this.workbox = this.workbox || {}; +this.workbox.routing = (function (exports, assert_js, logger_js, WorkboxError_js, getFriendlyURL_js) { + 'use strict'; + + try { + self['workbox:routing:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The default HTTP method, 'GET', used when there's no specific method + * configured for a route. + * + * @type {string} + * + * @private + */ + + const defaultMethod = 'GET'; + /** + * The list of valid HTTP methods associated with requests that could be routed. + * + * @type {Array} + * + * @private + */ + + const validMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT']; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * @param {function()|Object} handler Either a function, or an object with a + * 'handle' method. + * @return {Object} An object with a handle method. + * + * @private + */ + + const normalizeHandler = handler => { + if (handler && typeof handler === 'object') { + { + assert_js.assert.hasMethod(handler, 'handle', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'handler' + }); + } + + return handler; + } else { + { + assert_js.assert.isType(handler, 'function', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'handler' + }); + } + + return { + handle: handler + }; + } + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A `Route` consists of a pair of callback functions, "match" and "handler". + * The "match" callback determine if a route should be used to "handle" a + * request by returning a non-falsy value if it can. The "handler" callback + * is called when there is a match and should return a Promise that resolves + * to a `Response`. + * + * @memberof workbox-routing + */ + + class Route { + /** + * Constructor for Route class. + * + * @param {workbox-routing~matchCallback} match + * A callback function that determines whether the route matches a given + * `fetch` event by returning a non-falsy value. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resolving to a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(match, handler, method = defaultMethod) { + { + assert_js.assert.isType(match, 'function', { + moduleName: 'workbox-routing', + className: 'Route', + funcName: 'constructor', + paramName: 'match' + }); + + if (method) { + assert_js.assert.isOneOf(method, validMethods, { + paramName: 'method' + }); + } + } // These values are referenced directly by Router so cannot be + // altered by minificaton. + + + this.handler = normalizeHandler(handler); + this.match = match; + this.method = method; + } + /** + * + * @param {workbox-routing-handlerCallback} handler A callback + * function that returns a Promise resolving to a Response + */ + + + setCatchHandler(handler) { + this.catchHandler = normalizeHandler(handler); + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * NavigationRoute makes it easy to create a + * {@link workbox-routing.Route} that matches for browser + * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. + * + * It will only match incoming Requests whose + * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode} + * is set to `navigate`. + * + * You can optionally only apply this route to a subset of navigation requests + * by using one or both of the `denylist` and `allowlist` parameters. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ + + class NavigationRoute extends Route { + /** + * If both `denylist` and `allowlist` are provided, the `denylist` will + * take precedence and the request will not match this route. + * + * The regular expressions in `allowlist` and `denylist` + * are matched against the concatenated + * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} + * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} + * portions of the requested URL. + * + * *Note*: These RegExps may be evaluated against every destination URL during + * a navigation. Avoid using + * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077), + * or else your users may see delays when navigating your site. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {Object} options + * @param {Array} [options.denylist] If any of these patterns match, + * the route will not handle the request (even if a allowlist RegExp matches). + * @param {Array} [options.allowlist=[/./]] If any of these patterns + * match the URL's pathname and search parameter, the route will handle the + * request (assuming the denylist doesn't match). + */ + constructor(handler, { + allowlist = [/./], + denylist = [] + } = {}) { + { + assert_js.assert.isArrayOfClass(allowlist, RegExp, { + moduleName: 'workbox-routing', + className: 'NavigationRoute', + funcName: 'constructor', + paramName: 'options.allowlist' + }); + assert_js.assert.isArrayOfClass(denylist, RegExp, { + moduleName: 'workbox-routing', + className: 'NavigationRoute', + funcName: 'constructor', + paramName: 'options.denylist' + }); + } + + super(options => this._match(options), handler); + this._allowlist = allowlist; + this._denylist = denylist; + } + /** + * Routes match handler. + * + * @param {Object} options + * @param {URL} options.url + * @param {Request} options.request + * @return {boolean} + * + * @private + */ + + + _match({ + url, + request + }) { + if (request && request.mode !== 'navigate') { + return false; + } + + const pathnameAndSearch = url.pathname + url.search; + + for (const regExp of this._denylist) { + if (regExp.test(pathnameAndSearch)) { + { + logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL matches this denylist pattern: ` + `${regExp.toString()}`); + } + + return false; + } + } + + if (this._allowlist.some(regExp => regExp.test(pathnameAndSearch))) { + { + logger_js.logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`); + } + + return true; + } + + { + logger_js.logger.log(`The navigation route ${pathnameAndSearch} is not ` + `being used, since the URL being navigated to doesn't ` + `match the allowlist.`); + } + + return false; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * RegExpRoute makes it easy to create a regular expression based + * {@link workbox-routing.Route}. + * + * For same-origin requests the RegExp only needs to match part of the URL. For + * requests against third-party servers, you must define a RegExp that matches + * the start of the URL. + * + * @memberof workbox-routing + * @extends workbox-routing.Route + */ + + class RegExpRoute extends Route { + /** + * If the regular expression contains + * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references}, + * the captured values will be passed to the + * {@link workbox-routing~handlerCallback} `params` + * argument. + * + * @param {RegExp} regExp The regular expression to match against URLs. + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + */ + constructor(regExp, handler, method) { + { + assert_js.assert.isInstance(regExp, RegExp, { + moduleName: 'workbox-routing', + className: 'RegExpRoute', + funcName: 'constructor', + paramName: 'pattern' + }); + } + + const match = ({ + url + }) => { + const result = regExp.exec(url.href); // Return immediately if there's no match. + + if (!result) { + return; + } // Require that the match start at the first character in the URL string + // if it's a cross-origin request. + // See https://github.com/GoogleChrome/workbox/issues/281 for the context + // behind this behavior. + + + if (url.origin !== location.origin && result.index !== 0) { + { + logger_js.logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + `handle cross-origin requests if they match the entire URL.`); + } + + return; + } // If the route matches, but there aren't any capture groups defined, then + // this will return [], which is truthy and therefore sufficient to + // indicate a match. + // If there are capture groups, then it will return their values. + + + return result.slice(1); + }; + + super(match, handler, method); + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The Router can be used to process a `FetchEvent` using one or more + * {@link workbox-routing.Route}, responding with a `Response` if + * a matching route exists. + * + * If no route matches a given a request, the Router will use a "default" + * handler if one is defined. + * + * Should the matching Route throw an error, the Router will use a "catch" + * handler if one is defined to gracefully deal with issues and respond with a + * Request. + * + * If a request matches multiple routes, the **earliest** registered route will + * be used to respond to the request. + * + * @memberof workbox-routing + */ + + class Router { + /** + * Initializes a new Router. + */ + constructor() { + this._routes = new Map(); + this._defaultHandlerMap = new Map(); + } + /** + * @return {Map>} routes A `Map` of HTTP + * method name ('GET', etc.) to an array of all the corresponding `Route` + * instances that are registered. + */ + + + get routes() { + return this._routes; + } + /** + * Adds a fetch event listener to respond to events when a route matches + * the event's request. + */ + + + addFetchListener() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('fetch', event => { + const { + request + } = event; + const responsePromise = this.handleRequest({ + request, + event + }); + + if (responsePromise) { + event.respondWith(responsePromise); + } + }); + } + /** + * Adds a message event listener for URLs to cache from the window. + * This is useful to cache resources loaded on the page prior to when the + * service worker started controlling it. + * + * The format of the message data sent from the window should be as follows. + * Where the `urlsToCache` array may consist of URL strings or an array of + * URL string + `requestInit` object (the same as you'd pass to `fetch()`). + * + * ``` + * { + * type: 'CACHE_URLS', + * payload: { + * urlsToCache: [ + * './script1.js', + * './script2.js', + * ['./script3.js', {mode: 'no-cors'}], + * ], + * }, + * } + * ``` + */ + + + addCacheListener() { + // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705 + self.addEventListener('message', event => { + // event.data is type 'any' + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (event.data && event.data.type === 'CACHE_URLS') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { + payload + } = event.data; + + { + logger_js.logger.debug(`Caching URLs from the window`, payload.urlsToCache); + } + + const requestPromises = Promise.all(payload.urlsToCache.map(entry => { + if (typeof entry === 'string') { + entry = [entry]; + } + + const request = new Request(...entry); + return this.handleRequest({ + request, + event + }); // TODO(philipwalton): TypeScript errors without this typecast for + // some reason (probably a bug). The real type here should work but + // doesn't: `Array | undefined>`. + })); // TypeScript + + event.waitUntil(requestPromises); // If a MessageChannel was used, reply to the message on success. + + if (event.ports && event.ports[0]) { + void requestPromises.then(() => event.ports[0].postMessage(true)); + } + } + }); + } + /** + * Apply the routing rules to a FetchEvent object to get a Response from an + * appropriate Route's handler. + * + * @param {Object} options + * @param {Request} options.request The request to handle. + * @param {ExtendableEvent} options.event The event that triggered the + * request. + * @return {Promise|undefined} A promise is returned if a + * registered route can handle the request. If there is no matching + * route and there's no `defaultHandler`, `undefined` is returned. + */ + + + handleRequest({ + request, + event + }) { + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'handleRequest', + paramName: 'options.request' + }); + } + + const url = new URL(request.url, location.href); + + if (!url.protocol.startsWith('http')) { + { + logger_js.logger.debug(`Workbox Router only supports URLs that start with 'http'.`); + } + + return; + } + + const sameOrigin = url.origin === location.origin; + const { + params, + route + } = this.findMatchingRoute({ + event, + request, + sameOrigin, + url + }); + let handler = route && route.handler; + const debugMessages = []; + + { + if (handler) { + debugMessages.push([`Found a route to handle this request:`, route]); + + if (params) { + debugMessages.push([`Passing the following params to the route's handler:`, params]); + } + } + } // If we don't have a handler because there was no matching route, then + // fall back to defaultHandler if that's defined. + + + const method = request.method; + + if (!handler && this._defaultHandlerMap.has(method)) { + { + debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`); + } + + handler = this._defaultHandlerMap.get(method); + } + + if (!handler) { + { + // No handler so Workbox will do nothing. If logs is set of debug + // i.e. verbose, we should print out this information. + logger_js.logger.debug(`No route found for: ${getFriendlyURL_js.getFriendlyURL(url)}`); + } + + return; + } + + { + // We have a handler, meaning Workbox is going to handle the route. + // print the routing details to the console. + logger_js.logger.groupCollapsed(`Router is responding to: ${getFriendlyURL_js.getFriendlyURL(url)}`); + debugMessages.forEach(msg => { + if (Array.isArray(msg)) { + logger_js.logger.log(...msg); + } else { + logger_js.logger.log(msg); + } + }); + logger_js.logger.groupEnd(); + } // Wrap in try and catch in case the handle method throws a synchronous + // error. It should still callback to the catch handler. + + + let responsePromise; + + try { + responsePromise = handler.handle({ + url, + request, + event, + params + }); + } catch (err) { + responsePromise = Promise.reject(err); + } // Get route's catch handler, if it exists + + + const catchHandler = route && route.catchHandler; + + if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) { + responsePromise = responsePromise.catch(async err => { + // If there's a route catch handler, process that first + if (catchHandler) { + { + // Still include URL here as it will be async from the console group + // and may not make sense without the URL + logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to route's Catch Handler.`); + logger_js.logger.error(`Error thrown by:`, route); + logger_js.logger.error(err); + logger_js.logger.groupEnd(); + } + + try { + return await catchHandler.handle({ + url, + request, + event, + params + }); + } catch (catchErr) { + if (catchErr instanceof Error) { + err = catchErr; + } + } + } + + if (this._catchHandler) { + { + // Still include URL here as it will be async from the console group + // and may not make sense without the URL + logger_js.logger.groupCollapsed(`Error thrown when responding to: ` + ` ${getFriendlyURL_js.getFriendlyURL(url)}. Falling back to global Catch Handler.`); + logger_js.logger.error(`Error thrown by:`, route); + logger_js.logger.error(err); + logger_js.logger.groupEnd(); + } + + return this._catchHandler.handle({ + url, + request, + event + }); + } + + throw err; + }); + } + + return responsePromise; + } + /** + * Checks a request and URL (and optionally an event) against the list of + * registered routes, and if there's a match, returns the corresponding + * route along with any params generated by the match. + * + * @param {Object} options + * @param {URL} options.url + * @param {boolean} options.sameOrigin The result of comparing `url.origin` + * against the current origin. + * @param {Request} options.request The request to match. + * @param {Event} options.event The corresponding event. + * @return {Object} An object with `route` and `params` properties. + * They are populated if a matching route was found or `undefined` + * otherwise. + */ + + + findMatchingRoute({ + url, + sameOrigin, + request, + event + }) { + const routes = this._routes.get(request.method) || []; + + for (const route of routes) { + let params; // route.match returns type any, not possible to change right now. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + + const matchResult = route.match({ + url, + sameOrigin, + request, + event + }); + + if (matchResult) { + { + // Warn developers that using an async matchCallback is almost always + // not the right thing to do. + if (matchResult instanceof Promise) { + logger_js.logger.warn(`While routing ${getFriendlyURL_js.getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route); + } + } // See https://github.com/GoogleChrome/workbox/issues/2079 + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + + + params = matchResult; + + if (Array.isArray(params) && params.length === 0) { + // Instead of passing an empty array in as params, use undefined. + params = undefined; + } else if (matchResult.constructor === Object && // eslint-disable-line + Object.keys(matchResult).length === 0) { + // Instead of passing an empty object in as params, use undefined. + params = undefined; + } else if (typeof matchResult === 'boolean') { + // For the boolean value true (rather than just something truth-y), + // don't set params. + // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353 + params = undefined; + } // Return early if have a match. + + + return { + route, + params + }; + } + } // If no match was found above, return and empty object. + + + return {}; + } + /** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Each HTTP method ('GET', 'POST', etc.) gets its own default handler. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * @param {string} [method='GET'] The HTTP method to associate with this + * default handler. Each method has its own default. + */ + + + setDefaultHandler(handler, method = defaultMethod) { + this._defaultHandlerMap.set(method, normalizeHandler(handler)); + } + /** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + */ + + + setCatchHandler(handler) { + this._catchHandler = normalizeHandler(handler); + } + /** + * Registers a route with the router. + * + * @param {workbox-routing.Route} route The route to register. + */ + + + registerRoute(route) { + { + assert_js.assert.isType(route, 'object', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route' + }); + assert_js.assert.hasMethod(route, 'match', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route' + }); + assert_js.assert.isType(route.handler, 'object', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route' + }); + assert_js.assert.hasMethod(route.handler, 'handle', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route.handler' + }); + assert_js.assert.isType(route.method, 'string', { + moduleName: 'workbox-routing', + className: 'Router', + funcName: 'registerRoute', + paramName: 'route.method' + }); + } + + if (!this._routes.has(route.method)) { + this._routes.set(route.method, []); + } // Give precedence to all of the earlier routes by adding this additional + // route to the end of the array. + + + this._routes.get(route.method).push(route); + } + /** + * Unregisters a route with the router. + * + * @param {workbox-routing.Route} route The route to unregister. + */ + + + unregisterRoute(route) { + if (!this._routes.has(route.method)) { + throw new WorkboxError_js.WorkboxError('unregister-route-but-not-found-with-method', { + method: route.method + }); + } + + const routeIndex = this._routes.get(route.method).indexOf(route); + + if (routeIndex > -1) { + this._routes.get(route.method).splice(routeIndex, 1); + } else { + throw new WorkboxError_js.WorkboxError('unregister-route-route-not-registered'); + } + } + + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + let defaultRouter; + /** + * Creates a new, singleton Router instance if one does not exist. If one + * does already exist, that instance is returned. + * + * @private + * @return {Router} + */ + + const getOrCreateDefaultRouter = () => { + if (!defaultRouter) { + defaultRouter = new Router(); // The helpers that use the default Router assume these listeners exist. + + defaultRouter.addFetchListener(); + defaultRouter.addCacheListener(); + } + + return defaultRouter; + }; + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Easily register a RegExp, string, or function with a caching + * strategy to a singleton Router instance. + * + * This method will generate a Route for you if needed and + * call {@link workbox-routing.Router#registerRoute}. + * + * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture + * If the capture param is a `Route`, all other arguments will be ignored. + * @param {workbox-routing~handlerCallback} [handler] A callback + * function that returns a Promise resulting in a Response. This parameter + * is required if `capture` is not a `Route` object. + * @param {string} [method='GET'] The HTTP method to match the Route + * against. + * @return {workbox-routing.Route} The generated `Route`. + * + * @memberof workbox-routing + */ + + function registerRoute(capture, handler, method) { + let route; + + if (typeof capture === 'string') { + const captureUrl = new URL(capture, location.href); + + { + if (!(capture.startsWith('/') || capture.startsWith('http'))) { + throw new WorkboxError_js.WorkboxError('invalid-string', { + moduleName: 'workbox-routing', + funcName: 'registerRoute', + paramName: 'capture' + }); + } // We want to check if Express-style wildcards are in the pathname only. + // TODO: Remove this log message in v4. + + + const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture; // See https://github.com/pillarjs/path-to-regexp#parameters + + const wildcards = '[*:?+]'; + + if (new RegExp(`${wildcards}`).exec(valueToCheck)) { + logger_js.logger.debug(`The '$capture' parameter contains an Express-style wildcard ` + `character (${wildcards}). Strings are now always interpreted as ` + `exact matches; use a RegExp for partial or wildcard matches.`); + } + } + + const matchCallback = ({ + url + }) => { + { + if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) { + logger_js.logger.debug(`${capture} only partially matches the cross-origin URL ` + `${url.toString()}. This route will only handle cross-origin requests ` + `if they match the entire URL.`); + } + } + + return url.href === captureUrl.href; + }; // If `capture` is a string then `handler` and `method` must be present. + + + route = new Route(matchCallback, handler, method); + } else if (capture instanceof RegExp) { + // If `capture` is a `RegExp` then `handler` and `method` must be present. + route = new RegExpRoute(capture, handler, method); + } else if (typeof capture === 'function') { + // If `capture` is a function then `handler` and `method` must be present. + route = new Route(capture, handler, method); + } else if (capture instanceof Route) { + route = capture; + } else { + throw new WorkboxError_js.WorkboxError('unsupported-route-type', { + moduleName: 'workbox-routing', + funcName: 'registerRoute', + paramName: 'capture' + }); + } + + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.registerRoute(route); + return route; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ + + function setCatchHandler(handler) { + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.setCatchHandler(handler); + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Define a default `handler` that's called when no routes explicitly + * match the incoming request. + * + * Without a default handler, unmatched requests will go against the + * network as if there were no service worker present. + * + * @param {workbox-routing~handlerCallback} handler A callback + * function that returns a Promise resulting in a Response. + * + * @memberof workbox-routing + */ + + function setDefaultHandler(handler) { + const defaultRouter = getOrCreateDefaultRouter(); + defaultRouter.setDefaultHandler(handler); + } + + exports.NavigationRoute = NavigationRoute; + exports.RegExpRoute = RegExpRoute; + exports.Route = Route; + exports.Router = Router; + exports.registerRoute = registerRoute; + exports.setCatchHandler = setCatchHandler; + exports.setDefaultHandler = setDefaultHandler; + + return exports; + +}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private)); +//# sourceMappingURL=workbox-routing.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-routing.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-routing.dev.js.map new file mode 100644 index 0000000..fa57d31 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-routing.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-routing.dev.js","sources":["../_version.js","../utils/constants.js","../utils/normalizeHandler.js","../Route.js","../NavigationRoute.js","../RegExpRoute.js","../Router.js","../utils/getOrCreateDefaultRouter.js","../registerRoute.js","../setCatchHandler.js","../setDefaultHandler.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:routing:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The default HTTP method, 'GET', used when there's no specific method\n * configured for a route.\n *\n * @type {string}\n *\n * @private\n */\nexport const defaultMethod = 'GET';\n/**\n * The list of valid HTTP methods associated with requests that could be routed.\n *\n * @type {Array}\n *\n * @private\n */\nexport const validMethods = [\n 'DELETE',\n 'GET',\n 'HEAD',\n 'PATCH',\n 'POST',\n 'PUT',\n];\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {function()|Object} handler Either a function, or an object with a\n * 'handle' method.\n * @return {Object} An object with a handle method.\n *\n * @private\n */\nexport const normalizeHandler = (handler) => {\n if (handler && typeof handler === 'object') {\n if (process.env.NODE_ENV !== 'production') {\n assert.hasMethod(handler, 'handle', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'handler',\n });\n }\n return handler;\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(handler, 'function', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'handler',\n });\n }\n return { handle: handler };\n }\n};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { defaultMethod, validMethods } from './utils/constants.js';\nimport { normalizeHandler } from './utils/normalizeHandler.js';\nimport './_version.js';\n/**\n * A `Route` consists of a pair of callback functions, \"match\" and \"handler\".\n * The \"match\" callback determine if a route should be used to \"handle\" a\n * request by returning a non-falsy value if it can. The \"handler\" callback\n * is called when there is a match and should return a Promise that resolves\n * to a `Response`.\n *\n * @memberof workbox-routing\n */\nclass Route {\n /**\n * Constructor for Route class.\n *\n * @param {workbox-routing~matchCallback} match\n * A callback function that determines whether the route matches a given\n * `fetch` event by returning a non-falsy value.\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resolving to a Response.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n */\n constructor(match, handler, method = defaultMethod) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(match, 'function', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'match',\n });\n if (method) {\n assert.isOneOf(method, validMethods, { paramName: 'method' });\n }\n }\n // These values are referenced directly by Router so cannot be\n // altered by minificaton.\n this.handler = normalizeHandler(handler);\n this.match = match;\n this.method = method;\n }\n /**\n *\n * @param {workbox-routing-handlerCallback} handler A callback\n * function that returns a Promise resolving to a Response\n */\n setCatchHandler(handler) {\n this.catchHandler = normalizeHandler(handler);\n }\n}\nexport { Route };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from './Route.js';\nimport './_version.js';\n/**\n * NavigationRoute makes it easy to create a\n * {@link workbox-routing.Route} that matches for browser\n * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.\n *\n * It will only match incoming Requests whose\n * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}\n * is set to `navigate`.\n *\n * You can optionally only apply this route to a subset of navigation requests\n * by using one or both of the `denylist` and `allowlist` parameters.\n *\n * @memberof workbox-routing\n * @extends workbox-routing.Route\n */\nclass NavigationRoute extends Route {\n /**\n * If both `denylist` and `allowlist` are provided, the `denylist` will\n * take precedence and the request will not match this route.\n *\n * The regular expressions in `allowlist` and `denylist`\n * are matched against the concatenated\n * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}\n * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}\n * portions of the requested URL.\n *\n * *Note*: These RegExps may be evaluated against every destination URL during\n * a navigation. Avoid using\n * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\n * or else your users may see delays when navigating your site.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {Object} options\n * @param {Array} [options.denylist] If any of these patterns match,\n * the route will not handle the request (even if a allowlist RegExp matches).\n * @param {Array} [options.allowlist=[/./]] If any of these patterns\n * match the URL's pathname and search parameter, the route will handle the\n * request (assuming the denylist doesn't match).\n */\n constructor(handler, { allowlist = [/./], denylist = [] } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArrayOfClass(allowlist, RegExp, {\n moduleName: 'workbox-routing',\n className: 'NavigationRoute',\n funcName: 'constructor',\n paramName: 'options.allowlist',\n });\n assert.isArrayOfClass(denylist, RegExp, {\n moduleName: 'workbox-routing',\n className: 'NavigationRoute',\n funcName: 'constructor',\n paramName: 'options.denylist',\n });\n }\n super((options) => this._match(options), handler);\n this._allowlist = allowlist;\n this._denylist = denylist;\n }\n /**\n * Routes match handler.\n *\n * @param {Object} options\n * @param {URL} options.url\n * @param {Request} options.request\n * @return {boolean}\n *\n * @private\n */\n _match({ url, request }) {\n if (request && request.mode !== 'navigate') {\n return false;\n }\n const pathnameAndSearch = url.pathname + url.search;\n for (const regExp of this._denylist) {\n if (regExp.test(pathnameAndSearch)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The navigation route ${pathnameAndSearch} is not ` +\n `being used, since the URL matches this denylist pattern: ` +\n `${regExp.toString()}`);\n }\n return false;\n }\n }\n if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);\n }\n return true;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The navigation route ${pathnameAndSearch} is not ` +\n `being used, since the URL being navigated to doesn't ` +\n `match the allowlist.`);\n }\n return false;\n }\n}\nexport { NavigationRoute };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from './Route.js';\nimport './_version.js';\n/**\n * RegExpRoute makes it easy to create a regular expression based\n * {@link workbox-routing.Route}.\n *\n * For same-origin requests the RegExp only needs to match part of the URL. For\n * requests against third-party servers, you must define a RegExp that matches\n * the start of the URL.\n *\n * @memberof workbox-routing\n * @extends workbox-routing.Route\n */\nclass RegExpRoute extends Route {\n /**\n * If the regular expression contains\n * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},\n * the captured values will be passed to the\n * {@link workbox-routing~handlerCallback} `params`\n * argument.\n *\n * @param {RegExp} regExp The regular expression to match against URLs.\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n */\n constructor(regExp, handler, method) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(regExp, RegExp, {\n moduleName: 'workbox-routing',\n className: 'RegExpRoute',\n funcName: 'constructor',\n paramName: 'pattern',\n });\n }\n const match = ({ url }) => {\n const result = regExp.exec(url.href);\n // Return immediately if there's no match.\n if (!result) {\n return;\n }\n // Require that the match start at the first character in the URL string\n // if it's a cross-origin request.\n // See https://github.com/GoogleChrome/workbox/issues/281 for the context\n // behind this behavior.\n if (url.origin !== location.origin && result.index !== 0) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` +\n `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` +\n `handle cross-origin requests if they match the entire URL.`);\n }\n return;\n }\n // If the route matches, but there aren't any capture groups defined, then\n // this will return [], which is truthy and therefore sufficient to\n // indicate a match.\n // If there are capture groups, then it will return their values.\n return result.slice(1);\n };\n super(match, handler, method);\n }\n}\nexport { RegExpRoute };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { defaultMethod } from './utils/constants.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { normalizeHandler } from './utils/normalizeHandler.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\n/**\n * The Router can be used to process a `FetchEvent` using one or more\n * {@link workbox-routing.Route}, responding with a `Response` if\n * a matching route exists.\n *\n * If no route matches a given a request, the Router will use a \"default\"\n * handler if one is defined.\n *\n * Should the matching Route throw an error, the Router will use a \"catch\"\n * handler if one is defined to gracefully deal with issues and respond with a\n * Request.\n *\n * If a request matches multiple routes, the **earliest** registered route will\n * be used to respond to the request.\n *\n * @memberof workbox-routing\n */\nclass Router {\n /**\n * Initializes a new Router.\n */\n constructor() {\n this._routes = new Map();\n this._defaultHandlerMap = new Map();\n }\n /**\n * @return {Map>} routes A `Map` of HTTP\n * method name ('GET', etc.) to an array of all the corresponding `Route`\n * instances that are registered.\n */\n get routes() {\n return this._routes;\n }\n /**\n * Adds a fetch event listener to respond to events when a route matches\n * the event's request.\n */\n addFetchListener() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('fetch', ((event) => {\n const { request } = event;\n const responsePromise = this.handleRequest({ request, event });\n if (responsePromise) {\n event.respondWith(responsePromise);\n }\n }));\n }\n /**\n * Adds a message event listener for URLs to cache from the window.\n * This is useful to cache resources loaded on the page prior to when the\n * service worker started controlling it.\n *\n * The format of the message data sent from the window should be as follows.\n * Where the `urlsToCache` array may consist of URL strings or an array of\n * URL string + `requestInit` object (the same as you'd pass to `fetch()`).\n *\n * ```\n * {\n * type: 'CACHE_URLS',\n * payload: {\n * urlsToCache: [\n * './script1.js',\n * './script2.js',\n * ['./script3.js', {mode: 'no-cors'}],\n * ],\n * },\n * }\n * ```\n */\n addCacheListener() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('message', ((event) => {\n // event.data is type 'any'\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (event.data && event.data.type === 'CACHE_URLS') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { payload } = event.data;\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Caching URLs from the window`, payload.urlsToCache);\n }\n const requestPromises = Promise.all(payload.urlsToCache.map((entry) => {\n if (typeof entry === 'string') {\n entry = [entry];\n }\n const request = new Request(...entry);\n return this.handleRequest({ request, event });\n // TODO(philipwalton): TypeScript errors without this typecast for\n // some reason (probably a bug). The real type here should work but\n // doesn't: `Array | undefined>`.\n })); // TypeScript\n event.waitUntil(requestPromises);\n // If a MessageChannel was used, reply to the message on success.\n if (event.ports && event.ports[0]) {\n void requestPromises.then(() => event.ports[0].postMessage(true));\n }\n }\n }));\n }\n /**\n * Apply the routing rules to a FetchEvent object to get a Response from an\n * appropriate Route's handler.\n *\n * @param {Object} options\n * @param {Request} options.request The request to handle.\n * @param {ExtendableEvent} options.event The event that triggered the\n * request.\n * @return {Promise|undefined} A promise is returned if a\n * registered route can handle the request. If there is no matching\n * route and there's no `defaultHandler`, `undefined` is returned.\n */\n handleRequest({ request, event, }) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'handleRequest',\n paramName: 'options.request',\n });\n }\n const url = new URL(request.url, location.href);\n if (!url.protocol.startsWith('http')) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Workbox Router only supports URLs that start with 'http'.`);\n }\n return;\n }\n const sameOrigin = url.origin === location.origin;\n const { params, route } = this.findMatchingRoute({\n event,\n request,\n sameOrigin,\n url,\n });\n let handler = route && route.handler;\n const debugMessages = [];\n if (process.env.NODE_ENV !== 'production') {\n if (handler) {\n debugMessages.push([`Found a route to handle this request:`, route]);\n if (params) {\n debugMessages.push([\n `Passing the following params to the route's handler:`,\n params,\n ]);\n }\n }\n }\n // If we don't have a handler because there was no matching route, then\n // fall back to defaultHandler if that's defined.\n const method = request.method;\n if (!handler && this._defaultHandlerMap.has(method)) {\n if (process.env.NODE_ENV !== 'production') {\n debugMessages.push(`Failed to find a matching route. Falling ` +\n `back to the default handler for ${method}.`);\n }\n handler = this._defaultHandlerMap.get(method);\n }\n if (!handler) {\n if (process.env.NODE_ENV !== 'production') {\n // No handler so Workbox will do nothing. If logs is set of debug\n // i.e. verbose, we should print out this information.\n logger.debug(`No route found for: ${getFriendlyURL(url)}`);\n }\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // We have a handler, meaning Workbox is going to handle the route.\n // print the routing details to the console.\n logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);\n debugMessages.forEach((msg) => {\n if (Array.isArray(msg)) {\n logger.log(...msg);\n }\n else {\n logger.log(msg);\n }\n });\n logger.groupEnd();\n }\n // Wrap in try and catch in case the handle method throws a synchronous\n // error. It should still callback to the catch handler.\n let responsePromise;\n try {\n responsePromise = handler.handle({ url, request, event, params });\n }\n catch (err) {\n responsePromise = Promise.reject(err);\n }\n // Get route's catch handler, if it exists\n const catchHandler = route && route.catchHandler;\n if (responsePromise instanceof Promise &&\n (this._catchHandler || catchHandler)) {\n responsePromise = responsePromise.catch(async (err) => {\n // If there's a route catch handler, process that first\n if (catchHandler) {\n if (process.env.NODE_ENV !== 'production') {\n // Still include URL here as it will be async from the console group\n // and may not make sense without the URL\n logger.groupCollapsed(`Error thrown when responding to: ` +\n ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);\n logger.error(`Error thrown by:`, route);\n logger.error(err);\n logger.groupEnd();\n }\n try {\n return await catchHandler.handle({ url, request, event, params });\n }\n catch (catchErr) {\n if (catchErr instanceof Error) {\n err = catchErr;\n }\n }\n }\n if (this._catchHandler) {\n if (process.env.NODE_ENV !== 'production') {\n // Still include URL here as it will be async from the console group\n // and may not make sense without the URL\n logger.groupCollapsed(`Error thrown when responding to: ` +\n ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);\n logger.error(`Error thrown by:`, route);\n logger.error(err);\n logger.groupEnd();\n }\n return this._catchHandler.handle({ url, request, event });\n }\n throw err;\n });\n }\n return responsePromise;\n }\n /**\n * Checks a request and URL (and optionally an event) against the list of\n * registered routes, and if there's a match, returns the corresponding\n * route along with any params generated by the match.\n *\n * @param {Object} options\n * @param {URL} options.url\n * @param {boolean} options.sameOrigin The result of comparing `url.origin`\n * against the current origin.\n * @param {Request} options.request The request to match.\n * @param {Event} options.event The corresponding event.\n * @return {Object} An object with `route` and `params` properties.\n * They are populated if a matching route was found or `undefined`\n * otherwise.\n */\n findMatchingRoute({ url, sameOrigin, request, event, }) {\n const routes = this._routes.get(request.method) || [];\n for (const route of routes) {\n let params;\n // route.match returns type any, not possible to change right now.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const matchResult = route.match({ url, sameOrigin, request, event });\n if (matchResult) {\n if (process.env.NODE_ENV !== 'production') {\n // Warn developers that using an async matchCallback is almost always\n // not the right thing to do.\n if (matchResult instanceof Promise) {\n logger.warn(`While routing ${getFriendlyURL(url)}, an async ` +\n `matchCallback function was used. Please convert the ` +\n `following route to use a synchronous matchCallback function:`, route);\n }\n }\n // See https://github.com/GoogleChrome/workbox/issues/2079\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n params = matchResult;\n if (Array.isArray(params) && params.length === 0) {\n // Instead of passing an empty array in as params, use undefined.\n params = undefined;\n }\n else if (matchResult.constructor === Object && // eslint-disable-line\n Object.keys(matchResult).length === 0) {\n // Instead of passing an empty object in as params, use undefined.\n params = undefined;\n }\n else if (typeof matchResult === 'boolean') {\n // For the boolean value true (rather than just something truth-y),\n // don't set params.\n // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353\n params = undefined;\n }\n // Return early if have a match.\n return { route, params };\n }\n }\n // If no match was found above, return and empty object.\n return {};\n }\n /**\n * Define a default `handler` that's called when no routes explicitly\n * match the incoming request.\n *\n * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.\n *\n * Without a default handler, unmatched requests will go against the\n * network as if there were no service worker present.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {string} [method='GET'] The HTTP method to associate with this\n * default handler. Each method has its own default.\n */\n setDefaultHandler(handler, method = defaultMethod) {\n this._defaultHandlerMap.set(method, normalizeHandler(handler));\n }\n /**\n * If a Route throws an error while handling a request, this `handler`\n * will be called and given a chance to provide a response.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n */\n setCatchHandler(handler) {\n this._catchHandler = normalizeHandler(handler);\n }\n /**\n * Registers a route with the router.\n *\n * @param {workbox-routing.Route} route The route to register.\n */\n registerRoute(route) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(route, 'object', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.hasMethod(route, 'match', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.isType(route.handler, 'object', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.hasMethod(route.handler, 'handle', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route.handler',\n });\n assert.isType(route.method, 'string', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route.method',\n });\n }\n if (!this._routes.has(route.method)) {\n this._routes.set(route.method, []);\n }\n // Give precedence to all of the earlier routes by adding this additional\n // route to the end of the array.\n this._routes.get(route.method).push(route);\n }\n /**\n * Unregisters a route with the router.\n *\n * @param {workbox-routing.Route} route The route to unregister.\n */\n unregisterRoute(route) {\n if (!this._routes.has(route.method)) {\n throw new WorkboxError('unregister-route-but-not-found-with-method', {\n method: route.method,\n });\n }\n const routeIndex = this._routes.get(route.method).indexOf(route);\n if (routeIndex > -1) {\n this._routes.get(route.method).splice(routeIndex, 1);\n }\n else {\n throw new WorkboxError('unregister-route-route-not-registered');\n }\n }\n}\nexport { Router };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Router } from '../Router.js';\nimport '../_version.js';\nlet defaultRouter;\n/**\n * Creates a new, singleton Router instance if one does not exist. If one\n * does already exist, that instance is returned.\n *\n * @private\n * @return {Router}\n */\nexport const getOrCreateDefaultRouter = () => {\n if (!defaultRouter) {\n defaultRouter = new Router();\n // The helpers that use the default Router assume these listeners exist.\n defaultRouter.addFetchListener();\n defaultRouter.addCacheListener();\n }\n return defaultRouter;\n};\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Route } from './Route.js';\nimport { RegExpRoute } from './RegExpRoute.js';\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * Easily register a RegExp, string, or function with a caching\n * strategy to a singleton Router instance.\n *\n * This method will generate a Route for you if needed and\n * call {@link workbox-routing.Router#registerRoute}.\n *\n * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture\n * If the capture param is a `Route`, all other arguments will be ignored.\n * @param {workbox-routing~handlerCallback} [handler] A callback\n * function that returns a Promise resulting in a Response. This parameter\n * is required if `capture` is not a `Route` object.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n * @return {workbox-routing.Route} The generated `Route`.\n *\n * @memberof workbox-routing\n */\nfunction registerRoute(capture, handler, method) {\n let route;\n if (typeof capture === 'string') {\n const captureUrl = new URL(capture, location.href);\n if (process.env.NODE_ENV !== 'production') {\n if (!(capture.startsWith('/') || capture.startsWith('http'))) {\n throw new WorkboxError('invalid-string', {\n moduleName: 'workbox-routing',\n funcName: 'registerRoute',\n paramName: 'capture',\n });\n }\n // We want to check if Express-style wildcards are in the pathname only.\n // TODO: Remove this log message in v4.\n const valueToCheck = capture.startsWith('http')\n ? captureUrl.pathname\n : capture;\n // See https://github.com/pillarjs/path-to-regexp#parameters\n const wildcards = '[*:?+]';\n if (new RegExp(`${wildcards}`).exec(valueToCheck)) {\n logger.debug(`The '$capture' parameter contains an Express-style wildcard ` +\n `character (${wildcards}). Strings are now always interpreted as ` +\n `exact matches; use a RegExp for partial or wildcard matches.`);\n }\n }\n const matchCallback = ({ url }) => {\n if (process.env.NODE_ENV !== 'production') {\n if (url.pathname === captureUrl.pathname &&\n url.origin !== captureUrl.origin) {\n logger.debug(`${capture} only partially matches the cross-origin URL ` +\n `${url.toString()}. This route will only handle cross-origin requests ` +\n `if they match the entire URL.`);\n }\n }\n return url.href === captureUrl.href;\n };\n // If `capture` is a string then `handler` and `method` must be present.\n route = new Route(matchCallback, handler, method);\n }\n else if (capture instanceof RegExp) {\n // If `capture` is a `RegExp` then `handler` and `method` must be present.\n route = new RegExpRoute(capture, handler, method);\n }\n else if (typeof capture === 'function') {\n // If `capture` is a function then `handler` and `method` must be present.\n route = new Route(capture, handler, method);\n }\n else if (capture instanceof Route) {\n route = capture;\n }\n else {\n throw new WorkboxError('unsupported-route-type', {\n moduleName: 'workbox-routing',\n funcName: 'registerRoute',\n paramName: 'capture',\n });\n }\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.registerRoute(route);\n return route;\n}\nexport { registerRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * If a Route throws an error while handling a request, this `handler`\n * will be called and given a chance to provide a response.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n *\n * @memberof workbox-routing\n */\nfunction setCatchHandler(handler) {\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.setCatchHandler(handler);\n}\nexport { setCatchHandler };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * Define a default `handler` that's called when no routes explicitly\n * match the incoming request.\n *\n * Without a default handler, unmatched requests will go against the\n * network as if there were no service worker present.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n *\n * @memberof workbox-routing\n */\nfunction setDefaultHandler(handler) {\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.setDefaultHandler(handler);\n}\nexport { setDefaultHandler };\n"],"names":["self","_","e","defaultMethod","validMethods","normalizeHandler","handler","assert","hasMethod","moduleName","className","funcName","paramName","isType","handle","Route","constructor","match","method","isOneOf","setCatchHandler","catchHandler","NavigationRoute","allowlist","denylist","isArrayOfClass","RegExp","options","_match","_allowlist","_denylist","url","request","mode","pathnameAndSearch","pathname","search","regExp","test","logger","log","toString","some","debug","RegExpRoute","isInstance","result","exec","href","origin","location","index","slice","Router","_routes","Map","_defaultHandlerMap","routes","addFetchListener","addEventListener","event","responsePromise","handleRequest","respondWith","addCacheListener","data","type","payload","urlsToCache","requestPromises","Promise","all","map","entry","Request","waitUntil","ports","then","postMessage","URL","protocol","startsWith","sameOrigin","params","route","findMatchingRoute","debugMessages","push","has","get","getFriendlyURL","groupCollapsed","forEach","msg","Array","isArray","groupEnd","err","reject","_catchHandler","catch","error","catchErr","Error","matchResult","warn","length","undefined","Object","keys","setDefaultHandler","set","registerRoute","unregisterRoute","WorkboxError","routeIndex","indexOf","splice","defaultRouter","getOrCreateDefaultRouter","capture","captureUrl","valueToCheck","wildcards","matchCallback"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,uBAAD,CAAJ,IAAiCC,CAAC,EAAlC;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACO,MAAMC,aAAa,GAAG,KAAtB;IACP;IACA;IACA;IACA;IACA;IACA;IACA;;IACO,MAAMC,YAAY,GAAG,CACxB,QADwB,EAExB,KAFwB,EAGxB,MAHwB,EAIxB,OAJwB,EAKxB,MALwB,EAMxB,KANwB,CAArB;;ICxBP;IACA;AACA;IACA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;;IACO,MAAMC,gBAAgB,GAAIC,OAAD,IAAa;IACzC,MAAIA,OAAO,IAAI,OAAOA,OAAP,KAAmB,QAAlC,EAA4C;IACxC,IAA2C;IACvCC,MAAAA,gBAAM,CAACC,SAAP,CAAiBF,OAAjB,EAA0B,QAA1B,EAAoC;IAChCG,QAAAA,UAAU,EAAE,iBADoB;IAEhCC,QAAAA,SAAS,EAAE,OAFqB;IAGhCC,QAAAA,QAAQ,EAAE,aAHsB;IAIhCC,QAAAA,SAAS,EAAE;IAJqB,OAApC;IAMH;;IACD,WAAON,OAAP;IACH,GAVD,MAWK;IACD,IAA2C;IACvCC,MAAAA,gBAAM,CAACM,MAAP,CAAcP,OAAd,EAAuB,UAAvB,EAAmC;IAC/BG,QAAAA,UAAU,EAAE,iBADmB;IAE/BC,QAAAA,SAAS,EAAE,OAFoB;IAG/BC,QAAAA,QAAQ,EAAE,aAHqB;IAI/BC,QAAAA,SAAS,EAAE;IAJoB,OAAnC;IAMH;;IACD,WAAO;IAAEE,MAAAA,MAAM,EAAER;IAAV,KA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FI,MAGA;IACD,UAAM,IAAIN,4BAAJ,CAAiB,wBAAjB,EAA2C;IAC7CzG,MAAAA,UAAU,EAAE,iBADiC;IAE7CE,MAAAA,QAAQ,EAAE,eAFmC;IAG7CC,MAAAA,SAAS,EAAE;IAHkC,KAA3C,CAAN;IAKH;;IACD,QAAM0G,aAAa,GAAGC,wBAAwB,EAA9C;IACAD,EAAAA,aAAa,CAACN,aAAd,CAA4B5B,KAA5B;IACA,SAAOA,KAAP;IACH;;IC3FD;IACA;AACA;IACA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAAShE,eAAT,CAAyBd,OAAzB,EAAkC;IAC9B,QAAMgH,aAAa,GAAGC,wBAAwB,EAA9C;IACAD,EAAAA,aAAa,CAAClG,eAAd,CAA8Bd,OAA9B;IACH;;ICrBD;IACA;AACA;IACA;IACA;IACA;IACA;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASwG,iBAAT,CAA2BxG,OAA3B,EAAoC;IAChC,QAAMgH,aAAa,GAAGC,wBAAwB,EAA9C;IACAD,EAAAA,aAAa,CAACR,iBAAd,CAAgCxG,OAAhC;IACH;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-routing.prod.js b/src/Resources/workbox-v7.0.0/workbox-routing.prod.js new file mode 100644 index 0000000..aff7435 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-routing.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.routing=function(t,e){"use strict";try{self["workbox:routing:7.0.0"]&&_()}catch(t){}const s=t=>t&&"object"==typeof t?t:{handle:t};class r{constructor(t,e,r="GET"){this.handler=s(e),this.match=t,this.method=r}setCatchHandler(t){this.catchHandler=s(t)}}class n extends r{constructor(t,e,s){super((({url:e})=>{const s=t.exec(e.href);if(s&&(e.origin===location.origin||0===s.index))return s.slice(1)}),e,s)}}class i{constructor(){this.ft=new Map,this.dt=new Map}get routes(){return this.ft}addFetchListener(){self.addEventListener("fetch",(t=>{const{request:e}=t,s=this.handleRequest({request:e,event:t});s&&t.respondWith(s)}))}addCacheListener(){self.addEventListener("message",(t=>{if(t.data&&"CACHE_URLS"===t.data.type){const{payload:e}=t.data,s=Promise.all(e.urlsToCache.map((e=>{"string"==typeof e&&(e=[e]);const s=new Request(...e);return this.handleRequest({request:s,event:t})})));t.waitUntil(s),t.ports&&t.ports[0]&&s.then((()=>t.ports[0].postMessage(!0)))}}))}handleRequest({request:t,event:e}){const s=new URL(t.url,location.href);if(!s.protocol.startsWith("http"))return;const r=s.origin===location.origin,{params:n,route:i}=this.findMatchingRoute({event:e,request:t,sameOrigin:r,url:s});let o=i&&i.handler;const u=t.method;if(!o&&this.dt.has(u)&&(o=this.dt.get(u)),!o)return;let c;try{c=o.handle({url:s,request:t,event:e,params:n})}catch(t){c=Promise.reject(t)}const a=i&&i.catchHandler;return c instanceof Promise&&(this.wt||a)&&(c=c.catch((async r=>{if(a)try{return await a.handle({url:s,request:t,event:e,params:n})}catch(t){t instanceof Error&&(r=t)}if(this.wt)return this.wt.handle({url:s,request:t,event:e});throw r}))),c}findMatchingRoute({url:t,sameOrigin:e,request:s,event:r}){const n=this.ft.get(s.method)||[];for(const i of n){let n;const o=i.match({url:t,sameOrigin:e,request:s,event:r});if(o)return n=o,(Array.isArray(n)&&0===n.length||o.constructor===Object&&0===Object.keys(o).length||"boolean"==typeof o)&&(n=void 0),{route:i,params:n}}return{}}setDefaultHandler(t,e="GET"){this.dt.set(e,s(t))}setCatchHandler(t){this.wt=s(t)}registerRoute(t){this.ft.has(t.method)||this.ft.set(t.method,[]),this.ft.get(t.method).push(t)}unregisterRoute(t){if(!this.ft.has(t.method))throw new e.WorkboxError("unregister-route-but-not-found-with-method",{method:t.method});const s=this.ft.get(t.method).indexOf(t);if(!(s>-1))throw new e.WorkboxError("unregister-route-route-not-registered");this.ft.get(t.method).splice(s,1)}}let o;const u=()=>(o||(o=new i,o.addFetchListener(),o.addCacheListener()),o);return t.NavigationRoute=class extends r{constructor(t,{allowlist:e=[/./],denylist:s=[]}={}){super((t=>this.gt(t)),t),this.qt=e,this.yt=s}gt({url:t,request:e}){if(e&&"navigate"!==e.mode)return!1;const s=t.pathname+t.search;for(const t of this.yt)if(t.test(s))return!1;return!!this.qt.some((t=>t.test(s)))}},t.RegExpRoute=n,t.Route=r,t.Router=i,t.registerRoute=function(t,s,i){let o;if("string"==typeof t){const e=new URL(t,location.href);o=new r((({url:t})=>t.href===e.href),s,i)}else if(t instanceof RegExp)o=new n(t,s,i);else if("function"==typeof t)o=new r(t,s,i);else{if(!(t instanceof r))throw new e.WorkboxError("unsupported-route-type",{moduleName:"workbox-routing",funcName:"registerRoute",paramName:"capture"});o=t}return u().registerRoute(o),o},t.setCatchHandler=function(t){u().setCatchHandler(t)},t.setDefaultHandler=function(t){u().setDefaultHandler(t)},t}({},workbox.core._private); +//# sourceMappingURL=workbox-routing.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-routing.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-routing.prod.js.map new file mode 100644 index 0000000..b1348de --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-routing.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-routing.prod.js","sources":["../_version.js","../utils/constants.js","../utils/normalizeHandler.js","../Route.js","../RegExpRoute.js","../Router.js","../utils/getOrCreateDefaultRouter.js","../NavigationRoute.js","../registerRoute.js","../setCatchHandler.js","../setDefaultHandler.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:routing:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The default HTTP method, 'GET', used when there's no specific method\n * configured for a route.\n *\n * @type {string}\n *\n * @private\n */\nexport const defaultMethod = 'GET';\n/**\n * The list of valid HTTP methods associated with requests that could be routed.\n *\n * @type {Array}\n *\n * @private\n */\nexport const validMethods = [\n 'DELETE',\n 'GET',\n 'HEAD',\n 'PATCH',\n 'POST',\n 'PUT',\n];\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport '../_version.js';\n/**\n * @param {function()|Object} handler Either a function, or an object with a\n * 'handle' method.\n * @return {Object} An object with a handle method.\n *\n * @private\n */\nexport const normalizeHandler = (handler) => {\n if (handler && typeof handler === 'object') {\n if (process.env.NODE_ENV !== 'production') {\n assert.hasMethod(handler, 'handle', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'handler',\n });\n }\n return handler;\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(handler, 'function', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'handler',\n });\n }\n return { handle: handler };\n }\n};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { defaultMethod, validMethods } from './utils/constants.js';\nimport { normalizeHandler } from './utils/normalizeHandler.js';\nimport './_version.js';\n/**\n * A `Route` consists of a pair of callback functions, \"match\" and \"handler\".\n * The \"match\" callback determine if a route should be used to \"handle\" a\n * request by returning a non-falsy value if it can. The \"handler\" callback\n * is called when there is a match and should return a Promise that resolves\n * to a `Response`.\n *\n * @memberof workbox-routing\n */\nclass Route {\n /**\n * Constructor for Route class.\n *\n * @param {workbox-routing~matchCallback} match\n * A callback function that determines whether the route matches a given\n * `fetch` event by returning a non-falsy value.\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resolving to a Response.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n */\n constructor(match, handler, method = defaultMethod) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(match, 'function', {\n moduleName: 'workbox-routing',\n className: 'Route',\n funcName: 'constructor',\n paramName: 'match',\n });\n if (method) {\n assert.isOneOf(method, validMethods, { paramName: 'method' });\n }\n }\n // These values are referenced directly by Router so cannot be\n // altered by minificaton.\n this.handler = normalizeHandler(handler);\n this.match = match;\n this.method = method;\n }\n /**\n *\n * @param {workbox-routing-handlerCallback} handler A callback\n * function that returns a Promise resolving to a Response\n */\n setCatchHandler(handler) {\n this.catchHandler = normalizeHandler(handler);\n }\n}\nexport { Route };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from './Route.js';\nimport './_version.js';\n/**\n * RegExpRoute makes it easy to create a regular expression based\n * {@link workbox-routing.Route}.\n *\n * For same-origin requests the RegExp only needs to match part of the URL. For\n * requests against third-party servers, you must define a RegExp that matches\n * the start of the URL.\n *\n * @memberof workbox-routing\n * @extends workbox-routing.Route\n */\nclass RegExpRoute extends Route {\n /**\n * If the regular expression contains\n * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},\n * the captured values will be passed to the\n * {@link workbox-routing~handlerCallback} `params`\n * argument.\n *\n * @param {RegExp} regExp The regular expression to match against URLs.\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n */\n constructor(regExp, handler, method) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(regExp, RegExp, {\n moduleName: 'workbox-routing',\n className: 'RegExpRoute',\n funcName: 'constructor',\n paramName: 'pattern',\n });\n }\n const match = ({ url }) => {\n const result = regExp.exec(url.href);\n // Return immediately if there's no match.\n if (!result) {\n return;\n }\n // Require that the match start at the first character in the URL string\n // if it's a cross-origin request.\n // See https://github.com/GoogleChrome/workbox/issues/281 for the context\n // behind this behavior.\n if (url.origin !== location.origin && result.index !== 0) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` +\n `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` +\n `handle cross-origin requests if they match the entire URL.`);\n }\n return;\n }\n // If the route matches, but there aren't any capture groups defined, then\n // this will return [], which is truthy and therefore sufficient to\n // indicate a match.\n // If there are capture groups, then it will return their values.\n return result.slice(1);\n };\n super(match, handler, method);\n }\n}\nexport { RegExpRoute };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { defaultMethod } from './utils/constants.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { normalizeHandler } from './utils/normalizeHandler.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\n/**\n * The Router can be used to process a `FetchEvent` using one or more\n * {@link workbox-routing.Route}, responding with a `Response` if\n * a matching route exists.\n *\n * If no route matches a given a request, the Router will use a \"default\"\n * handler if one is defined.\n *\n * Should the matching Route throw an error, the Router will use a \"catch\"\n * handler if one is defined to gracefully deal with issues and respond with a\n * Request.\n *\n * If a request matches multiple routes, the **earliest** registered route will\n * be used to respond to the request.\n *\n * @memberof workbox-routing\n */\nclass Router {\n /**\n * Initializes a new Router.\n */\n constructor() {\n this._routes = new Map();\n this._defaultHandlerMap = new Map();\n }\n /**\n * @return {Map>} routes A `Map` of HTTP\n * method name ('GET', etc.) to an array of all the corresponding `Route`\n * instances that are registered.\n */\n get routes() {\n return this._routes;\n }\n /**\n * Adds a fetch event listener to respond to events when a route matches\n * the event's request.\n */\n addFetchListener() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('fetch', ((event) => {\n const { request } = event;\n const responsePromise = this.handleRequest({ request, event });\n if (responsePromise) {\n event.respondWith(responsePromise);\n }\n }));\n }\n /**\n * Adds a message event listener for URLs to cache from the window.\n * This is useful to cache resources loaded on the page prior to when the\n * service worker started controlling it.\n *\n * The format of the message data sent from the window should be as follows.\n * Where the `urlsToCache` array may consist of URL strings or an array of\n * URL string + `requestInit` object (the same as you'd pass to `fetch()`).\n *\n * ```\n * {\n * type: 'CACHE_URLS',\n * payload: {\n * urlsToCache: [\n * './script1.js',\n * './script2.js',\n * ['./script3.js', {mode: 'no-cors'}],\n * ],\n * },\n * }\n * ```\n */\n addCacheListener() {\n // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705\n self.addEventListener('message', ((event) => {\n // event.data is type 'any'\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (event.data && event.data.type === 'CACHE_URLS') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { payload } = event.data;\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Caching URLs from the window`, payload.urlsToCache);\n }\n const requestPromises = Promise.all(payload.urlsToCache.map((entry) => {\n if (typeof entry === 'string') {\n entry = [entry];\n }\n const request = new Request(...entry);\n return this.handleRequest({ request, event });\n // TODO(philipwalton): TypeScript errors without this typecast for\n // some reason (probably a bug). The real type here should work but\n // doesn't: `Array | undefined>`.\n })); // TypeScript\n event.waitUntil(requestPromises);\n // If a MessageChannel was used, reply to the message on success.\n if (event.ports && event.ports[0]) {\n void requestPromises.then(() => event.ports[0].postMessage(true));\n }\n }\n }));\n }\n /**\n * Apply the routing rules to a FetchEvent object to get a Response from an\n * appropriate Route's handler.\n *\n * @param {Object} options\n * @param {Request} options.request The request to handle.\n * @param {ExtendableEvent} options.event The event that triggered the\n * request.\n * @return {Promise|undefined} A promise is returned if a\n * registered route can handle the request. If there is no matching\n * route and there's no `defaultHandler`, `undefined` is returned.\n */\n handleRequest({ request, event, }) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'handleRequest',\n paramName: 'options.request',\n });\n }\n const url = new URL(request.url, location.href);\n if (!url.protocol.startsWith('http')) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Workbox Router only supports URLs that start with 'http'.`);\n }\n return;\n }\n const sameOrigin = url.origin === location.origin;\n const { params, route } = this.findMatchingRoute({\n event,\n request,\n sameOrigin,\n url,\n });\n let handler = route && route.handler;\n const debugMessages = [];\n if (process.env.NODE_ENV !== 'production') {\n if (handler) {\n debugMessages.push([`Found a route to handle this request:`, route]);\n if (params) {\n debugMessages.push([\n `Passing the following params to the route's handler:`,\n params,\n ]);\n }\n }\n }\n // If we don't have a handler because there was no matching route, then\n // fall back to defaultHandler if that's defined.\n const method = request.method;\n if (!handler && this._defaultHandlerMap.has(method)) {\n if (process.env.NODE_ENV !== 'production') {\n debugMessages.push(`Failed to find a matching route. Falling ` +\n `back to the default handler for ${method}.`);\n }\n handler = this._defaultHandlerMap.get(method);\n }\n if (!handler) {\n if (process.env.NODE_ENV !== 'production') {\n // No handler so Workbox will do nothing. If logs is set of debug\n // i.e. verbose, we should print out this information.\n logger.debug(`No route found for: ${getFriendlyURL(url)}`);\n }\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // We have a handler, meaning Workbox is going to handle the route.\n // print the routing details to the console.\n logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);\n debugMessages.forEach((msg) => {\n if (Array.isArray(msg)) {\n logger.log(...msg);\n }\n else {\n logger.log(msg);\n }\n });\n logger.groupEnd();\n }\n // Wrap in try and catch in case the handle method throws a synchronous\n // error. It should still callback to the catch handler.\n let responsePromise;\n try {\n responsePromise = handler.handle({ url, request, event, params });\n }\n catch (err) {\n responsePromise = Promise.reject(err);\n }\n // Get route's catch handler, if it exists\n const catchHandler = route && route.catchHandler;\n if (responsePromise instanceof Promise &&\n (this._catchHandler || catchHandler)) {\n responsePromise = responsePromise.catch(async (err) => {\n // If there's a route catch handler, process that first\n if (catchHandler) {\n if (process.env.NODE_ENV !== 'production') {\n // Still include URL here as it will be async from the console group\n // and may not make sense without the URL\n logger.groupCollapsed(`Error thrown when responding to: ` +\n ` ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);\n logger.error(`Error thrown by:`, route);\n logger.error(err);\n logger.groupEnd();\n }\n try {\n return await catchHandler.handle({ url, request, event, params });\n }\n catch (catchErr) {\n if (catchErr instanceof Error) {\n err = catchErr;\n }\n }\n }\n if (this._catchHandler) {\n if (process.env.NODE_ENV !== 'production') {\n // Still include URL here as it will be async from the console group\n // and may not make sense without the URL\n logger.groupCollapsed(`Error thrown when responding to: ` +\n ` ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);\n logger.error(`Error thrown by:`, route);\n logger.error(err);\n logger.groupEnd();\n }\n return this._catchHandler.handle({ url, request, event });\n }\n throw err;\n });\n }\n return responsePromise;\n }\n /**\n * Checks a request and URL (and optionally an event) against the list of\n * registered routes, and if there's a match, returns the corresponding\n * route along with any params generated by the match.\n *\n * @param {Object} options\n * @param {URL} options.url\n * @param {boolean} options.sameOrigin The result of comparing `url.origin`\n * against the current origin.\n * @param {Request} options.request The request to match.\n * @param {Event} options.event The corresponding event.\n * @return {Object} An object with `route` and `params` properties.\n * They are populated if a matching route was found or `undefined`\n * otherwise.\n */\n findMatchingRoute({ url, sameOrigin, request, event, }) {\n const routes = this._routes.get(request.method) || [];\n for (const route of routes) {\n let params;\n // route.match returns type any, not possible to change right now.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const matchResult = route.match({ url, sameOrigin, request, event });\n if (matchResult) {\n if (process.env.NODE_ENV !== 'production') {\n // Warn developers that using an async matchCallback is almost always\n // not the right thing to do.\n if (matchResult instanceof Promise) {\n logger.warn(`While routing ${getFriendlyURL(url)}, an async ` +\n `matchCallback function was used. Please convert the ` +\n `following route to use a synchronous matchCallback function:`, route);\n }\n }\n // See https://github.com/GoogleChrome/workbox/issues/2079\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n params = matchResult;\n if (Array.isArray(params) && params.length === 0) {\n // Instead of passing an empty array in as params, use undefined.\n params = undefined;\n }\n else if (matchResult.constructor === Object && // eslint-disable-line\n Object.keys(matchResult).length === 0) {\n // Instead of passing an empty object in as params, use undefined.\n params = undefined;\n }\n else if (typeof matchResult === 'boolean') {\n // For the boolean value true (rather than just something truth-y),\n // don't set params.\n // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353\n params = undefined;\n }\n // Return early if have a match.\n return { route, params };\n }\n }\n // If no match was found above, return and empty object.\n return {};\n }\n /**\n * Define a default `handler` that's called when no routes explicitly\n * match the incoming request.\n *\n * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.\n *\n * Without a default handler, unmatched requests will go against the\n * network as if there were no service worker present.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {string} [method='GET'] The HTTP method to associate with this\n * default handler. Each method has its own default.\n */\n setDefaultHandler(handler, method = defaultMethod) {\n this._defaultHandlerMap.set(method, normalizeHandler(handler));\n }\n /**\n * If a Route throws an error while handling a request, this `handler`\n * will be called and given a chance to provide a response.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n */\n setCatchHandler(handler) {\n this._catchHandler = normalizeHandler(handler);\n }\n /**\n * Registers a route with the router.\n *\n * @param {workbox-routing.Route} route The route to register.\n */\n registerRoute(route) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(route, 'object', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.hasMethod(route, 'match', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.isType(route.handler, 'object', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route',\n });\n assert.hasMethod(route.handler, 'handle', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route.handler',\n });\n assert.isType(route.method, 'string', {\n moduleName: 'workbox-routing',\n className: 'Router',\n funcName: 'registerRoute',\n paramName: 'route.method',\n });\n }\n if (!this._routes.has(route.method)) {\n this._routes.set(route.method, []);\n }\n // Give precedence to all of the earlier routes by adding this additional\n // route to the end of the array.\n this._routes.get(route.method).push(route);\n }\n /**\n * Unregisters a route with the router.\n *\n * @param {workbox-routing.Route} route The route to unregister.\n */\n unregisterRoute(route) {\n if (!this._routes.has(route.method)) {\n throw new WorkboxError('unregister-route-but-not-found-with-method', {\n method: route.method,\n });\n }\n const routeIndex = this._routes.get(route.method).indexOf(route);\n if (routeIndex > -1) {\n this._routes.get(route.method).splice(routeIndex, 1);\n }\n else {\n throw new WorkboxError('unregister-route-route-not-registered');\n }\n }\n}\nexport { Router };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Router } from '../Router.js';\nimport '../_version.js';\nlet defaultRouter;\n/**\n * Creates a new, singleton Router instance if one does not exist. If one\n * does already exist, that instance is returned.\n *\n * @private\n * @return {Router}\n */\nexport const getOrCreateDefaultRouter = () => {\n if (!defaultRouter) {\n defaultRouter = new Router();\n // The helpers that use the default Router assume these listeners exist.\n defaultRouter.addFetchListener();\n defaultRouter.addCacheListener();\n }\n return defaultRouter;\n};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { Route } from './Route.js';\nimport './_version.js';\n/**\n * NavigationRoute makes it easy to create a\n * {@link workbox-routing.Route} that matches for browser\n * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.\n *\n * It will only match incoming Requests whose\n * {@link https://fetch.spec.whatwg.org/#concept-request-mode|mode}\n * is set to `navigate`.\n *\n * You can optionally only apply this route to a subset of navigation requests\n * by using one or both of the `denylist` and `allowlist` parameters.\n *\n * @memberof workbox-routing\n * @extends workbox-routing.Route\n */\nclass NavigationRoute extends Route {\n /**\n * If both `denylist` and `allowlist` are provided, the `denylist` will\n * take precedence and the request will not match this route.\n *\n * The regular expressions in `allowlist` and `denylist`\n * are matched against the concatenated\n * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}\n * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}\n * portions of the requested URL.\n *\n * *Note*: These RegExps may be evaluated against every destination URL during\n * a navigation. Avoid using\n * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\n * or else your users may see delays when navigating your site.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n * @param {Object} options\n * @param {Array} [options.denylist] If any of these patterns match,\n * the route will not handle the request (even if a allowlist RegExp matches).\n * @param {Array} [options.allowlist=[/./]] If any of these patterns\n * match the URL's pathname and search parameter, the route will handle the\n * request (assuming the denylist doesn't match).\n */\n constructor(handler, { allowlist = [/./], denylist = [] } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArrayOfClass(allowlist, RegExp, {\n moduleName: 'workbox-routing',\n className: 'NavigationRoute',\n funcName: 'constructor',\n paramName: 'options.allowlist',\n });\n assert.isArrayOfClass(denylist, RegExp, {\n moduleName: 'workbox-routing',\n className: 'NavigationRoute',\n funcName: 'constructor',\n paramName: 'options.denylist',\n });\n }\n super((options) => this._match(options), handler);\n this._allowlist = allowlist;\n this._denylist = denylist;\n }\n /**\n * Routes match handler.\n *\n * @param {Object} options\n * @param {URL} options.url\n * @param {Request} options.request\n * @return {boolean}\n *\n * @private\n */\n _match({ url, request }) {\n if (request && request.mode !== 'navigate') {\n return false;\n }\n const pathnameAndSearch = url.pathname + url.search;\n for (const regExp of this._denylist) {\n if (regExp.test(pathnameAndSearch)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The navigation route ${pathnameAndSearch} is not ` +\n `being used, since the URL matches this denylist pattern: ` +\n `${regExp.toString()}`);\n }\n return false;\n }\n }\n if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`The navigation route ${pathnameAndSearch} ` + `is being used.`);\n }\n return true;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The navigation route ${pathnameAndSearch} is not ` +\n `being used, since the URL being navigated to doesn't ` +\n `match the allowlist.`);\n }\n return false;\n }\n}\nexport { NavigationRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Route } from './Route.js';\nimport { RegExpRoute } from './RegExpRoute.js';\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * Easily register a RegExp, string, or function with a caching\n * strategy to a singleton Router instance.\n *\n * This method will generate a Route for you if needed and\n * call {@link workbox-routing.Router#registerRoute}.\n *\n * @param {RegExp|string|workbox-routing.Route~matchCallback|workbox-routing.Route} capture\n * If the capture param is a `Route`, all other arguments will be ignored.\n * @param {workbox-routing~handlerCallback} [handler] A callback\n * function that returns a Promise resulting in a Response. This parameter\n * is required if `capture` is not a `Route` object.\n * @param {string} [method='GET'] The HTTP method to match the Route\n * against.\n * @return {workbox-routing.Route} The generated `Route`.\n *\n * @memberof workbox-routing\n */\nfunction registerRoute(capture, handler, method) {\n let route;\n if (typeof capture === 'string') {\n const captureUrl = new URL(capture, location.href);\n if (process.env.NODE_ENV !== 'production') {\n if (!(capture.startsWith('/') || capture.startsWith('http'))) {\n throw new WorkboxError('invalid-string', {\n moduleName: 'workbox-routing',\n funcName: 'registerRoute',\n paramName: 'capture',\n });\n }\n // We want to check if Express-style wildcards are in the pathname only.\n // TODO: Remove this log message in v4.\n const valueToCheck = capture.startsWith('http')\n ? captureUrl.pathname\n : capture;\n // See https://github.com/pillarjs/path-to-regexp#parameters\n const wildcards = '[*:?+]';\n if (new RegExp(`${wildcards}`).exec(valueToCheck)) {\n logger.debug(`The '$capture' parameter contains an Express-style wildcard ` +\n `character (${wildcards}). Strings are now always interpreted as ` +\n `exact matches; use a RegExp for partial or wildcard matches.`);\n }\n }\n const matchCallback = ({ url }) => {\n if (process.env.NODE_ENV !== 'production') {\n if (url.pathname === captureUrl.pathname &&\n url.origin !== captureUrl.origin) {\n logger.debug(`${capture} only partially matches the cross-origin URL ` +\n `${url.toString()}. This route will only handle cross-origin requests ` +\n `if they match the entire URL.`);\n }\n }\n return url.href === captureUrl.href;\n };\n // If `capture` is a string then `handler` and `method` must be present.\n route = new Route(matchCallback, handler, method);\n }\n else if (capture instanceof RegExp) {\n // If `capture` is a `RegExp` then `handler` and `method` must be present.\n route = new RegExpRoute(capture, handler, method);\n }\n else if (typeof capture === 'function') {\n // If `capture` is a function then `handler` and `method` must be present.\n route = new Route(capture, handler, method);\n }\n else if (capture instanceof Route) {\n route = capture;\n }\n else {\n throw new WorkboxError('unsupported-route-type', {\n moduleName: 'workbox-routing',\n funcName: 'registerRoute',\n paramName: 'capture',\n });\n }\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.registerRoute(route);\n return route;\n}\nexport { registerRoute };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * If a Route throws an error while handling a request, this `handler`\n * will be called and given a chance to provide a response.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n *\n * @memberof workbox-routing\n */\nfunction setCatchHandler(handler) {\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.setCatchHandler(handler);\n}\nexport { setCatchHandler };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { getOrCreateDefaultRouter } from './utils/getOrCreateDefaultRouter.js';\nimport './_version.js';\n/**\n * Define a default `handler` that's called when no routes explicitly\n * match the incoming request.\n *\n * Without a default handler, unmatched requests will go against the\n * network as if there were no service worker present.\n *\n * @param {workbox-routing~handlerCallback} handler A callback\n * function that returns a Promise resulting in a Response.\n *\n * @memberof workbox-routing\n */\nfunction setDefaultHandler(handler) {\n const defaultRouter = getOrCreateDefaultRouter();\n defaultRouter.setDefaultHandler(handler);\n}\nexport { setDefaultHandler };\n"],"names":["self","_","e","normalizeHandler","handler","handle","Route","constructor","match","method","setCatchHandler","catchHandler","RegExpRoute","regExp","url","result","exec","href","origin","location","index","slice","Router","_routes","Map","_defaultHandlerMap","routes","this","addFetchListener","addEventListener","event","request","responsePromise","handleRequest","respondWith","addCacheListener","data","type","payload","requestPromises","Promise","all","urlsToCache","map","entry","Request","waitUntil","ports","then","postMessage","URL","protocol","startsWith","sameOrigin","params","route","findMatchingRoute","has","get","err","reject","_catchHandler","catch","async","catchErr","Error","matchResult","Array","isArray","length","Object","keys","undefined","setDefaultHandler","set","registerRoute","push","unregisterRoute","WorkboxError","routeIndex","indexOf","splice","defaultRouter","getOrCreateDefaultRouter","allowlist","denylist","options","_match","_allowlist","_denylist","mode","pathnameAndSearch","pathname","search","test","some","capture","captureUrl","RegExp","moduleName","funcName","paramName"],"mappings":"8EAEA,IACIA,KAAK,0BAA4BC,GACpC,CACD,MAAOC,ICWA,MCAMC,EAAoBC,GACzBA,GAA8B,iBAAZA,EASXA,EAWA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AcpB,GACrBA,CACV,oBCzED,SAAyBnD,GACC+E,IACRzE,gBAAgBN,EACjC,sBCAD,SAA2BA,GACD+E,IACRV,kBAAkBrE,EACnC"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-strategies.dev.js b/src/Resources/workbox-v7.0.0/workbox-strategies.dev.js new file mode 100644 index 0000000..5cdd0d4 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-strategies.dev.js @@ -0,0 +1,1509 @@ +this.workbox = this.workbox || {}; +this.workbox.strategies = (function (exports, assert_js, logger_js, WorkboxError_js, cacheNames_js, getFriendlyURL_js, cacheMatchIgnoreParams_js, Deferred_js, executeQuotaErrorCallbacks_js, timeout_js) { + 'use strict'; + + try { + self['workbox:strategies:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + + function toRequest(input) { + return typeof input === 'string' ? new Request(input) : input; + } + /** + * A class created every time a Strategy instance instance calls + * {@link workbox-strategies.Strategy~handle} or + * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and + * cache actions around plugin callbacks and keeps track of when the strategy + * is "done" (i.e. all added `event.waitUntil()` promises have resolved). + * + * @memberof workbox-strategies + */ + + + class StrategyHandler { + /** + * Creates a new instance associated with the passed strategy and event + * that's handling the request. + * + * The constructor also initializes the state that will be passed to each of + * the plugins handling this request. + * + * @param {workbox-strategies.Strategy} strategy + * @param {Object} options + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] The return value from the + * {@link workbox-routing~matchCallback} (if applicable). + */ + constructor(strategy, options) { + this._cacheKeys = {}; + /** + * The request the strategy is performing (passed to the strategy's + * `handle()` or `handleAll()` method). + * @name request + * @instance + * @type {Request} + * @memberof workbox-strategies.StrategyHandler + */ + + /** + * The event associated with this request. + * @name event + * @instance + * @type {ExtendableEvent} + * @memberof workbox-strategies.StrategyHandler + */ + + /** + * A `URL` instance of `request.url` (if passed to the strategy's + * `handle()` or `handleAll()` method). + * Note: the `url` param will be present if the strategy was invoked + * from a workbox `Route` object. + * @name url + * @instance + * @type {URL|undefined} + * @memberof workbox-strategies.StrategyHandler + */ + + /** + * A `param` value (if passed to the strategy's + * `handle()` or `handleAll()` method). + * Note: the `param` param will be present if the strategy was invoked + * from a workbox `Route` object and the + * {@link workbox-routing~matchCallback} returned + * a truthy value (it will be that value). + * @name params + * @instance + * @type {*|undefined} + * @memberof workbox-strategies.StrategyHandler + */ + + { + assert_js.assert.isInstance(options.event, ExtendableEvent, { + moduleName: 'workbox-strategies', + className: 'StrategyHandler', + funcName: 'constructor', + paramName: 'options.event' + }); + } + + Object.assign(this, options); + this.event = options.event; + this._strategy = strategy; + this._handlerDeferred = new Deferred_js.Deferred(); + this._extendLifetimePromises = []; // Copy the plugins list (since it's mutable on the strategy), + // so any mutations don't affect this handler instance. + + this._plugins = [...strategy.plugins]; + this._pluginStateMap = new Map(); + + for (const plugin of this._plugins) { + this._pluginStateMap.set(plugin, {}); + } + + this.event.waitUntil(this._handlerDeferred.promise); + } + /** + * Fetches a given request (and invokes any applicable plugin callback + * methods) using the `fetchOptions` (for non-navigation requests) and + * `plugins` defined on the `Strategy` object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - `requestWillFetch()` + * - `fetchDidSucceed()` + * - `fetchDidFail()` + * + * @param {Request|string} input The URL or request to fetch. + * @return {Promise} + */ + + + async fetch(input) { + const { + event + } = this; + let request = toRequest(input); + + if (request.mode === 'navigate' && event instanceof FetchEvent && event.preloadResponse) { + const possiblePreloadResponse = await event.preloadResponse; + + if (possiblePreloadResponse) { + { + logger_js.logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL_js.getFriendlyURL(request.url)}'`); + } + + return possiblePreloadResponse; + } + } // If there is a fetchDidFail plugin, we need to save a clone of the + // original request before it's either modified by a requestWillFetch + // plugin or before the original request's body is consumed via fetch(). + + + const originalRequest = this.hasCallback('fetchDidFail') ? request.clone() : null; + + try { + for (const cb of this.iterateCallbacks('requestWillFetch')) { + request = await cb({ + request: request.clone(), + event + }); + } + } catch (err) { + if (err instanceof Error) { + throw new WorkboxError_js.WorkboxError('plugin-error-request-will-fetch', { + thrownErrorMessage: err.message + }); + } + } // The request can be altered by plugins with `requestWillFetch` making + // the original request (most likely from a `fetch` event) different + // from the Request we make. Pass both to `fetchDidFail` to aid debugging. + + + const pluginFilteredRequest = request.clone(); + + try { + let fetchResponse; // See https://github.com/GoogleChrome/workbox/issues/1796 + + fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions); + + if ("dev" !== 'production') { + logger_js.logger.debug(`Network request for ` + `'${getFriendlyURL_js.getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`); + } + + for (const callback of this.iterateCallbacks('fetchDidSucceed')) { + fetchResponse = await callback({ + event, + request: pluginFilteredRequest, + response: fetchResponse + }); + } + + return fetchResponse; + } catch (error) { + { + logger_js.logger.log(`Network request for ` + `'${getFriendlyURL_js.getFriendlyURL(request.url)}' threw an error.`, error); + } // `originalRequest` will only exist if a `fetchDidFail` callback + // is being used (see above). + + + if (originalRequest) { + await this.runCallbacks('fetchDidFail', { + error: error, + event, + originalRequest: originalRequest.clone(), + request: pluginFilteredRequest.clone() + }); + } + + throw error; + } + } + /** + * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on + * the response generated by `this.fetch()`. + * + * The call to `this.cachePut()` automatically invokes `this.waitUntil()`, + * so you do not have to manually call `waitUntil()` on the event. + * + * @param {Request|string} input The request or URL to fetch and cache. + * @return {Promise} + */ + + + async fetchAndCachePut(input) { + const response = await this.fetch(input); + const responseClone = response.clone(); + void this.waitUntil(this.cachePut(input, responseClone)); + return response; + } + /** + * Matches a request from the cache (and invokes any applicable plugin + * callback methods) using the `cacheName`, `matchOptions`, and `plugins` + * defined on the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillByUsed() + * - cachedResponseWillByUsed() + * + * @param {Request|string} key The Request or URL to use as the cache key. + * @return {Promise} A matching response, if found. + */ + + + async cacheMatch(key) { + const request = toRequest(key); + let cachedResponse; + const { + cacheName, + matchOptions + } = this._strategy; + const effectiveRequest = await this.getCacheKey(request, 'read'); + const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), { + cacheName + }); + cachedResponse = await caches.match(effectiveRequest, multiMatchOptions); + + { + if (cachedResponse) { + logger_js.logger.debug(`Found a cached response in '${cacheName}'.`); + } else { + logger_js.logger.debug(`No cached response found in '${cacheName}'.`); + } + } + + for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) { + cachedResponse = (await callback({ + cacheName, + matchOptions, + cachedResponse, + request: effectiveRequest, + event: this.event + })) || undefined; + } + + return cachedResponse; + } + /** + * Puts a request/response pair in the cache (and invokes any applicable + * plugin callback methods) using the `cacheName` and `plugins` defined on + * the strategy object. + * + * The following plugin lifecycle methods are invoked when using this method: + * - cacheKeyWillByUsed() + * - cacheWillUpdate() + * - cacheDidUpdate() + * + * @param {Request|string} key The request or URL to use as the cache key. + * @param {Response} response The response to cache. + * @return {Promise} `false` if a cacheWillUpdate caused the response + * not be cached, and `true` otherwise. + */ + + + async cachePut(key, response) { + const request = toRequest(key); // Run in the next task to avoid blocking other cache reads. + // https://github.com/w3c/ServiceWorker/issues/1397 + + await timeout_js.timeout(0); + const effectiveRequest = await this.getCacheKey(request, 'write'); + + { + if (effectiveRequest.method && effectiveRequest.method !== 'GET') { + throw new WorkboxError_js.WorkboxError('attempt-to-cache-non-get-request', { + url: getFriendlyURL_js.getFriendlyURL(effectiveRequest.url), + method: effectiveRequest.method + }); + } // See https://github.com/GoogleChrome/workbox/issues/2818 + + + const vary = response.headers.get('Vary'); + + if (vary) { + logger_js.logger.debug(`The response for ${getFriendlyURL_js.getFriendlyURL(effectiveRequest.url)} ` + `has a 'Vary: ${vary}' header. ` + `Consider setting the {ignoreVary: true} option on your strategy ` + `to ensure cache matching and deletion works as expected.`); + } + } + + if (!response) { + { + logger_js.logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL_js.getFriendlyURL(effectiveRequest.url)}'.`); + } + + throw new WorkboxError_js.WorkboxError('cache-put-with-no-response', { + url: getFriendlyURL_js.getFriendlyURL(effectiveRequest.url) + }); + } + + const responseToCache = await this._ensureResponseSafeToCache(response); + + if (!responseToCache) { + { + logger_js.logger.debug(`Response '${getFriendlyURL_js.getFriendlyURL(effectiveRequest.url)}' ` + `will not be cached.`, responseToCache); + } + + return false; + } + + const { + cacheName, + matchOptions + } = this._strategy; + const cache = await self.caches.open(cacheName); + const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate'); + const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams_js.cacheMatchIgnoreParams( // TODO(philipwalton): the `__WB_REVISION__` param is a precaching + // feature. Consider into ways to only add this behavior if using + // precaching. + cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) : null; + + { + logger_js.logger.debug(`Updating the '${cacheName}' cache with a new Response ` + `for ${getFriendlyURL_js.getFriendlyURL(effectiveRequest.url)}.`); + } + + try { + await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache); + } catch (error) { + if (error instanceof Error) { + // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError + if (error.name === 'QuotaExceededError') { + await executeQuotaErrorCallbacks_js.executeQuotaErrorCallbacks(); + } + + throw error; + } + } + + for (const callback of this.iterateCallbacks('cacheDidUpdate')) { + await callback({ + cacheName, + oldResponse, + newResponse: responseToCache.clone(), + request: effectiveRequest, + event: this.event + }); + } + + return true; + } + /** + * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and + * executes any of those callbacks found in sequence. The final `Request` + * object returned by the last plugin is treated as the cache key for cache + * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have + * been registered, the passed request is returned unmodified + * + * @param {Request} request + * @param {string} mode + * @return {Promise} + */ + + + async getCacheKey(request, mode) { + const key = `${request.url} | ${mode}`; + + if (!this._cacheKeys[key]) { + let effectiveRequest = request; + + for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) { + effectiveRequest = toRequest(await callback({ + mode, + request: effectiveRequest, + event: this.event, + // params has a type any can't change right now. + params: this.params // eslint-disable-line + + })); + } + + this._cacheKeys[key] = effectiveRequest; + } + + return this._cacheKeys[key]; + } + /** + * Returns true if the strategy has at least one plugin with the given + * callback. + * + * @param {string} name The name of the callback to check for. + * @return {boolean} + */ + + + hasCallback(name) { + for (const plugin of this._strategy.plugins) { + if (name in plugin) { + return true; + } + } + + return false; + } + /** + * Runs all plugin callbacks matching the given name, in order, passing the + * given param object (merged ith the current plugin state) as the only + * argument. + * + * Note: since this method runs all plugins, it's not suitable for cases + * where the return value of a callback needs to be applied prior to calling + * the next callback. See + * {@link workbox-strategies.StrategyHandler#iterateCallbacks} + * below for how to handle that case. + * + * @param {string} name The name of the callback to run within each plugin. + * @param {Object} param The object to pass as the first (and only) param + * when executing each callback. This object will be merged with the + * current plugin state prior to callback execution. + */ + + + async runCallbacks(name, param) { + for (const callback of this.iterateCallbacks(name)) { + // TODO(philipwalton): not sure why `any` is needed. It seems like + // this should work with `as WorkboxPluginCallbackParam[C]`. + await callback(param); + } + } + /** + * Accepts a callback and returns an iterable of matching plugin callbacks, + * where each callback is wrapped with the current handler state (i.e. when + * you call each callback, whatever object parameter you pass it will + * be merged with the plugin's current state). + * + * @param {string} name The name fo the callback to run + * @return {Array} + */ + + + *iterateCallbacks(name) { + for (const plugin of this._strategy.plugins) { + if (typeof plugin[name] === 'function') { + const state = this._pluginStateMap.get(plugin); + + const statefulCallback = param => { + const statefulParam = Object.assign(Object.assign({}, param), { + state + }); // TODO(philipwalton): not sure why `any` is needed. It seems like + // this should work with `as WorkboxPluginCallbackParam[C]`. + + return plugin[name](statefulParam); + }; + + yield statefulCallback; + } + } + } + /** + * Adds a promise to the + * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises} + * of the event event associated with the request being handled (usually a + * `FetchEvent`). + * + * Note: you can await + * {@link workbox-strategies.StrategyHandler~doneWaiting} + * to know when all added promises have settled. + * + * @param {Promise} promise A promise to add to the extend lifetime promises + * of the event that triggered the request. + */ + + + waitUntil(promise) { + this._extendLifetimePromises.push(promise); + + return promise; + } + /** + * Returns a promise that resolves once all promises passed to + * {@link workbox-strategies.StrategyHandler~waitUntil} + * have settled. + * + * Note: any work done after `doneWaiting()` settles should be manually + * passed to an event's `waitUntil()` method (not this handler's + * `waitUntil()` method), otherwise the service worker thread my be killed + * prior to your work completing. + */ + + + async doneWaiting() { + let promise; + + while (promise = this._extendLifetimePromises.shift()) { + await promise; + } + } + /** + * Stops running the strategy and immediately resolves any pending + * `waitUntil()` promises. + */ + + + destroy() { + this._handlerDeferred.resolve(null); + } + /** + * This method will call cacheWillUpdate on the available plugins (or use + * status === 200) to determine if the Response is safe and valid to cache. + * + * @param {Request} options.request + * @param {Response} options.response + * @return {Promise} + * + * @private + */ + + + async _ensureResponseSafeToCache(response) { + let responseToCache = response; + let pluginsUsed = false; + + for (const callback of this.iterateCallbacks('cacheWillUpdate')) { + responseToCache = (await callback({ + request: this.request, + response: responseToCache, + event: this.event + })) || undefined; + pluginsUsed = true; + + if (!responseToCache) { + break; + } + } + + if (!pluginsUsed) { + if (responseToCache && responseToCache.status !== 200) { + responseToCache = undefined; + } + + { + if (responseToCache) { + if (responseToCache.status !== 200) { + if (responseToCache.status === 0) { + logger_js.logger.warn(`The response for '${this.request.url}' ` + `is an opaque response. The caching strategy that you're ` + `using will not cache opaque responses by default.`); + } else { + logger_js.logger.debug(`The response for '${this.request.url}' ` + `returned a status code of '${response.status}' and won't ` + `be cached as a result.`); + } + } + } + } + } + + return responseToCache; + } + + } + + /* + Copyright 2020 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An abstract base class that all other strategy classes must extend from: + * + * @memberof workbox-strategies + */ + + class Strategy { + /** + * Creates a new instance of the strategy and sets all documented option + * properties as public instance properties. + * + * Note: if a custom strategy class extends the base Strategy class and does + * not need more than these properties, it does not need to define its own + * constructor. + * + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + */ + constructor(options = {}) { + /** + * Cache name to store and retrieve + * requests. Defaults to the cache names provided by + * {@link workbox-core.cacheNames}. + * + * @type {string} + */ + this.cacheName = cacheNames_js.cacheNames.getRuntimeName(options.cacheName); + /** + * The list + * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * used by this strategy. + * + * @type {Array} + */ + + this.plugins = options.plugins || []; + /** + * Values passed along to the + * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters} + * of all fetch() requests made by this strategy. + * + * @type {Object} + */ + + this.fetchOptions = options.fetchOptions; + /** + * The + * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions} + * for any `cache.match()` or `cache.put()` calls made by this strategy. + * + * @type {Object} + */ + + this.matchOptions = options.matchOptions; + } + /** + * Perform a request strategy and returns a `Promise` that will resolve with + * a `Response`, invoking all relevant plugin callbacks. + * + * When a strategy instance is registered with a Workbox + * {@link workbox-routing.Route}, this method is automatically + * called when the route matches. + * + * Alternatively, this method can be used in a standalone `FetchEvent` + * listener by passing it to `event.respondWith()`. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + */ + + + handle(options) { + const [responseDone] = this.handleAll(options); + return responseDone; + } + /** + * Similar to {@link workbox-strategies.Strategy~handle}, but + * instead of just returning a `Promise` that resolves to a `Response` it + * it will return an tuple of `[response, done]` promises, where the former + * (`response`) is equivalent to what `handle()` returns, and the latter is a + * Promise that will resolve once any promises that were added to + * `event.waitUntil()` as part of performing the strategy have completed. + * + * You can await the `done` promise to ensure any extra work performed by + * the strategy (usually caching responses) completes successfully. + * + * @param {FetchEvent|Object} options A `FetchEvent` or an object with the + * properties listed below. + * @param {Request|string} options.request A request to run this strategy for. + * @param {ExtendableEvent} options.event The event associated with the + * request. + * @param {URL} [options.url] + * @param {*} [options.params] + * @return {Array} A tuple of [response, done] + * promises that can be used to determine when the response resolves as + * well as when the handler has completed all its work. + */ + + + handleAll(options) { + // Allow for flexible options to be passed. + if (options instanceof FetchEvent) { + options = { + event: options, + request: options.request + }; + } + + const event = options.event; + const request = typeof options.request === 'string' ? new Request(options.request) : options.request; + const params = 'params' in options ? options.params : undefined; + const handler = new StrategyHandler(this, { + event, + request, + params + }); + + const responseDone = this._getResponse(handler, request, event); + + const handlerDone = this._awaitComplete(responseDone, handler, request, event); // Return an array of promises, suitable for use with Promise.all(). + + + return [responseDone, handlerDone]; + } + + async _getResponse(handler, request, event) { + await handler.runCallbacks('handlerWillStart', { + event, + request + }); + let response = undefined; + + try { + response = await this._handle(request, handler); // The "official" Strategy subclasses all throw this error automatically, + // but in case a third-party Strategy doesn't, ensure that we have a + // consistent failure when there's no response or an error response. + + if (!response || response.type === 'error') { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url + }); + } + } catch (error) { + if (error instanceof Error) { + for (const callback of handler.iterateCallbacks('handlerDidError')) { + response = await callback({ + error, + event, + request + }); + + if (response) { + break; + } + } + } + + if (!response) { + throw error; + } else { + logger_js.logger.log(`While responding to '${getFriendlyURL_js.getFriendlyURL(request.url)}', ` + `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` + `a handlerDidError plugin.`); + } + } + + for (const callback of handler.iterateCallbacks('handlerWillRespond')) { + response = await callback({ + event, + request, + response + }); + } + + return response; + } + + async _awaitComplete(responseDone, handler, request, event) { + let response; + let error; + + try { + response = await responseDone; + } catch (error) {// Ignore errors, as response errors should be caught via the `response` + // promise above. The `done` promise will only throw for errors in + // promises passed to `handler.waitUntil()`. + } + + try { + await handler.runCallbacks('handlerDidRespond', { + event, + request, + response + }); + await handler.doneWaiting(); + } catch (waitUntilError) { + if (waitUntilError instanceof Error) { + error = waitUntilError; + } + } + + await handler.runCallbacks('handlerDidComplete', { + event, + request, + response, + error: error + }); + handler.destroy(); + + if (error) { + throw error; + } + } + + } + /** + * Classes extending the `Strategy` based class should implement this method, + * and leverage the {@link workbox-strategies.StrategyHandler} + * arg to perform all fetching and cache logic, which will ensure all relevant + * cache, cache options, fetch options and plugins are used (per the current + * strategy instance). + * + * @name _handle + * @instance + * @abstract + * @function + * @param {Request} request + * @param {workbox-strategies.StrategyHandler} handler + * @return {Promise} + * + * @memberof workbox-strategies.Strategy + */ + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const messages = { + strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL_js.getFriendlyURL(request.url)}'`, + printFinalResponse: response => { + if (response) { + logger_js.logger.groupCollapsed(`View the final response here.`); + logger_js.logger.log(response || '[No response returned]'); + logger_js.logger.groupEnd(); + } + } + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network) + * request strategy. + * + * A cache first strategy is useful for assets that have been revisioned, + * such as URLs like `/styles/example.a8f5f1.css`, since they + * can be cached for long periods of time. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + + class CacheFirst extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + const logs = []; + + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'makeRequest', + paramName: 'request' + }); + } + + let response = await handler.cacheMatch(request); + let error = undefined; + + if (!response) { + { + logs.push(`No response found in the '${this.cacheName}' cache. ` + `Will respond with a network request.`); + } + + try { + response = await handler.fetchAndCachePut(request); + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + + { + if (response) { + logs.push(`Got response from network.`); + } else { + logs.push(`Unable to get a response from the network.`); + } + } + } else { + { + logs.push(`Found a cached response in the '${this.cacheName}' cache.`); + } + } + + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + + for (const log of logs) { + logger_js.logger.log(log); + } + + messages.printFinalResponse(response); + logger_js.logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url, + error + }); + } + + return response; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If there is no cache match, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + + class CacheOnly extends Strategy { + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + async _handle(request, handler) { + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'makeRequest', + paramName: 'request' + }); + } + + const response = await handler.cacheMatch(request); + + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + + if (response) { + logger_js.logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`); + messages.printFinalResponse(response); + } else { + logger_js.logger.log(`No response found in the '${this.cacheName}' cache.`); + } + + logger_js.logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url + }); + } + + return response; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + const cacheOkAndOpaquePlugin = { + /** + * Returns a valid response (to allow caching) if the status is 200 (OK) or + * 0 (opaque). + * + * @param {Object} options + * @param {Response} options.response + * @return {Response|null} + * + * @private + */ + cacheWillUpdate: async ({ + response + }) => { + if (response.status === 200 || response.status === 0) { + return response; + } + + return null; + } + }; + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a + * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache) + * request strategy. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + + class NetworkFirst extends Strategy { + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will fallback to the cache. + * + * This option can be used to combat + * "[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}" + * scenarios. + */ + constructor(options = {}) { + super(options); // If this instance contains no plugins with a 'cacheWillUpdate' callback, + // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. + + if (!this.plugins.some(p => 'cacheWillUpdate' in p)) { + this.plugins.unshift(cacheOkAndOpaquePlugin); + } + + this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; + + { + if (this._networkTimeoutSeconds) { + assert_js.assert.isType(this._networkTimeoutSeconds, 'number', { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'constructor', + paramName: 'networkTimeoutSeconds' + }); + } + } + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + + + async _handle(request, handler) { + const logs = []; + + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'handle', + paramName: 'makeRequest' + }); + } + + const promises = []; + let timeoutId; + + if (this._networkTimeoutSeconds) { + const { + id, + promise + } = this._getTimeoutPromise({ + request, + logs, + handler + }); + + timeoutId = id; + promises.push(promise); + } + + const networkPromise = this._getNetworkPromise({ + timeoutId, + request, + logs, + handler + }); + + promises.push(networkPromise); + const response = await handler.waitUntil((async () => { + // Promise.race() will resolve as soon as the first promise resolves. + return (await handler.waitUntil(Promise.race(promises))) || ( // If Promise.race() resolved with null, it might be due to a network + // timeout + a cache miss. If that were to happen, we'd rather wait until + // the networkPromise resolves instead of returning null. + // Note that it's fine to await an already-resolved promise, so we don't + // have to check to see if it's still "in flight". + await networkPromise); + })()); + + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + + for (const log of logs) { + logger_js.logger.log(log); + } + + messages.printFinalResponse(response); + logger_js.logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url + }); + } + + return response; + } + /** + * @param {Object} options + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs array + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + + + _getTimeoutPromise({ + request, + logs, + handler + }) { + let timeoutId; + const timeoutPromise = new Promise(resolve => { + const onNetworkTimeout = async () => { + { + logs.push(`Timing out the network response at ` + `${this._networkTimeoutSeconds} seconds.`); + } + + resolve(await handler.cacheMatch(request)); + }; + + timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000); + }); + return { + promise: timeoutPromise, + id: timeoutId + }; + } + /** + * @param {Object} options + * @param {number|undefined} options.timeoutId + * @param {Request} options.request + * @param {Array} options.logs A reference to the logs Array. + * @param {Event} options.event + * @return {Promise} + * + * @private + */ + + + async _getNetworkPromise({ + timeoutId, + request, + logs, + handler + }) { + let error; + let response; + + try { + response = await handler.fetchAndCachePut(request); + } catch (fetchError) { + if (fetchError instanceof Error) { + error = fetchError; + } + } + + if (timeoutId) { + clearTimeout(timeoutId); + } + + { + if (response) { + logs.push(`Got response from network.`); + } else { + logs.push(`Unable to get a response from the network. Will respond ` + `with a cached response.`); + } + } + + if (error || !response) { + response = await handler.cacheMatch(request); + + { + if (response) { + logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`); + } else { + logs.push(`No response found in the '${this.cacheName}' cache.`); + } + } + } + + return response; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a + * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only) + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/). + * + * If the network request fails, this will throw a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + + class NetworkOnly extends Strategy { + /** + * @param {Object} [options] + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {number} [options.networkTimeoutSeconds] If set, any network requests + * that fail to respond within the timeout will result in a network error. + */ + constructor(options = {}) { + super(options); + this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0; + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + + + async _handle(request, handler) { + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: '_handle', + paramName: 'request' + }); + } + + let error = undefined; + let response; + + try { + const promises = [handler.fetch(request)]; + + if (this._networkTimeoutSeconds) { + const timeoutPromise = timeout_js.timeout(this._networkTimeoutSeconds * 1000); + promises.push(timeoutPromise); + } + + response = await Promise.race(promises); + + if (!response) { + throw new Error(`Timed out the network response after ` + `${this._networkTimeoutSeconds} seconds.`); + } + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + + if (response) { + logger_js.logger.log(`Got response from network.`); + } else { + logger_js.logger.log(`Unable to get a response from the network.`); + } + + messages.printFinalResponse(response); + logger_js.logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url, + error + }); + } + + return response; + } + + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * An implementation of a + * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate) + * request strategy. + * + * Resources are requested from both the cache and the network in parallel. + * The strategy will respond with the cached version if available, otherwise + * wait for the network response. The cache is updated with the network response + * with each successful request. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses). + * Opaque responses are cross-origin requests where the response doesn't + * support [CORS](https://enable-cors.org/). + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. + * + * @extends workbox-strategies.Strategy + * @memberof workbox-strategies + */ + + class StaleWhileRevalidate extends Strategy { + /** + * @param {Object} [options] + * @param {string} [options.cacheName] Cache name to store and retrieve + * requests. Defaults to cache names provided by + * {@link workbox-core.cacheNames}. + * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. + * @param {Object} [options.fetchOptions] Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) + * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796) + * `fetch()` requests made by this strategy. + * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + */ + constructor(options = {}) { + super(options); // If this instance contains no plugins with a 'cacheWillUpdate' callback, + // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list. + + if (!this.plugins.some(p => 'cacheWillUpdate' in p)) { + this.plugins.unshift(cacheOkAndOpaquePlugin); + } + } + /** + * @private + * @param {Request|string} request A request to run this strategy for. + * @param {workbox-strategies.StrategyHandler} handler The event that + * triggered the request. + * @return {Promise} + */ + + + async _handle(request, handler) { + const logs = []; + + { + assert_js.assert.isInstance(request, Request, { + moduleName: 'workbox-strategies', + className: this.constructor.name, + funcName: 'handle', + paramName: 'request' + }); + } + + const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {// Swallow this error because a 'no-response' error will be thrown in + // main handler return flow. This will be in the `waitUntil()` flow. + }); + void handler.waitUntil(fetchAndCachePromise); + let response = await handler.cacheMatch(request); + let error; + + if (response) { + { + logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache. Will update with the network response in the background.`); + } + } else { + { + logs.push(`No response found in the '${this.cacheName}' cache. ` + `Will wait for the network response.`); + } + + try { + // NOTE(philipwalton): Really annoying that we have to type cast here. + // https://github.com/microsoft/TypeScript/issues/20006 + response = await fetchAndCachePromise; + } catch (err) { + if (err instanceof Error) { + error = err; + } + } + } + + { + logger_js.logger.groupCollapsed(messages.strategyStart(this.constructor.name, request)); + + for (const log of logs) { + logger_js.logger.log(log); + } + + messages.printFinalResponse(response); + logger_js.logger.groupEnd(); + } + + if (!response) { + throw new WorkboxError_js.WorkboxError('no-response', { + url: request.url, + error + }); + } + + return response; + } + + } + + exports.CacheFirst = CacheFirst; + exports.CacheOnly = CacheOnly; + exports.NetworkFirst = NetworkFirst; + exports.NetworkOnly = NetworkOnly; + exports.StaleWhileRevalidate = StaleWhileRevalidate; + exports.Strategy = Strategy; + exports.StrategyHandler = StrategyHandler; + + 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._private)); +//# sourceMappingURL=workbox-strategies.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-strategies.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-strategies.dev.js.map new file mode 100644 index 0000000..36e9ba0 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-strategies.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-strategies.dev.js","sources":["../_version.js","../StrategyHandler.js","../Strategy.js","../utils/messages.js","../CacheFirst.js","../CacheOnly.js","../plugins/cacheOkAndOpaquePlugin.js","../NetworkFirst.js","../NetworkOnly.js","../StaleWhileRevalidate.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:strategies:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { cacheMatchIgnoreParams } from 'workbox-core/_private/cacheMatchIgnoreParams.js';\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { executeQuotaErrorCallbacks } from 'workbox-core/_private/executeQuotaErrorCallbacks.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\nfunction toRequest(input) {\n return typeof input === 'string' ? new Request(input) : input;\n}\n/**\n * A class created every time a Strategy instance instance calls\n * {@link workbox-strategies.Strategy~handle} or\n * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and\n * cache actions around plugin callbacks and keeps track of when the strategy\n * is \"done\" (i.e. all added `event.waitUntil()` promises have resolved).\n *\n * @memberof workbox-strategies\n */\nclass StrategyHandler {\n /**\n * Creates a new instance associated with the passed strategy and event\n * that's handling the request.\n *\n * The constructor also initializes the state that will be passed to each of\n * the plugins handling this request.\n *\n * @param {workbox-strategies.Strategy} strategy\n * @param {Object} options\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params] The return value from the\n * {@link workbox-routing~matchCallback} (if applicable).\n */\n constructor(strategy, options) {\n this._cacheKeys = {};\n /**\n * The request the strategy is performing (passed to the strategy's\n * `handle()` or `handleAll()` method).\n * @name request\n * @instance\n * @type {Request}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * The event associated with this request.\n * @name event\n * @instance\n * @type {ExtendableEvent}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * A `URL` instance of `request.url` (if passed to the strategy's\n * `handle()` or `handleAll()` method).\n * Note: the `url` param will be present if the strategy was invoked\n * from a workbox `Route` object.\n * @name url\n * @instance\n * @type {URL|undefined}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * A `param` value (if passed to the strategy's\n * `handle()` or `handleAll()` method).\n * Note: the `param` param will be present if the strategy was invoked\n * from a workbox `Route` object and the\n * {@link workbox-routing~matchCallback} returned\n * a truthy value (it will be that value).\n * @name params\n * @instance\n * @type {*|undefined}\n * @memberof workbox-strategies.StrategyHandler\n */\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(options.event, ExtendableEvent, {\n moduleName: 'workbox-strategies',\n className: 'StrategyHandler',\n funcName: 'constructor',\n paramName: 'options.event',\n });\n }\n Object.assign(this, options);\n this.event = options.event;\n this._strategy = strategy;\n this._handlerDeferred = new Deferred();\n this._extendLifetimePromises = [];\n // Copy the plugins list (since it's mutable on the strategy),\n // so any mutations don't affect this handler instance.\n this._plugins = [...strategy.plugins];\n this._pluginStateMap = new Map();\n for (const plugin of this._plugins) {\n this._pluginStateMap.set(plugin, {});\n }\n this.event.waitUntil(this._handlerDeferred.promise);\n }\n /**\n * Fetches a given request (and invokes any applicable plugin callback\n * methods) using the `fetchOptions` (for non-navigation requests) and\n * `plugins` defined on the `Strategy` object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - `requestWillFetch()`\n * - `fetchDidSucceed()`\n * - `fetchDidFail()`\n *\n * @param {Request|string} input The URL or request to fetch.\n * @return {Promise}\n */\n async fetch(input) {\n const { event } = this;\n let request = toRequest(input);\n if (request.mode === 'navigate' &&\n event instanceof FetchEvent &&\n event.preloadResponse) {\n const possiblePreloadResponse = (await event.preloadResponse);\n if (possiblePreloadResponse) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Using a preloaded navigation response for ` +\n `'${getFriendlyURL(request.url)}'`);\n }\n return possiblePreloadResponse;\n }\n }\n // If there is a fetchDidFail plugin, we need to save a clone of the\n // original request before it's either modified by a requestWillFetch\n // plugin or before the original request's body is consumed via fetch().\n const originalRequest = this.hasCallback('fetchDidFail')\n ? request.clone()\n : null;\n try {\n for (const cb of this.iterateCallbacks('requestWillFetch')) {\n request = await cb({ request: request.clone(), event });\n }\n }\n catch (err) {\n if (err instanceof Error) {\n throw new WorkboxError('plugin-error-request-will-fetch', {\n thrownErrorMessage: err.message,\n });\n }\n }\n // The request can be altered by plugins with `requestWillFetch` making\n // the original request (most likely from a `fetch` event) different\n // from the Request we make. Pass both to `fetchDidFail` to aid debugging.\n const pluginFilteredRequest = request.clone();\n try {\n let fetchResponse;\n // See https://github.com/GoogleChrome/workbox/issues/1796\n fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Network request for ` +\n `'${getFriendlyURL(request.url)}' returned a response with ` +\n `status '${fetchResponse.status}'.`);\n }\n for (const callback of this.iterateCallbacks('fetchDidSucceed')) {\n fetchResponse = await callback({\n event,\n request: pluginFilteredRequest,\n response: fetchResponse,\n });\n }\n return fetchResponse;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Network request for ` +\n `'${getFriendlyURL(request.url)}' threw an error.`, error);\n }\n // `originalRequest` will only exist if a `fetchDidFail` callback\n // is being used (see above).\n if (originalRequest) {\n await this.runCallbacks('fetchDidFail', {\n error: error,\n event,\n originalRequest: originalRequest.clone(),\n request: pluginFilteredRequest.clone(),\n });\n }\n throw error;\n }\n }\n /**\n * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on\n * the response generated by `this.fetch()`.\n *\n * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,\n * so you do not have to manually call `waitUntil()` on the event.\n *\n * @param {Request|string} input The request or URL to fetch and cache.\n * @return {Promise}\n */\n async fetchAndCachePut(input) {\n const response = await this.fetch(input);\n const responseClone = response.clone();\n void this.waitUntil(this.cachePut(input, responseClone));\n return response;\n }\n /**\n * Matches a request from the cache (and invokes any applicable plugin\n * callback methods) using the `cacheName`, `matchOptions`, and `plugins`\n * defined on the strategy object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - cacheKeyWillByUsed()\n * - cachedResponseWillByUsed()\n *\n * @param {Request|string} key The Request or URL to use as the cache key.\n * @return {Promise} A matching response, if found.\n */\n async cacheMatch(key) {\n const request = toRequest(key);\n let cachedResponse;\n const { cacheName, matchOptions } = this._strategy;\n const effectiveRequest = await this.getCacheKey(request, 'read');\n const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), { cacheName });\n cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);\n if (process.env.NODE_ENV !== 'production') {\n if (cachedResponse) {\n logger.debug(`Found a cached response in '${cacheName}'.`);\n }\n else {\n logger.debug(`No cached response found in '${cacheName}'.`);\n }\n }\n for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {\n cachedResponse =\n (await callback({\n cacheName,\n matchOptions,\n cachedResponse,\n request: effectiveRequest,\n event: this.event,\n })) || undefined;\n }\n return cachedResponse;\n }\n /**\n * Puts a request/response pair in the cache (and invokes any applicable\n * plugin callback methods) using the `cacheName` and `plugins` defined on\n * the strategy object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - cacheKeyWillByUsed()\n * - cacheWillUpdate()\n * - cacheDidUpdate()\n *\n * @param {Request|string} key The request or URL to use as the cache key.\n * @param {Response} response The response to cache.\n * @return {Promise} `false` if a cacheWillUpdate caused the response\n * not be cached, and `true` otherwise.\n */\n async cachePut(key, response) {\n const request = toRequest(key);\n // Run in the next task to avoid blocking other cache reads.\n // https://github.com/w3c/ServiceWorker/issues/1397\n await timeout(0);\n const effectiveRequest = await this.getCacheKey(request, 'write');\n if (process.env.NODE_ENV !== 'production') {\n if (effectiveRequest.method && effectiveRequest.method !== 'GET') {\n throw new WorkboxError('attempt-to-cache-non-get-request', {\n url: getFriendlyURL(effectiveRequest.url),\n method: effectiveRequest.method,\n });\n }\n // See https://github.com/GoogleChrome/workbox/issues/2818\n const vary = response.headers.get('Vary');\n if (vary) {\n logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} ` +\n `has a 'Vary: ${vary}' header. ` +\n `Consider setting the {ignoreVary: true} option on your strategy ` +\n `to ensure cache matching and deletion works as expected.`);\n }\n }\n if (!response) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(`Cannot cache non-existent response for ` +\n `'${getFriendlyURL(effectiveRequest.url)}'.`);\n }\n throw new WorkboxError('cache-put-with-no-response', {\n url: getFriendlyURL(effectiveRequest.url),\n });\n }\n const responseToCache = await this._ensureResponseSafeToCache(response);\n if (!responseToCache) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` +\n `will not be cached.`, responseToCache);\n }\n return false;\n }\n const { cacheName, matchOptions } = this._strategy;\n const cache = await self.caches.open(cacheName);\n const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');\n const oldResponse = hasCacheUpdateCallback\n ? await cacheMatchIgnoreParams(\n // TODO(philipwalton): the `__WB_REVISION__` param is a precaching\n // feature. Consider into ways to only add this behavior if using\n // precaching.\n cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions)\n : null;\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Updating the '${cacheName}' cache with a new Response ` +\n `for ${getFriendlyURL(effectiveRequest.url)}.`);\n }\n try {\n await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);\n }\n catch (error) {\n if (error instanceof Error) {\n // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError\n if (error.name === 'QuotaExceededError') {\n await executeQuotaErrorCallbacks();\n }\n throw error;\n }\n }\n for (const callback of this.iterateCallbacks('cacheDidUpdate')) {\n await callback({\n cacheName,\n oldResponse,\n newResponse: responseToCache.clone(),\n request: effectiveRequest,\n event: this.event,\n });\n }\n return true;\n }\n /**\n * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and\n * executes any of those callbacks found in sequence. The final `Request`\n * object returned by the last plugin is treated as the cache key for cache\n * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have\n * been registered, the passed request is returned unmodified\n *\n * @param {Request} request\n * @param {string} mode\n * @return {Promise}\n */\n async getCacheKey(request, mode) {\n const key = `${request.url} | ${mode}`;\n if (!this._cacheKeys[key]) {\n let effectiveRequest = request;\n for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {\n effectiveRequest = toRequest(await callback({\n mode,\n request: effectiveRequest,\n event: this.event,\n // params has a type any can't change right now.\n params: this.params, // eslint-disable-line\n }));\n }\n this._cacheKeys[key] = effectiveRequest;\n }\n return this._cacheKeys[key];\n }\n /**\n * Returns true if the strategy has at least one plugin with the given\n * callback.\n *\n * @param {string} name The name of the callback to check for.\n * @return {boolean}\n */\n hasCallback(name) {\n for (const plugin of this._strategy.plugins) {\n if (name in plugin) {\n return true;\n }\n }\n return false;\n }\n /**\n * Runs all plugin callbacks matching the given name, in order, passing the\n * given param object (merged ith the current plugin state) as the only\n * argument.\n *\n * Note: since this method runs all plugins, it's not suitable for cases\n * where the return value of a callback needs to be applied prior to calling\n * the next callback. See\n * {@link workbox-strategies.StrategyHandler#iterateCallbacks}\n * below for how to handle that case.\n *\n * @param {string} name The name of the callback to run within each plugin.\n * @param {Object} param The object to pass as the first (and only) param\n * when executing each callback. This object will be merged with the\n * current plugin state prior to callback execution.\n */\n async runCallbacks(name, param) {\n for (const callback of this.iterateCallbacks(name)) {\n // TODO(philipwalton): not sure why `any` is needed. It seems like\n // this should work with `as WorkboxPluginCallbackParam[C]`.\n await callback(param);\n }\n }\n /**\n * Accepts a callback and returns an iterable of matching plugin callbacks,\n * where each callback is wrapped with the current handler state (i.e. when\n * you call each callback, whatever object parameter you pass it will\n * be merged with the plugin's current state).\n *\n * @param {string} name The name fo the callback to run\n * @return {Array}\n */\n *iterateCallbacks(name) {\n for (const plugin of this._strategy.plugins) {\n if (typeof plugin[name] === 'function') {\n const state = this._pluginStateMap.get(plugin);\n const statefulCallback = (param) => {\n const statefulParam = Object.assign(Object.assign({}, param), { state });\n // TODO(philipwalton): not sure why `any` is needed. It seems like\n // this should work with `as WorkboxPluginCallbackParam[C]`.\n return plugin[name](statefulParam);\n };\n yield statefulCallback;\n }\n }\n }\n /**\n * Adds a promise to the\n * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}\n * of the event event associated with the request being handled (usually a\n * `FetchEvent`).\n *\n * Note: you can await\n * {@link workbox-strategies.StrategyHandler~doneWaiting}\n * to know when all added promises have settled.\n *\n * @param {Promise} promise A promise to add to the extend lifetime promises\n * of the event that triggered the request.\n */\n waitUntil(promise) {\n this._extendLifetimePromises.push(promise);\n return promise;\n }\n /**\n * Returns a promise that resolves once all promises passed to\n * {@link workbox-strategies.StrategyHandler~waitUntil}\n * have settled.\n *\n * Note: any work done after `doneWaiting()` settles should be manually\n * passed to an event's `waitUntil()` method (not this handler's\n * `waitUntil()` method), otherwise the service worker thread my be killed\n * prior to your work completing.\n */\n async doneWaiting() {\n let promise;\n while ((promise = this._extendLifetimePromises.shift())) {\n await promise;\n }\n }\n /**\n * Stops running the strategy and immediately resolves any pending\n * `waitUntil()` promises.\n */\n destroy() {\n this._handlerDeferred.resolve(null);\n }\n /**\n * This method will call cacheWillUpdate on the available plugins (or use\n * status === 200) to determine if the Response is safe and valid to cache.\n *\n * @param {Request} options.request\n * @param {Response} options.response\n * @return {Promise}\n *\n * @private\n */\n async _ensureResponseSafeToCache(response) {\n let responseToCache = response;\n let pluginsUsed = false;\n for (const callback of this.iterateCallbacks('cacheWillUpdate')) {\n responseToCache =\n (await callback({\n request: this.request,\n response: responseToCache,\n event: this.event,\n })) || undefined;\n pluginsUsed = true;\n if (!responseToCache) {\n break;\n }\n }\n if (!pluginsUsed) {\n if (responseToCache && responseToCache.status !== 200) {\n responseToCache = undefined;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (responseToCache) {\n if (responseToCache.status !== 200) {\n if (responseToCache.status === 0) {\n logger.warn(`The response for '${this.request.url}' ` +\n `is an opaque response. The caching strategy that you're ` +\n `using will not cache opaque responses by default.`);\n }\n else {\n logger.debug(`The response for '${this.request.url}' ` +\n `returned a status code of '${response.status}' and won't ` +\n `be cached as a result.`);\n }\n }\n }\n }\n }\n return responseToCache;\n }\n}\nexport { StrategyHandler };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { StrategyHandler } from './StrategyHandler.js';\nimport './_version.js';\n/**\n * An abstract base class that all other strategy classes must extend from:\n *\n * @memberof workbox-strategies\n */\nclass Strategy {\n /**\n * Creates a new instance of the strategy and sets all documented option\n * properties as public instance properties.\n *\n * Note: if a custom strategy class extends the base Strategy class and does\n * not need more than these properties, it does not need to define its own\n * constructor.\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] The\n * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n */\n constructor(options = {}) {\n /**\n * Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n *\n * @type {string}\n */\n this.cacheName = cacheNames.getRuntimeName(options.cacheName);\n /**\n * The list\n * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * used by this strategy.\n *\n * @type {Array}\n */\n this.plugins = options.plugins || [];\n /**\n * Values passed along to the\n * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}\n * of all fetch() requests made by this strategy.\n *\n * @type {Object}\n */\n this.fetchOptions = options.fetchOptions;\n /**\n * The\n * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n *\n * @type {Object}\n */\n this.matchOptions = options.matchOptions;\n }\n /**\n * Perform a request strategy and returns a `Promise` that will resolve with\n * a `Response`, invoking all relevant plugin callbacks.\n *\n * When a strategy instance is registered with a Workbox\n * {@link workbox-routing.Route}, this method is automatically\n * called when the route matches.\n *\n * Alternatively, this method can be used in a standalone `FetchEvent`\n * listener by passing it to `event.respondWith()`.\n *\n * @param {FetchEvent|Object} options A `FetchEvent` or an object with the\n * properties listed below.\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params]\n */\n handle(options) {\n const [responseDone] = this.handleAll(options);\n return responseDone;\n }\n /**\n * Similar to {@link workbox-strategies.Strategy~handle}, but\n * instead of just returning a `Promise` that resolves to a `Response` it\n * it will return an tuple of `[response, done]` promises, where the former\n * (`response`) is equivalent to what `handle()` returns, and the latter is a\n * Promise that will resolve once any promises that were added to\n * `event.waitUntil()` as part of performing the strategy have completed.\n *\n * You can await the `done` promise to ensure any extra work performed by\n * the strategy (usually caching responses) completes successfully.\n *\n * @param {FetchEvent|Object} options A `FetchEvent` or an object with the\n * properties listed below.\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params]\n * @return {Array} A tuple of [response, done]\n * promises that can be used to determine when the response resolves as\n * well as when the handler has completed all its work.\n */\n handleAll(options) {\n // Allow for flexible options to be passed.\n if (options instanceof FetchEvent) {\n options = {\n event: options,\n request: options.request,\n };\n }\n const event = options.event;\n const request = typeof options.request === 'string'\n ? new Request(options.request)\n : options.request;\n const params = 'params' in options ? options.params : undefined;\n const handler = new StrategyHandler(this, { event, request, params });\n const responseDone = this._getResponse(handler, request, event);\n const handlerDone = this._awaitComplete(responseDone, handler, request, event);\n // Return an array of promises, suitable for use with Promise.all().\n return [responseDone, handlerDone];\n }\n async _getResponse(handler, request, event) {\n await handler.runCallbacks('handlerWillStart', { event, request });\n let response = undefined;\n try {\n response = await this._handle(request, handler);\n // The \"official\" Strategy subclasses all throw this error automatically,\n // but in case a third-party Strategy doesn't, ensure that we have a\n // consistent failure when there's no response or an error response.\n if (!response || response.type === 'error') {\n throw new WorkboxError('no-response', { url: request.url });\n }\n }\n catch (error) {\n if (error instanceof Error) {\n for (const callback of handler.iterateCallbacks('handlerDidError')) {\n response = await callback({ error, event, request });\n if (response) {\n break;\n }\n }\n }\n if (!response) {\n throw error;\n }\n else if (process.env.NODE_ENV !== 'production') {\n logger.log(`While responding to '${getFriendlyURL(request.url)}', ` +\n `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` +\n `a handlerDidError plugin.`);\n }\n }\n for (const callback of handler.iterateCallbacks('handlerWillRespond')) {\n response = await callback({ event, request, response });\n }\n return response;\n }\n async _awaitComplete(responseDone, handler, request, event) {\n let response;\n let error;\n try {\n response = await responseDone;\n }\n catch (error) {\n // Ignore errors, as response errors should be caught via the `response`\n // promise above. The `done` promise will only throw for errors in\n // promises passed to `handler.waitUntil()`.\n }\n try {\n await handler.runCallbacks('handlerDidRespond', {\n event,\n request,\n response,\n });\n await handler.doneWaiting();\n }\n catch (waitUntilError) {\n if (waitUntilError instanceof Error) {\n error = waitUntilError;\n }\n }\n await handler.runCallbacks('handlerDidComplete', {\n event,\n request,\n response,\n error: error,\n });\n handler.destroy();\n if (error) {\n throw error;\n }\n }\n}\nexport { Strategy };\n/**\n * Classes extending the `Strategy` based class should implement this method,\n * and leverage the {@link workbox-strategies.StrategyHandler}\n * arg to perform all fetching and cache logic, which will ensure all relevant\n * cache, cache options, fetch options and plugins are used (per the current\n * strategy instance).\n *\n * @name _handle\n * @instance\n * @abstract\n * @function\n * @param {Request} request\n * @param {workbox-strategies.StrategyHandler} handler\n * @return {Promise}\n *\n * @memberof workbox-strategies.Strategy\n */\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport '../_version.js';\nexport const messages = {\n strategyStart: (strategyName, request) => `Using ${strategyName} to respond to '${getFriendlyURL(request.url)}'`,\n printFinalResponse: (response) => {\n if (response) {\n logger.groupCollapsed(`View the final response here.`);\n logger.log(response || '[No response returned]');\n logger.groupEnd();\n }\n },\n};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network)\n * request strategy.\n *\n * A cache first strategy is useful for assets that have been revisioned,\n * such as URLs like `/styles/example.a8f5f1.css`, since they\n * can be cached for long periods of time.\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass CacheFirst extends Strategy {\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'makeRequest',\n paramName: 'request',\n });\n }\n let response = await handler.cacheMatch(request);\n let error = undefined;\n if (!response) {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`No response found in the '${this.cacheName}' cache. ` +\n `Will respond with a network request.`);\n }\n try {\n response = await handler.fetchAndCachePut(request);\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Got response from network.`);\n }\n else {\n logs.push(`Unable to get a response from the network.`);\n }\n }\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Found a cached response in the '${this.cacheName}' cache.`);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { CacheFirst };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only)\n * request strategy.\n *\n * This class is useful if you want to take advantage of any\n * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).\n *\n * If there is no cache match, this will throw a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass CacheOnly extends Strategy {\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'makeRequest',\n paramName: 'request',\n });\n }\n const response = await handler.cacheMatch(request);\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n if (response) {\n logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`);\n messages.printFinalResponse(response);\n }\n else {\n logger.log(`No response found in the '${this.cacheName}' cache.`);\n }\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url });\n }\n return response;\n }\n}\nexport { CacheOnly };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nexport const cacheOkAndOpaquePlugin = {\n /**\n * Returns a valid response (to allow caching) if the status is 200 (OK) or\n * 0 (opaque).\n *\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n *\n * @private\n */\n cacheWillUpdate: async ({ response }) => {\n if (response.status === 200 || response.status === 0) {\n return response;\n }\n return null;\n },\n};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache)\n * request strategy.\n *\n * By default, this strategy will cache responses with a 200 status code as\n * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n * Opaque responses are are cross-origin requests where the response doesn't\n * support [CORS](https://enable-cors.org/).\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass NetworkFirst extends Strategy {\n /**\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)\n * @param {number} [options.networkTimeoutSeconds] If set, any network requests\n * that fail to respond within the timeout will fallback to the cache.\n *\n * This option can be used to combat\n * \"[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}\"\n * scenarios.\n */\n constructor(options = {}) {\n super(options);\n // If this instance contains no plugins with a 'cacheWillUpdate' callback,\n // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.\n if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {\n this.plugins.unshift(cacheOkAndOpaquePlugin);\n }\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;\n if (process.env.NODE_ENV !== 'production') {\n if (this._networkTimeoutSeconds) {\n assert.isType(this._networkTimeoutSeconds, 'number', {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'constructor',\n paramName: 'networkTimeoutSeconds',\n });\n }\n }\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'handle',\n paramName: 'makeRequest',\n });\n }\n const promises = [];\n let timeoutId;\n if (this._networkTimeoutSeconds) {\n const { id, promise } = this._getTimeoutPromise({ request, logs, handler });\n timeoutId = id;\n promises.push(promise);\n }\n const networkPromise = this._getNetworkPromise({\n timeoutId,\n request,\n logs,\n handler,\n });\n promises.push(networkPromise);\n const response = await handler.waitUntil((async () => {\n // Promise.race() will resolve as soon as the first promise resolves.\n return ((await handler.waitUntil(Promise.race(promises))) ||\n // If Promise.race() resolved with null, it might be due to a network\n // timeout + a cache miss. If that were to happen, we'd rather wait until\n // the networkPromise resolves instead of returning null.\n // Note that it's fine to await an already-resolved promise, so we don't\n // have to check to see if it's still \"in flight\".\n (await networkPromise));\n })());\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url });\n }\n return response;\n }\n /**\n * @param {Object} options\n * @param {Request} options.request\n * @param {Array} options.logs A reference to the logs array\n * @param {Event} options.event\n * @return {Promise}\n *\n * @private\n */\n _getTimeoutPromise({ request, logs, handler, }) {\n let timeoutId;\n const timeoutPromise = new Promise((resolve) => {\n const onNetworkTimeout = async () => {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Timing out the network response at ` +\n `${this._networkTimeoutSeconds} seconds.`);\n }\n resolve(await handler.cacheMatch(request));\n };\n timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000);\n });\n return {\n promise: timeoutPromise,\n id: timeoutId,\n };\n }\n /**\n * @param {Object} options\n * @param {number|undefined} options.timeoutId\n * @param {Request} options.request\n * @param {Array} options.logs A reference to the logs Array.\n * @param {Event} options.event\n * @return {Promise}\n *\n * @private\n */\n async _getNetworkPromise({ timeoutId, request, logs, handler, }) {\n let error;\n let response;\n try {\n response = await handler.fetchAndCachePut(request);\n }\n catch (fetchError) {\n if (fetchError instanceof Error) {\n error = fetchError;\n }\n }\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Got response from network.`);\n }\n else {\n logs.push(`Unable to get a response from the network. Will respond ` +\n `with a cached response.`);\n }\n }\n if (error || !response) {\n response = await handler.cacheMatch(request);\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`);\n }\n else {\n logs.push(`No response found in the '${this.cacheName}' cache.`);\n }\n }\n }\n return response;\n }\n}\nexport { NetworkFirst };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)\n * request strategy.\n *\n * This class is useful if you want to take advantage of any\n * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).\n *\n * If the network request fails, this will throw a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass NetworkOnly extends Strategy {\n /**\n * @param {Object} [options]\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {number} [options.networkTimeoutSeconds] If set, any network requests\n * that fail to respond within the timeout will result in a network error.\n */\n constructor(options = {}) {\n super(options);\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: '_handle',\n paramName: 'request',\n });\n }\n let error = undefined;\n let response;\n try {\n const promises = [\n handler.fetch(request),\n ];\n if (this._networkTimeoutSeconds) {\n const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);\n promises.push(timeoutPromise);\n }\n response = await Promise.race(promises);\n if (!response) {\n throw new Error(`Timed out the network response after ` +\n `${this._networkTimeoutSeconds} seconds.`);\n }\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n if (response) {\n logger.log(`Got response from network.`);\n }\n else {\n logger.log(`Unable to get a response from the network.`);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { NetworkOnly };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate)\n * request strategy.\n *\n * Resources are requested from both the cache and the network in parallel.\n * The strategy will respond with the cached version if available, otherwise\n * wait for the network response. The cache is updated with the network response\n * with each successful request.\n *\n * By default, this strategy will cache responses with a 200 status code as\n * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n * Opaque responses are cross-origin requests where the response doesn't\n * support [CORS](https://enable-cors.org/).\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass StaleWhileRevalidate extends Strategy {\n /**\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)\n */\n constructor(options = {}) {\n super(options);\n // If this instance contains no plugins with a 'cacheWillUpdate' callback,\n // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.\n if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {\n this.plugins.unshift(cacheOkAndOpaquePlugin);\n }\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'handle',\n paramName: 'request',\n });\n }\n const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {\n // Swallow this error because a 'no-response' error will be thrown in\n // main handler return flow. This will be in the `waitUntil()` flow.\n });\n void handler.waitUntil(fetchAndCachePromise);\n let response = await handler.cacheMatch(request);\n let error;\n if (response) {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Found a cached response in the '${this.cacheName}'` +\n ` cache. Will update with the network response in the background.`);\n }\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`No response found in the '${this.cacheName}' cache. ` +\n `Will wait for the network response.`);\n }\n try {\n // NOTE(philipwalton): Really annoying that we have to type cast here.\n // https://github.com/microsoft/TypeScript/issues/20006\n response = (await fetchAndCachePromise);\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { StaleWhileRevalidate };\n"],"names":["self","_","e","toRequest","input","Request","StrategyHandler","constructor","strategy","options","_cacheKeys","assert","isInstance","event","ExtendableEvent","moduleName","className","funcName","paramName","Object","assign","_strategy","_handlerDeferred","Deferred","_extendLifetimePromises","_plugins","plugins","_pluginStateMap","Map","plugin","set","waitUntil","promise","fetch","request","mode","FetchEvent","preloadResponse","possiblePreloadResponse","logger","log","getFriendlyURL","url","originalRequest","hasCallback","clone","cb","iterateCallbacks","err","Error","WorkboxError","thrownErrorMessage","message","pluginFilteredRequest","fetchResponse","undefined","fetchOptions","process","debug","status","callback","response","error","runCallbacks","fetchAndCachePut","responseClone","cachePut","cacheMatch","key","cachedResponse","cacheName","matchOptions","effectiveRequest","getCacheKey","multiMatchOptions","caches","match","timeout","method","vary","headers","get","responseToCache","_ensureResponseSafeToCache","cache","open","hasCacheUpdateCallback","oldResponse","cacheMatchIgnoreParams","put","name","executeQuotaErrorCallbacks","newResponse","params","param","state","statefulCallback","statefulParam","push","doneWaiting","shift","destroy","resolve","pluginsUsed","warn","Strategy","cacheNames","getRuntimeName","handle","responseDone","handleAll","handler","_getResponse","handlerDone","_awaitComplete","_handle","type","toString","waitUntilError","messages","strategyStart","strategyName","printFinalResponse","groupCollapsed","groupEnd","CacheFirst","logs","CacheOnly","cacheOkAndOpaquePlugin","cacheWillUpdate","NetworkFirst","some","p","unshift","_networkTimeoutSeconds","networkTimeoutSeconds","isType","promises","timeoutId","id","_getTimeoutPromise","networkPromise","_getNetworkPromise","Promise","race","timeoutPromise","onNetworkTimeout","setTimeout","fetchError","clearTimeout","NetworkOnly","StaleWhileRevalidate","fetchAndCachePromise","catch"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,0BAAD,CAAJ,IAAoCC,CAAC,EAArC;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;;IAUA,SAASC,SAAT,CAAmBC,KAAnB,EAA0B;IACtB,SAAO,OAAOA,KAAP,KAAiB,QAAjB,GAA4B,IAAIC,OAAJ,CAAYD,KAAZ,CAA5B,GAAiDA,KAAxD;IACH;IACD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;IACA,MAAME,eAAN,CAAsB;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J;IACJ;IACJ;;IACD,WAAOuB,eAAP;IACH;;IAteiB;;IC5BtB;IACA;AACA;IACA;IACA;IACA;IACA;IAOA;IACA;IACA;IACA;IACA;;IACA,MAAMuB,QAAN,CAAe;IACX;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACIlG,EAAAA,WAAW,CAACE,OAAO,GAAG,EAAX,EAAe;IACtB;IACR;IACA;IACA;IACA;IACA;IACA;IACQ,SAAK6D,SAAL,GAAiBoC,wBAAU,CAACC,cAAX,CAA0BlG,OAAO,CAAC6D,SAAlC,CAAjB;IACA;IACR;IACA;IACA;IACA;IACA;IACA;;IACQ,SAAK5C,OAAL,GAAejB,OAAO,CAACiB,OAAR,IAAmB,EAAlC;IACA;IACR;IACA;IACA;IACA;IACA;IACA;;IACQ,SAAK8B,YAAL,GAAoB/C,OAAO,CAAC+C,YAA5B;IACA;IACR;IACA;IACA;IACA;IACA;IACA;;IACQ,SAAKe,YAAL,GAAoB9D,OAAO,CAAC8D,YAA5B;IACH;IACD;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;IACIqC,EAAAA,MAAM,CAACnG,OAAD,EAAU;IACZ,UAAM,CAACoG,YAAD,IAAiB,KAAKC,SAAL,CAAerG,OAAf,CAAvB;IACA,WAAOoG,YAAP;IACH;IACD;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;IACIC,EAAAA,SAAS,CAACrG,OAAD,EAAU;IACf;IACA,QAAIA,OAAO,YAAY2B,UAAvB,EAAmC;IAC/B3B,MAAAA,OAAO,GAAG;IACNI,QAAAA,KAAK,EAAEJ,OADD;IAENyB,QAAAA,OAAO,EAAEzB,OAAO,CAACyB;IAFX,OAAV;IAIH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F,QAAAA,gBAAM,CAACC,GAAP,CAAWA,GAAX;IACH;;IACD+E,MAAAA,QAAQ,CAACG,kBAAT,CAA4B7D,QAA5B;IACAtB,MAAAA,gBAAM,CAACqF,QAAP;IACH;;IACD,QAAI,CAAC/D,QAAL,EAAe;IACX,YAAM,IAAIX,4BAAJ,CAAiB,aAAjB,EAAgC;IAAER,QAAAA,GAAG,EAAER,OAAO,CAACQ,GAAf;IAAoBoB,QAAAA;IAApB,OAAhC,CAAN;IACH;;IACD,WAAOD,QAAP;IACH;;IAhFuC;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-strategies.prod.js b/src/Resources/workbox-v7.0.0/workbox-strategies.prod.js new file mode 100644 index 0000000..8a54d7c --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-strategies.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.strategies=function(t,e,s,r,n,a,i,o,c){"use strict";try{self["workbox:strategies:7.0.0"]&&_()}catch(t){}function h(t){return"string"==typeof t?new Request(t):t}class l{constructor(t,e){this.vt={},Object.assign(this,e),this.event=e.event,this.ht=t,this.bt=new n.Deferred,this.Et=[],this._t=[...t.plugins],this.kt=new Map;for(const t of this._t)this.kt.set(t,{});this.event.waitUntil(this.bt.promise)}async fetch(t){const{event:s}=this;let r=h(t);if("navigate"===r.mode&&s instanceof FetchEvent&&s.preloadResponse){const t=await s.preloadResponse;if(t)return t}const n=this.hasCallback("fetchDidFail")?r.clone():null;try{for(const t of this.iterateCallbacks("requestWillFetch"))r=await t({request:r.clone(),event:s})}catch(t){if(t instanceof Error)throw new e.WorkboxError("plugin-error-request-will-fetch",{thrownErrorMessage:t.message})}const a=r.clone();try{let t;t=await fetch(r,"navigate"===r.mode?void 0:this.ht.fetchOptions);for(const e of this.iterateCallbacks("fetchDidSucceed"))t=await e({event:s,request:a,response:t});return t}catch(t){throw n&&await this.runCallbacks("fetchDidFail",{error:t,event:s,originalRequest:n.clone(),request:a.clone()}),t}}async fetchAndCachePut(t){const e=await this.fetch(t),s=e.clone();return this.waitUntil(this.cachePut(t,s)),e}async cacheMatch(t){const e=h(t);let s;const{cacheName:r,matchOptions:n}=this.ht,a=await this.getCacheKey(e,"read"),i=Object.assign(Object.assign({},n),{cacheName:r});s=await caches.match(a,i);for(const t of this.iterateCallbacks("cachedResponseWillBeUsed"))s=await t({cacheName:r,matchOptions:n,cachedResponse:s,request:a,event:this.event})||void 0;return s}async cachePut(t,s){const n=h(t);await c.timeout(0);const o=await this.getCacheKey(n,"write");if(!s)throw new e.WorkboxError("cache-put-with-no-response",{url:i.getFriendlyURL(o.url)});const l=await this.xt(s);if(!l)return!1;const{cacheName:w,matchOptions:u}=this.ht,f=await self.caches.open(w),d=this.hasCallback("cacheDidUpdate"),p=d?await r.cacheMatchIgnoreParams(f,o.clone(),["__WB_REVISION__"],u):null;try{await f.put(o,d?l.clone():l)}catch(t){if(t instanceof Error)throw"QuotaExceededError"===t.name&&await a.executeQuotaErrorCallbacks(),t}for(const t of this.iterateCallbacks("cacheDidUpdate"))await t({cacheName:w,oldResponse:p,newResponse:l.clone(),request:o,event:this.event});return!0}async getCacheKey(t,e){const s=`${t.url} | ${e}`;if(!this.vt[s]){let r=t;for(const t of this.iterateCallbacks("cacheKeyWillBeUsed"))r=h(await t({mode:e,request:r,event:this.event,params:this.params}));this.vt[s]=r}return this.vt[s]}hasCallback(t){for(const e of this.ht.plugins)if(t in e)return!0;return!1}async runCallbacks(t,e){for(const s of this.iterateCallbacks(t))await s(e)}*iterateCallbacks(t){for(const e of this.ht.plugins)if("function"==typeof e[t]){const s=this.kt.get(e),r=r=>{const n=Object.assign(Object.assign({},r),{state:s});return e[t](n)};yield r}}waitUntil(t){return this.Et.push(t),t}async doneWaiting(){let t;for(;t=this.Et.shift();)await t}destroy(){this.bt.resolve(null)}async xt(t){let e=t,s=!1;for(const t of this.iterateCallbacks("cacheWillUpdate"))if(e=await t({request:this.request,response:e,event:this.event})||void 0,s=!0,!e)break;return s||e&&200!==e.status&&(e=void 0),e}}class w{constructor(t={}){this.cacheName=s.cacheNames.getRuntimeName(t.cacheName),this.plugins=t.plugins||[],this.fetchOptions=t.fetchOptions,this.matchOptions=t.matchOptions}handle(t){const[e]=this.handleAll(t);return e}handleAll(t){t instanceof FetchEvent&&(t={event:t,request:t.request});const e=t.event,s="string"==typeof t.request?new Request(t.request):t.request,r="params"in t?t.params:void 0,n=new l(this,{event:e,request:s,params:r}),a=this.Rt(n,s,e);return[a,this.Wt(a,n,s,e)]}async Rt(t,s,r){let n;await t.runCallbacks("handlerWillStart",{event:r,request:s});try{if(n=await this._handle(s,t),!n||"error"===n.type)throw new e.WorkboxError("no-response",{url:s.url})}catch(e){if(e instanceof Error)for(const a of t.iterateCallbacks("handlerDidError"))if(n=await a({error:e,event:r,request:s}),n)break;if(!n)throw e}for(const e of t.iterateCallbacks("handlerWillRespond"))n=await e({event:r,request:s,response:n});return n}async Wt(t,e,s,r){let n,a;try{n=await t}catch(a){}try{await e.runCallbacks("handlerDidRespond",{event:r,request:s,response:n}),await e.doneWaiting()}catch(t){t instanceof Error&&(a=t)}if(await e.runCallbacks("handlerDidComplete",{event:r,request:s,response:n,error:a}),e.destroy(),a)throw a}}const u={cacheWillUpdate:async({response:t})=>200===t.status||0===t.status?t:null};return t.CacheFirst=class extends w{async _handle(t,s){let r,n=await s.cacheMatch(t);if(!n)try{n=await s.fetchAndCachePut(t)}catch(t){t instanceof Error&&(r=t)}if(!n)throw new e.WorkboxError("no-response",{url:t.url,error:r});return n}},t.CacheOnly=class extends w{async _handle(t,s){const r=await s.cacheMatch(t);if(!r)throw new e.WorkboxError("no-response",{url:t.url});return r}},t.NetworkFirst=class extends w{constructor(t={}){super(t),this.plugins.some((t=>"cacheWillUpdate"in t))||this.plugins.unshift(u),this.Ot=t.networkTimeoutSeconds||0}async _handle(t,s){const r=[],n=[];let a;if(this.Ot){const{id:e,promise:i}=this.Ut({request:t,logs:r,handler:s});a=e,n.push(i)}const i=this.Ct({timeoutId:a,request:t,logs:r,handler:s});n.push(i);const o=await s.waitUntil((async()=>await s.waitUntil(Promise.race(n))||await i)());if(!o)throw new e.WorkboxError("no-response",{url:t.url});return o}Ut({request:t,logs:e,handler:s}){let r;return{promise:new Promise((e=>{r=setTimeout((async()=>{e(await s.cacheMatch(t))}),1e3*this.Ot)})),id:r}}async Ct({timeoutId:t,request:e,logs:s,handler:r}){let n,a;try{a=await r.fetchAndCachePut(e)}catch(t){t instanceof Error&&(n=t)}return t&&clearTimeout(t),!n&&a||(a=await r.cacheMatch(e)),a}},t.NetworkOnly=class extends w{constructor(t={}){super(t),this.Ot=t.networkTimeoutSeconds||0}async _handle(t,s){let r,n;try{const e=[s.fetch(t)];if(this.Ot){const t=c.timeout(1e3*this.Ot);e.push(t)}if(n=await Promise.race(e),!n)throw new Error(`Timed out the network response after ${this.Ot} seconds.`)}catch(t){t instanceof Error&&(r=t)}if(!n)throw new e.WorkboxError("no-response",{url:t.url,error:r});return n}},t.StaleWhileRevalidate=class extends w{constructor(t={}){super(t),this.plugins.some((t=>"cacheWillUpdate"in t))||this.plugins.unshift(u)}async _handle(t,s){const r=s.fetchAndCachePut(t).catch((()=>{}));s.waitUntil(r);let n,a=await s.cacheMatch(t);if(a);else try{a=await r}catch(t){t instanceof Error&&(n=t)}if(!a)throw new e.WorkboxError("no-response",{url:t.url,error:n});return a}},t.Strategy=w,t.StrategyHandler=l,t}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-strategies.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-strategies.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-strategies.prod.js.map new file mode 100644 index 0000000..a90b448 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-strategies.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-strategies.prod.js","sources":["../_version.js","../StrategyHandler.js","../Strategy.js","../plugins/cacheOkAndOpaquePlugin.js","../CacheFirst.js","../CacheOnly.js","../NetworkFirst.js","../NetworkOnly.js","../StaleWhileRevalidate.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:strategies:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { cacheMatchIgnoreParams } from 'workbox-core/_private/cacheMatchIgnoreParams.js';\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { executeQuotaErrorCallbacks } from 'workbox-core/_private/executeQuotaErrorCallbacks.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\nfunction toRequest(input) {\n return typeof input === 'string' ? new Request(input) : input;\n}\n/**\n * A class created every time a Strategy instance instance calls\n * {@link workbox-strategies.Strategy~handle} or\n * {@link workbox-strategies.Strategy~handleAll} that wraps all fetch and\n * cache actions around plugin callbacks and keeps track of when the strategy\n * is \"done\" (i.e. all added `event.waitUntil()` promises have resolved).\n *\n * @memberof workbox-strategies\n */\nclass StrategyHandler {\n /**\n * Creates a new instance associated with the passed strategy and event\n * that's handling the request.\n *\n * The constructor also initializes the state that will be passed to each of\n * the plugins handling this request.\n *\n * @param {workbox-strategies.Strategy} strategy\n * @param {Object} options\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params] The return value from the\n * {@link workbox-routing~matchCallback} (if applicable).\n */\n constructor(strategy, options) {\n this._cacheKeys = {};\n /**\n * The request the strategy is performing (passed to the strategy's\n * `handle()` or `handleAll()` method).\n * @name request\n * @instance\n * @type {Request}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * The event associated with this request.\n * @name event\n * @instance\n * @type {ExtendableEvent}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * A `URL` instance of `request.url` (if passed to the strategy's\n * `handle()` or `handleAll()` method).\n * Note: the `url` param will be present if the strategy was invoked\n * from a workbox `Route` object.\n * @name url\n * @instance\n * @type {URL|undefined}\n * @memberof workbox-strategies.StrategyHandler\n */\n /**\n * A `param` value (if passed to the strategy's\n * `handle()` or `handleAll()` method).\n * Note: the `param` param will be present if the strategy was invoked\n * from a workbox `Route` object and the\n * {@link workbox-routing~matchCallback} returned\n * a truthy value (it will be that value).\n * @name params\n * @instance\n * @type {*|undefined}\n * @memberof workbox-strategies.StrategyHandler\n */\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(options.event, ExtendableEvent, {\n moduleName: 'workbox-strategies',\n className: 'StrategyHandler',\n funcName: 'constructor',\n paramName: 'options.event',\n });\n }\n Object.assign(this, options);\n this.event = options.event;\n this._strategy = strategy;\n this._handlerDeferred = new Deferred();\n this._extendLifetimePromises = [];\n // Copy the plugins list (since it's mutable on the strategy),\n // so any mutations don't affect this handler instance.\n this._plugins = [...strategy.plugins];\n this._pluginStateMap = new Map();\n for (const plugin of this._plugins) {\n this._pluginStateMap.set(plugin, {});\n }\n this.event.waitUntil(this._handlerDeferred.promise);\n }\n /**\n * Fetches a given request (and invokes any applicable plugin callback\n * methods) using the `fetchOptions` (for non-navigation requests) and\n * `plugins` defined on the `Strategy` object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - `requestWillFetch()`\n * - `fetchDidSucceed()`\n * - `fetchDidFail()`\n *\n * @param {Request|string} input The URL or request to fetch.\n * @return {Promise}\n */\n async fetch(input) {\n const { event } = this;\n let request = toRequest(input);\n if (request.mode === 'navigate' &&\n event instanceof FetchEvent &&\n event.preloadResponse) {\n const possiblePreloadResponse = (await event.preloadResponse);\n if (possiblePreloadResponse) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Using a preloaded navigation response for ` +\n `'${getFriendlyURL(request.url)}'`);\n }\n return possiblePreloadResponse;\n }\n }\n // If there is a fetchDidFail plugin, we need to save a clone of the\n // original request before it's either modified by a requestWillFetch\n // plugin or before the original request's body is consumed via fetch().\n const originalRequest = this.hasCallback('fetchDidFail')\n ? request.clone()\n : null;\n try {\n for (const cb of this.iterateCallbacks('requestWillFetch')) {\n request = await cb({ request: request.clone(), event });\n }\n }\n catch (err) {\n if (err instanceof Error) {\n throw new WorkboxError('plugin-error-request-will-fetch', {\n thrownErrorMessage: err.message,\n });\n }\n }\n // The request can be altered by plugins with `requestWillFetch` making\n // the original request (most likely from a `fetch` event) different\n // from the Request we make. Pass both to `fetchDidFail` to aid debugging.\n const pluginFilteredRequest = request.clone();\n try {\n let fetchResponse;\n // See https://github.com/GoogleChrome/workbox/issues/1796\n fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Network request for ` +\n `'${getFriendlyURL(request.url)}' returned a response with ` +\n `status '${fetchResponse.status}'.`);\n }\n for (const callback of this.iterateCallbacks('fetchDidSucceed')) {\n fetchResponse = await callback({\n event,\n request: pluginFilteredRequest,\n response: fetchResponse,\n });\n }\n return fetchResponse;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Network request for ` +\n `'${getFriendlyURL(request.url)}' threw an error.`, error);\n }\n // `originalRequest` will only exist if a `fetchDidFail` callback\n // is being used (see above).\n if (originalRequest) {\n await this.runCallbacks('fetchDidFail', {\n error: error,\n event,\n originalRequest: originalRequest.clone(),\n request: pluginFilteredRequest.clone(),\n });\n }\n throw error;\n }\n }\n /**\n * Calls `this.fetch()` and (in the background) runs `this.cachePut()` on\n * the response generated by `this.fetch()`.\n *\n * The call to `this.cachePut()` automatically invokes `this.waitUntil()`,\n * so you do not have to manually call `waitUntil()` on the event.\n *\n * @param {Request|string} input The request or URL to fetch and cache.\n * @return {Promise}\n */\n async fetchAndCachePut(input) {\n const response = await this.fetch(input);\n const responseClone = response.clone();\n void this.waitUntil(this.cachePut(input, responseClone));\n return response;\n }\n /**\n * Matches a request from the cache (and invokes any applicable plugin\n * callback methods) using the `cacheName`, `matchOptions`, and `plugins`\n * defined on the strategy object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - cacheKeyWillByUsed()\n * - cachedResponseWillByUsed()\n *\n * @param {Request|string} key The Request or URL to use as the cache key.\n * @return {Promise} A matching response, if found.\n */\n async cacheMatch(key) {\n const request = toRequest(key);\n let cachedResponse;\n const { cacheName, matchOptions } = this._strategy;\n const effectiveRequest = await this.getCacheKey(request, 'read');\n const multiMatchOptions = Object.assign(Object.assign({}, matchOptions), { cacheName });\n cachedResponse = await caches.match(effectiveRequest, multiMatchOptions);\n if (process.env.NODE_ENV !== 'production') {\n if (cachedResponse) {\n logger.debug(`Found a cached response in '${cacheName}'.`);\n }\n else {\n logger.debug(`No cached response found in '${cacheName}'.`);\n }\n }\n for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {\n cachedResponse =\n (await callback({\n cacheName,\n matchOptions,\n cachedResponse,\n request: effectiveRequest,\n event: this.event,\n })) || undefined;\n }\n return cachedResponse;\n }\n /**\n * Puts a request/response pair in the cache (and invokes any applicable\n * plugin callback methods) using the `cacheName` and `plugins` defined on\n * the strategy object.\n *\n * The following plugin lifecycle methods are invoked when using this method:\n * - cacheKeyWillByUsed()\n * - cacheWillUpdate()\n * - cacheDidUpdate()\n *\n * @param {Request|string} key The request or URL to use as the cache key.\n * @param {Response} response The response to cache.\n * @return {Promise} `false` if a cacheWillUpdate caused the response\n * not be cached, and `true` otherwise.\n */\n async cachePut(key, response) {\n const request = toRequest(key);\n // Run in the next task to avoid blocking other cache reads.\n // https://github.com/w3c/ServiceWorker/issues/1397\n await timeout(0);\n const effectiveRequest = await this.getCacheKey(request, 'write');\n if (process.env.NODE_ENV !== 'production') {\n if (effectiveRequest.method && effectiveRequest.method !== 'GET') {\n throw new WorkboxError('attempt-to-cache-non-get-request', {\n url: getFriendlyURL(effectiveRequest.url),\n method: effectiveRequest.method,\n });\n }\n // See https://github.com/GoogleChrome/workbox/issues/2818\n const vary = response.headers.get('Vary');\n if (vary) {\n logger.debug(`The response for ${getFriendlyURL(effectiveRequest.url)} ` +\n `has a 'Vary: ${vary}' header. ` +\n `Consider setting the {ignoreVary: true} option on your strategy ` +\n `to ensure cache matching and deletion works as expected.`);\n }\n }\n if (!response) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(`Cannot cache non-existent response for ` +\n `'${getFriendlyURL(effectiveRequest.url)}'.`);\n }\n throw new WorkboxError('cache-put-with-no-response', {\n url: getFriendlyURL(effectiveRequest.url),\n });\n }\n const responseToCache = await this._ensureResponseSafeToCache(response);\n if (!responseToCache) {\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` +\n `will not be cached.`, responseToCache);\n }\n return false;\n }\n const { cacheName, matchOptions } = this._strategy;\n const cache = await self.caches.open(cacheName);\n const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');\n const oldResponse = hasCacheUpdateCallback\n ? await cacheMatchIgnoreParams(\n // TODO(philipwalton): the `__WB_REVISION__` param is a precaching\n // feature. Consider into ways to only add this behavior if using\n // precaching.\n cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions)\n : null;\n if (process.env.NODE_ENV !== 'production') {\n logger.debug(`Updating the '${cacheName}' cache with a new Response ` +\n `for ${getFriendlyURL(effectiveRequest.url)}.`);\n }\n try {\n await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);\n }\n catch (error) {\n if (error instanceof Error) {\n // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError\n if (error.name === 'QuotaExceededError') {\n await executeQuotaErrorCallbacks();\n }\n throw error;\n }\n }\n for (const callback of this.iterateCallbacks('cacheDidUpdate')) {\n await callback({\n cacheName,\n oldResponse,\n newResponse: responseToCache.clone(),\n request: effectiveRequest,\n event: this.event,\n });\n }\n return true;\n }\n /**\n * Checks the list of plugins for the `cacheKeyWillBeUsed` callback, and\n * executes any of those callbacks found in sequence. The final `Request`\n * object returned by the last plugin is treated as the cache key for cache\n * reads and/or writes. If no `cacheKeyWillBeUsed` plugin callbacks have\n * been registered, the passed request is returned unmodified\n *\n * @param {Request} request\n * @param {string} mode\n * @return {Promise}\n */\n async getCacheKey(request, mode) {\n const key = `${request.url} | ${mode}`;\n if (!this._cacheKeys[key]) {\n let effectiveRequest = request;\n for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {\n effectiveRequest = toRequest(await callback({\n mode,\n request: effectiveRequest,\n event: this.event,\n // params has a type any can't change right now.\n params: this.params, // eslint-disable-line\n }));\n }\n this._cacheKeys[key] = effectiveRequest;\n }\n return this._cacheKeys[key];\n }\n /**\n * Returns true if the strategy has at least one plugin with the given\n * callback.\n *\n * @param {string} name The name of the callback to check for.\n * @return {boolean}\n */\n hasCallback(name) {\n for (const plugin of this._strategy.plugins) {\n if (name in plugin) {\n return true;\n }\n }\n return false;\n }\n /**\n * Runs all plugin callbacks matching the given name, in order, passing the\n * given param object (merged ith the current plugin state) as the only\n * argument.\n *\n * Note: since this method runs all plugins, it's not suitable for cases\n * where the return value of a callback needs to be applied prior to calling\n * the next callback. See\n * {@link workbox-strategies.StrategyHandler#iterateCallbacks}\n * below for how to handle that case.\n *\n * @param {string} name The name of the callback to run within each plugin.\n * @param {Object} param The object to pass as the first (and only) param\n * when executing each callback. This object will be merged with the\n * current plugin state prior to callback execution.\n */\n async runCallbacks(name, param) {\n for (const callback of this.iterateCallbacks(name)) {\n // TODO(philipwalton): not sure why `any` is needed. It seems like\n // this should work with `as WorkboxPluginCallbackParam[C]`.\n await callback(param);\n }\n }\n /**\n * Accepts a callback and returns an iterable of matching plugin callbacks,\n * where each callback is wrapped with the current handler state (i.e. when\n * you call each callback, whatever object parameter you pass it will\n * be merged with the plugin's current state).\n *\n * @param {string} name The name fo the callback to run\n * @return {Array}\n */\n *iterateCallbacks(name) {\n for (const plugin of this._strategy.plugins) {\n if (typeof plugin[name] === 'function') {\n const state = this._pluginStateMap.get(plugin);\n const statefulCallback = (param) => {\n const statefulParam = Object.assign(Object.assign({}, param), { state });\n // TODO(philipwalton): not sure why `any` is needed. It seems like\n // this should work with `as WorkboxPluginCallbackParam[C]`.\n return plugin[name](statefulParam);\n };\n yield statefulCallback;\n }\n }\n }\n /**\n * Adds a promise to the\n * [extend lifetime promises]{@link https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises}\n * of the event event associated with the request being handled (usually a\n * `FetchEvent`).\n *\n * Note: you can await\n * {@link workbox-strategies.StrategyHandler~doneWaiting}\n * to know when all added promises have settled.\n *\n * @param {Promise} promise A promise to add to the extend lifetime promises\n * of the event that triggered the request.\n */\n waitUntil(promise) {\n this._extendLifetimePromises.push(promise);\n return promise;\n }\n /**\n * Returns a promise that resolves once all promises passed to\n * {@link workbox-strategies.StrategyHandler~waitUntil}\n * have settled.\n *\n * Note: any work done after `doneWaiting()` settles should be manually\n * passed to an event's `waitUntil()` method (not this handler's\n * `waitUntil()` method), otherwise the service worker thread my be killed\n * prior to your work completing.\n */\n async doneWaiting() {\n let promise;\n while ((promise = this._extendLifetimePromises.shift())) {\n await promise;\n }\n }\n /**\n * Stops running the strategy and immediately resolves any pending\n * `waitUntil()` promises.\n */\n destroy() {\n this._handlerDeferred.resolve(null);\n }\n /**\n * This method will call cacheWillUpdate on the available plugins (or use\n * status === 200) to determine if the Response is safe and valid to cache.\n *\n * @param {Request} options.request\n * @param {Response} options.response\n * @return {Promise}\n *\n * @private\n */\n async _ensureResponseSafeToCache(response) {\n let responseToCache = response;\n let pluginsUsed = false;\n for (const callback of this.iterateCallbacks('cacheWillUpdate')) {\n responseToCache =\n (await callback({\n request: this.request,\n response: responseToCache,\n event: this.event,\n })) || undefined;\n pluginsUsed = true;\n if (!responseToCache) {\n break;\n }\n }\n if (!pluginsUsed) {\n if (responseToCache && responseToCache.status !== 200) {\n responseToCache = undefined;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (responseToCache) {\n if (responseToCache.status !== 200) {\n if (responseToCache.status === 0) {\n logger.warn(`The response for '${this.request.url}' ` +\n `is an opaque response. The caching strategy that you're ` +\n `using will not cache opaque responses by default.`);\n }\n else {\n logger.debug(`The response for '${this.request.url}' ` +\n `returned a status code of '${response.status}' and won't ` +\n `be cached as a result.`);\n }\n }\n }\n }\n }\n return responseToCache;\n }\n}\nexport { StrategyHandler };\n","/*\n Copyright 2020 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { cacheNames } from 'workbox-core/_private/cacheNames.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { StrategyHandler } from './StrategyHandler.js';\nimport './_version.js';\n/**\n * An abstract base class that all other strategy classes must extend from:\n *\n * @memberof workbox-strategies\n */\nclass Strategy {\n /**\n * Creates a new instance of the strategy and sets all documented option\n * properties as public instance properties.\n *\n * Note: if a custom strategy class extends the base Strategy class and does\n * not need more than these properties, it does not need to define its own\n * constructor.\n *\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] The\n * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n */\n constructor(options = {}) {\n /**\n * Cache name to store and retrieve\n * requests. Defaults to the cache names provided by\n * {@link workbox-core.cacheNames}.\n *\n * @type {string}\n */\n this.cacheName = cacheNames.getRuntimeName(options.cacheName);\n /**\n * The list\n * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * used by this strategy.\n *\n * @type {Array}\n */\n this.plugins = options.plugins || [];\n /**\n * Values passed along to the\n * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}\n * of all fetch() requests made by this strategy.\n *\n * @type {Object}\n */\n this.fetchOptions = options.fetchOptions;\n /**\n * The\n * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}\n * for any `cache.match()` or `cache.put()` calls made by this strategy.\n *\n * @type {Object}\n */\n this.matchOptions = options.matchOptions;\n }\n /**\n * Perform a request strategy and returns a `Promise` that will resolve with\n * a `Response`, invoking all relevant plugin callbacks.\n *\n * When a strategy instance is registered with a Workbox\n * {@link workbox-routing.Route}, this method is automatically\n * called when the route matches.\n *\n * Alternatively, this method can be used in a standalone `FetchEvent`\n * listener by passing it to `event.respondWith()`.\n *\n * @param {FetchEvent|Object} options A `FetchEvent` or an object with the\n * properties listed below.\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params]\n */\n handle(options) {\n const [responseDone] = this.handleAll(options);\n return responseDone;\n }\n /**\n * Similar to {@link workbox-strategies.Strategy~handle}, but\n * instead of just returning a `Promise` that resolves to a `Response` it\n * it will return an tuple of `[response, done]` promises, where the former\n * (`response`) is equivalent to what `handle()` returns, and the latter is a\n * Promise that will resolve once any promises that were added to\n * `event.waitUntil()` as part of performing the strategy have completed.\n *\n * You can await the `done` promise to ensure any extra work performed by\n * the strategy (usually caching responses) completes successfully.\n *\n * @param {FetchEvent|Object} options A `FetchEvent` or an object with the\n * properties listed below.\n * @param {Request|string} options.request A request to run this strategy for.\n * @param {ExtendableEvent} options.event The event associated with the\n * request.\n * @param {URL} [options.url]\n * @param {*} [options.params]\n * @return {Array} A tuple of [response, done]\n * promises that can be used to determine when the response resolves as\n * well as when the handler has completed all its work.\n */\n handleAll(options) {\n // Allow for flexible options to be passed.\n if (options instanceof FetchEvent) {\n options = {\n event: options,\n request: options.request,\n };\n }\n const event = options.event;\n const request = typeof options.request === 'string'\n ? new Request(options.request)\n : options.request;\n const params = 'params' in options ? options.params : undefined;\n const handler = new StrategyHandler(this, { event, request, params });\n const responseDone = this._getResponse(handler, request, event);\n const handlerDone = this._awaitComplete(responseDone, handler, request, event);\n // Return an array of promises, suitable for use with Promise.all().\n return [responseDone, handlerDone];\n }\n async _getResponse(handler, request, event) {\n await handler.runCallbacks('handlerWillStart', { event, request });\n let response = undefined;\n try {\n response = await this._handle(request, handler);\n // The \"official\" Strategy subclasses all throw this error automatically,\n // but in case a third-party Strategy doesn't, ensure that we have a\n // consistent failure when there's no response or an error response.\n if (!response || response.type === 'error') {\n throw new WorkboxError('no-response', { url: request.url });\n }\n }\n catch (error) {\n if (error instanceof Error) {\n for (const callback of handler.iterateCallbacks('handlerDidError')) {\n response = await callback({ error, event, request });\n if (response) {\n break;\n }\n }\n }\n if (!response) {\n throw error;\n }\n else if (process.env.NODE_ENV !== 'production') {\n logger.log(`While responding to '${getFriendlyURL(request.url)}', ` +\n `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` +\n `a handlerDidError plugin.`);\n }\n }\n for (const callback of handler.iterateCallbacks('handlerWillRespond')) {\n response = await callback({ event, request, response });\n }\n return response;\n }\n async _awaitComplete(responseDone, handler, request, event) {\n let response;\n let error;\n try {\n response = await responseDone;\n }\n catch (error) {\n // Ignore errors, as response errors should be caught via the `response`\n // promise above. The `done` promise will only throw for errors in\n // promises passed to `handler.waitUntil()`.\n }\n try {\n await handler.runCallbacks('handlerDidRespond', {\n event,\n request,\n response,\n });\n await handler.doneWaiting();\n }\n catch (waitUntilError) {\n if (waitUntilError instanceof Error) {\n error = waitUntilError;\n }\n }\n await handler.runCallbacks('handlerDidComplete', {\n event,\n request,\n response,\n error: error,\n });\n handler.destroy();\n if (error) {\n throw error;\n }\n }\n}\nexport { Strategy };\n/**\n * Classes extending the `Strategy` based class should implement this method,\n * and leverage the {@link workbox-strategies.StrategyHandler}\n * arg to perform all fetching and cache logic, which will ensure all relevant\n * cache, cache options, fetch options and plugins are used (per the current\n * strategy instance).\n *\n * @name _handle\n * @instance\n * @abstract\n * @function\n * @param {Request} request\n * @param {workbox-strategies.StrategyHandler} handler\n * @return {Promise}\n *\n * @memberof workbox-strategies.Strategy\n */\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nexport const cacheOkAndOpaquePlugin = {\n /**\n * Returns a valid response (to allow caching) if the status is 200 (OK) or\n * 0 (opaque).\n *\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n *\n * @private\n */\n cacheWillUpdate: async ({ response }) => {\n if (response.status === 200 || response.status === 0) {\n return response;\n }\n return null;\n },\n};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a [cache-first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-first-falling-back-to-network)\n * request strategy.\n *\n * A cache first strategy is useful for assets that have been revisioned,\n * such as URLs like `/styles/example.a8f5f1.css`, since they\n * can be cached for long periods of time.\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass CacheFirst extends Strategy {\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'makeRequest',\n paramName: 'request',\n });\n }\n let response = await handler.cacheMatch(request);\n let error = undefined;\n if (!response) {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`No response found in the '${this.cacheName}' cache. ` +\n `Will respond with a network request.`);\n }\n try {\n response = await handler.fetchAndCachePut(request);\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Got response from network.`);\n }\n else {\n logs.push(`Unable to get a response from the network.`);\n }\n }\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Found a cached response in the '${this.cacheName}' cache.`);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { CacheFirst };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a [cache-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#cache-only)\n * request strategy.\n *\n * This class is useful if you want to take advantage of any\n * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).\n *\n * If there is no cache match, this will throw a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass CacheOnly extends Strategy {\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'makeRequest',\n paramName: 'request',\n });\n }\n const response = await handler.cacheMatch(request);\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n if (response) {\n logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`);\n messages.printFinalResponse(response);\n }\n else {\n logger.log(`No response found in the '${this.cacheName}' cache.`);\n }\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url });\n }\n return response;\n }\n}\nexport { CacheOnly };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [network first](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-first-falling-back-to-cache)\n * request strategy.\n *\n * By default, this strategy will cache responses with a 200 status code as\n * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n * Opaque responses are are cross-origin requests where the response doesn't\n * support [CORS](https://enable-cors.org/).\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass NetworkFirst extends Strategy {\n /**\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)\n * @param {number} [options.networkTimeoutSeconds] If set, any network requests\n * that fail to respond within the timeout will fallback to the cache.\n *\n * This option can be used to combat\n * \"[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}\"\n * scenarios.\n */\n constructor(options = {}) {\n super(options);\n // If this instance contains no plugins with a 'cacheWillUpdate' callback,\n // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.\n if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {\n this.plugins.unshift(cacheOkAndOpaquePlugin);\n }\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;\n if (process.env.NODE_ENV !== 'production') {\n if (this._networkTimeoutSeconds) {\n assert.isType(this._networkTimeoutSeconds, 'number', {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'constructor',\n paramName: 'networkTimeoutSeconds',\n });\n }\n }\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'handle',\n paramName: 'makeRequest',\n });\n }\n const promises = [];\n let timeoutId;\n if (this._networkTimeoutSeconds) {\n const { id, promise } = this._getTimeoutPromise({ request, logs, handler });\n timeoutId = id;\n promises.push(promise);\n }\n const networkPromise = this._getNetworkPromise({\n timeoutId,\n request,\n logs,\n handler,\n });\n promises.push(networkPromise);\n const response = await handler.waitUntil((async () => {\n // Promise.race() will resolve as soon as the first promise resolves.\n return ((await handler.waitUntil(Promise.race(promises))) ||\n // If Promise.race() resolved with null, it might be due to a network\n // timeout + a cache miss. If that were to happen, we'd rather wait until\n // the networkPromise resolves instead of returning null.\n // Note that it's fine to await an already-resolved promise, so we don't\n // have to check to see if it's still \"in flight\".\n (await networkPromise));\n })());\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url });\n }\n return response;\n }\n /**\n * @param {Object} options\n * @param {Request} options.request\n * @param {Array} options.logs A reference to the logs array\n * @param {Event} options.event\n * @return {Promise}\n *\n * @private\n */\n _getTimeoutPromise({ request, logs, handler, }) {\n let timeoutId;\n const timeoutPromise = new Promise((resolve) => {\n const onNetworkTimeout = async () => {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Timing out the network response at ` +\n `${this._networkTimeoutSeconds} seconds.`);\n }\n resolve(await handler.cacheMatch(request));\n };\n timeoutId = setTimeout(onNetworkTimeout, this._networkTimeoutSeconds * 1000);\n });\n return {\n promise: timeoutPromise,\n id: timeoutId,\n };\n }\n /**\n * @param {Object} options\n * @param {number|undefined} options.timeoutId\n * @param {Request} options.request\n * @param {Array} options.logs A reference to the logs Array.\n * @param {Event} options.event\n * @return {Promise}\n *\n * @private\n */\n async _getNetworkPromise({ timeoutId, request, logs, handler, }) {\n let error;\n let response;\n try {\n response = await handler.fetchAndCachePut(request);\n }\n catch (fetchError) {\n if (fetchError instanceof Error) {\n error = fetchError;\n }\n }\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Got response from network.`);\n }\n else {\n logs.push(`Unable to get a response from the network. Will respond ` +\n `with a cached response.`);\n }\n }\n if (error || !response) {\n response = await handler.cacheMatch(request);\n if (process.env.NODE_ENV !== 'production') {\n if (response) {\n logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`);\n }\n else {\n logs.push(`No response found in the '${this.cacheName}' cache.`);\n }\n }\n }\n return response;\n }\n}\nexport { NetworkFirst };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [network-only](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#network-only)\n * request strategy.\n *\n * This class is useful if you want to take advantage of any\n * [Workbox plugins](https://developer.chrome.com/docs/workbox/using-plugins/).\n *\n * If the network request fails, this will throw a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass NetworkOnly extends Strategy {\n /**\n * @param {Object} [options]\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {number} [options.networkTimeoutSeconds] If set, any network requests\n * that fail to respond within the timeout will result in a network error.\n */\n constructor(options = {}) {\n super(options);\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || 0;\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: '_handle',\n paramName: 'request',\n });\n }\n let error = undefined;\n let response;\n try {\n const promises = [\n handler.fetch(request),\n ];\n if (this._networkTimeoutSeconds) {\n const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);\n promises.push(timeoutPromise);\n }\n response = await Promise.race(promises);\n if (!response) {\n throw new Error(`Timed out the network response after ` +\n `${this._networkTimeoutSeconds} seconds.`);\n }\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n if (response) {\n logger.log(`Got response from network.`);\n }\n else {\n logger.log(`Unable to get a response from the network.`);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { NetworkOnly };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { cacheOkAndOpaquePlugin } from './plugins/cacheOkAndOpaquePlugin.js';\nimport { Strategy } from './Strategy.js';\nimport { messages } from './utils/messages.js';\nimport './_version.js';\n/**\n * An implementation of a\n * [stale-while-revalidate](https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate)\n * request strategy.\n *\n * Resources are requested from both the cache and the network in parallel.\n * The strategy will respond with the cached version if available, otherwise\n * wait for the network response. The cache is updated with the network response\n * with each successful request.\n *\n * By default, this strategy will cache responses with a 200 status code as\n * well as [opaque responses](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\n * Opaque responses are cross-origin requests where the response doesn't\n * support [CORS](https://enable-cors.org/).\n *\n * If the network request fails, and there is no cache match, this will throw\n * a `WorkboxError` exception.\n *\n * @extends workbox-strategies.Strategy\n * @memberof workbox-strategies\n */\nclass StaleWhileRevalidate extends Strategy {\n /**\n * @param {Object} [options]\n * @param {string} [options.cacheName] Cache name to store and retrieve\n * requests. Defaults to cache names provided by\n * {@link workbox-core.cacheNames}.\n * @param {Array} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}\n * to use in conjunction with this caching strategy.\n * @param {Object} [options.fetchOptions] Values passed along to the\n * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)\n * `fetch()` requests made by this strategy.\n * @param {Object} [options.matchOptions] [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)\n */\n constructor(options = {}) {\n super(options);\n // If this instance contains no plugins with a 'cacheWillUpdate' callback,\n // prepend the `cacheOkAndOpaquePlugin` plugin to the plugins list.\n if (!this.plugins.some((p) => 'cacheWillUpdate' in p)) {\n this.plugins.unshift(cacheOkAndOpaquePlugin);\n }\n }\n /**\n * @private\n * @param {Request|string} request A request to run this strategy for.\n * @param {workbox-strategies.StrategyHandler} handler The event that\n * triggered the request.\n * @return {Promise}\n */\n async _handle(request, handler) {\n const logs = [];\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(request, Request, {\n moduleName: 'workbox-strategies',\n className: this.constructor.name,\n funcName: 'handle',\n paramName: 'request',\n });\n }\n const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {\n // Swallow this error because a 'no-response' error will be thrown in\n // main handler return flow. This will be in the `waitUntil()` flow.\n });\n void handler.waitUntil(fetchAndCachePromise);\n let response = await handler.cacheMatch(request);\n let error;\n if (response) {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`Found a cached response in the '${this.cacheName}'` +\n ` cache. Will update with the network response in the background.`);\n }\n }\n else {\n if (process.env.NODE_ENV !== 'production') {\n logs.push(`No response found in the '${this.cacheName}' cache. ` +\n `Will wait for the network response.`);\n }\n try {\n // NOTE(philipwalton): Really annoying that we have to type cast here.\n // https://github.com/microsoft/TypeScript/issues/20006\n response = (await fetchAndCachePromise);\n }\n catch (err) {\n if (err instanceof Error) {\n error = err;\n }\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(messages.strategyStart(this.constructor.name, request));\n for (const log of logs) {\n logger.log(log);\n }\n messages.printFinalResponse(response);\n logger.groupEnd();\n }\n if (!response) {\n throw new WorkboxError('no-response', { url: request.url, error });\n }\n return response;\n }\n}\nexport { StaleWhileRevalidate };\n"],"names":["self","_","e","toRequest","input","Request","StrategyHandler","constructor","strategy","options","_cacheKeys","Object","assign","this","event","_strategy","_handlerDeferred","Deferred","_extendLifetimePromises","_plugins","plugins","_pluginStateMap","Map","plugin","set","waitUntil","promise","request","mode","FetchEvent","preloadResponse","possiblePreloadResponse","originalRequest","hasCallback","clone","cb","iterateCallbacks","err","Error","WorkboxError","thrownErrorMessage","message","pluginFilteredRequest","fetchResponse","fetch","undefined","fetchOptions","callback","response","error","runCallbacks","responseClone","cachePut","key","cachedResponse","cacheName","matchOptions","effectiveRequest","getCacheKey","multiMatchOptions","caches","match","timeout","url","getFriendlyURL","responseToCache","_ensureResponseSafeToCache","cache","open","hasCacheUpdateCallback","oldResponse","cacheMatchIgnoreParams","put","name","executeQuotaErrorCallbacks","newResponse","params","param","state","get","statefulCallback","statefulParam","push","shift","destroy","resolve","pluginsUsed","status","Strategy","cacheNames","getRuntimeName","handle","responseDone","handleAll","handler","_getResponse","_awaitComplete","_handle","type","doneWaiting","waitUntilError","cacheOkAndOpaquePlugin","cacheWillUpdate","async","cacheMatch","fetchAndCachePut","some","p","unshift","_networkTimeoutSeconds","networkTimeoutSeconds","logs","promises","timeoutId","id","_getTimeoutPromise","networkPromise","_getNetworkPromise","Promise","race","setTimeout","fetchError","clearTimeout","timeoutPromise","fetchAndCachePromise","catch"],"mappings":"+FAEA,IACIA,KAAK,6BAA+BC,GACvC,CACD,MAAOC,ICWP,SAASC,EAAUC,SACS,iBAAVA,EAAqB,IAAIC,QAAQD,GAASA,CAC3D,CAUD,MAAME,EAiBFC,YAAYC,EAAUC,QACbC,GAAa,GA8ClBC,OAAOC,OAAOC,KAAMJ,QACfK,MAAQL,EAAQK,WAChBC,GAAYP,OACZQ,GAAmB,IAAIC,gBACvBC,GAA0B,QAG1BC,GAAW,IAAIX,EAASY,cACxBC,GAAkB,IAAIC,QACtB,MAAMC,KAAUV,KAAKM,QACjBE,GAAgBG,IAAID,EAAQ,SAEhCT,MAAMW,UAAUZ,KAAKG,GAAiBU,qBAenCtB,SACFU,MAAEA,GAAUD,SACdc,EAAUxB,EAAUC,MACH,aAAjBuB,EAAQC,MACRd,aAAiBe,YACjBf,EAAMgB,gBAAiB,OACjBC,QAAiCjB,EAAMgB,mBACzCC,SAKOA,QAMTC,EAAkBnB,KAAKoB,YAAY,gBACnCN,EAAQO,QACR,aAEG,MAAMC,KAAMtB,KAAKuB,iBAAiB,oBACnCT,QAAgBQ,EAAG,CAAER,QAASA,EAAQO,QAASpB,UAGvD,MAAOuB,MACCA,aAAeC,YACT,IAAIC,eAAa,kCAAmC,CACtDC,mBAAoBH,EAAII,gBAO9BC,EAAwBf,EAAQO,gBAE9BS,EAEJA,QAAsBC,MAAMjB,EAA0B,aAAjBA,EAAQC,UAAsBiB,EAAYhC,KAAKE,GAAU+B,kBAMzF,MAAMC,KAAYlC,KAAKuB,iBAAiB,mBACzCO,QAAsBI,EAA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workbox-streams.dev.js b/src/Resources/workbox-v7.0.0/workbox-streams.dev.js new file mode 100644 index 0000000..cf17aa1 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-streams.dev.js @@ -0,0 +1,331 @@ +this.workbox = this.workbox || {}; +this.workbox.streams = (function (exports, assert_js, Deferred_js, logger_js, WorkboxError_js, canConstructReadableStream_js) { + 'use strict'; + + try { + self['workbox:streams:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Takes either a Response, a ReadableStream, or a + * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the + * ReadableStreamReader object associated with it. + * + * @param {workbox-streams.StreamSource} source + * @return {ReadableStreamReader} + * @private + */ + + function _getReaderFromSource(source) { + if (source instanceof Response) { + // See https://github.com/GoogleChrome/workbox/issues/2998 + if (source.body) { + return source.body.getReader(); + } + + throw new WorkboxError_js.WorkboxError('opaque-streams-source', { + type: source.type + }); + } + + if (source instanceof ReadableStream) { + return source.getReader(); + } + + return new Response(source).body.getReader(); + } + /** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit). + * + * Returns an object exposing a ReadableStream with each individual stream's + * data returned in sequence, along with a Promise which signals when the + * stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @return {Object<{done: Promise, stream: ReadableStream}>} + * + * @memberof workbox-streams + */ + + + function concatenate(sourcePromises) { + { + assert_js.assert.isArray(sourcePromises, { + moduleName: 'workbox-streams', + funcName: 'concatenate', + paramName: 'sourcePromises' + }); + } + + const readerPromises = sourcePromises.map(sourcePromise => { + return Promise.resolve(sourcePromise).then(source => { + return _getReaderFromSource(source); + }); + }); + const streamDeferred = new Deferred_js.Deferred(); + let i = 0; + const logMessages = []; + const stream = new ReadableStream({ + pull(controller) { + return readerPromises[i].then(reader => { + if (reader instanceof ReadableStreamDefaultReader) { + return reader.read(); + } else { + return; + } + }).then(result => { + if (result === null || result === void 0 ? void 0 : result.done) { + { + logMessages.push(['Reached the end of source:', sourcePromises[i]]); + } + + i++; + + if (i >= readerPromises.length) { + // Log all the messages in the group at once in a single group. + { + logger_js.logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`); + + for (const message of logMessages) { + if (Array.isArray(message)) { + logger_js.logger.log(...message); + } else { + logger_js.logger.log(message); + } + } + + logger_js.logger.log('Finished reading all sources.'); + logger_js.logger.groupEnd(); + } + + controller.close(); + streamDeferred.resolve(); + return; + } // The `pull` method is defined because we're inside it. + + + return this.pull(controller); + } else { + controller.enqueue(result === null || result === void 0 ? void 0 : result.value); + } + }).catch(error => { + { + logger_js.logger.error('An error occurred:', error); + } + + streamDeferred.reject(error); + throw error; + }); + }, + + cancel() { + { + logger_js.logger.warn('The ReadableStream was cancelled.'); + } + + streamDeferred.resolve(); + } + + }); + return { + done: streamDeferred.promise, + stream + }; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * is available. + * + * @private + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ + + function createHeaders(headersInit = {}) { + // See https://github.com/GoogleChrome/workbox/issues/1461 + const headers = new Headers(headersInit); + + if (!headers.has('content-type')) { + headers.set('content-type', 'text/html'); + } + + return headers; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Takes multiple source Promises, each of which could resolve to a Response, a + * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit), + * along with a + * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit). + * + * Returns an object exposing a Response whose body consists of each individual + * stream's data returned in sequence, along with a Promise which signals when + * the stream is finished (useful for passing to a FetchEvent's waitUntil()). + * + * @param {Array>} sourcePromises + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {Object<{done: Promise, response: Response}>} + * + * @memberof workbox-streams + */ + + function concatenateToResponse(sourcePromises, headersInit) { + const { + done, + stream + } = concatenate(sourcePromises); + const headers = createHeaders(headersInit); + const response = new Response(stream, { + headers + }); + return { + done, + response + }; + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * This is a utility method that determines whether the current browser supports + * the features required to create streamed responses. Currently, it checks if + * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) + * can be created. + * + * @return {boolean} `true`, if the current browser meets the requirements for + * streaming responses, and `false` otherwise. + * + * @memberof workbox-streams + */ + + function isSupported() { + return canConstructReadableStream_js.canConstructReadableStream(); + } + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A shortcut to create a strategy that could be dropped-in to Workbox's router. + * + * On browsers that do not support constructing new `ReadableStream`s, this + * strategy will automatically wait for all the `sourceFunctions` to complete, + * and create a final response that concatenates their values together. + * + * @param {Array} sourceFunctions + * An array of functions similar to {@link workbox-routing~handlerCallback} + * but that instead return a {@link workbox-streams.StreamSource} (or a + * Promise which resolves to one). + * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified, + * `'text/html'` will be used by default. + * @return {workbox-routing~handlerCallback} + * @memberof workbox-streams + */ + + function strategy(sourceFunctions, headersInit) { + return async ({ + event, + request, + url, + params + }) => { + const sourcePromises = sourceFunctions.map(fn => { + // Ensure the return value of the function is always a promise. + return Promise.resolve(fn({ + event, + request, + url, + params + })); + }); + + if (isSupported()) { + const { + done, + response + } = concatenateToResponse(sourcePromises, headersInit); + + if (event) { + event.waitUntil(done); + } + + return response; + } + + { + logger_js.logger.log(`The current browser doesn't support creating response ` + `streams. Falling back to non-streaming response instead.`); + } // Fallback to waiting for everything to finish, and concatenating the + // responses. + + + const blobPartsPromises = sourcePromises.map(async sourcePromise => { + const source = await sourcePromise; + + if (source instanceof Response) { + return source.blob(); + } else { + // Technically, a `StreamSource` object can include any valid + // `BodyInit` type, including `FormData` and `URLSearchParams`, which + // cannot be passed to the Blob constructor directly, so we have to + // convert them to actual Blobs first. + return new Response(source).blob(); + } + }); + const blobParts = await Promise.all(blobPartsPromises); + const headers = createHeaders(headersInit); // Constructing a new Response from a Blob source is well-supported. + // So is constructing a new Blob from multiple source Blobs or strings. + + return new Response(new Blob(blobParts), { + headers + }); + }; + } + + exports.concatenate = concatenate; + exports.concatenateToResponse = concatenateToResponse; + exports.isSupported = isSupported; + exports.strategy = strategy; + + return exports; + +}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private)); +//# sourceMappingURL=workbox-streams.dev.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-streams.dev.js.map b/src/Resources/workbox-v7.0.0/workbox-streams.dev.js.map new file mode 100644 index 0000000..967f332 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-streams.dev.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-streams.dev.js","sources":["../_version.js","../concatenate.js","../utils/createHeaders.js","../concatenateToResponse.js","../isSupported.js","../strategy.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:streams:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Takes either a Response, a ReadableStream, or a\n * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the\n * ReadableStreamReader object associated with it.\n *\n * @param {workbox-streams.StreamSource} source\n * @return {ReadableStreamReader}\n * @private\n */\nfunction _getReaderFromSource(source) {\n if (source instanceof Response) {\n // See https://github.com/GoogleChrome/workbox/issues/2998\n if (source.body) {\n return source.body.getReader();\n }\n throw new WorkboxError('opaque-streams-source', { type: source.type });\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n return new Response(source).body.getReader();\n}\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit).\n *\n * Returns an object exposing a ReadableStream with each individual stream's\n * data returned in sequence, along with a Promise which signals when the\n * stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array>} sourcePromises\n * @return {Object<{done: Promise, stream: ReadableStream}>}\n *\n * @memberof workbox-streams\n */\nfunction concatenate(sourcePromises) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(sourcePromises, {\n moduleName: 'workbox-streams',\n funcName: 'concatenate',\n paramName: 'sourcePromises',\n });\n }\n const readerPromises = sourcePromises.map((sourcePromise) => {\n return Promise.resolve(sourcePromise).then((source) => {\n return _getReaderFromSource(source);\n });\n });\n const streamDeferred = new Deferred();\n let i = 0;\n const logMessages = [];\n const stream = new ReadableStream({\n pull(controller) {\n return readerPromises[i]\n .then((reader) => {\n if (reader instanceof ReadableStreamDefaultReader) {\n return reader.read();\n }\n else {\n return;\n }\n })\n .then((result) => {\n if (result === null || result === void 0 ? void 0 : result.done) {\n if (process.env.NODE_ENV !== 'production') {\n logMessages.push([\n 'Reached the end of source:',\n sourcePromises[i],\n ]);\n }\n i++;\n if (i >= readerPromises.length) {\n // Log all the messages in the group at once in a single group.\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`);\n for (const message of logMessages) {\n if (Array.isArray(message)) {\n logger.log(...message);\n }\n else {\n logger.log(message);\n }\n }\n logger.log('Finished reading all sources.');\n logger.groupEnd();\n }\n controller.close();\n streamDeferred.resolve();\n return;\n }\n // The `pull` method is defined because we're inside it.\n return this.pull(controller);\n }\n else {\n controller.enqueue(result === null || result === void 0 ? void 0 : result.value);\n }\n })\n .catch((error) => {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('An error occurred:', error);\n }\n streamDeferred.reject(error);\n throw error;\n });\n },\n cancel() {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('The ReadableStream was cancelled.');\n }\n streamDeferred.resolve();\n },\n });\n return { done: streamDeferred.promise, stream };\n}\nexport { concatenate };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * is available.\n *\n * @private\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox-streams\n */\nfunction createHeaders(headersInit = {}) {\n // See https://github.com/GoogleChrome/workbox/issues/1461\n const headers = new Headers(headersInit);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'text/html');\n }\n return headers;\n}\nexport { createHeaders };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { createHeaders } from './utils/createHeaders.js';\nimport { concatenate } from './concatenate.js';\nimport './_version.js';\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit),\n * along with a\n * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit).\n *\n * Returns an object exposing a Response whose body consists of each individual\n * stream's data returned in sequence, along with a Promise which signals when\n * the stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array>} sourcePromises\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {Object<{done: Promise, response: Response}>}\n *\n * @memberof workbox-streams\n */\nfunction concatenateToResponse(sourcePromises, headersInit) {\n const { done, stream } = concatenate(sourcePromises);\n const headers = createHeaders(headersInit);\n const response = new Response(stream, { headers });\n return { done, response };\n}\nexport { concatenateToResponse };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { canConstructReadableStream } from 'workbox-core/_private/canConstructReadableStream.js';\nimport './_version.js';\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * can be created.\n *\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox-streams\n */\nfunction isSupported() {\n return canConstructReadableStream();\n}\nexport { isSupported };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { createHeaders } from './utils/createHeaders.js';\nimport { concatenateToResponse } from './concatenateToResponse.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * A shortcut to create a strategy that could be dropped-in to Workbox's router.\n *\n * On browsers that do not support constructing new `ReadableStream`s, this\n * strategy will automatically wait for all the `sourceFunctions` to complete,\n * and create a final response that concatenates their values together.\n *\n * @param {Array} sourceFunctions\n * An array of functions similar to {@link workbox-routing~handlerCallback}\n * but that instead return a {@link workbox-streams.StreamSource} (or a\n * Promise which resolves to one).\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {workbox-routing~handlerCallback}\n * @memberof workbox-streams\n */\nfunction strategy(sourceFunctions, headersInit) {\n return async ({ event, request, url, params }) => {\n const sourcePromises = sourceFunctions.map((fn) => {\n // Ensure the return value of the function is always a promise.\n return Promise.resolve(fn({ event, request, url, params }));\n });\n if (isSupported()) {\n const { done, response } = concatenateToResponse(sourcePromises, headersInit);\n if (event) {\n event.waitUntil(done);\n }\n return response;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The current browser doesn't support creating response ` +\n `streams. Falling back to non-streaming response instead.`);\n }\n // Fallback to waiting for everything to finish, and concatenating the\n // responses.\n const blobPartsPromises = sourcePromises.map(async (sourcePromise) => {\n const source = await sourcePromise;\n if (source instanceof Response) {\n return source.blob();\n }\n else {\n // Technically, a `StreamSource` object can include any valid\n // `BodyInit` type, including `FormData` and `URLSearchParams`, which\n // cannot be passed to the Blob constructor directly, so we have to\n // convert them to actual Blobs first.\n return new Response(source).blob();\n }\n });\n const blobParts = await Promise.all(blobPartsPromises);\n const headers = createHeaders(headersInit);\n // Constructing a new Response from a Blob source is well-supported.\n // So is constructing a new Blob from multiple source Blobs or strings.\n return new Response(new Blob(blobParts), { headers });\n };\n}\nexport { strategy };\n"],"names":["self","_","e","_getReaderFromSource","source","Response","body","getReader","WorkboxError","type","ReadableStream","concatenate","sourcePromises","assert","isArray","moduleName","funcName","paramName","readerPromises","map","sourcePromise","Promise","resolve","then","streamDeferred","Deferred","i","logMessages","stream","pull","controller","reader","ReadableStreamDefaultReader","read","result","done","push","length","logger","groupCollapsed","message","Array","log","groupEnd","close","enqueue","value","catch","error","reject","cancel","warn","promise","createHeaders","headersInit","headers","Headers","has","set","concatenateToResponse","response","isSupported","canConstructReadableStream","strategy","sourceFunctions","event","request","url","params","fn","waitUntil","blobPartsPromises","blob","blobParts","all","Blob"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,uBAAD,CAAJ,IAAiCC,CAAC,EAAlC;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAMA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASC,oBAAT,CAA8BC,MAA9B,EAAsC;IAClC,MAAIA,MAAM,YAAYC,QAAtB,EAAgC;IAC5B;IACA,QAAID,MAAM,CAACE,IAAX,EAAiB;IACb,aAAOF,MAAM,CAACE,IAAP,CAAYC,SAAZ,EAAP;IACH;;IACD,UAAM,IAAIC,4BAAJ,CAAiB,uBAAjB,EAA0C;IAAEC,MAAAA,IAAI,EAAEL,MAAM,CAACK;IAAf,KAA1C,CAAN;IACH;;IACD,MAAIL,MAAM,YAAYM,cAAtB,EAAsC;IAClC,WAAON,MAAM,CAACG,SAAP,EAAP;IACH;;IACD,SAAO,IAAIF,QAAJ,CAAaD,MAAb,EAAqBE,IAArB,CAA0BC,SAA1B,EAAP;IACH;IACD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;IACA,SAASI,WAAT,CAAqBC,cAArB,EAAqC;IACjC,EAA2C;IACvCC,IAAAA,gBAAM,CAACC,OAAP,CAAeF,cAAf,EAA+B;IAC3BG,MAAAA,UAAU,EAAE,iBADe;IAE3BC,MAAAA,QAAQ,EAAE,aAFiB;IAG3BC,MAAAA,SAAS,EAAE;IAHgB,KAA/B;IAKH;;IACD,QAAMC,cAAc,GAAGN,cAAc,CAACO,GAAf,CAAoBC,aAAD,IAAmB;IACzD,WAAOC,OAAO,CAACC,OAAR,CAAgBF,aAAhB,EAA+BG,IAA/B,CAAqCnB,MAAD,IAAY;IACnD,aAAOD,oBAAoB,CAACC,MAAD,CAA3B;IACH,KAFM,CAAP;IAGH,GAJsB,CAAv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BnC,IAAhB;IACH;;IACD,aAAOyB,QAAP;IACH;;IACD,IAA2C;IACvCtB,MAAAA,gBAAM,CAACI,GAAP,CAAY,wDAAD,GACN,0DADL;IAEH,KAf6C;IAiB9C;;;IACA,UAAM6B,iBAAiB,GAAG3D,cAAc,CAACO,GAAf,CAAmB,MAAOC,aAAP,IAAyB;IAClE,YAAMhB,MAAM,GAAG,MAAMgB,aAArB;;IACA,UAAIhB,MAAM,YAAYC,QAAtB,EAAgC;IAC5B,eAAOD,MAAM,CAACoE,IAAP,EAAP;IACH,OAFD,MAGK;IACD;IACA;IACA;IACA;IACA,eAAO,IAAInE,QAAJ,CAAaD,MAAb,EAAqBoE,IAArB,EAAP;IACH;IACJ,KAZyB,CAA1B;IAaA,UAAMC,SAAS,GAAG,MAAMpD,OAAO,CAACqD,GAAR,CAAYH,iBAAZ,CAAxB;IACA,UAAMhB,OAAO,GAAGF,aAAa,CAACC,WAAD,CAA7B,CAhC8C;IAkC9C;;IACA,WAAO,IAAIjD,QAAJ,CAAa,IAAIsE,IAAJ,CAASF,SAAT,CAAb,EAAkC;IAAElB,MAAAA;IAAF,KAAlC,CAAP;IACH,GApCD;IAqCH;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-streams.prod.js b/src/Resources/workbox-v7.0.0/workbox-streams.prod.js new file mode 100644 index 0000000..163b1ce --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-streams.prod.js @@ -0,0 +1,2 @@ +this.workbox=this.workbox||{},this.workbox.streams=function(e,n,t,r){"use strict";try{self["workbox:streams:7.0.0"]&&_()}catch(e){}function s(e){const r=e.map((e=>Promise.resolve(e).then((e=>function(e){if(e instanceof Response){if(e.body)return e.body.getReader();throw new t.WorkboxError("opaque-streams-source",{type:e.type})}return e instanceof ReadableStream?e.getReader():new Response(e).body.getReader()}(e))))),s=new n.Deferred;let o=0;const a=new ReadableStream({pull(e){return r[o].then((e=>e instanceof ReadableStreamDefaultReader?e.read():void 0)).then((n=>{if(null==n?void 0:n.done)return o++,o>=r.length?(e.close(),void s.resolve()):this.pull(e);e.enqueue(null==n?void 0:n.value)})).catch((e=>{throw s.reject(e),e}))},cancel(){s.resolve()}});return{done:s.promise,stream:a}}function o(e={}){const n=new Headers(e);return n.has("content-type")||n.set("content-type","text/html"),n}function a(e,n){const{done:t,stream:r}=s(e),a=o(n);return{done:t,response:new Response(r,{headers:a})}}function u(){return r.canConstructReadableStream()}return e.concatenate=s,e.concatenateToResponse=a,e.isSupported=u,e.strategy=function(e,n){return async({event:t,request:r,url:s,params:c})=>{const i=e.map((e=>Promise.resolve(e({event:t,request:r,url:s,params:c}))));if(u()){const{done:e,response:r}=a(i,n);return t&&t.waitUntil(e),r}const f=i.map((async e=>{const n=await e;return n instanceof Response?n.blob():new Response(n).blob()})),l=await Promise.all(f),w=o(n);return new Response(new Blob(l),{headers:w})}},e}({},workbox.core._private,workbox.core._private,workbox.core._private); +//# sourceMappingURL=workbox-streams.prod.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-streams.prod.js.map b/src/Resources/workbox-v7.0.0/workbox-streams.prod.js.map new file mode 100644 index 0000000..eebd000 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-streams.prod.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-streams.prod.js","sources":["../_version.js","../concatenate.js","../utils/createHeaders.js","../concatenateToResponse.js","../isSupported.js","../strategy.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:streams:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport './_version.js';\n/**\n * Takes either a Response, a ReadableStream, or a\n * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the\n * ReadableStreamReader object associated with it.\n *\n * @param {workbox-streams.StreamSource} source\n * @return {ReadableStreamReader}\n * @private\n */\nfunction _getReaderFromSource(source) {\n if (source instanceof Response) {\n // See https://github.com/GoogleChrome/workbox/issues/2998\n if (source.body) {\n return source.body.getReader();\n }\n throw new WorkboxError('opaque-streams-source', { type: source.type });\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n return new Response(source).body.getReader();\n}\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit).\n *\n * Returns an object exposing a ReadableStream with each individual stream's\n * data returned in sequence, along with a Promise which signals when the\n * stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array>} sourcePromises\n * @return {Object<{done: Promise, stream: ReadableStream}>}\n *\n * @memberof workbox-streams\n */\nfunction concatenate(sourcePromises) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(sourcePromises, {\n moduleName: 'workbox-streams',\n funcName: 'concatenate',\n paramName: 'sourcePromises',\n });\n }\n const readerPromises = sourcePromises.map((sourcePromise) => {\n return Promise.resolve(sourcePromise).then((source) => {\n return _getReaderFromSource(source);\n });\n });\n const streamDeferred = new Deferred();\n let i = 0;\n const logMessages = [];\n const stream = new ReadableStream({\n pull(controller) {\n return readerPromises[i]\n .then((reader) => {\n if (reader instanceof ReadableStreamDefaultReader) {\n return reader.read();\n }\n else {\n return;\n }\n })\n .then((result) => {\n if (result === null || result === void 0 ? void 0 : result.done) {\n if (process.env.NODE_ENV !== 'production') {\n logMessages.push([\n 'Reached the end of source:',\n sourcePromises[i],\n ]);\n }\n i++;\n if (i >= readerPromises.length) {\n // Log all the messages in the group at once in a single group.\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`);\n for (const message of logMessages) {\n if (Array.isArray(message)) {\n logger.log(...message);\n }\n else {\n logger.log(message);\n }\n }\n logger.log('Finished reading all sources.');\n logger.groupEnd();\n }\n controller.close();\n streamDeferred.resolve();\n return;\n }\n // The `pull` method is defined because we're inside it.\n return this.pull(controller);\n }\n else {\n controller.enqueue(result === null || result === void 0 ? void 0 : result.value);\n }\n })\n .catch((error) => {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('An error occurred:', error);\n }\n streamDeferred.reject(error);\n throw error;\n });\n },\n cancel() {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('The ReadableStream was cancelled.');\n }\n streamDeferred.resolve();\n },\n });\n return { done: streamDeferred.promise, stream };\n}\nexport { concatenate };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * is available.\n *\n * @private\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox-streams\n */\nfunction createHeaders(headersInit = {}) {\n // See https://github.com/GoogleChrome/workbox/issues/1461\n const headers = new Headers(headersInit);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'text/html');\n }\n return headers;\n}\nexport { createHeaders };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { createHeaders } from './utils/createHeaders.js';\nimport { concatenate } from './concatenate.js';\nimport './_version.js';\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit),\n * along with a\n * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit).\n *\n * Returns an object exposing a Response whose body consists of each individual\n * stream's data returned in sequence, along with a Promise which signals when\n * the stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array>} sourcePromises\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {Object<{done: Promise, response: Response}>}\n *\n * @memberof workbox-streams\n */\nfunction concatenateToResponse(sourcePromises, headersInit) {\n const { done, stream } = concatenate(sourcePromises);\n const headers = createHeaders(headersInit);\n const response = new Response(stream, { headers });\n return { done, response };\n}\nexport { concatenateToResponse };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { canConstructReadableStream } from 'workbox-core/_private/canConstructReadableStream.js';\nimport './_version.js';\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * can be created.\n *\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox-streams\n */\nfunction isSupported() {\n return canConstructReadableStream();\n}\nexport { isSupported };\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { createHeaders } from './utils/createHeaders.js';\nimport { concatenateToResponse } from './concatenateToResponse.js';\nimport { isSupported } from './isSupported.js';\nimport './_version.js';\n/**\n * A shortcut to create a strategy that could be dropped-in to Workbox's router.\n *\n * On browsers that do not support constructing new `ReadableStream`s, this\n * strategy will automatically wait for all the `sourceFunctions` to complete,\n * and create a final response that concatenates their values together.\n *\n * @param {Array} sourceFunctions\n * An array of functions similar to {@link workbox-routing~handlerCallback}\n * but that instead return a {@link workbox-streams.StreamSource} (or a\n * Promise which resolves to one).\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {workbox-routing~handlerCallback}\n * @memberof workbox-streams\n */\nfunction strategy(sourceFunctions, headersInit) {\n return async ({ event, request, url, params }) => {\n const sourcePromises = sourceFunctions.map((fn) => {\n // Ensure the return value of the function is always a promise.\n return Promise.resolve(fn({ event, request, url, params }));\n });\n if (isSupported()) {\n const { done, response } = concatenateToResponse(sourcePromises, headersInit);\n if (event) {\n event.waitUntil(done);\n }\n return response;\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The current browser doesn't support creating response ` +\n `streams. Falling back to non-streaming response instead.`);\n }\n // Fallback to waiting for everything to finish, and concatenating the\n // responses.\n const blobPartsPromises = sourcePromises.map(async (sourcePromise) => {\n const source = await sourcePromise;\n if (source instanceof Response) {\n return source.blob();\n }\n else {\n // Technically, a `StreamSource` object can include any valid\n // `BodyInit` type, including `FormData` and `URLSearchParams`, which\n // cannot be passed to the Blob constructor directly, so we have to\n // convert them to actual Blobs first.\n return new Response(source).blob();\n }\n });\n const blobParts = await Promise.all(blobPartsPromises);\n const headers = createHeaders(headersInit);\n // Constructing a new Response from a Blob source is well-supported.\n // So is constructing a new Blob from multiple source Blobs or strings.\n return new Response(new Blob(blobParts), { headers });\n };\n}\nexport { strategy };\n"],"names":["self","_","e","concatenate","sourcePromises","readerPromises","map","sourcePromise","Promise","resolve","then","source","Response","body","getReader","WorkboxError","type","ReadableStream","_getReaderFromSource","streamDeferred","Deferred","i","stream","pull","controller","reader","ReadableStreamDefaultReader","read","result","done","length","close","this","enqueue","value","catch","error","reject","cancel","promise","createHeaders","headersInit","headers","Headers","has","set","concatenateToResponse","response","isSupported","canConstructReadableStream","sourceFunctions","async","event","request","url","params","fn","waitUntil","blobPartsPromises","blob","blobParts","all","Blob"],"mappings":"kFAEA,IACIA,KAAK,0BAA4BC,GACpC,CACD,MAAOC,IC0CP,SAASC,EAAYC,SAQXC,EAAiBD,EAAeE,KAAKC,GAChCC,QAAQC,QAAQF,G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QLW,EAAoBtD,EAAeE,KAAI6C,gBACnCxC,QAAeJ,SACjBI,aAAkBC,SACXD,EAAOgD,OAOP,IAAI/C,SAASD,GAAQgD,UAG9BC,QAAkBpD,QAAQqD,IAAIH,GAC9BhB,EAAUF,EAAcC,UAGvB,IAAI7B,SAAS,IAAIkD,KAAKF,GAAY,CAAElB,WAA3C,CAEP"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-sw.js b/src/Resources/workbox-v7.0.0/workbox-sw.js new file mode 100644 index 0000000..9e003b3 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-sw.js @@ -0,0 +1,2 @@ +!function(){"use strict";try{self["workbox:sw:7.0.0"]&&_()}catch(t){}const t={backgroundSync:"background-sync",broadcastUpdate:"broadcast-update",cacheableResponse:"cacheable-response",core:"core",expiration:"expiration",googleAnalytics:"offline-ga",navigationPreload:"navigation-preload",precaching:"precaching",rangeRequests:"range-requests",routing:"routing",strategies:"strategies",streams:"streams",recipes:"recipes"};self.workbox=new class{constructor(){return this.v={},this.Pt={debug:"localhost"===self.location.hostname,modulePathPrefix:null,modulePathCb:null},this.$t=this.Pt.debug?"dev":"prod",this.jt=!1,new Proxy(this,{get(e,s){if(e[s])return e[s];const o=t[s];return o&&e.loadModule(`workbox-${o}`),e[s]}})}setConfig(t={}){if(this.jt)throw new Error("Config must be set before accessing workbox.* modules");Object.assign(this.Pt,t),this.$t=this.Pt.debug?"dev":"prod"}loadModule(t){const e=this.St(t);try{importScripts(e),this.jt=!0}catch(s){throw console.error(`Unable to import module '${t}' from '${e}'.`),s}}St(t){if(this.Pt.modulePathCb)return this.Pt.modulePathCb(t,this.Pt.debug);let e=["https://storage.googleapis.com/workbox-cdn/releases/7.0.0"];const s=`${t}.${this.$t}.js`,o=this.Pt.modulePathPrefix;return o&&(e=o.split("/"),""===e[e.length-1]&&e.splice(e.length-1,1)),e.push(s),e.join("/")}}}(); +//# sourceMappingURL=workbox-sw.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-sw.js.map b/src/Resources/workbox-v7.0.0/workbox-sw.js.map new file mode 100644 index 0000000..e5a30e4 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-sw.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-sw.js","sources":["../_version.mjs","../controllers/WorkboxSW.mjs","../index.mjs"],"sourcesContent":["try{self['workbox:sw:7.0.0']&&_()}catch(e){}// eslint-disable-line","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport '../_version.mjs';\n\nconst CDN_PATH = `WORKBOX_CDN_ROOT_URL`;\n\nconst MODULE_KEY_TO_NAME_MAPPING = {\n /**\n * @name backgroundSync\n * @memberof workbox\n * @see module:workbox-background-sync\n */\n backgroundSync: 'background-sync',\n /**\n * @name broadcastUpdate\n * @memberof workbox\n * @see module:workbox-broadcast-update\n */\n broadcastUpdate: 'broadcast-update',\n /**\n * @name cacheableResponse\n * @memberof workbox\n * @see module:workbox-cacheable-response\n */\n cacheableResponse: 'cacheable-response',\n /**\n * @name core\n * @memberof workbox\n * @see module:workbox-core\n */\n core: 'core',\n /**\n * @name expiration\n * @memberof workbox\n * @see module:workbox-expiration\n */\n expiration: 'expiration',\n /**\n * @name googleAnalytics\n * @memberof workbox\n * @see module:workbox-google-analytics\n */\n googleAnalytics: 'offline-ga',\n /**\n * @name navigationPreload\n * @memberof workbox\n * @see module:workbox-navigation-preload\n */\n navigationPreload: 'navigation-preload',\n /**\n * @name precaching\n * @memberof workbox\n * @see module:workbox-precaching\n */\n precaching: 'precaching',\n /**\n * @name rangeRequests\n * @memberof workbox\n * @see module:workbox-range-requests\n */\n rangeRequests: 'range-requests',\n /**\n * @name routing\n * @memberof workbox\n * @see module:workbox-routing\n */\n routing: 'routing',\n /**\n * @name strategies\n * @memberof workbox\n * @see module:workbox-strategies\n */\n strategies: 'strategies',\n /**\n * @name streams\n * @memberof workbox\n * @see module:workbox-streams\n */\n streams: 'streams',\n /**\n * @name recipes\n * @memberof workbox\n * @see module:workbox-recipes\n */\n recipes: 'recipes',\n};\n\n/**\n * This class can be used to make it easy to use the various parts of\n * Workbox.\n *\n * @private\n */\nexport class WorkboxSW {\n /**\n * Creates a proxy that automatically loads workbox namespaces on demand.\n *\n * @private\n */\n constructor() {\n this.v = {};\n this._options = {\n debug: self.location.hostname === 'localhost',\n modulePathPrefix: null,\n modulePathCb: null,\n };\n\n this._env = this._options.debug ? 'dev' : 'prod';\n this._modulesLoaded = false;\n\n return new Proxy(this, {\n get(target, key) {\n if (target[key]) {\n return target[key];\n }\n\n const moduleName = MODULE_KEY_TO_NAME_MAPPING[key];\n if (moduleName) {\n target.loadModule(`workbox-${moduleName}`);\n }\n\n return target[key];\n },\n });\n }\n\n /**\n * Updates the configuration options. You can specify whether to treat as a\n * debug build and whether to use a CDN or a specific path when importing\n * other workbox-modules\n *\n * @param {Object} [options]\n * @param {boolean} [options.debug] If true, `dev` builds are using, otherwise\n * `prod` builds are used. By default, `prod` is used unless on localhost.\n * @param {Function} [options.modulePathPrefix] To avoid using the CDN with\n * `workbox-sw` set the path prefix of where modules should be loaded from.\n * For example `modulePathPrefix: '/third_party/workbox/v3.0.0/'`.\n * @param {workbox~ModulePathCallback} [options.modulePathCb] If defined,\n * this callback will be responsible for determining the path of each\n * workbox module.\n *\n * @alias workbox.setConfig\n */\n setConfig(options = {}) {\n if (!this._modulesLoaded) {\n Object.assign(this._options, options);\n this._env = this._options.debug ? 'dev' : 'prod';\n } else {\n throw new Error('Config must be set before accessing workbox.* modules');\n }\n }\n\n /**\n * Load a Workbox module by passing in the appropriate module name.\n *\n * This is not generally needed unless you know there are modules that are\n * dynamically used and you want to safe guard use of the module while the\n * user may be offline.\n *\n * @param {string} moduleName\n *\n * @alias workbox.loadModule\n */\n loadModule(moduleName) {\n const modulePath = this._getImportPath(moduleName);\n try {\n importScripts(modulePath);\n this._modulesLoaded = true;\n } catch (err) {\n // TODO Add context of this error if using the CDN vs the local file.\n\n // We can't rely on workbox-core being loaded so using console\n // eslint-disable-next-line\n console.error(\n `Unable to import module '${moduleName}' from '${modulePath}'.`);\n throw err;\n }\n }\n\n /**\n * This method will get the path / CDN URL to be used for importScript calls.\n *\n * @param {string} moduleName\n * @return {string} URL to the desired module.\n *\n * @private\n */\n _getImportPath(moduleName) {\n if (this._options.modulePathCb) {\n return this._options.modulePathCb(moduleName, this._options.debug);\n }\n\n // TODO: This needs to be dynamic some how.\n let pathParts = [CDN_PATH];\n\n const fileName = `${moduleName}.${this._env}.js`;\n\n const pathPrefix = this._options.modulePathPrefix;\n if (pathPrefix) {\n // Split to avoid issues with developers ending / not ending with slash\n pathParts = pathPrefix.split('/');\n\n // We don't need a slash at the end as we will be adding\n // a filename regardless\n if (pathParts[pathParts.length - 1] === '') {\n pathParts.splice(pathParts.length - 1, 1);\n }\n }\n\n pathParts.push(fileName);\n\n return pathParts.join('/');\n }\n}\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport {WorkboxSW} from './controllers/WorkboxSW.mjs';\nimport './_version.mjs';\n\n/**\n * @namespace workbox\n */\n\n// Don't export anything, just expose a global.\nself.workbox = new WorkboxSW();\n"],"names":["self","_","e","MODULE_KEY_TO_NAME_MAPPING","backgroundSync","broadcastUpdate","cacheableResponse","core","expiration","googleAnalytics","navigationPreload","precaching","rangeRequests","routing","strategies","streams","recipes","workbox","constructor","v","_options","debug","location","hostname","modulePathPrefix","modulePathCb","_env","this","_modulesLoaded","Proxy","get","target","key","moduleName","loadModule","setConfig","options","Error","Object","assign","modulePath","_getImportPath","importScripts","err","console","error","pathParts","fileName","pathPrefix","split","length","splice","push","join"],"mappings":"yBAAA,IAAIA,KAAK,qBAAqBC,GAAI,CAAA,MAAMC,ICUxC,MAEMC,EAA6B,CAMjCC,eAAgB,kBAMhBC,gBAAiB,mBAMjBC,kBAAmB,qBAMnBC,KAAM,OAMNC,WAAY,aAMZC,gBAAiB,aAMjBC,kBAAmB,qBAMnBC,WAAY,aAMZC,cAAe,iBAMfC,QAAS,UAMTC,WAAY,aAMZC,QAAS,UAMTC,QAAS,WC1EXhB,KAAKiB,QAAU,IDmFR,MAMLC,0BACOC,EAAI,QACJC,GAAW,CACdC,MAAkC,cAA3BrB,KAAKsB,SAASC,SACrBC,iBAAkB,KAClBC,aAAc,WAGXC,GAAOC,KAAKP,GAASC,MAAQ,MAAQ,YACrCO,IAAiB,EAEf,IAAIC,MAAMF,KAAM,CACrBG,IAAIC,EAAQC,MACND,EAAOC,UACFD,EAAOC,SAGVC,EAAa9B,EAA2B6B,UAC1CC,GACFF,EAAOG,WAAY,WAAUD,KAGxBF,EAAOC,MAsBpBG,UAAUC,EAAU,OACbT,KAAKC,SAIF,IAAIS,MAAM,yDAHhBC,OAAOC,OAAOZ,KAAKP,GAAUgB,QACxBV,GAAOC,KAAKP,GAASC,MAAQ,MAAQ,OAiB9Ca,WAAWD,SACHO,EAAab,KAAKc,GAAeR,OAErCS,cAAcF,QACTZ,IAAiB,EACtB,MAAOe,SAKPC,QAAQC,MACH,4BAA2BZ,YAAqBO,OAC/CG,GAYVF,GAAeR,MACTN,KAAKP,GAASK,oBACTE,KAAKP,GAASK,aAAaQ,EAAYN,KAAKP,GAASC,WAI1DyB,EAAY,CA7LF,mEA+LRC,EAAY,GAAEd,KAAcN,KAAKD,QAEjCsB,EAAarB,KAAKP,GAASI,wBAC7BwB,IAEFF,EAAYE,EAAWC,MAAM,KAIW,KAApCH,EAAUA,EAAUI,OAAS,IAC/BJ,EAAUK,OAAOL,EAAUI,OAAS,EAAG,IAI3CJ,EAAUM,KAAKL,GAERD,EAAUO,KAAK"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-window.dev.es5.mjs b/src/Resources/workbox-v7.0.0/workbox-window.dev.es5.mjs new file mode 100644 index 0000000..7f870de --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.dev.es5.mjs @@ -0,0 +1,1121 @@ +try { + self['workbox:window:7.0.0'] && _(); +} catch (e) {} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ +// Better not change type of data. +// eslint-disable-next-line @typescript-eslint/ban-types + +function messageSW(sw, data) { + return new Promise(function (resolve) { + var messageChannel = new MessageChannel(); + + messageChannel.port1.onmessage = function (event) { + resolve(event.data); + }; + + sw.postMessage(data, [messageChannel.port2]); + }); +} + +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} + +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} + +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +} + +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + + return arr2; +} + +function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it; + + if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + it = o[Symbol.iterator](); + return it.next.bind(it); +} + +try { + self['workbox:core:7.0.0'] && _(); +} catch (e) {} + +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ + +var Deferred = +/** + * Creates a promise and exposes its resolve and reject functions as methods. + */ +function Deferred() { + var _this = this; + + this.promise = new Promise(function (resolve, reject) { + _this.resolve = resolve; + _this.reject = reject; + }); +}; + +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ + +function dontWaitFor(promise) { + // Effective no-op. + void promise.then(function () {}); +} + +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +var logger = function () { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + + var inGroup = false; + var methodToColorMap = { + debug: "#7f8c8d", + log: "#2ecc71", + warn: "#f39c12", + error: "#c0392b", + groupCollapsed: "#3498db", + groupEnd: null // No colored prefix on groupEnd + + }; + + var print = function print(method, args) { + var _console2; + + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + var _console; + + (_console = console)[method].apply(_console, args); + + return; + } + } + + var styles = ["background: " + methodToColorMap[method], "border-radius: 0.5em", "color: white", "font-weight: bold", "padding: 2px 0.5em"]; // When in a group, the workbox prefix is not displayed. + + var logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + + (_console2 = console)[method].apply(_console2, logPrefix.concat(args)); + + if (method === 'groupCollapsed') { + inGroup = true; + } + + if (method === 'groupEnd') { + inGroup = false; + } + }; // eslint-disable-next-line @typescript-eslint/ban-types + + + var api = {}; + var loggerMethods = Object.keys(methodToColorMap); + + var _loop = function _loop() { + var key = _loggerMethods[_i]; + var method = key; + + api[method] = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + print(method, args); + }; + }; + + for (var _i = 0, _loggerMethods = loggerMethods; _i < _loggerMethods.length; _i++) { + _loop(); + } + + return api; +}(); + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +/** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ +var WorkboxEventTarget = /*#__PURE__*/function () { + function WorkboxEventTarget() { + this._eventListenerRegistry = new Map(); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + + + var _proto = WorkboxEventTarget.prototype; + + _proto.addEventListener = function addEventListener(type, listener) { + var foo = this._getEventListenersByType(type); + + foo.add(listener); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + ; + + _proto.removeEventListener = function removeEventListener(type, listener) { + this._getEventListenersByType(type).delete(listener); + } + /** + * @param {Object} event + * @private + */ + ; + + _proto.dispatchEvent = function dispatchEvent(event) { + event.target = this; + + var listeners = this._getEventListenersByType(event.type); + + for (var _iterator = _createForOfIteratorHelperLoose(listeners), _step; !(_step = _iterator()).done;) { + var listener = _step.value; + listener(event); + } + } + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */ + ; + + _proto._getEventListenersByType = function _getEventListenersByType(type) { + if (!this._eventListenerRegistry.has(type)) { + this._eventListenerRegistry.set(type, new Set()); + } + + return this._eventListenerRegistry.get(type); + }; + + return WorkboxEventTarget; +}(); + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ + +function urlsMatch(url1, url2) { + var _location = location, + href = _location.href; + return new URL(url1, href).href === new URL(url2, href).href; +} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ + +var WorkboxEvent = function WorkboxEvent(type, props) { + this.type = type; + Object.assign(this, props); +}; + +// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically +// chosen, but it seems to avoid false positives in my testing. + +function _await(value, then, direct) { + if (direct) { + return then ? then(value) : value; + } + + if (!value || !value.then) { + value = Promise.resolve(value); + } + + return then ? value.then(then) : value; +} + +var WAITING_TIMEOUT_DURATION = 200; // The amount of time after a registration that we can reasonably conclude +// that the registration didn't trigger an update. + +function _async(f) { + return function () { + for (var args = [], i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + try { + return Promise.resolve(f.apply(this, args)); + } catch (e) { + return Promise.reject(e); + } + }; +} + +var REGISTRATION_TIMEOUT_DURATION = 60000; // The de facto standard message that a service worker should be listening for +// to trigger a call to skipWaiting(). + +function _empty() {} + +var SKIP_WAITING_MESSAGE = { + type: 'SKIP_WAITING' +}; +/** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ + +function _awaitIgnored(value, direct) { + if (!direct) { + return value && value.then ? value.then(_empty) : Promise.resolve(); + } +} + +var Workbox = /*#__PURE__*/function (_WorkboxEventTarget) { + _inheritsLoose(Workbox, _WorkboxEventTarget); + + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + function Workbox(scriptURL, registerOptions) { + var _this; + + if (registerOptions === void 0) { + registerOptions = {}; + } + + _this = _WorkboxEventTarget.call(this) || this; + _this._registerOptions = {}; + _this._updateFoundCount = 0; // Deferreds we can resolve later. + + _this._swDeferred = new Deferred(); + _this._activeDeferred = new Deferred(); + _this._controllingDeferred = new Deferred(); + _this._registrationTime = 0; + _this._ownSWs = new Set(); + /** + * @private + */ + + _this._onUpdateFound = function () { + // `this._registration` will never be `undefined` after an update is found. + var registration = _this._registration; + var installingSW = registration.installing; // If the script URL passed to `navigator.serviceWorker.register()` is + // different from the current controlling SW's script URL, we know any + // successful registration calls will trigger an `updatefound` event. + // But if the registered script URL is the same as the current controlling + // SW's script URL, we'll only get an `updatefound` event if the file + // changed since it was last registered. This can be a problem if the user + // opens up the same page in a different tab, and that page registers + // a SW that triggers an update. It's a problem because this page has no + // good way of knowing whether the `updatefound` event came from the SW + // script it registered or from a registration attempt made by a newer + // version of the page running in another tab. + // To minimize the possibility of a false positive, we use the logic here: + + var updateLikelyTriggeredExternally = // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + _this._updateFoundCount > 0 || // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, _this._scriptURL.toString()) || // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > _this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? // If any of the above are not true, we assume the update was + // triggered by this instance. + true : false; + + if (updateLikelyTriggeredExternally) { + _this._externalSW = installingSW; + registration.removeEventListener('updatefound', _this._onUpdateFound); + } else { + // If the update was not triggered externally we know the installing + // SW is the one we registered, so we set it. + _this._sw = installingSW; + + _this._ownSWs.add(installingSW); + + _this._swDeferred.resolve(installingSW); // The `installing` state isn't something we have a dedicated + // callback for, but we do log messages for it in development. + + + { + if (navigator.serviceWorker.controller) { + logger.log('Updated service worker found. Installing now...'); + } else { + logger.log('Service worker is installing...'); + } + } + } // Increment the `updatefound` count, so future invocations of this + // method can be sure they were triggered externally. + + + ++_this._updateFoundCount; // Add a `statechange` listener regardless of whether this update was + // triggered externally, since we have callbacks for both. + + installingSW.addEventListener('statechange', _this._onStateChange); + }; + /** + * @private + * @param {Event} originalEvent + */ + + + _this._onStateChange = function (originalEvent) { + // `this._registration` will never be `undefined` after an update is found. + var registration = _this._registration; + var sw = originalEvent.target; + var state = sw.state; + var isExternal = sw === _this._externalSW; + var eventProps = { + sw: sw, + isExternal: isExternal, + originalEvent: originalEvent + }; + + if (!isExternal && _this._isUpdate) { + eventProps.isUpdate = true; + } + + _this.dispatchEvent(new WorkboxEvent(state, eventProps)); + + if (state === 'installed') { + // This timeout is used to ignore cases where the service worker calls + // `skipWaiting()` in the install event, thus moving it directly in the + // activating state. (Since all service workers *must* go through the + // waiting phase, the only way to detect `skipWaiting()` called in the + // install event is to observe that the time spent in the waiting phase + // is very short.) + // NOTE: we don't need separate timeouts for the own and external SWs + // since they can't go through these phases at the same time. + _this._waitingTimeout = self.setTimeout(function () { + // Ensure the SW is still waiting (it may now be redundant). + if (state === 'installed' && registration.waiting === sw) { + _this.dispatchEvent(new WorkboxEvent('waiting', eventProps)); + + { + if (isExternal) { + logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...'); + } else { + logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...'); + } + } + } + }, WAITING_TIMEOUT_DURATION); + } else if (state === 'activating') { + clearTimeout(_this._waitingTimeout); + + if (!isExternal) { + _this._activeDeferred.resolve(sw); + } + } + + { + switch (state) { + case 'installed': + if (isExternal) { + logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.'); + } else { + logger.log('Registered service worker installed.'); + } + + break; + + case 'activated': + if (isExternal) { + logger.warn('An external service worker has activated.'); + } else { + logger.log('Registered service worker activated.'); + + if (sw !== navigator.serviceWorker.controller) { + logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.'); + } + } + + break; + + case 'redundant': + if (sw === _this._compatibleControllingSW) { + logger.log('Previously controlling service worker now redundant!'); + } else if (!isExternal) { + logger.log('Registered service worker now redundant!'); + } + + break; + } + } + }; + /** + * @private + * @param {Event} originalEvent + */ + + + _this._onControllerChange = function (originalEvent) { + var sw = _this._sw; + var isExternal = sw !== navigator.serviceWorker.controller; // Unconditionally dispatch the controlling event, with isExternal set + // to distinguish between controller changes due to the initial registration + // vs. an update-check or other tab's registration. + // See https://github.com/GoogleChrome/workbox/issues/2786 + + _this.dispatchEvent(new WorkboxEvent('controlling', { + isExternal: isExternal, + originalEvent: originalEvent, + sw: sw, + isUpdate: _this._isUpdate + })); + + if (!isExternal) { + { + logger.log('Registered service worker now controlling this page.'); + } + + _this._controllingDeferred.resolve(sw); + } + }; + /** + * @private + * @param {Event} originalEvent + */ + + + _this._onMessage = _async(function (originalEvent) { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + var data = originalEvent.data, + ports = originalEvent.ports, + source = originalEvent.source; // Wait until there's an "own" service worker. This is used to buffer + // `message` events that may be received prior to calling `register()`. + + return _await(_this.getSW(), function () { + if (_this._ownSWs.has(source)) { + _this.dispatchEvent(new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data: data, + originalEvent: originalEvent, + ports: ports, + sw: source + })); + } + }); // If the service worker that sent the message is in the list of own + // service workers for this instance, dispatch a `message` event. + // NOTE: we check for all previously owned service workers rather than + // just the current one because some messages (e.g. cache updates) use + // a timeout when sent and may be delayed long enough for a service worker + // update to be found. + }); + _this._scriptURL = scriptURL; + _this._registerOptions = registerOptions; // Add a message listener immediately since messages received during + // page load are buffered only until the DOMContentLoaded event: + // https://github.com/GoogleChrome/workbox/issues/2202 + + navigator.serviceWorker.addEventListener('message', _this._onMessage); + return _this; + } + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + + + var _proto = Workbox.prototype; + + _proto.register = function register(_temp) { + var _ref = _temp === void 0 ? {} : _temp, + _ref$immediate = _ref.immediate, + immediate = _ref$immediate === void 0 ? false : _ref$immediate; + + try { + var _this3 = this; + + if ("dev" !== 'production') { + if (_this3._registrationTime) { + logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.'); + return; + } + } + + return _invoke(function () { + if (!immediate && document.readyState !== 'complete') { + return _awaitIgnored(new Promise(function (res) { + return window.addEventListener('load', res); + })); + } + }, function () { + // Set this flag to true if any service worker was controlling the page + // at registration time. + _this3._isUpdate = Boolean(navigator.serviceWorker.controller); // Before registering, attempt to determine if a SW is already controlling + // the page, and if that SW script (and version, if specified) matches this + // instance's script. + + _this3._compatibleControllingSW = _this3._getControllingSWIfCompatible(); + return _await(_this3._registerScript(), function (_this2$_registerScrip) { + _this3._registration = _this2$_registerScrip; + + // If we have a compatible controller, store the controller as the "own" + // SW, resolve active/controlling deferreds and add necessary listeners. + if (_this3._compatibleControllingSW) { + _this3._sw = _this3._compatibleControllingSW; + + _this3._activeDeferred.resolve(_this3._compatibleControllingSW); + + _this3._controllingDeferred.resolve(_this3._compatibleControllingSW); + + _this3._compatibleControllingSW.addEventListener('statechange', _this3._onStateChange, { + once: true + }); + } // If there's a waiting service worker with a matching URL before the + // `updatefound` event fires, it likely means that this site is open + // in another tab, or the user refreshed the page (and thus the previous + // page wasn't fully unloaded before this page started loading). + // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting + + + var waitingSW = _this3._registration.waiting; + + if (waitingSW && urlsMatch(waitingSW.scriptURL, _this3._scriptURL.toString())) { + // Store the waiting SW as the "own" Sw, even if it means overwriting + // a compatible controller. + _this3._sw = waitingSW; // Run this in the next microtask, so any code that adds an event + // listener after awaiting `register()` will get this event. + + dontWaitFor(Promise.resolve().then(function () { + _this3.dispatchEvent(new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true + })); + + if ("dev" !== 'production') { + logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...'); + } + })); + } // If an "own" SW is already set, resolve the deferred. + + + if (_this3._sw) { + _this3._swDeferred.resolve(_this3._sw); + + _this3._ownSWs.add(_this3._sw); + } + + if ("dev" !== 'production') { + logger.log('Successfully registered service worker.', _this3._scriptURL.toString()); + + if (navigator.serviceWorker.controller) { + if (_this3._compatibleControllingSW) { + logger.debug('A service worker with the same script URL ' + 'is already controlling this page.'); + } else { + logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...'); + } + } + + var currentPageIsOutOfScope = function currentPageIsOutOfScope() { + var scopeURL = new URL(_this3._registerOptions.scope || _this3._scriptURL.toString(), document.baseURI); + var scopeURLBasePath = new URL('./', scopeURL.href).pathname; + return !location.pathname.startsWith(scopeURLBasePath); + }; + + if (currentPageIsOutOfScope()) { + logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?'); + } + } + + _this3._registration.addEventListener('updatefound', _this3._onUpdateFound); + + navigator.serviceWorker.addEventListener('controllerchange', _this3._onControllerChange); + return _this3._registration; + }); + }); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Checks for updates of the registered service worker. + */ + ; + + _proto.update = function update() { + try { + var _this5 = this; + + if (!_this5._registration) { + if ("dev" !== 'production') { + logger.error('Cannot update a Workbox instance without ' + 'being registered. Register the Workbox instance first.'); + } + + return; + } // Try to update registration + + + return _awaitIgnored(_this5._registration.update()); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + ; + + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + _proto.getSW = function getSW() { + // If `this._sw` is set, resolve with that as we want `getSW()` to + // return the correct (new) service worker if an update is found. + return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise; + } + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + // We might be able to change the 'data' type to Record in the future. + // eslint-disable-next-line @typescript-eslint/ban-types + ; + + _proto.messageSW = function messageSW$1(data) { + try { + var _this7 = this; + + return _await(_this7.getSW(), function (sw) { + return messageSW(sw, data); + }); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + ; + + _proto.messageSkipWaiting = function messageSkipWaiting() { + if (this._registration && this._registration.waiting) { + void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); + } + } + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */ + ; + + _proto._getControllingSWIfCompatible = function _getControllingSWIfCompatible() { + var controller = navigator.serviceWorker.controller; + + if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) { + return controller; + } else { + return undefined; + } + } + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */ + ; + + _proto._registerScript = function _registerScript() { + try { + var _this9 = this; + + return _catch(function () { + // this._scriptURL may be a TrustedScriptURL, but there's no support for + // passing that to register() in lib.dom right now. + // https://github.com/GoogleChrome/workbox/issues/2855 + return _await(navigator.serviceWorker.register(_this9._scriptURL, _this9._registerOptions), function (reg) { + // Keep track of when registration happened, so it can be used in the + // `this._onUpdateFound` heuristic. Also use the presence of this + // property as a way to see if `.register()` has been called. + _this9._registrationTime = performance.now(); + return reg; + }); + }, function (error) { + if ("dev" !== 'production') { + logger.error(error); + } // Re-throw the error. + + + throw error; + }); + } catch (e) { + return Promise.reject(e); + } + }; + + _createClass(Workbox, [{ + key: "active", + get: function get() { + return this._activeDeferred.promise; + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + + }, { + key: "controlling", + get: function get() { + return this._controllingDeferred.promise; + } + }]); + + return Workbox; +}(WorkboxEventTarget); + +function _invoke(body, then) { + var result = body(); + + if (result && result.then) { + return result.then(then); + } + + return then(result); +} // The jsdoc comments below outline the events this instance may dispatch: +// ----------------------------------------------------------------------- + +/** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ + + +function _catch(body, recover) { + try { + var result = body(); + } catch (e) { + return recover(e); + } + + if (result && result.then) { + return result.then(void 0, recover); + } + + return result; +} + +export { Workbox, WorkboxEvent, messageSW }; +//# sourceMappingURL=workbox-window.dev.es5.mjs.map diff --git a/src/Resources/workbox-v7.0.0/workbox-window.dev.es5.mjs.map b/src/Resources/workbox-v7.0.0/workbox-window.dev.es5.mjs.map new file mode 100644 index 0000000..754c7b7 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.dev.es5.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-window.dev.es5.mjs","sources":["../_version.js","../messageSW.js","../../workbox-core/_version.js","../../workbox-core/_private/Deferred.js","../../workbox-core/_private/dontWaitFor.js","../../workbox-core/_private/logger.js","../utils/WorkboxEventTarget.js","../utils/urlsMatch.js","../utils/WorkboxEvent.js","../Workbox.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:window:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will not\n * resolve.\n *\n * @param {ServiceWorker} sw The service worker to send the message to.\n * @param {Object} data An object to send to the service worker.\n * @return {Promise}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","promise","reject","dontWaitFor","then","logger","globalThis","__WB_DISABLE_DEV_LOGS","inGroup","methodToColorMap","debug","log","warn","error","groupCollapsed","groupEnd","print","method","args","test","navigator","userAgent","console","styles","logPrefix","join","api","loggerMethods","Object","keys","key","WorkboxEventTarget","_eventListenerRegistry","Map","addEventListener","type","listener","foo","_getEventListenersByType","add","removeEventListener","delete","dispatchEvent","target","listeners","has","set","Set","get","urlsMatch","url1","url2","location","href","URL","WorkboxEvent","props","assign","_await","value","direct","WAITING_TIMEOUT_DURATION","_async","f","i","arguments","length","apply","REGISTRATION_TIMEOUT_DURATION","_empty","SKIP_WAITING_MESSAGE","_awaitIgnored","Workbox","scriptURL","registerOptions","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","_onUpdateFound","registration","_registration","installingSW","installing","updateLikelyTriggeredExternally","_scriptURL","toString","performance","now","_externalSW","_sw","serviceWorker","controller","_onStateChange","originalEvent","state","isExternal","eventProps","_isUpdate","isUpdate","_waitingTimeout","setTimeout","waiting","clearTimeout","_compatibleControllingSW","_onControllerChange","_onMessage","ports","source","getSW","register","immediate","process","document","readyState","res","window","Boolean","_getControllingSWIfCompatible","_registerScript","once","waitingSW","wasWaitingBeforeRegister","currentPageIsOutOfScope","scopeURL","scope","baseURI","scopeURLBasePath","pathname","startsWith","update","undefined","messageSkipWaiting","reg","body","result","recover"],"mappings":"AAEA,IAAI;AACAA,EAAAA,IAAI,CAAC,sBAAD,CAAJ,IAAgCC,CAAC,EAAjC;AACH,CAFD,CAGA,OAAOC,C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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;wBACsB;AACd,aAAO,KAAK8E,oBAAL,CAA0B9E,OAAjC;AACH;;;;EA9WiB8B;;AA4ff,iBAAiB0G,IAAjB,EAAuBrI,IAAvB,EAA6B;AACnC,MAAIsI,MAAM,GAAGD,IAAI,EAAjB;;AACA,MAAIC,MAAM,IAAIA,MAAM,CAACtI,IAArB,EAA2B;AAC1B,WAAOsI,MAAM,CAACtI,IAAP,CAAYA,IAAZ,CAAP;AACA;;AACD,SAAOA,IAAI,CAACsI,MAAD,CAAX;AACA;AAhDD;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAzDO,gBAAgBD,IAAhB,EAAsBE,OAAtB,EAA+B;AACrC,MAAI;AACH,QAAID,MAAM,GAAGD,IAAI,EAAjB;AACA,GAFD,CAEE,OAAMtJ,CAAN,EAAS;AACV,WAAOwJ,OAAO,CAACxJ,CAAD,CAAd;AACA;;AACD,MAAIuJ,MAAM,IAAIA,MAAM,CAACtI,IAArB,EAA2B;AAC1B,WAAOsI,MAAM,CAACtI,IAAP,CAAY,KAAK,CAAjB,EAAoBuI,OAApB,CAAP;AACA;;AACD,SAAOD,MAAP;AACA;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-window.dev.mjs b/src/Resources/workbox-v7.0.0/workbox-window.dev.mjs new file mode 100644 index 0000000..9db4251 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.dev.mjs @@ -0,0 +1,945 @@ +try { + self['workbox:window:7.0.0'] && _(); +} catch (e) {} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ +// Better not change type of data. +// eslint-disable-next-line @typescript-eslint/ban-types + +function messageSW(sw, data) { + return new Promise(resolve => { + const messageChannel = new MessageChannel(); + + messageChannel.port1.onmessage = event => { + resolve(event.data); + }; + + sw.postMessage(data, [messageChannel.port2]); + }); +} + +try { + self['workbox:core:7.0.0'] && _(); +} catch (e) {} + +/* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ + +class Deferred { + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + +} + +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ + +function dontWaitFor(promise) { + // Effective no-op. + void promise.then(() => {}); +} + +/* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +const logger = (() => { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + + let inGroup = false; + const methodToColorMap = { + debug: `#7f8c8d`, + log: `#2ecc71`, + warn: `#f39c12`, + error: `#c0392b`, + groupCollapsed: `#3498db`, + groupEnd: null // No colored prefix on groupEnd + + }; + + const print = function (method, args) { + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + console[method](...args); + return; + } + } + + const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`]; // When in a group, the workbox prefix is not displayed. + + const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + console[method](...logPrefix, ...args); + + if (method === 'groupCollapsed') { + inGroup = true; + } + + if (method === 'groupEnd') { + inGroup = false; + } + }; // eslint-disable-next-line @typescript-eslint/ban-types + + + const api = {}; + const loggerMethods = Object.keys(methodToColorMap); + + for (const key of loggerMethods) { + const method = key; + + api[method] = (...args) => { + print(method, args); + }; + } + + return api; +})(); + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ + +/** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ +class WorkboxEventTarget { + constructor() { + this._eventListenerRegistry = new Map(); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + + + addEventListener(type, listener) { + const foo = this._getEventListenersByType(type); + + foo.add(listener); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + + + removeEventListener(type, listener) { + this._getEventListenersByType(type).delete(listener); + } + /** + * @param {Object} event + * @private + */ + + + dispatchEvent(event) { + event.target = this; + + const listeners = this._getEventListenersByType(event.type); + + for (const listener of listeners) { + listener(event); + } + } + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */ + + + _getEventListenersByType(type) { + if (!this._eventListenerRegistry.has(type)) { + this._eventListenerRegistry.set(type, new Set()); + } + + return this._eventListenerRegistry.get(type); + } + +} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ + +function urlsMatch(url1, url2) { + const { + href + } = location; + return new URL(url1, href).href === new URL(url2, href).href; +} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +/** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ + +class WorkboxEvent { + constructor(type, props) { + this.type = type; + Object.assign(this, props); + } + +} + +/* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. +*/ +// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically +// chosen, but it seems to avoid false positives in my testing. + +const WAITING_TIMEOUT_DURATION = 200; // The amount of time after a registration that we can reasonably conclude +// that the registration didn't trigger an update. + +const REGISTRATION_TIMEOUT_DURATION = 60000; // The de facto standard message that a service worker should be listening for +// to trigger a call to skipWaiting(). + +const SKIP_WAITING_MESSAGE = { + type: 'SKIP_WAITING' +}; +/** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ + +class Workbox extends WorkboxEventTarget { + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + constructor(scriptURL, registerOptions = {}) { + super(); + this._registerOptions = {}; + this._updateFoundCount = 0; // Deferreds we can resolve later. + + this._swDeferred = new Deferred(); + this._activeDeferred = new Deferred(); + this._controllingDeferred = new Deferred(); + this._registrationTime = 0; + this._ownSWs = new Set(); + /** + * @private + */ + + this._onUpdateFound = () => { + // `this._registration` will never be `undefined` after an update is found. + const registration = this._registration; + const installingSW = registration.installing; // If the script URL passed to `navigator.serviceWorker.register()` is + // different from the current controlling SW's script URL, we know any + // successful registration calls will trigger an `updatefound` event. + // But if the registered script URL is the same as the current controlling + // SW's script URL, we'll only get an `updatefound` event if the file + // changed since it was last registered. This can be a problem if the user + // opens up the same page in a different tab, and that page registers + // a SW that triggers an update. It's a problem because this page has no + // good way of knowing whether the `updatefound` event came from the SW + // script it registered or from a registration attempt made by a newer + // version of the page running in another tab. + // To minimize the possibility of a false positive, we use the logic here: + + const updateLikelyTriggeredExternally = // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + this._updateFoundCount > 0 || // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? // If any of the above are not true, we assume the update was + // triggered by this instance. + true : false; + + if (updateLikelyTriggeredExternally) { + this._externalSW = installingSW; + registration.removeEventListener('updatefound', this._onUpdateFound); + } else { + // If the update was not triggered externally we know the installing + // SW is the one we registered, so we set it. + this._sw = installingSW; + + this._ownSWs.add(installingSW); + + this._swDeferred.resolve(installingSW); // The `installing` state isn't something we have a dedicated + // callback for, but we do log messages for it in development. + + + { + if (navigator.serviceWorker.controller) { + logger.log('Updated service worker found. Installing now...'); + } else { + logger.log('Service worker is installing...'); + } + } + } // Increment the `updatefound` count, so future invocations of this + // method can be sure they were triggered externally. + + + ++this._updateFoundCount; // Add a `statechange` listener regardless of whether this update was + // triggered externally, since we have callbacks for both. + + installingSW.addEventListener('statechange', this._onStateChange); + }; + /** + * @private + * @param {Event} originalEvent + */ + + + this._onStateChange = originalEvent => { + // `this._registration` will never be `undefined` after an update is found. + const registration = this._registration; + const sw = originalEvent.target; + const { + state + } = sw; + const isExternal = sw === this._externalSW; + const eventProps = { + sw, + isExternal, + originalEvent + }; + + if (!isExternal && this._isUpdate) { + eventProps.isUpdate = true; + } + + this.dispatchEvent(new WorkboxEvent(state, eventProps)); + + if (state === 'installed') { + // This timeout is used to ignore cases where the service worker calls + // `skipWaiting()` in the install event, thus moving it directly in the + // activating state. (Since all service workers *must* go through the + // waiting phase, the only way to detect `skipWaiting()` called in the + // install event is to observe that the time spent in the waiting phase + // is very short.) + // NOTE: we don't need separate timeouts for the own and external SWs + // since they can't go through these phases at the same time. + this._waitingTimeout = self.setTimeout(() => { + // Ensure the SW is still waiting (it may now be redundant). + if (state === 'installed' && registration.waiting === sw) { + this.dispatchEvent(new WorkboxEvent('waiting', eventProps)); + + { + if (isExternal) { + logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...'); + } else { + logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...'); + } + } + } + }, WAITING_TIMEOUT_DURATION); + } else if (state === 'activating') { + clearTimeout(this._waitingTimeout); + + if (!isExternal) { + this._activeDeferred.resolve(sw); + } + } + + { + switch (state) { + case 'installed': + if (isExternal) { + logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.'); + } else { + logger.log('Registered service worker installed.'); + } + + break; + + case 'activated': + if (isExternal) { + logger.warn('An external service worker has activated.'); + } else { + logger.log('Registered service worker activated.'); + + if (sw !== navigator.serviceWorker.controller) { + logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.'); + } + } + + break; + + case 'redundant': + if (sw === this._compatibleControllingSW) { + logger.log('Previously controlling service worker now redundant!'); + } else if (!isExternal) { + logger.log('Registered service worker now redundant!'); + } + + break; + } + } + }; + /** + * @private + * @param {Event} originalEvent + */ + + + this._onControllerChange = originalEvent => { + const sw = this._sw; + const isExternal = sw !== navigator.serviceWorker.controller; // Unconditionally dispatch the controlling event, with isExternal set + // to distinguish between controller changes due to the initial registration + // vs. an update-check or other tab's registration. + // See https://github.com/GoogleChrome/workbox/issues/2786 + + this.dispatchEvent(new WorkboxEvent('controlling', { + isExternal, + originalEvent, + sw, + isUpdate: this._isUpdate + })); + + if (!isExternal) { + { + logger.log('Registered service worker now controlling this page.'); + } + + this._controllingDeferred.resolve(sw); + } + }; + /** + * @private + * @param {Event} originalEvent + */ + + + this._onMessage = async originalEvent => { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const { + data, + ports, + source + } = originalEvent; // Wait until there's an "own" service worker. This is used to buffer + // `message` events that may be received prior to calling `register()`. + + await this.getSW(); // If the service worker that sent the message is in the list of own + // service workers for this instance, dispatch a `message` event. + // NOTE: we check for all previously owned service workers rather than + // just the current one because some messages (e.g. cache updates) use + // a timeout when sent and may be delayed long enough for a service worker + // update to be found. + + if (this._ownSWs.has(source)) { + this.dispatchEvent(new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data, + originalEvent, + ports, + sw: source + })); + } + }; + + this._scriptURL = scriptURL; + this._registerOptions = registerOptions; // Add a message listener immediately since messages received during + // page load are buffered only until the DOMContentLoaded event: + // https://github.com/GoogleChrome/workbox/issues/2202 + + navigator.serviceWorker.addEventListener('message', this._onMessage); + } + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + + + async register({ + immediate = false + } = {}) { + { + if (this._registrationTime) { + logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.'); + return; + } + } + + if (!immediate && document.readyState !== 'complete') { + await new Promise(res => window.addEventListener('load', res)); + } // Set this flag to true if any service worker was controlling the page + // at registration time. + + + this._isUpdate = Boolean(navigator.serviceWorker.controller); // Before registering, attempt to determine if a SW is already controlling + // the page, and if that SW script (and version, if specified) matches this + // instance's script. + + this._compatibleControllingSW = this._getControllingSWIfCompatible(); + this._registration = await this._registerScript(); // If we have a compatible controller, store the controller as the "own" + // SW, resolve active/controlling deferreds and add necessary listeners. + + if (this._compatibleControllingSW) { + this._sw = this._compatibleControllingSW; + + this._activeDeferred.resolve(this._compatibleControllingSW); + + this._controllingDeferred.resolve(this._compatibleControllingSW); + + this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { + once: true + }); + } // If there's a waiting service worker with a matching URL before the + // `updatefound` event fires, it likely means that this site is open + // in another tab, or the user refreshed the page (and thus the previous + // page wasn't fully unloaded before this page started loading). + // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting + + + const waitingSW = this._registration.waiting; + + if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) { + // Store the waiting SW as the "own" Sw, even if it means overwriting + // a compatible controller. + this._sw = waitingSW; // Run this in the next microtask, so any code that adds an event + // listener after awaiting `register()` will get this event. + + dontWaitFor(Promise.resolve().then(() => { + this.dispatchEvent(new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true + })); + + { + logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...'); + } + })); + } // If an "own" SW is already set, resolve the deferred. + + + if (this._sw) { + this._swDeferred.resolve(this._sw); + + this._ownSWs.add(this._sw); + } + + { + logger.log('Successfully registered service worker.', this._scriptURL.toString()); + + if (navigator.serviceWorker.controller) { + if (this._compatibleControllingSW) { + logger.debug('A service worker with the same script URL ' + 'is already controlling this page.'); + } else { + logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...'); + } + } + + const currentPageIsOutOfScope = () => { + const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI); + const scopeURLBasePath = new URL('./', scopeURL.href).pathname; + return !location.pathname.startsWith(scopeURLBasePath); + }; + + if (currentPageIsOutOfScope()) { + logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?'); + } + } + + this._registration.addEventListener('updatefound', this._onUpdateFound); + + navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange); + return this._registration; + } + /** + * Checks for updates of the registered service worker. + */ + + + async update() { + if (!this._registration) { + { + logger.error('Cannot update a Workbox instance without ' + 'being registered. Register the Workbox instance first.'); + } + + return; + } // Try to update registration + + + await this._registration.update(); + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + + + get active() { + return this._activeDeferred.promise; + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + + + get controlling() { + return this._controllingDeferred.promise; + } + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + + + getSW() { + // If `this._sw` is set, resolve with that as we want `getSW()` to + // return the correct (new) service worker if an update is found. + return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise; + } + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + // We might be able to change the 'data' type to Record in the future. + // eslint-disable-next-line @typescript-eslint/ban-types + + + async messageSW(data) { + const sw = await this.getSW(); + return messageSW(sw, data); + } + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + + + messageSkipWaiting() { + if (this._registration && this._registration.waiting) { + void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); + } + } + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */ + + + _getControllingSWIfCompatible() { + const controller = navigator.serviceWorker.controller; + + if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) { + return controller; + } else { + return undefined; + } + } + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */ + + + async _registerScript() { + try { + // this._scriptURL may be a TrustedScriptURL, but there's no support for + // passing that to register() in lib.dom right now. + // https://github.com/GoogleChrome/workbox/issues/2855 + const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions); // Keep track of when registration happened, so it can be used in the + // `this._onUpdateFound` heuristic. Also use the presence of this + // property as a way to see if `.register()` has been called. + + this._registrationTime = performance.now(); + return reg; + } catch (error) { + { + logger.error(error); + } // Re-throw the error. + + + throw error; + } + } + +} +// ----------------------------------------------------------------------- + +/** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ + +/** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ + +export { Workbox, WorkboxEvent, messageSW }; +//# sourceMappingURL=workbox-window.dev.mjs.map diff --git a/src/Resources/workbox-v7.0.0/workbox-window.dev.mjs.map b/src/Resources/workbox-v7.0.0/workbox-window.dev.mjs.map new file mode 100644 index 0000000..b6d828f --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.dev.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-window.dev.mjs","sources":["../_version.js","../messageSW.js","../../workbox-core/_version.js","../../workbox-core/_private/Deferred.js","../../workbox-core/_private/dontWaitFor.js","../../workbox-core/_private/logger.js","../utils/WorkboxEventTarget.js","../utils/urlsMatch.js","../utils/WorkboxEvent.js","../Workbox.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:window:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will not\n * resolve.\n *\n * @param {ServiceWorker} sw The service worker to send the message to.\n * @param {Object} data An object to send to the service worker.\n * @return {Promise}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","constructor","promise","reject","dontWaitFor","then","logger","globalThis","__WB_DISABLE_DEV_LOGS","inGroup","methodToColorMap","debug","log","warn","error","groupCollapsed","groupEnd","print","method","args","test","navigator","userAgent","console","styles","logPrefix","join","api","loggerMethods","Object","keys","key","WorkboxEventTarget","_eventListenerRegistry","Map","addEventListener","type","listener","foo","_getEventListenersByType","add","removeEventListener","delete","dispatchEvent","target","listeners","has","set","Set","get","urlsMatch","url1","url2","href","location","URL","WorkboxEvent","props","assign","WAITING_TIMEOUT_DURATION","REGISTRATION_TIMEOUT_DURATION","SKIP_WAITING_MESSAGE","Workbox","scriptURL","registerOptions","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","_onUpdateFound","registration","_registration","installingSW","installing","updateLikelyTriggeredExternally","_scriptURL","toString","performance","now","_externalSW","_sw","serviceWorker","controller","_onStateChange","originalEvent","state","isExternal","eventProps","_isUpdate","isUpdate","_waitingTimeout","setTimeout","waiting","clearTimeout","_compatibleControllingSW","_onControllerChange","_onMessage","ports","source","getSW","register","immediate","document","readyState","res","window","Boolean","_getControllingSWIfCompatible","_registerScript","once","waitingSW","wasWaitingBeforeRegister","currentPageIsOutOfScope","scopeURL","scope","baseURI","scopeURLBasePath","pathname","startsWith","update","active","controlling","undefined","messageSkipWaiting","reg"],"mappings":"AAEA,IAAI;AACAA,EAAAA,IAAI,CAAC,sBAAD,CAAJ,IAAgCC,CAAC,EAAjC;AACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ACLV;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,SAASC,SAAT,CAAmBC,EAAnB,EAAuBC,IAAvB,EAA6B;AACzB,SAAO,IAAIC,OAAJ,CAAaC,OAAD,I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SAAS,CAAC+D,aAAV,CAAwBC,UAA3C;;AACA,QAAIA,UAAU,IACVnC,SAAS,CAACmC,UAAU,CAACtB,SAAZ,EAAuB,KAAKe,UAAL,CAAgBC,QAAhB,EAAvB,CADb,EACiE;AAC7D,aAAOM,UAAP;AACH,KAHD,MAIK;AACD,aAAOwC,SAAP;AACH;AACJ;AACD;AACJ;AACA;AACA;AACA;AACA;;;AACI,QAAMd,eAAN,GAAwB;AACpB,QAAI;AACA;AACA;AACA;AACA,YAAMgB,GAAG,GAAG,MAAM1G,SAAS,CAAC+D,aAAV,CAAwBmB,QAAxB,CAAiC,KAAKzB,UAAtC,EAAkD,KAAKb,gBAAvD,CAAlB,CAJA;AAMA;AACA;;AACA,WAAKK,iBAAL,GAAyBU,WAAW,CAACC,GAAZ,EAAzB;AACA,aAAO8C,GAAP;AACH,KAVD,CAWA,OAAOjH,KAAP,EAAc;AACV,MAA2C;AACvCR,QAAAA,MAAM,CAACQ,KAAP,CAAaA,KAAb;AACH,OAHS;;;AAKV,YAAMA,KAAN;AACH;AACJ;;AA9coC;AAkdzC;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-window.dev.umd.js b/src/Resources/workbox-v7.0.0/workbox-window.dev.umd.js new file mode 100644 index 0000000..a6b1540 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.dev.umd.js @@ -0,0 +1,1133 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.workbox = {})); +}(this, (function (exports) { 'use strict'; + + try { + self['workbox:window:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Sends a data object to a service worker via `postMessage` and resolves with + * a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will not + * resolve. + * + * @param {ServiceWorker} sw The service worker to send the message to. + * @param {Object} data An object to send to the service worker. + * @return {Promise} + * @memberof workbox-window + */ + // Better not change type of data. + // eslint-disable-next-line @typescript-eslint/ban-types + + function messageSW(sw, data) { + return new Promise(function (resolve) { + var messageChannel = new MessageChannel(); + + messageChannel.port1.onmessage = function (event) { + resolve(event.data); + }; + + sw.postMessage(data, [messageChannel.port2]); + }); + } + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; + } + + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } + + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + + return arr2; + } + + function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it; + + if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + it = o[Symbol.iterator](); + return it.next.bind(it); + } + + try { + self['workbox:core:7.0.0'] && _(); + } catch (e) {} + + /* + Copyright 2018 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * The Deferred class composes Promises in a way that allows for them to be + * resolved or rejected from outside the constructor. In most cases promises + * should be used directly, but Deferreds can be necessary when the logic to + * resolve a promise must be separate. + * + * @private + */ + + var Deferred = + /** + * Creates a promise and exposes its resolve and reject functions as methods. + */ + function Deferred() { + var _this = this; + + this.promise = new Promise(function (resolve, reject) { + _this.resolve = resolve; + _this.reject = reject; + }); + }; + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A helper function that prevents a promise from being flagged as unused. + * + * @private + **/ + + function dontWaitFor(promise) { + // Effective no-op. + void promise.then(function () {}); + } + + /* + Copyright 2019 Google LLC + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + var logger = function () { + // Don't overwrite this value if it's already set. + // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923 + if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) { + self.__WB_DISABLE_DEV_LOGS = false; + } + + var inGroup = false; + var methodToColorMap = { + debug: "#7f8c8d", + log: "#2ecc71", + warn: "#f39c12", + error: "#c0392b", + groupCollapsed: "#3498db", + groupEnd: null // No colored prefix on groupEnd + + }; + + var print = function print(method, args) { + var _console2; + + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + + if (method === 'groupCollapsed') { + // Safari doesn't print all console.groupCollapsed() arguments: + // https://bugs.webkit.org/show_bug.cgi?id=182754 + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + var _console; + + (_console = console)[method].apply(_console, args); + + return; + } + } + + var styles = ["background: " + methodToColorMap[method], "border-radius: 0.5em", "color: white", "font-weight: bold", "padding: 2px 0.5em"]; // When in a group, the workbox prefix is not displayed. + + var logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; + + (_console2 = console)[method].apply(_console2, logPrefix.concat(args)); + + if (method === 'groupCollapsed') { + inGroup = true; + } + + if (method === 'groupEnd') { + inGroup = false; + } + }; // eslint-disable-next-line @typescript-eslint/ban-types + + + var api = {}; + var loggerMethods = Object.keys(methodToColorMap); + + var _loop = function _loop() { + var key = _loggerMethods[_i]; + var method = key; + + api[method] = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + print(method, args); + }; + }; + + for (var _i = 0, _loggerMethods = loggerMethods; _i < _loggerMethods.length; _i++) { + _loop(); + } + + return api; + }(); + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + + /** + * A minimal `EventTarget` shim. + * This is necessary because not all browsers support constructable + * `EventTarget`, so using a real `EventTarget` will error. + * @private + */ + var WorkboxEventTarget = /*#__PURE__*/function () { + function WorkboxEventTarget() { + this._eventListenerRegistry = new Map(); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + + + var _proto = WorkboxEventTarget.prototype; + + _proto.addEventListener = function addEventListener(type, listener) { + var foo = this._getEventListenersByType(type); + + foo.add(listener); + } + /** + * @param {string} type + * @param {Function} listener + * @private + */ + ; + + _proto.removeEventListener = function removeEventListener(type, listener) { + this._getEventListenersByType(type).delete(listener); + } + /** + * @param {Object} event + * @private + */ + ; + + _proto.dispatchEvent = function dispatchEvent(event) { + event.target = this; + + var listeners = this._getEventListenersByType(event.type); + + for (var _iterator = _createForOfIteratorHelperLoose(listeners), _step; !(_step = _iterator()).done;) { + var listener = _step.value; + listener(event); + } + } + /** + * Returns a Set of listeners associated with the passed event type. + * If no handlers have been registered, an empty Set is returned. + * + * @param {string} type The event type. + * @return {Set} An array of handler functions. + * @private + */ + ; + + _proto._getEventListenersByType = function _getEventListenersByType(type) { + if (!this._eventListenerRegistry.has(type)) { + this._eventListenerRegistry.set(type, new Set()); + } + + return this._eventListenerRegistry.get(type); + }; + + return WorkboxEventTarget; + }(); + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * Returns true if two URLs have the same `.href` property. The URLS can be + * relative, and if they are the current location href is used to resolve URLs. + * + * @private + * @param {string} url1 + * @param {string} url2 + * @return {boolean} + */ + + function urlsMatch(url1, url2) { + var _location = location, + href = _location.href; + return new URL(url1, href).href === new URL(url2, href).href; + } + + /* + Copyright 2019 Google LLC + + Use of this source code is governed by an MIT-style + license that can be found in the LICENSE file or at + https://opensource.org/licenses/MIT. + */ + /** + * A minimal `Event` subclass shim. + * This doesn't *actually* subclass `Event` because not all browsers support + * constructable `EventTarget`, and using a real `Event` will error. + * @private + */ + + var WorkboxEvent = function WorkboxEvent(type, props) { + this.type = type; + Object.assign(this, props); + }; + + // `skipWaiting()` wasn't called. This 200 amount wasn't scientifically + // chosen, but it seems to avoid false positives in my testing. + + function _await(value, then, direct) { + if (direct) { + return then ? then(value) : value; + } + + if (!value || !value.then) { + value = Promise.resolve(value); + } + + return then ? value.then(then) : value; + } + + var WAITING_TIMEOUT_DURATION = 200; // The amount of time after a registration that we can reasonably conclude + // that the registration didn't trigger an update. + + function _async(f) { + return function () { + for (var args = [], i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + try { + return Promise.resolve(f.apply(this, args)); + } catch (e) { + return Promise.reject(e); + } + }; + } + + var REGISTRATION_TIMEOUT_DURATION = 60000; // The de facto standard message that a service worker should be listening for + // to trigger a call to skipWaiting(). + + function _empty() {} + + var SKIP_WAITING_MESSAGE = { + type: 'SKIP_WAITING' + }; + /** + * A class to aid in handling service worker registration, updates, and + * reacting to service worker lifecycle events. + * + * @fires {@link workbox-window.Workbox#message} + * @fires {@link workbox-window.Workbox#installed} + * @fires {@link workbox-window.Workbox#waiting} + * @fires {@link workbox-window.Workbox#controlling} + * @fires {@link workbox-window.Workbox#activated} + * @fires {@link workbox-window.Workbox#redundant} + * @memberof workbox-window + */ + + function _awaitIgnored(value, direct) { + if (!direct) { + return value && value.then ? value.then(_empty) : Promise.resolve(); + } + } + + var Workbox = /*#__PURE__*/function (_WorkboxEventTarget) { + _inheritsLoose(Workbox, _WorkboxEventTarget); + + /** + * Creates a new Workbox instance with a script URL and service worker + * options. The script URL and options are the same as those used when + * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). + * + * @param {string|TrustedScriptURL} scriptURL The service worker script + * associated with this instance. Using a + * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported. + * @param {Object} [registerOptions] The service worker options associated + * with this instance. + */ + // eslint-disable-next-line @typescript-eslint/ban-types + function Workbox(scriptURL, registerOptions) { + var _this; + + if (registerOptions === void 0) { + registerOptions = {}; + } + + _this = _WorkboxEventTarget.call(this) || this; + _this._registerOptions = {}; + _this._updateFoundCount = 0; // Deferreds we can resolve later. + + _this._swDeferred = new Deferred(); + _this._activeDeferred = new Deferred(); + _this._controllingDeferred = new Deferred(); + _this._registrationTime = 0; + _this._ownSWs = new Set(); + /** + * @private + */ + + _this._onUpdateFound = function () { + // `this._registration` will never be `undefined` after an update is found. + var registration = _this._registration; + var installingSW = registration.installing; // If the script URL passed to `navigator.serviceWorker.register()` is + // different from the current controlling SW's script URL, we know any + // successful registration calls will trigger an `updatefound` event. + // But if the registered script URL is the same as the current controlling + // SW's script URL, we'll only get an `updatefound` event if the file + // changed since it was last registered. This can be a problem if the user + // opens up the same page in a different tab, and that page registers + // a SW that triggers an update. It's a problem because this page has no + // good way of knowing whether the `updatefound` event came from the SW + // script it registered or from a registration attempt made by a newer + // version of the page running in another tab. + // To minimize the possibility of a false positive, we use the logic here: + + var updateLikelyTriggeredExternally = // Since we enforce only calling `register()` once, and since we don't + // add the `updatefound` event listener until the `register()` call, if + // `_updateFoundCount` is > 0 then it means this method has already + // been called, thus this SW must be external + _this._updateFoundCount > 0 || // If the script URL of the installing SW is different from this + // instance's script URL, we know it's definitely not from our + // registration. + !urlsMatch(installingSW.scriptURL, _this._scriptURL.toString()) || // If all of the above are false, then we use a time-based heuristic: + // Any `updatefound` event that occurs long after our registration is + // assumed to be external. + performance.now() > _this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? // If any of the above are not true, we assume the update was + // triggered by this instance. + true : false; + + if (updateLikelyTriggeredExternally) { + _this._externalSW = installingSW; + registration.removeEventListener('updatefound', _this._onUpdateFound); + } else { + // If the update was not triggered externally we know the installing + // SW is the one we registered, so we set it. + _this._sw = installingSW; + + _this._ownSWs.add(installingSW); + + _this._swDeferred.resolve(installingSW); // The `installing` state isn't something we have a dedicated + // callback for, but we do log messages for it in development. + + + { + if (navigator.serviceWorker.controller) { + logger.log('Updated service worker found. Installing now...'); + } else { + logger.log('Service worker is installing...'); + } + } + } // Increment the `updatefound` count, so future invocations of this + // method can be sure they were triggered externally. + + + ++_this._updateFoundCount; // Add a `statechange` listener regardless of whether this update was + // triggered externally, since we have callbacks for both. + + installingSW.addEventListener('statechange', _this._onStateChange); + }; + /** + * @private + * @param {Event} originalEvent + */ + + + _this._onStateChange = function (originalEvent) { + // `this._registration` will never be `undefined` after an update is found. + var registration = _this._registration; + var sw = originalEvent.target; + var state = sw.state; + var isExternal = sw === _this._externalSW; + var eventProps = { + sw: sw, + isExternal: isExternal, + originalEvent: originalEvent + }; + + if (!isExternal && _this._isUpdate) { + eventProps.isUpdate = true; + } + + _this.dispatchEvent(new WorkboxEvent(state, eventProps)); + + if (state === 'installed') { + // This timeout is used to ignore cases where the service worker calls + // `skipWaiting()` in the install event, thus moving it directly in the + // activating state. (Since all service workers *must* go through the + // waiting phase, the only way to detect `skipWaiting()` called in the + // install event is to observe that the time spent in the waiting phase + // is very short.) + // NOTE: we don't need separate timeouts for the own and external SWs + // since they can't go through these phases at the same time. + _this._waitingTimeout = self.setTimeout(function () { + // Ensure the SW is still waiting (it may now be redundant). + if (state === 'installed' && registration.waiting === sw) { + _this.dispatchEvent(new WorkboxEvent('waiting', eventProps)); + + { + if (isExternal) { + logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...'); + } else { + logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...'); + } + } + } + }, WAITING_TIMEOUT_DURATION); + } else if (state === 'activating') { + clearTimeout(_this._waitingTimeout); + + if (!isExternal) { + _this._activeDeferred.resolve(sw); + } + } + + { + switch (state) { + case 'installed': + if (isExternal) { + logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.'); + } else { + logger.log('Registered service worker installed.'); + } + + break; + + case 'activated': + if (isExternal) { + logger.warn('An external service worker has activated.'); + } else { + logger.log('Registered service worker activated.'); + + if (sw !== navigator.serviceWorker.controller) { + logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.'); + } + } + + break; + + case 'redundant': + if (sw === _this._compatibleControllingSW) { + logger.log('Previously controlling service worker now redundant!'); + } else if (!isExternal) { + logger.log('Registered service worker now redundant!'); + } + + break; + } + } + }; + /** + * @private + * @param {Event} originalEvent + */ + + + _this._onControllerChange = function (originalEvent) { + var sw = _this._sw; + var isExternal = sw !== navigator.serviceWorker.controller; // Unconditionally dispatch the controlling event, with isExternal set + // to distinguish between controller changes due to the initial registration + // vs. an update-check or other tab's registration. + // See https://github.com/GoogleChrome/workbox/issues/2786 + + _this.dispatchEvent(new WorkboxEvent('controlling', { + isExternal: isExternal, + originalEvent: originalEvent, + sw: sw, + isUpdate: _this._isUpdate + })); + + if (!isExternal) { + { + logger.log('Registered service worker now controlling this page.'); + } + + _this._controllingDeferred.resolve(sw); + } + }; + /** + * @private + * @param {Event} originalEvent + */ + + + _this._onMessage = _async(function (originalEvent) { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + var data = originalEvent.data, + ports = originalEvent.ports, + source = originalEvent.source; // Wait until there's an "own" service worker. This is used to buffer + // `message` events that may be received prior to calling `register()`. + + return _await(_this.getSW(), function () { + if (_this._ownSWs.has(source)) { + _this.dispatchEvent(new WorkboxEvent('message', { + // Can't change type 'any' of data. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + data: data, + originalEvent: originalEvent, + ports: ports, + sw: source + })); + } + }); // If the service worker that sent the message is in the list of own + // service workers for this instance, dispatch a `message` event. + // NOTE: we check for all previously owned service workers rather than + // just the current one because some messages (e.g. cache updates) use + // a timeout when sent and may be delayed long enough for a service worker + // update to be found. + }); + _this._scriptURL = scriptURL; + _this._registerOptions = registerOptions; // Add a message listener immediately since messages received during + // page load are buffered only until the DOMContentLoaded event: + // https://github.com/GoogleChrome/workbox/issues/2202 + + navigator.serviceWorker.addEventListener('message', _this._onMessage); + return _this; + } + /** + * Registers a service worker for this instances script URL and service + * worker options. By default this method delays registration until after + * the window has loaded. + * + * @param {Object} [options] + * @param {Function} [options.immediate=false] Setting this to true will + * register the service worker immediately, even if the window has + * not loaded (not recommended). + */ + + + var _proto = Workbox.prototype; + + _proto.register = function register(_temp) { + var _ref = _temp === void 0 ? {} : _temp, + _ref$immediate = _ref.immediate, + immediate = _ref$immediate === void 0 ? false : _ref$immediate; + + try { + var _this3 = this; + + if ("dev" !== 'production') { + if (_this3._registrationTime) { + logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.'); + return; + } + } + + return _invoke(function () { + if (!immediate && document.readyState !== 'complete') { + return _awaitIgnored(new Promise(function (res) { + return window.addEventListener('load', res); + })); + } + }, function () { + // Set this flag to true if any service worker was controlling the page + // at registration time. + _this3._isUpdate = Boolean(navigator.serviceWorker.controller); // Before registering, attempt to determine if a SW is already controlling + // the page, and if that SW script (and version, if specified) matches this + // instance's script. + + _this3._compatibleControllingSW = _this3._getControllingSWIfCompatible(); + return _await(_this3._registerScript(), function (_this2$_registerScrip) { + _this3._registration = _this2$_registerScrip; + + // If we have a compatible controller, store the controller as the "own" + // SW, resolve active/controlling deferreds and add necessary listeners. + if (_this3._compatibleControllingSW) { + _this3._sw = _this3._compatibleControllingSW; + + _this3._activeDeferred.resolve(_this3._compatibleControllingSW); + + _this3._controllingDeferred.resolve(_this3._compatibleControllingSW); + + _this3._compatibleControllingSW.addEventListener('statechange', _this3._onStateChange, { + once: true + }); + } // If there's a waiting service worker with a matching URL before the + // `updatefound` event fires, it likely means that this site is open + // in another tab, or the user refreshed the page (and thus the previous + // page wasn't fully unloaded before this page started loading). + // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting + + + var waitingSW = _this3._registration.waiting; + + if (waitingSW && urlsMatch(waitingSW.scriptURL, _this3._scriptURL.toString())) { + // Store the waiting SW as the "own" Sw, even if it means overwriting + // a compatible controller. + _this3._sw = waitingSW; // Run this in the next microtask, so any code that adds an event + // listener after awaiting `register()` will get this event. + + dontWaitFor(Promise.resolve().then(function () { + _this3.dispatchEvent(new WorkboxEvent('waiting', { + sw: waitingSW, + wasWaitingBeforeRegister: true + })); + + if ("dev" !== 'production') { + logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...'); + } + })); + } // If an "own" SW is already set, resolve the deferred. + + + if (_this3._sw) { + _this3._swDeferred.resolve(_this3._sw); + + _this3._ownSWs.add(_this3._sw); + } + + if ("dev" !== 'production') { + logger.log('Successfully registered service worker.', _this3._scriptURL.toString()); + + if (navigator.serviceWorker.controller) { + if (_this3._compatibleControllingSW) { + logger.debug('A service worker with the same script URL ' + 'is already controlling this page.'); + } else { + logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...'); + } + } + + var currentPageIsOutOfScope = function currentPageIsOutOfScope() { + var scopeURL = new URL(_this3._registerOptions.scope || _this3._scriptURL.toString(), document.baseURI); + var scopeURLBasePath = new URL('./', scopeURL.href).pathname; + return !location.pathname.startsWith(scopeURLBasePath); + }; + + if (currentPageIsOutOfScope()) { + logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?'); + } + } + + _this3._registration.addEventListener('updatefound', _this3._onUpdateFound); + + navigator.serviceWorker.addEventListener('controllerchange', _this3._onControllerChange); + return _this3._registration; + }); + }); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Checks for updates of the registered service worker. + */ + ; + + _proto.update = function update() { + try { + var _this5 = this; + + if (!_this5._registration) { + if ("dev" !== 'production') { + logger.error('Cannot update a Workbox instance without ' + 'being registered. Register the Workbox instance first.'); + } + + return; + } // Try to update registration + + + return _awaitIgnored(_this5._registration.update()); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is active. If a service worker was already controlling at registration + * time then it will resolve to that if the script URLs (and optionally + * script versions) match, otherwise it will wait until an update is found + * and activates. + * + * @return {Promise} + */ + ; + + /** + * Resolves with a reference to a service worker that matches the script URL + * of this instance, as soon as it's available. + * + * If, at registration time, there's already an active or waiting service + * worker with a matching script URL, it will be used (with the waiting + * service worker taking precedence over the active service worker if both + * match, since the waiting service worker would have been registered more + * recently). + * If there's no matching active or waiting service worker at registration + * time then the promise will not resolve until an update is found and starts + * installing, at which point the installing service worker is used. + * + * @return {Promise} + */ + _proto.getSW = function getSW() { + // If `this._sw` is set, resolve with that as we want `getSW()` to + // return the correct (new) service worker if an update is found. + return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise; + } + /** + * Sends the passed data object to the service worker registered by this + * instance (via {@link workbox-window.Workbox#getSW}) and resolves + * with a response (if any). + * + * A response can be set in a message handler in the service worker by + * calling `event.ports[0].postMessage(...)`, which will resolve the promise + * returned by `messageSW()`. If no response is set, the promise will never + * resolve. + * + * @param {Object} data An object to send to the service worker + * @return {Promise} + */ + // We might be able to change the 'data' type to Record in the future. + // eslint-disable-next-line @typescript-eslint/ban-types + ; + + _proto.messageSW = function messageSW$1(data) { + try { + var _this7 = this; + + return _await(_this7.getSW(), function (sw) { + return messageSW(sw, data); + }); + } catch (e) { + return Promise.reject(e); + } + } + /** + * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's + * currently in the `waiting` state associated with the current registration. + * + * If there is no current registration or no service worker is `waiting`, + * calling this will have no effect. + */ + ; + + _proto.messageSkipWaiting = function messageSkipWaiting() { + if (this._registration && this._registration.waiting) { + void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE); + } + } + /** + * Checks for a service worker already controlling the page and returns + * it if its script URL matches. + * + * @private + * @return {ServiceWorker|undefined} + */ + ; + + _proto._getControllingSWIfCompatible = function _getControllingSWIfCompatible() { + var controller = navigator.serviceWorker.controller; + + if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) { + return controller; + } else { + return undefined; + } + } + /** + * Registers a service worker for this instances script URL and register + * options and tracks the time registration was complete. + * + * @private + */ + ; + + _proto._registerScript = function _registerScript() { + try { + var _this9 = this; + + return _catch(function () { + // this._scriptURL may be a TrustedScriptURL, but there's no support for + // passing that to register() in lib.dom right now. + // https://github.com/GoogleChrome/workbox/issues/2855 + return _await(navigator.serviceWorker.register(_this9._scriptURL, _this9._registerOptions), function (reg) { + // Keep track of when registration happened, so it can be used in the + // `this._onUpdateFound` heuristic. Also use the presence of this + // property as a way to see if `.register()` has been called. + _this9._registrationTime = performance.now(); + return reg; + }); + }, function (error) { + if ("dev" !== 'production') { + logger.error(error); + } // Re-throw the error. + + + throw error; + }); + } catch (e) { + return Promise.reject(e); + } + }; + + _createClass(Workbox, [{ + key: "active", + get: function get() { + return this._activeDeferred.promise; + } + /** + * Resolves to the service worker registered by this instance as soon as it + * is controlling the page. If a service worker was already controlling at + * registration time then it will resolve to that if the script URLs (and + * optionally script versions) match, otherwise it will wait until an update + * is found and starts controlling the page. + * Note: the first time a service worker is installed it will active but + * not start controlling the page unless `clients.claim()` is called in the + * service worker. + * + * @return {Promise} + */ + + }, { + key: "controlling", + get: function get() { + return this._controllingDeferred.promise; + } + }]); + + return Workbox; + }(WorkboxEventTarget); + + function _invoke(body, then) { + var result = body(); + + if (result && result.then) { + return result.then(then); + } + + return then(result); + } // The jsdoc comments below outline the events this instance may dispatch: + // ----------------------------------------------------------------------- + + /** + * The `message` event is dispatched any time a `postMessage` is received. + * + * @event workbox-window.Workbox#message + * @type {WorkboxEvent} + * @property {*} data The `data` property from the original `message` event. + * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent} + * event. + * @property {string} type `message`. + * @property {MessagePort[]} ports The `ports` value from `originalEvent`. + * @property {Workbox} target The `Workbox` instance. + */ + + /** + * The `installed` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `installed`. + * + * Then can happen either the very first time a service worker is installed, + * or after an update to the current service worker is found. In the case + * of an update being found, the event's `isUpdate` property will be `true`. + * + * @event workbox-window.Workbox#installed + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `installed`. + * @property {Workbox} target The `Workbox` instance. + */ + + /** + * The `waiting` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `installed` and then doesn't immediately change to `activating`. + * It may also be dispatched if a service worker with the same + * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * was already waiting when the {@link workbox-window.Workbox#register} + * method was called. + * + * @event workbox-window.Workbox#waiting + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event|undefined} originalEvent The original + * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event, or `undefined` in the case where the service worker was waiting + * to before `.register()` was called. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with + * a matching `scriptURL` was already waiting when this `Workbox` + * instance called `register()`. + * @property {string} type `waiting`. + * @property {Workbox} target The `Workbox` instance. + */ + + /** + * The `controlling` event is dispatched if a + * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer} + * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL} + * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller} + * matches the `scriptURL` of the `Workbox` instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}. + * + * @event workbox-window.Workbox#controlling + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this service worker was registered. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `controlling`. + * @property {Workbox} target The `Workbox` instance. + */ + + /** + * The `activated` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker} + * changes to `activated`. + * + * @event workbox-window.Workbox#activated + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {boolean|undefined} isExternal True if this event is associated + * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}. + * @property {string} type `activated`. + * @property {Workbox} target The `Workbox` instance. + */ + + /** + * The `redundant` event is dispatched if the state of a + * {@link workbox-window.Workbox} instance's + * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw} + * changes to `redundant`. + * + * @event workbox-window.Workbox#redundant + * @type {WorkboxEvent} + * @property {ServiceWorker} sw The service worker instance. + * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange} + * event. + * @property {boolean|undefined} isUpdate True if a service worker was already + * controlling when this `Workbox` instance called `register()`. + * @property {string} type `redundant`. + * @property {Workbox} target The `Workbox` instance. + */ + + + function _catch(body, recover) { + try { + var result = body(); + } catch (e) { + return recover(e); + } + + if (result && result.then) { + return result.then(void 0, recover); + } + + return result; + } + + exports.Workbox = Workbox; + exports.WorkboxEvent = WorkboxEvent; + exports.messageSW = messageSW; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=workbox-window.dev.umd.js.map diff --git a/src/Resources/workbox-v7.0.0/workbox-window.dev.umd.js.map b/src/Resources/workbox-v7.0.0/workbox-window.dev.umd.js.map new file mode 100644 index 0000000..4b271c7 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.dev.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-window.dev.umd.js","sources":["../_version.js","../messageSW.js","../../workbox-core/_version.js","../../workbox-core/_private/Deferred.js","../../workbox-core/_private/dontWaitFor.js","../../workbox-core/_private/logger.js","../utils/WorkboxEventTarget.js","../utils/urlsMatch.js","../utils/WorkboxEvent.js","../Workbox.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:window:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will not\n * resolve.\n *\n * @param {ServiceWorker} sw The service worker to send the message to.\n * @param {Object} data An object to send to the service worker.\n * @return {Promise}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nconst logger = (process.env.NODE_ENV === 'production'\n ? null\n : (() => {\n // Don't overwrite this value if it's already set.\n // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923\n if (!('__WB_DISABLE_DEV_LOGS' in globalThis)) {\n self.__WB_DISABLE_DEV_LOGS = false;\n }\n let inGroup = false;\n const methodToColorMap = {\n debug: `#7f8c8d`,\n log: `#2ecc71`,\n warn: `#f39c12`,\n error: `#c0392b`,\n groupCollapsed: `#3498db`,\n groupEnd: null, // No colored prefix on groupEnd\n };\n const print = function (method, args) {\n if (self.__WB_DISABLE_DEV_LOGS) {\n return;\n }\n if (method === 'groupCollapsed') {\n // Safari doesn't print all console.groupCollapsed() arguments:\n // https://bugs.webkit.org/show_bug.cgi?id=182754\n if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n console[method](...args);\n return;\n }\n }\n const styles = [\n `background: ${methodToColorMap[method]}`,\n `border-radius: 0.5em`,\n `color: white`,\n `font-weight: bold`,\n `padding: 2px 0.5em`,\n ];\n // When in a group, the workbox prefix is not displayed.\n const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];\n console[method](...logPrefix, ...args);\n if (method === 'groupCollapsed') {\n inGroup = true;\n }\n if (method === 'groupEnd') {\n inGroup = false;\n }\n };\n // eslint-disable-next-line @typescript-eslint/ban-types\n const api = {};\n const loggerMethods = Object.keys(methodToColorMap);\n for (const key of loggerMethods) {\n const method = key;\n api[method] = (...args) => {\n print(method, args);\n };\n }\n return api;\n })());\nexport { logger };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","promise","reject","dontWaitFor","then","logger","globalThis","__WB_DISABLE_DEV_LOGS","inGroup","methodToColorMap","debug","log","warn","error","groupCollapsed","groupEnd","print","method","args","test","navigator","userAgent","console","styles","logPrefix","join","api","loggerMethods","Object","keys","key","WorkboxEventTarget","_eventListenerRegistry","Map","addEventListener","type","listener","foo","_getEventListenersByType","add","removeEventListener","delete","dispatchEvent","target","listeners","has","set","Set","get","urlsMatch","url1","url2","location","href","URL","WorkboxEvent","props","assign","_await","value","direct","WAITING_TIMEOUT_DURATION","_async","f","i","arguments","length","apply","REGISTRATION_TIMEOUT_DURATION","_empty","SKIP_WAITING_MESSAGE","_awaitIgnored","Workbox","scriptURL","registerOptions","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","_onUpdateFound","registration","_registration","installingSW","installing","updateLikelyTriggeredExternally","_scriptURL","toString","performance","now","_externalSW","_sw","serviceWorker","controller","_onStateChange","originalEvent","state","isExternal","eventProps","_isUpdate","isUpdate","_waitingTimeout","setTimeout","waiting","clearTimeout","_compatibleControllingSW","_onControllerChange","_onMessage","ports","source","getSW","register","immediate","process","document","readyState","res","window","Boolean","_getControllingSWIfCompatible","_registerScript","once","waitingSW","wasWaitingBeforeRegister","currentPageIsOutOfScope","scopeURL","scope","baseURI","scopeURLBasePath","pathname","startsWith","update","undefined","messageSkipWaiting","reg","body","result","recover"],"mappings":";;;;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,sBAAD,CAAJ,IAAgCC,CAAC,EAAjC;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA,SAASC,SAAT,CAAmBC,EAAnB,EAAuBC,IAAvB,EAA6B;IACzB,SAAO,IAAIC,OAAJ,CAAY,UAACC,OAAD,EAAa;IAC5B,QAAMC,cAAc,GAAG,IAAIC,cAAJ,EAAvB;;IACAD,IAAAA,cAAc,CAACE,KAAf,CAAqBC,SAArB,GAAiC,UAACC,KAAD,EAAW;IACxCL,MAAAA,OAAO,CAACK,KAAK,CAACP,IAAP,CAAP;IACH,KAFD;;IAGAD,IAAAA,EAAE,CAACS,WAAH,CAAeR,IAAf,EAAqB,CAACG,cAAc,CAACM,KAAhB,CAArB;IACH,GANM,CAAP;IAOH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IC9BD,IAAI;IACAd,EAAAA,IAAI,CAAC,oBAAD,CAAJ,IAA8BC,CAAC,EAA/B;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAEA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;QACMa;IACF;IACJ;IACA;IACI,oBAAc;IAAA;;IACV,OAAKC,OAAL,GAAe,IAAIV,OAAJ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B,YAIM6D,GAJN;IAKA;IACA;IACA;IACA,iBAAKxD,iBAAL,GAAyBU,WAAW,CAACC,GAAZ,EAAzB;IACA,iBAAO6C,GAAP;IATA;IAUH,OAXmB,YAYb3H,KAZa,EAYN;IACV,YAAIsG,KAAA,KAAyB,YAA7B,EAA2C;IACvC9G,UAAAA,MAAM,CAACQ,KAAP,CAAaA,KAAb;IACH,SAHS;;;IAKV,cAAMA,KAAN;IACH,OAlBmB;IAmBvB;;;;;;;4BAjHY;IACT,aAAO,KAAKiE,eAAL,CAAqB7E,OAA5B;IACH;IACD;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;;4BACsB;IACd,aAAO,KAAK8E,oBAAL,CAA0B9E,OAAjC;IACH;;;;MA9WiB8B;;IA4ff,iBAAiB0G,IAAjB,EAAuBrI,IAAvB,EAA6B;IACnC,MAAIsI,MAAM,GAAGD,IAAI,EAAjB;;IACA,MAAIC,MAAM,IAAIA,MAAM,CAACtI,IAArB,EAA2B;IAC1B,WAAOsI,MAAM,CAACtI,IAAP,CAAYA,IAAZ,CAAP;IACA;;IACD,SAAOA,IAAI,CAACsI,MAAD,CAAX;IACA;IAhDD;;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;IAzDO,gBAAgBD,IAAhB,EAAsBE,OAAtB,EAA+B;IACrC,MAAI;IACH,QAAID,MAAM,GAAGD,IAAI,EAAjB;IACA,GAFD,CAEE,OAAMtJ,CAAN,EAAS;IACV,WAAOwJ,OAAO,CAACxJ,CAAD,CAAd;IACA;;IACD,MAAIuJ,MAAM,IAAIA,MAAM,CAACtI,IAArB,EAA2B;IAC1B,WAAOsI,MAAM,CAACtI,IAAP,CAAY,KAAK,CAAjB,EAAoBuI,OAApB,CAAP;IACA;;IACD,SAAOD,MAAP;IACA;;;;;;;;;;;;"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-window.prod.es5.mjs b/src/Resources/workbox-v7.0.0/workbox-window.prod.es5.mjs new file mode 100644 index 0000000..bbb3d22 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.prod.es5.mjs @@ -0,0 +1,2 @@ +try{self["workbox:window:7.0.0"]&&_()}catch(n){}function n(n,t){return new Promise((function(r){var e=new MessageChannel;e.port1.onmessage=function(n){r(n.data)},n.postMessage(t,[e.port2])}))}function t(n,t){for(var r=0;rn.length)&&(t=n.length);for(var r=0,e=new Array(t);r=n.length?{done:!0}:{done:!1,value:n[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(e=n[Symbol.iterator]()).next.bind(e)}try{self["workbox:core:7.0.0"]&&_()}catch(n){}var i=function(){var n=this;this.promise=new Promise((function(t,r){n.resolve=t,n.reject=r}))};function o(n,t){var r=location.href;return new URL(n,r).href===new URL(t,r).href}var u=function(n,t){this.type=n,Object.assign(this,t)};function a(n,t,r){return r?t?t(n):n:(n&&n.then||(n=Promise.resolve(n)),t?n.then(t):n)}function c(){}var f={type:"SKIP_WAITING"};function s(n,t){if(!t)return n&&n.then?n.then(c):Promise.resolve()}var v=function(r){var e,c;function v(n,t){var e,c;return void 0===t&&(t={}),(e=r.call(this)||this).nn={},e.tn=0,e.rn=new i,e.en=new i,e.on=new i,e.un=0,e.an=new Set,e.cn=function(){var n=e.fn,t=n.installing;e.tn>0||!o(t.scriptURL,e.sn.toString())||performance.now()>e.un+6e4?(e.vn=t,n.removeEventListener("updatefound",e.cn)):(e.hn=t,e.an.add(t),e.rn.resolve(t)),++e.tn,t.addEventListener("statechange",e.ln)},e.ln=function(n){var t=e.fn,r=n.target,i=r.state,o=r===e.vn,a={sw:r,isExternal:o,originalEvent:n};!o&&e.mn&&(a.isUpdate=!0),e.dispatchEvent(new u(i,a)),"installed"===i?e.wn=self.setTimeout((function(){"installed"===i&&t.waiting===r&&e.dispatchEvent(new u("waiting",a))}),200):"activating"===i&&(clearTimeout(e.wn),o||e.en.resolve(r))},e.dn=function(n){var t=e.hn,r=t!==navigator.serviceWorker.controller;e.dispatchEvent(new u("controlling",{isExternal:r,originalEvent:n,sw:t,isUpdate:e.mn})),r||e.on.resolve(t)},e.gn=(c=function(n){var t=n.data,r=n.ports,i=n.source;return a(e.getSW(),(function(){e.an.has(i)&&e.dispatchEvent(new u("message",{data:t,originalEvent:n,ports:r,sw:i}))}))},function(){for(var n=[],t=0;t}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","promise","reject","_this","urlsMatch","url1","url2","href","location","URL","WorkboxEvent","type","props","Object","assign","this","_await","value","then","direct","_empty","SKIP_WAITING_MESSAGE","_awaitIgnored","Workbox","scriptURL","registerOptions","f","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","Set","_onUpdateFound","registration","_registration","installingSW","installing","_scriptURL","toString","performance","now","_externalSW","removeEventListener","_sw","add","addEventListener","_onStateChange","originalEvent","target","state","isExternal","eventProps","_isUpdate","isUpdate","dispatchEvent","_waitingTimeout","setTimeout","waiting","clearTimeout","_onControllerChange","navigator","serviceWorker","controller","_onMessage","ports","source","getSW","has","args","i","arguments","length","apply","register","immediate","body","result","document","readyState","res","window","Boolean","_compatibleControllingSW","_this3","_getControllingSWIfCompatible","_registerScript","once","waitingSW","wasWaitingBeforeRegister","update","undefined","messageSkipWaiting","recover","_this9","reg","error","_eventListenerRegistry","Map","listener","_getEventListenersByType","delete","set","get"],"mappings":"AAEA,IACIA,KAAK,yBAA2BC,GACnC,CACD,MAAOC,ICmBP,SAASC,EAAUC,EAAIC,UACZ,IAAIC,SAAQ,SAACC,OACVC,EAAiB,IAAIC,eAC3BD,EAAeE,MAA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AAcuB,QAASvC,MAUnDkE,GAAA,eACUtB,EAAaF,UAAUC,cAAcC,kBACvCA,GACA7D,EAAU6D,EAAWzC,UAAWT,KAAKyB,GAAWC,YACzCwB,YAYTuB,wBAKqDzE,YA6ExD,SAAgB+D,EAAMiB,WAEvBhB,EAASD,IACZ,MAAM3F,UACA4G,EAAQ5G,MAEZ4F,GAAUA,EAAO7D,YACb6D,EAAO7D,UAAK,EAAQ6E,UAErBhB,CACP,uBAvF6BhB,UAAUC,cAAcY,SAASoB,EAAKxD,GAAYwD,EAAKrE,cAAnEsE,YAIDjE,GAAoBU,YAAYC,MAC9BsD,iBAEJC,SAKGA,qFA9GHnF,KAAKe,GAAgB7B,mDAerBc,KAAKgB,GAAqB9B,wEEnY5BkG,GAAyB,IAAIC,+BAOtCpD,iBAAA,SAAiBrC,EAAM0F,GACPtF,KAAKuF,GAAyB3F,GACtCoC,IAAIsD,MAOZxD,oBAAA,SAAoBlC,EAAM0F,QACjBC,GAAyB3F,GAAM4F,OAAOF,MAM/C5C,cAAA,SAAc5D,GACVA,EAAMsD,OAASpC,mBACGA,KAAKuF,GAAyBzG,EAAMc,sBACpB,EAC9B0F,WAASxG,OAWjByG,GAAA,SAAyB3F,UAChBI,KAAKoF,GAAuB7B,IAAI3D,SAC5BwF,GAAuBK,IAAI7F,EAAM,IAAIuB,KAEvCnB,KAAKoF,GAAuBM,IAAI9F,KA5C/C"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-window.prod.mjs b/src/Resources/workbox-v7.0.0/workbox-window.prod.mjs new file mode 100644 index 0000000..ff1c27e --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.prod.mjs @@ -0,0 +1,2 @@ +try{self["workbox:window:7.0.0"]&&_()}catch(t){}function t(t,s){return new Promise((i=>{const e=new MessageChannel;e.port1.onmessage=t=>{i(t.data)},t.postMessage(s,[e.port2])}))}try{self["workbox:core:7.0.0"]&&_()}catch(t){}class s{constructor(){this.promise=new Promise(((t,s)=>{this.resolve=t,this.reject=s}))}}class i{constructor(){this.Lt=new Map}addEventListener(t,s){this.It(t).add(s)}removeEventListener(t,s){this.It(t).delete(s)}dispatchEvent(t){t.target=this;const s=this.It(t.type);for(const i of s)i(t)}It(t){return this.Lt.has(t)||this.Lt.set(t,new Set),this.Lt.get(t)}}function e(t,s){const{href:i}=location;return new URL(t,i).href===new URL(s,i).href}class h{constructor(t,s){this.type=t,Object.assign(this,s)}}const n={type:"SKIP_WAITING"};class a extends i{constructor(t,i={}){super(),this.Bt={},this.Tt=0,this.Mt=new s,this.At=new s,this.Gt=new s,this.Kt=0,this.Nt=new Set,this.zt=()=>{const t=this.Dt,s=t.installing;this.Tt>0||!e(s.scriptURL,this.Ft.toString())||performance.now()>this.Kt+6e4?(this.Ht=s,t.removeEventListener("updatefound",this.zt)):(this.Jt=s,this.Nt.add(s),this.Mt.resolve(s)),++this.Tt,s.addEventListener("statechange",this.Qt)},this.Qt=t=>{const s=this.Dt,i=t.target,{state:e}=i,n=i===this.Ht,a={sw:i,isExternal:n,originalEvent:t};!n&&this.Vt&&(a.isUpdate=!0),this.dispatchEvent(new h(e,a)),"installed"===e?this.Xt=self.setTimeout((()=>{"installed"===e&&s.waiting===i&&this.dispatchEvent(new h("waiting",a))}),200):"activating"===e&&(clearTimeout(this.Xt),n||this.At.resolve(i))},this.Yt=t=>{const s=this.Jt,i=s!==navigator.serviceWorker.controller;this.dispatchEvent(new h("controlling",{isExternal:i,originalEvent:t,sw:s,isUpdate:this.Vt})),i||this.Gt.resolve(s)},this.Zt=async t=>{const{data:s,ports:i,source:e}=t;await this.getSW(),this.Nt.has(e)&&this.dispatchEvent(new h("message",{data:s,originalEvent:t,ports:i,sw:e}))},this.Ft=t,this.Bt=i,navigator.serviceWorker.addEventListener("message",this.Zt)}async register({immediate:t=!1}={}){t||"complete"===document.readyState||await new Promise((t=>window.addEventListener("load",t))),this.Vt=Boolean(navigator.serviceWorker.controller),this.ts=this.ss(),this.Dt=await this.es(),this.ts&&(this.Jt=this.ts,this.At.resolve(this.ts),this.Gt.resolve(this.ts),this.ts.addEventListener("statechange",this.Qt,{once:!0}));const s=this.Dt.waiting;return s&&e(s.scriptURL,this.Ft.toString())&&(this.Jt=s,Promise.resolve().then((()=>{this.dispatchEvent(new h("waiting",{sw:s,wasWaitingBeforeRegister:!0}))})).then((()=>{}))),this.Jt&&(this.Mt.resolve(this.Jt),this.Nt.add(this.Jt)),this.Dt.addEventListener("updatefound",this.zt),navigator.serviceWorker.addEventListener("controllerchange",this.Yt),this.Dt}async update(){this.Dt&&await this.Dt.update()}get active(){return this.At.promise}get controlling(){return this.Gt.promise}getSW(){return void 0!==this.Jt?Promise.resolve(this.Jt):this.Mt.promise}async messageSW(s){return t(await this.getSW(),s)}messageSkipWaiting(){this.Dt&&this.Dt.waiting&&t(this.Dt.waiting,n)}ss(){const t=navigator.serviceWorker.controller;return t&&e(t.scriptURL,this.Ft.toString())?t:void 0}async es(){try{const t=await navigator.serviceWorker.register(this.Ft,this.Bt);return this.Kt=performance.now(),t}catch(t){throw t}}}export{a as Workbox,h as WorkboxEvent,t as messageSW}; +//# sourceMappingURL=workbox-window.prod.mjs.map diff --git a/src/Resources/workbox-v7.0.0/workbox-window.prod.mjs.map b/src/Resources/workbox-v7.0.0/workbox-window.prod.mjs.map new file mode 100644 index 0000000..a6db096 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.prod.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"workbox-window.prod.mjs","sources":["../_version.js","../messageSW.js","../../workbox-core/_version.js","../../workbox-core/_private/Deferred.js","../utils/WorkboxEventTarget.js","../utils/urlsMatch.js","../utils/WorkboxEvent.js","../Workbox.js","../../workbox-core/_private/dontWaitFor.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:window:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport './_version.js';\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will not\n * resolve.\n *\n * @param {ServiceWorker} sw The service worker to send the message to.\n * @param {Object} data An object to send to the service worker.\n * @return {Promise}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","constructor","promise","reject","WorkboxEventTarget","_eventListenerRegistry","Map","addEventListener","type","listener","this","_getEventListenersByType","add","removeEventListener","delete","dispatchEvent","target","listeners","has","set","Set","get","urlsMatch","url1","url2","href","location","URL","WorkboxEvent","props","Object","assign","SKIP_WAITING_MESSAGE","Workbox","scriptURL","registerOptions","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","_onUpdateFound","registration","_registration","installingSW","installing","_scriptURL","toString","performance","now","_externalSW","_sw","_onStateChange","originalEvent","state","isExternal","eventProps","_isUpdate","isUpdate","_waitingTimeout","setTimeout","waiting","clearTimeout","_onControllerChange","navigator","serviceWorker","controller","_onMessage","async","ports","source","getSW","immediate","document","readyState","res","window","Boolean","_compatibleControllingSW","_getControllingSWIfCompatible","_registerScript","once","waitingSW","then","wasWaitingBeforeRegister","update","active","controlling","undefined","messageSkipWaiting","reg","register","error"],"mappings":"AAEA,IACIA,KAAK,yBAA2BC,GACnC,CACD,MAAOC,ICmBP,SAASC,EAAUC,EAAIC,UACZ,IAAIC,SAASC,UACVC,EAAiB,IAAIC,eAC3BD,EAAeE,MAAMC,UAAaC,IAC9BL,EAAQK,EAAMP,KAAd,EAEJD,EAAGS,YAAYR,EAAM,CAACG,EAAeM,UAE5C,CC9BD,IACId,KAAK,uBAAyBC,GACjC,CACD,MAAOC,ICWP,MAAMa,EAIFC,mBACSC,QAAU,IAAIX,SAAQ,CAACC,EAASW,UAC5BX,QAAUA,OACVW,OAASA,CAAd,KCVL,MAAMC,EACTH,mBACSI,GAAyB,IAAIC,IAOtCC,iBAAiBC,EAAMC,GACPC,KAAKC,GAAyBH,GACtCI,IAAIH,GAOZI,oBAAoBL,EAAMC,QACjBE,GAAyBH,GAAMM,OAAOL,GAM/CM,cAAclB,GACVA,EAAMmB,OAASN,WACTO,EAAYP,KAAKC,GAAyBd,EAAMW,UACjD,MAAMC,KAAYQ,EACnBR,EAASZ,GAWjBc,GAAyBH,UAChBE,KAAKL,GAAuBa,IAAIV,SAC5BH,GAAuBc,IAAIX,EAAM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cAAc5D,iBAAiB,mBAAoBG,KAAKuD,IAC3DvD,KAAKmC,kBAMPnC,KAAKmC,UAQJnC,KAAKmC,GAAc0C,SAWzBC,oBACO9E,KAAK6B,GAAgBrC,QAc5BuF,yBACO/E,KAAK8B,GAAqBtC,QAiBrCuE,oBAGwBiB,IAAbhF,KAAK2C,GACN9D,QAAQC,QAAQkB,KAAK2C,IACrB3C,KAAK4B,GAAYpC,wBAiBXZ,UAELF,QADUsB,KAAK+D,QACDnF,GASzBqG,qBACQjF,KAAKmC,IAAiBnC,KAAKmC,GAAckB,SACpC3E,EAAUsB,KAAKmC,GAAckB,QAAS/B,GAUnDiD,WACUb,EAAaF,UAAUC,cAAcC,kBACvCA,GACA9C,EAAU8C,EAAWlC,UAAWxB,KAAKsC,GAAWC,YACzCmB,8BAiBDwB,QAAY1B,UAAUC,cAAc0B,SAASnF,KAAKsC,GAAYtC,KAAK0B,gBAIpEK,GAAoBS,YAAYC,MAC9ByC,EAEX,MAAOE,SAKGA"} \ No newline at end of file diff --git a/src/Resources/workbox-v7.0.0/workbox-window.prod.umd.js b/src/Resources/workbox-v7.0.0/workbox-window.prod.umd.js new file mode 100644 index 0000000..785e2c7 --- /dev/null +++ b/src/Resources/workbox-v7.0.0/workbox-window.prod.umd.js @@ -0,0 +1,2 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((n="undefined"!=typeof globalThis?globalThis:n||self).workbox={})}(this,(function(n){"use strict";try{self["workbox:window:7.0.0"]&&_()}catch(n){}function t(n,t){return new Promise((function(r){var e=new MessageChannel;e.port1.onmessage=function(n){r(n.data)},n.postMessage(t,[e.port2])}))}function r(n,t){for(var r=0;rn.length)&&(t=n.length);for(var r=0,e=new Array(t);r=n.length?{done:!0}:{done:!1,value:n[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=n[Symbol.iterator]()).next.bind(r)}try{self["workbox:core:7.0.0"]&&_()}catch(n){}var o=function(){var n=this;this.promise=new Promise((function(t,r){n.resolve=t,n.reject=r}))};function u(n,t){var r=location.href;return new URL(n,r).href===new URL(t,r).href}var a=function(n,t){this.type=n,Object.assign(this,t)};function c(n,t,r){return r?t?t(n):n:(n&&n.then||(n=Promise.resolve(n)),t?n.then(t):n)}function f(){}var s={type:"SKIP_WAITING"};function v(n,t){if(!t)return n&&n.then?n.then(f):Promise.resolve()}var h=function(n){var e,i;function f(t,r){var e,i;return void 0===r&&(r={}),(e=n.call(this)||this).nn={},e.tn=0,e.rn=new o,e.en=new o,e.on=new o,e.un=0,e.an=new Set,e.cn=function(){var n=e.fn,t=n.installing;e.tn>0||!u(t.scriptURL,e.sn.toString())||performance.now()>e.un+6e4?(e.vn=t,n.removeEventListener("updatefound",e.cn)):(e.hn=t,e.an.add(t),e.rn.resolve(t)),++e.tn,t.addEventListener("statechange",e.ln)},e.ln=function(n){var t=e.fn,r=n.target,i=r.state,o=r===e.vn,u={sw:r,isExternal:o,originalEvent:n};!o&&e.dn&&(u.isUpdate=!0),e.dispatchEvent(new a(i,u)),"installed"===i?e.mn=self.setTimeout((function(){"installed"===i&&t.waiting===r&&e.dispatchEvent(new a("waiting",u))}),200):"activating"===i&&(clearTimeout(e.mn),o||e.en.resolve(r))},e.wn=function(n){var t=e.hn,r=t!==navigator.serviceWorker.controller;e.dispatchEvent(new a("controlling",{isExternal:r,originalEvent:n,sw:t,isUpdate:e.dn})),r||e.on.resolve(t)},e.gn=(i=function(n){var t=n.data,r=n.ports,i=n.source;return c(e.getSW(),(function(){e.an.has(i)&&e.dispatchEvent(new a("message",{data:t,originalEvent:n,ports:r,sw:i}))}))},function(){for(var n=[],t=0;t}\n * @memberof workbox-window\n */\n// Better not change type of data.\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction messageSW(sw, data) {\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => {\n resolve(event.data);\n };\n sw.postMessage(data, [messageChannel.port2]);\n });\n}\nexport { messageSW };\n","\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:core:7.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * The Deferred class composes Promises in a way that allows for them to be\n * resolved or rejected from outside the constructor. In most cases promises\n * should be used directly, but Deferreds can be necessary when the logic to\n * resolve a promise must be separate.\n *\n * @private\n */\nclass Deferred {\n /**\n * Creates a promise and exposes its resolve and reject functions as methods.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\nexport { Deferred };\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * Returns true if two URLs have the same `.href` property. The URLS can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param {string} url1\n * @param {string} url2\n * @return {boolean}\n */\nexport function urlsMatch(url1, url2) {\n const { href } = location;\n return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class WorkboxEvent {\n constructor(type, props) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport { Deferred } from 'workbox-core/_private/Deferred.js';\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { messageSW } from './messageSW.js';\nimport { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';\nimport { urlsMatch } from './utils/urlsMatch.js';\nimport { WorkboxEvent } from './utils/WorkboxEvent.js';\nimport './_version.js';\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires {@link workbox-window.Workbox#message}\n * @fires {@link workbox-window.Workbox#installed}\n * @fires {@link workbox-window.Workbox#waiting}\n * @fires {@link workbox-window.Workbox#controlling}\n * @fires {@link workbox-window.Workbox#activated}\n * @fires {@link workbox-window.Workbox#redundant}\n * @memberof workbox-window\n */\nclass Workbox extends WorkboxEventTarget {\n /**\n * Creates a new Workbox instance with a script URL and service worker\n * options. The script URL and options are the same as those used when\n * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n *\n * @param {string|TrustedScriptURL} scriptURL The service worker script\n * associated with this instance. Using a\n * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.\n * @param {Object} [registerOptions] The service worker options associated\n * with this instance.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor(scriptURL, registerOptions = {}) {\n super();\n this._registerOptions = {};\n this._updateFoundCount = 0;\n // Deferreds we can resolve later.\n this._swDeferred = new Deferred();\n this._activeDeferred = new Deferred();\n this._controllingDeferred = new Deferred();\n this._registrationTime = 0;\n this._ownSWs = new Set();\n /**\n * @private\n */\n this._onUpdateFound = () => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const installingSW = registration.installing;\n // If the script URL passed to `navigator.serviceWorker.register()` is\n // different from the current controlling SW's script URL, we know any\n // successful registration calls will trigger an `updatefound` event.\n // But if the registered script URL is the same as the current controlling\n // SW's script URL, we'll only get an `updatefound` event if the file\n // changed since it was last registered. This can be a problem if the user\n // opens up the same page in a different tab, and that page registers\n // a SW that triggers an update. It's a problem because this page has no\n // good way of knowing whether the `updatefound` event came from the SW\n // script it registered or from a registration attempt made by a newer\n // version of the page running in another tab.\n // To minimize the possibility of a false positive, we use the logic here:\n const updateLikelyTriggeredExternally = \n // Since we enforce only calling `register()` once, and since we don't\n // add the `updatefound` event listener until the `register()` call, if\n // `_updateFoundCount` is > 0 then it means this method has already\n // been called, thus this SW must be external\n this._updateFoundCount > 0 ||\n // If the script URL of the installing SW is different from this\n // instance's script URL, we know it's definitely not from our\n // registration.\n !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n // If all of the above are false, then we use a time-based heuristic:\n // Any `updatefound` event that occurs long after our registration is\n // assumed to be external.\n performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION\n ? // If any of the above are not true, we assume the update was\n // triggered by this instance.\n true\n : false;\n if (updateLikelyTriggeredExternally) {\n this._externalSW = installingSW;\n registration.removeEventListener('updatefound', this._onUpdateFound);\n }\n else {\n // If the update was not triggered externally we know the installing\n // SW is the one we registered, so we set it.\n this._sw = installingSW;\n this._ownSWs.add(installingSW);\n this._swDeferred.resolve(installingSW);\n // The `installing` state isn't something we have a dedicated\n // callback for, but we do log messages for it in development.\n if (process.env.NODE_ENV !== 'production') {\n if (navigator.serviceWorker.controller) {\n logger.log('Updated service worker found. Installing now...');\n }\n else {\n logger.log('Service worker is installing...');\n }\n }\n }\n // Increment the `updatefound` count, so future invocations of this\n // method can be sure they were triggered externally.\n ++this._updateFoundCount;\n // Add a `statechange` listener regardless of whether this update was\n // triggered externally, since we have callbacks for both.\n installingSW.addEventListener('statechange', this._onStateChange);\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onStateChange = (originalEvent) => {\n // `this._registration` will never be `undefined` after an update is found.\n const registration = this._registration;\n const sw = originalEvent.target;\n const { state } = sw;\n const isExternal = sw === this._externalSW;\n const eventProps = {\n sw,\n isExternal,\n originalEvent,\n };\n if (!isExternal && this._isUpdate) {\n eventProps.isUpdate = true;\n }\n this.dispatchEvent(new WorkboxEvent(state, eventProps));\n if (state === 'installed') {\n // This timeout is used to ignore cases where the service worker calls\n // `skipWaiting()` in the install event, thus moving it directly in the\n // activating state. (Since all service workers *must* go through the\n // waiting phase, the only way to detect `skipWaiting()` called in the\n // install event is to observe that the time spent in the waiting phase\n // is very short.)\n // NOTE: we don't need separate timeouts for the own and external SWs\n // since they can't go through these phases at the same time.\n this._waitingTimeout = self.setTimeout(() => {\n // Ensure the SW is still waiting (it may now be redundant).\n if (state === 'installed' && registration.waiting === sw) {\n this.dispatchEvent(new WorkboxEvent('waiting', eventProps));\n if (process.env.NODE_ENV !== 'production') {\n if (isExternal) {\n logger.warn('An external service worker has installed but is ' +\n 'waiting for this client to close before activating...');\n }\n else {\n logger.warn('The service worker has installed but is waiting ' +\n 'for existing clients to close before activating...');\n }\n }\n }\n }, WAITING_TIMEOUT_DURATION);\n }\n else if (state === 'activating') {\n clearTimeout(this._waitingTimeout);\n if (!isExternal) {\n this._activeDeferred.resolve(sw);\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n switch (state) {\n case 'installed':\n if (isExternal) {\n logger.warn('An external service worker has installed. ' +\n 'You may want to suggest users reload this page.');\n }\n else {\n logger.log('Registered service worker installed.');\n }\n break;\n case 'activated':\n if (isExternal) {\n logger.warn('An external service worker has activated.');\n }\n else {\n logger.log('Registered service worker activated.');\n if (sw !== navigator.serviceWorker.controller) {\n logger.warn('The registered service worker is active but ' +\n 'not yet controlling the page. Reload or run ' +\n '`clients.claim()` in the service worker.');\n }\n }\n break;\n case 'redundant':\n if (sw === this._compatibleControllingSW) {\n logger.log('Previously controlling service worker now redundant!');\n }\n else if (!isExternal) {\n logger.log('Registered service worker now redundant!');\n }\n break;\n }\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onControllerChange = (originalEvent) => {\n const sw = this._sw;\n const isExternal = sw !== navigator.serviceWorker.controller;\n // Unconditionally dispatch the controlling event, with isExternal set\n // to distinguish between controller changes due to the initial registration\n // vs. an update-check or other tab's registration.\n // See https://github.com/GoogleChrome/workbox/issues/2786\n this.dispatchEvent(new WorkboxEvent('controlling', {\n isExternal,\n originalEvent,\n sw,\n isUpdate: this._isUpdate,\n }));\n if (!isExternal) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Registered service worker now controlling this page.');\n }\n this._controllingDeferred.resolve(sw);\n }\n };\n /**\n * @private\n * @param {Event} originalEvent\n */\n this._onMessage = async (originalEvent) => {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { data, ports, source } = originalEvent;\n // Wait until there's an \"own\" service worker. This is used to buffer\n // `message` events that may be received prior to calling `register()`.\n await this.getSW();\n // If the service worker that sent the message is in the list of own\n // service workers for this instance, dispatch a `message` event.\n // NOTE: we check for all previously owned service workers rather than\n // just the current one because some messages (e.g. cache updates) use\n // a timeout when sent and may be delayed long enough for a service worker\n // update to be found.\n if (this._ownSWs.has(source)) {\n this.dispatchEvent(new WorkboxEvent('message', {\n // Can't change type 'any' of data.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data,\n originalEvent,\n ports,\n sw: source,\n }));\n }\n };\n this._scriptURL = scriptURL;\n this._registerOptions = registerOptions;\n // Add a message listener immediately since messages received during\n // page load are buffered only until the DOMContentLoaded event:\n // https://github.com/GoogleChrome/workbox/issues/2202\n navigator.serviceWorker.addEventListener('message', this._onMessage);\n }\n /**\n * Registers a service worker for this instances script URL and service\n * worker options. By default this method delays registration until after\n * the window has loaded.\n *\n * @param {Object} [options]\n * @param {Function} [options.immediate=false] Setting this to true will\n * register the service worker immediately, even if the window has\n * not loaded (not recommended).\n */\n async register({ immediate = false } = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (this._registrationTime) {\n logger.error('Cannot re-register a Workbox instance after it has ' +\n 'been registered. Create a new instance instead.');\n return;\n }\n }\n if (!immediate && document.readyState !== 'complete') {\n await new Promise((res) => window.addEventListener('load', res));\n }\n // Set this flag to true if any service worker was controlling the page\n // at registration time.\n this._isUpdate = Boolean(navigator.serviceWorker.controller);\n // Before registering, attempt to determine if a SW is already controlling\n // the page, and if that SW script (and version, if specified) matches this\n // instance's script.\n this._compatibleControllingSW = this._getControllingSWIfCompatible();\n this._registration = await this._registerScript();\n // If we have a compatible controller, store the controller as the \"own\"\n // SW, resolve active/controlling deferreds and add necessary listeners.\n if (this._compatibleControllingSW) {\n this._sw = this._compatibleControllingSW;\n this._activeDeferred.resolve(this._compatibleControllingSW);\n this._controllingDeferred.resolve(this._compatibleControllingSW);\n this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });\n }\n // If there's a waiting service worker with a matching URL before the\n // `updatefound` event fires, it likely means that this site is open\n // in another tab, or the user refreshed the page (and thus the previous\n // page wasn't fully unloaded before this page started loading).\n // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n const waitingSW = this._registration.waiting;\n if (waitingSW &&\n urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n // Store the waiting SW as the \"own\" Sw, even if it means overwriting\n // a compatible controller.\n this._sw = waitingSW;\n // Run this in the next microtask, so any code that adds an event\n // listener after awaiting `register()` will get this event.\n dontWaitFor(Promise.resolve().then(() => {\n this.dispatchEvent(new WorkboxEvent('waiting', {\n sw: waitingSW,\n wasWaitingBeforeRegister: true,\n }));\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('A service worker was already waiting to activate ' +\n 'before this script was registered...');\n }\n }));\n }\n // If an \"own\" SW is already set, resolve the deferred.\n if (this._sw) {\n this._swDeferred.resolve(this._sw);\n this._ownSWs.add(this._sw);\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log('Successfully registered service worker.', this._scriptURL.toString());\n if (navigator.serviceWorker.controller) {\n if (this._compatibleControllingSW) {\n logger.debug('A service worker with the same script URL ' +\n 'is already controlling this page.');\n }\n else {\n logger.debug('A service worker with a different script URL is ' +\n 'currently controlling the page. The browser is now fetching ' +\n 'the new script now...');\n }\n }\n const currentPageIsOutOfScope = () => {\n const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);\n const scopeURLBasePath = new URL('./', scopeURL.href).pathname;\n return !location.pathname.startsWith(scopeURLBasePath);\n };\n if (currentPageIsOutOfScope()) {\n logger.warn('The current page is not in scope for the registered ' +\n 'service worker. Was this a mistake?');\n }\n }\n this._registration.addEventListener('updatefound', this._onUpdateFound);\n navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);\n return this._registration;\n }\n /**\n * Checks for updates of the registered service worker.\n */\n async update() {\n if (!this._registration) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('Cannot update a Workbox instance without ' +\n 'being registered. Register the Workbox instance first.');\n }\n return;\n }\n // Try to update registration\n await this._registration.update();\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is active. If a service worker was already controlling at registration\n * time then it will resolve to that if the script URLs (and optionally\n * script versions) match, otherwise it will wait until an update is found\n * and activates.\n *\n * @return {Promise}\n */\n get active() {\n return this._activeDeferred.promise;\n }\n /**\n * Resolves to the service worker registered by this instance as soon as it\n * is controlling the page. If a service worker was already controlling at\n * registration time then it will resolve to that if the script URLs (and\n * optionally script versions) match, otherwise it will wait until an update\n * is found and starts controlling the page.\n * Note: the first time a service worker is installed it will active but\n * not start controlling the page unless `clients.claim()` is called in the\n * service worker.\n *\n * @return {Promise}\n */\n get controlling() {\n return this._controllingDeferred.promise;\n }\n /**\n * Resolves with a reference to a service worker that matches the script URL\n * of this instance, as soon as it's available.\n *\n * If, at registration time, there's already an active or waiting service\n * worker with a matching script URL, it will be used (with the waiting\n * service worker taking precedence over the active service worker if both\n * match, since the waiting service worker would have been registered more\n * recently).\n * If there's no matching active or waiting service worker at registration\n * time then the promise will not resolve until an update is found and starts\n * installing, at which point the installing service worker is used.\n *\n * @return {Promise}\n */\n getSW() {\n // If `this._sw` is set, resolve with that as we want `getSW()` to\n // return the correct (new) service worker if an update is found.\n return this._sw !== undefined\n ? Promise.resolve(this._sw)\n : this._swDeferred.promise;\n }\n /**\n * Sends the passed data object to the service worker registered by this\n * instance (via {@link workbox-window.Workbox#getSW}) and resolves\n * with a response (if any).\n *\n * A response can be set in a message handler in the service worker by\n * calling `event.ports[0].postMessage(...)`, which will resolve the promise\n * returned by `messageSW()`. If no response is set, the promise will never\n * resolve.\n *\n * @param {Object} data An object to send to the service worker\n * @return {Promise}\n */\n // We might be able to change the 'data' type to Record in the future.\n // eslint-disable-next-line @typescript-eslint/ban-types\n async messageSW(data) {\n const sw = await this.getSW();\n return messageSW(sw, data);\n }\n /**\n * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's\n * currently in the `waiting` state associated with the current registration.\n *\n * If there is no current registration or no service worker is `waiting`,\n * calling this will have no effect.\n */\n messageSkipWaiting() {\n if (this._registration && this._registration.waiting) {\n void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n }\n }\n /**\n * Checks for a service worker already controlling the page and returns\n * it if its script URL matches.\n *\n * @private\n * @return {ServiceWorker|undefined}\n */\n _getControllingSWIfCompatible() {\n const controller = navigator.serviceWorker.controller;\n if (controller &&\n urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n return controller;\n }\n else {\n return undefined;\n }\n }\n /**\n * Registers a service worker for this instances script URL and register\n * options and tracks the time registration was complete.\n *\n * @private\n */\n async _registerScript() {\n try {\n // this._scriptURL may be a TrustedScriptURL, but there's no support for\n // passing that to register() in lib.dom right now.\n // https://github.com/GoogleChrome/workbox/issues/2855\n const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);\n // Keep track of when registration happened, so it can be used in the\n // `this._onUpdateFound` heuristic. Also use the presence of this\n // property as a way to see if `.register()` has been called.\n this._registrationTime = performance.now();\n return reg;\n }\n catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n logger.error(error);\n }\n // Re-throw the error.\n throw error;\n }\n }\n}\nexport { Workbox };\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {WorkboxEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n * event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event, or `undefined` in the case where the service worker was waiting\n * to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n * a matching `scriptURL` was already waiting when this `Workbox`\n * instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {WorkboxEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n * event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n * controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n","/*\n Copyright 2019 Google LLC\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\n/**\n * A helper function that prevents a promise from being flagged as unused.\n *\n * @private\n **/\nexport function dontWaitFor(promise) {\n // Effective no-op.\n void promise.then(() => { });\n}\n","/*\n Copyright 2019 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class WorkboxEventTarget {\n constructor() {\n this._eventListenerRegistry = new Map();\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n addEventListener(type, listener) {\n const foo = this._getEventListenersByType(type);\n foo.add(listener);\n }\n /**\n * @param {string} type\n * @param {Function} listener\n * @private\n */\n removeEventListener(type, listener) {\n this._getEventListenersByType(type).delete(listener);\n }\n /**\n * @param {Object} event\n * @private\n */\n dispatchEvent(event) {\n event.target = this;\n const listeners = this._getEventListenersByType(event.type);\n for (const listener of listeners) {\n listener(event);\n }\n }\n /**\n * Returns a Set of listeners associated with the passed event type.\n * If no handlers have been registered, an empty Set is returned.\n *\n * @param {string} type The event type.\n * @return {Set} An array of handler functions.\n * @private\n */\n _getEventListenersByType(type) {\n if (!this._eventListenerRegistry.has(type)) {\n this._eventListenerRegistry.set(type, new Set());\n }\n return this._eventListenerRegistry.get(type);\n }\n}\n"],"names":["self","_","e","messageSW","sw","data","Promise","resolve","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","Deferred","promise","reject","_this","urlsMatch","url1","url2","href","location","URL","WorkboxEvent","type","props","Object","assign","this","_await","value","then","direct","_empty","SKIP_WAITING_MESSAGE","_awaitIgnored","Workbox","scriptURL","registerOptions","f","_registerOptions","_updateFoundCount","_swDeferred","_activeDeferred","_controllingDeferred","_registrationTime","_ownSWs","Set","_onUpdateFound","registration","_registration","installingSW","installing","_scriptURL","toString","performance","now","_externalSW","removeEventListener","_sw","add","addEventListener","_onStateChange","originalEvent","target","state","isExternal","eventProps","_isUpdate","isUpdate","dispatchEvent","_waitingTimeout","setTimeout","waiting","clearTimeout","_onControllerChange","navigator","serviceWorker","controller","_onMessage","ports","source","getSW","has","args","i","arguments","length","apply","register","immediate","body","result","document","readyState","res","window","Boolean","_compatibleControllingSW","_this3","_getControllingSWIfCompatible","_registerScript","once","waitingSW","wasWaitingBeforeRegister","update","undefined","messageSkipWaiting","recover","_this9","reg","error","_eventListenerRegistry","Map","listener","_getEventListenersByType","delete","set","get"],"mappings":"+OAEA,IACIA,KAAK,yBAA2BC,GACnC,CACD,MAAOC,ICmBP,SAASC,EAAUC,EAAIC,UACZ,IAAIC,SAAQ,SAACC,OACVC,EAAiB,IAAIC,eAC3BD,EAAeE,MAAMC,UAAY,SAACC,GAC9BL,EAAQK,EAAMP,OAElBD,EAAGS,YAAYR,EAAM,CAACG,EAAeM,UAE5C,49BC9BD,IACId,KAAK,uBAAyBC,GACjC,CACD,MAAOC,QCWDa,EAIF,2BACSC,QAAU,IAAIV,SAAQ,SAACC,EAASU,GACjCC,EAAKX,QAAUA,EACfW,EAAKD,OAASA,IAErB,ECRE,SAASE,EAAUC,EAAMC,OACpBC,EAASC,SAATD,YACD,IAAIE,IAAIJ,EAAME,GAAMA,OAAS,IAAIE,IAAIH,EAAMC,GAAMA,IAC3D,KCNYG,EACT,SAAYC,EAAMC,QACTD,KAAOA,EACZE,OAAOC,OAAOC,KAAMH,EACvB,ECkEE,SAASI,EAAOC,EAAOC,EAAMC,UAC/BA,EACID,EAAOA,EAAKD,GAASA,GAExBA,GAAUA,EAAMC,OACpBD,EAAQ1B,QAAQC,QAAQyB,IAElBC,EAAOD,EAAMC,KAAKA,GAAQD,EACjC,CAogBM,SAASG,KAxkBhB,IAAMC,EAAuB,CAAEV,KAAM,gBAuE9B,SAASW,EAAcL,EAAOE,OAC/BA,SACGF,GAASA,EAAMC,KAAOD,EAAMC,KAAKE,GAAU7B,QAAQC,SAE3D,KA9DK+B,iCAaUC,EAAWC,SAoBJC,kBApBID,IAAAA,EAAkB,2BAEhCE,GAAmB,KACnBC,GAAoB,IAEpBC,GAAc,IAAI7B,IAClB8B,GAAkB,IAAI9B,IACtB+B,GAAuB,IAAI/B,IAC3BgC,GAAoB,IACpBC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ceWorkerBuilder.php index a4b01f7..9046e4c 100644 --- a/src/Service/ServiceWorkerBuilder.php +++ b/src/Service/ServiceWorkerBuilder.php @@ -5,6 +5,7 @@ namespace SpomkyLabs\PwaBundle\Service; use SpomkyLabs\PwaBundle\Dto\Manifest; +use SpomkyLabs\PwaBundle\Dto\Workbox; use Symfony\Component\AssetMapper\AssetMapperInterface; use Symfony\Component\Serializer\Encoder\JsonEncode; use Symfony\Component\Serializer\SerializerInterface; @@ -19,52 +20,49 @@ final readonly class ServiceWorkerBuilder { - private ?string $serviceWorkerPublicUrl; - public function __construct( private SerializerInterface $serializer, private Manifest $manifest, private AssetMapperInterface $assetMapper, ) { - $serviceWorkerPublicUrl = $manifest->serviceWorker?->dest; - $this->serviceWorkerPublicUrl = $serviceWorkerPublicUrl === null ? null : '/' . trim( - $serviceWorkerPublicUrl, - '/' - ); } public function build(): ?string { - if ($this->serviceWorkerPublicUrl === null) { - return null; - } - $serviceWorkerSource = $this->manifest->serviceWorker?->src; - if ($serviceWorkerSource === null) { + $serviceWorker = $this->manifest->serviceWorker; + if ($serviceWorker === null) { return null; } - if (! str_starts_with($serviceWorkerSource, '/')) { - $asset = $this->assetMapper->getAsset($serviceWorkerSource); + if (! str_starts_with($serviceWorker->src, '/')) { + $asset = $this->assetMapper->getAsset($serviceWorker->src); assert($asset !== null, 'Unable to find service worker source asset'); $body = $asset->content ?? file_get_contents($asset->sourcePath); } else { - $body = file_get_contents($serviceWorkerSource); + $body = file_get_contents($serviceWorker->src); } assert(is_string($body), 'Unable to find service worker source content'); - $body = $this->processPrecachedAssets($body); - $body = $this->processWarmCacheUrls($body); - $body = $this->processWidgets($body); + $workbox = $serviceWorker->workbox; + if ($workbox->enabled === true) { + $body = $this->processWorkbox($workbox, $body); + } - return $this->processOfflineFallback($body); + return $body; } - private function processPrecachedAssets(string $body): string + private function processWorkbox(Workbox $workbox, string $body): string { - $config = $this->manifest->serviceWorker; - if ($config === null) { - return $body; - } - if (! str_contains($body, $config->precachingPlaceholder)) { + $body = $this->processWorkboxImport($workbox, $body); + $body = $this->processPrecachedAssets($workbox, $body); + $body = $this->processWarmCacheUrls($workbox, $body); + $body = $this->processWidgets($workbox, $body); + + return $this->processOfflineFallback($workbox, $body); + } + + private function processPrecachedAssets(Workbox $workbox, string $body): string + { + if (! str_contains($body, $workbox->precachingPlaceholder)) { return $body; } $result = []; @@ -87,19 +85,15 @@ private function processPrecachedAssets(string $body): string precacheAndRoute({$assets}); PRECACHE_STRATEGY; - return str_replace($config->precachingPlaceholder, trim($declaration), $body); + return str_replace($workbox->precachingPlaceholder, trim($declaration), $body); } - private function processWarmCacheUrls(string $body): string + private function processWarmCacheUrls(Workbox $workbox, string $body): string { - $config = $this->manifest->serviceWorker; - if ($config === null) { + if (! str_contains($body, $workbox->warmCachePlaceholder)) { return $body; } - if (! str_contains($body, $config->warmCachePlaceholder)) { - return $body; - } - $urls = $config->warmCacheUrls; + $urls = $workbox->warmCacheUrls; if (count($urls) === 0) { return $body; } @@ -126,20 +120,16 @@ private function processWarmCacheUrls(string $body): string }); WARM_CACHE_URL_STRATEGY; - return str_replace($config->warmCachePlaceholder, trim($declaration), $body); + return str_replace($workbox->warmCachePlaceholder, trim($declaration), $body); } - private function processOfflineFallback(string $body): string + private function processOfflineFallback(Workbox $workbox, string $body): string { - $config = $this->manifest->serviceWorker; - if ($config === null) { - return $body; - } - if (! str_contains($body, $config->offlineFallbackPlaceholder) || $config->offlineFallback === null) { + if (! str_contains($body, $workbox->offlineFallbackPlaceholder) || $workbox->offlineFallback === null) { return $body; } - $url = $this->serializer->serialize($config->offlineFallback, 'json', [ + $url = $this->serializer->serialize($workbox->offlineFallback, 'json', [ JsonEncode::OPTIONS => JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR, ]); @@ -165,16 +155,12 @@ private function processOfflineFallback(string $body): string }); OFFLINE_FALLBACK_STRATEGY; - return str_replace($config->offlineFallbackPlaceholder, trim($declaration), $body); + return str_replace($workbox->offlineFallbackPlaceholder, trim($declaration), $body); } - private function processWidgets(string $body): string + private function processWidgets(Workbox $workbox, string $body): string { - $config = $this->manifest->serviceWorker; - if ($config === null) { - return $body; - } - if (! str_contains($body, $config->widgetsPlaceholder)) { + if (! str_contains($body, $workbox->widgetsPlaceholder)) { return $body; } $tags = []; @@ -250,6 +236,32 @@ private function processWidgets(string $body): string } OFFLINE_FALLBACK_STRATEGY; - return str_replace($config->widgetsPlaceholder, trim($declaration), $body); + return str_replace($workbox->widgetsPlaceholder, trim($declaration), $body); + } + + private function processWorkboxImport(Workbox $workbox, string $body): string + { + if (! str_contains($body, $workbox->workboxImportPlaceholder)) { + return $body; + } + if ($workbox->useCDN === true) { + $declaration = <<version}/workbox-sw.js' +); +IMPORT_CDN_STRATEGY; + } else { + $version = $workbox->version; + $publicUrl = '/' . trim($workbox->workboxPublicUrl, '/'); + $declaration = <<workboxImportPlaceholder, trim($declaration), $body); } } diff --git a/src/Subscriber/PwaDevServerSubscriber.php b/src/Subscriber/PwaDevServerSubscriber.php index e0469cb..57162dc 100644 --- a/src/Subscriber/PwaDevServerSubscriber.php +++ b/src/Subscriber/PwaDevServerSubscriber.php @@ -9,6 +9,7 @@ use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Config\FileLocator; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\Event\ResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; @@ -16,6 +17,11 @@ use Symfony\Component\Serializer\Encoder\JsonEncode; use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; use Symfony\Component\Serializer\SerializerInterface; +use function assert; +use function count; +use function is_array; +use function is_string; +use function mb_strlen; use const JSON_PRETTY_PRINT; use const JSON_THROW_ON_ERROR; use const JSON_UNESCAPED_SLASHES; @@ -27,7 +33,12 @@ private null|string $serviceWorkerPublicUrl; + private null|string $workboxPublicUrl; + + private null|string $workboxVersion; + public function __construct( + private readonly FileLocator $fileLocator, private ServiceWorkerBuilder $serviceWorkerBuilder, private SerializerInterface $serializer, private Manifest $manifest, @@ -41,6 +52,14 @@ public function __construct( $serviceWorkerPublicUrl, '/' ); + if ($manifest->serviceWorker?->workbox->enabled === true) { + $this->workboxVersion = $manifest->serviceWorker->workbox->version; + $workboxPublicUrl = $manifest->serviceWorker->workbox->workboxPublicUrl; + $this->workboxPublicUrl = '/' . trim($workboxPublicUrl, '/'); + } else { + $this->workboxVersion = null; + $this->workboxPublicUrl = null; + } } public function onKernelRequest(RequestEvent $event): void @@ -49,13 +68,21 @@ public function onKernelRequest(RequestEvent $event): void return; } - switch ($event->getRequest()->getPathInfo()) { - case $this->manifestPublicUrl : + $pathInfo = $event->getRequest() + ->getPathInfo(); + switch (true) { + case $pathInfo === $this->manifestPublicUrl : $this->serveManifest($event); break; - case $this->serviceWorkerPublicUrl : + case $pathInfo === $this->serviceWorkerPublicUrl : $this->serveServiceWorker($event); break; + case $this->workboxVersion !== null && $this->workboxPublicUrl !== null && str_starts_with( + $pathInfo, + $this->workboxPublicUrl + ) : + $this->serveWorkboxFile($event, $pathInfo); + break; } } @@ -114,4 +141,35 @@ private function serveServiceWorker(RequestEvent $event): void $event->setResponse($response); $event->stopPropagation(); } + + private function serveWorkboxFile(RequestEvent $event, string $pathInfo): void + { + if (str_contains($pathInfo, '/..')) { + return; + } + $asset = mb_substr($pathInfo, mb_strlen($this->workboxPublicUrl)); + $resource = sprintf('@SpomkyLabsPwaBundle/Resources/workbox-v%s%s', $this->workboxVersion, $asset); + $resourcePath = $this->fileLocator->locate($resource, null, false); + if (is_array($resourcePath)) { + if (count($resourcePath) === 1) { + $resourcePath = $resourcePath[0]; + } else { + return; + } + } + if (! is_string($resourcePath)) { + return; + } + + $body = file_get_contents($resourcePath); + assert(is_string($body), 'Unable to load the file content.'); + $response = new Response($body, Response::HTTP_OK, [ + 'Content-Type' => 'application/javascript', + 'X-SW-Dev' => true, + 'Etag' => hash('xxh128', $body), + ]); + + $event->setResponse($response); + $event->stopPropagation(); + } } diff --git a/src/Subscriber/WorkboxCompileEventListener.php b/src/Subscriber/WorkboxCompileEventListener.php new file mode 100644 index 0000000..c795bf9 --- /dev/null +++ b/src/Subscriber/WorkboxCompileEventListener.php @@ -0,0 +1,59 @@ +manifest->serviceWorker; + if ($serviceWorker === null || $serviceWorker->workbox->enabled !== true || $serviceWorker->workbox->useCDN === true) { + return; + } + $workboxVersion = $serviceWorker->workbox->version; + $workboxPublicUrl = '/' . trim($serviceWorker->workbox->workboxPublicUrl, '/'); + + $resourcePath = $this->fileLocator->locate( + sprintf('@SpomkyLabsPwaBundle/Resources/workbox-v%s', $workboxVersion) + ); + if (! is_string($resourcePath)) { + return; + } + + $files = scandir($resourcePath); + assert(is_array($files), 'Unable to list the files.'); + foreach ($files as $file) { + if (in_array($file, ['.', '..'], true)) { + continue; + } + if (str_contains($file, '.dev.')) { + continue; + } + $content = file_get_contents(sprintf('%s/%s', $resourcePath, $file)); + assert(is_string($content), 'Unable to load the file content.'); + $this->assetsFilesystem->write(sprintf('%s/%s', $workboxPublicUrl, $file), $content); + } + } +} diff --git a/tests/sw.js b/tests/sw.js index e5c5227..2a1ed19 100644 --- a/tests/sw.js +++ b/tests/sw.js @@ -1,23 +1,38 @@ -importScripts( - 'https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js' -); - -// *** Recipes *** -// You are free to change or remove any of these presets as you wish. -// See https://developer.chrome.com/docs/workbox/modules/workbox-recipes for more information. +//WORKBOX_IMPORT_PLACEHOLDER const { pageCache, imageCache, - staticResourceCache, googleFontsCache, } = workbox.recipes; +const {registerRoute} = workbox.routing; +const {CacheFirst} = workbox.strategies; +const {CacheableResponsePlugin} = workbox.cacheableResponse; + +pageCache(); +imageCache(); +googleFontsCache(); -pageCache();// => Cache pages with a network-first strategy. -staticResourceCache();// => Cache CSS, JS, and Web Worker requests with a cache-first strategy. -imageCache();// => Cache images with a cache-first strategy. -googleFontsCache();// => Cache the underlying font files with a cache-first strategy. +const cacheName = 'static-resources'; +const matchCallback = ({request}) => + // CSS + request.destination === 'style' || + // JavaScript + request.destination === 'script' || + // Web Workers + request.destination === 'worker'; + +registerRoute( + matchCallback, + new CacheFirst({ + cacheName, + plugins: [ + new CacheableResponsePlugin({ + statuses: [0, 200], + }), + ], + }) +); -// *** Bundle rules *** //PRECACHING_PLACEHOLDER //WARM_CACHE_URLS_PLACEHOLDER //OFFLINE_FALLBACK_PLACEHOLDER