CommonJsExportRequireDependency.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Dependency = require("../Dependency");
  7. const { UsageState } = require("../ExportsInfo");
  8. const Template = require("../Template");
  9. const { equals } = require("../util/ArrayHelpers");
  10. const makeSerializable = require("../util/makeSerializable");
  11. const propertyAccess = require("../util/propertyAccess");
  12. const { handleDependencyBase } = require("./CommonJsDependencyHelpers");
  13. const ModuleDependency = require("./ModuleDependency");
  14. const processExportInfo = require("./processExportInfo");
  15. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  16. /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
  17. /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
  18. /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */
  19. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  20. /** @typedef {import("../ExportsInfo")} ExportsInfo */
  21. /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */
  22. /** @typedef {import("../Module")} Module */
  23. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  24. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  25. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  26. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  27. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  28. /** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */
  29. const idsSymbol = Symbol("CommonJsExportRequireDependency.ids");
  30. const EMPTY_OBJECT = {};
  31. class CommonJsExportRequireDependency extends ModuleDependency {
  32. /**
  33. * @param {Range} range range
  34. * @param {Range | null} valueRange value range
  35. * @param {CommonJSDependencyBaseKeywords} base base
  36. * @param {string[]} names names
  37. * @param {string} request request
  38. * @param {string[]} ids ids
  39. * @param {boolean} resultUsed true, when the result is used
  40. */
  41. constructor(range, valueRange, base, names, request, ids, resultUsed) {
  42. super(request);
  43. this.range = range;
  44. this.valueRange = valueRange;
  45. this.base = base;
  46. this.names = names;
  47. this.ids = ids;
  48. this.resultUsed = resultUsed;
  49. this.asiSafe = undefined;
  50. }
  51. get type() {
  52. return "cjs export require";
  53. }
  54. /**
  55. * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module
  56. */
  57. couldAffectReferencingModule() {
  58. return Dependency.TRANSITIVE;
  59. }
  60. /**
  61. * @param {ModuleGraph} moduleGraph the module graph
  62. * @returns {string[]} the imported id
  63. */
  64. getIds(moduleGraph) {
  65. return (
  66. /** @type {TODO} */ (moduleGraph.getMeta(this))[idsSymbol] || this.ids
  67. );
  68. }
  69. /**
  70. * @param {ModuleGraph} moduleGraph the module graph
  71. * @param {string[]} ids the imported ids
  72. * @returns {void}
  73. */
  74. setIds(moduleGraph, ids) {
  75. /** @type {TODO} */ (moduleGraph.getMeta(this))[idsSymbol] = ids;
  76. }
  77. /**
  78. * Returns list of exports referenced by this dependency
  79. * @param {ModuleGraph} moduleGraph module graph
  80. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  81. * @returns {(string[] | ReferencedExport)[]} referenced exports
  82. */
  83. getReferencedExports(moduleGraph, runtime) {
  84. const ids = this.getIds(moduleGraph);
  85. const getFullResult = () => {
  86. if (ids.length === 0) {
  87. return Dependency.EXPORTS_OBJECT_REFERENCED;
  88. } else {
  89. return [
  90. {
  91. name: ids,
  92. canMangle: false
  93. }
  94. ];
  95. }
  96. };
  97. if (this.resultUsed) return getFullResult();
  98. /** @type {ExportsInfo | undefined} */
  99. let exportsInfo = moduleGraph.getExportsInfo(
  100. /** @type {Module} */ (moduleGraph.getParentModule(this))
  101. );
  102. for (const name of this.names) {
  103. const exportInfo = /** @type {ExportInfo} */ (
  104. exportsInfo.getReadOnlyExportInfo(name)
  105. );
  106. const used = exportInfo.getUsed(runtime);
  107. if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED;
  108. if (used !== UsageState.OnlyPropertiesUsed) return getFullResult();
  109. exportsInfo = exportInfo.exportsInfo;
  110. if (!exportsInfo) return getFullResult();
  111. }
  112. if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) {
  113. return getFullResult();
  114. }
  115. /** @type {string[][]} */
  116. const referencedExports = [];
  117. for (const exportInfo of exportsInfo.orderedExports) {
  118. processExportInfo(
  119. runtime,
  120. referencedExports,
  121. ids.concat(exportInfo.name),
  122. exportInfo,
  123. false
  124. );
  125. }
  126. return referencedExports.map(name => ({
  127. name,
  128. canMangle: false
  129. }));
  130. }
  131. /**
  132. * Returns the exported names
  133. * @param {ModuleGraph} moduleGraph module graph
  134. * @returns {ExportsSpec | undefined} export names
  135. */
  136. getExports(moduleGraph) {
  137. const ids = this.getIds(moduleGraph);
  138. if (this.names.length === 1) {
  139. const name = this.names[0];
  140. const from = moduleGraph.getConnection(this);
  141. if (!from) return;
  142. return {
  143. exports: [
  144. {
  145. name,
  146. from,
  147. export: ids.length === 0 ? null : ids,
  148. // we can't mangle names that are in an empty object
  149. // because one could access the prototype property
  150. // when export isn't set yet
  151. canMangle: !(name in EMPTY_OBJECT) && false
  152. }
  153. ],
  154. dependencies: [from.module]
  155. };
  156. } else if (this.names.length > 0) {
  157. const name = this.names[0];
  158. return {
  159. exports: [
  160. {
  161. name,
  162. // we can't mangle names that are in an empty object
  163. // because one could access the prototype property
  164. // when export isn't set yet
  165. canMangle: !(name in EMPTY_OBJECT) && false
  166. }
  167. ],
  168. dependencies: undefined
  169. };
  170. } else {
  171. const from = moduleGraph.getConnection(this);
  172. if (!from) return;
  173. const reexportInfo = this.getStarReexports(
  174. moduleGraph,
  175. undefined,
  176. from.module
  177. );
  178. if (reexportInfo) {
  179. return {
  180. exports: Array.from(
  181. /** @type {TODO} */ (reexportInfo).exports,
  182. name => {
  183. return {
  184. name,
  185. from,
  186. export: ids.concat(name),
  187. canMangle: !(name in EMPTY_OBJECT) && false
  188. };
  189. }
  190. ),
  191. // TODO handle deep reexports
  192. dependencies: [from.module]
  193. };
  194. } else {
  195. return {
  196. exports: true,
  197. from: ids.length === 0 ? from : undefined,
  198. canMangle: false,
  199. dependencies: [from.module]
  200. };
  201. }
  202. }
  203. }
  204. /**
  205. * @param {ModuleGraph} moduleGraph the module graph
  206. * @param {RuntimeSpec} runtime the runtime
  207. * @param {Module} importedModule the imported module (optional)
  208. * @returns {{exports?: Set<string>, checked?: Set<string>} | undefined} information
  209. */
  210. getStarReexports(
  211. moduleGraph,
  212. runtime,
  213. importedModule = /** @type {Module} */ (moduleGraph.getModule(this))
  214. ) {
  215. /** @type {ExportsInfo | undefined} */
  216. let importedExportsInfo = moduleGraph.getExportsInfo(importedModule);
  217. const ids = this.getIds(moduleGraph);
  218. if (ids.length > 0)
  219. importedExportsInfo = importedExportsInfo.getNestedExportsInfo(ids);
  220. /** @type {ExportsInfo | undefined} */
  221. let exportsInfo = moduleGraph.getExportsInfo(
  222. /** @type {Module} */ (moduleGraph.getParentModule(this))
  223. );
  224. if (this.names.length > 0)
  225. exportsInfo = exportsInfo.getNestedExportsInfo(this.names);
  226. const noExtraExports =
  227. importedExportsInfo &&
  228. importedExportsInfo.otherExportsInfo.provided === false;
  229. const noExtraImports =
  230. exportsInfo &&
  231. exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused;
  232. if (!noExtraExports && !noExtraImports) {
  233. return;
  234. }
  235. const isNamespaceImport =
  236. importedModule.getExportsType(moduleGraph, false) === "namespace";
  237. /** @type {Set<string>} */
  238. const exports = new Set();
  239. /** @type {Set<string>} */
  240. const checked = new Set();
  241. if (noExtraImports) {
  242. for (const exportInfo of /** @type {ExportsInfo} */ (exportsInfo)
  243. .orderedExports) {
  244. const name = exportInfo.name;
  245. if (exportInfo.getUsed(runtime) === UsageState.Unused) continue;
  246. if (name === "__esModule" && isNamespaceImport) {
  247. exports.add(name);
  248. } else if (importedExportsInfo) {
  249. const importedExportInfo =
  250. importedExportsInfo.getReadOnlyExportInfo(name);
  251. if (importedExportInfo.provided === false) continue;
  252. exports.add(name);
  253. if (importedExportInfo.provided === true) continue;
  254. checked.add(name);
  255. } else {
  256. exports.add(name);
  257. checked.add(name);
  258. }
  259. }
  260. } else if (noExtraExports) {
  261. for (const importedExportInfo of /** @type {ExportsInfo} */ (
  262. importedExportsInfo
  263. ).orderedExports) {
  264. const name = importedExportInfo.name;
  265. if (importedExportInfo.provided === false) continue;
  266. if (exportsInfo) {
  267. const exportInfo = exportsInfo.getReadOnlyExportInfo(name);
  268. if (exportInfo.getUsed(runtime) === UsageState.Unused) continue;
  269. }
  270. exports.add(name);
  271. if (importedExportInfo.provided === true) continue;
  272. checked.add(name);
  273. }
  274. if (isNamespaceImport) {
  275. exports.add("__esModule");
  276. checked.delete("__esModule");
  277. }
  278. }
  279. return { exports, checked };
  280. }
  281. /**
  282. * @param {ObjectSerializerContext} context context
  283. */
  284. serialize(context) {
  285. const { write } = context;
  286. write(this.asiSafe);
  287. write(this.range);
  288. write(this.valueRange);
  289. write(this.base);
  290. write(this.names);
  291. write(this.ids);
  292. write(this.resultUsed);
  293. super.serialize(context);
  294. }
  295. /**
  296. * @param {ObjectDeserializerContext} context context
  297. */
  298. deserialize(context) {
  299. const { read } = context;
  300. this.asiSafe = read();
  301. this.range = read();
  302. this.valueRange = read();
  303. this.base = read();
  304. this.names = read();
  305. this.ids = read();
  306. this.resultUsed = read();
  307. super.deserialize(context);
  308. }
  309. }
  310. makeSerializable(
  311. CommonJsExportRequireDependency,
  312. "webpack/lib/dependencies/CommonJsExportRequireDependency"
  313. );
  314. CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends (
  315. ModuleDependency.Template
  316. ) {
  317. /**
  318. * @param {Dependency} dependency the dependency for which the template should be applied
  319. * @param {ReplaceSource} source the current replace source which can be modified
  320. * @param {DependencyTemplateContext} templateContext the context object
  321. * @returns {void}
  322. */
  323. apply(
  324. dependency,
  325. source,
  326. {
  327. module,
  328. runtimeTemplate,
  329. chunkGraph,
  330. moduleGraph,
  331. runtimeRequirements,
  332. runtime
  333. }
  334. ) {
  335. const dep = /** @type {CommonJsExportRequireDependency} */ (dependency);
  336. const used = moduleGraph
  337. .getExportsInfo(module)
  338. .getUsedName(dep.names, runtime);
  339. const [type, base] = handleDependencyBase(
  340. dep.base,
  341. module,
  342. runtimeRequirements
  343. );
  344. const importedModule = moduleGraph.getModule(dep);
  345. let requireExpr = runtimeTemplate.moduleExports({
  346. module: importedModule,
  347. chunkGraph,
  348. request: dep.request,
  349. weak: dep.weak,
  350. runtimeRequirements
  351. });
  352. if (importedModule) {
  353. const ids = dep.getIds(moduleGraph);
  354. const usedImported = moduleGraph
  355. .getExportsInfo(importedModule)
  356. .getUsedName(ids, runtime);
  357. if (usedImported) {
  358. const comment = equals(usedImported, ids)
  359. ? ""
  360. : Template.toNormalComment(propertyAccess(ids)) + " ";
  361. requireExpr += `${comment}${propertyAccess(usedImported)}`;
  362. }
  363. }
  364. switch (type) {
  365. case "expression":
  366. source.replace(
  367. dep.range[0],
  368. dep.range[1] - 1,
  369. used
  370. ? `${base}${propertyAccess(used)} = ${requireExpr}`
  371. : `/* unused reexport */ ${requireExpr}`
  372. );
  373. return;
  374. case "Object.defineProperty":
  375. throw new Error("TODO");
  376. default:
  377. throw new Error("Unexpected type");
  378. }
  379. }
  380. };
  381. module.exports = CommonJsExportRequireDependency;