UNPKG

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