features.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.enableFeature = enableFeature;
  6. exports.isLoose = isLoose;
  7. exports.verifyUsedFeatures = verifyUsedFeatures;
  8. exports.FEATURES = void 0;
  9. var _decorators = require("./decorators");
  10. const FEATURES = Object.freeze({
  11. fields: 1 << 1,
  12. privateMethods: 1 << 2,
  13. decorators: 1 << 3
  14. });
  15. exports.FEATURES = FEATURES;
  16. const featuresKey = "@babel/plugin-class-features/featuresKey";
  17. const looseKey = "@babel/plugin-class-features/looseKey";
  18. function enableFeature(file, feature, loose) {
  19. if (!hasFeature(file, feature)) {
  20. file.set(featuresKey, file.get(featuresKey) | feature);
  21. if (loose) file.set(looseKey, file.get(looseKey) | feature);
  22. }
  23. }
  24. function hasFeature(file, feature) {
  25. return !!(file.get(featuresKey) & feature);
  26. }
  27. function isLoose(file, feature) {
  28. return !!(file.get(looseKey) & feature);
  29. }
  30. function verifyUsedFeatures(path, file) {
  31. if ((0, _decorators.hasOwnDecorators)(path.node)) {
  32. if (!hasFeature(file, FEATURES.decorators)) {
  33. throw path.buildCodeFrameError("Decorators are not enabled." + "\nIf you are using " + '["@babel/plugin-proposal-decorators", { "legacy": true }], ' + 'make sure it comes *before* "@babel/plugin-proposal-class-properties" ' + "and enable loose mode, like so:\n" + '\t["@babel/plugin-proposal-decorators", { "legacy": true }]\n' + '\t["@babel/plugin-proposal-class-properties", { "loose": true }]');
  34. }
  35. if (path.isPrivate()) {
  36. throw path.buildCodeFrameError(`Private ${path.isClassMethod() ? "methods" : "fields"} in decorated classes are not supported yet.`);
  37. }
  38. }
  39. if (path.isPrivate() && path.isMethod()) {
  40. if (!hasFeature(file, FEATURES.privateMethods)) {
  41. throw path.buildCodeFrameError("Class private methods are not enabled.");
  42. }
  43. if (path.node.static && path.node.kind !== "method") {
  44. throw path.buildCodeFrameError("@babel/plugin-class-features doesn't support class static private accessors yet.");
  45. }
  46. }
  47. if (hasFeature(file, FEATURES.privateMethods) && hasFeature(file, FEATURES.fields) && isLoose(file, FEATURES.privateMethods) !== isLoose(file, FEATURES.fields)) {
  48. throw path.buildCodeFrameError("'loose' mode configuration must be the same for both @babel/plugin-proposal-class-properties " + "and @babel/plugin-proposal-private-methods");
  49. }
  50. if (path.isProperty()) {
  51. if (!hasFeature(file, FEATURES.fields)) {
  52. throw path.buildCodeFrameError("Class fields are not enabled.");
  53. }
  54. }
  55. }