normalization.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 {(value: 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 {(value: 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 {(value: 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 {(value: 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 {(value: T) => R} fn nested handler
  85. * @param {Record<string, (value: 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. // TODO webpack6 remove `libraryTarget`/`auxiliaryComment`/`amdContainer`/etc in favor of the `library` option
  340. library: libraryBase && {
  341. type:
  342. output.libraryTarget !== undefined
  343. ? output.libraryTarget
  344. : libraryBase.type,
  345. auxiliaryComment:
  346. output.auxiliaryComment !== undefined
  347. ? output.auxiliaryComment
  348. : libraryBase.auxiliaryComment,
  349. amdContainer:
  350. output.amdContainer !== undefined
  351. ? output.amdContainer
  352. : libraryBase.amdContainer,
  353. export:
  354. output.libraryExport !== undefined
  355. ? output.libraryExport
  356. : libraryBase.export,
  357. name: libraryBase.name,
  358. umdNamedDefine:
  359. output.umdNamedDefine !== undefined
  360. ? output.umdNamedDefine
  361. : libraryBase.umdNamedDefine
  362. },
  363. module: output.module,
  364. path: output.path,
  365. pathinfo: output.pathinfo,
  366. publicPath: output.publicPath,
  367. sourceMapFilename: output.sourceMapFilename,
  368. sourcePrefix: output.sourcePrefix,
  369. strictModuleErrorHandling: output.strictModuleErrorHandling,
  370. strictModuleExceptionHandling: output.strictModuleExceptionHandling,
  371. trustedTypes: optionalNestedConfig(output.trustedTypes, trustedTypes => {
  372. if (trustedTypes === true) return {};
  373. if (typeof trustedTypes === "string")
  374. return { policyName: trustedTypes };
  375. return { ...trustedTypes };
  376. }),
  377. uniqueName: output.uniqueName,
  378. wasmLoading: output.wasmLoading,
  379. webassemblyModuleFilename: output.webassemblyModuleFilename,
  380. workerPublicPath: output.workerPublicPath,
  381. workerChunkLoading: output.workerChunkLoading,
  382. workerWasmLoading: output.workerWasmLoading
  383. };
  384. return result;
  385. }),
  386. parallelism: config.parallelism,
  387. performance: optionalNestedConfig(config.performance, performance => {
  388. if (performance === false) return false;
  389. return {
  390. ...performance
  391. };
  392. }),
  393. plugins: /** @type {Plugins} */ (nestedArray(config.plugins, p => [...p])),
  394. profile: config.profile,
  395. recordsInputPath:
  396. config.recordsInputPath !== undefined
  397. ? config.recordsInputPath
  398. : config.recordsPath,
  399. recordsOutputPath:
  400. config.recordsOutputPath !== undefined
  401. ? config.recordsOutputPath
  402. : config.recordsPath,
  403. resolve: nestedConfig(config.resolve, resolve => ({
  404. ...resolve,
  405. byDependency: keyedNestedConfig(resolve.byDependency, cloneObject)
  406. })),
  407. resolveLoader: cloneObject(config.resolveLoader),
  408. snapshot: nestedConfig(config.snapshot, snapshot => ({
  409. resolveBuildDependencies: optionalNestedConfig(
  410. snapshot.resolveBuildDependencies,
  411. resolveBuildDependencies => ({
  412. timestamp: resolveBuildDependencies.timestamp,
  413. hash: resolveBuildDependencies.hash
  414. })
  415. ),
  416. buildDependencies: optionalNestedConfig(
  417. snapshot.buildDependencies,
  418. buildDependencies => ({
  419. timestamp: buildDependencies.timestamp,
  420. hash: buildDependencies.hash
  421. })
  422. ),
  423. resolve: optionalNestedConfig(snapshot.resolve, resolve => ({
  424. timestamp: resolve.timestamp,
  425. hash: resolve.hash
  426. })),
  427. module: optionalNestedConfig(snapshot.module, module => ({
  428. timestamp: module.timestamp,
  429. hash: module.hash
  430. })),
  431. immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]),
  432. managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p]),
  433. unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, p => [...p])
  434. })),
  435. stats: nestedConfig(config.stats, stats => {
  436. if (stats === false) {
  437. return {
  438. preset: "none"
  439. };
  440. }
  441. if (stats === true) {
  442. return {
  443. preset: "normal"
  444. };
  445. }
  446. if (typeof stats === "string") {
  447. return {
  448. preset: stats
  449. };
  450. }
  451. return {
  452. ...stats
  453. };
  454. }),
  455. target: config.target,
  456. watch: config.watch,
  457. watchOptions: cloneObject(config.watchOptions)
  458. });
  459. /**
  460. * @param {EntryStatic} entry static entry options
  461. * @returns {EntryStaticNormalized} normalized static entry options
  462. */
  463. const getNormalizedEntryStatic = entry => {
  464. if (typeof entry === "string") {
  465. return {
  466. main: {
  467. import: [entry]
  468. }
  469. };
  470. }
  471. if (Array.isArray(entry)) {
  472. return {
  473. main: {
  474. import: entry
  475. }
  476. };
  477. }
  478. /** @type {EntryStaticNormalized} */
  479. const result = {};
  480. for (const key of Object.keys(entry)) {
  481. const value = entry[key];
  482. if (typeof value === "string") {
  483. result[key] = {
  484. import: [value]
  485. };
  486. } else if (Array.isArray(value)) {
  487. result[key] = {
  488. import: value
  489. };
  490. } else {
  491. result[key] = {
  492. import:
  493. /** @type {EntryDescriptionNormalized["import"]} */
  494. (
  495. value.import &&
  496. (Array.isArray(value.import) ? value.import : [value.import])
  497. ),
  498. filename: value.filename,
  499. layer: value.layer,
  500. runtime: value.runtime,
  501. baseUri: value.baseUri,
  502. publicPath: value.publicPath,
  503. chunkLoading: value.chunkLoading,
  504. asyncChunks: value.asyncChunks,
  505. wasmLoading: value.wasmLoading,
  506. dependOn:
  507. /** @type {EntryDescriptionNormalized["dependOn"]} */
  508. (
  509. value.dependOn &&
  510. (Array.isArray(value.dependOn)
  511. ? value.dependOn
  512. : [value.dependOn])
  513. ),
  514. library: value.library
  515. };
  516. }
  517. }
  518. return result;
  519. };
  520. /**
  521. * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
  522. * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
  523. */
  524. const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
  525. if (runtimeChunk === undefined) return;
  526. if (runtimeChunk === false) return false;
  527. if (runtimeChunk === "single") {
  528. return {
  529. name: () => "runtime"
  530. };
  531. }
  532. if (runtimeChunk === true || runtimeChunk === "multiple") {
  533. return {
  534. /**
  535. * @param {Entrypoint} entrypoint entrypoint
  536. * @returns {string} runtime chunk name
  537. */
  538. name: entrypoint => `runtime~${entrypoint.name}`
  539. };
  540. }
  541. const { name } = runtimeChunk;
  542. return {
  543. name: typeof name === "function" ? name : () => name
  544. };
  545. };
  546. module.exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions;