Template.js 13 KB

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