index.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.get = get;
  6. exports.minVersion = minVersion;
  7. exports.getDependencies = getDependencies;
  8. exports.ensure = ensure;
  9. exports.default = exports.list = void 0;
  10. function _traverse() {
  11. const data = _interopRequireDefault(require("@babel/traverse"));
  12. _traverse = function () {
  13. return data;
  14. };
  15. return data;
  16. }
  17. function t() {
  18. const data = _interopRequireWildcard(require("@babel/types"));
  19. t = function () {
  20. return data;
  21. };
  22. return data;
  23. }
  24. var _helpers = _interopRequireDefault(require("./helpers"));
  25. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  26. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27. function makePath(path) {
  28. const parts = [];
  29. for (; path.parentPath; path = path.parentPath) {
  30. parts.push(path.key);
  31. if (path.inList) parts.push(path.listKey);
  32. }
  33. return parts.reverse().join(".");
  34. }
  35. function getHelperMetadata(file) {
  36. const globals = new Set();
  37. const localBindingNames = new Set();
  38. const dependencies = new Map();
  39. let exportName;
  40. let exportPath;
  41. const exportBindingAssignments = [];
  42. const importPaths = [];
  43. const importBindingsReferences = [];
  44. (0, _traverse().default)(file, {
  45. ImportDeclaration(child) {
  46. const name = child.node.source.value;
  47. if (!_helpers.default[name]) {
  48. throw child.buildCodeFrameError(`Unknown helper ${name}`);
  49. }
  50. if (child.get("specifiers").length !== 1 || !child.get("specifiers.0").isImportDefaultSpecifier()) {
  51. throw child.buildCodeFrameError("Helpers can only import a default value");
  52. }
  53. const bindingIdentifier = child.node.specifiers[0].local;
  54. dependencies.set(bindingIdentifier, name);
  55. importPaths.push(makePath(child));
  56. },
  57. ExportDefaultDeclaration(child) {
  58. const decl = child.get("declaration");
  59. if (decl.isFunctionDeclaration()) {
  60. if (!decl.node.id) {
  61. throw decl.buildCodeFrameError("Helpers should give names to their exported func declaration");
  62. }
  63. exportName = decl.node.id.name;
  64. }
  65. exportPath = makePath(child);
  66. },
  67. ExportAllDeclaration(child) {
  68. throw child.buildCodeFrameError("Helpers can only export default");
  69. },
  70. ExportNamedDeclaration(child) {
  71. throw child.buildCodeFrameError("Helpers can only export default");
  72. },
  73. Statement(child) {
  74. if (child.isModuleDeclaration()) return;
  75. child.skip();
  76. }
  77. });
  78. (0, _traverse().default)(file, {
  79. Program(path) {
  80. const bindings = path.scope.getAllBindings();
  81. Object.keys(bindings).forEach(name => {
  82. if (name === exportName) return;
  83. if (dependencies.has(bindings[name].identifier)) return;
  84. localBindingNames.add(name);
  85. });
  86. },
  87. ReferencedIdentifier(child) {
  88. const name = child.node.name;
  89. const binding = child.scope.getBinding(name, true);
  90. if (!binding) {
  91. globals.add(name);
  92. } else if (dependencies.has(binding.identifier)) {
  93. importBindingsReferences.push(makePath(child));
  94. }
  95. },
  96. AssignmentExpression(child) {
  97. const left = child.get("left");
  98. if (!(exportName in left.getBindingIdentifiers())) return;
  99. if (!left.isIdentifier()) {
  100. throw left.buildCodeFrameError("Only simple assignments to exports are allowed in helpers");
  101. }
  102. const binding = child.scope.getBinding(exportName);
  103. if (binding && binding.scope.path.isProgram()) {
  104. exportBindingAssignments.push(makePath(child));
  105. }
  106. }
  107. });
  108. if (!exportPath) throw new Error("Helpers must default-export something.");
  109. exportBindingAssignments.reverse();
  110. return {
  111. globals: Array.from(globals),
  112. localBindingNames: Array.from(localBindingNames),
  113. dependencies,
  114. exportBindingAssignments,
  115. exportPath,
  116. exportName,
  117. importBindingsReferences,
  118. importPaths
  119. };
  120. }
  121. function permuteHelperAST(file, metadata, id, localBindings, getDependency) {
  122. if (localBindings && !id) {
  123. throw new Error("Unexpected local bindings for module-based helpers.");
  124. }
  125. if (!id) return;
  126. const {
  127. localBindingNames,
  128. dependencies,
  129. exportBindingAssignments,
  130. exportPath,
  131. exportName,
  132. importBindingsReferences,
  133. importPaths
  134. } = metadata;
  135. const dependenciesRefs = {};
  136. dependencies.forEach((name, id) => {
  137. dependenciesRefs[id.name] = typeof getDependency === "function" && getDependency(name) || id;
  138. });
  139. const toRename = {};
  140. const bindings = new Set(localBindings || []);
  141. localBindingNames.forEach(name => {
  142. let newName = name;
  143. while (bindings.has(newName)) newName = "_" + newName;
  144. if (newName !== name) toRename[name] = newName;
  145. });
  146. if (id.type === "Identifier" && exportName !== id.name) {
  147. toRename[exportName] = id.name;
  148. }
  149. (0, _traverse().default)(file, {
  150. Program(path) {
  151. const exp = path.get(exportPath);
  152. const imps = importPaths.map(p => path.get(p));
  153. const impsBindingRefs = importBindingsReferences.map(p => path.get(p));
  154. const decl = exp.get("declaration");
  155. if (id.type === "Identifier") {
  156. if (decl.isFunctionDeclaration()) {
  157. exp.replaceWith(decl);
  158. } else {
  159. exp.replaceWith(t().variableDeclaration("var", [t().variableDeclarator(id, decl.node)]));
  160. }
  161. } else if (id.type === "MemberExpression") {
  162. if (decl.isFunctionDeclaration()) {
  163. exportBindingAssignments.forEach(assignPath => {
  164. const assign = path.get(assignPath);
  165. assign.replaceWith(t().assignmentExpression("=", id, assign.node));
  166. });
  167. exp.replaceWith(decl);
  168. path.pushContainer("body", t().expressionStatement(t().assignmentExpression("=", id, t().identifier(exportName))));
  169. } else {
  170. exp.replaceWith(t().expressionStatement(t().assignmentExpression("=", id, decl.node)));
  171. }
  172. } else {
  173. throw new Error("Unexpected helper format.");
  174. }
  175. Object.keys(toRename).forEach(name => {
  176. path.scope.rename(name, toRename[name]);
  177. });
  178. for (const path of imps) path.remove();
  179. for (const path of impsBindingRefs) {
  180. const node = t().cloneNode(dependenciesRefs[path.node.name]);
  181. path.replaceWith(node);
  182. }
  183. path.stop();
  184. }
  185. });
  186. }
  187. const helperData = Object.create(null);
  188. function loadHelper(name) {
  189. if (!helperData[name]) {
  190. const helper = _helpers.default[name];
  191. if (!helper) {
  192. throw Object.assign(new ReferenceError(`Unknown helper ${name}`), {
  193. code: "BABEL_HELPER_UNKNOWN",
  194. helper: name
  195. });
  196. }
  197. const fn = () => {
  198. return t().file(helper.ast());
  199. };
  200. const metadata = getHelperMetadata(fn());
  201. helperData[name] = {
  202. build(getDependency, id, localBindings) {
  203. const file = fn();
  204. permuteHelperAST(file, metadata, id, localBindings, getDependency);
  205. return {
  206. nodes: file.program.body,
  207. globals: metadata.globals
  208. };
  209. },
  210. minVersion() {
  211. return helper.minVersion;
  212. },
  213. dependencies: metadata.dependencies
  214. };
  215. }
  216. return helperData[name];
  217. }
  218. function get(name, getDependency, id, localBindings) {
  219. return loadHelper(name).build(getDependency, id, localBindings);
  220. }
  221. function minVersion(name) {
  222. return loadHelper(name).minVersion();
  223. }
  224. function getDependencies(name) {
  225. return Array.from(loadHelper(name).dependencies.values());
  226. }
  227. function ensure(name) {
  228. loadHelper(name);
  229. }
  230. const list = Object.keys(_helpers.default).map(name => name.replace(/^_/, "")).filter(name => name !== "__esModule");
  231. exports.list = list;
  232. var _default = get;
  233. exports.default = _default;