Skip to content
This repository has been archived by the owner on Sep 10, 2023. It is now read-only.

Commit

Permalink
feat: support decorator for class. not support class property/method …
Browse files Browse the repository at this point in the history
…in current
  • Loading branch information
axetroy committed Mar 29, 2018
1 parent 1aab40b commit dae053c
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1199,6 +1199,22 @@ const visitors: EvaluateMap = {
const ClassConstructor = evaluate(
path.createChild(path.node.body, path.scope.createChild("class"))
);

// support class decorators
const classDecorators = (path.node.decorators || [])
.map(node => evaluate(path.createChild(node)))
.reverse(); // revers decorators

// TODO: support class property decorator
// support class method decorators
// const propertyDecorators = path.node.body.body.filter(
// node => node.decorators && node.decorators.length
// );

for (const decorator of classDecorators) {
decorator(ClassConstructor);
}

path.scope.const(path.node.id.name, ClassConstructor);
},
ClassBody(path) {
Expand Down Expand Up @@ -1343,6 +1359,9 @@ const visitors: EvaluateMap = {
ClassExpression(path) {
//
},
Decorator(path) {
return evaluate(path.createChild(path.node.expression));
},
Super(path) {
const { ctx } = path;
const { SuperClass, ClassConstructor, ClassEntity } = ctx;
Expand Down
1 change: 1 addition & 0 deletions src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export interface INodeTypeMap {
ExportSpecifier: t.ExportSpecifier;
SpreadProperty: t.SpreadProperty;
DoExpression: t.DoExpression;
Decorator: t.Decorator;
}

export type EvaluateMap = {
Expand Down
44 changes: 44 additions & 0 deletions test/experimental/decorators/decorator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import test from "ava";
import vm from "../../../src/vm";

test("DoExpression", t => {
const sandbox: any = vm.createContext({});

const Person: any = vm.runInContext(
`
function testable(target){
target.testable = true;
}
@testable
class Person{
}
module.exports = Person;
`,
sandbox
);
t.deepEqual(Person.testable, true);
});

test("DoExpression", t => {
const sandbox: any = vm.createContext({});

const Person: any = vm.runInContext(
`
function testable(target){
target.prototype.testable = true;
}
@testable
class Person{
}
module.exports = Person;
`,
sandbox
);
const person = new Person();
t.deepEqual(Person.testable, undefined);
t.deepEqual(person.testable, true);
});

0 comments on commit dae053c

Please sign in to comment.