| 1 | /*
|
|---|
| 2 | Copyright 2020 Google LLC
|
|---|
| 3 |
|
|---|
| 4 | Use of this source code is governed by an MIT-style
|
|---|
| 5 | license that can be found in the LICENSE file or at
|
|---|
| 6 | https://opensource.org/licenses/MIT.
|
|---|
| 7 | */
|
|---|
| 8 | import { cacheNames } from 'workbox-core/_private/cacheNames.js';
|
|---|
| 9 | import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
|
|---|
| 10 | import { logger } from 'workbox-core/_private/logger.js';
|
|---|
| 11 | import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';
|
|---|
| 12 | import { StrategyHandler } from './StrategyHandler.js';
|
|---|
| 13 | import './_version.js';
|
|---|
| 14 | /**
|
|---|
| 15 | * An abstract base class that all other strategy classes must extend from:
|
|---|
| 16 | *
|
|---|
| 17 | * @memberof workbox-strategies
|
|---|
| 18 | */
|
|---|
| 19 | class Strategy {
|
|---|
| 20 | /**
|
|---|
| 21 | * Creates a new instance of the strategy and sets all documented option
|
|---|
| 22 | * properties as public instance properties.
|
|---|
| 23 | *
|
|---|
| 24 | * Note: if a custom strategy class extends the base Strategy class and does
|
|---|
| 25 | * not need more than these properties, it does not need to define its own
|
|---|
| 26 | * constructor.
|
|---|
| 27 | *
|
|---|
| 28 | * @param {Object} [options]
|
|---|
| 29 | * @param {string} [options.cacheName] Cache name to store and retrieve
|
|---|
| 30 | * requests. Defaults to the cache names provided by
|
|---|
| 31 | * {@link workbox-core.cacheNames}.
|
|---|
| 32 | * @param {Array<Object>} [options.plugins] [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
|
|---|
| 33 | * to use in conjunction with this caching strategy.
|
|---|
| 34 | * @param {Object} [options.fetchOptions] Values passed along to the
|
|---|
| 35 | * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
|
|---|
| 36 | * of [non-navigation](https://github.com/GoogleChrome/workbox/issues/1796)
|
|---|
| 37 | * `fetch()` requests made by this strategy.
|
|---|
| 38 | * @param {Object} [options.matchOptions] The
|
|---|
| 39 | * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
|
|---|
| 40 | * for any `cache.match()` or `cache.put()` calls made by this strategy.
|
|---|
| 41 | */
|
|---|
| 42 | constructor(options = {}) {
|
|---|
| 43 | /**
|
|---|
| 44 | * Cache name to store and retrieve
|
|---|
| 45 | * requests. Defaults to the cache names provided by
|
|---|
| 46 | * {@link workbox-core.cacheNames}.
|
|---|
| 47 | *
|
|---|
| 48 | * @type {string}
|
|---|
| 49 | */
|
|---|
| 50 | this.cacheName = cacheNames.getRuntimeName(options.cacheName);
|
|---|
| 51 | /**
|
|---|
| 52 | * The list
|
|---|
| 53 | * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
|
|---|
| 54 | * used by this strategy.
|
|---|
| 55 | *
|
|---|
| 56 | * @type {Array<Object>}
|
|---|
| 57 | */
|
|---|
| 58 | this.plugins = options.plugins || [];
|
|---|
| 59 | /**
|
|---|
| 60 | * Values passed along to the
|
|---|
| 61 | * [`init`]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters}
|
|---|
| 62 | * of all fetch() requests made by this strategy.
|
|---|
| 63 | *
|
|---|
| 64 | * @type {Object}
|
|---|
| 65 | */
|
|---|
| 66 | this.fetchOptions = options.fetchOptions;
|
|---|
| 67 | /**
|
|---|
| 68 | * The
|
|---|
| 69 | * [`CacheQueryOptions`]{@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions}
|
|---|
| 70 | * for any `cache.match()` or `cache.put()` calls made by this strategy.
|
|---|
| 71 | *
|
|---|
| 72 | * @type {Object}
|
|---|
| 73 | */
|
|---|
| 74 | this.matchOptions = options.matchOptions;
|
|---|
| 75 | }
|
|---|
| 76 | /**
|
|---|
| 77 | * Perform a request strategy and returns a `Promise` that will resolve with
|
|---|
| 78 | * a `Response`, invoking all relevant plugin callbacks.
|
|---|
| 79 | *
|
|---|
| 80 | * When a strategy instance is registered with a Workbox
|
|---|
| 81 | * {@link workbox-routing.Route}, this method is automatically
|
|---|
| 82 | * called when the route matches.
|
|---|
| 83 | *
|
|---|
| 84 | * Alternatively, this method can be used in a standalone `FetchEvent`
|
|---|
| 85 | * listener by passing it to `event.respondWith()`.
|
|---|
| 86 | *
|
|---|
| 87 | * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
|
|---|
| 88 | * properties listed below.
|
|---|
| 89 | * @param {Request|string} options.request A request to run this strategy for.
|
|---|
| 90 | * @param {ExtendableEvent} options.event The event associated with the
|
|---|
| 91 | * request.
|
|---|
| 92 | * @param {URL} [options.url]
|
|---|
| 93 | * @param {*} [options.params]
|
|---|
| 94 | */
|
|---|
| 95 | handle(options) {
|
|---|
| 96 | const [responseDone] = this.handleAll(options);
|
|---|
| 97 | return responseDone;
|
|---|
| 98 | }
|
|---|
| 99 | /**
|
|---|
| 100 | * Similar to {@link workbox-strategies.Strategy~handle}, but
|
|---|
| 101 | * instead of just returning a `Promise` that resolves to a `Response` it
|
|---|
| 102 | * it will return an tuple of `[response, done]` promises, where the former
|
|---|
| 103 | * (`response`) is equivalent to what `handle()` returns, and the latter is a
|
|---|
| 104 | * Promise that will resolve once any promises that were added to
|
|---|
| 105 | * `event.waitUntil()` as part of performing the strategy have completed.
|
|---|
| 106 | *
|
|---|
| 107 | * You can await the `done` promise to ensure any extra work performed by
|
|---|
| 108 | * the strategy (usually caching responses) completes successfully.
|
|---|
| 109 | *
|
|---|
| 110 | * @param {FetchEvent|Object} options A `FetchEvent` or an object with the
|
|---|
| 111 | * properties listed below.
|
|---|
| 112 | * @param {Request|string} options.request A request to run this strategy for.
|
|---|
| 113 | * @param {ExtendableEvent} options.event The event associated with the
|
|---|
| 114 | * request.
|
|---|
| 115 | * @param {URL} [options.url]
|
|---|
| 116 | * @param {*} [options.params]
|
|---|
| 117 | * @return {Array<Promise>} A tuple of [response, done]
|
|---|
| 118 | * promises that can be used to determine when the response resolves as
|
|---|
| 119 | * well as when the handler has completed all its work.
|
|---|
| 120 | */
|
|---|
| 121 | handleAll(options) {
|
|---|
| 122 | // Allow for flexible options to be passed.
|
|---|
| 123 | if (options instanceof FetchEvent) {
|
|---|
| 124 | options = {
|
|---|
| 125 | event: options,
|
|---|
| 126 | request: options.request,
|
|---|
| 127 | };
|
|---|
| 128 | }
|
|---|
| 129 | const event = options.event;
|
|---|
| 130 | const request = typeof options.request === 'string'
|
|---|
| 131 | ? new Request(options.request)
|
|---|
| 132 | : options.request;
|
|---|
| 133 | const params = 'params' in options ? options.params : undefined;
|
|---|
| 134 | const handler = new StrategyHandler(this, { event, request, params });
|
|---|
| 135 | const responseDone = this._getResponse(handler, request, event);
|
|---|
| 136 | const handlerDone = this._awaitComplete(responseDone, handler, request, event);
|
|---|
| 137 | // Return an array of promises, suitable for use with Promise.all().
|
|---|
| 138 | return [responseDone, handlerDone];
|
|---|
| 139 | }
|
|---|
| 140 | async _getResponse(handler, request, event) {
|
|---|
| 141 | await handler.runCallbacks('handlerWillStart', { event, request });
|
|---|
| 142 | let response = undefined;
|
|---|
| 143 | try {
|
|---|
| 144 | response = await this._handle(request, handler);
|
|---|
| 145 | // The "official" Strategy subclasses all throw this error automatically,
|
|---|
| 146 | // but in case a third-party Strategy doesn't, ensure that we have a
|
|---|
| 147 | // consistent failure when there's no response or an error response.
|
|---|
| 148 | if (!response || response.type === 'error') {
|
|---|
| 149 | throw new WorkboxError('no-response', { url: request.url });
|
|---|
| 150 | }
|
|---|
| 151 | }
|
|---|
| 152 | catch (error) {
|
|---|
| 153 | if (error instanceof Error) {
|
|---|
| 154 | for (const callback of handler.iterateCallbacks('handlerDidError')) {
|
|---|
| 155 | response = await callback({ error, event, request });
|
|---|
| 156 | if (response) {
|
|---|
| 157 | break;
|
|---|
| 158 | }
|
|---|
| 159 | }
|
|---|
| 160 | }
|
|---|
| 161 | if (!response) {
|
|---|
| 162 | throw error;
|
|---|
| 163 | }
|
|---|
| 164 | else if (process.env.NODE_ENV !== 'production') {
|
|---|
| 165 | logger.log(`While responding to '${getFriendlyURL(request.url)}', ` +
|
|---|
| 166 | `an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` +
|
|---|
| 167 | `a handlerDidError plugin.`);
|
|---|
| 168 | }
|
|---|
| 169 | }
|
|---|
| 170 | for (const callback of handler.iterateCallbacks('handlerWillRespond')) {
|
|---|
| 171 | response = await callback({ event, request, response });
|
|---|
| 172 | }
|
|---|
| 173 | return response;
|
|---|
| 174 | }
|
|---|
| 175 | async _awaitComplete(responseDone, handler, request, event) {
|
|---|
| 176 | let response;
|
|---|
| 177 | let error;
|
|---|
| 178 | try {
|
|---|
| 179 | response = await responseDone;
|
|---|
| 180 | }
|
|---|
| 181 | catch (error) {
|
|---|
| 182 | // Ignore errors, as response errors should be caught via the `response`
|
|---|
| 183 | // promise above. The `done` promise will only throw for errors in
|
|---|
| 184 | // promises passed to `handler.waitUntil()`.
|
|---|
| 185 | }
|
|---|
| 186 | try {
|
|---|
| 187 | await handler.runCallbacks('handlerDidRespond', {
|
|---|
| 188 | event,
|
|---|
| 189 | request,
|
|---|
| 190 | response,
|
|---|
| 191 | });
|
|---|
| 192 | await handler.doneWaiting();
|
|---|
| 193 | }
|
|---|
| 194 | catch (waitUntilError) {
|
|---|
| 195 | if (waitUntilError instanceof Error) {
|
|---|
| 196 | error = waitUntilError;
|
|---|
| 197 | }
|
|---|
| 198 | }
|
|---|
| 199 | await handler.runCallbacks('handlerDidComplete', {
|
|---|
| 200 | event,
|
|---|
| 201 | request,
|
|---|
| 202 | response,
|
|---|
| 203 | error: error,
|
|---|
| 204 | });
|
|---|
| 205 | handler.destroy();
|
|---|
| 206 | if (error) {
|
|---|
| 207 | throw error;
|
|---|
| 208 | }
|
|---|
| 209 | }
|
|---|
| 210 | }
|
|---|
| 211 | export { Strategy };
|
|---|
| 212 | /**
|
|---|
| 213 | * Classes extending the `Strategy` based class should implement this method,
|
|---|
| 214 | * and leverage the {@link workbox-strategies.StrategyHandler}
|
|---|
| 215 | * arg to perform all fetching and cache logic, which will ensure all relevant
|
|---|
| 216 | * cache, cache options, fetch options and plugins are used (per the current
|
|---|
| 217 | * strategy instance).
|
|---|
| 218 | *
|
|---|
| 219 | * @name _handle
|
|---|
| 220 | * @instance
|
|---|
| 221 | * @abstract
|
|---|
| 222 | * @function
|
|---|
| 223 | * @param {Request} request
|
|---|
| 224 | * @param {workbox-strategies.StrategyHandler} handler
|
|---|
| 225 | * @return {Promise<Response>}
|
|---|
| 226 | *
|
|---|
| 227 | * @memberof workbox-strategies.Strategy
|
|---|
| 228 | */
|
|---|