DefinePlugin.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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_DYNAMIC,
  9. JAVASCRIPT_MODULE_TYPE_ESM
  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. /**
  336. * @type {Map<string, Set<string>>}
  337. */
  338. const finalByNestedKey = new Map();
  339. /**
  340. * @type {Map<string, Set<string>>}
  341. */
  342. const nestedByFinalKey = new Map();
  343. compiler.hooks.compilation.tap(
  344. PLUGIN_NAME,
  345. (compilation, { normalModuleFactory }) => {
  346. const logger = compilation.getLogger("webpack.DefinePlugin");
  347. compilation.dependencyTemplates.set(
  348. ConstDependency,
  349. new ConstDependency.Template()
  350. );
  351. const { runtimeTemplate } = compilation;
  352. const mainHash = createHash(
  353. /** @type {HashFunction} */
  354. (compilation.outputOptions.hashFunction)
  355. );
  356. mainHash.update(
  357. /** @type {string} */
  358. (compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || ""
  359. );
  360. /**
  361. * Handler
  362. * @param {JavascriptParser} parser Parser
  363. * @returns {void}
  364. */
  365. const handler = parser => {
  366. const hooked = new Set();
  367. const mainValue =
  368. /** @type {ValueCacheVersion} */
  369. (compilation.valueCacheVersions.get(VALUE_DEP_MAIN));
  370. parser.hooks.program.tap(PLUGIN_NAME, () => {
  371. const buildInfo = /** @type {BuildInfo} */ (
  372. parser.state.module.buildInfo
  373. );
  374. if (!buildInfo.valueDependencies) {
  375. buildInfo.valueDependencies = new Map();
  376. }
  377. buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
  378. });
  379. /**
  380. * @param {string} key key
  381. */
  382. const addValueDependency = key => {
  383. const buildInfo =
  384. /** @type {BuildInfo} */
  385. (parser.state.module.buildInfo);
  386. /** @type {NonNullable<BuildInfo["valueDependencies"]>} */
  387. (buildInfo.valueDependencies).set(
  388. VALUE_DEP_PREFIX + key,
  389. /** @type {ValueCacheVersion} */
  390. (compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key))
  391. );
  392. };
  393. /**
  394. * @template T
  395. * @param {string} key key
  396. * @param {(expression: Expression) => T} fn fn
  397. * @returns {(expression: Expression) => T} result
  398. */
  399. const withValueDependency =
  400. (key, fn) =>
  401. (...args) => {
  402. addValueDependency(key);
  403. return fn(...args);
  404. };
  405. /**
  406. * Walk definitions
  407. * @param {Record<string, CodeValue>} definitions Definitions map
  408. * @param {string} prefix Prefix string
  409. * @returns {void}
  410. */
  411. const walkDefinitions = (definitions, prefix) => {
  412. for (const key of Object.keys(definitions)) {
  413. const code = definitions[key];
  414. if (
  415. code &&
  416. typeof code === "object" &&
  417. !(code instanceof RuntimeValue) &&
  418. !(code instanceof RegExp)
  419. ) {
  420. walkDefinitions(
  421. /** @type {Record<string, CodeValue>} */ (code),
  422. `${prefix + key}.`
  423. );
  424. applyObjectDefine(prefix + key, code);
  425. continue;
  426. }
  427. applyDefineKey(prefix, key);
  428. applyDefine(prefix + key, code);
  429. }
  430. };
  431. /**
  432. * Apply define key
  433. * @param {string} prefix Prefix
  434. * @param {string} key Key
  435. * @returns {void}
  436. */
  437. const applyDefineKey = (prefix, key) => {
  438. const splittedKey = key.split(".");
  439. const firstKey = splittedKey[0];
  440. for (const [i, _] of splittedKey.slice(1).entries()) {
  441. const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
  442. parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
  443. addValueDependency(key);
  444. if (
  445. parser.scope.definitions.get(firstKey) instanceof VariableInfo
  446. ) {
  447. return false;
  448. }
  449. return true;
  450. });
  451. }
  452. if (prefix === "") {
  453. const final = splittedKey[splittedKey.length - 1];
  454. const nestedSet = nestedByFinalKey.get(final);
  455. if (!nestedSet || nestedSet.size <= 0) return;
  456. for (const nested of /** @type {Set<string>} */ (nestedSet)) {
  457. if (nested && !hooked.has(nested)) {
  458. // only detect the same nested key once
  459. hooked.add(nested);
  460. parser.hooks.expression.for(nested).tap(
  461. {
  462. name: PLUGIN_NAME,
  463. // why 100? Ensures it runs after object define
  464. stage: 100
  465. },
  466. expr => {
  467. const destructed =
  468. parser.destructuringAssignmentPropertiesFor(expr);
  469. if (destructed === undefined) {
  470. return;
  471. }
  472. /** @type {Record<string, CodeValue>} */
  473. const obj = {};
  474. const finalSet = finalByNestedKey.get(nested);
  475. for (const { id } of destructed) {
  476. const fullKey = `${nested}.${id}`;
  477. if (
  478. !finalSet ||
  479. !finalSet.has(id) ||
  480. !definitions[fullKey]
  481. ) {
  482. return;
  483. }
  484. obj[id] = definitions[fullKey];
  485. }
  486. let strCode = stringifyObj(
  487. obj,
  488. parser,
  489. compilation.valueCacheVersions,
  490. key,
  491. runtimeTemplate,
  492. logger,
  493. !parser.isAsiPosition(
  494. /** @type {Range} */ (expr.range)[0]
  495. ),
  496. getObjKeys(destructed)
  497. );
  498. if (parser.scope.inShorthand) {
  499. strCode = `${parser.scope.inShorthand}:${strCode}`;
  500. }
  501. return toConstantDependency(parser, strCode)(expr);
  502. }
  503. );
  504. }
  505. }
  506. }
  507. };
  508. /**
  509. * Apply Code
  510. * @param {string} key Key
  511. * @param {CodeValue} code Code
  512. * @returns {void}
  513. */
  514. const applyDefine = (key, code) => {
  515. const originalKey = key;
  516. const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key);
  517. if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, "");
  518. let recurse = false;
  519. let recurseTypeof = false;
  520. if (!isTypeof) {
  521. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  522. addValueDependency(originalKey);
  523. return true;
  524. });
  525. parser.hooks.evaluateIdentifier
  526. .for(key)
  527. .tap(PLUGIN_NAME, expr => {
  528. /**
  529. * this is needed in case there is a recursion in the DefinePlugin
  530. * to prevent an endless recursion
  531. * e.g.: new DefinePlugin({
  532. * "a": "b",
  533. * "b": "a"
  534. * });
  535. */
  536. if (recurse) return;
  537. addValueDependency(originalKey);
  538. recurse = true;
  539. const res = parser.evaluate(
  540. toCode(
  541. code,
  542. parser,
  543. compilation.valueCacheVersions,
  544. key,
  545. runtimeTemplate,
  546. logger,
  547. null
  548. )
  549. );
  550. recurse = false;
  551. res.setRange(/** @type {Range} */ (expr.range));
  552. return res;
  553. });
  554. parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
  555. addValueDependency(originalKey);
  556. let strCode = toCode(
  557. code,
  558. parser,
  559. compilation.valueCacheVersions,
  560. originalKey,
  561. runtimeTemplate,
  562. logger,
  563. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  564. null
  565. );
  566. if (parser.scope.inShorthand) {
  567. strCode = `${parser.scope.inShorthand}:${strCode}`;
  568. }
  569. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  570. return toConstantDependency(parser, strCode, [
  571. RuntimeGlobals.require
  572. ])(expr);
  573. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  574. return toConstantDependency(parser, strCode, [
  575. RuntimeGlobals.requireScope
  576. ])(expr);
  577. }
  578. return toConstantDependency(parser, strCode)(expr);
  579. });
  580. }
  581. parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, expr => {
  582. /**
  583. * this is needed in case there is a recursion in the DefinePlugin
  584. * to prevent an endless recursion
  585. * e.g.: new DefinePlugin({
  586. * "typeof a": "typeof b",
  587. * "typeof b": "typeof a"
  588. * });
  589. */
  590. if (recurseTypeof) return;
  591. recurseTypeof = true;
  592. addValueDependency(originalKey);
  593. const codeCode = toCode(
  594. code,
  595. parser,
  596. compilation.valueCacheVersions,
  597. originalKey,
  598. runtimeTemplate,
  599. logger,
  600. null
  601. );
  602. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  603. const res = parser.evaluate(typeofCode);
  604. recurseTypeof = false;
  605. res.setRange(/** @type {Range} */ (expr.range));
  606. return res;
  607. });
  608. parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => {
  609. addValueDependency(originalKey);
  610. const codeCode = toCode(
  611. code,
  612. parser,
  613. compilation.valueCacheVersions,
  614. originalKey,
  615. runtimeTemplate,
  616. logger,
  617. null
  618. );
  619. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  620. const res = parser.evaluate(typeofCode);
  621. if (!res.isString()) return;
  622. return toConstantDependency(
  623. parser,
  624. JSON.stringify(res.string)
  625. ).bind(parser)(expr);
  626. });
  627. };
  628. /**
  629. * Apply Object
  630. * @param {string} key Key
  631. * @param {object} obj Object
  632. * @returns {void}
  633. */
  634. const applyObjectDefine = (key, obj) => {
  635. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  636. addValueDependency(key);
  637. return true;
  638. });
  639. parser.hooks.evaluateIdentifier.for(key).tap(PLUGIN_NAME, expr => {
  640. addValueDependency(key);
  641. return new BasicEvaluatedExpression()
  642. .setTruthy()
  643. .setSideEffects(false)
  644. .setRange(/** @type {Range} */ (expr.range));
  645. });
  646. parser.hooks.evaluateTypeof
  647. .for(key)
  648. .tap(
  649. PLUGIN_NAME,
  650. withValueDependency(key, evaluateToString("object"))
  651. );
  652. parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
  653. addValueDependency(key);
  654. let strCode = stringifyObj(
  655. obj,
  656. parser,
  657. compilation.valueCacheVersions,
  658. key,
  659. runtimeTemplate,
  660. logger,
  661. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  662. getObjKeys(parser.destructuringAssignmentPropertiesFor(expr))
  663. );
  664. if (parser.scope.inShorthand) {
  665. strCode = `${parser.scope.inShorthand}:${strCode}`;
  666. }
  667. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  668. return toConstantDependency(parser, strCode, [
  669. RuntimeGlobals.require
  670. ])(expr);
  671. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  672. return toConstantDependency(parser, strCode, [
  673. RuntimeGlobals.requireScope
  674. ])(expr);
  675. }
  676. return toConstantDependency(parser, strCode)(expr);
  677. });
  678. parser.hooks.typeof
  679. .for(key)
  680. .tap(
  681. PLUGIN_NAME,
  682. withValueDependency(
  683. key,
  684. toConstantDependency(parser, JSON.stringify("object"))
  685. )
  686. );
  687. };
  688. walkDefinitions(definitions, "");
  689. };
  690. normalModuleFactory.hooks.parser
  691. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  692. .tap(PLUGIN_NAME, handler);
  693. normalModuleFactory.hooks.parser
  694. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  695. .tap(PLUGIN_NAME, handler);
  696. normalModuleFactory.hooks.parser
  697. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  698. .tap(PLUGIN_NAME, handler);
  699. /**
  700. * Walk definitions
  701. * @param {Record<string, CodeValue>} definitions Definitions map
  702. * @param {string} prefix Prefix string
  703. * @returns {void}
  704. */
  705. const walkDefinitionsForValues = (definitions, prefix) => {
  706. for (const key of Object.keys(definitions)) {
  707. const code = definitions[key];
  708. const version = /** @type {string} */ (toCacheVersion(code));
  709. const name = VALUE_DEP_PREFIX + prefix + key;
  710. mainHash.update(`|${prefix}${key}`);
  711. const oldVersion = compilation.valueCacheVersions.get(name);
  712. if (oldVersion === undefined) {
  713. compilation.valueCacheVersions.set(name, version);
  714. } else if (oldVersion !== version) {
  715. const warning = new WebpackError(
  716. `${PLUGIN_NAME}\nConflicting values for '${prefix + key}'`
  717. );
  718. warning.details = `'${oldVersion}' !== '${version}'`;
  719. warning.hideStack = true;
  720. compilation.warnings.push(warning);
  721. }
  722. if (
  723. code &&
  724. typeof code === "object" &&
  725. !(code instanceof RuntimeValue) &&
  726. !(code instanceof RegExp)
  727. ) {
  728. walkDefinitionsForValues(
  729. /** @type {Record<string, CodeValue>} */ (code),
  730. `${prefix + key}.`
  731. );
  732. }
  733. }
  734. };
  735. /**
  736. * @param {Record<string, CodeValue>} definitions Definitions map
  737. * @returns {void}
  738. */
  739. const walkDefinitionsForKeys = definitions => {
  740. /**
  741. * @param {Map<string, Set<string>>} map Map
  742. * @param {string} key key
  743. * @param {string} value v
  744. * @returns {void}
  745. */
  746. const addToMap = (map, key, value) => {
  747. if (map.has(key)) {
  748. /** @type {Set<string>} */
  749. (map.get(key)).add(value);
  750. } else {
  751. map.set(key, new Set([value]));
  752. }
  753. };
  754. for (const key of Object.keys(definitions)) {
  755. const code = definitions[key];
  756. if (
  757. !code ||
  758. typeof code === "object" ||
  759. TYPEOF_OPERATOR_REGEXP.test(key)
  760. ) {
  761. continue;
  762. }
  763. const idx = key.lastIndexOf(".");
  764. if (idx <= 0 || idx >= key.length - 1) {
  765. continue;
  766. }
  767. const nested = key.slice(0, idx);
  768. const final = key.slice(idx + 1);
  769. addToMap(finalByNestedKey, nested, final);
  770. addToMap(nestedByFinalKey, final, nested);
  771. }
  772. };
  773. walkDefinitionsForKeys(definitions);
  774. walkDefinitionsForValues(definitions, "");
  775. compilation.valueCacheVersions.set(
  776. VALUE_DEP_MAIN,
  777. /** @type {string} */ (mainHash.digest("hex").slice(0, 8))
  778. );
  779. }
  780. );
  781. }
  782. }
  783. module.exports = DefinePlugin;