-
Notifications
You must be signed in to change notification settings - Fork 39
/
proxify.ts
62 lines (57 loc) · 1.65 KB
/
proxify.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import type { ASTNode } from "../types";
import { MagicastError } from "../error";
import type { Proxified, ProxifiedModule, ProxifiedValue } from "./types";
import { proxifyArray } from "./array";
import { proxifyFunctionCall } from "./function-call";
import { proxifyObject } from "./object";
import { proxifyNewExpression } from "./new-expression";
import { proxifyIdentifier } from "./identifier";
import { LITERALS_AST, LITERALS_TYPEOF } from "./_utils";
const _cache = new WeakMap<ASTNode, any>();
export function proxify<T>(node: ASTNode, mod?: ProxifiedModule): Proxified<T> {
if (LITERALS_TYPEOF.has(typeof node)) {
return node as any;
}
if (LITERALS_AST.has(node.type)) {
return (node as any).value as any;
}
if (_cache.has(node)) {
return _cache.get(node) as Proxified<T>;
}
let proxy: ProxifiedValue;
switch (node.type) {
case "ObjectExpression": {
proxy = proxifyObject(node, mod);
break;
}
case "ArrayExpression": {
proxy = proxifyArray(node, mod);
break;
}
case "CallExpression": {
proxy = proxifyFunctionCall(node, mod);
break;
}
case "NewExpression": {
proxy = proxifyNewExpression(node, mod);
break;
}
case "Identifier": {
proxy = proxifyIdentifier(node);
break;
}
case "TSAsExpression":
case "TSSatisfiesExpression": {
proxy = proxify(node.expression, mod) as ProxifiedValue;
break;
}
default: {
throw new MagicastError(`Casting "${node.type}" is not supported`, {
ast: node,
code: mod?.$code,
});
}
}
_cache.set(node, proxy);
return proxy as unknown as Proxified<T>;
}