maybeParse.cjs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const babel = require("./babel-core.cjs");
  2. const convert = require("../convert/index.cjs");
  3. const {
  4. getVisitorKeys,
  5. getTokLabels
  6. } = require("./ast-info.cjs");
  7. const extractParserOptionsPlugin = require("./extract-parser-options-plugin.cjs");
  8. const ref = {};
  9. let extractParserOptionsConfigItem;
  10. const MULTIPLE_OVERRIDES = /More than one plugin attempted to override parsing/;
  11. module.exports = function maybeParse(code, options) {
  12. if (!extractParserOptionsConfigItem) {
  13. extractParserOptionsConfigItem = babel.createConfigItem([extractParserOptionsPlugin, ref], {
  14. dirname: __dirname,
  15. type: "plugin"
  16. });
  17. }
  18. const {
  19. plugins
  20. } = options;
  21. options.plugins = plugins.concat(extractParserOptionsConfigItem);
  22. try {
  23. return {
  24. parserOptions: babel.parseSync(code, options),
  25. ast: null
  26. };
  27. } catch (err) {
  28. if (!MULTIPLE_OVERRIDES.test(err.message)) {
  29. throw err;
  30. }
  31. }
  32. options.plugins = plugins;
  33. let ast;
  34. try {
  35. ast = babel.parseSync(code, options);
  36. } catch (err) {
  37. throw convert.error(err);
  38. }
  39. return {
  40. ast: convert.ast(ast, code, getTokLabels(), getVisitorKeys()),
  41. parserOptions: null
  42. };
  43. };