inject-manifest.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 {
  9. RawSource
  10. } = require('webpack-sources');
  11. const {
  12. SingleEntryPlugin
  13. } = require('webpack');
  14. const replaceAndUpdateSourceMap = require('workbox-build/build/lib/replace-and-update-source-map');
  15. const stringify = require('fast-json-stable-stringify');
  16. const upath = require('upath');
  17. const validate = require('workbox-build/build/lib/validate-options');
  18. const webpackInjectManifestSchema = require('workbox-build/build/options/schema/webpack-inject-manifest');
  19. const getManifestEntriesFromCompilation = require('./lib/get-manifest-entries-from-compilation');
  20. const getSourcemapAssetName = require('./lib/get-sourcemap-asset-name');
  21. const relativeToOutputPath = require('./lib/relative-to-output-path'); // Used to keep track of swDest files written by *any* instance of this plugin.
  22. // See https://github.com/GoogleChrome/workbox/issues/2181
  23. const _generatedAssetNames = new Set();
  24. /**
  25. * This class supports compiling a service worker file provided via `swSrc`,
  26. * and injecting into that service worker a list of URLs and revision
  27. * information for precaching based on the webpack asset pipeline.
  28. *
  29. * Use an instance of `InjectManifest` in the
  30. * [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
  31. * webpack config.
  32. *
  33. * @memberof module:workbox-webpack-plugin
  34. */
  35. class InjectManifest {
  36. // eslint-disable-next-line jsdoc/newline-after-description
  37. /**
  38. * Creates an instance of InjectManifest.
  39. *
  40. * @param {Object} config The configuration to use.
  41. *
  42. * @param {string} config.swSrc An existing service worker file that will be
  43. * compiled and have a precache manifest injected into it.
  44. *
  45. * @param {Array<module:workbox-build.ManifestEntry>} [config.additionalManifestEntries]
  46. * A list of entries to be precached, in addition to any entries that are
  47. * generated as part of the build configuration.
  48. *
  49. * @param {Array<string>} [config.chunks] One or more chunk names whose corresponding
  50. * output files should be included in the precache manifest.
  51. *
  52. * @param {boolean} [config.compileSrc=true] When `true` (the default), the
  53. * `swSrc` file will be compiled by webpack. When `false`, compilation will
  54. * not occur (and `webpackCompilationPlugins` can't be used.) Set to `false`
  55. * if you want to inject the manifest into, e.g., a JSON file.
  56. *
  57. * @param {RegExp} [config.dontCacheBustURLsMatching] Assets that match this will be
  58. * assumed to be uniquely versioned via their URL, and exempted from the normal
  59. * HTTP cache-busting that's done when populating the precache. While not
  60. * required, it's recommended that if your existing build process already
  61. * inserts a `[hash]` value into each filename, you provide a RegExp that will
  62. * detect that, as it will reduce the bandwidth consumed when precaching.
  63. *
  64. * @param {Array<string|RegExp|Function>} [config.exclude=[/\.map$/, /^manifest.*\.js$]]
  65. * One or more specifiers used to exclude assets from the precache manifest.
  66. * This is interpreted following
  67. * [the same rules](https://webpack.js.org/configuration/module/#condition)
  68. * as `webpack`'s standard `exclude` option.
  69. *
  70. * @param {Array<string>} [config.importScriptsViaChunks] One or more names of
  71. * webpack chunks. The content of those chunks will be included in the
  72. * generated service worker, via a call to `importScripts()`.
  73. *
  74. * @param {Array<string>} [config.excludeChunks] One or more chunk names whose
  75. * corresponding output files should be excluded from the precache manifest.
  76. *
  77. * @param {Array<string|RegExp|Function>} [config.include]
  78. * One or more specifiers used to include assets in the precache manifest.
  79. * This is interpreted following
  80. * [the same rules](https://webpack.js.org/configuration/module/#condition)
  81. * as `webpack`'s standard `include` option.
  82. *
  83. * @param {string} [config.injectionPoint='self.__WB_MANIFEST'] The string to
  84. * find inside of the `swSrc` file. Once found, it will be replaced by the
  85. * generated precache manifest.
  86. *
  87. * @param {Array<module:workbox-build.ManifestTransform>} [config.manifestTransforms]
  88. * One or more functions which will be applied sequentially against the
  89. * generated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are
  90. * also specified, their corresponding transformations will be applied first.
  91. *
  92. * @param {number} [config.maximumFileSizeToCacheInBytes=2097152] This value can be
  93. * used to determine the maximum size of files that will be precached. This
  94. * prevents you from inadvertently precaching very large files that might have
  95. * accidentally matched one of your patterns.
  96. *
  97. * @param {string} [config.mode] If set to 'production', then an optimized service
  98. * worker bundle that excludes debugging info will be produced. If not explicitly
  99. * configured here, the `mode` value configured in the current `webpack`
  100. * compilation will be used.
  101. *
  102. * @param {object<string, string>} [config.modifyURLPrefix] A mapping of prefixes
  103. * that, if present in an entry in the precache manifest, will be replaced with
  104. * the corresponding value. This can be used to, for example, remove or add a
  105. * path prefix from a manifest entry if your web hosting setup doesn't match
  106. * your local filesystem setup. As an alternative with more flexibility, you can
  107. * use the `manifestTransforms` option and provide a function that modifies the
  108. * entries in the manifest using whatever logic you provide.
  109. *
  110. * @param {string} [config.swDest] The asset name of the
  111. * service worker file that will be created by this plugin. If omitted, the
  112. * name will be based on the `swSrc` name.
  113. *
  114. * @param {Array<Object>} [config.webpackCompilationPlugins] Optional `webpack`
  115. * plugins that will be used when compiling the `swSrc` input file.
  116. */
  117. constructor(config = {}) {
  118. this.config = config;
  119. this.alreadyCalled = false;
  120. }
  121. /**
  122. * @param {Object} [compiler] default compiler object passed from webpack
  123. *
  124. * @private
  125. */
  126. propagateWebpackConfig(compiler) {
  127. // Because this.config is listed last, properties that are already set
  128. // there take precedence over derived properties from the compiler.
  129. this.config = Object.assign({
  130. mode: compiler.mode
  131. }, this.config);
  132. }
  133. /**
  134. * @param {Object} [compiler] default compiler object passed from webpack
  135. *
  136. * @private
  137. */
  138. apply(compiler) {
  139. this.propagateWebpackConfig(compiler);
  140. compiler.hooks.make.tapPromise(this.constructor.name, compilation => this.handleMake(compilation, compiler).catch(error => compilation.errors.push(error)));
  141. compiler.hooks.emit.tapPromise(this.constructor.name, compilation => this.handleEmit(compilation).catch(error => compilation.errors.push(error)));
  142. }
  143. /**
  144. * @param {Object} compilation The webpack compilation.
  145. * @param {Object} parentCompiler The webpack parent compiler.
  146. *
  147. * @private
  148. */
  149. async performChildCompilation(compilation, parentCompiler) {
  150. const outputOptions = {
  151. path: parentCompiler.options.output.path,
  152. filename: this.config.swDest
  153. };
  154. const childCompiler = compilation.createChildCompiler(this.constructor.name, outputOptions);
  155. childCompiler.context = parentCompiler.context;
  156. childCompiler.inputFileSystem = parentCompiler.inputFileSystem;
  157. childCompiler.outputFileSystem = parentCompiler.outputFileSystem;
  158. if (Array.isArray(this.config.webpackCompilationPlugins)) {
  159. for (const plugin of this.config.webpackCompilationPlugins) {
  160. plugin.apply(childCompiler);
  161. }
  162. }
  163. new SingleEntryPlugin(parentCompiler.context, this.config.swSrc, this.constructor.name).apply(childCompiler);
  164. await new Promise((resolve, reject) => {
  165. childCompiler.runAsChild((error, entries, childCompilation) => {
  166. if (error) {
  167. reject(error);
  168. } else {
  169. compilation.warnings = compilation.warnings.concat(childCompilation.warnings);
  170. compilation.errors = compilation.errors.concat(childCompilation.errors);
  171. resolve();
  172. }
  173. });
  174. });
  175. }
  176. /**
  177. * @param {Object} compilation The webpack compilation.
  178. * @param {Object} parentCompiler The webpack parent compiler.
  179. *
  180. * @private
  181. */
  182. addSrcToAssets(compilation, parentCompiler) {
  183. const source = parentCompiler.inputFileSystem.readFileSync(this.config.swSrc).toString();
  184. compilation.assets[this.config.swDest] = new RawSource(source);
  185. }
  186. /**
  187. * @param {Object} compilation The webpack compilation.
  188. * @param {Object} parentCompiler The webpack parent compiler.
  189. *
  190. * @private
  191. */
  192. async handleMake(compilation, parentCompiler) {
  193. try {
  194. this.config = validate(this.config, webpackInjectManifestSchema);
  195. } catch (error) {
  196. throw new Error(`Please check your ${this.constructor.name} plugin ` + `configuration:\n${error.message}`);
  197. }
  198. this.config.swDest = relativeToOutputPath(compilation, this.config.swDest);
  199. _generatedAssetNames.add(this.config.swDest);
  200. if (this.config.compileSrc) {
  201. await this.performChildCompilation(compilation, parentCompiler);
  202. } else {
  203. this.addSrcToAssets(compilation, parentCompiler);
  204. }
  205. }
  206. /**
  207. * @param {Object} compilation The webpack compilation.
  208. *
  209. * @private
  210. */
  211. async handleEmit(compilation) {
  212. // See https://github.com/GoogleChrome/workbox/issues/1790
  213. if (this.alreadyCalled) {
  214. compilation.warnings.push(`${this.constructor.name} has been called ` + `multiple times, perhaps due to running webpack in --watch mode. The ` + `precache manifest generated after the first call may be inaccurate! ` + `Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` + `more information.`);
  215. } else {
  216. this.alreadyCalled = true;
  217. }
  218. const config = Object.assign({}, this.config); // Ensure that we don't precache any of the assets generated by *any*
  219. // instance of this plugin.
  220. config.exclude.push(({
  221. asset
  222. }) => _generatedAssetNames.has(asset.name)); // See https://webpack.js.org/contribute/plugin-patterns/#monitoring-the-watch-graph
  223. const absoluteSwSrc = upath.resolve(this.config.swSrc);
  224. compilation.fileDependencies.add(absoluteSwSrc);
  225. const swAsset = compilation.assets[config.swDest];
  226. const initialSWAssetString = swAsset.source();
  227. if (!initialSWAssetString.includes(config.injectionPoint)) {
  228. throw new Error(`Can't find ${config.injectionPoint} in your SW source.`);
  229. }
  230. const manifestEntries = await getManifestEntriesFromCompilation(compilation, config);
  231. let manifestString = stringify(manifestEntries);
  232. if (this.config.compileSrc) {
  233. // See https://github.com/GoogleChrome/workbox/issues/2263
  234. manifestString = manifestString.replace(/"/g, `'`);
  235. }
  236. const sourcemapAssetName = getSourcemapAssetName(compilation, initialSWAssetString, config.swDest);
  237. if (sourcemapAssetName) {
  238. const sourcemapAsset = compilation.assets[sourcemapAssetName];
  239. const {
  240. source,
  241. map
  242. } = await replaceAndUpdateSourceMap({
  243. jsFilename: config.swDest,
  244. originalMap: JSON.parse(sourcemapAsset.source()),
  245. originalSource: initialSWAssetString,
  246. replaceString: manifestString,
  247. searchString: config.injectionPoint
  248. });
  249. compilation.assets[sourcemapAssetName] = new RawSource(map);
  250. compilation.assets[config.swDest] = new RawSource(source);
  251. } else {
  252. // If there's no sourcemap associated with swDest, a simple string
  253. // replacement will suffice.
  254. compilation.assets[config.swDest] = new RawSource(initialSWAssetString.replace(config.injectionPoint, manifestString));
  255. }
  256. }
  257. }
  258. module.exports = InjectManifest;