normalization.js 17 KB

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