1 | ;
|
2 | /*
|
3 | Copyright 2018 Google LLC
|
4 |
|
5 | Use of this source code is governed by an MIT-style
|
6 | license that can be found in the LICENSE file or at
|
7 | https://opensource.org/licenses/MIT.
|
8 | */
|
9 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
10 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
11 | };
|
12 | Object.defineProperty(exports, "__esModule", { value: true });
|
13 | exports.generateSW = void 0;
|
14 | const upath_1 = __importDefault(require("upath"));
|
15 | const get_file_manifest_entries_1 = require("./lib/get-file-manifest-entries");
|
16 | const rebase_path_1 = require("./lib/rebase-path");
|
17 | const validate_options_1 = require("./lib/validate-options");
|
18 | const write_sw_using_default_template_1 = require("./lib/write-sw-using-default-template");
|
19 | // eslint-disable-next-line jsdoc/newline-after-description
|
20 | /**
|
21 | * This method creates a list of URLs to precache, referred to as a "precache
|
22 | * manifest", based on the options you provide.
|
23 | *
|
24 | * It also takes in additional options that configures the service worker's
|
25 | * behavior, like any `runtimeCaching` rules it should use.
|
26 | *
|
27 | * Based on the precache manifest and the additional configuration, it writes
|
28 | * a ready-to-use service worker file to disk at `swDest`.
|
29 | *
|
30 | * @param {Object} config The configuration to use.
|
31 | *
|
32 | * @param {string} config.globDirectory The local directory you wish to match
|
33 | * `globPatterns` against. The path is relative to the current directory.
|
34 | *
|
35 | * @param {string} config.swDest The path and filename of the service worker file
|
36 | * that will be created by the build process, relative to the current working
|
37 | * directory. It must end in '.js'.
|
38 | *
|
39 | * @param {Array<module:workbox-build.ManifestEntry>} [config.additionalManifestEntries]
|
40 | * A list of entries to be precached, in addition to any entries that are
|
41 | * generated as part of the build configuration.
|
42 | *
|
43 | * @param {Array<string>} [config.babelPresetEnvTargets=['chrome >= 56']]
|
44 | * The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass to
|
45 | * `babel-preset-env` when transpiling the service worker bundle.
|
46 | *
|
47 | * @param {string} [config.cacheId] An optional ID to be prepended to cache
|
48 | * names. This is primarily useful for local development where multiple sites
|
49 | * may be served from the same `http://localhost:port` origin.
|
50 | *
|
51 | * @param {boolean} [config.cleanupOutdatedCaches=false] Whether or not Workbox
|
52 | * should attempt to identify and delete any precaches created by older,
|
53 | * incompatible versions.
|
54 | *
|
55 | * @param {boolean} [config.clientsClaim=false] Whether or not the service
|
56 | * worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)
|
57 | * any existing clients as soon as it activates.
|
58 | *
|
59 | * @param {string} [config.directoryIndex='index.html'] If a navigation request
|
60 | * for a URL ending in `/` fails to match a precached URL, this value will be
|
61 | * appended to the URL and that will be checked for a precache match. This
|
62 | * should be set to what your web server is using for its directory index.
|
63 | *
|
64 | * @param {RegExp} [config.dontCacheBustURLsMatching] Assets that match this will be
|
65 | * assumed to be uniquely versioned via their URL, and exempted from the normal
|
66 | * HTTP cache-busting that's done when populating the precache. While not
|
67 | * required, it's recommended that if your existing build process already
|
68 | * inserts a `[hash]` value into each filename, you provide a RegExp that will
|
69 | * detect that, as it will reduce the bandwidth consumed when precaching.
|
70 | *
|
71 | * @param {boolean} [config.globFollow=true] Determines whether or not symlinks
|
72 | * are followed when generating the precache manifest. For more information, see
|
73 | * the definition of `follow` in the `glob`
|
74 | * [documentation](https://github.com/isaacs/node-glob#options).
|
75 | *
|
76 | * @param {Array<string>} [config.globIgnores=['node_modules/**']]
|
77 | * A set of patterns matching files to always exclude when generating the
|
78 | * precache manifest. For more information, see the definition of `ignore` in the `glob`
|
79 | * [documentation](https://github.com/isaacs/node-glob#options).
|
80 | *
|
81 | * @param {Array<string>} [config.globPatterns=['**.{js,css,html}']]
|
82 | * Files matching any of these patterns will be included in the precache
|
83 | * manifest. For more information, see the
|
84 | * [`glob` primer](https://github.com/isaacs/node-glob#glob-primer).
|
85 | *
|
86 | * @param {boolean} [config.globStrict=true] If true, an error reading a directory when
|
87 | * generating a precache manifest will cause the build to fail. If false, the
|
88 | * problematic directory will be skipped. For more information, see the
|
89 | * definition of `strict` in the `glob`
|
90 | * [documentation](https://github.com/isaacs/node-glob#options).
|
91 | *
|
92 | * @param {Array<RegExp>} [config.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]]
|
93 | * Any search parameter names that match against one of the RegExp in this array
|
94 | * will be removed before looking for a precache match. This is useful if your
|
95 | * users might request URLs that contain, for example, URL parameters used to
|
96 | * track the source of the traffic.
|
97 | *
|
98 | * @param {Array<string>} [config.importScripts] A list of JavaScript files that
|
99 | * should be passed to [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)
|
100 | * inside the generated service worker file. This is useful when you want to
|
101 | * let Workbox create your top-level service worker file, but want to include
|
102 | * some additional code, such as a push event listener.
|
103 | *
|
104 | * @param {boolean} [config.inlineWorkboxRuntime=false] Whether the runtime code
|
105 | * for the Workbox library should be included in the top-level service worker,
|
106 | * or split into a separate file that needs to be deployed alongside the service
|
107 | * worker. Keeping the runtime separate means that users will not have to
|
108 | * re-download the Workbox code each time your top-level service worker changes.
|
109 | *
|
110 | * @param {Array<module:workbox-build.ManifestTransform>} [config.manifestTransforms] One or more
|
111 | * functions which will be applied sequentially against the generated manifest.
|
112 | * If `modifyURLPrefix` or `dontCacheBustURLsMatching` are also specified, their
|
113 | * corresponding transformations will be applied first.
|
114 | *
|
115 | * @param {number} [config.maximumFileSizeToCacheInBytes=2097152] This value can be
|
116 | * used to determine the maximum size of files that will be precached. This
|
117 | * prevents you from inadvertently precaching very large files that might have
|
118 | * accidentally matched one of your patterns.
|
119 | *
|
120 | * @param {string} [config.mode='production'] If set to 'production', then an
|
121 | * optimized service worker bundle that excludes debugging info will be
|
122 | * produced. If not explicitly configured here, the `process.env.NODE_ENV` value
|
123 | * will be used, and failing that, it will fall back to `'production'`.
|
124 | *
|
125 | * @param {object<string, string>} [config.modifyURLPrefix] A mapping of prefixes
|
126 | * that, if present in an entry in the precache manifest, will be replaced with
|
127 | * the corresponding value. This can be used to, for example, remove or add a
|
128 | * path prefix from a manifest entry if your web hosting setup doesn't match
|
129 | * your local filesystem setup. As an alternative with more flexibility, you can
|
130 | * use the `manifestTransforms` option and provide a function that modifies the
|
131 | * entries in the manifest using whatever logic you provide.
|
132 | *
|
133 | * @param {string} [config.navigateFallback] If specified, all
|
134 | * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)
|
135 | * for URLs that aren't precached will be fulfilled with the HTML at the URL
|
136 | * provided. You must pass in the URL of an HTML document that is listed in your
|
137 | * precache manifest. This is meant to be used in a Single Page App scenario, in
|
138 | * which you want all navigations to use common [App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).
|
139 | *
|
140 | * @param {Array<RegExp>} [config.navigateFallbackDenylist] An optional array
|
141 | * of regular expressions that restricts which URLs the configured
|
142 | * `navigateFallback` behavior applies to. This is useful if only a subset of
|
143 | * your site's URLs should be treated as being part of a
|
144 | * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). If
|
145 | * both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
|
146 | * configured, the denylist takes precedent.
|
147 | *
|
148 | * @param {Array<RegExp>} [config.navigateFallbackAllowlist] An optional array
|
149 | * of regular expressions that restricts which URLs the configured
|
150 | * `navigateFallback` behavior applies to. This is useful if only a subset of
|
151 | * your site's URLs should be treated as being part of a
|
152 | * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). If
|
153 | * both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
|
154 | * configured, the denylist takes precedent.
|
155 | *
|
156 | * @param {boolean} [config.navigationPreload=false] Whether or not to enable
|
157 | * [navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)
|
158 | * in the generated service worker. When set to true, you must also use
|
159 | * `runtimeCaching` to set up an appropriate response strategy that will match
|
160 | * navigation requests, and make use of the preloaded response.
|
161 | *
|
162 | * @param {boolean|Object} [config.offlineGoogleAnalytics=false] Controls
|
163 | * whether or not to include support for
|
164 | * [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).
|
165 | * When `true`, the call to `workbox-google-analytics`'s `initialize()` will be
|
166 | * added to your generated service worker. When set to an `Object`, that object
|
167 | * will be passed in to the `initialize()` call, allowing you to customize the
|
168 | * behavior.
|
169 | *
|
170 | * @param {Array<RuntimeCachingEntry>} [config.runtimeCaching]
|
171 | *
|
172 | * @param {boolean} [config.skipWaiting=false] Whether to add an
|
173 | * unconditional call to [`skipWaiting()`]{@link module:workbox-core.skipWaiting}
|
174 | * to the generated service worker. If `false`, then a `message` listener will
|
175 | * be added instead, allowing you to conditionally call `skipWaiting()` by posting
|
176 | * a message containing {type: 'SKIP_WAITING'}.
|
177 | *
|
178 | * @param {boolean} [config.sourcemap=true] Whether to create a sourcemap
|
179 | * for the generated service worker files.
|
180 | *
|
181 | * @param {Object} [config.templatedURLs] If a URL is rendered based on some
|
182 | * server-side logic, its contents may depend on multiple files or on some other
|
183 | * unique string value. The keys in this object are server-rendered URLs. If the
|
184 | * values are an array of strings, they will be interpreted as `glob` patterns,
|
185 | * and the contents of any files matching the patterns will be used to uniquely
|
186 | * version the URL. If used with a single string, it will be interpreted as
|
187 | * unique versioning information that you've generated for a given URL.
|
188 | *
|
189 | * @return {Promise<{count: number, filePaths: Array<string>, size: number, warnings: Array<string>}>}
|
190 | * A promise that resolves once the service worker and related files
|
191 | * (indicated by `filePaths`) has been written to `swDest`. The `size` property
|
192 | * contains the aggregate size of all the precached entries, in bytes, and the
|
193 | * `count` property contains the total number of precached entries. Any
|
194 | * non-fatal warning messages will be returned via `warnings`.
|
195 | *
|
196 | * @memberof module:workbox-build
|
197 | */
|
198 | async function generateSW(config) {
|
199 | const options = validate_options_1.validateGenerateSWOptions(config);
|
200 | let entriesResult;
|
201 | if (options.globDirectory) {
|
202 | // Make sure we leave swDest out of the precache manifest.
|
203 | options.globIgnores.push(rebase_path_1.rebasePath({
|
204 | baseDirectory: options.globDirectory,
|
205 | file: options.swDest,
|
206 | }));
|
207 | // If we create an extra external runtime file, ignore that, too.
|
208 | // See https://rollupjs.org/guide/en/#outputchunkfilenames for naming.
|
209 | if (!options.inlineWorkboxRuntime) {
|
210 | const swDestDir = upath_1.default.dirname(options.swDest);
|
211 | const workboxRuntimeFile = upath_1.default.join(swDestDir, 'workbox-*.js');
|
212 | options.globIgnores.push(rebase_path_1.rebasePath({
|
213 | baseDirectory: options.globDirectory,
|
214 | file: workboxRuntimeFile,
|
215 | }));
|
216 | }
|
217 | // We've previously asserted that options.globDirectory is set, so this
|
218 | // should be a safe cast.
|
219 | entriesResult = await get_file_manifest_entries_1.getFileManifestEntries(options);
|
220 | }
|
221 | else {
|
222 | entriesResult = {
|
223 | count: 0,
|
224 | manifestEntries: [],
|
225 | size: 0,
|
226 | warnings: [],
|
227 | };
|
228 | }
|
229 | const filePaths = await write_sw_using_default_template_1.writeSWUsingDefaultTemplate(Object.assign({
|
230 | manifestEntries: entriesResult.manifestEntries,
|
231 | }, options));
|
232 | return {
|
233 | filePaths,
|
234 | count: entriesResult.count,
|
235 | size: entriesResult.size,
|
236 | warnings: entriesResult.warnings,
|
237 | };
|
238 | }
|
239 | exports.generateSW = generateSW;
|