Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

708 строки
20 KiB

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