source: frontend/node_modules/webpack/lib/Template.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

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