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

main
Last change on this file was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

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