normalization.js 16 KB

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