source: trip-planner-front/node_modules/webpack/lib/config/normalization.js@ 8d391a1

Last change on this file since 8d391a1 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 15.6 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 util = require("util");
9
10/** @typedef {import("../../declarations/WebpackOptions").EntryStatic} EntryStatic */
11/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */
12/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
13/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
14/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */
15/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */
16/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */
17/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
18/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */
19
20const handledDeprecatedNoEmitOnErrors = util.deprecate(
21 (noEmitOnErrors, emitOnErrors) => {
22 if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) {
23 throw new Error(
24 "Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config."
25 );
26 }
27 return !noEmitOnErrors;
28 },
29 "optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors",
30 "DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS"
31);
32
33/**
34 * @template T
35 * @template R
36 * @param {T|undefined} value value or not
37 * @param {function(T): R} fn nested handler
38 * @returns {R} result value
39 */
40const nestedConfig = (value, fn) =>
41 value === undefined ? fn(/** @type {T} */ ({})) : fn(value);
42
43/**
44 * @template T
45 * @param {T|undefined} value value or not
46 * @returns {T} result value
47 */
48const cloneObject = value => {
49 return /** @type {T} */ ({ ...value });
50};
51
52/**
53 * @template T
54 * @template R
55 * @param {T|undefined} value value or not
56 * @param {function(T): R} fn nested handler
57 * @returns {R|undefined} result value
58 */
59const optionalNestedConfig = (value, fn) =>
60 value === undefined ? undefined : fn(value);
61
62/**
63 * @template T
64 * @template R
65 * @param {T[]|undefined} value array or not
66 * @param {function(T[]): R[]} fn nested handler
67 * @returns {R[]|undefined} cloned value
68 */
69const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([]));
70
71/**
72 * @template T
73 * @template R
74 * @param {T[]|undefined} value array or not
75 * @param {function(T[]): R[]} fn nested handler
76 * @returns {R[]|undefined} cloned value
77 */
78const optionalNestedArray = (value, fn) =>
79 Array.isArray(value) ? fn(value) : undefined;
80
81/**
82 * @template T
83 * @template R
84 * @param {Record<string, T>|undefined} value value or not
85 * @param {function(T): R} fn nested handler
86 * @param {Record<string, function(T): R>=} customKeys custom nested handler for some keys
87 * @returns {Record<string, R>} result value
88 */
89const keyedNestedConfig = (value, fn, customKeys) => {
90 const result =
91 value === undefined
92 ? {}
93 : Object.keys(value).reduce(
94 (obj, key) => (
95 (obj[key] = (
96 customKeys && key in customKeys ? customKeys[key] : fn
97 )(value[key])),
98 obj
99 ),
100 /** @type {Record<string, R>} */ ({})
101 );
102 if (customKeys) {
103 for (const key of Object.keys(customKeys)) {
104 if (!(key in result)) {
105 result[key] = customKeys[key](/** @type {T} */ ({}));
106 }
107 }
108 }
109 return result;
110};
111
112/**
113 * @param {WebpackOptions} config input config
114 * @returns {WebpackOptionsNormalized} normalized options
115 */
116const getNormalizedWebpackOptions = config => {
117 return {
118 amd: config.amd,
119 bail: config.bail,
120 cache: optionalNestedConfig(config.cache, cache => {
121 if (cache === false) return false;
122 if (cache === true) {
123 return {
124 type: "memory",
125 maxGenerations: undefined
126 };
127 }
128 switch (cache.type) {
129 case "filesystem":
130 return {
131 type: "filesystem",
132 allowCollectingMemory: cache.allowCollectingMemory,
133 maxMemoryGenerations: cache.maxMemoryGenerations,
134 maxAge: cache.maxAge,
135 profile: cache.profile,
136 buildDependencies: cloneObject(cache.buildDependencies),
137 cacheDirectory: cache.cacheDirectory,
138 cacheLocation: cache.cacheLocation,
139 hashAlgorithm: cache.hashAlgorithm,
140 compression: cache.compression,
141 idleTimeout: cache.idleTimeout,
142 idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore,
143 idleTimeoutAfterLargeChanges: cache.idleTimeoutAfterLargeChanges,
144 name: cache.name,
145 store: cache.store,
146 version: cache.version
147 };
148 case undefined:
149 case "memory":
150 return {
151 type: "memory",
152 maxGenerations: cache.maxGenerations
153 };
154 default:
155 // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339)
156 throw new Error(`Not implemented cache.type ${cache.type}`);
157 }
158 }),
159 context: config.context,
160 dependencies: config.dependencies,
161 devServer: optionalNestedConfig(config.devServer, devServer => ({
162 ...devServer
163 })),
164 devtool: config.devtool,
165 entry:
166 config.entry === undefined
167 ? { main: {} }
168 : typeof config.entry === "function"
169 ? (
170 fn => () =>
171 Promise.resolve().then(fn).then(getNormalizedEntryStatic)
172 )(config.entry)
173 : getNormalizedEntryStatic(config.entry),
174 experiments: nestedConfig(config.experiments, experiments => ({
175 ...experiments,
176 buildHttp: optionalNestedConfig(experiments.buildHttp, options =>
177 options === true ? {} : options
178 )
179 })),
180 externals: config.externals,
181 externalsPresets: cloneObject(config.externalsPresets),
182 externalsType: config.externalsType,
183 ignoreWarnings: config.ignoreWarnings
184 ? config.ignoreWarnings.map(ignore => {
185 if (typeof ignore === "function") return ignore;
186 const i = ignore instanceof RegExp ? { message: ignore } : ignore;
187 return (warning, { requestShortener }) => {
188 if (!i.message && !i.module && !i.file) return false;
189 if (i.message && !i.message.test(warning.message)) {
190 return false;
191 }
192 if (
193 i.module &&
194 (!warning.module ||
195 !i.module.test(
196 warning.module.readableIdentifier(requestShortener)
197 ))
198 ) {
199 return false;
200 }
201 if (i.file && (!warning.file || !i.file.test(warning.file))) {
202 return false;
203 }
204 return true;
205 };
206 })
207 : undefined,
208 infrastructureLogging: cloneObject(config.infrastructureLogging),
209 loader: cloneObject(config.loader),
210 mode: config.mode,
211 module: nestedConfig(config.module, module => ({
212 noParse: module.noParse,
213 unsafeCache: module.unsafeCache,
214 parser: keyedNestedConfig(module.parser, cloneObject, {
215 javascript: parserOptions => ({
216 unknownContextRequest: module.unknownContextRequest,
217 unknownContextRegExp: module.unknownContextRegExp,
218 unknownContextRecursive: module.unknownContextRecursive,
219 unknownContextCritical: module.unknownContextCritical,
220 exprContextRequest: module.exprContextRequest,
221 exprContextRegExp: module.exprContextRegExp,
222 exprContextRecursive: module.exprContextRecursive,
223 exprContextCritical: module.exprContextCritical,
224 wrappedContextRegExp: module.wrappedContextRegExp,
225 wrappedContextRecursive: module.wrappedContextRecursive,
226 wrappedContextCritical: module.wrappedContextCritical,
227 strictExportPresence: module.strictExportPresence,
228 strictThisContextOnImports: module.strictThisContextOnImports,
229 ...parserOptions
230 })
231 }),
232 generator: cloneObject(module.generator),
233 defaultRules: optionalNestedArray(module.defaultRules, r => [...r]),
234 rules: nestedArray(module.rules, r => [...r])
235 })),
236 name: config.name,
237 node: nestedConfig(
238 config.node,
239 node =>
240 node && {
241 ...node
242 }
243 ),
244 optimization: nestedConfig(config.optimization, optimization => {
245 return {
246 ...optimization,
247 runtimeChunk: getNormalizedOptimizationRuntimeChunk(
248 optimization.runtimeChunk
249 ),
250 splitChunks: nestedConfig(
251 optimization.splitChunks,
252 splitChunks =>
253 splitChunks && {
254 ...splitChunks,
255 defaultSizeTypes: splitChunks.defaultSizeTypes
256 ? [...splitChunks.defaultSizeTypes]
257 : ["..."],
258 cacheGroups: cloneObject(splitChunks.cacheGroups)
259 }
260 ),
261 emitOnErrors:
262 optimization.noEmitOnErrors !== undefined
263 ? handledDeprecatedNoEmitOnErrors(
264 optimization.noEmitOnErrors,
265 optimization.emitOnErrors
266 )
267 : optimization.emitOnErrors
268 };
269 }),
270 output: nestedConfig(config.output, output => {
271 const { library } = output;
272 const libraryAsName = /** @type {LibraryName} */ (library);
273 const libraryBase =
274 typeof library === "object" &&
275 library &&
276 !Array.isArray(library) &&
277 "type" in library
278 ? library
279 : libraryAsName || output.libraryTarget
280 ? /** @type {LibraryOptions} */ ({
281 name: libraryAsName
282 })
283 : undefined;
284 /** @type {OutputNormalized} */
285 const result = {
286 assetModuleFilename: output.assetModuleFilename,
287 charset: output.charset,
288 chunkFilename: output.chunkFilename,
289 chunkFormat: output.chunkFormat,
290 chunkLoading: output.chunkLoading,
291 chunkLoadingGlobal: output.chunkLoadingGlobal,
292 chunkLoadTimeout: output.chunkLoadTimeout,
293 clean: output.clean,
294 compareBeforeEmit: output.compareBeforeEmit,
295 crossOriginLoading: output.crossOriginLoading,
296 devtoolFallbackModuleFilenameTemplate:
297 output.devtoolFallbackModuleFilenameTemplate,
298 devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate,
299 devtoolNamespace: output.devtoolNamespace,
300 environment: cloneObject(output.environment),
301 enabledChunkLoadingTypes: output.enabledChunkLoadingTypes
302 ? [...output.enabledChunkLoadingTypes]
303 : ["..."],
304 enabledLibraryTypes: output.enabledLibraryTypes
305 ? [...output.enabledLibraryTypes]
306 : ["..."],
307 enabledWasmLoadingTypes: output.enabledWasmLoadingTypes
308 ? [...output.enabledWasmLoadingTypes]
309 : ["..."],
310 filename: output.filename,
311 globalObject: output.globalObject,
312 hashDigest: output.hashDigest,
313 hashDigestLength: output.hashDigestLength,
314 hashFunction: output.hashFunction,
315 hashSalt: output.hashSalt,
316 hotUpdateChunkFilename: output.hotUpdateChunkFilename,
317 hotUpdateGlobal: output.hotUpdateGlobal,
318 hotUpdateMainFilename: output.hotUpdateMainFilename,
319 iife: output.iife,
320 importFunctionName: output.importFunctionName,
321 importMetaName: output.importMetaName,
322 scriptType: output.scriptType,
323 library: libraryBase && {
324 type:
325 output.libraryTarget !== undefined
326 ? output.libraryTarget
327 : libraryBase.type,
328 auxiliaryComment:
329 output.auxiliaryComment !== undefined
330 ? output.auxiliaryComment
331 : libraryBase.auxiliaryComment,
332 export:
333 output.libraryExport !== undefined
334 ? output.libraryExport
335 : libraryBase.export,
336 name: libraryBase.name,
337 umdNamedDefine:
338 output.umdNamedDefine !== undefined
339 ? output.umdNamedDefine
340 : libraryBase.umdNamedDefine
341 },
342 module: output.module,
343 path: output.path,
344 pathinfo: output.pathinfo,
345 publicPath: output.publicPath,
346 sourceMapFilename: output.sourceMapFilename,
347 sourcePrefix: output.sourcePrefix,
348 strictModuleExceptionHandling: output.strictModuleExceptionHandling,
349 trustedTypes: optionalNestedConfig(
350 output.trustedTypes,
351 trustedTypes => {
352 if (trustedTypes === true) return {};
353 if (typeof trustedTypes === "string")
354 return { policyName: trustedTypes };
355 return { ...trustedTypes };
356 }
357 ),
358 uniqueName: output.uniqueName,
359 wasmLoading: output.wasmLoading,
360 webassemblyModuleFilename: output.webassemblyModuleFilename,
361 workerChunkLoading: output.workerChunkLoading,
362 workerWasmLoading: output.workerWasmLoading
363 };
364 return result;
365 }),
366 parallelism: config.parallelism,
367 performance: optionalNestedConfig(config.performance, performance => {
368 if (performance === false) return false;
369 return {
370 ...performance
371 };
372 }),
373 plugins: nestedArray(config.plugins, p => [...p]),
374 profile: config.profile,
375 recordsInputPath:
376 config.recordsInputPath !== undefined
377 ? config.recordsInputPath
378 : config.recordsPath,
379 recordsOutputPath:
380 config.recordsOutputPath !== undefined
381 ? config.recordsOutputPath
382 : config.recordsPath,
383 resolve: nestedConfig(config.resolve, resolve => ({
384 ...resolve,
385 byDependency: keyedNestedConfig(resolve.byDependency, cloneObject)
386 })),
387 resolveLoader: cloneObject(config.resolveLoader),
388 snapshot: nestedConfig(config.snapshot, snapshot => ({
389 resolveBuildDependencies: optionalNestedConfig(
390 snapshot.resolveBuildDependencies,
391 resolveBuildDependencies => ({
392 timestamp: resolveBuildDependencies.timestamp,
393 hash: resolveBuildDependencies.hash
394 })
395 ),
396 buildDependencies: optionalNestedConfig(
397 snapshot.buildDependencies,
398 buildDependencies => ({
399 timestamp: buildDependencies.timestamp,
400 hash: buildDependencies.hash
401 })
402 ),
403 resolve: optionalNestedConfig(snapshot.resolve, resolve => ({
404 timestamp: resolve.timestamp,
405 hash: resolve.hash
406 })),
407 module: optionalNestedConfig(snapshot.module, module => ({
408 timestamp: module.timestamp,
409 hash: module.hash
410 })),
411 immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]),
412 managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p])
413 })),
414 stats: nestedConfig(config.stats, stats => {
415 if (stats === false) {
416 return {
417 preset: "none"
418 };
419 }
420 if (stats === true) {
421 return {
422 preset: "normal"
423 };
424 }
425 if (typeof stats === "string") {
426 return {
427 preset: stats
428 };
429 }
430 return {
431 ...stats
432 };
433 }),
434 target: config.target,
435 watch: config.watch,
436 watchOptions: cloneObject(config.watchOptions)
437 };
438};
439
440/**
441 * @param {EntryStatic} entry static entry options
442 * @returns {EntryStaticNormalized} normalized static entry options
443 */
444const getNormalizedEntryStatic = entry => {
445 if (typeof entry === "string") {
446 return {
447 main: {
448 import: [entry]
449 }
450 };
451 }
452 if (Array.isArray(entry)) {
453 return {
454 main: {
455 import: entry
456 }
457 };
458 }
459 /** @type {EntryStaticNormalized} */
460 const result = {};
461 for (const key of Object.keys(entry)) {
462 const value = entry[key];
463 if (typeof value === "string") {
464 result[key] = {
465 import: [value]
466 };
467 } else if (Array.isArray(value)) {
468 result[key] = {
469 import: value
470 };
471 } else {
472 result[key] = {
473 import:
474 value.import &&
475 (Array.isArray(value.import) ? value.import : [value.import]),
476 filename: value.filename,
477 layer: value.layer,
478 runtime: value.runtime,
479 publicPath: value.publicPath,
480 chunkLoading: value.chunkLoading,
481 wasmLoading: value.wasmLoading,
482 dependOn:
483 value.dependOn &&
484 (Array.isArray(value.dependOn) ? value.dependOn : [value.dependOn]),
485 library: value.library
486 };
487 }
488 }
489 return result;
490};
491
492/**
493 * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
494 * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
495 */
496const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
497 if (runtimeChunk === undefined) return undefined;
498 if (runtimeChunk === false) return false;
499 if (runtimeChunk === "single") {
500 return {
501 name: () => "runtime"
502 };
503 }
504 if (runtimeChunk === true || runtimeChunk === "multiple") {
505 return {
506 name: entrypoint => `runtime~${entrypoint.name}`
507 };
508 }
509 const { name } = runtimeChunk;
510 return {
511 name: typeof name === "function" ? name : () => name
512 };
513};
514
515exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions;
Note: See TracBrowser for help on using the repository browser.