From d14e997c5ecb6a7624a41b4bf9e071e4d998e73a Mon Sep 17 00:00:00 2001 From: wessberg Date: Sat, 6 Apr 2019 12:28:50 +0200 Subject: [PATCH 1/8] Upgraded workbox-sw typings to v4.2 --- types/workbox-sw/index.d.ts | 1657 ++++++++++++++++++++++++----------- 1 file changed, 1140 insertions(+), 517 deletions(-) diff --git a/types/workbox-sw/index.d.ts b/types/workbox-sw/index.d.ts index 30d9244dd6..eb98e7c5ce 100644 --- a/types/workbox-sw/index.d.ts +++ b/types/workbox-sw/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for workbox-sw 3.2 +// Type definitions for workbox-sw 4.2 // Project: https://github.com/GoogleChrome/workbox // Definitions by: Frederik Wessberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,88 +8,149 @@ * ===== BroadcastCacheUpdate ===== */ -interface IBroadcastCacheUpdateOptions { +interface BroadcastCacheUpdateOptions { + /** + * The name that will be used when creating the `BroadcastChannel`, + * which defaults to 'workbox' (the channel name used by the `workbox-window` package). + */ + channelName: string; + /** * A list of headers that will be used to determine whether the responses differ. */ headersToCheck: string[]; /** - * An attribution value that indicates where the update originated. + * The amount of time to wait for a ready message from the window on navigation requests + * before sending the update. */ - source: string; + deferNoticationTimeout: number; +} + +interface NotifyIfUpdatedOptions { + /** + * Cached response to compare. + */ + oldResponse: Response; + + /** + * Possibly updated response to compare. + */ + newResponse: Response; + + /** + * The URL of the request. + */ + url: string; + + /** + * Name of the cache the responses belong to. This is included in the broadcast message. + */ + cacheName: string; + + /** + * An optional event that triggered this possible cache update. + */ + event?: Event; } /** - * Uses the Broadcast Channel API to notify interested parties when a cached response has been updated. - * For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked + * Uses the [Broadcast Channel API]{@link https://developers.google.com/web/updates/2016/09/broadcastchannel} + * to notify interested parties when a cached response has been updated. + * In browsers that do not support the Broadcast Channel API, the instance + * falls back to sending the update via `postMessage()` to all window clients. + * + * For efficiency's sake, the underlying response bodies are not compared; + * only specific response headers are checked. */ declare class BroadcastCacheUpdate { /** - * Compare two Responses and send a message via the Broadcast Channel API if they differ. - * Neither of the Responses can be opaque. - * @param {Response} firstResponse - First response to compare. - * @param {Response} secondResponse - Second response to compare. - * @param {string} url - The URL of the updated request. - * @param {string} cacheName - Name of the cache the responses belong to. This is included in the message posted on the broadcast channel. + * Compare two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response) and send a message via the + * {@link https://developers.google.com/web/updates/2016/09/broadcastchannel|Broadcast Channel API} + * if they differ. + * Neither of the Responses can be {@link http://stackoverflow.com/questions/39109789|opaque}. + * + * @param {NotifyIfUpdatedOptions} options + * @returns {Promise} Resolves once the update is sent. */ - notifyIfUpdated (firstResponse: Response, secondResponse: Response, url: string, cacheName: string): void; + notifyIfUpdated (options: NotifyIfUpdatedOptions): Promise; } /** * Construct a BroadcastCacheUpdate instance with a specific channelName to broadcast messages on */ -interface IBroadcastCacheUpdateConstructor { - new (channelName: string, options: Partial): BroadcastCacheUpdate; +interface BroadcastCacheUpdateConstructor { + /** + * Construct a BroadcastCacheUpdate instance with a specific `channelName` to + * broadcast messages on + * @param {Partial} options + * @return {BroadcastCacheUpdate} + */ + new (options?: Partial): BroadcastCacheUpdate; } /** * ===== CacheableResponse ===== */ -interface ICacheableResponseOptions { +interface CacheableResponseOptions { + /** + * One or more status codes that a `Response` can have and be considered cacheable. + */ statuses: number[]; - headers: { [key: string]: string }; + /** + * 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. + */ + headers: Record; } /** - * This class allows you to set up rules determining what status codes and/or headers need to be present in order for a Response to be considered cacheable. + * 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. */ declare class CacheableResponse { /** * 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. - * @returns {boolean} + * @returns {boolean} `true` if the `Response` is cacheable, and `false` otherwise. */ isResponseCacheable (response: Response): boolean; } -/** - * 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. - */ -interface ICacheableResponseConstructor { - new (options: Partial): CacheableResponse; +interface CacheableResponseConstructor { + /** + * 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 {Partial} options + * @return {CacheableResponse} + */ + new (options: Partial): CacheableResponse; } /** * ===== CacheExpiration ===== */ -interface ICacheExpirationOptions { +interface CacheExpirationOptions { /** - * The maximum number of entries to store in a cache. + * The maximum number of entries to cache. + * Entries used the least will be removed as the maximum is reached. */ maxEntries: number; /** - * The maximum lifetime of a request to stay in the cache before it's removed. + * The maximum age of an entry before it's treated as stale and removed. */ maxAgeSeconds: number; } /** - * The CacheExpiration class allows you define an expiration and / or limit on the number of responses stored in a Cache. + * 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). */ declare class CacheExpiration { /** @@ -101,185 +162,280 @@ declare class CacheExpiration { /** * 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. + * + * Note: This method will not remove the cached entry, call + * `expireEntries()` to remove indexedDB and Cache entries. * @param {string} url * @returns {Promise} */ isURLExpired (url: string): Promise; /** - * 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. + * 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 * @returns {Promise} */ updateTimestamp (url: string): Promise; + + /** + * Removes the IndexedDB object store used to keep track of + * cache expiration metadata. + * @return {Promise} + */ + delete (): Promise; } -/** - * To construct a new CacheExpiration instance you must provide at least one of the config properties. - */ -interface ICacheExpirationConstructor { - new (cacheName: string, config: Partial): CacheExpiration; +interface CacheExpirationConstructor { + + /** + * 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 {Partial} config + * @return {CacheExpiration} + */ + new (cacheName: string, config: Partial): CacheExpiration; } /** * ===== Strategies ===== */ -interface ICacheStrategyHandleOptions { +interface CacheStrategyHandleOptions { + /** + * The request to run this strategy for. + */ + request: Request; + + /** + * The event that triggered the request. + */ event: FetchEvent; } -interface ICacheStrategyMakeRequestOptions { +interface CacheStrategyMakeRequestOptions { + /** + * Either a [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request} object, + * or a string URL, corresponding to the request to be made. + */ request: Request|string; + + /** + * If provided, `event.waitUntil()` will + * be called automatically to extend the service worker's lifetime. + */ event?: FetchEvent; } declare class CacheStrategy { /** * This method will perform a request strategy and follows an API that will work with the Workbox Router. - * @param {ICacheStrategyHandleOptions} input + * @param {CacheStrategyHandleOptions} input * @returns {Promise} */ - handle (input: ICacheStrategyHandleOptions): Promise; + handle (input: CacheStrategyHandleOptions): Promise; /** - * This method can be used to perform a make a standalone request outside the context of the Workbox Router. - * @param {ICacheStrategyMakeRequestOptions} input + * This method can be used to perform a make a standalone request outside the + * context of the Workbox Router. + * + * See "[Advanced Recipes](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests)" + * for more usage information. + * @param {CacheStrategyMakeRequestOptions} input * @returns {Promise} */ - makeRequest (input: ICacheStrategyMakeRequestOptions): Promise; + makeRequest (input: CacheStrategyMakeRequestOptions): Promise; } /** * ===== CacheOnly strategy ===== */ -interface ICacheOnlyOptions { +interface CacheOnlyOptions { /** * Cache name to store and retrieve requests. Defaults to cache names provided by workbox-core. */ cacheName: string; /** - * Plugins to use in conjunction with this caching strategy. + * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} + * to use in conjunction with this caching strategy. */ plugins: Plugin[]; + + /** + * [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) + */ + matchOptions: CacheQueryOptions; } /** - * An implementation of a cache-only request strategy. - * This class is useful if you want to take advantage of any Workbox plugins. + * An implementation of a + * [cache-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only} + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}. + * + * If there is no cache match, this will throw a `WorkboxError` exception. */ declare class CacheOnly extends CacheStrategy { } -/** - * Instantiates a new CacheOnly strategy - */ -interface ICacheOnlyConstructor { - new (options?: Partial): CacheOnly; +interface CacheOnlyConstructor { + + /** + * Instantiates a new CacheOnly strategy + * @param {Partial} options + * @return {CacheOnly} + */ + new (options?: Partial): CacheOnly; } /** * ===== CacheFirst strategy ===== */ -interface ICacheFirstOptions extends ICacheOnlyOptions { +interface CacheFirstOptions extends CacheOnlyOptions { /** - * Values passed along to the init of all fetch() requests made by this strategy. + * Values passed along to the + * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) */ fetchOptions: RequestInit; } /** - * An implementation of a cache-first 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. + * An implementation of a [cache-first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-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. */ declare class CacheFirst extends CacheStrategy { } -/** - * Instantiates a new CacheFirst strategy - */ -interface ICacheFirstConstructor { - new (options?: Partial): CacheFirst; +interface CacheFirstConstructor { + /** + * Instantiates a new CacheFirst strategy + * @param {Partial} options + * @return {CacheFirst} + */ + new (options?: Partial): CacheFirst; } /** * ===== NetworkOnly strategy ===== */ -interface INetworkOnlyOptions extends ICacheFirstOptions { +interface NetworkOnlyOptions extends CacheFirstOptions { } /** - * An implementation of a network-only request strategy. - * This class is useful if you want to take advantage of any Workbox plugins. + * An implementation of a + * [network-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-only} + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}. + * + * If the network request fails, this will throw a `WorkboxError` exception. */ declare class NetworkOnly extends CacheStrategy { } -/** - * Instantiates a new NetworkOnly strategy - */ -interface INetworkOnlyConstructor { - new (options?: Partial): NetworkOnly; +interface NetworkOnlyConstructor { + /** + * Instantiates a new NetworkOnly strategy + * @param {Partial} options + * @return {NetworkOnly} + */ + new (options?: Partial): NetworkOnly; } /** * ===== NetworkFirst strategy ===== */ -interface INetworkFirstOptions extends ICacheFirstOptions { +interface NetworkFirstOptions extends CacheFirstOptions { + /** + * If set, any network requests + * that fail to respond within the timeout will fallback to the cache. + */ networkTimeoutSeconds: number; } /** - * An implementation of a network first request strategy. - * By default, this strategy will cache responses with a 200 status code as well as opaque responses. - * Opaque responses are are cross-origin requests where the response doesn't support CORS. + * An implementation of a + * [network first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-falling-back-to-cache} + * request strategy. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}. + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS]{@link https://enable-cors.org/}. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. */ declare class NetworkFirst extends CacheStrategy { } -/** - * Instantiates a new NetworkFirst strategy - */ -interface INetworkFirstConstructor { - new (options?: Partial): NetworkFirst; +interface NetworkFirstConstructor { + /** + * Instantiates a new NetworkFirst strategy + * @param {Partial} options + * @return {NetworkFirst} + */ + new (options?: Partial): NetworkFirst; } /** * ===== StaleWhileRevalidate strategy ===== */ -interface IStaleWhileRevalidateOptions extends ICacheFirstOptions { +interface StaleWhileRevalidateOptions extends CacheFirstOptions { } /** - * An implementation of a stale-while-revalidate request strategy. + * An implementation of a + * [stale-while-revalidate]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#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. - * Opaque responses are are cross-origin requests where the response doesn't support CORS. + * 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]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}. + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS]{@link https://enable-cors.org/}. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. */ declare class StaleWhileRevalidate extends CacheStrategy { } -/** - * Instantiates a new StaleWhileRevalidate strategy - */ -interface IStaleWhileRevalidateConstructor { - new (options?: Partial): StaleWhileRevalidate; +interface StaleWhileRevalidateConstructor { + /** + * Instantiates a new StaleWhileRevalidate strategy + * @param {Partial} options + * @return {StaleWhileRevalidate} + */ + new (options?: Partial): StaleWhileRevalidate; } /** * ===== MatchCallback ===== */ -interface IMatchContext extends IURLContext { +interface MatchContext extends URLContext { /** * The service workers' fetch event. */ @@ -289,13 +445,13 @@ interface IMatchContext extends IURLContext { /** * To signify a match, return anything other than null. Return null if the route shouldn't match. */ -type MatchCallback = (context: IMatchContext) => {}|null; +type MatchCallback = (context: MatchContext) => {}|null; /** * ===== HandlerCallback ===== */ -interface IHandlerContext extends IMatchContext { +interface HandlerContext extends MatchContext { /** * Parameters returned by the Route's match callback function. This will be undefined if nothing was returned. */ @@ -306,21 +462,16 @@ interface IHandlerContext extends IMatchContext { * The "handler" callback is called when a service worker's fetch event has been matched by a Route. This callback should return a Promise that resolves with a Response. * If a value is returned by the match callback it will be passed in as the context.params argument. */ -type HandlerCallback = (context: IHandlerContext) => Promise; +type HandlerCallback = (context: HandlerContext) => Promise; /** * ===== NavigationRoute ===== */ -interface IHandlerOptions { - url: string; - event: FetchEvent; - params: URLSearchParams; -} - -interface INavigationRouteOptions { +interface NavigationRouteOptions { /** - * If any of these patterns match, the route will not handle the request (even if a whitelist RegExp matches). + * If any of these patterns match, + * the route will not handle the request (even if a whitelist RegExp matches). */ blacklist: RegExp[]; @@ -332,19 +483,35 @@ interface INavigationRouteOptions { } /** - * NavigationRoute makes it easy to create a Route that matches for browser navigation requests. - * It will only match incoming Requests whose 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 blacklist and whitelist parameters. + * NavigationRoute makes it easy to create a 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 + * [`mode`]{@link https://fetch.spec.whatwg.org/#concept-request-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 `blacklist` and `whitelist` parameters. */ declare class NavigationRoute { } -/** - * If both blacklist and whitelist are provided, the blacklist will take precedence and the request will not match this route. - * The regular expressions in whitelist and blacklist are matched against the concatenated pathname and search portions of the requested URL. - */ -interface INavigationRouteConstructor { - new (handler: HandlerCallback, options: Partial): NavigationRoute; +interface NavigationRouteConstructor { + /** + * If both `blacklist` and `whitelist` are provided, the `blacklist` will + * take precedence and the request will not match this route. + * + * The regular expressions in `whitelist` and `blacklist` + * 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. + + * @param {HandlerCallback} handler + * @param {Partial} options + * @return {NavigationRoute} + */ + new (handler: HandlerCallback, options: Partial): NavigationRoute; } /** @@ -357,28 +524,36 @@ interface INavigationRouteConstructor { declare class BroadcastUpdatePlugin { } -/** - * Construct a new instance with a specific channelName to broadcast messages on - */ -interface IBroadcastUpdatePluginConstructor { - new (channelName: string, options?: Partial): BroadcastUpdatePlugin; +interface BroadcastUpdatePluginConstructor { + /** + * Construct a BroadcastCacheUpdate instance with the passed options and + * calls its `notifyIfUpdated()` method whenever the plugin's + * `cacheDidUpdate` callback is invoked. + * @param {Partial} options + * @return {BroadcastUpdatePlugin} + */ + new (options?: Partial): BroadcastUpdatePlugin; } /** - * ===== BroadcastUpdatePlugin ===== + * ===== RangeRequestsPlugin ===== */ /** - * 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. + * 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. */ declare class RangeRequestsPlugin { } -/** - * Instantiates a new RangeRequestsPlugin - */ -interface IRangeRequestsPluginConstructor { +interface RangeRequestsPluginConstructor { + /** + * Instantiates a new RangeRequestsPlugin + * @return {RangeRequestsPlugin} + */ new (): RangeRequestsPlugin; } @@ -387,18 +562,24 @@ interface IRangeRequestsPluginConstructor { */ /** - * 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. + * 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. */ declare class CacheableResponsePlugin { } -/** - * To construct a new cacheable response Plugin 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. - */ -interface ICacheableResponsePluginConstructor { - new (config: Partial): CacheableResponsePlugin; +interface CacheableResponsePluginConstructor { + /** + * To construct a new cacheable response Plugin 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 {Partial} config + * @return {CacheableResponsePlugin} + */ + new (config: Partial): CacheableResponsePlugin; } /** @@ -406,16 +587,18 @@ interface ICacheableResponsePluginConstructor { */ /** - * A class implementing the fetchDidFail lifecycle callback. - * This makes it easier to add failed requests to a background sync Queue. + * A class implementing the `fetchDidFail` lifecycle callback. This makes it + * easier to add failed requests to a background sync Queue. */ declare class BackgroundSyncPlugin { } -/** - * Instantiates a new BackgroundSyncPlugin - */ -interface IBackgroundSyncPluginConstructor { +interface BackgroundSyncPluginConstructor { + /** + * Instantiates a new BackgroundSyncPlugin + * @param {*} queueArgs - Args to forward to the composed Queue instance. + * @return {BackgroundSyncPlugin} + */ new (...queueArgs: any[]): BackgroundSyncPlugin; } @@ -423,22 +606,59 @@ interface IBackgroundSyncPluginConstructor { * ===== ExpirationPlugin ===== */ -/** - * This plugin can be used in the Workbox API's to regularly enforce a limit on the age and / or the number of cached requests. - * Whenever a cached request is used or updated, this plugin will look at the used Cache and remove any old or extra requests. - * When using maxAgeSeconds, requests may be used once after expiring because the expiration clean up will not have occurred - * until after the cached request has been used. If the request has a "Date" header, then a light weight expiration check is - * performed and the request will not be used immediately. - * When using maxEntries, the last request to be used will be the request that is removed from the Cache. - */ -declare class ExpirationPlugin { +interface CacheExpirationPluginOptions extends CacheExpirationOptions { + /** + * Whether to opt this cache in to automatic deletion + * if the available storage quota has been exceeded. + */ + purgeOnQuotaError: boolean; } /** - * Instantiates a new ExpirationPlugin + * This plugin can be used in the Workbox APIs to regularly enforce a + * limit on the age and / or the number of cached requests. + * + * Whenever a cached request is used or updated, this plugin will look + * at the used Cache and remove any old or extra requests. + * + * When using `maxAgeSeconds`, requests may be used *once* after expiring + * because the expiration clean up will not have occurred until *after* the + * cached request has been used. If the request has a "Date" header, then + * a light weight expiration check is performed and the request will not be + * used immediately. + * + * When using `maxEntries`, the last request to be used will be the request + * that is removed from the Cache. */ -interface IExpirationPluginConstructor { - new (config: Partial): ExpirationPlugin; +declare class ExpirationPlugin { + + /** + * 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. + * @return {Promise} + */ + deleteCacheAndMetadata(): Promise; +} + +interface ExpirationPluginConstructor { + /** + * Instantiates a new ExpirationPlugin + * @param {Partial} config + * @return {ExpirationPlugin} + */ + new (config: Partial): ExpirationPlugin; } /** @@ -451,48 +671,48 @@ type Plugin = BroadcastUpdatePlugin|RangeRequestsPlugin|CacheableResponsePlugin| * ===== BackgroundSync ===== */ -interface IStorableRequestOptions { +interface StorableRequestOptions { url: string; /** * See: https://fetch.spec.whatwg.org/#requestinit */ requestInit: RequestInit; - - /** - * The time the request was created, defaulting to the current time if not specified. - */ - timestamp: number; } /** * A class to make it easier to serialize and de-serialize requests so they can be stored in IndexedDB. + * @private */ declare class StorableRequest { - readonly timestamp: number; - toObject (): IStorableRequestOptions; + /** + * Returns a deep clone of the instances `_requestData` object. + * @private + * @return {StorableRequestOptions} + */ + toObject (): StorableRequestOptions; + /** + * Converts this instance to a Request. + * @private + * @return {Request} + */ toRequest (): Request; + /** + * Creates and returns a deep clone of the instance. + * @private + * @return {StorableRequest} + */ clone (): StorableRequest; } -/** - * Accepts a URL and RequestInit dictionary that can be used to create a - * new Request object. A timestamp is also generated so consumers can - * reference when the object was created. - */ -interface IStorableRequestConstructor { - new (options: IStorableRequestOptions): StorableRequest; - fromRequest (request: Request): StorableRequest; -} - /** * ===== PrecacheController ===== */ -interface ICleanupResult { +interface CleanupResult { /** * List of URLs that were deleted from the precache cache. */ @@ -503,18 +723,11 @@ interface ICleanupResult { deletedRevisionDetails: string[]; } -interface IActivateOptions { +interface InstallOptions { /** - * Plugins to be used for fetching and caching during install. + * The install event (if needed). */ - plugins: Plugin[]; -} - -interface IInstallOptions { - /** - * Suppress warning messages. - */ - suppressWarnings: boolean; + event: Event; /** * Plugins to be used for fetching and caching during install. @@ -522,21 +735,21 @@ interface IInstallOptions { plugins: Plugin[]; } -interface IPrecacheEntry { +interface PrecacheEntry { url: string; revision: string; } -interface IInstallResult { +interface InstallResult { /** * List of entries supplied for precaching that were precached. */ - updatedEntries: (string|IPrecacheEntry)[]; + updatedEntries: (string|PrecacheEntry)[]; /** * List of entries supplied for precaching that were already precached. */ - notUpdatedEntries: (string|IPrecacheEntry)[]; + notUpdatedEntries: (string|PrecacheEntry)[]; } /** @@ -544,36 +757,60 @@ interface IInstallResult { */ declare class PrecacheController { /** - * Takes the current set of temporary files and moves them to the final cache, deleting the temporary cache once copying is complete. - * @param {IActivateOptions} options - * @returns {Promise} Resolves with an object containing details of the deleted cache requests and precache revision details. + * Deletes assets that are no longer present in the current precache manifest. + * Call this method from the service worker activate event. + * @returns {Promise} */ - activate (options: Partial): Promise; + activate (): Promise; /** - * This method will add items to the precache list, removing duplicates and ensuring the information is valid. - * @param {(string | IPrecacheEntry)[]} entries - Array of entries to precache. + * This method will add items to the precache list, removing duplicates + * and ensuring the information is valid. + * @param {(string | PrecacheEntry)[]} entries - Array of entries to precache. */ - addToCacheList (entries: (string|IPrecacheEntry)[]): void; + addToCacheList (entries: (string|PrecacheEntry)[]): void; /** - * Returns an array of fully qualified URL's that will be precached. + * Returns a mapping of a precached URL to the corresponding cache key, taking + * into account the revision information for the URL. + * + * @returns {Map} A URL to cache key mapping. + */ + getURLsToCacheKeys(): Map; + + /** + * 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. + * @returns {string} The versioned URL that corresponds to a cache key + * for the original URL, or undefined if that URL isn't precached. + */ + getCacheKeyForURL(url: string): string; + + /** + * Returns a list of all the URLs that have been precached by the current + * service worker. * @returns {string[]} An array of URLs. */ getCachedUrls (): string[]; /** - * Call this method from a service work install event to start precaching assets. - * @param {Partial} options - * @returns {Promise} + * Precaches new and updated assets. Call this method from the service worker + * install event. + * @param {Partial} options + * @returns {Promise} */ - install (options?: Partial): Promise; + install (options?: Partial): Promise; } -/** - * Create a new PrecacheController. - */ -interface IPrecacheControllerConstructor { +interface PrecacheControllerConstructor { + /** + * Create a new PrecacheController. + * @param {string} cacheName - An optional name for the cache, to override the default precache name. + * @return {PrecacheController} + */ new (cacheName?: string): PrecacheController; } @@ -581,71 +818,113 @@ interface IPrecacheControllerConstructor { * ===== Queue ===== */ -interface IQueueCallback { - /** - * Invoked immediately before the request is stored to IndexedDB. Use this callback to modify request data at store time. - * @param {StorableRequest} request - */ - requestWillEnqueue (request: StorableRequest): void; - /** - * Invoked immediately before the request is re-fetched. Use this callback to modify request data at fetch time. - * @param {StorableRequest} request - */ - requestWillReplay (request: StorableRequest): void; +interface QueueOptions { /** - * Invoked after all requests in the queue have successfully replayed. - * @param {StorableRequest[]} requests + * 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. */ - queueDidReplay (requests: StorableRequest[]): void; -} + onSync: (queue: Queue) => void; -interface IQueueOptions { /** - * 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. + * 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. */ maxRetentionTime: number; +} + +interface QueueEntry { /** - * Callbacks to observe the lifecycle of queued requests. Use these to respond to or modify the requests during the replay process. + * The request to store in the queue. */ - callbacks: Partial; + request: Request; + + /** + * 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. + */ + metadata: any; + + /** + * 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. + */ + timestamp: number; } /** - * 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. + * 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. */ declare class Queue { readonly name: string; /** - * Stores the passed request into IndexedDB. The database used is workbox-background-sync and the object store name is the same as the name this instance was created with (to guarantee it's unique). - * @param {Request} request - The request object to store. + * Stores the passed request in IndexedDB (with its timestamp and any + * metadata) at the end of the queue. + * @param {QueueEntry} entry * @returns {Promise} */ - addRequest (request: Request): Promise; + pushRequest (entry: QueueEntry): Promise; /** - * Retrieves all stored requests in IndexedDB and retries them. If the queue contained requests that - * were successfully replayed, the queueDidReplay callback is invoked (which implies the queue is now empty). - * If any of the requests fail, a new sync registration is created to retry again later. + * Stores the passed request in IndexedDB (with its timestamp and any + * metadata) at the beginning of the queue. + * @param {QueueEntry} entry + * @return {Promise} + */ + unshiftRequest (entry: QueueEntry): Promise; + + /** + * 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} + */ + popRequest (): Promise; + + /** + * 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} + */ + shiftRequest (): Promise; + + /** + * 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). * @returns {Promise} */ replayRequests (): Promise; + + /** + * Registers a sync event with a tag unique to this instance. + * @return {Promise} + */ + registerSync (): Promise; } /** * Creates an instance of Queue with the given options */ -interface IQueueConstructor { +interface QueueConstructor { /** - * @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 {Partial} options - * @returns {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 {Partial} options + * @return {Queue} */ - new (name: string, options?: Partial): Queue; + new (name: string, options?: Partial): Queue; } /** @@ -653,23 +932,23 @@ interface IQueueConstructor { */ /** - * 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. + * 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`. */ declare class Route { } -/** - * Constructor for Route class. - */ -interface IRouteConstructor { + +interface RouteConstructor { + /** - * - * @param {MatchCallback} match - A callback function that determines whether the route matches a given fetch event by returning a non-falsy value. + * Constructor for Route class. + * @param {MatchCallback} match - A callback function that determines whether the route matches a given `fetch` event by returning a non-falsy value. * @param {HandlerCallback} handler - A callback function that returns a Promise resolving to a Response. - * @param {string} [method] - The HTTP method to match the Route against. + * @param {string} [method="GET"] - The HTTP method to match the Route * @returns {Route} */ new (match: MatchCallback, handler: HandlerCallback, method?: string): Route; @@ -681,15 +960,18 @@ interface IRouteConstructor { /** * RegExpRoute makes it easy to create a regular expression based 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. + * + * 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. + * + * [See the module docs for info.]{@link https://developers.google.com/web/tools/workbox/modules/workbox-routing} */ declare class RegExpRoute extends Route { } -/** - * If the regular expression contains capture groups, the captured values will be passed to the handler's params argument. - */ -interface IRegExpRouteConstructor { + +interface RegExpRouteConstructor { /** * * @param {RegExp} regExp - The regular expression to match against URLs. @@ -697,6 +979,17 @@ interface IRegExpRouteConstructor { * @param {string} [method] - The HTTP method to match the Route against. * @returns {RegExpRoute} */ + + /** + * 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 handler's `params` + * argument. + * @param {RegExp} regExp - The regular expression to match against URLs. + * @param {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. + * @return {RegExpRoute} + */ new (regExp: RegExp, handler: HandlerCallback, method?: string): RegExpRoute; } @@ -704,38 +997,130 @@ interface IRegExpRouteConstructor { * ===== Router ===== */ +interface HandleRequestOptions { + /** + * The request to handle (this is usually from a fetch event, but it does not have to be). + */ + request: Request; + + /** + * The event that triggered the request, if applicable. + */ + event?: FetchEvent; +} + +interface FindMatchingRouteOptions { + url: URL; + + /** + * The request to match. + */ + request: Request; + + /** + * The corresponding event (unless N/A). + */ + event?: FetchEvent; +} + +interface FindMatchingRouteResult { + route: Route; + params: URLSearchParams; +} + /** - * The Router can be used to process a FetchEvent through one or more Routes responding with a Request 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. + * The Router can be used to process a FetchEvent through one or more + * Routes responding with a Request 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. */ declare class Router { - /** - * Apply the routing rules to a FetchEvent object to get a Response from an appropriate Route's handler. - * @param {FetchEvent} event - The event from a service worker's 'fetch' event listener. - * @returns {Promise?} A promise is returned if a registered route can handle the FetchEvent's request. If there is no matching route and there's no defaultHandler, undefined is returned. - */ - handleRequest (event: FetchEvent): Promise|undefined; /** - * Registers a route with the router. - * @param {Route} route + * A `Map` of HTTP method name ('GET', etc.) to an array of all the corresponding `Route` + * instances that are registered. + * @type {Map} */ - registerRoute (route: Route): void; + readonly routes: Map; /** - * If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response. + * Adds a fetch event listener to respond to events when a route matches + * the event's request. + */ + addFetchListener(): void; + + /** + * 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 (): void; + + /** + * Apply the routing rules to a FetchEvent object to get a Response from an + * appropriate Route's handler. + * @param {HandleRequestOptions} options + * @returns {Promise?} 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 (options: HandleRequestOptions): Promise|undefined; + + /** + * 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 {FindMatchingRouteOptions} options + * @return {Partial} + */ + findMatchingRoute (options: FindMatchingRouteOptions): Partial + + /** + * 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 {HandlerCallback} handler - * @param {workbox.routing.Route~handlerCallback} handler A callback function that returns a Promise resulting in a Response. + */ + setDefaultHandler (handler: HandlerCallback): void; + + /** + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. */ setCatchHandler (handler: HandlerCallback): void; /** - * 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 {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + * Registers a route with the router. + * @param {Route} route - The route to register. */ - setDefaultHandler (handler: HandlerCallback): void; + registerRoute (route: Route): void; /** * Unregisters a route with the router. @@ -744,10 +1129,11 @@ declare class Router { unregisterRoute (route: Route): void; } -/** - * Initializes a new Router. - */ -interface IRouterConstructor { +interface RouterConstructor { + /** + * Initializes a new Router. + * @return {Router} + */ new (): Router; } @@ -755,44 +1141,11 @@ interface IRouterConstructor { * ===== CoreNamespace ===== */ -interface ICacheNames { +interface CacheNames { precache: string; runtime: string; - googleAnalytics: string; -} - -interface ILogLevel { - /** - * Prints all logs from Workbox. Useful for debugging. - */ - debug: 0; - - /** - * Prints console log, warn, error and groups. Default for debug builds. - */ - log: 1; - - /** - * Prints console warn, error and groups. Default for non-debug builds. - */ - warn: 2; - - /** - * Print console error and groups. - */ - error: 3; - - /** - * Force no logging from Workbox. - */ - silent: 4; -} - -interface ICacheNameDetails { prefix: string; suffix: string; - precache: string; - runtime: string; googleAnalytics: string; } @@ -801,39 +1154,49 @@ interface ICacheNameDetails { */ declare class CoreNamespace { /** - * 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. + * 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. */ - static readonly cacheNames: ICacheNames; + static readonly cacheNames: CacheNames; /** - * The available log levels in Workbox: debug, log, warn, error and silent. + * Claim any currently available clients once the service worker + * becomes active. This is normally used in conjunction with `skipWaiting()`. */ - static readonly LOG_LEVELS: ILogLevel; + static clientsClaim (): void; /** - * Get the current log level. + * Adds a function to the set of callbacks that will be executed when there's + * a quota error. + * @param {() => *} callback */ - static readonly logLevel: ILogLevel[keyof ILogLevel]; + static registerQuotaErrorCallback (callback: () => any): void; /** - * You can alter the default cache names used by the Workbox modules by changing the cache name details. - * Cache names are generated as --. - * @param {Partial} details + * Modifies the default cache names used by the Workbox packages. + * Cache names are generated as `--`. + * @param {Partial} details */ - static setCacheNameDetails (details: Partial): void; + static setCacheNameDetails (details: Partial): void; /** - * Set the current log level passing in one of the values from LOG_LEVELS. - * @param {number} logLevel - The new log level to use. + * Force a service worker to become active, instead of waiting. This is + * normally used in conjunction with `clientsClaim()`. */ - static setLogLevel (logLevel: ILogLevel[keyof ILogLevel]): void; + static skipWaiting (): void; } /** * ===== PrecachingNamespace ===== */ -interface IURLContext { +interface URLContext { /** * The request's URL. */ @@ -843,14 +1206,15 @@ interface IURLContext { /** * The "urlManipulation" callback can be used to determine if there are any additional permutations of a URL that should be used to check against the available precached files. * For example, Workbox supports checking for '/index.html' when the URL '/' is provided. This callback allows additional, custom checks. - * @param {IURLContext} context + * @param {URLContext} context * @returns {URL[]} To add additional urls to test, return an Array of URL's. Please note that these should not be Strings, but URL objects. */ -type UrlManipulation = (context: IURLContext) => URL[]; +type UrlManipulation = (context: URLContext) => URL[]; -interface IRouteOptions { +interface RouteOptions { /** - * The directoryIndex will check cache entries for a URLs ending with '/' to see if there is a hit when appending the directoryIndex value. + * The `directoryIndex` will check cache entries for a URLs ending with '/' to see if there is a hit when + * appending the `directoryIndex` value. */ directoryIndex: string|null; @@ -860,12 +1224,13 @@ interface IRouteOptions { ignoreUrlParametersMatching: RegExp[]; /** - * The cleanUrls option will check the cache for the URL with a .html added to the end of the end. + * The `cleanURLs` option will check the cache for the URL with a `.html` added to the end of the end. */ cleanUrls: boolean; /** - * This is a function that should take a URL and return an array of alternative URL's that should be checked for precache matches. + * This is a function that should take a URL and return an array of + * alternative URL's that should be checked for precache matches. */ urlManipulation: UrlManipulation; } @@ -875,10 +1240,6 @@ interface IRouteOptions { * If you require finer grained control, you can use the PrecacheController to determine when performed. */ declare class PrecachingNamespace { - /** - * Performs efficient precaching of assets. - */ - static readonly PrecacheController: IPrecacheControllerConstructor; /** * Add plugins to precaching. @@ -887,122 +1248,192 @@ declare class PrecachingNamespace { static addPlugins (newPlugins: Plugin[]): void; /** - * Add a fetch listener to the service worker that will respond to network 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 {Partial} route + * 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 {Partial} [route] */ - static addRoute (route: Partial): void; + static addRoute (route?: Partial): void; /** - * Add items to the precache list, removing any duplicates and store the files in the "precache cache" when the service worker installs. + * Adds an `activate` event listener which will clean up incompatible + * precaches that were created by older versions of Workbox. + */ + static cleanupOutdatedCaches (): void; + + /** + * 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. + * @returns {string} The cache key that corresponds to that URL. + */ + static getCacheKeyForURL (url: string): string; + + /** + * Adds items to the precache list, removing any duplicates and + * stores the files in the + * "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 addRoute(). - * If you have a single array of files to precache, you can just call precacheAndRoute(). - * @param {(string | IPrecacheEntry)[]} entries + * + * 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 + * addRoute(). + * + * If you have a single array of files to precache, you can just call + * precacheAndRoute(). + * @param {(string | PrecacheEntry)[]} entries - Array of entries to precache. */ - static precache (entries: (string|IPrecacheEntry)[]): void; + static precache (entries: (string|PrecacheEntry)[]): void; /** - * 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 precache() and addRoute() in a single call. - * @param {(string | IPrecacheEntry)[]} entries - Array of entries to precache. - * @param {Partial} [route] - see addRoute() options + * 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 precache() and + * addRoute() in a single call. + * @param {(string | PrecacheEntry)[]} entries - Array of entries to precache. + * @param {Partial} [options] - see addRoute() options */ - static precacheAndRoute (entries: (string|IPrecacheEntry)[], route?: Partial): void; + static precacheAndRoute (entries: (string|PrecacheEntry)[], options?: Partial): void; /** - * Warnings will be logged if any of the precached assets are entered without a revision property. - * This is extremely dangerous if the URL's aren't revisioned. - * However, the warnings can be supressed with this method. - * @param {boolean} suppress + * Performs efficient precaching of assets. */ - static suppressWarnings (suppress: boolean): void; + static readonly PrecacheController: PrecacheControllerConstructor; } /** * ===== RoutingNamespace ===== */ -interface IRegisterNavigationRouteOptions extends INavigationRouteOptions { +interface RegisterNavigationRouteOptions extends NavigationRouteOptions { + /** + * Cache name to store and retrieve requests. Defaults to precache cache name provided by `cacheNames`. + */ cacheName: string; } declare class RoutingNamespace { /** - * NavigationRoute makes it easy to create a Route that matches for browser navigation requests. - * It will only match incoming Requests whose 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 blacklist and whitelist parameters. + * NavigationRoute makes it easy to create a 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 + * [`mode`]{@link https://fetch.spec.whatwg.org/#concept-request-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 `blacklist` and `whitelist` parameters. */ - static readonly NavigationRoute: INavigationRouteConstructor; + static readonly NavigationRoute: NavigationRouteConstructor; /** - * RegExpRoute makes it easy to create a regular expression based 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. + * RegExpRoute makes it easy to create a regular expression based + * 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. + * + * [See the module docs for info.]{@link https://developers.google.com/web/tools/workbox/modules/workbox-routing} */ - static readonly RegExpRoute: IRegExpRouteConstructor; + static readonly RegExpRoute: RegExpRouteConstructor; /** - * 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. - */ - static readonly Route: IRouteConstructor; - - /** - * The Router can be used to process a FetchEvent through one or more Routes responding with a Request 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. - */ - static readonly Router: IRouterConstructor; - - /** - * Register a route that will return a precached file for a navigation request. This is useful for the application shell pattern. - * This method will generate a NavigationRoute and call Router.registerRoute(). - * @param {string} cachedAssetUrl - * @param {Partial} [options] + * Registers a route that will return a precached file for a navigation + * request. This is useful for the + * [application shell pattern]{@link https://developers.google.com/web/fundamentals/architecture/app-shell}. + * + * When determining the URL of the precached HTML document, you will likely need + * to call `workbox.precaching.getCacheKeyForURL(originalUrl)`, to account for + * the fact that Workbox's precaching naming conventions often results in URL + * cache keys that contain extra revisioning info. + * + * This method will generate a NavigationRoute and call Router.registerRoute() on a singleton Router instance. + * @param {string} cachedAssetUrl - The cache key to use for the HTML file. + * @param {Partial} [options] * @returns {NavigationRoute} Returns the generated Route. */ - static registerNavigationRoute (cachedAssetUrl: string, options?: Partial): NavigationRoute; + static registerNavigationRoute (cachedAssetUrl: string, options?: Partial): NavigationRoute; /** - * Easily register a RegExp, string, or function with a caching strategy to the Router. - * This method will generate a Route for you if needed and call Router.registerRoute(). - * @param {string | RegExp | MatchCallback | Route} capture - If the capture param is a Route, all other arguments will be ignored. + * 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 Router.registerRoute(). + * @param {string | RegExp | MatchCallback | Route} capture - If the capture param is a `Route`, all other arguments will be ignored. * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. - * @param {string} method - The HTTP method to match the Route against. - * @returns {Route} The generated Route(Useful for unregistering). + * @param {string} [method="GET"] - The HTTP method to match the Route against. + * @returns {Route} The generated `Route` (Useful for unregistering). */ static registerRoute (capture: string|RegExp|MatchCallback|Route, handler: HandlerCallback, method?: string): Route; /** - * If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response. - * @param {IHandlerOptions} handler - A callback function that returns a Promise resulting in a Response. - * @returns {Promise} + * 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`. */ - static setCatchHandler (handler: IHandlerOptions): Promise; + static readonly Route: RouteConstructor; /** - * 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 {IHandlerOptions} handler - A callback function that returns a Promise resulting in a Response. - * @returns {Promise} + * The Router can be used to process a FetchEvent through one or more + * Routes responding with a Request 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. */ - static setDefaultHandler (handler: IHandlerOptions): Promise; + static readonly Router: RouterConstructor; /** - * Unregisters a route with the router. - * @param {Route} route - The route to unregister + * If a Route throws an error while handling a request, this `handler` + * will be called and given a chance to provide a response. + * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. */ - static unregisterRoute (route: Route): void; + static setCatchHandler (handler: HandlerCallback): void; + + /** + * 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 {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + */ + static setDefaultHandler (handler: HandlerCallback): Promise; } /** * ===== StrategiesNamespace ===== */ -interface IStrategyOptions { +interface StrategyOptions { /** * Name of cache to use for caching (both lookup and updating). */ @@ -1011,7 +1442,7 @@ interface IStrategyOptions { /** * Defining this object will add a cache expiration plugins to this strategy. */ - cacheExpiration: Partial; + cacheExpiration: Partial; /** * The Plugins to use along with the Strategy @@ -1024,73 +1455,116 @@ interface IStrategyOptions { */ declare class StrategiesNamespace { /** - * An implementation of a cache-first 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. + * An implementation of a [cache-first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-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. */ - static readonly CacheFirst: ICacheFirstConstructor; + static readonly CacheFirst: CacheFirstConstructor; /** - * An implementation of a cache-only request strategy. - * This class is useful if you want to take advantage of any Workbox plugins. + * An implementation of a + * [cache-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only} + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}. + * + * If there is no cache match, this will throw a `WorkboxError` exception. */ - static readonly CacheOnly: ICacheOnlyConstructor; + static readonly CacheOnly: CacheOnlyConstructor; /** - * An implementation of a network first request strategy. - * By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are are cross-origin requests where the response doesn't support CORS. + * An implementation of a + * [network first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-falling-back-to-cache} + * request strategy. + * + * By default, this strategy will cache responses with a 200 status code as + * well as [opaque responses]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}. + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS]{@link https://enable-cors.org/}. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. */ - static readonly NetworkFirst: INetworkFirstConstructor; + static readonly NetworkFirst: NetworkFirstConstructor; /** - * An implementation of a network-only request strategy. - * This class is useful if you want to take advantage of any Workbox plugins. + * An implementation of a + * [network-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-only} + * request strategy. + * + * This class is useful if you want to take advantage of any + * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}. + * + * If the network request fails, this will throw a `WorkboxError` exception. */ - static readonly NetworkOnly: INetworkOnlyConstructor; + static readonly NetworkOnly: NetworkOnlyConstructor; /** - * An implementation of a stale-while-revalidate request strategy. + * An implementation of a + * [stale-while-revalidate]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#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. - * Opaque responses are are cross-origin requests where the response doesn't support CORS. + * 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]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}. + * Opaque responses are are cross-origin requests where the response doesn't + * support [CORS]{@link https://enable-cors.org/}. + * + * If the network request fails, and there is no cache match, this will throw + * a `WorkboxError` exception. */ - static readonly StaleWhileRevalidate: IStaleWhileRevalidateConstructor; + static readonly StaleWhileRevalidate: StaleWhileRevalidateConstructor; /** * Instantiates a new CacheFirst strategy - * @param {Partial} [options] + * @deprecated use new workbox.strategies.CacheFirst() syntax + * @param {Partial} [options] * @returns {HandlerCallback} */ - static cacheFirst (options?: Partial): HandlerCallback; + static cacheFirst (options?: Partial): HandlerCallback; /** * Instantiates a new CacheOnly strategy - * @param {Partial} [options] + * @deprecated use new workbox.strategies.CacheOnly() syntax + * @param {Partial} [options] * @returns {HandlerCallback} */ - static cacheOnly (options?: Partial): HandlerCallback; + static cacheOnly (options?: Partial): HandlerCallback; /** * Instantiates a new NetworkFirst strategy - * @param {Partial} [options] + * @deprecated use new workbox.strategies.NetworkFirst() syntax + * @param {Partial} [options] * @returns {HandlerCallback} */ - static networkFirst (options?: Partial): HandlerCallback; + static networkFirst (options?: Partial): HandlerCallback; /** * Instantiates a new NetworkOnly strategy - * @param {Partial} [options] + * @deprecated use new workbox.strategies.NetworkOnly() syntax + * @param {Partial} [options] * @returns {HandlerCallback} */ - static networkOnly (options?: Partial): HandlerCallback; + static networkOnly (options?: Partial): HandlerCallback; /** * Instantiates a new StaleWhileRevalidate strategy - * @param {Partial} [options] + * @deprecated use new workbox.strategies.StaleWhileRevalidate() syntax + * @param {Partial} [options] * @returns {StaleWhileRevalidate} */ - static staleWhileRevalidate (options?: Partial): HandlerCallback; + static staleWhileRevalidate (options?: Partial): HandlerCallback; } /** @@ -1099,55 +1573,61 @@ declare class StrategiesNamespace { type StreamSource = Response|ReadableStream|BodyInit; -interface IConcatenateResult { +interface ConcatenateResult { done: Promise; stream: ReadableStream; } -interface IConcatenateToResponseResult { +interface ConcatenateToResponseResult { done: Promise; response: Response; } declare class StreamsNamespace { /** - * Takes multiple source Promises, each of which could resolve to a Response, a ReadableStream, or a 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()). + * 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 {Promise[]} sourcePromises - Array of Promise containing StreamSource - * @returns {IConcatenateResult} + * @returns {ConcatenateResult} */ - static concatenate (sourcePromises: Promise[]): IConcatenateResult; + static concatenate (sourcePromises: Promise[]): ConcatenateResult; /** - * Takes multiple source Promises, each of which could resolve to a Response, a ReadableStream, or a BodyInit,along with a 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()). + * 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 {Promise[]} sourcePromises - Array of Promise containing StreamSource - * @param {HeadersInit} [headersInit] - If there's no Content-Type specified, 'text/html' will be used by default. - * @returns {IConcatenateToResponseResult} + * @param {HeadersInit} [headersInit] - If there's no `Content-Type` specified, `'text/html'` will be used by default. + * @returns {ConcatenateToResponseResult} */ - static concatenateToResponse (sourcePromises: Promise[], headersInit?: HeadersInit): IConcatenateToResponseResult; + static concatenateToResponse (sourcePromises: Promise[], headersInit?: HeadersInit): ConcatenateToResponseResult; /** - * This is a utility method that determines whether the current browser supports the features required to create streamed responses. Currently, it checks if ReadableStream is available. - * @param {HeadersInit} [headersInit] - If there's no Content-Type specified, 'text/html' will be used by default. - * @returns {boolean} - true, if the current browser meets the requirements for streaming responses, and false otherwise. - */ - static createHeaders (headersInit?: HeadersInit): boolean; - - /** - * This is a utility method that determines whether the current browser supports the features required to create streamed responses. Currently, it checks if ReadableStream is available. - * @returns {boolean} - true, if the current browser meets the requirements for streaming responses, and false otherwise. + * 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. + * @returns {boolean} `true`, if the current browser meets the requirements for streaming responses, and `false` otherwise. */ static isSupported (): boolean; /** * A shortcut to create a strategy that could be dropped-in to Workbox's router. - * On browsers that do not support constructing new ReadableStreams, this strategy will automatically wait for - * all the sourceFunctions to complete, and create a final response that concatenates their values together. - * @param {HandlerCallback[]} sourceFunctions - Each function should return a 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. + * + * 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 {HandlerCallback[]} sourceFunctions - Each function should return a 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. * @returns {HandlerCallback} */ static strategy (sourceFunctions: HandlerCallback[], headersInit?: HeadersInit): HandlerCallback; @@ -1159,19 +1639,28 @@ declare class StreamsNamespace { declare class ExpirationNamespace { /** - * The CacheExpiration class allows you define an expiration and / or limit on the number of responses stored in a Cache. + * 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). */ - static readonly CacheExpiration: ICacheExpirationConstructor; + static readonly CacheExpiration: CacheExpirationConstructor; /** - * This plugin can be used in the Workbox API's to regularly enforce a limit on the age and / or the number of cached requests. - * Whenever a cached request is used or updated, this plugin will look at the used Cache and remove any old or extra requests. - * When using maxAgeSeconds, requests may be used once after expiring because the expiration clean up will not - * have occurred until after the cached request has been used. If the request has a "Date" header, then a light weight - * expiration check is performed and the request will not be used immediately. - * When using maxEntries, the last request to be used will be the request that is removed from the Cache. + * This plugin can be used in the Workbox APIs to regularly enforce a + * limit on the age and / or the number of cached requests. + * + * Whenever a cached request is used or updated, this plugin will look + * at the used Cache and remove any old or extra requests. + * + * When using `maxAgeSeconds`, requests may be used *once* after expiring + * because the expiration clean up will not have occurred until *after* the + * cached request has been used. If the request has a "Date" header, then + * a light weight expiration check is performed and the request will not be + * used immediately. + * + * When using `maxEntries`, the last request to be used will be the request + * that is removed from the Cache. */ - static readonly Plugin: IExpirationPluginConstructor; + static readonly Plugin: ExpirationPluginConstructor; } /** @@ -1180,41 +1669,75 @@ declare class ExpirationNamespace { declare class BackgroundSyncNamespace { /** - * A class implementing the fetchDidFail lifecycle callback. This makes it easier to add failed requests to a background sync Queue. + * A class implementing the `fetchDidFail` lifecycle callback. This makes it + * easier to add failed requests to a background sync Queue. */ - static readonly Plugin: IBackgroundSyncPluginConstructor; + static readonly Plugin: BackgroundSyncPluginConstructor; /** - * 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. + * 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. */ - static readonly Queue: IQueueConstructor; + static readonly Queue: QueueConstructor; } /** * ===== GoogleAnalyticsNamespace ===== */ -interface IGoogleAnalyticsInitializeOptions { +interface GoogleAnalyticsInitializeOptions { /** - * The cache name to store and retrieve analytics.js. Defaults to the cache names provided by workbox-core. + * The cache name to store and retrieve analytics.js. + * Defaults to the cache names provided by `workbox-core`. */ cacheName: string; /** - * Measurement Protocol 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. + * [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. */ - parameterOverrides: { [key: string]: string }; + parameterOverrides: Record; /** - * 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. + * 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. * @param {URLSearchParams} params */ hitFilter (params: URLSearchParams): void; } declare class GoogleAnalyticsNamespace { - static initialize (options: Partial): void; + /** + * + * @param {Partial} options + */ + static initialize (options?: Partial): void; +} + +/** + * ===== NavigationPreloadNamespace ===== + */ + +declare class NavigationPreloadNamespace { + /** + * If the browser supports Navigation Preload, then this will disable it. + */ + static disable (): void; + + /** + * 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. + */ + static enable (headerValue?: string): void; + + /** + * @return {boolean} Whether or not the current browser supports enabling navigation preload. + */ + static isSupported (): boolean; } /** @@ -1223,45 +1746,103 @@ declare class GoogleAnalyticsNamespace { declare class CacheableResponseNamespace { /** - * This class allows you to set up rules determining what status codes and/or headers need to be present in order for a Response to be considered cacheable. + * 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. */ - static readonly CacheableResponse: ICacheableResponseConstructor; + static readonly CacheableResponse: CacheableResponseConstructor; /** - * 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. + * 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. */ - static readonly Plugin: ICacheableResponsePluginConstructor; + static readonly Plugin: CacheableResponsePluginConstructor; } /** * ===== BroadcastUpdateNamespace ===== */ +interface BroadcastUpdateOptions { + /** + * The name of the cache in which the updated `Response` was stored. + */ + cacheName: string; + + /** + * The URL associated with the updated `Response`. + */ + url: string; + + /** + * The `BroadcastChannel` to use. If no channel is set or the browser doesn't support the BroadcastChannel + * api, then an attempt will be made to `postMessage` each window client. + */ + channel?: BroadcastChannel; +} + declare class BroadcastUpdateNamespace { /** - * Uses the Broadcast Channel API to notify interested parties when a cached response has been updated. - * For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked. + * Uses the [Broadcast Channel API]{@link https://developers.google.com/web/updates/2016/09/broadcastchannel} + * to notify interested parties when a cached response has been updated. + * In browsers that do not support the Broadcast Channel API, the instance + * falls back to sending the update via `postMessage()` to all window clients. + * + * For efficiency's sake, the underlying response bodies are not compared; + * only specific response headers are checked. */ - static readonly BroadcastCacheUpdate: IBroadcastCacheUpdateConstructor; + static readonly BroadcastCacheUpdate: BroadcastCacheUpdateConstructor; /** - * This plugin will automatically broadcast a message whenever a cached response is updated. + * Construct a BroadcastCacheUpdate instance with the passed options and + * calls its `notifyIfUpdated()` method whenever the plugin's + * `cacheDidUpdate` callback is invoked. */ - static readonly Plugin: IBroadcastUpdatePluginConstructor; + static readonly Plugin: BroadcastUpdatePluginConstructor; /** - * You would not normally call this method directly; - * it's called automatically by an instance of the BroadcastCacheUpdate class. - * It's exposed here for the benefit of developers who would rather not use the full BroadcastCacheUpdate implementation. - * Calling this will dispatch a message on the provided Broadcast Channel to notify interested subscribers about a - * change to a cached resource. - * The message that's posted has a formation inspired by the Flux standard action format like so: - * @param {BroadcastChannel} channel - The BroadcastChannel to use. - * @param {string} cacheName - The name of the cache in which the updated Response was stored. - * @param {string} url - The URL associated with the updated Response. - * @param {string} source - A string identifying this library as the source of the update message. + * You would not normally call this method directly; it's called automatically + * by an instance of the {@link BroadcastCacheUpdate} class. It's exposed here + * for the benefit of developers who would rather not use the full + * `BroadcastCacheUpdate` implementation. + * + * Calling this will dispatch a message on the provided + * {@link https://developers.google.com/web/updates/2016/09/broadcastchannel|Broadcast Channel} + * to notify interested subscribers about a change to a cached resource. + * + * The message that's posted has a formation inspired by the + * [Flux standard action](https://github.com/acdlite/flux-standard-action#introduction) + * format like so: + * + * ``` + * { + * type: 'CACHE_UPDATED', + * meta: 'workbox-broadcast-update', + * payload: { + * cacheName: 'the-cache-name', + * updatedURL: 'https://example.com/' + * } + * } + * ``` + * + * (Usage of [Flux](https://facebook.github.io/flux/) itself is not at + * all required.) + * @param {BroadcastUpdateOptions} options + * @returns {Promise} */ - static broadCastUpdate (channel: BroadcastChannel, cacheName: string, url: string, source: string): void; + static broadCastUpdate (options: BroadcastUpdateOptions): Promise; + + /** + * Given two `Response's`, compares several header values to see if they are + * the same or not. + * @param {Response} firstResponse + * @param {Response} secondResponse + * @param {string[]} headersToCheck + * @return {boolean} + */ + static responsesAreSame (firstResponse: Response, secondResponse: Response, headersToCheck: string[]): boolean; } /** @@ -1269,21 +1850,37 @@ declare class BroadcastUpdateNamespace { */ declare class RangeRequestsNamespace { - /** - * 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. - */ - static readonly Plugin: IRangeRequestsPluginConstructor; /** - * Given a Request and Response objects as input, this will return a promise for a new Response. + * 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. + * * @param {Request} request - A request, which should contain a Range: header. - * @param {Response} originalResponse - An original response containing the full content. - * @returns {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. + * @param {Response} originalResponse - A response. + * @returns {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. */ static createPartialResponse (request: Request, originalResponse: Response): Promise; + + /** + * 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. + */ + static readonly Plugin: RangeRequestsPluginConstructor; } /** @@ -1297,6 +1894,13 @@ interface WorkboxPlugin { */ readonly cacheWillUpdate?: (context: CacheWillUpdatePluginContext) => Promise|Response|null; + /** + * This allows developers to override the default cache key for reads or writes (or both). + * @param {CacheKeyWillBeUsedPluginContext} context + * @returns {Promise|string|Request} + */ + readonly cacheKeyWillBeUsed?: (context: CacheKeyWillBeUsedPluginContext) => Promise|string|Request; + /** * Called when a new entry is added to a cache or it’s updated. Useful if you wish to perform an action after a cache update. * @param {CacheDidUpdatePluginContext} context @@ -1324,6 +1928,13 @@ interface WorkboxPlugin { * @returns {void} */ readonly fetchDidFail?: (context: FetchDidFailPluginContext) => void; + + /** + * Called when a network request is successful, regardless of what the HTTP status is of the response. + * @param {FetchDidSucceedPluginContext} + * @returns {Promise|Response} + */ + readonly fetchDidSucceed?: (context: FetchDidSucceedPluginContext) => Promise|Response; } interface CacheWillUpdatePluginContext { @@ -1331,7 +1942,13 @@ interface CacheWillUpdatePluginContext { readonly response: Response; } +interface CacheKeyWillBeUsedPluginContext { + readonly request: Request; + readonly mode: string; +} + interface CacheDidUpdatePluginContext { + readonly event: Event; readonly cacheName: string; readonly request: Request; readonly oldResponse: Response; @@ -1355,6 +1972,11 @@ interface FetchDidFailPluginContext { readonly error: Error; } +interface FetchDidSucceedPluginContext { + readonly request: Request; + readonly response: Response; +} + /** * ===== WorkboxNamespace ===== */ @@ -1367,19 +1989,24 @@ interface FetchDidFailPluginContext { */ type ModulePathCallback = (moduleName: string, debug: boolean) => string; -interface IConfigOptions { +interface ConfigOptions { /** - * If true, dev builds are using, otherwise prod builds are used. By default, prod is used unless on localhost. + * If true, `dev` builds are used, otherwise `prod` builds are used. + * By default, `prod` is used unless on localhost. */ debug: boolean; /** - * To avoid using the CDN with workbox-sw set the path prefix of where modules should be loaded from. For example modulePathPrefix: '/third_party/workbox/v3.0.0/'. + * To avoid using the CDN with `workbox-sw` + * set the path prefix of where modules should be loaded from. + * For example `modulePathPrefix: '/third_party/workbox/v3.0.0/'`. */ modulePathPrefix: string; /** - * If defined, this callback will be responsible for determining the path of each workbox module. + * If defined, + * this callback will be responsible for determining the path of each + * workbox module. */ modulePathCb: ModulePathCallback; } @@ -1391,34 +2018,30 @@ declare class WorkboxNamespace { static readonly core: typeof CoreNamespace; static readonly expiration: typeof ExpirationNamespace; static readonly googleAnalytics: typeof GoogleAnalyticsNamespace; + static readonly navigationPreload: typeof NavigationPreloadNamespace; static readonly precaching: typeof PrecachingNamespace; static readonly rangeRequests: typeof RangeRequestsNamespace; static readonly routing: typeof RoutingNamespace; static readonly strategies: typeof StrategiesNamespace; static readonly streams: typeof StreamsNamespace; - /** - * Claim any currently available clients once the service worker becomes active. This is normally used in conjunction with skipWaiting(). - */ - static clientsClaim (): void; - /** * Load a Workbox module by passing in the appropriate module name. - * This is not generally needed unless you know there are modules that are dynamically used and you want to safe guard use of the module while the user may be offline. + * + * This is not generally needed unless you know there are modules that are + * dynamically used and you want to safe guard use of the module while the + * user may be offline. * @param {string} moduleName */ static loadModule (moduleName: string): void; /** - * Updates the configuration options. You can specify whether to treat as a debug build and whether to use a CDN or a specific path when importing other workbox-modules - * @param {Partial} config + * Updates the configuration options. You can specify whether to treat as a + * debug build and whether to use a CDN or a specific path when importing + * other workbox-modules + * @param {Partial} config */ - static setConfig (config?: Partial): void; - - /** - * Force a service worker to become active, instead of waiting. This is normally used in conjunction with clientsClaim(). - */ - static skipWaiting (): void; + static setConfig (config?: Partial): void; } export = WorkboxNamespace; From e96af9d4340ace37319ef73af9ace3787d882986 Mon Sep 17 00:00:00 2001 From: wessberg Date: Sat, 6 Apr 2019 12:36:02 +0200 Subject: [PATCH 2/8] Upgraded workbox-sw typings to v4.2 --- types/workbox-sw/index.d.ts | 2 +- types/workbox-sw/workbox-sw-tests.ts | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/types/workbox-sw/index.d.ts b/types/workbox-sw/index.d.ts index eb98e7c5ce..bf2c193357 100644 --- a/types/workbox-sw/index.d.ts +++ b/types/workbox-sw/index.d.ts @@ -462,7 +462,7 @@ interface HandlerContext extends MatchContext { * The "handler" callback is called when a service worker's fetch event has been matched by a Route. This callback should return a Promise that resolves with a Response. * If a value is returned by the match callback it will be passed in as the context.params argument. */ -type HandlerCallback = (context: HandlerContext) => Promise; +type HandlerCallback = CacheStrategy|((context: HandlerContext) => Promise); /** * ===== NavigationRoute ===== diff --git a/types/workbox-sw/workbox-sw-tests.ts b/types/workbox-sw/workbox-sw-tests.ts index f8cdadabee..e63474768d 100644 --- a/types/workbox-sw/workbox-sw-tests.ts +++ b/types/workbox-sw/workbox-sw-tests.ts @@ -1,9 +1,7 @@ import WorkboxSW = require("workbox-sw"); -// $ExpectError -WorkboxSW.core.setLogLevel(5); // $ExpectType void -WorkboxSW.routing.registerRoute("/", WorkboxSW.strategies.networkFirst()); // $ExpectType Route +WorkboxSW.routing.registerRoute("/", new WorkboxSW.strategies.NetworkFirst()); // $ExpectType Route // $ExpectError WorkboxSW.precaching.precacheAndRoute(/foo/); From 446bc4263148f37f9c552157767e88719dfecd43 Mon Sep 17 00:00:00 2001 From: wessberg Date: Sat, 6 Apr 2019 12:36:57 +0200 Subject: [PATCH 3/8] Updated workbox-sw tests --- types/workbox-sw/workbox-sw-tests.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/workbox-sw/workbox-sw-tests.ts b/types/workbox-sw/workbox-sw-tests.ts index e63474768d..99bcebe422 100644 --- a/types/workbox-sw/workbox-sw-tests.ts +++ b/types/workbox-sw/workbox-sw-tests.ts @@ -1,8 +1,9 @@ import WorkboxSW = require("workbox-sw"); - WorkboxSW.routing.registerRoute("/", new WorkboxSW.strategies.NetworkFirst()); // $ExpectType Route +WorkboxSW.routing.registerRoute("/", WorkboxSW.strategies.networkFirst()); // $ExpectType Route + // $ExpectError WorkboxSW.precaching.precacheAndRoute(/foo/); From 506480526e218dc9194bc2981f02360b626a1103 Mon Sep 17 00:00:00 2001 From: wessberg Date: Sat, 6 Apr 2019 12:43:02 +0200 Subject: [PATCH 4/8] fixes linting errors --- types/workbox-sw/index.d.ts | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/types/workbox-sw/index.d.ts b/types/workbox-sw/index.d.ts index bf2c193357..7b30758be5 100644 --- a/types/workbox-sw/index.d.ts +++ b/types/workbox-sw/index.d.ts @@ -188,7 +188,6 @@ declare class CacheExpiration { } interface CacheExpirationConstructor { - /** * To construct a new CacheExpiration instance you must provide at least * one of the `config` properties. @@ -284,7 +283,6 @@ declare class CacheOnly extends CacheStrategy { } interface CacheOnlyConstructor { - /** * Instantiates a new CacheOnly strategy * @param {Partial} options @@ -506,10 +504,9 @@ interface NavigationRouteConstructor { * [`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. - * @param {HandlerCallback} handler * @param {Partial} options - * @return {NavigationRoute} + * @returns {NavigationRoute} */ new (handler: HandlerCallback, options: Partial): NavigationRoute; } @@ -631,7 +628,6 @@ interface CacheExpirationPluginOptions extends CacheExpirationOptions { * that is removed from the Cache. */ declare class ExpirationPlugin { - /** * This is a helper method that performs two operations: * @@ -685,7 +681,6 @@ interface StorableRequestOptions { * @private */ declare class StorableRequest { - /** * Returns a deep clone of the instances `_requestData` object. * @private @@ -819,7 +814,6 @@ interface PrecacheControllerConstructor { */ interface QueueOptions { - /** * 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 @@ -920,7 +914,9 @@ declare class Queue { interface QueueConstructor { /** * 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 {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 {Partial} options * @return {Queue} */ @@ -941,9 +937,7 @@ interface QueueConstructor { declare class Route { } - interface RouteConstructor { - /** * Constructor for Route class. * @param {MatchCallback} match - A callback function that determines whether the route matches a given `fetch` event by returning a non-falsy value. @@ -970,7 +964,6 @@ interface RouteConstructor { declare class RegExpRoute extends Route { } - interface RegExpRouteConstructor { /** * @@ -1044,7 +1037,6 @@ interface FindMatchingRouteResult { * be used to respond to the request. */ declare class Router { - /** * A `Map` of HTTP method name ('GET', etc.) to an array of all the corresponding `Route` * instances that are registered. @@ -1097,7 +1089,7 @@ declare class Router { * @param {FindMatchingRouteOptions} options * @return {Partial} */ - findMatchingRoute (options: FindMatchingRouteOptions): Partial + findMatchingRoute (options: FindMatchingRouteOptions): Partial; /** * Define a default `handler` that's called when no routes explicitly @@ -1240,7 +1232,6 @@ interface RouteOptions { * If you require finer grained control, you can use the PrecacheController to determine when performed. */ declare class PrecachingNamespace { - /** * Add plugins to precaching. * @param {Plugin[]} newPlugins @@ -1730,7 +1721,10 @@ declare class NavigationPreloadNamespace { /** * 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. + * @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. */ static enable (headerValue?: string): void; @@ -1850,7 +1844,6 @@ declare class BroadcastUpdateNamespace { */ declare class RangeRequestsNamespace { - /** * Given a `Request` and `Response` objects as input, this will return a * promise for a new `Response`. @@ -1869,7 +1862,10 @@ declare class RangeRequestsNamespace { * * @param {Request} request - A request, which should contain a Range: header. * @param {Response} originalResponse - A response. - * @returns {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. + * @returns {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. */ static createPartialResponse (request: Request, originalResponse: Response): Promise; From b20b95db9b659d1deb5c0f3e490959cbe03cb4db Mon Sep 17 00:00:00 2001 From: wessberg Date: Mon, 8 Apr 2019 19:44:53 +0200 Subject: [PATCH 5/8] fix(workbox-sw): adds v3/ subdirectory with v3 version of polyfill including path mapping --- types/workbox-sw/v3/index.d.ts | 1424 +++++++++++++++++++++++++++++ types/workbox-sw/v3/tsconfig.json | 15 + types/workbox-sw/v3/tslint.json | 3 + 3 files changed, 1442 insertions(+) create mode 100644 types/workbox-sw/v3/index.d.ts create mode 100644 types/workbox-sw/v3/tsconfig.json create mode 100644 types/workbox-sw/v3/tslint.json diff --git a/types/workbox-sw/v3/index.d.ts b/types/workbox-sw/v3/index.d.ts new file mode 100644 index 0000000000..0518d37f67 --- /dev/null +++ b/types/workbox-sw/v3/index.d.ts @@ -0,0 +1,1424 @@ +// Type definitions for workbox-sw 3.2 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Frederik Wessberg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/** + * ===== BroadcastCacheUpdate ===== + */ + +interface IBroadcastCacheUpdateOptions { + /** + * A list of headers that will be used to determine whether the responses differ. + */ + headersToCheck: string[]; + + /** + * An attribution value that indicates where the update originated. + */ + source: string; +} + +/** + * Uses the Broadcast Channel API to notify interested parties when a cached response has been updated. + * For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked + */ +declare class BroadcastCacheUpdate { + /** + * Compare two Responses and send a message via the Broadcast Channel API if they differ. + * Neither of the Responses can be opaque. + * @param {Response} firstResponse - First response to compare. + * @param {Response} secondResponse - Second response to compare. + * @param {string} url - The URL of the updated request. + * @param {string} cacheName - Name of the cache the responses belong to. This is included in the message posted on the broadcast channel. + */ + notifyIfUpdated (firstResponse: Response, secondResponse: Response, url: string, cacheName: string): void; +} + +/** + * Construct a BroadcastCacheUpdate instance with a specific channelName to broadcast messages on + */ +interface IBroadcastCacheUpdateConstructor { + new (channelName: string, options: Partial): BroadcastCacheUpdate; +} + +/** + * ===== CacheableResponse ===== + */ + +interface ICacheableResponseOptions { + statuses: number[]; + headers: { [key: string]: string }; +} + +/** + * This class allows you to set up rules determining what status codes and/or headers need to be present in order for a Response to be considered cacheable. + */ +declare class CacheableResponse { + /** + * 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. + * @returns {boolean} + */ + isResponseCacheable (response: Response): boolean; +} + +/** + * 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. + */ +interface ICacheableResponseConstructor { + new (options: Partial): CacheableResponse; +} + +/** + * ===== CacheExpiration ===== + */ + +interface ICacheExpirationOptions { + /** + * The maximum number of entries to store in a cache. + */ + maxEntries: number; + + /** + * The maximum lifetime of a request to stay in the cache before it's removed. + */ + maxAgeSeconds: number; +} + +/** + * The CacheExpiration class allows you define an expiration and / or limit on the number of responses stored in a Cache. + */ +declare class CacheExpiration { + /** + * Expires entries for the given cache and given criteria. + * @returns {Promise} + */ + expireEntries (): Promise; + + /** + * 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 + * @returns {Promise} + */ + isURLExpired (url: string): Promise; + + /** + * 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 + * @returns {Promise} + */ + updateTimestamp (url: string): Promise; +} + +/** + * To construct a new CacheExpiration instance you must provide at least one of the config properties. + */ +interface ICacheExpirationConstructor { + new (cacheName: string, config: Partial): CacheExpiration; +} + +/** + * ===== Strategies ===== + */ + +interface ICacheStrategyHandleOptions { + event: FetchEvent; +} + +interface ICacheStrategyMakeRequestOptions { + request: Request|string; + event?: FetchEvent; +} + +declare class CacheStrategy { + /** + * This method will perform a request strategy and follows an API that will work with the Workbox Router. + * @param {ICacheStrategyHandleOptions} input + * @returns {Promise} + */ + handle (input: ICacheStrategyHandleOptions): Promise; + + /** + * This method can be used to perform a make a standalone request outside the context of the Workbox Router. + * @param {ICacheStrategyMakeRequestOptions} input + * @returns {Promise} + */ + makeRequest (input: ICacheStrategyMakeRequestOptions): Promise; +} + +/** + * ===== CacheOnly strategy ===== + */ + +interface ICacheOnlyOptions { + /** + * Cache name to store and retrieve requests. Defaults to cache names provided by workbox-core. + */ + cacheName: string; + /** + * Plugins to use in conjunction with this caching strategy. + */ + plugins: Plugin[]; +} + +/** + * An implementation of a cache-only request strategy. + * This class is useful if you want to take advantage of any Workbox plugins. + */ +declare class CacheOnly extends CacheStrategy { +} + +/** + * Instantiates a new CacheOnly strategy + */ +interface ICacheOnlyConstructor { + new (options?: Partial): CacheOnly; +} + +/** + * ===== CacheFirst strategy ===== + */ + +interface ICacheFirstOptions extends ICacheOnlyOptions { + /** + * Values passed along to the init of all fetch() requests made by this strategy. + */ + fetchOptions: RequestInit; +} + +/** + * An implementation of a cache-first 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. + */ +declare class CacheFirst extends CacheStrategy { +} + +/** + * Instantiates a new CacheFirst strategy + */ +interface ICacheFirstConstructor { + new (options?: Partial): CacheFirst; +} + +/** + * ===== NetworkOnly strategy ===== + */ + +interface INetworkOnlyOptions extends ICacheFirstOptions { +} + +/** + * An implementation of a network-only request strategy. + * This class is useful if you want to take advantage of any Workbox plugins. + */ +declare class NetworkOnly extends CacheStrategy { +} + +/** + * Instantiates a new NetworkOnly strategy + */ +interface INetworkOnlyConstructor { + new (options?: Partial): NetworkOnly; +} + +/** + * ===== NetworkFirst strategy ===== + */ + +interface INetworkFirstOptions extends ICacheFirstOptions { + networkTimeoutSeconds: number; +} + +/** + * An implementation of a network first request strategy. + * By default, this strategy will cache responses with a 200 status code as well as opaque responses. + * Opaque responses are are cross-origin requests where the response doesn't support CORS. + */ +declare class NetworkFirst extends CacheStrategy { +} + +/** + * Instantiates a new NetworkFirst strategy + */ +interface INetworkFirstConstructor { + new (options?: Partial): NetworkFirst; +} + +/** + * ===== StaleWhileRevalidate strategy ===== + */ + +interface IStaleWhileRevalidateOptions extends ICacheFirstOptions { +} + +/** + * An implementation of a 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. + * Opaque responses are are cross-origin requests where the response doesn't support CORS. + */ +declare class StaleWhileRevalidate extends CacheStrategy { +} + +/** + * Instantiates a new StaleWhileRevalidate strategy + */ +interface IStaleWhileRevalidateConstructor { + new (options?: Partial): StaleWhileRevalidate; +} + +/** + * ===== MatchCallback ===== + */ + +interface IMatchContext extends IURLContext { + /** + * The service workers' fetch event. + */ + event: FetchEvent; +} + +/** + * To signify a match, return anything other than null. Return null if the route shouldn't match. + */ +type MatchCallback = (context: IMatchContext) => {}|null; + +/** + * ===== HandlerCallback ===== + */ + +interface IHandlerContext extends IMatchContext { + /** + * Parameters returned by the Route's match callback function. This will be undefined if nothing was returned. + */ + params?: {}; +} + +/** + * The "handler" callback is called when a service worker's fetch event has been matched by a Route. This callback should return a Promise that resolves with a Response. + * If a value is returned by the match callback it will be passed in as the context.params argument. + */ +type HandlerCallback = (context: IHandlerContext) => Promise; + +/** + * ===== NavigationRoute ===== + */ + +interface IHandlerOptions { + url: string; + event: FetchEvent; + params: URLSearchParams; +} + +interface INavigationRouteOptions { + /** + * If any of these patterns match, the route will not handle the request (even if a whitelist RegExp matches). + */ + blacklist: RegExp[]; + + /** + * If any of these patterns match the URL's pathname and search parameter, + * the route will handle the request (assuming the blacklist doesn't match). + */ + whitelist: RegExp[]; +} + +/** + * NavigationRoute makes it easy to create a Route that matches for browser navigation requests. + * It will only match incoming Requests whose 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 blacklist and whitelist parameters. + */ +declare class NavigationRoute { +} + +/** + * If both blacklist and whitelist are provided, the blacklist will take precedence and the request will not match this route. + * The regular expressions in whitelist and blacklist are matched against the concatenated pathname and search portions of the requested URL. + */ +interface INavigationRouteConstructor { + new (handler: HandlerCallback, options: Partial): NavigationRoute; +} + +/** + * ===== BroadcastUpdatePlugin ===== + */ + +/** + * This plugin will automatically broadcast a message whenever a cached response is updated. + */ +declare class BroadcastUpdatePlugin { +} + +/** + * Construct a new instance with a specific channelName to broadcast messages on + */ +interface IBroadcastUpdatePluginConstructor { + new (channelName: string, options?: Partial): BroadcastUpdatePlugin; +} + +/** + * ===== BroadcastUpdatePlugin ===== + */ + +/** + * 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. + */ +declare class RangeRequestsPlugin { +} + +/** + * Instantiates a new RangeRequestsPlugin + */ +interface IRangeRequestsPluginConstructor { + new (): RangeRequestsPlugin; +} + +/** + * ===== CacheableResponsePlugin ===== + */ + +/** + * 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. + */ +declare class CacheableResponsePlugin { +} + +/** + * To construct a new cacheable response Plugin 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. + */ +interface ICacheableResponsePluginConstructor { + new (config: Partial): CacheableResponsePlugin; +} + +/** + * ===== BackgroundSyncPlugin ===== + */ + +/** + * A class implementing the fetchDidFail lifecycle callback. + * This makes it easier to add failed requests to a background sync Queue. + */ +declare class BackgroundSyncPlugin { +} + +/** + * Instantiates a new BackgroundSyncPlugin + */ +interface IBackgroundSyncPluginConstructor { + new (...queueArgs: any[]): BackgroundSyncPlugin; +} + +/** + * ===== ExpirationPlugin ===== + */ + +/** + * This plugin can be used in the Workbox API's to regularly enforce a limit on the age and / or the number of cached requests. + * Whenever a cached request is used or updated, this plugin will look at the used Cache and remove any old or extra requests. + * When using maxAgeSeconds, requests may be used once after expiring because the expiration clean up will not have occurred + * until after the cached request has been used. If the request has a "Date" header, then a light weight expiration check is + * performed and the request will not be used immediately. + * When using maxEntries, the last request to be used will be the request that is removed from the Cache. + */ +declare class ExpirationPlugin { +} + +/** + * Instantiates a new ExpirationPlugin + */ +interface IExpirationPluginConstructor { + new (config: Partial): ExpirationPlugin; +} + +/** + * ===== ExpirationPlugin ===== + */ + +type Plugin = BroadcastUpdatePlugin|RangeRequestsPlugin|CacheableResponsePlugin|BackgroundSyncPlugin|ExpirationPlugin|WorkboxPlugin; + +/** + * ===== BackgroundSync ===== + */ + +interface IStorableRequestOptions { + url: string; + + /** + * See: https://fetch.spec.whatwg.org/#requestinit + */ + requestInit: RequestInit; + + /** + * The time the request was created, defaulting to the current time if not specified. + */ + timestamp: number; +} + +/** + * A class to make it easier to serialize and de-serialize requests so they can be stored in IndexedDB. + */ +declare class StorableRequest { + readonly timestamp: number; + + toObject (): IStorableRequestOptions; + + toRequest (): Request; + + clone (): StorableRequest; +} + +/** + * Accepts a URL and RequestInit dictionary that can be used to create a + * new Request object. A timestamp is also generated so consumers can + * reference when the object was created. + */ +interface IStorableRequestConstructor { + new (options: IStorableRequestOptions): StorableRequest; + fromRequest (request: Request): StorableRequest; +} + +/** + * ===== PrecacheController ===== + */ + +interface ICleanupResult { + /** + * List of URLs that were deleted from the precache cache. + */ + deletedCacheRequests: string[]; + /** + * List of URLs that were deleted from the precache cache. + */ + deletedRevisionDetails: string[]; +} + +interface IActivateOptions { + /** + * Plugins to be used for fetching and caching during install. + */ + plugins: Plugin[]; +} + +interface IInstallOptions { + /** + * Suppress warning messages. + */ + suppressWarnings: boolean; + + /** + * Plugins to be used for fetching and caching during install. + */ + plugins: Plugin[]; +} + +interface IPrecacheEntry { + url: string; + revision: string; +} + +interface IInstallResult { + /** + * List of entries supplied for precaching that were precached. + */ + updatedEntries: (string|IPrecacheEntry)[]; + + /** + * List of entries supplied for precaching that were already precached. + */ + notUpdatedEntries: (string|IPrecacheEntry)[]; +} + +/** + * Performs efficient precaching of assets. + */ +declare class PrecacheController { + /** + * Takes the current set of temporary files and moves them to the final cache, deleting the temporary cache once copying is complete. + * @param {IActivateOptions} options + * @returns {Promise} Resolves with an object containing details of the deleted cache requests and precache revision details. + */ + activate (options: Partial): Promise; + + /** + * This method will add items to the precache list, removing duplicates and ensuring the information is valid. + * @param {(string | IPrecacheEntry)[]} entries - Array of entries to precache. + */ + addToCacheList (entries: (string|IPrecacheEntry)[]): void; + + /** + * Returns an array of fully qualified URL's that will be precached. + * @returns {string[]} An array of URLs. + */ + getCachedUrls (): string[]; + + /** + * Call this method from a service work install event to start precaching assets. + * @param {Partial} options + * @returns {Promise} + */ + install (options?: Partial): Promise; +} + +/** + * Create a new PrecacheController. + */ +interface IPrecacheControllerConstructor { + new (cacheName?: string): PrecacheController; +} + +/** + * ===== Queue ===== + */ + +interface IQueueCallback { + /** + * Invoked immediately before the request is stored to IndexedDB. Use this callback to modify request data at store time. + * @param {StorableRequest} request + */ + requestWillEnqueue (request: StorableRequest): void; + /** + * Invoked immediately before the request is re-fetched. Use this callback to modify request data at fetch time. + * @param {StorableRequest} request + */ + requestWillReplay (request: StorableRequest): void; + + /** + * Invoked after all requests in the queue have successfully replayed. + * @param {StorableRequest[]} requests + */ + queueDidReplay (requests: StorableRequest[]): void; +} + +interface IQueueOptions { + /** + * 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. + */ + maxRetentionTime: number; + /** + * Callbacks to observe the lifecycle of queued requests. Use these to respond to or modify the requests during the replay process. + */ + callbacks: Partial; +} + +/** + * 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. + */ +declare class Queue { + readonly name: string; + + /** + * Stores the passed request into IndexedDB. The database used is workbox-background-sync and the object store name is the same as the name this instance was created with (to guarantee it's unique). + * @param {Request} request - The request object to store. + * @returns {Promise} + */ + addRequest (request: Request): Promise; + + /** + * Retrieves all stored requests in IndexedDB and retries them. If the queue contained requests that + * were successfully replayed, the queueDidReplay callback is invoked (which implies the queue is now empty). + * If any of the requests fail, a new sync registration is created to retry again later. + * @returns {Promise} + */ + replayRequests (): Promise; +} + +/** + * Creates an instance of Queue with the given options + */ +interface IQueueConstructor { + /** + * @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 {Partial} options + * @returns {Queue} + */ + new (name: string, options?: Partial): Queue; +} + +/** + * ===== Route ===== + */ + +/** + * 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. + */ +declare class Route { +} + +/** + * Constructor for Route class. + */ +interface IRouteConstructor { + /** + * + * @param {MatchCallback} match - A callback function that determines whether the route matches a given fetch event by returning a non-falsy value. + * @param {HandlerCallback} handler - A callback function that returns a Promise resolving to a Response. + * @param {string} [method] - The HTTP method to match the Route against. + * @returns {Route} + */ + new (match: MatchCallback, handler: HandlerCallback, method?: string): Route; +} + +/** + * ===== RegExpRoute ===== + */ + +/** + * RegExpRoute makes it easy to create a regular expression based 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. + */ +declare class RegExpRoute extends Route { +} + +/** + * If the regular expression contains capture groups, the captured values will be passed to the handler's params argument. + */ +interface IRegExpRouteConstructor { + /** + * + * @param {RegExp} regExp - The regular expression to match against URLs. + * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + * @param {string} [method] - The HTTP method to match the Route against. + * @returns {RegExpRoute} + */ + new (regExp: RegExp, handler: HandlerCallback, method?: string): RegExpRoute; +} + +/** + * ===== Router ===== + */ + +/** + * The Router can be used to process a FetchEvent through one or more Routes responding with a Request 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. + */ +declare class Router { + /** + * Apply the routing rules to a FetchEvent object to get a Response from an appropriate Route's handler. + * @param {FetchEvent} event - The event from a service worker's 'fetch' event listener. + * @returns {Promise?} A promise is returned if a registered route can handle the FetchEvent's request. If there is no matching route and there's no defaultHandler, undefined is returned. + */ + handleRequest (event: FetchEvent): Promise|undefined; + + /** + * Registers a route with the router. + * @param {Route} route + */ + registerRoute (route: Route): void; + + /** + * If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response. + * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + */ + setCatchHandler (handler: HandlerCallback): void; + + /** + * 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 {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + */ + setDefaultHandler (handler: HandlerCallback): void; + + /** + * Unregisters a route with the router. + * @param {Route} route - The route to unregister. + */ + unregisterRoute (route: Route): void; +} + +/** + * Initializes a new Router. + */ +interface IRouterConstructor { + new (): Router; +} + +/** + * ===== CoreNamespace ===== + */ + +interface ICacheNames { + precache: string; + runtime: string; + googleAnalytics: string; +} + +interface ILogLevel { + /** + * Prints all logs from Workbox. Useful for debugging. + */ + debug: 0; + + /** + * Prints console log, warn, error and groups. Default for debug builds. + */ + log: 1; + + /** + * Prints console warn, error and groups. Default for non-debug builds. + */ + warn: 2; + + /** + * Print console error and groups. + */ + error: 3; + + /** + * Force no logging from Workbox. + */ + silent: 4; +} + +interface ICacheNameDetails { + prefix: string; + suffix: string; + precache: string; + runtime: string; + googleAnalytics: string; +} + +/** + * All of the Workbox service worker libraries use workbox-core for shared code as well as setting default values that need to be shared (like cache names). + */ +declare class CoreNamespace { + /** + * 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. + */ + static readonly cacheNames: ICacheNames; + + /** + * The available log levels in Workbox: debug, log, warn, error and silent. + */ + static readonly LOG_LEVELS: ILogLevel; + + /** + * Get the current log level. + */ + static readonly logLevel: ILogLevel[keyof ILogLevel]; + + /** + * You can alter the default cache names used by the Workbox modules by changing the cache name details. + * Cache names are generated as --. + * @param {Partial} details + */ + static setCacheNameDetails (details: Partial): void; + + /** + * Set the current log level passing in one of the values from LOG_LEVELS. + * @param {number} logLevel - The new log level to use. + */ + static setLogLevel (logLevel: ILogLevel[keyof ILogLevel]): void; +} + +/** + * ===== PrecachingNamespace ===== + */ + +interface IURLContext { + /** + * The request's URL. + */ + url: URL; +} + +/** + * The "urlManipulation" callback can be used to determine if there are any additional permutations of a URL that should be used to check against the available precached files. + * For example, Workbox supports checking for '/index.html' when the URL '/' is provided. This callback allows additional, custom checks. + * @param {IURLContext} context + * @returns {URL[]} To add additional urls to test, return an Array of URL's. Please note that these should not be Strings, but URL objects. + */ +type UrlManipulation = (context: IURLContext) => URL[]; + +interface IRouteOptions { + /** + * The directoryIndex will check cache entries for a URLs ending with '/' to see if there is a hit when appending the directoryIndex value. + */ + directoryIndex: string|null; + + /** + * An array of regex's to remove search params when looking for a cache match. + */ + ignoreUrlParametersMatching: RegExp[]; + + /** + * The cleanUrls option will check the cache for the URL with a .html added to the end of the end. + */ + cleanUrls: boolean; + + /** + * This is a function that should take a URL and return an array of alternative URL's that should be checked for precache matches. + */ + urlManipulation: UrlManipulation; +} + +/** + * Most consumers of this module will want to use the precacheAndRoute() method to add assets to the Cache and respond to network requests with these cached assets. + * If you require finer grained control, you can use the PrecacheController to determine when performed. + */ +declare class PrecachingNamespace { + /** + * Performs efficient precaching of assets. + */ + static readonly PrecacheController: IPrecacheControllerConstructor; + + /** + * Add plugins to precaching. + * @param {Plugin[]} newPlugins + */ + static addPlugins (newPlugins: Plugin[]): void; + + /** + * Add a fetch listener to the service worker that will respond to network 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 {Partial} route + */ + static addRoute (route: Partial): void; + + /** + * Add items to the precache list, removing any duplicates and store the files in the "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 addRoute(). + * If you have a single array of files to precache, you can just call precacheAndRoute(). + * @param {(string | IPrecacheEntry)[]} entries + */ + static precache (entries: (string|IPrecacheEntry)[]): void; + + /** + * 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 precache() and addRoute() in a single call. + * @param {(string | IPrecacheEntry)[]} entries - Array of entries to precache. + * @param {Partial} [route] - see addRoute() options + */ + static precacheAndRoute (entries: (string|IPrecacheEntry)[], route?: Partial): void; + + /** + * Warnings will be logged if any of the precached assets are entered without a revision property. + * This is extremely dangerous if the URL's aren't revisioned. + * However, the warnings can be supressed with this method. + * @param {boolean} suppress + */ + static suppressWarnings (suppress: boolean): void; +} + +/** + * ===== RoutingNamespace ===== + */ + +interface IRegisterNavigationRouteOptions extends INavigationRouteOptions { + cacheName: string; +} + +declare class RoutingNamespace { + /** + * NavigationRoute makes it easy to create a Route that matches for browser navigation requests. + * It will only match incoming Requests whose 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 blacklist and whitelist parameters. + */ + static readonly NavigationRoute: INavigationRouteConstructor; + + /** + * RegExpRoute makes it easy to create a regular expression based 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. + */ + static readonly RegExpRoute: IRegExpRouteConstructor; + + /** + * 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. + */ + static readonly Route: IRouteConstructor; + + /** + * The Router can be used to process a FetchEvent through one or more Routes responding with a Request 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. + */ + static readonly Router: IRouterConstructor; + + /** + * Register a route that will return a precached file for a navigation request. This is useful for the application shell pattern. + * This method will generate a NavigationRoute and call Router.registerRoute(). + * @param {string} cachedAssetUrl + * @param {Partial} [options] + * @returns {NavigationRoute} Returns the generated Route. + */ + static registerNavigationRoute (cachedAssetUrl: string, options?: Partial): NavigationRoute; + + /** + * Easily register a RegExp, string, or function with a caching strategy to the Router. + * This method will generate a Route for you if needed and call Router.registerRoute(). + * @param {string | RegExp | MatchCallback | Route} capture - If the capture param is a Route, all other arguments will be ignored. + * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. + * @param {string} method - The HTTP method to match the Route against. + * @returns {Route} The generated Route(Useful for unregistering). + */ + static registerRoute (capture: string|RegExp|MatchCallback|Route, handler: HandlerCallback, method?: string): Route; + + /** + * If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response. + * @param {IHandlerOptions} handler - A callback function that returns a Promise resulting in a Response. + * @returns {Promise} + */ + static setCatchHandler (handler: IHandlerOptions): Promise; + + /** + * 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 {IHandlerOptions} handler - A callback function that returns a Promise resulting in a Response. + * @returns {Promise} + */ + static setDefaultHandler (handler: IHandlerOptions): Promise; + + /** + * Unregisters a route with the router. + * @param {Route} route - The route to unregister + */ + static unregisterRoute (route: Route): void; +} + +/** + * ===== StrategiesNamespace ===== + */ + +interface IStrategyOptions { + /** + * Name of cache to use for caching (both lookup and updating). + */ + cacheName: string; + + /** + * Defining this object will add a cache expiration plugins to this strategy. + */ + cacheExpiration: Partial; + + /** + * The Plugins to use along with the Strategy + */ + plugins: Plugin[]; +} + +/** + * There are common caching strategies that most service workers will need and use. This module provides simple implementations of these strategies. + */ +declare class StrategiesNamespace { + /** + * An implementation of a cache-first 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. + */ + static readonly CacheFirst: ICacheFirstConstructor; + + /** + * An implementation of a cache-only request strategy. + * This class is useful if you want to take advantage of any Workbox plugins. + */ + static readonly CacheOnly: ICacheOnlyConstructor; + + /** + * An implementation of a network first request strategy. + * By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are are cross-origin requests where the response doesn't support CORS. + */ + static readonly NetworkFirst: INetworkFirstConstructor; + + /** + * An implementation of a network-only request strategy. + * This class is useful if you want to take advantage of any Workbox plugins. + */ + static readonly NetworkOnly: INetworkOnlyConstructor; + + /** + * An implementation of a 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. + * Opaque responses are are cross-origin requests where the response doesn't support CORS. + */ + static readonly StaleWhileRevalidate: IStaleWhileRevalidateConstructor; + + /** + * Instantiates a new CacheFirst strategy + * @param {Partial} [options] + * @returns {HandlerCallback} + */ + static cacheFirst (options?: Partial): HandlerCallback; + + /** + * Instantiates a new CacheOnly strategy + * @param {Partial} [options] + * @returns {HandlerCallback} + */ + static cacheOnly (options?: Partial): HandlerCallback; + + /** + * Instantiates a new NetworkFirst strategy + * @param {Partial} [options] + * @returns {HandlerCallback} + */ + static networkFirst (options?: Partial): HandlerCallback; + + /** + * Instantiates a new NetworkOnly strategy + * @param {Partial} [options] + * @returns {HandlerCallback} + */ + static networkOnly (options?: Partial): HandlerCallback; + + /** + * Instantiates a new StaleWhileRevalidate strategy + * @param {Partial} [options] + * @returns {StaleWhileRevalidate} + */ + static staleWhileRevalidate (options?: Partial): HandlerCallback; +} + +/** + * ===== StreamsNamespace ===== + */ + +type StreamSource = Response|ReadableStream|BodyInit; + +interface IConcatenateResult { + done: Promise; + stream: ReadableStream; +} + +interface IConcatenateToResponseResult { + done: Promise; + response: Response; +} + +declare class StreamsNamespace { + /** + * Takes multiple source Promises, each of which could resolve to a Response, a ReadableStream, or a 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 {Promise[]} sourcePromises - Array of Promise containing StreamSource + * @returns {IConcatenateResult} + */ + static concatenate (sourcePromises: Promise[]): IConcatenateResult; + + /** + * Takes multiple source Promises, each of which could resolve to a Response, a ReadableStream, or a BodyInit,along with a 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 {Promise[]} sourcePromises - Array of Promise containing StreamSource + * @param {HeadersInit} [headersInit] - If there's no Content-Type specified, 'text/html' will be used by default. + * @returns {IConcatenateToResponseResult} + */ + static concatenateToResponse (sourcePromises: Promise[], headersInit?: HeadersInit): IConcatenateToResponseResult; + + /** + * This is a utility method that determines whether the current browser supports the features required to create streamed responses. Currently, it checks if ReadableStream is available. + * @param {HeadersInit} [headersInit] - If there's no Content-Type specified, 'text/html' will be used by default. + * @returns {boolean} - true, if the current browser meets the requirements for streaming responses, and false otherwise. + */ + static createHeaders (headersInit?: HeadersInit): boolean; + + /** + * This is a utility method that determines whether the current browser supports the features required to create streamed responses. Currently, it checks if ReadableStream is available. + * @returns {boolean} - true, if the current browser meets the requirements for streaming responses, and false otherwise. + */ + static isSupported (): boolean; + + /** + * A shortcut to create a strategy that could be dropped-in to Workbox's router. + * On browsers that do not support constructing new ReadableStreams, this strategy will automatically wait for + * all the sourceFunctions to complete, and create a final response that concatenates their values together. + * @param {HandlerCallback[]} sourceFunctions - Each function should return a 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. + * @returns {HandlerCallback} + */ + static strategy (sourceFunctions: HandlerCallback[], headersInit?: HeadersInit): HandlerCallback; +} + +/** + * ===== ExpirationNamespace ===== + */ + +declare class ExpirationNamespace { + /** + * The CacheExpiration class allows you define an expiration and / or limit on the number of responses stored in a Cache. + */ + static readonly CacheExpiration: ICacheExpirationConstructor; + + /** + * This plugin can be used in the Workbox API's to regularly enforce a limit on the age and / or the number of cached requests. + * Whenever a cached request is used or updated, this plugin will look at the used Cache and remove any old or extra requests. + * When using maxAgeSeconds, requests may be used once after expiring because the expiration clean up will not + * have occurred until after the cached request has been used. If the request has a "Date" header, then a light weight + * expiration check is performed and the request will not be used immediately. + * When using maxEntries, the last request to be used will be the request that is removed from the Cache. + */ + static readonly Plugin: IExpirationPluginConstructor; +} + +/** + * ===== BackgroundSyncNamespace ===== + */ + +declare class BackgroundSyncNamespace { + /** + * A class implementing the fetchDidFail lifecycle callback. This makes it easier to add failed requests to a background sync Queue. + */ + static readonly Plugin: IBackgroundSyncPluginConstructor; + + /** + * 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. + */ + static readonly Queue: IQueueConstructor; +} + +/** + * ===== GoogleAnalyticsNamespace ===== + */ + +interface IGoogleAnalyticsInitializeOptions { + /** + * The cache name to store and retrieve analytics.js. Defaults to the cache names provided by workbox-core. + */ + cacheName: string; + + /** + * Measurement Protocol 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. + */ + parameterOverrides: { [key: string]: string }; + + /** + * 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. + * @param {URLSearchParams} params + */ + hitFilter (params: URLSearchParams): void; +} + +declare class GoogleAnalyticsNamespace { + static initialize (options: Partial): void; +} + +/** + * ===== CacheableResponseNamespace ===== + */ + +declare class CacheableResponseNamespace { + /** + * This class allows you to set up rules determining what status codes and/or headers need to be present in order for a Response to be considered cacheable. + */ + static readonly CacheableResponse: ICacheableResponseConstructor; + + /** + * 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. + */ + static readonly Plugin: ICacheableResponsePluginConstructor; +} + +/** + * ===== BroadcastUpdateNamespace ===== + */ + +declare class BroadcastUpdateNamespace { + /** + * Uses the Broadcast Channel API to notify interested parties when a cached response has been updated. + * For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked. + */ + static readonly BroadcastCacheUpdate: IBroadcastCacheUpdateConstructor; + + /** + * This plugin will automatically broadcast a message whenever a cached response is updated. + */ + static readonly Plugin: IBroadcastUpdatePluginConstructor; + + /** + * You would not normally call this method directly; + * it's called automatically by an instance of the BroadcastCacheUpdate class. + * It's exposed here for the benefit of developers who would rather not use the full BroadcastCacheUpdate implementation. + * Calling this will dispatch a message on the provided Broadcast Channel to notify interested subscribers about a + * change to a cached resource. + * The message that's posted has a formation inspired by the Flux standard action format like so: + * @param {BroadcastChannel} channel - The BroadcastChannel to use. + * @param {string} cacheName - The name of the cache in which the updated Response was stored. + * @param {string} url - The URL associated with the updated Response. + * @param {string} source - A string identifying this library as the source of the update message. + */ + static broadCastUpdate (channel: BroadcastChannel, cacheName: string, url: string, source: string): void; +} + +/** + * ===== RangeRequestsNamespace ===== + */ + +declare class RangeRequestsNamespace { + /** + * 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. + */ + static readonly Plugin: IRangeRequestsPluginConstructor; + + /** + * Given a Request and Response objects as input, this will return a promise for a new Response. + * @param {Request} request - A request, which should contain a Range: header. + * @param {Response} originalResponse - An original response containing the full content. + * @returns {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. + */ + static createPartialResponse (request: Request, originalResponse: Response): Promise; +} + +/** + * ===== Workbox Plugin ===== + */ +interface WorkboxPlugin { + /** + * Called before a Response is used to update a cache. You can alter the Response before it’s added to the cache or return null to avoid updating the cache at all. + * @param {CacheWillUpdatePluginContext} context + * @returns {Promise|Response|null} + */ + readonly cacheWillUpdate?: (context: CacheWillUpdatePluginContext) => Promise|Response|null; + + /** + * Called when a new entry is added to a cache or it’s updated. Useful if you wish to perform an action after a cache update. + * @param {CacheDidUpdatePluginContext} context + * @returns {void} + */ + readonly cacheDidUpdate?: (context: CacheDidUpdatePluginContext) => void; + + /** + * Before a cached Response is used to respond to a fetch event, this callback can be used to allow or block the Response from being used. + * @param {CacheResponseWillBeUsedPluginContext} context + * @returns {Promise|Response|null} + */ + readonly cachedResponseWillBeUsed?: (context: CacheResponseWillBeUsedPluginContext) => Promise|Response|null; + + /** + * This is called whenever a fetch event is about to be made. You can alter the Request in this callback. + * @param {RequestWillFetchPluginContext} context + * @returns {Request} + */ + readonly requestWillFetch?: (context: RequestWillFetchPluginContext) => Request; + + /** + * Called when a fetch event fails (note this is when the network request can’t be made at all and not when a request is a non-200 request). + * @param {FetchDidFailPluginContext} + * @returns {void} + */ + readonly fetchDidFail?: (context: FetchDidFailPluginContext) => void; +} + +interface CacheWillUpdatePluginContext { + readonly request: Request; + readonly response: Response; +} + +interface CacheDidUpdatePluginContext { + readonly cacheName: string; + readonly request: Request; + readonly oldResponse: Response; + readonly newResponse: Response; +} + +interface CacheResponseWillBeUsedPluginContext { + readonly cacheName: string; + readonly request: Request; + readonly matchOptions: any; + readonly cachedResponse: Response; +} + +interface RequestWillFetchPluginContext { + readonly request: Request; +} + +interface FetchDidFailPluginContext { + readonly originalRequest: Request; + readonly request: Request; + readonly error: Error; +} + +/** + * ===== WorkboxNamespace ===== + */ + +/** + * A ModulePathCallback function can be used to modify the modify the where Workbox modules are loaded. + * @param {string} moduleName - The name of the module to load (i.e. 'workbox-core', 'workbox-precaching' etc.). + * @param {boolean} debug - When true, dev builds should be loaded, otherwise load prod builds. + * @returns {string} This callback should return a path of module. This will be passed to importScripts(). + */ +type ModulePathCallback = (moduleName: string, debug: boolean) => string; + +interface IConfigOptions { + /** + * If true, dev builds are using, otherwise prod builds are used. By default, prod is used unless on localhost. + */ + debug: boolean; + + /** + * To avoid using the CDN with workbox-sw set the path prefix of where modules should be loaded from. For example modulePathPrefix: '/third_party/workbox/v3.0.0/'. + */ + modulePathPrefix: string; + + /** + * If defined, this callback will be responsible for determining the path of each workbox module. + */ + modulePathCb: ModulePathCallback; +} + +declare class WorkboxNamespace { + static readonly backgroundSync: typeof BackgroundSyncNamespace; + static readonly broadcastUpdate: typeof BroadcastUpdateNamespace; + static readonly cacheableResponse: typeof CacheableResponseNamespace; + static readonly core: typeof CoreNamespace; + static readonly expiration: typeof ExpirationNamespace; + static readonly googleAnalytics: typeof GoogleAnalyticsNamespace; + static readonly precaching: typeof PrecachingNamespace; + static readonly rangeRequests: typeof RangeRequestsNamespace; + static readonly routing: typeof RoutingNamespace; + static readonly strategies: typeof StrategiesNamespace; + static readonly streams: typeof StreamsNamespace; + + /** + * Claim any currently available clients once the service worker becomes active. This is normally used in conjunction with skipWaiting(). + */ + static clientsClaim (): void; + + /** + * Load a Workbox module by passing in the appropriate module name. + * This is not generally needed unless you know there are modules that are dynamically used and you want to safe guard use of the module while the user may be offline. + * @param {string} moduleName + */ + static loadModule (moduleName: string): void; + + /** + * Updates the configuration options. You can specify whether to treat as a debug build and whether to use a CDN or a specific path when importing other workbox-modules + * @param {Partial} config + */ + static setConfig (config?: Partial): void; + + /** + * Force a service worker to become active, instead of waiting. This is normally used in conjunction with clientsClaim(). + */ + static skipWaiting (): void; +} + +export = WorkboxNamespace; \ No newline at end of file diff --git a/types/workbox-sw/v3/tsconfig.json b/types/workbox-sw/v3/tsconfig.json new file mode 100644 index 0000000000..bf16574d58 --- /dev/null +++ b/types/workbox-sw/v3/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "workbox-sw": [ + "workbox-sw/v3" + ], + "workbox-sw/*": [ + "workbox-sw/v3/*" + ] + } + } +} \ No newline at end of file diff --git a/types/workbox-sw/v3/tslint.json b/types/workbox-sw/v3/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/types/workbox-sw/v3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} From 732bc6e3adae792914a30c6a062899f6c724cf73 Mon Sep 17 00:00:00 2001 From: wessberg Date: Mon, 8 Apr 2019 19:45:35 +0200 Subject: [PATCH 6/8] fix(workbox-sw): adds v3/ subdirectory with v3 version of polyfill including path mapping --- types/workbox-sw/v3/tsconfig.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/workbox-sw/v3/tsconfig.json b/types/workbox-sw/v3/tsconfig.json index bf16574d58..acec1443a8 100644 --- a/types/workbox-sw/v3/tsconfig.json +++ b/types/workbox-sw/v3/tsconfig.json @@ -1,5 +1,8 @@ { "extends": "../tsconfig.json", + "files": [ + "index.d.ts" + ], "compilerOptions": { "baseUrl": "../../", "typeRoots": ["../../"], From 36f9b51bcc5e3bdc0fc89b66c35bf1cad2030fa0 Mon Sep 17 00:00:00 2001 From: wessberg Date: Mon, 8 Apr 2019 23:11:22 +0200 Subject: [PATCH 7/8] fixed Travis --- types/workbox-sw/v3/tsconfig.json | 19 ++++++++++++++++--- types/workbox-sw/v3/tslint.json | 13 +++++++++++-- types/workbox-sw/v3/workbox-sw-tests.ts | 11 +++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 types/workbox-sw/v3/workbox-sw-tests.ts diff --git a/types/workbox-sw/v3/tsconfig.json b/types/workbox-sw/v3/tsconfig.json index acec1443a8..7a3f7637a7 100644 --- a/types/workbox-sw/v3/tsconfig.json +++ b/types/workbox-sw/v3/tsconfig.json @@ -1,9 +1,19 @@ { - "extends": "../tsconfig.json", "files": [ - "index.d.ts" + "index.d.ts", + "workbox-sw-tests.ts" ], "compilerOptions": { + "module": "commonjs", + "target": "es2017", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../../", "typeRoots": ["../../"], "paths": { @@ -13,6 +23,9 @@ "workbox-sw/*": [ "workbox-sw/v3/*" ] - } + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/types/workbox-sw/v3/tslint.json b/types/workbox-sw/v3/tslint.json index f9e30021f4..2e8bef6022 100644 --- a/types/workbox-sw/v3/tslint.json +++ b/types/workbox-sw/v3/tslint.json @@ -1,3 +1,12 @@ { - "extends": "../tslint.json" -} + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-redundant-jsdoc-2": false, + "no-unnecessary-class": false, + "no-empty-interface": false, + "array-type": false, + "interface-name": false, + "space-before-function-paren": false + } +} \ No newline at end of file diff --git a/types/workbox-sw/v3/workbox-sw-tests.ts b/types/workbox-sw/v3/workbox-sw-tests.ts new file mode 100644 index 0000000000..4d8b04f09d --- /dev/null +++ b/types/workbox-sw/v3/workbox-sw-tests.ts @@ -0,0 +1,11 @@ +import WorkboxSW = require("workbox-sw"); + +// $ExpectError +WorkboxSW.core.setLogLevel(5); // $ExpectType void + +WorkboxSW.routing.registerRoute("/", WorkboxSW.strategies.networkFirst()); // $ExpectType Route + +// $ExpectError +WorkboxSW.precaching.precacheAndRoute(/foo/); + +WorkboxSW.precaching.precacheAndRoute(["some-resource.js"], {directoryIndex: "/"}); // $ExpectType void \ No newline at end of file From cf3a95f26e5224a17fd59e056adb531f40574fb8 Mon Sep 17 00:00:00 2001 From: wessberg Date: Mon, 8 Apr 2019 23:13:06 +0200 Subject: [PATCH 8/8] fixed lint --- types/workbox-sw/v3/index.d.ts | 8 +++++--- types/workbox-sw/v3/workbox-sw-tests.ts | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/types/workbox-sw/v3/index.d.ts b/types/workbox-sw/v3/index.d.ts index 0518d37f67..4d94cec7ec 100644 --- a/types/workbox-sw/v3/index.d.ts +++ b/types/workbox-sw/v3/index.d.ts @@ -619,7 +619,8 @@ declare class Queue { readonly name: string; /** - * Stores the passed request into IndexedDB. The database used is workbox-background-sync and the object store name is the same as the name this instance was created with (to guarantee it's unique). + * Stores the passed request into IndexedDB. The database used is workbox-background-sync and + * the object store name is the same as the name this instance was created with (to guarantee it's unique). * @param {Request} request - The request object to store. * @returns {Promise} */ @@ -714,7 +715,8 @@ declare class Router { /** * Apply the routing rules to a FetchEvent object to get a Response from an appropriate Route's handler. * @param {FetchEvent} event - The event from a service worker's 'fetch' event listener. - * @returns {Promise?} A promise is returned if a registered route can handle the FetchEvent's request. If there is no matching route and there's no defaultHandler, undefined is returned. + * @returns {Promise?} A promise is returned if a registered route can handle the FetchEvent's request. + * If there is no matching route and there's no defaultHandler, undefined is returned. */ handleRequest (event: FetchEvent): Promise|undefined; @@ -1421,4 +1423,4 @@ declare class WorkboxNamespace { static skipWaiting (): void; } -export = WorkboxNamespace; \ No newline at end of file +export = WorkboxNamespace; diff --git a/types/workbox-sw/v3/workbox-sw-tests.ts b/types/workbox-sw/v3/workbox-sw-tests.ts index 4d8b04f09d..f8cdadabee 100644 --- a/types/workbox-sw/v3/workbox-sw-tests.ts +++ b/types/workbox-sw/v3/workbox-sw-tests.ts @@ -8,4 +8,4 @@ WorkboxSW.routing.registerRoute("/", WorkboxSW.strategies.networkFirst()); // $E // $ExpectError WorkboxSW.precaching.precacheAndRoute(/foo/); -WorkboxSW.precaching.precacheAndRoute(["some-resource.js"], {directoryIndex: "/"}); // $ExpectType void \ No newline at end of file +WorkboxSW.precaching.precacheAndRoute(["some-resource.js"], {directoryIndex: "/"}); // $ExpectType void