| 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 { warmStrategyCache } from './warmStrategyCache';
|
|---|
| 9 | import { registerRoute } from 'workbox-routing/registerRoute.js';
|
|---|
| 10 | import { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';
|
|---|
| 11 | import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';
|
|---|
| 12 | import './_version.js';
|
|---|
| 13 | /**
|
|---|
| 14 | * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files}
|
|---|
| 15 | *
|
|---|
| 16 | * @memberof workbox-recipes
|
|---|
| 17 | *
|
|---|
| 18 | * @param {Object} [options]
|
|---|
| 19 | * @param {string} [options.cacheName] Name for cache. Defaults to static-resources
|
|---|
| 20 | * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker';
|
|---|
| 21 | * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe
|
|---|
| 22 | * @param {string[]} [options.warmCache] Paths to call to use to warm this cache
|
|---|
| 23 | */
|
|---|
| 24 | function staticResourceCache(options = {}) {
|
|---|
| 25 | const defaultMatchCallback = ({ request }) => request.destination === 'style' ||
|
|---|
| 26 | request.destination === 'script' ||
|
|---|
| 27 | request.destination === 'worker';
|
|---|
| 28 | const cacheName = options.cacheName || 'static-resources';
|
|---|
| 29 | const matchCallback = options.matchCallback || defaultMatchCallback;
|
|---|
| 30 | const plugins = options.plugins || [];
|
|---|
| 31 | plugins.push(new CacheableResponsePlugin({
|
|---|
| 32 | statuses: [0, 200],
|
|---|
| 33 | }));
|
|---|
| 34 | const strategy = new StaleWhileRevalidate({
|
|---|
| 35 | cacheName,
|
|---|
| 36 | plugins,
|
|---|
| 37 | });
|
|---|
| 38 | registerRoute(matchCallback, strategy);
|
|---|
| 39 | // Warms the cache
|
|---|
| 40 | if (options.warmCache) {
|
|---|
| 41 | warmStrategyCache({ urls: options.warmCache, strategy });
|
|---|
| 42 | }
|
|---|
| 43 | }
|
|---|
| 44 | export { staticResourceCache };
|
|---|