DefinePlugin.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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.collectDestructuringAssignmentProperties.tap(
  461. PLUGIN_NAME,
  462. (expr) => {
  463. const nameInfo = parser.getNameForExpression(expr);
  464. if (nameInfo && nameInfo.name === nested) return true;
  465. }
  466. );
  467. parser.hooks.expression.for(nested).tap(
  468. {
  469. name: PLUGIN_NAME,
  470. // why 100? Ensures it runs after object define
  471. stage: 100
  472. },
  473. (expr) => {
  474. const destructed =
  475. parser.destructuringAssignmentPropertiesFor(expr);
  476. if (destructed === undefined) {
  477. return;
  478. }
  479. /** @type {Record<string, CodeValue>} */
  480. const obj = {};
  481. const finalSet = finalByNestedKey.get(nested);
  482. for (const { id } of destructed) {
  483. const fullKey = `${nested}.${id}`;
  484. if (
  485. !finalSet ||
  486. !finalSet.has(id) ||
  487. !definitions[fullKey]
  488. ) {
  489. return;
  490. }
  491. obj[id] = definitions[fullKey];
  492. }
  493. let strCode = stringifyObj(
  494. obj,
  495. parser,
  496. compilation.valueCacheVersions,
  497. key,
  498. runtimeTemplate,
  499. logger,
  500. !parser.isAsiPosition(
  501. /** @type {Range} */ (expr.range)[0]
  502. ),
  503. getObjKeys(destructed)
  504. );
  505. if (parser.scope.inShorthand) {
  506. strCode = `${parser.scope.inShorthand}:${strCode}`;
  507. }
  508. return toConstantDependency(parser, strCode)(expr);
  509. }
  510. );
  511. }
  512. }
  513. }
  514. };
  515. /**
  516. * Apply Code
  517. * @param {string} key Key
  518. * @param {CodeValue} code Code
  519. * @returns {void}
  520. */
  521. const applyDefine = (key, code) => {
  522. const originalKey = key;
  523. const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key);
  524. if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, "");
  525. let recurse = false;
  526. let recurseTypeof = false;
  527. if (!isTypeof) {
  528. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  529. addValueDependency(originalKey);
  530. return true;
  531. });
  532. parser.hooks.evaluateIdentifier
  533. .for(key)
  534. .tap(PLUGIN_NAME, (expr) => {
  535. /**
  536. * this is needed in case there is a recursion in the DefinePlugin
  537. * to prevent an endless recursion
  538. * e.g.: new DefinePlugin({
  539. * "a": "b",
  540. * "b": "a"
  541. * });
  542. */
  543. if (recurse) return;
  544. addValueDependency(originalKey);
  545. recurse = true;
  546. const res = parser.evaluate(
  547. toCode(
  548. code,
  549. parser,
  550. compilation.valueCacheVersions,
  551. key,
  552. runtimeTemplate,
  553. logger,
  554. null
  555. )
  556. );
  557. recurse = false;
  558. res.setRange(/** @type {Range} */ (expr.range));
  559. return res;
  560. });
  561. parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => {
  562. addValueDependency(originalKey);
  563. let strCode = toCode(
  564. code,
  565. parser,
  566. compilation.valueCacheVersions,
  567. originalKey,
  568. runtimeTemplate,
  569. logger,
  570. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  571. null
  572. );
  573. if (parser.scope.inShorthand) {
  574. strCode = `${parser.scope.inShorthand}:${strCode}`;
  575. }
  576. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  577. return toConstantDependency(parser, strCode, [
  578. RuntimeGlobals.require
  579. ])(expr);
  580. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  581. return toConstantDependency(parser, strCode, [
  582. RuntimeGlobals.requireScope
  583. ])(expr);
  584. }
  585. return toConstantDependency(parser, strCode)(expr);
  586. });
  587. }
  588. parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, (expr) => {
  589. /**
  590. * this is needed in case there is a recursion in the DefinePlugin
  591. * to prevent an endless recursion
  592. * e.g.: new DefinePlugin({
  593. * "typeof a": "typeof b",
  594. * "typeof b": "typeof a"
  595. * });
  596. */
  597. if (recurseTypeof) return;
  598. recurseTypeof = true;
  599. addValueDependency(originalKey);
  600. const codeCode = toCode(
  601. code,
  602. parser,
  603. compilation.valueCacheVersions,
  604. originalKey,
  605. runtimeTemplate,
  606. logger,
  607. null
  608. );
  609. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  610. const res = parser.evaluate(typeofCode);
  611. recurseTypeof = false;
  612. res.setRange(/** @type {Range} */ (expr.range));
  613. return res;
  614. });
  615. parser.hooks.typeof.for(key).tap(PLUGIN_NAME, (expr) => {
  616. addValueDependency(originalKey);
  617. const codeCode = toCode(
  618. code,
  619. parser,
  620. compilation.valueCacheVersions,
  621. originalKey,
  622. runtimeTemplate,
  623. logger,
  624. null
  625. );
  626. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  627. const res = parser.evaluate(typeofCode);
  628. if (!res.isString()) return;
  629. return toConstantDependency(
  630. parser,
  631. JSON.stringify(res.string)
  632. ).bind(parser)(expr);
  633. });
  634. };
  635. /**
  636. * Apply Object
  637. * @param {string} key Key
  638. * @param {object} obj Object
  639. * @returns {void}
  640. */
  641. const applyObjectDefine = (key, obj) => {
  642. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  643. addValueDependency(key);
  644. return true;
  645. });
  646. parser.hooks.evaluateIdentifier
  647. .for(key)
  648. .tap(PLUGIN_NAME, (expr) => {
  649. addValueDependency(key);
  650. return new BasicEvaluatedExpression()
  651. .setTruthy()
  652. .setSideEffects(false)
  653. .setRange(/** @type {Range} */ (expr.range));
  654. });
  655. parser.hooks.evaluateTypeof
  656. .for(key)
  657. .tap(
  658. PLUGIN_NAME,
  659. withValueDependency(key, evaluateToString("object"))
  660. );
  661. parser.hooks.collectDestructuringAssignmentProperties.tap(
  662. PLUGIN_NAME,
  663. (expr) => {
  664. const nameInfo = parser.getNameForExpression(expr);
  665. if (nameInfo && nameInfo.name === key) return true;
  666. }
  667. );
  668. parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => {
  669. addValueDependency(key);
  670. let strCode = stringifyObj(
  671. obj,
  672. parser,
  673. compilation.valueCacheVersions,
  674. key,
  675. runtimeTemplate,
  676. logger,
  677. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  678. getObjKeys(parser.destructuringAssignmentPropertiesFor(expr))
  679. );
  680. if (parser.scope.inShorthand) {
  681. strCode = `${parser.scope.inShorthand}:${strCode}`;
  682. }
  683. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  684. return toConstantDependency(parser, strCode, [
  685. RuntimeGlobals.require
  686. ])(expr);
  687. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  688. return toConstantDependency(parser, strCode, [
  689. RuntimeGlobals.requireScope
  690. ])(expr);
  691. }
  692. return toConstantDependency(parser, strCode)(expr);
  693. });
  694. parser.hooks.typeof
  695. .for(key)
  696. .tap(
  697. PLUGIN_NAME,
  698. withValueDependency(
  699. key,
  700. toConstantDependency(parser, JSON.stringify("object"))
  701. )
  702. );
  703. };
  704. walkDefinitions(definitions, "");
  705. };
  706. normalModuleFactory.hooks.parser
  707. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  708. .tap(PLUGIN_NAME, handler);
  709. normalModuleFactory.hooks.parser
  710. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  711. .tap(PLUGIN_NAME, handler);
  712. normalModuleFactory.hooks.parser
  713. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  714. .tap(PLUGIN_NAME, handler);
  715. /**
  716. * Walk definitions
  717. * @param {Record<string, CodeValue>} definitions Definitions map
  718. * @param {string} prefix Prefix string
  719. * @returns {void}
  720. */
  721. const walkDefinitionsForValues = (definitions, prefix) => {
  722. for (const key of Object.keys(definitions)) {
  723. const code = definitions[key];
  724. const version = /** @type {string} */ (toCacheVersion(code));
  725. const name = VALUE_DEP_PREFIX + prefix + key;
  726. mainHash.update(`|${prefix}${key}`);
  727. const oldVersion = compilation.valueCacheVersions.get(name);
  728. if (oldVersion === undefined) {
  729. compilation.valueCacheVersions.set(name, version);
  730. } else if (oldVersion !== version) {
  731. const warning = new WebpackError(
  732. `${PLUGIN_NAME}\nConflicting values for '${prefix + key}'`
  733. );
  734. warning.details = `'${oldVersion}' !== '${version}'`;
  735. warning.hideStack = true;
  736. compilation.warnings.push(warning);
  737. }
  738. if (
  739. code &&
  740. typeof code === "object" &&
  741. !(code instanceof RuntimeValue) &&
  742. !(code instanceof RegExp)
  743. ) {
  744. walkDefinitionsForValues(
  745. /** @type {Record<string, CodeValue>} */ (code),
  746. `${prefix + key}.`
  747. );
  748. }
  749. }
  750. };
  751. /**
  752. * @param {Record<string, CodeValue>} definitions Definitions map
  753. * @returns {void}
  754. */
  755. const walkDefinitionsForKeys = (definitions) => {
  756. /**
  757. * @param {Map<string, Set<string>>} map Map
  758. * @param {string} key key
  759. * @param {string} value v
  760. * @returns {void}
  761. */
  762. const addToMap = (map, key, value) => {
  763. if (map.has(key)) {
  764. /** @type {Set<string>} */
  765. (map.get(key)).add(value);
  766. } else {
  767. map.set(key, new Set([value]));
  768. }
  769. };
  770. for (const key of Object.keys(definitions)) {
  771. const code = definitions[key];
  772. if (
  773. !code ||
  774. typeof code === "object" ||
  775. TYPEOF_OPERATOR_REGEXP.test(key)
  776. ) {
  777. continue;
  778. }
  779. const idx = key.lastIndexOf(".");
  780. if (idx <= 0 || idx >= key.length - 1) {
  781. continue;
  782. }
  783. const nested = key.slice(0, idx);
  784. const final = key.slice(idx + 1);
  785. addToMap(finalByNestedKey, nested, final);
  786. addToMap(nestedByFinalKey, final, nested);
  787. }
  788. };
  789. walkDefinitionsForKeys(definitions);
  790. walkDefinitionsForValues(definitions, "");
  791. compilation.valueCacheVersions.set(
  792. VALUE_DEP_MAIN,
  793. /** @type {string} */ (mainHash.digest("hex").slice(0, 8))
  794. );
  795. }
  796. );
  797. }
  798. }
  799. module.exports = DefinePlugin;