UNPKG

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