HarmonyImportDependencyParserPlugin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const HotModuleReplacementPlugin = require("../HotModuleReplacementPlugin");
  7. const InnerGraph = require("../optimize/InnerGraph");
  8. const ConstDependency = require("./ConstDependency");
  9. const HarmonyAcceptDependency = require("./HarmonyAcceptDependency");
  10. const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency");
  11. const HarmonyEvaluatedImportSpecifierDependency = require("./HarmonyEvaluatedImportSpecifierDependency");
  12. const HarmonyExports = require("./HarmonyExports");
  13. const { ExportPresenceModes } = require("./HarmonyImportDependency");
  14. const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency");
  15. const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency");
  16. /** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
  17. /** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
  18. /** @typedef {import("estree").Identifier} Identifier */
  19. /** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
  20. /** @typedef {import("estree").ImportExpression} ImportExpression */
  21. /** @typedef {import("estree").Literal} Literal */
  22. /** @typedef {import("estree").MemberExpression} MemberExpression */
  23. /** @typedef {import("estree").ObjectExpression} ObjectExpression */
  24. /** @typedef {import("estree").Property} Property */
  25. /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  26. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  27. /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
  28. /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
  29. /** @typedef {import("../javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */
  30. /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */
  31. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  32. /** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */
  33. /** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */
  34. /** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */
  35. const harmonySpecifierTag = Symbol("harmony import");
  36. /**
  37. * @typedef {object} HarmonySettings
  38. * @property {string[]} ids
  39. * @property {string} source
  40. * @property {number} sourceOrder
  41. * @property {string} name
  42. * @property {boolean} await
  43. * @property {Record<string, any> | undefined} assertions
  44. */
  45. /**
  46. * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | (ImportExpression & { arguments?: ObjectExpression[] })} node node with assertions
  47. * @returns {ImportAttributes} import attributes
  48. */
  49. function getAttributes(node) {
  50. if (
  51. node.type === "ImportExpression" &&
  52. node.arguments &&
  53. node.arguments[0] &&
  54. node.arguments[0].type === "ObjectExpression" &&
  55. node.arguments[0].properties[0] &&
  56. node.arguments[0].properties[0].type === "Property" &&
  57. node.arguments[0].properties[0].value.type === "ObjectExpression" &&
  58. node.arguments[0].properties[0].value.properties
  59. ) {
  60. const properties =
  61. /** @type {Property[]} */
  62. (node.arguments[0].properties[0].value.properties);
  63. const result = /** @type {ImportAttributes} */ ({});
  64. for (const property of properties) {
  65. const key =
  66. /** @type {string} */
  67. (
  68. property.key.type === "Identifier"
  69. ? property.key.name
  70. : /** @type {Literal} */ (property.key).value
  71. );
  72. result[key] =
  73. /** @type {string} */
  74. (/** @type {Literal} */ (property.value).value);
  75. }
  76. const key =
  77. node.arguments[0].properties[0].key.type === "Identifier"
  78. ? node.arguments[0].properties[0].key.name
  79. : /** @type {Literal} */ (node.arguments[0].properties[0].key).value;
  80. if (key === "assert") {
  81. result._isLegacyAssert = true;
  82. }
  83. return result;
  84. }
  85. // TODO remove cast when @types/estree has been updated to import assertions
  86. const isImportAssertion =
  87. /** @type {{ assertions?: ImportAttributeNode[] }} */ (node).assertions !==
  88. undefined;
  89. const attributes = isImportAssertion
  90. ? /** @type {{ assertions?: ImportAttributeNode[] }} */ (node).assertions
  91. : /** @type {{ attributes?: ImportAttributeNode[] }} */ (node).attributes;
  92. if (attributes === undefined) {
  93. return undefined;
  94. }
  95. const result = /** @type {ImportAttributes} */ ({});
  96. for (const attribute of attributes) {
  97. const key =
  98. /** @type {string} */
  99. (
  100. attribute.key.type === "Identifier"
  101. ? attribute.key.name
  102. : attribute.key.value
  103. );
  104. result[key] = /** @type {string} */ (attribute.value.value);
  105. }
  106. if (isImportAssertion) {
  107. result._isLegacyAssert = true;
  108. }
  109. return result;
  110. }
  111. module.exports = class HarmonyImportDependencyParserPlugin {
  112. /**
  113. * @param {JavascriptParserOptions} options options
  114. */
  115. constructor(options) {
  116. this.exportPresenceMode =
  117. options.importExportsPresence !== undefined
  118. ? ExportPresenceModes.fromUserOption(options.importExportsPresence)
  119. : options.exportsPresence !== undefined
  120. ? ExportPresenceModes.fromUserOption(options.exportsPresence)
  121. : options.strictExportPresence
  122. ? ExportPresenceModes.ERROR
  123. : ExportPresenceModes.AUTO;
  124. this.strictThisContextOnImports = options.strictThisContextOnImports;
  125. }
  126. /**
  127. * @param {JavascriptParser} parser the parser
  128. * @returns {void}
  129. */
  130. apply(parser) {
  131. const { exportPresenceMode } = this;
  132. function getNonOptionalPart(members, membersOptionals) {
  133. let i = 0;
  134. while (i < members.length && membersOptionals[i] === false) i++;
  135. return i !== members.length ? members.slice(0, i) : members;
  136. }
  137. function getNonOptionalMemberChain(node, count) {
  138. while (count--) node = node.object;
  139. return node;
  140. }
  141. parser.hooks.isPure
  142. .for("Identifier")
  143. .tap("HarmonyImportDependencyParserPlugin", expression => {
  144. const expr = /** @type {Identifier} */ (expression);
  145. if (
  146. parser.isVariableDefined(expr.name) ||
  147. parser.getTagData(expr.name, harmonySpecifierTag)
  148. ) {
  149. return true;
  150. }
  151. });
  152. parser.hooks.import.tap(
  153. "HarmonyImportDependencyParserPlugin",
  154. (statement, source) => {
  155. parser.state.lastHarmonyImportOrder =
  156. (parser.state.lastHarmonyImportOrder || 0) + 1;
  157. const clearDep = new ConstDependency(
  158. parser.isAsiPosition(/** @type {Range} */ (statement.range)[0])
  159. ? ";"
  160. : "",
  161. /** @type {Range} */ (statement.range)
  162. );
  163. clearDep.loc = /** @type {DependencyLocation} */ (statement.loc);
  164. parser.state.module.addPresentationalDependency(clearDep);
  165. parser.unsetAsiPosition(/** @type {Range} */ (statement.range)[1]);
  166. const attributes = getAttributes(statement);
  167. const sideEffectDep = new HarmonyImportSideEffectDependency(
  168. /** @type {string} */ (source),
  169. parser.state.lastHarmonyImportOrder,
  170. attributes
  171. );
  172. sideEffectDep.loc = /** @type {DependencyLocation} */ (statement.loc);
  173. parser.state.module.addDependency(sideEffectDep);
  174. return true;
  175. }
  176. );
  177. parser.hooks.importSpecifier.tap(
  178. "HarmonyImportDependencyParserPlugin",
  179. (statement, source, id, name) => {
  180. const ids = id === null ? [] : [id];
  181. parser.tagVariable(name, harmonySpecifierTag, {
  182. name,
  183. source,
  184. ids,
  185. sourceOrder: parser.state.lastHarmonyImportOrder,
  186. assertions: getAttributes(statement)
  187. });
  188. return true;
  189. }
  190. );
  191. parser.hooks.binaryExpression.tap(
  192. "HarmonyImportDependencyParserPlugin",
  193. expression => {
  194. if (expression.operator !== "in") return;
  195. const leftPartEvaluated = parser.evaluateExpression(expression.left);
  196. if (leftPartEvaluated.couldHaveSideEffects()) return;
  197. const leftPart = leftPartEvaluated.asString();
  198. if (!leftPart) return;
  199. const rightPart = parser.evaluateExpression(expression.right);
  200. if (!rightPart.isIdentifier()) return;
  201. const rootInfo = rightPart.rootInfo;
  202. if (
  203. typeof rootInfo === "string" ||
  204. !rootInfo ||
  205. !rootInfo.tagInfo ||
  206. rootInfo.tagInfo.tag !== harmonySpecifierTag
  207. )
  208. return;
  209. const settings = rootInfo.tagInfo.data;
  210. const members = rightPart.getMembers();
  211. const dep = new HarmonyEvaluatedImportSpecifierDependency(
  212. settings.source,
  213. settings.sourceOrder,
  214. settings.ids.concat(members).concat([leftPart]),
  215. settings.name,
  216. /** @type {Range} */ (expression.range),
  217. settings.assertions,
  218. "in"
  219. );
  220. dep.directImport = members.length === 0;
  221. dep.asiSafe = !parser.isAsiPosition(
  222. /** @type {Range} */ (expression.range)[0]
  223. );
  224. dep.loc = /** @type {DependencyLocation} */ (expression.loc);
  225. parser.state.module.addDependency(dep);
  226. InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
  227. return true;
  228. }
  229. );
  230. parser.hooks.expression
  231. .for(harmonySpecifierTag)
  232. .tap("HarmonyImportDependencyParserPlugin", expr => {
  233. const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
  234. const dep = new HarmonyImportSpecifierDependency(
  235. settings.source,
  236. settings.sourceOrder,
  237. settings.ids,
  238. settings.name,
  239. /** @type {Range} */ (expr.range),
  240. exportPresenceMode,
  241. settings.assertions,
  242. []
  243. );
  244. dep.referencedPropertiesInDestructuring =
  245. parser.destructuringAssignmentPropertiesFor(expr);
  246. dep.shorthand = parser.scope.inShorthand;
  247. dep.directImport = true;
  248. dep.asiSafe = !parser.isAsiPosition(
  249. /** @type {Range} */ (expr.range)[0]
  250. );
  251. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  252. dep.call = parser.scope.inTaggedTemplateTag;
  253. parser.state.module.addDependency(dep);
  254. InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
  255. return true;
  256. });
  257. parser.hooks.expressionMemberChain
  258. .for(harmonySpecifierTag)
  259. .tap(
  260. "HarmonyImportDependencyParserPlugin",
  261. (expression, members, membersOptionals, memberRanges) => {
  262. const settings = /** @type {HarmonySettings} */ (
  263. parser.currentTagData
  264. );
  265. const nonOptionalMembers = getNonOptionalPart(
  266. members,
  267. membersOptionals
  268. );
  269. const ranges = memberRanges.slice(
  270. 0,
  271. memberRanges.length - (members.length - nonOptionalMembers.length)
  272. );
  273. const expr =
  274. nonOptionalMembers !== members
  275. ? getNonOptionalMemberChain(
  276. expression,
  277. members.length - nonOptionalMembers.length
  278. )
  279. : expression;
  280. const ids = settings.ids.concat(nonOptionalMembers);
  281. const dep = new HarmonyImportSpecifierDependency(
  282. settings.source,
  283. settings.sourceOrder,
  284. ids,
  285. settings.name,
  286. /** @type {Range} */ (expr.range),
  287. exportPresenceMode,
  288. settings.assertions,
  289. ranges
  290. );
  291. dep.referencedPropertiesInDestructuring =
  292. parser.destructuringAssignmentPropertiesFor(expr);
  293. dep.asiSafe = !parser.isAsiPosition(
  294. /** @type {Range} */ (expr.range)[0]
  295. );
  296. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  297. parser.state.module.addDependency(dep);
  298. InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
  299. return true;
  300. }
  301. );
  302. parser.hooks.callMemberChain
  303. .for(harmonySpecifierTag)
  304. .tap(
  305. "HarmonyImportDependencyParserPlugin",
  306. (expression, members, membersOptionals, memberRanges) => {
  307. const { arguments: args, callee } = expression;
  308. const settings = /** @type {HarmonySettings} */ (
  309. parser.currentTagData
  310. );
  311. const nonOptionalMembers = getNonOptionalPart(
  312. members,
  313. membersOptionals
  314. );
  315. const ranges = memberRanges.slice(
  316. 0,
  317. memberRanges.length - (members.length - nonOptionalMembers.length)
  318. );
  319. const expr =
  320. nonOptionalMembers !== members
  321. ? getNonOptionalMemberChain(
  322. callee,
  323. members.length - nonOptionalMembers.length
  324. )
  325. : callee;
  326. const ids = settings.ids.concat(nonOptionalMembers);
  327. const dep = new HarmonyImportSpecifierDependency(
  328. settings.source,
  329. settings.sourceOrder,
  330. ids,
  331. settings.name,
  332. /** @type {Range} */ (expr.range),
  333. exportPresenceMode,
  334. settings.assertions,
  335. ranges
  336. );
  337. dep.directImport = members.length === 0;
  338. dep.call = true;
  339. dep.asiSafe = !parser.isAsiPosition(
  340. /** @type {Range} */ (expr.range)[0]
  341. );
  342. // only in case when we strictly follow the spec we need a special case here
  343. dep.namespaceObjectAsContext =
  344. members.length > 0 && this.strictThisContextOnImports;
  345. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  346. parser.state.module.addDependency(dep);
  347. if (args) parser.walkExpressions(args);
  348. InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
  349. return true;
  350. }
  351. );
  352. const { hotAcceptCallback, hotAcceptWithoutCallback } =
  353. HotModuleReplacementPlugin.getParserHooks(parser);
  354. hotAcceptCallback.tap(
  355. "HarmonyImportDependencyParserPlugin",
  356. (expr, requests) => {
  357. if (!HarmonyExports.isEnabled(parser.state)) {
  358. // This is not a harmony module, skip it
  359. return;
  360. }
  361. const dependencies = requests.map(request => {
  362. const dep = new HarmonyAcceptImportDependency(request);
  363. dep.loc = expr.loc;
  364. parser.state.module.addDependency(dep);
  365. return dep;
  366. });
  367. if (dependencies.length > 0) {
  368. const dep = new HarmonyAcceptDependency(
  369. expr.range,
  370. dependencies,
  371. true
  372. );
  373. dep.loc = expr.loc;
  374. parser.state.module.addDependency(dep);
  375. }
  376. }
  377. );
  378. hotAcceptWithoutCallback.tap(
  379. "HarmonyImportDependencyParserPlugin",
  380. (expr, requests) => {
  381. if (!HarmonyExports.isEnabled(parser.state)) {
  382. // This is not a harmony module, skip it
  383. return;
  384. }
  385. const dependencies = requests.map(request => {
  386. const dep = new HarmonyAcceptImportDependency(request);
  387. dep.loc = expr.loc;
  388. parser.state.module.addDependency(dep);
  389. return dep;
  390. });
  391. if (dependencies.length > 0) {
  392. const dep = new HarmonyAcceptDependency(
  393. expr.range,
  394. dependencies,
  395. false
  396. );
  397. dep.loc = expr.loc;
  398. parser.state.module.addDependency(dep);
  399. }
  400. }
  401. );
  402. }
  403. };
  404. module.exports.harmonySpecifierTag = harmonySpecifierTag;
  405. // TODO remove it in webpack@6 in favor getAttributes
  406. module.exports.getAssertions = getAttributes;
  407. module.exports.getAttributes = getAttributes;