normalization.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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").OptimizationNormalized} OptimizationNormalized */
  16. /** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */
  17. /** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */
  18. /** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */
  19. /** @typedef {import("../../declarations/WebpackOptions").PluginsNormalized} PluginsNormalized */
  20. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
  21. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */
  22. /** @typedef {import("../WebpackError")} WebpackError */
  23. /**
  24. * Defines the webpack options interception type used by this module.
  25. * @typedef {object} WebpackOptionsInterception
  26. * @property {WebpackOptionsNormalized["devtool"]=} devtool
  27. */
  28. const handledDeprecatedNoEmitOnErrors = util.deprecate(
  29. /**
  30. * Handles the callback logic for this hook.
  31. * @param {boolean} noEmitOnErrors no emit on errors
  32. * @param {boolean | undefined} emitOnErrors emit on errors
  33. * @returns {boolean} emit on errors
  34. */
  35. (noEmitOnErrors, emitOnErrors) => {
  36. if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) {
  37. throw new Error(
  38. "Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config."
  39. );
  40. }
  41. return !noEmitOnErrors;
  42. },
  43. "optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors",
  44. "DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS"
  45. );
  46. /**
  47. * Returns result value.
  48. * @template T
  49. * @template R
  50. * @param {T | undefined} value value or not
  51. * @param {(value: T) => R} fn nested handler
  52. * @returns {R} result value
  53. */
  54. const nestedConfig = (value, fn) =>
  55. value === undefined ? fn(/** @type {T} */ ({})) : fn(value);
  56. /**
  57. * Returns result value.
  58. * @template T
  59. * @param {T | undefined} value value or not
  60. * @returns {T} result value
  61. */
  62. const cloneObject = (value) => /** @type {T} */ ({ ...value });
  63. /**
  64. * Optional nested config.
  65. * @template T
  66. * @template R
  67. * @param {T | undefined} value value or not
  68. * @param {(value: T) => R} fn nested handler
  69. * @returns {R | undefined} result value
  70. */
  71. const optionalNestedConfig = (value, fn) =>
  72. value === undefined ? undefined : fn(value);
  73. /**
  74. * Returns cloned value.
  75. * @template T
  76. * @template R
  77. * @param {T[] | undefined} value array or not
  78. * @param {(value: T[]) => R[]} fn nested handler
  79. * @returns {R[] | undefined} cloned value
  80. */
  81. const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([]));
  82. /**
  83. * Optional nested array.
  84. * @template T
  85. * @template R
  86. * @param {T[] | undefined} value array or not
  87. * @param {(value: T[]) => R[]} fn nested handler
  88. * @returns {R[] | undefined} cloned value
  89. */
  90. const optionalNestedArray = (value, fn) =>
  91. Array.isArray(value) ? fn(value) : undefined;
  92. /**
  93. * Keyed nested config.
  94. * @template T
  95. * @template R
  96. * @param {Record<string, T> | undefined} value value or not
  97. * @param {(value: T) => R} fn nested handler
  98. * @param {Record<string, (value: T) => R>=} customKeys custom nested handler for some keys
  99. * @returns {Record<string, R>} result value
  100. */
  101. const keyedNestedConfig = (value, fn, customKeys) => {
  102. /* eslint-disable no-sequences */
  103. const result =
  104. value === undefined
  105. ? {}
  106. : Object.keys(value).reduce(
  107. (obj, key) => (
  108. (obj[key] = (
  109. customKeys && key in customKeys ? customKeys[key] : fn
  110. )(value[key])),
  111. obj
  112. ),
  113. /** @type {Record<string, R>} */ ({})
  114. );
  115. /* eslint-enable no-sequences */
  116. if (customKeys) {
  117. for (const key of Object.keys(customKeys)) {
  118. if (!(key in result)) {
  119. result[key] = customKeys[key](/** @type {T} */ ({}));
  120. }
  121. }
  122. }
  123. return result;
  124. };
  125. /**
  126. * Gets normalized webpack options.
  127. * @param {WebpackOptions} config input config
  128. * @returns {WebpackOptionsNormalized} normalized options
  129. */
  130. const getNormalizedWebpackOptions = (config) => ({
  131. amd: config.amd,
  132. bail: config.bail,
  133. cache:
  134. /** @type {NonNullable<CacheOptions>} */
  135. (
  136. optionalNestedConfig(config.cache, (cache) => {
  137. if (cache === false) return false;
  138. if (cache === true) {
  139. return {
  140. type: "memory",
  141. maxGenerations: undefined
  142. };
  143. }
  144. switch (cache.type) {
  145. case "filesystem":
  146. return {
  147. type: "filesystem",
  148. allowCollectingMemory: cache.allowCollectingMemory,
  149. maxMemoryGenerations: cache.maxMemoryGenerations,
  150. maxAge: cache.maxAge,
  151. profile: cache.profile,
  152. buildDependencies: cloneObject(cache.buildDependencies),
  153. cacheDirectory: cache.cacheDirectory,
  154. cacheLocation: cache.cacheLocation,
  155. hashAlgorithm: cache.hashAlgorithm,
  156. compression: cache.compression,
  157. idleTimeout: cache.idleTimeout,
  158. idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore,
  159. idleTimeoutAfterLargeChanges: cache.idleTimeoutAfterLargeChanges,
  160. name: cache.name,
  161. store: cache.store,
  162. version: cache.version,
  163. readonly: cache.readonly
  164. };
  165. case undefined:
  166. case "memory":
  167. return {
  168. type: "memory",
  169. maxGenerations: cache.maxGenerations
  170. };
  171. default:
  172. // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339)
  173. throw new Error(`Not implemented cache.type ${cache.type}`);
  174. }
  175. })
  176. ),
  177. context: config.context,
  178. dependencies: config.dependencies,
  179. devServer: optionalNestedConfig(config.devServer, (devServer) => {
  180. if (devServer === false) return false;
  181. return { ...devServer };
  182. }),
  183. devtool: config.devtool,
  184. dotenv: config.dotenv,
  185. entry:
  186. config.entry === undefined
  187. ? { main: {} }
  188. : typeof config.entry === "function"
  189. ? (
  190. (fn) => () =>
  191. Promise.resolve().then(fn).then(getNormalizedEntryStatic)
  192. )(config.entry)
  193. : getNormalizedEntryStatic(config.entry),
  194. experiments: nestedConfig(config.experiments, (experiments) => ({
  195. ...experiments,
  196. buildHttp: optionalNestedConfig(experiments.buildHttp, (options) =>
  197. Array.isArray(options) ? { allowedUris: options } : options
  198. ),
  199. lazyCompilation: optionalNestedConfig(
  200. experiments.lazyCompilation,
  201. (options) => (options === true ? {} : options)
  202. )
  203. })),
  204. externals: /** @type {NonNullable<Externals>} */ (config.externals),
  205. externalsPresets: cloneObject(config.externalsPresets),
  206. externalsType: config.externalsType,
  207. ignoreWarnings: config.ignoreWarnings
  208. ? config.ignoreWarnings.map((ignore) => {
  209. if (typeof ignore === "function") return ignore;
  210. const i = ignore instanceof RegExp ? { message: ignore } : ignore;
  211. return (warning, { requestShortener }) => {
  212. if (!i.message && !i.module && !i.file) return false;
  213. if (i.message && !i.message.test(warning.message)) {
  214. return false;
  215. }
  216. if (
  217. i.module &&
  218. (!(/** @type {WebpackError} */ (warning).module) ||
  219. !i.module.test(
  220. /** @type {WebpackError} */
  221. (warning).module.readableIdentifier(requestShortener)
  222. ))
  223. ) {
  224. return false;
  225. }
  226. if (
  227. i.file &&
  228. (!(/** @type {WebpackError} */ (warning).file) ||
  229. !i.file.test(/** @type {WebpackError} */ (warning).file))
  230. ) {
  231. return false;
  232. }
  233. return true;
  234. };
  235. })
  236. : undefined,
  237. infrastructureLogging: cloneObject(config.infrastructureLogging),
  238. loader: cloneObject(config.loader),
  239. mode: config.mode,
  240. module:
  241. /** @type {ModuleOptionsNormalized} */
  242. (
  243. nestedConfig(config.module, (module) => ({
  244. noParse: module.noParse,
  245. unsafeCache: module.unsafeCache,
  246. parser: keyedNestedConfig(module.parser, cloneObject, {
  247. javascript: (parserOptions) => ({
  248. // TODO webpack 6 remove from `ModuleOptions`, keep only `*ByModuleType`
  249. unknownContextRequest: module.unknownContextRequest,
  250. unknownContextRegExp: module.unknownContextRegExp,
  251. unknownContextRecursive: module.unknownContextRecursive,
  252. unknownContextCritical: module.unknownContextCritical,
  253. exprContextRequest: module.exprContextRequest,
  254. exprContextRegExp: module.exprContextRegExp,
  255. exprContextRecursive: module.exprContextRecursive,
  256. exprContextCritical: module.exprContextCritical,
  257. wrappedContextRegExp: module.wrappedContextRegExp,
  258. wrappedContextRecursive: module.wrappedContextRecursive,
  259. wrappedContextCritical: module.wrappedContextCritical,
  260. strictExportPresence: module.strictExportPresence,
  261. strictThisContextOnImports: module.strictThisContextOnImports,
  262. ...parserOptions
  263. })
  264. }),
  265. generator: cloneObject(module.generator),
  266. defaultRules: optionalNestedArray(module.defaultRules, (r) => [...r]),
  267. rules: nestedArray(module.rules, (r) => [...r])
  268. }))
  269. ),
  270. name: config.name,
  271. node: nestedConfig(
  272. config.node,
  273. (node) =>
  274. node && {
  275. ...node
  276. }
  277. ),
  278. optimization: nestedConfig(config.optimization, (optimization) => ({
  279. ...optimization,
  280. runtimeChunk: getNormalizedOptimizationRuntimeChunk(
  281. optimization.runtimeChunk
  282. ),
  283. splitChunks: nestedConfig(
  284. optimization.splitChunks,
  285. (splitChunks) =>
  286. splitChunks && {
  287. ...splitChunks,
  288. defaultSizeTypes: splitChunks.defaultSizeTypes
  289. ? [...splitChunks.defaultSizeTypes]
  290. : ["..."],
  291. cacheGroups: cloneObject(splitChunks.cacheGroups)
  292. }
  293. ),
  294. minimizer:
  295. optimization.minimizer !== undefined
  296. ? /** @type {OptimizationNormalized["minimizer"]} */ (
  297. nestedArray(optimization.minimizer, (p) => p.filter(Boolean))
  298. )
  299. : optimization.minimizer,
  300. emitOnErrors:
  301. optimization.noEmitOnErrors !== undefined
  302. ? handledDeprecatedNoEmitOnErrors(
  303. optimization.noEmitOnErrors,
  304. optimization.emitOnErrors
  305. )
  306. : optimization.emitOnErrors
  307. })),
  308. output: nestedConfig(config.output, (output) => {
  309. const { library } = output;
  310. const libraryAsName = /** @type {LibraryName} */ (library);
  311. const libraryBase =
  312. typeof library === "object" &&
  313. library &&
  314. !Array.isArray(library) &&
  315. "type" in library
  316. ? library
  317. : libraryAsName || output.libraryTarget
  318. ? /** @type {LibraryOptions} */ ({
  319. name: libraryAsName
  320. })
  321. : undefined;
  322. /** @type {OutputNormalized} */
  323. const result = {
  324. assetModuleFilename: output.assetModuleFilename,
  325. asyncChunks: output.asyncChunks,
  326. charset: output.charset,
  327. chunkFilename: output.chunkFilename,
  328. chunkFormat: output.chunkFormat,
  329. chunkLoading: output.chunkLoading,
  330. chunkLoadingGlobal: output.chunkLoadingGlobal,
  331. chunkLoadTimeout: output.chunkLoadTimeout,
  332. cssFilename: output.cssFilename,
  333. cssChunkFilename: output.cssChunkFilename,
  334. clean: output.clean,
  335. compareBeforeEmit: output.compareBeforeEmit,
  336. crossOriginLoading: output.crossOriginLoading,
  337. devtoolFallbackModuleFilenameTemplate:
  338. output.devtoolFallbackModuleFilenameTemplate,
  339. devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate,
  340. devtoolNamespace: output.devtoolNamespace,
  341. environment: cloneObject(output.environment),
  342. enabledChunkLoadingTypes: output.enabledChunkLoadingTypes
  343. ? [...output.enabledChunkLoadingTypes]
  344. : ["..."],
  345. enabledLibraryTypes: output.enabledLibraryTypes
  346. ? [...output.enabledLibraryTypes]
  347. : ["..."],
  348. enabledWasmLoadingTypes: output.enabledWasmLoadingTypes
  349. ? [...output.enabledWasmLoadingTypes]
  350. : ["..."],
  351. filename: output.filename,
  352. globalObject: output.globalObject,
  353. hashDigest: output.hashDigest,
  354. hashDigestLength: output.hashDigestLength,
  355. hashFunction: output.hashFunction,
  356. hashSalt: output.hashSalt,
  357. hotUpdateChunkFilename: output.hotUpdateChunkFilename,
  358. hotUpdateGlobal: output.hotUpdateGlobal,
  359. hotUpdateMainFilename: output.hotUpdateMainFilename,
  360. ignoreBrowserWarnings: output.ignoreBrowserWarnings,
  361. iife: output.iife,
  362. importFunctionName: output.importFunctionName,
  363. importMetaName: output.importMetaName,
  364. scriptType: output.scriptType,
  365. // TODO webpack 6 remove `libraryTarget`/`auxiliaryComment`/`amdContainer`/etc in favor of the `library` option
  366. library: libraryBase && {
  367. type:
  368. output.libraryTarget !== undefined
  369. ? output.libraryTarget
  370. : libraryBase.type,
  371. auxiliaryComment:
  372. output.auxiliaryComment !== undefined
  373. ? output.auxiliaryComment
  374. : libraryBase.auxiliaryComment,
  375. amdContainer:
  376. output.amdContainer !== undefined
  377. ? output.amdContainer
  378. : libraryBase.amdContainer,
  379. export:
  380. output.libraryExport !== undefined
  381. ? output.libraryExport
  382. : libraryBase.export,
  383. name: libraryBase.name,
  384. umdNamedDefine:
  385. output.umdNamedDefine !== undefined
  386. ? output.umdNamedDefine
  387. : libraryBase.umdNamedDefine
  388. },
  389. module: output.module,
  390. path: output.path,
  391. pathinfo: output.pathinfo,
  392. publicPath: output.publicPath,
  393. sourceMapFilename: output.sourceMapFilename,
  394. sourcePrefix: output.sourcePrefix,
  395. strictModuleErrorHandling: output.strictModuleErrorHandling,
  396. strictModuleExceptionHandling: output.strictModuleExceptionHandling,
  397. trustedTypes: optionalNestedConfig(
  398. output.trustedTypes,
  399. (trustedTypes) => {
  400. if (trustedTypes === true) return {};
  401. if (typeof trustedTypes === "string") {
  402. return { policyName: trustedTypes };
  403. }
  404. return { ...trustedTypes };
  405. }
  406. ),
  407. uniqueName: output.uniqueName,
  408. wasmLoading: output.wasmLoading,
  409. webassemblyModuleFilename: output.webassemblyModuleFilename,
  410. workerPublicPath: output.workerPublicPath,
  411. workerChunkLoading: output.workerChunkLoading,
  412. workerWasmLoading: output.workerWasmLoading
  413. };
  414. return result;
  415. }),
  416. parallelism: config.parallelism,
  417. validate: config.validate,
  418. performance: optionalNestedConfig(config.performance, (performance) => {
  419. if (performance === false) return false;
  420. return {
  421. ...performance
  422. };
  423. }),
  424. plugins: /** @type {PluginsNormalized} */ (
  425. nestedArray(config.plugins, (p) => p.filter(Boolean))
  426. ),
  427. profile: config.profile,
  428. recordsInputPath:
  429. config.recordsInputPath !== undefined
  430. ? config.recordsInputPath
  431. : config.recordsPath,
  432. recordsOutputPath:
  433. config.recordsOutputPath !== undefined
  434. ? config.recordsOutputPath
  435. : config.recordsPath,
  436. resolve: nestedConfig(config.resolve, (resolve) => ({
  437. ...resolve,
  438. byDependency: keyedNestedConfig(resolve.byDependency, cloneObject)
  439. })),
  440. resolveLoader: cloneObject(config.resolveLoader),
  441. snapshot: nestedConfig(config.snapshot, (snapshot) => ({
  442. resolveBuildDependencies: optionalNestedConfig(
  443. snapshot.resolveBuildDependencies,
  444. (resolveBuildDependencies) => ({
  445. timestamp: resolveBuildDependencies.timestamp,
  446. hash: resolveBuildDependencies.hash
  447. })
  448. ),
  449. buildDependencies: optionalNestedConfig(
  450. snapshot.buildDependencies,
  451. (buildDependencies) => ({
  452. timestamp: buildDependencies.timestamp,
  453. hash: buildDependencies.hash
  454. })
  455. ),
  456. resolve: optionalNestedConfig(snapshot.resolve, (resolve) => ({
  457. timestamp: resolve.timestamp,
  458. hash: resolve.hash
  459. })),
  460. module: optionalNestedConfig(snapshot.module, (module) => ({
  461. timestamp: module.timestamp,
  462. hash: module.hash
  463. })),
  464. contextModule: optionalNestedConfig(
  465. snapshot.contextModule,
  466. (contextModule) => ({
  467. timestamp: contextModule.timestamp,
  468. hash: contextModule.hash
  469. })
  470. ),
  471. immutablePaths: optionalNestedArray(snapshot.immutablePaths, (p) => [...p]),
  472. managedPaths: optionalNestedArray(snapshot.managedPaths, (p) => [...p]),
  473. unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, (p) => [...p])
  474. })),
  475. stats: nestedConfig(config.stats, (stats) => {
  476. if (stats === false) {
  477. return {
  478. preset: "none"
  479. };
  480. }
  481. if (stats === true) {
  482. return {
  483. preset: "normal"
  484. };
  485. }
  486. if (typeof stats === "string") {
  487. return {
  488. preset: stats
  489. };
  490. }
  491. return {
  492. ...stats
  493. };
  494. }),
  495. target: config.target,
  496. watch: config.watch,
  497. watchOptions: cloneObject(config.watchOptions)
  498. });
  499. /**
  500. * Gets normalized entry static.
  501. * @param {EntryStatic} entry static entry options
  502. * @returns {EntryStaticNormalized} normalized static entry options
  503. */
  504. const getNormalizedEntryStatic = (entry) => {
  505. if (typeof entry === "string") {
  506. return {
  507. main: {
  508. import: [entry]
  509. }
  510. };
  511. }
  512. if (Array.isArray(entry)) {
  513. return {
  514. main: {
  515. import: entry
  516. }
  517. };
  518. }
  519. /** @type {EntryStaticNormalized} */
  520. const result = {};
  521. for (const key of Object.keys(entry)) {
  522. const value = entry[key];
  523. if (typeof value === "string") {
  524. result[key] = {
  525. import: [value]
  526. };
  527. } else if (Array.isArray(value)) {
  528. result[key] = {
  529. import: value
  530. };
  531. } else {
  532. result[key] = {
  533. import:
  534. /** @type {EntryDescriptionNormalized["import"]} */
  535. (
  536. value.import &&
  537. (Array.isArray(value.import) ? value.import : [value.import])
  538. ),
  539. filename: value.filename,
  540. layer: value.layer,
  541. runtime: value.runtime,
  542. baseUri: value.baseUri,
  543. publicPath: value.publicPath,
  544. chunkLoading: value.chunkLoading,
  545. asyncChunks: value.asyncChunks,
  546. wasmLoading: value.wasmLoading,
  547. dependOn:
  548. /** @type {EntryDescriptionNormalized["dependOn"]} */
  549. (
  550. value.dependOn &&
  551. (Array.isArray(value.dependOn)
  552. ? value.dependOn
  553. : [value.dependOn])
  554. ),
  555. library: value.library
  556. };
  557. }
  558. }
  559. return result;
  560. };
  561. /**
  562. * Gets normalized optimization runtime chunk.
  563. * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
  564. * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
  565. */
  566. const getNormalizedOptimizationRuntimeChunk = (runtimeChunk) => {
  567. if (runtimeChunk === undefined) return;
  568. if (runtimeChunk === false) return false;
  569. if (runtimeChunk === "single") {
  570. return {
  571. name: () => "runtime"
  572. };
  573. }
  574. if (runtimeChunk === true || runtimeChunk === "multiple") {
  575. return {
  576. name: (entrypoint) => `runtime~${entrypoint.name}`
  577. };
  578. }
  579. const { name } = runtimeChunk;
  580. return {
  581. name:
  582. typeof name === "function"
  583. ? /** @type {Exclude<OptimizationRuntimeChunkNormalized, false>["name"]} */
  584. (name)
  585. : () => /** @type {string} */ (name)
  586. };
  587. };
  588. /**
  589. * Apply webpack options interception.
  590. * @param {WebpackOptionsNormalized} options options to be intercepted
  591. * @returns {{ options: WebpackOptionsNormalized, interception?: WebpackOptionsInterception }} options and interception
  592. */
  593. const applyWebpackOptionsInterception = (options) => {
  594. // Return origin options when backCompat is disabled
  595. if (options.experiments.futureDefaults) {
  596. return {
  597. options
  598. };
  599. }
  600. // TODO webpack 6 - remove compatibility logic and move `devtools` fully into `devtool` with multi-type support
  601. let _devtool = options.devtool;
  602. /** @type {WebpackOptionsNormalized["devtool"]} */
  603. let cached;
  604. const devtoolBackCompat = () => {
  605. if (Array.isArray(_devtool)) {
  606. if (cached) return cached;
  607. // Prefer `all`, then `javascript`, then `css`
  608. const match = ["all", "javascript", "css"]
  609. .map((type) =>
  610. /** @type {Extract<WebpackOptionsNormalized["devtool"], EXPECTED_ANY[]>} */ (
  611. _devtool
  612. ).find((item) => item.type === type)
  613. )
  614. .find(Boolean);
  615. // If `devtool: []` is specified, return `false` here
  616. return (cached = match ? match.use : false);
  617. }
  618. return _devtool;
  619. };
  620. /** @type {ProxyHandler<WebpackOptionsNormalized>} */
  621. const handler = Object.create(null);
  622. handler.get = (target, prop, receiver) => {
  623. if (prop === "devtool") {
  624. return devtoolBackCompat();
  625. }
  626. return Reflect.get(target, prop, receiver);
  627. };
  628. handler.set = (target, prop, value, receiver) => {
  629. if (prop === "devtool") {
  630. _devtool = value;
  631. cached = undefined;
  632. return true;
  633. }
  634. return Reflect.set(target, prop, value, receiver);
  635. };
  636. handler.deleteProperty = (target, prop) => {
  637. if (prop === "devtool") {
  638. _devtool = undefined;
  639. cached = undefined;
  640. return true;
  641. }
  642. return Reflect.deleteProperty(target, prop);
  643. };
  644. handler.defineProperty = (target, prop, descriptor) => {
  645. if (prop === "devtool") {
  646. _devtool = descriptor.value;
  647. cached = undefined;
  648. return true;
  649. }
  650. return Reflect.defineProperty(target, prop, descriptor);
  651. };
  652. handler.getOwnPropertyDescriptor = (target, prop) => {
  653. if (prop === "devtool") {
  654. return {
  655. configurable: true,
  656. enumerable: true,
  657. value: devtoolBackCompat(),
  658. writable: true
  659. };
  660. }
  661. return Reflect.getOwnPropertyDescriptor(target, prop);
  662. };
  663. return {
  664. options: new Proxy(options, handler),
  665. interception: {
  666. get devtool() {
  667. return _devtool;
  668. }
  669. }
  670. };
  671. };
  672. module.exports.applyWebpackOptionsInterception =
  673. applyWebpackOptionsInterception;
  674. module.exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions;