Template.js 13 KB

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