Template.js 14 KB

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