index.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _helperModuleTransforms = require("@babel/helper-module-transforms");
  8. var _helperSimpleAccess = require("@babel/helper-simple-access");
  9. var _core = require("@babel/core");
  10. var _utils = require("babel-plugin-dynamic-import-node/utils");
  11. var _default = (0, _helperPluginUtils.declare)((api, options) => {
  12. var _api$assumption, _api$assumption2, _api$assumption3;
  13. api.assertVersion(7);
  14. const transformImportCall = (0, _utils.createDynamicImportTransform)(api);
  15. const {
  16. strictNamespace = false,
  17. mjsStrictNamespace = strictNamespace,
  18. allowTopLevelThis,
  19. strict,
  20. strictMode,
  21. noInterop,
  22. importInterop,
  23. lazy = false,
  24. allowCommonJSExports = true,
  25. loose = false
  26. } = options;
  27. const constantReexports = (_api$assumption = api.assumption("constantReexports")) != null ? _api$assumption : loose;
  28. const enumerableModuleMeta = (_api$assumption2 = api.assumption("enumerableModuleMeta")) != null ? _api$assumption2 : loose;
  29. const noIncompleteNsImportDetection = (_api$assumption3 = api.assumption("noIncompleteNsImportDetection")) != null ? _api$assumption3 : false;
  30. if (typeof lazy !== "boolean" && typeof lazy !== "function" && (!Array.isArray(lazy) || !lazy.every(item => typeof item === "string"))) {
  31. throw new Error(`.lazy must be a boolean, array of strings, or a function`);
  32. }
  33. if (typeof strictNamespace !== "boolean") {
  34. throw new Error(`.strictNamespace must be a boolean, or undefined`);
  35. }
  36. if (typeof mjsStrictNamespace !== "boolean") {
  37. throw new Error(`.mjsStrictNamespace must be a boolean, or undefined`);
  38. }
  39. const getAssertion = localName => _core.template.expression.ast`
  40. (function(){
  41. throw new Error(
  42. "The CommonJS '" + "${localName}" + "' variable is not available in ES6 modules." +
  43. "Consider setting setting sourceType:script or sourceType:unambiguous in your " +
  44. "Babel config for this file.");
  45. })()
  46. `;
  47. const moduleExportsVisitor = {
  48. ReferencedIdentifier(path) {
  49. const localName = path.node.name;
  50. if (localName !== "module" && localName !== "exports") return;
  51. const localBinding = path.scope.getBinding(localName);
  52. const rootBinding = this.scope.getBinding(localName);
  53. if (rootBinding !== localBinding || path.parentPath.isObjectProperty({
  54. value: path.node
  55. }) && path.parentPath.parentPath.isObjectPattern() || path.parentPath.isAssignmentExpression({
  56. left: path.node
  57. }) || path.isAssignmentExpression({
  58. left: path.node
  59. })) {
  60. return;
  61. }
  62. path.replaceWith(getAssertion(localName));
  63. },
  64. UpdateExpression(path) {
  65. const arg = path.get("argument");
  66. const localName = arg.node.name;
  67. if (localName !== "module" && localName !== "exports") return;
  68. const localBinding = path.scope.getBinding(localName);
  69. const rootBinding = this.scope.getBinding(localName);
  70. if (rootBinding !== localBinding) return;
  71. path.replaceWith(_core.types.assignmentExpression(path.node.operator[0] + "=", arg.node, getAssertion(localName)));
  72. },
  73. AssignmentExpression(path) {
  74. const left = path.get("left");
  75. if (left.isIdentifier()) {
  76. const localName = path.node.name;
  77. if (localName !== "module" && localName !== "exports") return;
  78. const localBinding = path.scope.getBinding(localName);
  79. const rootBinding = this.scope.getBinding(localName);
  80. if (rootBinding !== localBinding) return;
  81. const right = path.get("right");
  82. right.replaceWith(_core.types.sequenceExpression([right.node, getAssertion(localName)]));
  83. } else if (left.isPattern()) {
  84. const ids = left.getOuterBindingIdentifiers();
  85. const localName = Object.keys(ids).filter(localName => {
  86. if (localName !== "module" && localName !== "exports") return false;
  87. return this.scope.getBinding(localName) === path.scope.getBinding(localName);
  88. })[0];
  89. if (localName) {
  90. const right = path.get("right");
  91. right.replaceWith(_core.types.sequenceExpression([right.node, getAssertion(localName)]));
  92. }
  93. }
  94. }
  95. };
  96. return {
  97. name: "transform-modules-commonjs",
  98. pre() {
  99. this.file.set("@babel/plugin-transform-modules-*", "commonjs");
  100. },
  101. visitor: {
  102. CallExpression(path) {
  103. if (!this.file.has("@babel/plugin-proposal-dynamic-import")) return;
  104. if (!path.get("callee").isImport()) return;
  105. let {
  106. scope
  107. } = path;
  108. do {
  109. scope.rename("require");
  110. } while (scope = scope.parent);
  111. transformImportCall(this, path.get("callee"));
  112. },
  113. Program: {
  114. exit(path, state) {
  115. if (!(0, _helperModuleTransforms.isModule)(path)) return;
  116. path.scope.rename("exports");
  117. path.scope.rename("module");
  118. path.scope.rename("require");
  119. path.scope.rename("__filename");
  120. path.scope.rename("__dirname");
  121. if (!allowCommonJSExports) {
  122. (0, _helperSimpleAccess.default)(path, new Set(["module", "exports"]), false);
  123. path.traverse(moduleExportsVisitor, {
  124. scope: path.scope
  125. });
  126. }
  127. let moduleName = (0, _helperModuleTransforms.getModuleName)(this.file.opts, options);
  128. if (moduleName) moduleName = _core.types.stringLiteral(moduleName);
  129. const {
  130. meta,
  131. headers
  132. } = (0, _helperModuleTransforms.rewriteModuleStatementsAndPrepareHeader)(path, {
  133. exportName: "exports",
  134. constantReexports,
  135. enumerableModuleMeta,
  136. strict,
  137. strictMode,
  138. allowTopLevelThis,
  139. noInterop,
  140. importInterop,
  141. lazy,
  142. esNamespaceOnly: typeof state.filename === "string" && /\.mjs$/.test(state.filename) ? mjsStrictNamespace : strictNamespace,
  143. noIncompleteNsImportDetection
  144. });
  145. for (const [source, metadata] of meta.source) {
  146. const loadExpr = _core.types.callExpression(_core.types.identifier("require"), [_core.types.stringLiteral(source)]);
  147. let header;
  148. if ((0, _helperModuleTransforms.isSideEffectImport)(metadata)) {
  149. if (metadata.lazy) throw new Error("Assertion failure");
  150. header = _core.types.expressionStatement(loadExpr);
  151. } else {
  152. const init = (0, _helperModuleTransforms.wrapInterop)(path, loadExpr, metadata.interop) || loadExpr;
  153. if (metadata.lazy) {
  154. header = _core.template.ast`
  155. function ${metadata.name}() {
  156. const data = ${init};
  157. ${metadata.name} = function(){ return data; };
  158. return data;
  159. }
  160. `;
  161. } else {
  162. header = _core.template.ast`
  163. var ${metadata.name} = ${init};
  164. `;
  165. }
  166. }
  167. header.loc = metadata.loc;
  168. headers.push(header);
  169. headers.push(...(0, _helperModuleTransforms.buildNamespaceInitStatements)(meta, metadata, constantReexports));
  170. }
  171. (0, _helperModuleTransforms.ensureStatementsHoisted)(headers);
  172. path.unshiftContainer("body", headers);
  173. path.get("body").forEach(path => {
  174. if (headers.indexOf(path.node) === -1) return;
  175. if (path.isVariableDeclaration()) {
  176. path.scope.registerDeclaration(path);
  177. }
  178. });
  179. }
  180. }
  181. }
  182. };
  183. });
  184. exports.default = _default;