normalization.js 18 KB

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