normalization.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. if (devServer === false) return false;
  169. return { ...devServer };
  170. }),
  171. devtool: config.devtool,
  172. entry:
  173. config.entry === undefined
  174. ? { main: {} }
  175. : typeof config.entry === "function"
  176. ? (
  177. fn => () =>
  178. Promise.resolve().then(fn).then(getNormalizedEntryStatic)
  179. )(config.entry)
  180. : getNormalizedEntryStatic(config.entry),
  181. experiments: nestedConfig(config.experiments, experiments => ({
  182. ...experiments,
  183. buildHttp: optionalNestedConfig(experiments.buildHttp, options =>
  184. Array.isArray(options) ? { allowedUris: options } : options
  185. ),
  186. lazyCompilation: optionalNestedConfig(
  187. experiments.lazyCompilation,
  188. options => (options === true ? {} : options)
  189. )
  190. })),
  191. externals: /** @type {NonNullable<Externals>} */ (config.externals),
  192. externalsPresets: cloneObject(config.externalsPresets),
  193. externalsType: config.externalsType,
  194. ignoreWarnings: config.ignoreWarnings
  195. ? config.ignoreWarnings.map(ignore => {
  196. if (typeof ignore === "function") return ignore;
  197. const i = ignore instanceof RegExp ? { message: ignore } : ignore;
  198. return (warning, { requestShortener }) => {
  199. if (!i.message && !i.module && !i.file) return false;
  200. if (i.message && !i.message.test(warning.message)) {
  201. return false;
  202. }
  203. if (
  204. i.module &&
  205. (!warning.module ||
  206. !i.module.test(
  207. warning.module.readableIdentifier(requestShortener)
  208. ))
  209. ) {
  210. return false;
  211. }
  212. if (i.file && (!warning.file || !i.file.test(warning.file))) {
  213. return false;
  214. }
  215. return true;
  216. };
  217. })
  218. : undefined,
  219. infrastructureLogging: cloneObject(config.infrastructureLogging),
  220. loader: cloneObject(config.loader),
  221. mode: config.mode,
  222. module:
  223. /** @type {ModuleOptionsNormalized} */
  224. (
  225. nestedConfig(config.module, module => ({
  226. noParse: module.noParse,
  227. unsafeCache: module.unsafeCache,
  228. parser: keyedNestedConfig(module.parser, cloneObject, {
  229. javascript: parserOptions => ({
  230. unknownContextRequest: module.unknownContextRequest,
  231. unknownContextRegExp: module.unknownContextRegExp,
  232. unknownContextRecursive: module.unknownContextRecursive,
  233. unknownContextCritical: module.unknownContextCritical,
  234. exprContextRequest: module.exprContextRequest,
  235. exprContextRegExp: module.exprContextRegExp,
  236. exprContextRecursive: module.exprContextRecursive,
  237. exprContextCritical: module.exprContextCritical,
  238. wrappedContextRegExp: module.wrappedContextRegExp,
  239. wrappedContextRecursive: module.wrappedContextRecursive,
  240. wrappedContextCritical: module.wrappedContextCritical,
  241. // TODO webpack 6 remove
  242. strictExportPresence: module.strictExportPresence,
  243. strictThisContextOnImports: module.strictThisContextOnImports,
  244. ...parserOptions
  245. })
  246. }),
  247. generator: cloneObject(module.generator),
  248. defaultRules: optionalNestedArray(module.defaultRules, r => [...r]),
  249. rules: nestedArray(module.rules, r => [...r])
  250. }))
  251. ),
  252. name: config.name,
  253. node: nestedConfig(
  254. config.node,
  255. node =>
  256. node && {
  257. ...node
  258. }
  259. ),
  260. optimization: nestedConfig(config.optimization, optimization => {
  261. return {
  262. ...optimization,
  263. runtimeChunk: getNormalizedOptimizationRuntimeChunk(
  264. optimization.runtimeChunk
  265. ),
  266. splitChunks: nestedConfig(
  267. optimization.splitChunks,
  268. splitChunks =>
  269. splitChunks && {
  270. ...splitChunks,
  271. defaultSizeTypes: splitChunks.defaultSizeTypes
  272. ? [...splitChunks.defaultSizeTypes]
  273. : ["..."],
  274. cacheGroups: cloneObject(splitChunks.cacheGroups)
  275. }
  276. ),
  277. emitOnErrors:
  278. optimization.noEmitOnErrors !== undefined
  279. ? handledDeprecatedNoEmitOnErrors(
  280. optimization.noEmitOnErrors,
  281. optimization.emitOnErrors
  282. )
  283. : optimization.emitOnErrors
  284. };
  285. }),
  286. output: nestedConfig(config.output, output => {
  287. const { library } = output;
  288. const libraryAsName = /** @type {LibraryName} */ (library);
  289. const libraryBase =
  290. typeof library === "object" &&
  291. library &&
  292. !Array.isArray(library) &&
  293. "type" in library
  294. ? library
  295. : libraryAsName || output.libraryTarget
  296. ? /** @type {LibraryOptions} */ ({
  297. name: libraryAsName
  298. })
  299. : undefined;
  300. /** @type {OutputNormalized} */
  301. const result = {
  302. assetModuleFilename: output.assetModuleFilename,
  303. asyncChunks: output.asyncChunks,
  304. charset: output.charset,
  305. chunkFilename: output.chunkFilename,
  306. chunkFormat: output.chunkFormat,
  307. chunkLoading: output.chunkLoading,
  308. chunkLoadingGlobal: output.chunkLoadingGlobal,
  309. chunkLoadTimeout: output.chunkLoadTimeout,
  310. cssFilename: output.cssFilename,
  311. cssChunkFilename: output.cssChunkFilename,
  312. cssHeadDataCompression: output.cssHeadDataCompression,
  313. clean: output.clean,
  314. compareBeforeEmit: output.compareBeforeEmit,
  315. crossOriginLoading: output.crossOriginLoading,
  316. devtoolFallbackModuleFilenameTemplate:
  317. output.devtoolFallbackModuleFilenameTemplate,
  318. devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate,
  319. devtoolNamespace: output.devtoolNamespace,
  320. environment: cloneObject(output.environment),
  321. enabledChunkLoadingTypes: output.enabledChunkLoadingTypes
  322. ? [...output.enabledChunkLoadingTypes]
  323. : ["..."],
  324. enabledLibraryTypes: output.enabledLibraryTypes
  325. ? [...output.enabledLibraryTypes]
  326. : ["..."],
  327. enabledWasmLoadingTypes: output.enabledWasmLoadingTypes
  328. ? [...output.enabledWasmLoadingTypes]
  329. : ["..."],
  330. filename: output.filename,
  331. globalObject: output.globalObject,
  332. hashDigest: output.hashDigest,
  333. hashDigestLength: output.hashDigestLength,
  334. hashFunction: output.hashFunction,
  335. hashSalt: output.hashSalt,
  336. hotUpdateChunkFilename: output.hotUpdateChunkFilename,
  337. hotUpdateGlobal: output.hotUpdateGlobal,
  338. hotUpdateMainFilename: output.hotUpdateMainFilename,
  339. ignoreBrowserWarnings: output.ignoreBrowserWarnings,
  340. iife: output.iife,
  341. importFunctionName: output.importFunctionName,
  342. importMetaName: output.importMetaName,
  343. scriptType: output.scriptType,
  344. library: libraryBase && {
  345. type:
  346. output.libraryTarget !== undefined
  347. ? output.libraryTarget
  348. : libraryBase.type,
  349. auxiliaryComment:
  350. output.auxiliaryComment !== undefined
  351. ? output.auxiliaryComment
  352. : libraryBase.auxiliaryComment,
  353. amdContainer:
  354. output.amdContainer !== undefined
  355. ? output.amdContainer
  356. : libraryBase.amdContainer,
  357. export:
  358. output.libraryExport !== undefined
  359. ? output.libraryExport
  360. : libraryBase.export,
  361. name: libraryBase.name,
  362. umdNamedDefine:
  363. output.umdNamedDefine !== undefined
  364. ? output.umdNamedDefine
  365. : libraryBase.umdNamedDefine
  366. },
  367. module: output.module,
  368. path: output.path,
  369. pathinfo: output.pathinfo,
  370. publicPath: output.publicPath,
  371. sourceMapFilename: output.sourceMapFilename,
  372. sourcePrefix: output.sourcePrefix,
  373. strictModuleErrorHandling: output.strictModuleErrorHandling,
  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. unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, p => [...p])
  441. })),
  442. stats: nestedConfig(config.stats, stats => {
  443. if (stats === false) {
  444. return {
  445. preset: "none"
  446. };
  447. }
  448. if (stats === true) {
  449. return {
  450. preset: "normal"
  451. };
  452. }
  453. if (typeof stats === "string") {
  454. return {
  455. preset: stats
  456. };
  457. }
  458. return {
  459. ...stats
  460. };
  461. }),
  462. target: config.target,
  463. watch: config.watch,
  464. watchOptions: cloneObject(config.watchOptions)
  465. };
  466. };
  467. /**
  468. * @param {EntryStatic} entry static entry options
  469. * @returns {EntryStaticNormalized} normalized static entry options
  470. */
  471. const getNormalizedEntryStatic = entry => {
  472. if (typeof entry === "string") {
  473. return {
  474. main: {
  475. import: [entry]
  476. }
  477. };
  478. }
  479. if (Array.isArray(entry)) {
  480. return {
  481. main: {
  482. import: entry
  483. }
  484. };
  485. }
  486. /** @type {EntryStaticNormalized} */
  487. const result = {};
  488. for (const key of Object.keys(entry)) {
  489. const value = entry[key];
  490. if (typeof value === "string") {
  491. result[key] = {
  492. import: [value]
  493. };
  494. } else if (Array.isArray(value)) {
  495. result[key] = {
  496. import: value
  497. };
  498. } else {
  499. result[key] = {
  500. import:
  501. /** @type {EntryDescriptionNormalized["import"]} */
  502. (
  503. value.import &&
  504. (Array.isArray(value.import) ? value.import : [value.import])
  505. ),
  506. filename: value.filename,
  507. layer: value.layer,
  508. runtime: value.runtime,
  509. baseUri: value.baseUri,
  510. publicPath: value.publicPath,
  511. chunkLoading: value.chunkLoading,
  512. asyncChunks: value.asyncChunks,
  513. wasmLoading: value.wasmLoading,
  514. dependOn:
  515. /** @type {EntryDescriptionNormalized["dependOn"]} */
  516. (
  517. value.dependOn &&
  518. (Array.isArray(value.dependOn)
  519. ? value.dependOn
  520. : [value.dependOn])
  521. ),
  522. library: value.library
  523. };
  524. }
  525. }
  526. return result;
  527. };
  528. /**
  529. * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
  530. * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
  531. */
  532. const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
  533. if (runtimeChunk === undefined) return undefined;
  534. if (runtimeChunk === false) return false;
  535. if (runtimeChunk === "single") {
  536. return {
  537. name: () => "runtime"
  538. };
  539. }
  540. if (runtimeChunk === true || runtimeChunk === "multiple") {
  541. return {
  542. /**
  543. * @param {Entrypoint} entrypoint entrypoint
  544. * @returns {string} runtime chunk name
  545. */
  546. name: entrypoint => `runtime~${entrypoint.name}`
  547. };
  548. }
  549. const { name } = runtimeChunk;
  550. return {
  551. name: typeof name === "function" ? name : () => name
  552. };
  553. };
  554. exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions;