normalization.js 18 KB

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