inject-manifest.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. "use strict";
  2. /*
  3. Copyright 2018 Google LLC
  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. const assert = require('assert');
  9. const fse = require('fs-extra');
  10. const sourceMapURL = require('source-map-url');
  11. const stringify = require('fast-json-stable-stringify');
  12. const upath = require('upath');
  13. const errors = require('./lib/errors');
  14. const escapeRegexp = require('./lib/escape-regexp');
  15. const getFileManifestEntries = require('./lib/get-file-manifest-entries');
  16. const injectManifestSchema = require('./options/schema/inject-manifest');
  17. const rebasePath = require('./lib/rebase-path');
  18. const replaceAndUpdateSourceMap = require('./lib/replace-and-update-source-map');
  19. const validate = require('./lib/validate-options'); // 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. * The manifest is injected into the `swSrc` file, and the placeholder string
  25. * `injectionPoint` determines where in the file the manifest should go.
  26. *
  27. * The final service worker file, with the manifest injected, is written to
  28. * 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 {string} config.swSrc The path and filename of the service worker file
  40. * that will be read during the build process, relative to the current working
  41. * directory.
  42. *
  43. * @param {Array<module:workbox-build.ManifestEntry>} [config.additionalManifestEntries]
  44. * A list of entries to be precached, in addition to any entries that are
  45. * generated as part of the build configuration.
  46. *
  47. * @param {RegExp} [config.dontCacheBustURLsMatching] Assets that match this will be
  48. * assumed to be uniquely versioned via their URL, and exempted from the normal
  49. * HTTP cache-busting that's done when populating the precache. While not
  50. * required, it's recommended that if your existing build process already
  51. * inserts a `[hash]` value into each filename, you provide a RegExp that will
  52. * detect that, as it will reduce the bandwidth consumed when precaching.
  53. *
  54. * @param {boolean} [config.globFollow=true] Determines whether or not symlinks
  55. * are followed when generating the precache manifest. For more information, see
  56. * the definition of `follow` in the `glob`
  57. * [documentation](https://github.com/isaacs/node-glob#options).
  58. *
  59. * @param {Array<string>} [config.globIgnores=['node_modules/**']]
  60. * A set of patterns matching files to always exclude when generating the
  61. * precache manifest. For more information, see the definition of `ignore` in the `glob`
  62. * [documentation](https://github.com/isaacs/node-glob#options).
  63. *
  64. * @param {Array<string>} [config.globPatterns=['**.{js,css,html}']]
  65. * Files matching any of these patterns will be included in the precache
  66. * manifest. For more information, see the
  67. * [`glob` primer](https://github.com/isaacs/node-glob#glob-primer).
  68. *
  69. * @param {boolean} [config.globStrict=true] If true, an error reading a directory when
  70. * generating a precache manifest will cause the build to fail. If false, the
  71. * problematic directory will be skipped. For more information, see the
  72. * definition of `strict` in the `glob`
  73. * [documentation](https://github.com/isaacs/node-glob#options).
  74. *
  75. * @param {string} [config.injectionPoint='self.__WB_MANIFEST'] The string to
  76. * find inside of the `swSrc` file. Once found, it will be replaced by the
  77. * generated precache manifest.
  78. *
  79. * @param {Array<module:workbox-build.ManifestTransform>} [config.manifestTransforms] One or more
  80. * functions which will be applied sequentially against the generated manifest.
  81. * If `modifyURLPrefix` or `dontCacheBustURLsMatching` are also specified, their
  82. * corresponding transformations will be applied first.
  83. *
  84. * @param {number} [config.maximumFileSizeToCacheInBytes=2097152] This value can be
  85. * used to determine the maximum size of files that will be precached. This
  86. * prevents you from inadvertently precaching very large files that might have
  87. * accidentally matched one of your patterns.
  88. *
  89. * @param {string} [config.mode='production'] If set to 'production', then an
  90. * optimized service worker bundle that excludes debugging info will be
  91. * produced. If not explicitly configured here, the `process.env.NODE_ENV` value
  92. * will be used, and failing that, it will fall back to `'production'`.
  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. async function injectManifest(config) {
  120. const options = validate(config, injectManifestSchema); // Make sure we leave swSrc and swDest out of the precache manifest.
  121. for (const file of [options.swSrc, options.swDest]) {
  122. options.globIgnores.push(rebasePath({
  123. file,
  124. baseDirectory: options.globDirectory
  125. }));
  126. }
  127. const globalRegexp = new RegExp(escapeRegexp(options.injectionPoint), 'g');
  128. const {
  129. count,
  130. size,
  131. manifestEntries,
  132. warnings
  133. } = await getFileManifestEntries(options);
  134. let swFileContents;
  135. try {
  136. swFileContents = await fse.readFile(options.swSrc, 'utf8');
  137. } catch (error) {
  138. throw new Error(`${errors['invalid-sw-src']} ${error.message}`);
  139. }
  140. const injectionResults = swFileContents.match(globalRegexp);
  141. if (!injectionResults) {
  142. // See https://github.com/GoogleChrome/workbox/issues/2230
  143. if (upath.resolve(options.swSrc) === upath.resolve(options.swDest)) {
  144. throw new Error(errors['same-src-and-dest'] + ' ' + options.injectionPoint);
  145. }
  146. throw new Error(errors['injection-point-not-found'] + ' ' + options.injectionPoint);
  147. }
  148. assert(injectionResults.length === 1, errors['multiple-injection-points'] + options.injectionPoint);
  149. const manifestString = stringify(manifestEntries);
  150. const filesToWrite = {};
  151. const url = sourceMapURL.getFrom(swFileContents); // If our swSrc file contains a sourcemap, we would invalidate that
  152. // mapping if we just replaced injectionPoint with the stringified manifest.
  153. // Instead, we need to update the swDest contents as well as the sourcemap
  154. // at the same time.
  155. // See https://github.com/GoogleChrome/workbox/issues/2235
  156. if (url) {
  157. const sourcemapSrcPath = upath.resolve(upath.dirname(options.swSrc), url);
  158. const sourcemapDestPath = upath.resolve(upath.dirname(options.swDest), url);
  159. let originalMap;
  160. try {
  161. originalMap = await fse.readJSON(sourcemapSrcPath, 'utf8');
  162. } catch (error) {
  163. throw new Error(`${errors['cant-find-sourcemap']} ${error.message}`);
  164. }
  165. const {
  166. map,
  167. source
  168. } = await replaceAndUpdateSourceMap({
  169. originalMap,
  170. jsFilename: upath.basename(options.swDest),
  171. originalSource: swFileContents,
  172. replaceString: manifestString,
  173. searchString: options.injectionPoint
  174. });
  175. filesToWrite[options.swDest] = source;
  176. filesToWrite[sourcemapDestPath] = map;
  177. } else {
  178. // If there's no sourcemap associated with swSrc, a simple string
  179. // replacement will suffice.
  180. filesToWrite[options.swDest] = swFileContents.replace(globalRegexp, manifestString);
  181. }
  182. for (const [file, contents] of Object.entries(filesToWrite)) {
  183. try {
  184. await fse.mkdirp(upath.dirname(file));
  185. } catch (error) {
  186. throw new Error(errors['unable-to-make-injection-directory'] + ` '${error.message}'`);
  187. }
  188. await fse.writeFile(file, contents);
  189. }
  190. return {
  191. count,
  192. size,
  193. warnings,
  194. // Use upath.resolve() to make all the paths absolute.
  195. filePaths: Object.keys(filesToWrite).map(f => upath.resolve(f))
  196. };
  197. }
  198. module.exports = injectManifest;