index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. Object.defineProperty(exports, "buildDynamicImport", {
  6. enumerable: true,
  7. get: function () {
  8. return _dynamicImport.buildDynamicImport;
  9. }
  10. });
  11. exports.buildNamespaceInitStatements = buildNamespaceInitStatements;
  12. exports.ensureStatementsHoisted = ensureStatementsHoisted;
  13. Object.defineProperty(exports, "getDynamicImportSource", {
  14. enumerable: true,
  15. get: function () {
  16. return _dynamicImport.getDynamicImportSource;
  17. }
  18. });
  19. Object.defineProperty(exports, "getModuleName", {
  20. enumerable: true,
  21. get: function () {
  22. return _getModuleName.default;
  23. }
  24. });
  25. Object.defineProperty(exports, "hasExports", {
  26. enumerable: true,
  27. get: function () {
  28. return _normalizeAndLoadMetadata.hasExports;
  29. }
  30. });
  31. Object.defineProperty(exports, "isModule", {
  32. enumerable: true,
  33. get: function () {
  34. return _helperModuleImports.isModule;
  35. }
  36. });
  37. Object.defineProperty(exports, "isSideEffectImport", {
  38. enumerable: true,
  39. get: function () {
  40. return _normalizeAndLoadMetadata.isSideEffectImport;
  41. }
  42. });
  43. exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader;
  44. Object.defineProperty(exports, "rewriteThis", {
  45. enumerable: true,
  46. get: function () {
  47. return _rewriteThis.default;
  48. }
  49. });
  50. exports.wrapInterop = wrapInterop;
  51. var _assert = require("assert");
  52. var _t = require("@babel/types");
  53. var _template = require("@babel/template");
  54. var _helperModuleImports = require("@babel/helper-module-imports");
  55. var _rewriteThis = require("./rewrite-this");
  56. var _rewriteLiveReferences = require("./rewrite-live-references");
  57. var _normalizeAndLoadMetadata = require("./normalize-and-load-metadata");
  58. var _dynamicImport = require("./dynamic-import");
  59. var _getModuleName = require("./get-module-name");
  60. const {
  61. booleanLiteral,
  62. callExpression,
  63. cloneNode,
  64. directive,
  65. directiveLiteral,
  66. expressionStatement,
  67. identifier,
  68. isIdentifier,
  69. memberExpression,
  70. stringLiteral,
  71. valueToNode,
  72. variableDeclaration,
  73. variableDeclarator
  74. } = _t;
  75. function rewriteModuleStatementsAndPrepareHeader(path, {
  76. loose,
  77. exportName,
  78. strict,
  79. allowTopLevelThis,
  80. strictMode,
  81. noInterop,
  82. importInterop = noInterop ? "none" : "babel",
  83. lazy,
  84. esNamespaceOnly,
  85. filename,
  86. constantReexports = loose,
  87. enumerableModuleMeta = loose,
  88. noIncompleteNsImportDetection
  89. }) {
  90. (0, _normalizeAndLoadMetadata.validateImportInteropOption)(importInterop);
  91. _assert((0, _helperModuleImports.isModule)(path), "Cannot process module statements in a script");
  92. path.node.sourceType = "script";
  93. const meta = (0, _normalizeAndLoadMetadata.default)(path, exportName, {
  94. importInterop,
  95. initializeReexports: constantReexports,
  96. lazy,
  97. esNamespaceOnly,
  98. filename
  99. });
  100. if (!allowTopLevelThis) {
  101. (0, _rewriteThis.default)(path);
  102. }
  103. (0, _rewriteLiveReferences.default)(path, meta);
  104. if (strictMode !== false) {
  105. const hasStrict = path.node.directives.some(directive => {
  106. return directive.value.value === "use strict";
  107. });
  108. if (!hasStrict) {
  109. path.unshiftContainer("directives", directive(directiveLiteral("use strict")));
  110. }
  111. }
  112. const headers = [];
  113. if ((0, _normalizeAndLoadMetadata.hasExports)(meta) && !strict) {
  114. headers.push(buildESModuleHeader(meta, enumerableModuleMeta));
  115. }
  116. const nameList = buildExportNameListDeclaration(path, meta);
  117. if (nameList) {
  118. meta.exportNameListName = nameList.name;
  119. headers.push(nameList.statement);
  120. }
  121. headers.push(...buildExportInitializationStatements(path, meta, constantReexports, noIncompleteNsImportDetection));
  122. return {
  123. meta,
  124. headers
  125. };
  126. }
  127. function ensureStatementsHoisted(statements) {
  128. statements.forEach(header => {
  129. header._blockHoist = 3;
  130. });
  131. }
  132. function wrapInterop(programPath, expr, type) {
  133. if (type === "none") {
  134. return null;
  135. }
  136. if (type === "node-namespace") {
  137. return callExpression(programPath.hub.addHelper("interopRequireWildcard"), [expr, booleanLiteral(true)]);
  138. } else if (type === "node-default") {
  139. return null;
  140. }
  141. let helper;
  142. if (type === "default") {
  143. helper = "interopRequireDefault";
  144. } else if (type === "namespace") {
  145. helper = "interopRequireWildcard";
  146. } else {
  147. throw new Error(`Unknown interop: ${type}`);
  148. }
  149. return callExpression(programPath.hub.addHelper(helper), [expr]);
  150. }
  151. function buildNamespaceInitStatements(metadata, sourceMetadata, constantReexports = false) {
  152. const statements = [];
  153. let srcNamespace = identifier(sourceMetadata.name);
  154. if (sourceMetadata.lazy) srcNamespace = callExpression(srcNamespace, []);
  155. for (const localName of sourceMetadata.importsNamespace) {
  156. if (localName === sourceMetadata.name) continue;
  157. statements.push(_template.default.statement`var NAME = SOURCE;`({
  158. NAME: localName,
  159. SOURCE: cloneNode(srcNamespace)
  160. }));
  161. }
  162. if (constantReexports) {
  163. statements.push(...buildReexportsFromMeta(metadata, sourceMetadata, true));
  164. }
  165. for (const exportName of sourceMetadata.reexportNamespace) {
  166. statements.push((sourceMetadata.lazy ? _template.default.statement`
  167. Object.defineProperty(EXPORTS, "NAME", {
  168. enumerable: true,
  169. get: function() {
  170. return NAMESPACE;
  171. }
  172. });
  173. ` : _template.default.statement`EXPORTS.NAME = NAMESPACE;`)({
  174. EXPORTS: metadata.exportName,
  175. NAME: exportName,
  176. NAMESPACE: cloneNode(srcNamespace)
  177. }));
  178. }
  179. if (sourceMetadata.reexportAll) {
  180. const statement = buildNamespaceReexport(metadata, cloneNode(srcNamespace), constantReexports);
  181. statement.loc = sourceMetadata.reexportAll.loc;
  182. statements.push(statement);
  183. }
  184. return statements;
  185. }
  186. const ReexportTemplate = {
  187. constant: _template.default.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`,
  188. constantComputed: _template.default.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`,
  189. spec: _template.default.statement`
  190. Object.defineProperty(EXPORTS, "EXPORT_NAME", {
  191. enumerable: true,
  192. get: function() {
  193. return NAMESPACE_IMPORT;
  194. },
  195. });
  196. `
  197. };
  198. function buildReexportsFromMeta(meta, metadata, constantReexports) {
  199. const namespace = metadata.lazy ? callExpression(identifier(metadata.name), []) : identifier(metadata.name);
  200. const {
  201. stringSpecifiers
  202. } = meta;
  203. return Array.from(metadata.reexports, ([exportName, importName]) => {
  204. let NAMESPACE_IMPORT = cloneNode(namespace);
  205. if (importName === "default" && metadata.interop === "node-default") {} else if (stringSpecifiers.has(importName)) {
  206. NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, stringLiteral(importName), true);
  207. } else {
  208. NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, identifier(importName));
  209. }
  210. const astNodes = {
  211. EXPORTS: meta.exportName,
  212. EXPORT_NAME: exportName,
  213. NAMESPACE_IMPORT
  214. };
  215. if (constantReexports || isIdentifier(NAMESPACE_IMPORT)) {
  216. if (stringSpecifiers.has(exportName)) {
  217. return ReexportTemplate.constantComputed(astNodes);
  218. } else {
  219. return ReexportTemplate.constant(astNodes);
  220. }
  221. } else {
  222. return ReexportTemplate.spec(astNodes);
  223. }
  224. });
  225. }
  226. function buildESModuleHeader(metadata, enumerableModuleMeta = false) {
  227. return (enumerableModuleMeta ? _template.default.statement`
  228. EXPORTS.__esModule = true;
  229. ` : _template.default.statement`
  230. Object.defineProperty(EXPORTS, "__esModule", {
  231. value: true,
  232. });
  233. `)({
  234. EXPORTS: metadata.exportName
  235. });
  236. }
  237. function buildNamespaceReexport(metadata, namespace, constantReexports) {
  238. return (constantReexports ? _template.default.statement`
  239. Object.keys(NAMESPACE).forEach(function(key) {
  240. if (key === "default" || key === "__esModule") return;
  241. VERIFY_NAME_LIST;
  242. if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
  243. EXPORTS[key] = NAMESPACE[key];
  244. });
  245. ` : _template.default.statement`
  246. Object.keys(NAMESPACE).forEach(function(key) {
  247. if (key === "default" || key === "__esModule") return;
  248. VERIFY_NAME_LIST;
  249. if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
  250. Object.defineProperty(EXPORTS, key, {
  251. enumerable: true,
  252. get: function() {
  253. return NAMESPACE[key];
  254. },
  255. });
  256. });
  257. `)({
  258. NAMESPACE: namespace,
  259. EXPORTS: metadata.exportName,
  260. VERIFY_NAME_LIST: metadata.exportNameListName ? (0, _template.default)`
  261. if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;
  262. `({
  263. EXPORTS_LIST: metadata.exportNameListName
  264. }) : null
  265. });
  266. }
  267. function buildExportNameListDeclaration(programPath, metadata) {
  268. const exportedVars = Object.create(null);
  269. for (const data of metadata.local.values()) {
  270. for (const name of data.names) {
  271. exportedVars[name] = true;
  272. }
  273. }
  274. let hasReexport = false;
  275. for (const data of metadata.source.values()) {
  276. for (const exportName of data.reexports.keys()) {
  277. exportedVars[exportName] = true;
  278. }
  279. for (const exportName of data.reexportNamespace) {
  280. exportedVars[exportName] = true;
  281. }
  282. hasReexport = hasReexport || !!data.reexportAll;
  283. }
  284. if (!hasReexport || Object.keys(exportedVars).length === 0) return null;
  285. const name = programPath.scope.generateUidIdentifier("exportNames");
  286. delete exportedVars.default;
  287. return {
  288. name: name.name,
  289. statement: variableDeclaration("var", [variableDeclarator(name, valueToNode(exportedVars))])
  290. };
  291. }
  292. function buildExportInitializationStatements(programPath, metadata, constantReexports = false, noIncompleteNsImportDetection = false) {
  293. const initStatements = [];
  294. for (const [localName, data] of metadata.local) {
  295. if (data.kind === "import") {} else if (data.kind === "hoisted") {
  296. initStatements.push([data.names[0], buildInitStatement(metadata, data.names, identifier(localName))]);
  297. } else if (!noIncompleteNsImportDetection) {
  298. for (const exportName of data.names) {
  299. initStatements.push([exportName, null]);
  300. }
  301. }
  302. }
  303. for (const data of metadata.source.values()) {
  304. if (!constantReexports) {
  305. const reexportsStatements = buildReexportsFromMeta(metadata, data, false);
  306. const reexports = [...data.reexports.keys()];
  307. for (let i = 0; i < reexportsStatements.length; i++) {
  308. initStatements.push([reexports[i], reexportsStatements[i]]);
  309. }
  310. }
  311. if (!noIncompleteNsImportDetection) {
  312. for (const exportName of data.reexportNamespace) {
  313. initStatements.push([exportName, null]);
  314. }
  315. }
  316. }
  317. initStatements.sort(([a], [b]) => {
  318. if (a < b) return -1;
  319. if (b < a) return 1;
  320. return 0;
  321. });
  322. const results = [];
  323. if (noIncompleteNsImportDetection) {
  324. for (const [, initStatement] of initStatements) {
  325. results.push(initStatement);
  326. }
  327. } else {
  328. const chunkSize = 100;
  329. for (let i = 0; i < initStatements.length; i += chunkSize) {
  330. let uninitializedExportNames = [];
  331. for (let j = 0; j < chunkSize && i + j < initStatements.length; j++) {
  332. const [exportName, initStatement] = initStatements[i + j];
  333. if (initStatement !== null) {
  334. if (uninitializedExportNames.length > 0) {
  335. results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode()));
  336. uninitializedExportNames = [];
  337. }
  338. results.push(initStatement);
  339. } else {
  340. uninitializedExportNames.push(exportName);
  341. }
  342. }
  343. if (uninitializedExportNames.length > 0) {
  344. results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode()));
  345. }
  346. }
  347. }
  348. return results;
  349. }
  350. const InitTemplate = {
  351. computed: _template.default.expression`EXPORTS["NAME"] = VALUE`,
  352. default: _template.default.expression`EXPORTS.NAME = VALUE`
  353. };
  354. function buildInitStatement(metadata, exportNames, initExpr) {
  355. const {
  356. stringSpecifiers,
  357. exportName: EXPORTS
  358. } = metadata;
  359. return expressionStatement(exportNames.reduce((acc, exportName) => {
  360. const params = {
  361. EXPORTS,
  362. NAME: exportName,
  363. VALUE: acc
  364. };
  365. if (stringSpecifiers.has(exportName)) {
  366. return InitTemplate.computed(params);
  367. } else {
  368. return InitTemplate.default(params);
  369. }
  370. }, initExpr));
  371. }
  372. //# sourceMappingURL=index.js.map