1 | /*
|
2 | Copyright 2018 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 |
|
9 | import {RawSourceMap} from 'source-map';
|
10 | import assert from 'assert';
|
11 | import fse from 'fs-extra';
|
12 | import sourceMapURL from 'source-map-url';
|
13 | import stringify from 'fast-json-stable-stringify';
|
14 | import upath from 'upath';
|
15 |
|
16 | import {BuildResult} from './types';
|
17 | import {errors} from './lib/errors';
|
18 | import {escapeRegExp} from './lib/escape-regexp';
|
19 | import {getFileManifestEntries} from './lib/get-file-manifest-entries';
|
20 | import {rebasePath} from './lib/rebase-path';
|
21 | import {replaceAndUpdateSourceMap} from './lib/replace-and-update-source-map';
|
22 | import {validateInjectManifestOptions} from './lib/validate-options';
|
23 |
|
24 | // eslint-disable-next-line jsdoc/newline-after-description
|
25 | /**
|
26 | * This method creates a list of URLs to precache, referred to as a "precache
|
27 | * manifest", based on the options you provide.
|
28 | *
|
29 | * The manifest is injected into the `swSrc` file, and the placeholder string
|
30 | * `injectionPoint` determines where in the file the manifest should go.
|
31 | *
|
32 | * The final service worker file, with the manifest injected, is written to
|
33 | * disk at `swDest`.
|
34 | *
|
35 | * @param {Object} config The configuration to use.
|
36 | *
|
37 | * @param {string} config.globDirectory The local directory you wish to match
|
38 | * `globPatterns` against. The path is relative to the current directory.
|
39 | *
|
40 | * @param {string} config.swDest The path and filename of the service worker file
|
41 | * that will be created by the build process, relative to the current working
|
42 | * directory. It must end in '.js'.
|
43 | *
|
44 | * @param {string} config.swSrc The path and filename of the service worker file
|
45 | * that will be read during the build process, relative to the current working
|
46 | * directory.
|
47 | *
|
48 | * @param {Array<module:workbox-build.ManifestEntry>} [config.additionalManifestEntries]
|
49 | * A list of entries to be precached, in addition to any entries that are
|
50 | * generated as part of the build configuration.
|
51 | *
|
52 | * @param {RegExp} [config.dontCacheBustURLsMatching] Assets that match this will be
|
53 | * assumed to be uniquely versioned via their URL, and exempted from the normal
|
54 | * HTTP cache-busting that's done when populating the precache. While not
|
55 | * required, it's recommended that if your existing build process already
|
56 | * inserts a `[hash]` value into each filename, you provide a RegExp that will
|
57 | * detect that, as it will reduce the bandwidth consumed when precaching.
|
58 | *
|
59 | * @param {boolean} [config.globFollow=true] Determines whether or not symlinks
|
60 | * are followed when generating the precache manifest. For more information, see
|
61 | * the definition of `follow` in the `glob`
|
62 | * [documentation](https://github.com/isaacs/node-glob#options).
|
63 | *
|
64 | * @param {Array<string>} [config.globIgnores=['node_modules/**']]
|
65 | * A set of patterns matching files to always exclude when generating the
|
66 | * precache manifest. For more information, see the definition of `ignore` in the `glob`
|
67 | * [documentation](https://github.com/isaacs/node-glob#options).
|
68 | *
|
69 | * @param {Array<string>} [config.globPatterns=['**.{js,css,html}']]
|
70 | * Files matching any of these patterns will be included in the precache
|
71 | * manifest. For more information, see the
|
72 | * [`glob` primer](https://github.com/isaacs/node-glob#glob-primer).
|
73 | *
|
74 | * @param {boolean} [config.globStrict=true] If true, an error reading a directory when
|
75 | * generating a precache manifest will cause the build to fail. If false, the
|
76 | * problematic directory will be skipped. For more information, see the
|
77 | * definition of `strict` in the `glob`
|
78 | * [documentation](https://github.com/isaacs/node-glob#options).
|
79 | *
|
80 | * @param {string} [config.injectionPoint='self.__WB_MANIFEST'] The string to
|
81 | * find inside of the `swSrc` file. Once found, it will be replaced by the
|
82 | * generated precache manifest.
|
83 | *
|
84 | * @param {Array<module:workbox-build.ManifestTransform>} [config.manifestTransforms] One or more
|
85 | * functions which will be applied sequentially against the generated manifest.
|
86 | * If `modifyURLPrefix` or `dontCacheBustURLsMatching` are also specified, their
|
87 | * corresponding transformations will be applied first.
|
88 | *
|
89 | * @param {number} [config.maximumFileSizeToCacheInBytes=2097152] This value can be
|
90 | * used to determine the maximum size of files that will be precached. This
|
91 | * prevents you from inadvertently precaching very large files that might have
|
92 | * accidentally matched one of your patterns.
|
93 | *
|
94 | * @param {object<string, string>} [config.modifyURLPrefix] A mapping of prefixes
|
95 | * that, if present in an entry in the precache manifest, will be replaced with
|
96 | * the corresponding value. This can be used to, for example, remove or add a
|
97 | * path prefix from a manifest entry if your web hosting setup doesn't match
|
98 | * your local filesystem setup. As an alternative with more flexibility, you can
|
99 | * use the `manifestTransforms` option and provide a function that modifies the
|
100 | * entries in the manifest using whatever logic you provide.
|
101 | *
|
102 | * @param {Object} [config.templatedURLs] If a URL is rendered based on some
|
103 | * server-side logic, its contents may depend on multiple files or on some other
|
104 | * unique string value. The keys in this object are server-rendered URLs. If the
|
105 | * values are an array of strings, they will be interpreted as `glob` patterns,
|
106 | * and the contents of any files matching the patterns will be used to uniquely
|
107 | * version the URL. If used with a single string, it will be interpreted as
|
108 | * unique versioning information that you've generated for a given URL.
|
109 | *
|
110 | * @return {Promise<{count: number, filePaths: Array<string>, size: number, warnings: Array<string>}>}
|
111 | * A promise that resolves once the service worker and related files
|
112 | * (indicated by `filePaths`) has been written to `swDest`. The `size` property
|
113 | * contains the aggregate size of all the precached entries, in bytes, and the
|
114 | * `count` property contains the total number of precached entries. Any
|
115 | * non-fatal warning messages will be returned via `warnings`.
|
116 | *
|
117 | * @memberof module:workbox-build
|
118 | */
|
119 | export async function injectManifest(config: unknown): Promise<BuildResult> {
|
120 | const options = validateInjectManifestOptions(config);
|
121 |
|
122 | // Make sure we leave swSrc and swDest out of the precache manifest.
|
123 | for (const file of [options.swSrc, options.swDest]) {
|
124 | options.globIgnores!.push(rebasePath({
|
125 | file,
|
126 | baseDirectory: options.globDirectory,
|
127 | }));
|
128 | }
|
129 |
|
130 | const globalRegexp = new RegExp(escapeRegExp(options.injectionPoint!), 'g');
|
131 |
|
132 | const {count, size, manifestEntries, warnings} =
|
133 | await getFileManifestEntries(options);
|
134 | let swFileContents: string;
|
135 | try {
|
136 | swFileContents = await fse.readFile(options.swSrc, 'utf8');
|
137 | } catch (error) {
|
138 | throw new Error(`${errors['invalid-sw-src']} ${error instanceof Error && error.message ? error.message : ''}`);
|
139 | }
|
140 |
|
141 | const injectionResults = swFileContents.match(globalRegexp);
|
142 | // See https://github.com/GoogleChrome/workbox/issues/2230
|
143 | const injectionPoint = options.injectionPoint ? options.injectionPoint : '';
|
144 | if (!injectionResults) {
|
145 | if (upath.resolve(options.swSrc) === upath.resolve(options.swDest)) {
|
146 | throw new Error(`${errors['same-src-and-dest']} ${injectionPoint}`);
|
147 | }
|
148 | throw new Error(`${errors['injection-point-not-found']} ${injectionPoint}`);
|
149 | }
|
150 |
|
151 | assert(injectionResults.length === 1, `${errors['multiple-injection-points']} ${injectionPoint}`);
|
152 |
|
153 | const manifestString = stringify(manifestEntries);
|
154 | const filesToWrite: {[key: string]: string} = {};
|
155 | // sourceMapURL returns value type any and could be null.
|
156 | // url is checked before it is used later.
|
157 | const url: string = sourceMapURL.getFrom(swFileContents); // eslint-disable-line
|
158 | // If our swSrc file contains a sourcemap, we would invalidate that
|
159 | // mapping if we just replaced injectionPoint with the stringified manifest.
|
160 | // Instead, we need to update the swDest contents as well as the sourcemap
|
161 | // (assuming it's a real file, not a data: URL) at the same time.
|
162 | // See https://github.com/GoogleChrome/workbox/issues/2235
|
163 | // and https://github.com/GoogleChrome/workbox/issues/2648
|
164 | if (url && !url.startsWith('data:')) {
|
165 | const sourcemapSrcPath = upath.resolve(upath.dirname(options.swSrc), url);
|
166 | const sourcemapDestPath = upath.resolve(upath.dirname(options.swDest), url);
|
167 |
|
168 | let originalMap: RawSourceMap;
|
169 | try {
|
170 | // readJSON returns Promise<any>.
|
171 | // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
172 | originalMap = await fse.readJSON(sourcemapSrcPath, {encoding: 'utf8'});
|
173 | } catch (error) {
|
174 | throw new Error(`${errors['cant-find-sourcemap']} ${error instanceof Error && error.message ? error.message : ''}`);
|
175 | }
|
176 |
|
177 | const {map, source} = await replaceAndUpdateSourceMap({
|
178 | originalMap,
|
179 | jsFilename: upath.basename(options.swDest),
|
180 | originalSource: swFileContents,
|
181 | replaceString: manifestString,
|
182 | searchString: options.injectionPoint!,
|
183 | });
|
184 |
|
185 | filesToWrite[options.swDest] = source;
|
186 | filesToWrite[sourcemapDestPath] = map;
|
187 | } else {
|
188 | // If there's no sourcemap associated with swSrc, a simple string
|
189 | // replacement will suffice.
|
190 | filesToWrite[options.swDest] = swFileContents.replace(
|
191 | globalRegexp, manifestString);
|
192 | }
|
193 |
|
194 | for (const [file, contents] of Object.entries(filesToWrite)) {
|
195 | try {
|
196 | await fse.mkdirp(upath.dirname(file));
|
197 | } catch (error) {
|
198 | throw new Error(errors['unable-to-make-sw-directory'] +
|
199 | ` '${error instanceof Error && error.message ? error.message : ''}'`);
|
200 | }
|
201 |
|
202 | await fse.writeFile(file, contents);
|
203 | }
|
204 |
|
205 | return {
|
206 | count,
|
207 | size,
|
208 | warnings,
|
209 | // Use upath.resolve() to make all the paths absolute.
|
210 | filePaths: Object.keys(filesToWrite).map((f) => upath.resolve(f)),
|
211 | };
|
212 | }
|