DefinePlugin.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const {
  7. JAVASCRIPT_MODULE_TYPE_AUTO,
  8. JAVASCRIPT_MODULE_TYPE_ESM,
  9. JAVASCRIPT_MODULE_TYPE_DYNAMIC
  10. } = require("./ModuleTypeConstants");
  11. const RuntimeGlobals = require("./RuntimeGlobals");
  12. const WebpackError = require("./WebpackError");
  13. const ConstDependency = require("./dependencies/ConstDependency");
  14. const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
  15. const { VariableInfo } = require("./javascript/JavascriptParser");
  16. const {
  17. evaluateToString,
  18. toConstantDependency
  19. } = require("./javascript/JavascriptParserHelpers");
  20. const createHash = require("./util/createHash");
  21. /** @typedef {import("estree").Expression} Expression */
  22. /** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
  23. /** @typedef {import("./Compiler")} Compiler */
  24. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  25. /** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
  26. /** @typedef {import("./NormalModule")} NormalModule */
  27. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  28. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  29. /** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */
  30. /** @typedef {import("./javascript/JavascriptParser").Range} Range */
  31. /** @typedef {import("./logging/Logger").Logger} Logger */
  32. /** @typedef {null | undefined | RegExp | EXPECTED_FUNCTION | string | number | boolean | bigint | undefined} CodeValuePrimitive */
  33. /** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive | RuntimeValue>} CodeValue */
  34. /**
  35. * @typedef {object} RuntimeValueOptions
  36. * @property {string[]=} fileDependencies
  37. * @property {string[]=} contextDependencies
  38. * @property {string[]=} missingDependencies
  39. * @property {string[]=} buildDependencies
  40. * @property {string| (() => string)=} version
  41. */
  42. /** @typedef {string | Set<string>} ValueCacheVersion */
  43. /** @typedef {(value: { module: NormalModule, key: string, readonly version: ValueCacheVersion }) => CodeValuePrimitive} GeneratorFn */
  44. class RuntimeValue {
  45. /**
  46. * @param {GeneratorFn} fn generator function
  47. * @param {true | string[] | RuntimeValueOptions=} options options
  48. */
  49. constructor(fn, options) {
  50. this.fn = fn;
  51. if (Array.isArray(options)) {
  52. options = {
  53. fileDependencies: options
  54. };
  55. }
  56. this.options = options || {};
  57. }
  58. get fileDependencies() {
  59. return this.options === true ? true : this.options.fileDependencies;
  60. }
  61. /**
  62. * @param {JavascriptParser} parser the parser
  63. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  64. * @param {string} key the defined key
  65. * @returns {CodeValuePrimitive} code
  66. */
  67. exec(parser, valueCacheVersions, key) {
  68. const buildInfo = /** @type {BuildInfo} */ (parser.state.module.buildInfo);
  69. if (this.options === true) {
  70. buildInfo.cacheable = false;
  71. } else {
  72. if (this.options.fileDependencies) {
  73. for (const dep of this.options.fileDependencies) {
  74. /** @type {NonNullable<BuildInfo["fileDependencies"]>} */
  75. (buildInfo.fileDependencies).add(dep);
  76. }
  77. }
  78. if (this.options.contextDependencies) {
  79. for (const dep of this.options.contextDependencies) {
  80. /** @type {NonNullable<BuildInfo["contextDependencies"]>} */
  81. (buildInfo.contextDependencies).add(dep);
  82. }
  83. }
  84. if (this.options.missingDependencies) {
  85. for (const dep of this.options.missingDependencies) {
  86. /** @type {NonNullable<BuildInfo["missingDependencies"]>} */
  87. (buildInfo.missingDependencies).add(dep);
  88. }
  89. }
  90. if (this.options.buildDependencies) {
  91. for (const dep of this.options.buildDependencies) {
  92. /** @type {NonNullable<BuildInfo["buildDependencies"]>} */
  93. (buildInfo.buildDependencies).add(dep);
  94. }
  95. }
  96. }
  97. return this.fn({
  98. module: parser.state.module,
  99. key,
  100. get version() {
  101. return /** @type {ValueCacheVersion} */ (
  102. valueCacheVersions.get(VALUE_DEP_PREFIX + key)
  103. );
  104. }
  105. });
  106. }
  107. getCacheVersion() {
  108. return this.options === true
  109. ? undefined
  110. : (typeof this.options.version === "function"
  111. ? this.options.version()
  112. : this.options.version) || "unset";
  113. }
  114. }
  115. /**
  116. * @param {Set<DestructuringAssignmentProperty> | undefined} properties properties
  117. * @returns {Set<string> | undefined} used keys
  118. */
  119. function getObjKeys(properties) {
  120. if (!properties) return;
  121. return new Set([...properties].map(p => p.id));
  122. }
  123. /** @typedef {Set<string> | null} ObjKeys */
  124. /** @typedef {boolean | undefined | null} AsiSafe */
  125. /**
  126. * @param {EXPECTED_ANY[] | {[k: string]: EXPECTED_ANY}} obj obj
  127. * @param {JavascriptParser} parser Parser
  128. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  129. * @param {string} key the defined key
  130. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  131. * @param {Logger} logger the logger object
  132. * @param {AsiSafe=} asiSafe asi safe (undefined: unknown, null: unneeded)
  133. * @param {ObjKeys=} objKeys used keys
  134. * @returns {string} code converted to string that evaluates
  135. */
  136. const stringifyObj = (
  137. obj,
  138. parser,
  139. valueCacheVersions,
  140. key,
  141. runtimeTemplate,
  142. logger,
  143. asiSafe,
  144. objKeys
  145. ) => {
  146. let code;
  147. const arr = Array.isArray(obj);
  148. if (arr) {
  149. code = `[${obj
  150. .map(code =>
  151. toCode(
  152. code,
  153. parser,
  154. valueCacheVersions,
  155. key,
  156. runtimeTemplate,
  157. logger,
  158. null
  159. )
  160. )
  161. .join(",")}]`;
  162. } else {
  163. let keys = Object.keys(obj);
  164. if (objKeys) {
  165. keys = objKeys.size === 0 ? [] : keys.filter(k => objKeys.has(k));
  166. }
  167. code = `{${keys
  168. .map(key => {
  169. const code = obj[key];
  170. return `${JSON.stringify(key)}:${toCode(
  171. code,
  172. parser,
  173. valueCacheVersions,
  174. key,
  175. runtimeTemplate,
  176. logger,
  177. null
  178. )}`;
  179. })
  180. .join(",")}}`;
  181. }
  182. switch (asiSafe) {
  183. case null:
  184. return code;
  185. case true:
  186. return arr ? code : `(${code})`;
  187. case false:
  188. return arr ? `;${code}` : `;(${code})`;
  189. default:
  190. return `/*#__PURE__*/Object(${code})`;
  191. }
  192. };
  193. /**
  194. * Convert code to a string that evaluates
  195. * @param {CodeValue} code Code to evaluate
  196. * @param {JavascriptParser} parser Parser
  197. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  198. * @param {string} key the defined key
  199. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  200. * @param {Logger} logger the logger object
  201. * @param {boolean | undefined | null=} asiSafe asi safe (undefined: unknown, null: unneeded)
  202. * @param {ObjKeys=} objKeys used keys
  203. * @returns {string} code converted to string that evaluates
  204. */
  205. const toCode = (
  206. code,
  207. parser,
  208. valueCacheVersions,
  209. key,
  210. runtimeTemplate,
  211. logger,
  212. asiSafe,
  213. objKeys
  214. ) => {
  215. const transformToCode = () => {
  216. if (code === null) {
  217. return "null";
  218. }
  219. if (code === undefined) {
  220. return "undefined";
  221. }
  222. if (Object.is(code, -0)) {
  223. return "-0";
  224. }
  225. if (code instanceof RuntimeValue) {
  226. return toCode(
  227. code.exec(parser, valueCacheVersions, key),
  228. parser,
  229. valueCacheVersions,
  230. key,
  231. runtimeTemplate,
  232. logger,
  233. asiSafe
  234. );
  235. }
  236. if (code instanceof RegExp && code.toString) {
  237. return code.toString();
  238. }
  239. if (typeof code === "function" && code.toString) {
  240. return `(${code.toString()})`;
  241. }
  242. if (typeof code === "object") {
  243. return stringifyObj(
  244. code,
  245. parser,
  246. valueCacheVersions,
  247. key,
  248. runtimeTemplate,
  249. logger,
  250. asiSafe,
  251. objKeys
  252. );
  253. }
  254. if (typeof code === "bigint") {
  255. return runtimeTemplate.supportsBigIntLiteral()
  256. ? `${code}n`
  257. : `BigInt("${code}")`;
  258. }
  259. return `${code}`;
  260. };
  261. const strCode = transformToCode();
  262. logger.debug(`Replaced "${key}" with "${strCode}"`);
  263. return strCode;
  264. };
  265. /**
  266. * @param {CodeValue} code code
  267. * @returns {string | undefined} result
  268. */
  269. const toCacheVersion = code => {
  270. if (code === null) {
  271. return "null";
  272. }
  273. if (code === undefined) {
  274. return "undefined";
  275. }
  276. if (Object.is(code, -0)) {
  277. return "-0";
  278. }
  279. if (code instanceof RuntimeValue) {
  280. return code.getCacheVersion();
  281. }
  282. if (code instanceof RegExp && code.toString) {
  283. return code.toString();
  284. }
  285. if (typeof code === "function" && code.toString) {
  286. return `(${code.toString()})`;
  287. }
  288. if (typeof code === "object") {
  289. const items = Object.keys(code).map(key => ({
  290. key,
  291. value: toCacheVersion(
  292. /** @type {Record<string, EXPECTED_ANY>} */
  293. (code)[key]
  294. )
  295. }));
  296. if (items.some(({ value }) => value === undefined)) return;
  297. return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
  298. }
  299. if (typeof code === "bigint") {
  300. return `${code}n`;
  301. }
  302. return `${code}`;
  303. };
  304. const PLUGIN_NAME = "DefinePlugin";
  305. const VALUE_DEP_PREFIX = `webpack/${PLUGIN_NAME} `;
  306. const VALUE_DEP_MAIN = `webpack/${PLUGIN_NAME}_hash`;
  307. const TYPEOF_OPERATOR_REGEXP = /^typeof\s+/;
  308. const WEBPACK_REQUIRE_FUNCTION_REGEXP = new RegExp(
  309. `${RuntimeGlobals.require}\\s*(!?\\.)`
  310. );
  311. const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = new RegExp(RuntimeGlobals.require);
  312. class DefinePlugin {
  313. /**
  314. * Create a new define plugin
  315. * @param {Record<string, CodeValue>} definitions A map of global object definitions
  316. */
  317. constructor(definitions) {
  318. this.definitions = definitions;
  319. }
  320. /**
  321. * @param {GeneratorFn} fn generator function
  322. * @param {true | string[] | RuntimeValueOptions=} options options
  323. * @returns {RuntimeValue} runtime value
  324. */
  325. static runtimeValue(fn, options) {
  326. return new RuntimeValue(fn, options);
  327. }
  328. /**
  329. * Apply the plugin
  330. * @param {Compiler} compiler the compiler instance
  331. * @returns {void}
  332. */
  333. apply(compiler) {
  334. const definitions = this.definitions;
  335. compiler.hooks.compilation.tap(
  336. PLUGIN_NAME,
  337. (compilation, { normalModuleFactory }) => {
  338. const logger = compilation.getLogger("webpack.DefinePlugin");
  339. compilation.dependencyTemplates.set(
  340. ConstDependency,
  341. new ConstDependency.Template()
  342. );
  343. const { runtimeTemplate } = compilation;
  344. const mainHash = createHash(
  345. /** @type {HashFunction} */
  346. (compilation.outputOptions.hashFunction)
  347. );
  348. mainHash.update(
  349. /** @type {string} */
  350. (compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || ""
  351. );
  352. /**
  353. * Handler
  354. * @param {JavascriptParser} parser Parser
  355. * @returns {void}
  356. */
  357. const handler = parser => {
  358. const mainValue =
  359. /** @type {ValueCacheVersion} */
  360. (compilation.valueCacheVersions.get(VALUE_DEP_MAIN));
  361. parser.hooks.program.tap(PLUGIN_NAME, () => {
  362. const buildInfo = /** @type {BuildInfo} */ (
  363. parser.state.module.buildInfo
  364. );
  365. if (!buildInfo.valueDependencies)
  366. buildInfo.valueDependencies = new Map();
  367. buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
  368. });
  369. /**
  370. * @param {string} key key
  371. */
  372. const addValueDependency = key => {
  373. const buildInfo =
  374. /** @type {BuildInfo} */
  375. (parser.state.module.buildInfo);
  376. /** @type {NonNullable<BuildInfo["valueDependencies"]>} */
  377. (buildInfo.valueDependencies).set(
  378. VALUE_DEP_PREFIX + key,
  379. /** @type {ValueCacheVersion} */
  380. (compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key))
  381. );
  382. };
  383. /**
  384. * @template T
  385. * @param {string} key key
  386. * @param {(expression: Expression) => T} fn fn
  387. * @returns {(expression: Expression) => T} result
  388. */
  389. const withValueDependency =
  390. (key, fn) =>
  391. (...args) => {
  392. addValueDependency(key);
  393. return fn(...args);
  394. };
  395. /**
  396. * Walk definitions
  397. * @param {Record<string, CodeValue>} definitions Definitions map
  398. * @param {string} prefix Prefix string
  399. * @returns {void}
  400. */
  401. const walkDefinitions = (definitions, prefix) => {
  402. for (const key of Object.keys(definitions)) {
  403. const code = definitions[key];
  404. if (
  405. code &&
  406. typeof code === "object" &&
  407. !(code instanceof RuntimeValue) &&
  408. !(code instanceof RegExp)
  409. ) {
  410. walkDefinitions(
  411. /** @type {Record<string, CodeValue>} */ (code),
  412. `${prefix + key}.`
  413. );
  414. applyObjectDefine(prefix + key, code);
  415. continue;
  416. }
  417. applyDefineKey(prefix, key);
  418. applyDefine(prefix + key, code);
  419. }
  420. };
  421. /**
  422. * Apply define key
  423. * @param {string} prefix Prefix
  424. * @param {string} key Key
  425. * @returns {void}
  426. */
  427. const applyDefineKey = (prefix, key) => {
  428. const splittedKey = key.split(".");
  429. const firstKey = splittedKey[0];
  430. for (const [i, _] of splittedKey.slice(1).entries()) {
  431. const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
  432. parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
  433. addValueDependency(key);
  434. if (
  435. parser.scope.definitions.get(firstKey) instanceof VariableInfo
  436. ) {
  437. return false;
  438. }
  439. return true;
  440. });
  441. }
  442. };
  443. /**
  444. * Apply Code
  445. * @param {string} key Key
  446. * @param {CodeValue} code Code
  447. * @returns {void}
  448. */
  449. const applyDefine = (key, code) => {
  450. const originalKey = key;
  451. const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key);
  452. if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, "");
  453. let recurse = false;
  454. let recurseTypeof = false;
  455. if (!isTypeof) {
  456. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  457. addValueDependency(originalKey);
  458. return true;
  459. });
  460. parser.hooks.evaluateIdentifier
  461. .for(key)
  462. .tap(PLUGIN_NAME, expr => {
  463. /**
  464. * this is needed in case there is a recursion in the DefinePlugin
  465. * to prevent an endless recursion
  466. * e.g.: new DefinePlugin({
  467. * "a": "b",
  468. * "b": "a"
  469. * });
  470. */
  471. if (recurse) return;
  472. addValueDependency(originalKey);
  473. recurse = true;
  474. const res = parser.evaluate(
  475. toCode(
  476. code,
  477. parser,
  478. compilation.valueCacheVersions,
  479. key,
  480. runtimeTemplate,
  481. logger,
  482. null
  483. )
  484. );
  485. recurse = false;
  486. res.setRange(/** @type {Range} */ (expr.range));
  487. return res;
  488. });
  489. parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
  490. addValueDependency(originalKey);
  491. let strCode = toCode(
  492. code,
  493. parser,
  494. compilation.valueCacheVersions,
  495. originalKey,
  496. runtimeTemplate,
  497. logger,
  498. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  499. null
  500. );
  501. if (parser.scope.inShorthand) {
  502. strCode = `${parser.scope.inShorthand}:${strCode}`;
  503. }
  504. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  505. return toConstantDependency(parser, strCode, [
  506. RuntimeGlobals.require
  507. ])(expr);
  508. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  509. return toConstantDependency(parser, strCode, [
  510. RuntimeGlobals.requireScope
  511. ])(expr);
  512. }
  513. return toConstantDependency(parser, strCode)(expr);
  514. });
  515. }
  516. parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, expr => {
  517. /**
  518. * this is needed in case there is a recursion in the DefinePlugin
  519. * to prevent an endless recursion
  520. * e.g.: new DefinePlugin({
  521. * "typeof a": "typeof b",
  522. * "typeof b": "typeof a"
  523. * });
  524. */
  525. if (recurseTypeof) return;
  526. recurseTypeof = true;
  527. addValueDependency(originalKey);
  528. const codeCode = toCode(
  529. code,
  530. parser,
  531. compilation.valueCacheVersions,
  532. originalKey,
  533. runtimeTemplate,
  534. logger,
  535. null
  536. );
  537. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  538. const res = parser.evaluate(typeofCode);
  539. recurseTypeof = false;
  540. res.setRange(/** @type {Range} */ (expr.range));
  541. return res;
  542. });
  543. parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => {
  544. addValueDependency(originalKey);
  545. const codeCode = toCode(
  546. code,
  547. parser,
  548. compilation.valueCacheVersions,
  549. originalKey,
  550. runtimeTemplate,
  551. logger,
  552. null
  553. );
  554. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  555. const res = parser.evaluate(typeofCode);
  556. if (!res.isString()) return;
  557. return toConstantDependency(
  558. parser,
  559. JSON.stringify(res.string)
  560. ).bind(parser)(expr);
  561. });
  562. };
  563. /**
  564. * Apply Object
  565. * @param {string} key Key
  566. * @param {object} obj Object
  567. * @returns {void}
  568. */
  569. const applyObjectDefine = (key, obj) => {
  570. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  571. addValueDependency(key);
  572. return true;
  573. });
  574. parser.hooks.evaluateIdentifier.for(key).tap(PLUGIN_NAME, expr => {
  575. addValueDependency(key);
  576. return new BasicEvaluatedExpression()
  577. .setTruthy()
  578. .setSideEffects(false)
  579. .setRange(/** @type {Range} */ (expr.range));
  580. });
  581. parser.hooks.evaluateTypeof
  582. .for(key)
  583. .tap(
  584. PLUGIN_NAME,
  585. withValueDependency(key, evaluateToString("object"))
  586. );
  587. parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
  588. addValueDependency(key);
  589. let strCode = stringifyObj(
  590. obj,
  591. parser,
  592. compilation.valueCacheVersions,
  593. key,
  594. runtimeTemplate,
  595. logger,
  596. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  597. getObjKeys(parser.destructuringAssignmentPropertiesFor(expr))
  598. );
  599. if (parser.scope.inShorthand) {
  600. strCode = `${parser.scope.inShorthand}:${strCode}`;
  601. }
  602. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  603. return toConstantDependency(parser, strCode, [
  604. RuntimeGlobals.require
  605. ])(expr);
  606. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  607. return toConstantDependency(parser, strCode, [
  608. RuntimeGlobals.requireScope
  609. ])(expr);
  610. }
  611. return toConstantDependency(parser, strCode)(expr);
  612. });
  613. parser.hooks.typeof
  614. .for(key)
  615. .tap(
  616. PLUGIN_NAME,
  617. withValueDependency(
  618. key,
  619. toConstantDependency(parser, JSON.stringify("object"))
  620. )
  621. );
  622. };
  623. walkDefinitions(definitions, "");
  624. };
  625. normalModuleFactory.hooks.parser
  626. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  627. .tap(PLUGIN_NAME, handler);
  628. normalModuleFactory.hooks.parser
  629. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  630. .tap(PLUGIN_NAME, handler);
  631. normalModuleFactory.hooks.parser
  632. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  633. .tap(PLUGIN_NAME, handler);
  634. /**
  635. * Walk definitions
  636. * @param {Record<string, CodeValue>} definitions Definitions map
  637. * @param {string} prefix Prefix string
  638. * @returns {void}
  639. */
  640. const walkDefinitionsForValues = (definitions, prefix) => {
  641. for (const key of Object.keys(definitions)) {
  642. const code = definitions[key];
  643. const version = /** @type {string} */ (toCacheVersion(code));
  644. const name = VALUE_DEP_PREFIX + prefix + key;
  645. mainHash.update(`|${prefix}${key}`);
  646. const oldVersion = compilation.valueCacheVersions.get(name);
  647. if (oldVersion === undefined) {
  648. compilation.valueCacheVersions.set(name, version);
  649. } else if (oldVersion !== version) {
  650. const warning = new WebpackError(
  651. `${PLUGIN_NAME}\nConflicting values for '${prefix + key}'`
  652. );
  653. warning.details = `'${oldVersion}' !== '${version}'`;
  654. warning.hideStack = true;
  655. compilation.warnings.push(warning);
  656. }
  657. if (
  658. code &&
  659. typeof code === "object" &&
  660. !(code instanceof RuntimeValue) &&
  661. !(code instanceof RegExp)
  662. ) {
  663. walkDefinitionsForValues(
  664. /** @type {Record<string, CodeValue>} */ (code),
  665. `${prefix + key}.`
  666. );
  667. }
  668. }
  669. };
  670. walkDefinitionsForValues(definitions, "");
  671. compilation.valueCacheVersions.set(
  672. VALUE_DEP_MAIN,
  673. /** @type {string} */ (mainHash.digest("hex").slice(0, 8))
  674. );
  675. }
  676. );
  677. }
  678. }
  679. module.exports = DefinePlugin;