Template.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource, PrefixSource } = require("webpack-sources");
  7. const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
  8. const RuntimeGlobals = require("./RuntimeGlobals");
  9. /** @typedef {import("webpack-sources").Source} Source */
  10. /** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
  11. /** @typedef {import("./Chunk")} Chunk */
  12. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  13. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  14. /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
  15. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  16. /** @typedef {import("./Compilation").PathData} PathData */
  17. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  18. /** @typedef {import("./Module")} Module */
  19. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  20. /** @typedef {import("./ModuleTemplate")} ModuleTemplate */
  21. /** @typedef {import("./RuntimeModule")} RuntimeModule */
  22. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  23. /** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
  24. /** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
  25. /** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
  26. const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
  27. const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
  28. const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
  29. const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $
  30. const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS =
  31. NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9
  32. const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g;
  33. const INDENT_MULTILINE_REGEX = /^\t/gm;
  34. const LINE_SEPARATOR_REGEX = /\r?\n/g;
  35. const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/;
  36. const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g;
  37. const COMMENT_END_REGEX = /\*\//g;
  38. const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g;
  39. const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
  40. /**
  41. * @typedef {object} RenderManifestOptions
  42. * @property {Chunk} chunk the chunk used to render
  43. * @property {string} hash
  44. * @property {string} fullHash
  45. * @property {OutputOptions} outputOptions
  46. * @property {CodeGenerationResults} codeGenerationResults
  47. * @property {{javascript: ModuleTemplate}} moduleTemplates
  48. * @property {DependencyTemplates} dependencyTemplates
  49. * @property {RuntimeTemplate} runtimeTemplate
  50. * @property {ModuleGraph} moduleGraph
  51. * @property {ChunkGraph} chunkGraph
  52. */
  53. /** @typedef {RenderManifestEntryTemplated | RenderManifestEntryStatic} RenderManifestEntry */
  54. /**
  55. * @typedef {object} RenderManifestEntryTemplated
  56. * @property {function(): Source} render
  57. * @property {TemplatePath} filenameTemplate
  58. * @property {PathData=} pathOptions
  59. * @property {AssetInfo=} info
  60. * @property {string} identifier
  61. * @property {string=} hash
  62. * @property {boolean=} auxiliary
  63. */
  64. /**
  65. * @typedef {object} RenderManifestEntryStatic
  66. * @property {function(): Source} render
  67. * @property {string} filename
  68. * @property {AssetInfo} info
  69. * @property {string} identifier
  70. * @property {string=} hash
  71. * @property {boolean=} auxiliary
  72. */
  73. /**
  74. * @typedef {object} HasId
  75. * @property {number | string} id
  76. */
  77. /**
  78. * @typedef {function(Module, number): boolean} ModuleFilterPredicate
  79. */
  80. class Template {
  81. /**
  82. * @param {Function} fn a runtime function (.runtime.js) "template"
  83. * @returns {string} the updated and normalized function string
  84. */
  85. static getFunctionContent(fn) {
  86. return fn
  87. .toString()
  88. .replace(FUNCTION_CONTENT_REGEX, "")
  89. .replace(INDENT_MULTILINE_REGEX, "")
  90. .replace(LINE_SEPARATOR_REGEX, "\n");
  91. }
  92. /**
  93. * @param {string} str the string converted to identifier
  94. * @returns {string} created identifier
  95. */
  96. static toIdentifier(str) {
  97. if (typeof str !== "string") return "";
  98. return str
  99. .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1")
  100. .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_");
  101. }
  102. /**
  103. * @param {string} str string to be converted to commented in bundle code
  104. * @returns {string} returns a commented version of string
  105. */
  106. static toComment(str) {
  107. if (!str) return "";
  108. return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`;
  109. }
  110. /**
  111. * @param {string} str string to be converted to "normal comment"
  112. * @returns {string} returns a commented version of string
  113. */
  114. static toNormalComment(str) {
  115. if (!str) return "";
  116. return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`;
  117. }
  118. /**
  119. * @param {string} str string path to be normalized
  120. * @returns {string} normalized bundle-safe path
  121. */
  122. static toPath(str) {
  123. if (typeof str !== "string") return "";
  124. return str
  125. .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-")
  126. .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
  127. }
  128. // map number to a single character a-z, A-Z or multiple characters if number is too big
  129. /**
  130. * @param {number} n number to convert to ident
  131. * @returns {string} returns single character ident
  132. */
  133. static numberToIdentifier(n) {
  134. if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) {
  135. // use multiple letters
  136. return (
  137. Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) +
  138. Template.numberToIdentifierContinuation(
  139. Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS)
  140. )
  141. );
  142. }
  143. // lower case
  144. if (n < DELTA_A_TO_Z) {
  145. return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
  146. }
  147. n -= DELTA_A_TO_Z;
  148. // upper case
  149. if (n < DELTA_A_TO_Z) {
  150. return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
  151. }
  152. if (n === DELTA_A_TO_Z) return "_";
  153. return "$";
  154. }
  155. /**
  156. * @param {number} n number to convert to ident
  157. * @returns {string} returns single character ident
  158. */
  159. static numberToIdentifierContinuation(n) {
  160. if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) {
  161. // use multiple letters
  162. return (
  163. Template.numberToIdentifierContinuation(
  164. n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS
  165. ) +
  166. Template.numberToIdentifierContinuation(
  167. Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS)
  168. )
  169. );
  170. }
  171. // lower case
  172. if (n < DELTA_A_TO_Z) {
  173. return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
  174. }
  175. n -= DELTA_A_TO_Z;
  176. // upper case
  177. if (n < DELTA_A_TO_Z) {
  178. return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
  179. }
  180. n -= DELTA_A_TO_Z;
  181. // numbers
  182. if (n < 10) {
  183. return `${n}`;
  184. }
  185. if (n === 10) return "_";
  186. return "$";
  187. }
  188. /**
  189. * @param {string | string[]} s string to convert to identity
  190. * @returns {string} converted identity
  191. */
  192. static indent(s) {
  193. if (Array.isArray(s)) {
  194. return s.map(Template.indent).join("\n");
  195. }
  196. const str = s.trimEnd();
  197. if (!str) return "";
  198. const ind = str[0] === "\n" ? "" : "\t";
  199. return ind + str.replace(/\n([^\n])/g, "\n\t$1");
  200. }
  201. /**
  202. * @param {string|string[]} s string to create prefix for
  203. * @param {string} prefix prefix to compose
  204. * @returns {string} returns new prefix string
  205. */
  206. static prefix(s, prefix) {
  207. const str = Template.asString(s).trim();
  208. if (!str) return "";
  209. const ind = str[0] === "\n" ? "" : prefix;
  210. return ind + str.replace(/\n([^\n])/g, `\n${prefix}$1`);
  211. }
  212. /**
  213. * @param {string|string[]} str string or string collection
  214. * @returns {string} returns a single string from array
  215. */
  216. static asString(str) {
  217. if (Array.isArray(str)) {
  218. return str.join("\n");
  219. }
  220. return str;
  221. }
  222. /**
  223. * @typedef {object} WithId
  224. * @property {string|number} id
  225. */
  226. /**
  227. * @param {WithId[]} modules a collection of modules to get array bounds for
  228. * @returns {[number, number] | false} returns the upper and lower array bounds
  229. * or false if not every module has a number based id
  230. */
  231. static getModulesArrayBounds(modules) {
  232. let maxId = -Infinity;
  233. let minId = Infinity;
  234. for (const module of modules) {
  235. const moduleId = module.id;
  236. if (typeof moduleId !== "number") return false;
  237. if (maxId < moduleId) maxId = moduleId;
  238. if (minId > moduleId) minId = moduleId;
  239. }
  240. if (minId < 16 + String(minId).length) {
  241. // add minId x ',' instead of 'Array(minId).concat(…)'
  242. minId = 0;
  243. }
  244. // start with -1 because the first module needs no comma
  245. let objectOverhead = -1;
  246. for (const module of modules) {
  247. // module id + colon + comma
  248. objectOverhead += `${module.id}`.length + 2;
  249. }
  250. // number of commas, or when starting non-zero the length of Array(minId).concat()
  251. const arrayOverhead = minId === 0 ? maxId : 16 + `${minId}`.length + maxId;
  252. return arrayOverhead < objectOverhead ? [minId, maxId] : false;
  253. }
  254. /**
  255. * @param {ChunkRenderContext} renderContext render context
  256. * @param {Module[]} modules modules to render (should be ordered by identifier)
  257. * @param {function(Module): Source | null} renderModule function to render a module
  258. * @param {string=} prefix applying prefix strings
  259. * @returns {Source | null} rendered chunk modules in a Source object or null if no modules
  260. */
  261. static renderChunkModules(renderContext, modules, renderModule, prefix = "") {
  262. const { chunkGraph } = renderContext;
  263. const source = new ConcatSource();
  264. if (modules.length === 0) {
  265. return null;
  266. }
  267. /** @type {{id: string|number, source: Source|string}[]} */
  268. const allModules = modules.map(module => ({
  269. id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
  270. source: renderModule(module) || "false"
  271. }));
  272. const bounds = Template.getModulesArrayBounds(allModules);
  273. if (bounds) {
  274. // Render a spare array
  275. const minId = bounds[0];
  276. const maxId = bounds[1];
  277. if (minId !== 0) {
  278. source.add(`Array(${minId}).concat(`);
  279. }
  280. source.add("[\n");
  281. /** @type {Map<string|number, {id: string|number, source: Source|string}>} */
  282. const modules = new Map();
  283. for (const module of allModules) {
  284. modules.set(module.id, module);
  285. }
  286. for (let idx = minId; idx <= maxId; idx++) {
  287. const module = modules.get(idx);
  288. if (idx !== minId) {
  289. source.add(",\n");
  290. }
  291. source.add(`/* ${idx} */`);
  292. if (module) {
  293. source.add("\n");
  294. source.add(module.source);
  295. }
  296. }
  297. source.add(`\n${prefix}]`);
  298. if (minId !== 0) {
  299. source.add(")");
  300. }
  301. } else {
  302. // Render an object
  303. source.add("{\n");
  304. for (let i = 0; i < allModules.length; i++) {
  305. const module = allModules[i];
  306. if (i !== 0) {
  307. source.add(",\n");
  308. }
  309. source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
  310. source.add(module.source);
  311. }
  312. source.add(`\n\n${prefix}}`);
  313. }
  314. return source;
  315. }
  316. /**
  317. * @param {RuntimeModule[]} runtimeModules array of runtime modules in order
  318. * @param {RenderContext & { codeGenerationResults?: CodeGenerationResults }} renderContext render context
  319. * @returns {Source} rendered runtime modules in a Source object
  320. */
  321. static renderRuntimeModules(runtimeModules, renderContext) {
  322. const source = new ConcatSource();
  323. for (const module of runtimeModules) {
  324. const codeGenerationResults = renderContext.codeGenerationResults;
  325. let runtimeSource;
  326. if (codeGenerationResults) {
  327. runtimeSource = codeGenerationResults.getSource(
  328. module,
  329. renderContext.chunk.runtime,
  330. WEBPACK_MODULE_TYPE_RUNTIME
  331. );
  332. } else {
  333. const codeGenResult = module.codeGeneration({
  334. chunkGraph: renderContext.chunkGraph,
  335. dependencyTemplates: renderContext.dependencyTemplates,
  336. moduleGraph: renderContext.moduleGraph,
  337. runtimeTemplate: renderContext.runtimeTemplate,
  338. runtime: renderContext.chunk.runtime,
  339. codeGenerationResults
  340. });
  341. if (!codeGenResult) continue;
  342. runtimeSource = codeGenResult.sources.get("runtime");
  343. }
  344. if (runtimeSource) {
  345. source.add(`${Template.toNormalComment(module.identifier())}\n`);
  346. if (!module.shouldIsolate()) {
  347. source.add(runtimeSource);
  348. source.add("\n\n");
  349. } else if (renderContext.runtimeTemplate.supportsArrowFunction()) {
  350. source.add("(() => {\n");
  351. source.add(new PrefixSource("\t", runtimeSource));
  352. source.add("\n})();\n\n");
  353. } else {
  354. source.add("!function() {\n");
  355. source.add(new PrefixSource("\t", runtimeSource));
  356. source.add("\n}();\n\n");
  357. }
  358. }
  359. }
  360. return source;
  361. }
  362. /**
  363. * @param {RuntimeModule[]} runtimeModules array of runtime modules in order
  364. * @param {RenderContext} renderContext render context
  365. * @returns {Source} rendered chunk runtime modules in a Source object
  366. */
  367. static renderChunkRuntimeModules(runtimeModules, renderContext) {
  368. return new PrefixSource(
  369. "/******/ ",
  370. new ConcatSource(
  371. `function(${RuntimeGlobals.require}) { // webpackRuntimeModules\n`,
  372. this.renderRuntimeModules(runtimeModules, renderContext),
  373. "}\n"
  374. )
  375. );
  376. }
  377. }
  378. module.exports = Template;
  379. module.exports.NUMBER_OF_IDENTIFIER_START_CHARS =
  380. NUMBER_OF_IDENTIFIER_START_CHARS;
  381. module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS =
  382. NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS;