scriptable 0.0.5 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/settings.local.json +10 -0
- package/README.md +139 -0
- package/dist/binary-ops.d.ts +2 -0
- package/dist/binary-ops.js +16 -0
- package/dist/builtin-functions.d.ts +3 -0
- package/dist/builtin-functions.js +151 -0
- package/dist/environment.d.ts +16 -0
- package/dist/environment.js +111 -0
- package/dist/evaluate.d.ts +5 -0
- package/dist/evaluate.js +232 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +26 -0
- package/dist/logic-ops.d.ts +2 -0
- package/dist/logic-ops.js +5 -0
- package/package.json +17 -50
- package/src/__tests__/{break-out.js → break-out.test.ts} +4 -15
- package/src/__tests__/{builtin-functions-date.js → builtin-functions-date.test.ts} +30 -11
- package/src/__tests__/{builtin-functions.js → builtin-functions.test.ts} +2 -3
- package/src/__tests__/{expressions.js → expressions.test.ts} +2 -3
- package/src/__tests__/{functions.js → functions.test.ts} +7 -8
- package/src/__tests__/{logic.js → logic.test.ts} +2 -3
- package/src/__tests__/new-features.test.ts +158 -0
- package/src/__tests__/security.test.ts +399 -0
- package/src/__tests__/{variables.js → variables.test.ts} +99 -7
- package/src/binary-ops.ts +18 -0
- package/src/builtin-functions.ts +177 -0
- package/src/environment.ts +132 -0
- package/src/evaluate.ts +275 -0
- package/src/index.ts +42 -0
- package/src/logic-ops.ts +6 -0
- package/tsconfig.json +16 -0
- package/.npmignore +0 -1
- package/src/__tests__/index.js +0 -85
- package/src/binary-ops.js +0 -13
- package/src/builtin-functions.js +0 -58
- package/src/environment.js +0 -60
- package/src/evaluate.js +0 -152
- package/src/index.js +0 -26
- package/src/logic-ops.js +0 -6
- package/yarn.lock +0 -2632
package/README.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# scriptable
|
|
2
|
+
|
|
3
|
+
A safe, sandboxed JavaScript interpreter that walks the AST node-by-node. No `eval()`, no `new Function()` — only explicitly handled node types are executed, with only whitelisted functions available to scripts.
|
|
4
|
+
|
|
5
|
+
Designed for executing user-provided or AI-generated JS in constrained environments like Cloudflare Workers where CSP blocks dynamic code evaluation.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add scriptable
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import runner from "scriptable";
|
|
17
|
+
|
|
18
|
+
const run = runner();
|
|
19
|
+
|
|
20
|
+
const { result, env } = run(`
|
|
21
|
+
const tax = price * 0.1;
|
|
22
|
+
const total = price + tax;
|
|
23
|
+
`, { price: 100 });
|
|
24
|
+
|
|
25
|
+
// result: 110 (last expression value)
|
|
26
|
+
// env: { price: 100, tax: 10, total: 110 }
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Injecting custom functions
|
|
30
|
+
|
|
31
|
+
Scripts can only call functions you explicitly provide. Pass them via the `functions` option:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
const run = runner({
|
|
35
|
+
functions: {
|
|
36
|
+
add: (a, b) => a + b,
|
|
37
|
+
greet: (name) => `hello ${name}`,
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const { result } = run(`greet("world")`);
|
|
42
|
+
// result: "hello world"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The default `functions` include array/collection operations (`map`, `filter`, `reduce`, `forEach`, `concat`, `keys`, `values`, etc.), number formatting (`numberFormatter`, `formatDollars`), date formatting (`formatDate`, `currentDate`), and array mutation (`push`, `shift`).
|
|
46
|
+
|
|
47
|
+
### API
|
|
48
|
+
|
|
49
|
+
**`runner(options?)`** returns an executor function.
|
|
50
|
+
|
|
51
|
+
- `options.functions` — `Record<string, Function>` of callable functions (defaults to built-in set)
|
|
52
|
+
|
|
53
|
+
**`run(code, env?, debug?)`** executes code and returns `{ result, env }`.
|
|
54
|
+
|
|
55
|
+
- `code` — JavaScript source string
|
|
56
|
+
- `env` — initial variables available to the script (default `{}`)
|
|
57
|
+
- `debug` — if truthy, logs the AST to console
|
|
58
|
+
- Returns `result` (value of last expression) and `env` (all variables after execution)
|
|
59
|
+
|
|
60
|
+
## Supported syntax
|
|
61
|
+
|
|
62
|
+
| Node type | Examples |
|
|
63
|
+
|---|---|
|
|
64
|
+
| Variables | `var`, `let`, `const`, assignment |
|
|
65
|
+
| Functions | `function foo() {}`, arrow functions `() => {}` |
|
|
66
|
+
| Expressions | Binary (`+`, `-`, `*`, `/`, `%`, comparisons), logical (`&&`, `\|\|`), unary (`!`, `-`, `+`, `typeof`) |
|
|
67
|
+
| Conditionals | `if`/`else if`/`else`, ternary `? :` |
|
|
68
|
+
| Literals | Strings, numbers, booleans, arrays, objects |
|
|
69
|
+
| Template literals | `` `hello ${name}` `` |
|
|
70
|
+
| Spread | `[...arr]`, `{...obj}`, `fn(...args)` |
|
|
71
|
+
| Member access | `obj.prop`, `obj["prop"]`, `arr[0]` |
|
|
72
|
+
| Return | `return` in functions |
|
|
73
|
+
|
|
74
|
+
Unsupported node types throw `"Cannot evaluate <type>"`, which is the primary security mechanism — there is no way to access `this`, `arguments`, constructors, `import`, `require`, or any runtime API unless explicitly injected via `functions`.
|
|
75
|
+
|
|
76
|
+
## Changes from v0.0.x
|
|
77
|
+
|
|
78
|
+
This is a full rewrite of the original package. The interpreter behavior and API shape are preserved.
|
|
79
|
+
|
|
80
|
+
### Parser: Babylon → Acorn
|
|
81
|
+
|
|
82
|
+
Replaced [Babylon](https://github.com/babel/babylon) with [Acorn](https://github.com/acornjs/acorn) (~12KB, zero transitive deps, ESM, actively maintained, Cloudflare Workers compatible).
|
|
83
|
+
|
|
84
|
+
### Language: JavaScript → TypeScript
|
|
85
|
+
|
|
86
|
+
All source converted to TypeScript with strict mode. Builds to ESM (`dist/`) with declaration files.
|
|
87
|
+
|
|
88
|
+
### Dependencies removed
|
|
89
|
+
|
|
90
|
+
| Old | Replacement |
|
|
91
|
+
|---|---|
|
|
92
|
+
| `babylon` | `acorn` |
|
|
93
|
+
| `lodash` | Native equivalents (`Object.keys`, `Array.map`, etc.) |
|
|
94
|
+
| `moment` + `moment-timezone` | `Intl.DateTimeFormat` (zero deps, built into all runtimes) |
|
|
95
|
+
| `jest` | `vitest` |
|
|
96
|
+
|
|
97
|
+
### Test runner: Jest → Vitest
|
|
98
|
+
|
|
99
|
+
All tests ported to Vitest. The moment-dependent date tests now use `Intl.DateTimeFormat` and accept runtime-dependent timezone abbreviations (e.g. `AEST` in browsers/Workers, `GMT+10` in some Node versions).
|
|
100
|
+
|
|
101
|
+
### New AST node types
|
|
102
|
+
|
|
103
|
+
- **TemplateLiteral** — backtick strings with `${expression}` interpolation
|
|
104
|
+
- **SpreadElement** — `...` in arrays, objects, and function arguments
|
|
105
|
+
- **ConditionalExpression** — ternary `condition ? a : b`
|
|
106
|
+
- **UnaryExpression** — `!`, `-`, `+`, `typeof`
|
|
107
|
+
- **IfStatement else** — `else` and `else if` branches (previously only `if`)
|
|
108
|
+
|
|
109
|
+
### Bug fixes
|
|
110
|
+
|
|
111
|
+
- `VariableDeclarator` now evaluates initializers with the environment, so `const x = foo(bar)` works (previously only literal initializers like `const x = "hello"` worked)
|
|
112
|
+
- `BlockStatement` uses a native `for` loop instead of `lodash/forEach` for return-statement breaking
|
|
113
|
+
|
|
114
|
+
### Date builtins
|
|
115
|
+
|
|
116
|
+
`currentDate(tz?)` and `formatDate(dateString, format, timezone?)` are reimplemented using `Intl.DateTimeFormat`. The `formatDate` function accepts moment-style format tokens:
|
|
117
|
+
|
|
118
|
+
| Token | Output | Example |
|
|
119
|
+
|---|---|---|
|
|
120
|
+
| `YYYY` | 4-digit year | `2017` |
|
|
121
|
+
| `YY` | 2-digit year | `17` |
|
|
122
|
+
| `MMMM` | Full month | `January` |
|
|
123
|
+
| `MMM` | Short month | `Jan` |
|
|
124
|
+
| `MM` | Padded month | `01` |
|
|
125
|
+
| `DD` | Padded day | `05` |
|
|
126
|
+
| `D` | Day | `5` |
|
|
127
|
+
| `HH` | 24-hour padded | `09` |
|
|
128
|
+
| `h` | 12-hour | `9` |
|
|
129
|
+
| `mm` | Minutes padded | `08` |
|
|
130
|
+
| `ss` | Seconds padded | `05` |
|
|
131
|
+
| `a` | am/pm | `am` |
|
|
132
|
+
| `A` | AM/PM | `AM` |
|
|
133
|
+
| `z` | Timezone abbr | `UTC` |
|
|
134
|
+
|
|
135
|
+
### Package setup
|
|
136
|
+
|
|
137
|
+
- ESM (`"type": "module"`) with TypeScript build
|
|
138
|
+
- pnpm for package management
|
|
139
|
+
- `exports` field with types
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const binaryOps = {
|
|
2
|
+
"+": (l, r) => l + r,
|
|
3
|
+
"-": (l, r) => l - r,
|
|
4
|
+
"*": (l, r) => l * r,
|
|
5
|
+
"/": (l, r) => l / r,
|
|
6
|
+
"%": (l, r) => l % r,
|
|
7
|
+
">": (l, r) => l > r,
|
|
8
|
+
"<": (l, r) => l < r,
|
|
9
|
+
">=": (l, r) => l >= r,
|
|
10
|
+
"<=": (l, r) => l <= r,
|
|
11
|
+
"==": (l, r) => l === r,
|
|
12
|
+
"!=": (l, r) => l !== r,
|
|
13
|
+
"===": (l, r) => l === r,
|
|
14
|
+
"!==": (l, r) => l !== r,
|
|
15
|
+
};
|
|
16
|
+
export default binaryOps;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Date helpers (Intl-based, no moment dependency)
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
function getDateParts(date, tz) {
|
|
5
|
+
const fmt = (opts) => new Intl.DateTimeFormat("en-US", { timeZone: tz, ...opts });
|
|
6
|
+
const year = parseInt(fmt({ year: "numeric" }).format(date));
|
|
7
|
+
const month = parseInt(fmt({ month: "numeric" }).format(date));
|
|
8
|
+
const day = parseInt(fmt({ day: "numeric" }).format(date));
|
|
9
|
+
const h24Parts = fmt({
|
|
10
|
+
hour: "numeric",
|
|
11
|
+
minute: "numeric",
|
|
12
|
+
second: "numeric",
|
|
13
|
+
hourCycle: "h23",
|
|
14
|
+
}).formatToParts(date);
|
|
15
|
+
const part = (type) => h24Parts.find((p) => p.type === type)?.value || "0";
|
|
16
|
+
const hour24 = parseInt(part("hour"));
|
|
17
|
+
const minute = parseInt(part("minute"));
|
|
18
|
+
const second = parseInt(part("second"));
|
|
19
|
+
const hour12 = hour24 === 0 ? 12 : hour24 > 12 ? hour24 - 12 : hour24;
|
|
20
|
+
const ampm = hour24 >= 12 ? "pm" : "am";
|
|
21
|
+
const monthShort = fmt({ month: "short" }).format(date);
|
|
22
|
+
const monthLong = fmt({ month: "long" }).format(date);
|
|
23
|
+
const tzAbbr = fmt({ timeZoneName: "short" })
|
|
24
|
+
.formatToParts(date)
|
|
25
|
+
.find((p) => p.type === "timeZoneName")?.value || "";
|
|
26
|
+
return {
|
|
27
|
+
year, month, day,
|
|
28
|
+
hour12, hour24, minute, second,
|
|
29
|
+
ampm, monthShort, monthLong, tzAbbr,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const FORMAT_TOKENS = /YYYY|YY|MMMM|MMM|MM|M|DD|D|HH|H|hh|h|mm|m|ss|s|a|A|z/g;
|
|
33
|
+
function applyFormat(parts, format) {
|
|
34
|
+
return format.replace(FORMAT_TOKENS, (token) => {
|
|
35
|
+
switch (token) {
|
|
36
|
+
case "YYYY": return String(parts.year);
|
|
37
|
+
case "YY": return String(parts.year).slice(-2);
|
|
38
|
+
case "MMMM": return parts.monthLong;
|
|
39
|
+
case "MMM": return parts.monthShort;
|
|
40
|
+
case "MM": return String(parts.month).padStart(2, "0");
|
|
41
|
+
case "M": return String(parts.month);
|
|
42
|
+
case "DD": return String(parts.day).padStart(2, "0");
|
|
43
|
+
case "D": return String(parts.day);
|
|
44
|
+
case "HH": return String(parts.hour24).padStart(2, "0");
|
|
45
|
+
case "H": return String(parts.hour24);
|
|
46
|
+
case "hh": return String(parts.hour12).padStart(2, "0");
|
|
47
|
+
case "h": return String(parts.hour12);
|
|
48
|
+
case "mm": return String(parts.minute).padStart(2, "0");
|
|
49
|
+
case "m": return String(parts.minute);
|
|
50
|
+
case "ss": return String(parts.second).padStart(2, "0");
|
|
51
|
+
case "s": return String(parts.second);
|
|
52
|
+
case "a": return parts.ampm;
|
|
53
|
+
case "A": return parts.ampm.toUpperCase();
|
|
54
|
+
case "z": return parts.tzAbbr;
|
|
55
|
+
default: return token;
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// Number helpers
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
function numberFormatter(...args) {
|
|
63
|
+
return new Intl.NumberFormat(...args).format;
|
|
64
|
+
}
|
|
65
|
+
const functions = {
|
|
66
|
+
push(...args) {
|
|
67
|
+
const [target, item] = args;
|
|
68
|
+
target.push(item);
|
|
69
|
+
},
|
|
70
|
+
shift(...args) {
|
|
71
|
+
const [target] = args;
|
|
72
|
+
return target.shift();
|
|
73
|
+
},
|
|
74
|
+
currentDate(tz) {
|
|
75
|
+
return new Date();
|
|
76
|
+
},
|
|
77
|
+
formatDate(dateString, format, timezone) {
|
|
78
|
+
const date = /^\d+$/.test(dateString)
|
|
79
|
+
? new Date(+dateString)
|
|
80
|
+
: new Date(dateString);
|
|
81
|
+
const tz = timezone || "UTC";
|
|
82
|
+
return applyFormat(getDateParts(date, tz), format);
|
|
83
|
+
},
|
|
84
|
+
numberFormatter,
|
|
85
|
+
formatDollars: numberFormatter("en-us", {
|
|
86
|
+
minimumFractionDigits: 2,
|
|
87
|
+
maximumFractionDigits: 2,
|
|
88
|
+
}),
|
|
89
|
+
// Array/collection operations (replaces lodash)
|
|
90
|
+
map(arr, fn) {
|
|
91
|
+
return arr.map(fn);
|
|
92
|
+
},
|
|
93
|
+
filter(arr, fn) {
|
|
94
|
+
return arr.filter(fn);
|
|
95
|
+
},
|
|
96
|
+
find(arr, fn) {
|
|
97
|
+
return arr.find(fn);
|
|
98
|
+
},
|
|
99
|
+
forEach(arr, fn) {
|
|
100
|
+
arr.forEach(fn);
|
|
101
|
+
},
|
|
102
|
+
reduce(arr, fn, initial) {
|
|
103
|
+
return initial !== undefined ? arr.reduce(fn, initial) : arr.reduce(fn);
|
|
104
|
+
},
|
|
105
|
+
concat(arr, ...items) {
|
|
106
|
+
return arr.concat(...items);
|
|
107
|
+
},
|
|
108
|
+
keys(obj) {
|
|
109
|
+
return Object.keys(obj);
|
|
110
|
+
},
|
|
111
|
+
values(obj) {
|
|
112
|
+
return Object.values(obj);
|
|
113
|
+
},
|
|
114
|
+
entries(obj) {
|
|
115
|
+
return Object.entries(obj);
|
|
116
|
+
},
|
|
117
|
+
assign(...args) {
|
|
118
|
+
return Object.assign({}, ...args);
|
|
119
|
+
},
|
|
120
|
+
join(arr, sep) {
|
|
121
|
+
return arr.join(sep);
|
|
122
|
+
},
|
|
123
|
+
includes(arr, item) {
|
|
124
|
+
return arr.includes(item);
|
|
125
|
+
},
|
|
126
|
+
slice(arr, start, end) {
|
|
127
|
+
return arr.slice(start, end);
|
|
128
|
+
},
|
|
129
|
+
sort(arr, fn) {
|
|
130
|
+
return [...arr].sort(fn);
|
|
131
|
+
},
|
|
132
|
+
reverse(arr) {
|
|
133
|
+
return [...arr].reverse();
|
|
134
|
+
},
|
|
135
|
+
flat(arr, depth) {
|
|
136
|
+
return arr.flat(depth);
|
|
137
|
+
},
|
|
138
|
+
flatMap(arr, fn) {
|
|
139
|
+
return arr.flatMap(fn);
|
|
140
|
+
},
|
|
141
|
+
some(arr, fn) {
|
|
142
|
+
return arr.some(fn);
|
|
143
|
+
},
|
|
144
|
+
every(arr, fn) {
|
|
145
|
+
return arr.every(fn);
|
|
146
|
+
},
|
|
147
|
+
indexOf(arr, item) {
|
|
148
|
+
return arr.indexOf(item);
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
export default functions;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface Loc {
|
|
2
|
+
line: number;
|
|
3
|
+
column: number;
|
|
4
|
+
}
|
|
5
|
+
export default class Environment {
|
|
6
|
+
vars: Record<string, any>;
|
|
7
|
+
parent: Environment | null;
|
|
8
|
+
constructor(parent?: Environment);
|
|
9
|
+
extend(): Environment;
|
|
10
|
+
getGlobalScope(): Environment;
|
|
11
|
+
lookup(name: string): Environment;
|
|
12
|
+
defined(name: string): boolean;
|
|
13
|
+
get(name: string, loc: Loc): any;
|
|
14
|
+
set(name: string, value: any, loc: Loc): any;
|
|
15
|
+
def(name: string, value: any): any;
|
|
16
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Properties that could be used for prototype-chain traversal or pollution.
|
|
2
|
+
// Defense-in-depth: also checked in evaluate.ts MemberExpression.
|
|
3
|
+
const BLOCKED_PROPS = new Set([
|
|
4
|
+
"constructor",
|
|
5
|
+
"__proto__",
|
|
6
|
+
"prototype",
|
|
7
|
+
"__defineGetter__",
|
|
8
|
+
"__defineSetter__",
|
|
9
|
+
"__lookupGetter__",
|
|
10
|
+
"__lookupSetter__",
|
|
11
|
+
]);
|
|
12
|
+
function assertSafeParts(parts) {
|
|
13
|
+
for (const part of parts) {
|
|
14
|
+
if (BLOCKED_PROPS.has(part)) {
|
|
15
|
+
throw new Error(`Access to property '${part}' is not allowed`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function deepHas(obj, path) {
|
|
20
|
+
const parts = path.split(".");
|
|
21
|
+
assertSafeParts(parts);
|
|
22
|
+
let current = obj;
|
|
23
|
+
for (const part of parts) {
|
|
24
|
+
if (current == null || typeof current !== "object")
|
|
25
|
+
return false;
|
|
26
|
+
if (!Object.prototype.hasOwnProperty.call(current, part))
|
|
27
|
+
return false;
|
|
28
|
+
current = current[part];
|
|
29
|
+
}
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
function deepGet(obj, path) {
|
|
33
|
+
const parts = path.split(".");
|
|
34
|
+
assertSafeParts(parts);
|
|
35
|
+
let current = obj;
|
|
36
|
+
for (const part of parts) {
|
|
37
|
+
if (current == null)
|
|
38
|
+
return undefined;
|
|
39
|
+
current = current[part];
|
|
40
|
+
}
|
|
41
|
+
return current;
|
|
42
|
+
}
|
|
43
|
+
function deepSet(obj, path, value) {
|
|
44
|
+
const parts = path.split(".");
|
|
45
|
+
assertSafeParts(parts);
|
|
46
|
+
let current = obj;
|
|
47
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
48
|
+
if (current[parts[i]] == null || typeof current[parts[i]] !== "object") {
|
|
49
|
+
current[parts[i]] = {};
|
|
50
|
+
}
|
|
51
|
+
current = current[parts[i]];
|
|
52
|
+
}
|
|
53
|
+
current[parts[parts.length - 1]] = value;
|
|
54
|
+
}
|
|
55
|
+
export default class Environment {
|
|
56
|
+
constructor(parent) {
|
|
57
|
+
this.vars = Object.create(parent ? parent.vars : null);
|
|
58
|
+
this.parent = parent || null;
|
|
59
|
+
}
|
|
60
|
+
extend() {
|
|
61
|
+
return new Environment(this);
|
|
62
|
+
}
|
|
63
|
+
getGlobalScope() {
|
|
64
|
+
let scope = this;
|
|
65
|
+
while (scope.parent) {
|
|
66
|
+
scope = scope.parent;
|
|
67
|
+
}
|
|
68
|
+
return scope;
|
|
69
|
+
}
|
|
70
|
+
lookup(name) {
|
|
71
|
+
let scope = this;
|
|
72
|
+
while (scope.parent) {
|
|
73
|
+
if (Object.prototype.hasOwnProperty.call(scope.vars, name)) {
|
|
74
|
+
return scope;
|
|
75
|
+
}
|
|
76
|
+
scope = scope.parent;
|
|
77
|
+
}
|
|
78
|
+
return scope;
|
|
79
|
+
}
|
|
80
|
+
defined(name) {
|
|
81
|
+
if (name in this.vars) {
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
if (deepHas(this.vars, name)) {
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
get(name, loc) {
|
|
90
|
+
if (name in this.vars) {
|
|
91
|
+
return this.vars[name];
|
|
92
|
+
}
|
|
93
|
+
if (deepHas(this.vars, name)) {
|
|
94
|
+
return deepGet(this.vars, name);
|
|
95
|
+
}
|
|
96
|
+
throw new ReferenceError(`"${name}" is not defined (${loc.line}:${loc.column})`);
|
|
97
|
+
}
|
|
98
|
+
set(name, value, loc) {
|
|
99
|
+
const baseName = name.replace(/\..*/, "");
|
|
100
|
+
const scope = this.lookup(baseName);
|
|
101
|
+
if (!scope && this.parent) {
|
|
102
|
+
throw new ReferenceError(`"${name}" is not defined (${loc.line}:${loc.column})`);
|
|
103
|
+
}
|
|
104
|
+
deepSet((scope || this).vars, name, value);
|
|
105
|
+
return value;
|
|
106
|
+
}
|
|
107
|
+
def(name, value) {
|
|
108
|
+
deepSet(this.vars, name, value);
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
}
|
package/dist/evaluate.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import binaryOps from "./binary-ops.js";
|
|
2
|
+
import logicOps from "./logic-ops.js";
|
|
3
|
+
// Properties that enable sandbox escape (prototype chain → Function constructor)
|
|
4
|
+
// or prototype pollution. Blocked in both MemberExpression and deep path access.
|
|
5
|
+
const BLOCKED_PROPS = new Set([
|
|
6
|
+
"constructor",
|
|
7
|
+
"__proto__",
|
|
8
|
+
"prototype",
|
|
9
|
+
"__defineGetter__",
|
|
10
|
+
"__defineSetter__",
|
|
11
|
+
"__lookupGetter__",
|
|
12
|
+
"__lookupSetter__",
|
|
13
|
+
]);
|
|
14
|
+
function assertSafeProperty(prop) {
|
|
15
|
+
if (BLOCKED_PROPS.has(prop)) {
|
|
16
|
+
throw new Error(`Access to property '${prop}' is not allowed`);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
// Execution step counter — reset via resetStepCounter() before each run.
|
|
20
|
+
let _steps = 0;
|
|
21
|
+
let _maxSteps = 0;
|
|
22
|
+
export function resetStepCounter(maxSteps) {
|
|
23
|
+
_steps = 0;
|
|
24
|
+
_maxSteps = maxSteps;
|
|
25
|
+
}
|
|
26
|
+
function loc(exp) {
|
|
27
|
+
return exp.loc.start;
|
|
28
|
+
}
|
|
29
|
+
function makeFunc(params, body, env, functions) {
|
|
30
|
+
const scope = env.extend();
|
|
31
|
+
return (...args) => {
|
|
32
|
+
params.forEach((param, idx) => {
|
|
33
|
+
scope.def(param, idx < args.length ? args[idx] : false);
|
|
34
|
+
});
|
|
35
|
+
return evaluate(body, scope, functions);
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const evals = {
|
|
39
|
+
ArrowFunctionExpression(exp, env, functions) {
|
|
40
|
+
const params = exp.params.map((param) => evaluate(param));
|
|
41
|
+
return makeFunc(params, exp.body, env, functions);
|
|
42
|
+
},
|
|
43
|
+
ArrayExpression(exp, env, functions) {
|
|
44
|
+
const result = [];
|
|
45
|
+
for (const el of exp.elements) {
|
|
46
|
+
if (el && el.type === "SpreadElement") {
|
|
47
|
+
const spread = evaluate(el.argument, env, functions);
|
|
48
|
+
result.push(...spread);
|
|
49
|
+
}
|
|
50
|
+
else if (el) {
|
|
51
|
+
result.push(evaluate(el, env, functions));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
},
|
|
56
|
+
AssignmentExpression(exp, env, functions) {
|
|
57
|
+
const target = evaluate(exp.left);
|
|
58
|
+
return env.set(target, evaluate(exp.right, env, functions), loc(exp));
|
|
59
|
+
},
|
|
60
|
+
BinaryExpression(exp, env, functions) {
|
|
61
|
+
const left = evaluate(exp.left, env, functions);
|
|
62
|
+
const right = evaluate(exp.right, env, functions);
|
|
63
|
+
return binaryOps[exp.operator](left, right);
|
|
64
|
+
},
|
|
65
|
+
BlockStatement(exp, env, functions) {
|
|
66
|
+
const scope = env.extend();
|
|
67
|
+
let result;
|
|
68
|
+
for (const part of exp.body) {
|
|
69
|
+
result = evaluate(part, scope, functions);
|
|
70
|
+
if (part.type === "ReturnStatement") {
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
},
|
|
76
|
+
CallExpression(exp, env, functions) {
|
|
77
|
+
const func = evaluate(exp.callee);
|
|
78
|
+
// Collect args, handling spread
|
|
79
|
+
const args = [];
|
|
80
|
+
for (const arg of exp.arguments) {
|
|
81
|
+
if (arg.type === "SpreadElement") {
|
|
82
|
+
const spread = evaluate(arg.argument, env, functions);
|
|
83
|
+
args.push(...spread);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
args.push(evaluate(arg, env, functions));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (functions[func]) {
|
|
90
|
+
return functions[func](...args);
|
|
91
|
+
}
|
|
92
|
+
if (env.defined(func)) {
|
|
93
|
+
const customFunc = env.get(func, loc(exp));
|
|
94
|
+
if (typeof customFunc === "function") {
|
|
95
|
+
return customFunc(...args);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const l = loc(exp);
|
|
99
|
+
throw new Error(`${func} is not a function (${l.line}:${l.column})`);
|
|
100
|
+
},
|
|
101
|
+
ConditionalExpression(exp, env, functions) {
|
|
102
|
+
const test = evaluate(exp.test, env, functions);
|
|
103
|
+
return test
|
|
104
|
+
? evaluate(exp.consequent, env, functions)
|
|
105
|
+
: evaluate(exp.alternate, env, functions);
|
|
106
|
+
},
|
|
107
|
+
ExpressionStatement(exp, env, functions) {
|
|
108
|
+
return evaluate(exp.expression, env, functions);
|
|
109
|
+
},
|
|
110
|
+
FunctionDeclaration(exp, env, functions) {
|
|
111
|
+
const name = evaluate(exp.id);
|
|
112
|
+
const params = exp.params.map((param) => evaluate(param));
|
|
113
|
+
env.set(name, makeFunc(params, exp.body, env, functions), loc(exp));
|
|
114
|
+
},
|
|
115
|
+
Identifier(exp, env) {
|
|
116
|
+
if (env) {
|
|
117
|
+
return env.get(exp.name, loc(exp));
|
|
118
|
+
}
|
|
119
|
+
return exp.name;
|
|
120
|
+
},
|
|
121
|
+
IfStatement(exp, env, functions) {
|
|
122
|
+
const test = evaluate(exp.test, env, functions);
|
|
123
|
+
if (test) {
|
|
124
|
+
return evaluate(exp.consequent, env, functions);
|
|
125
|
+
}
|
|
126
|
+
if (exp.alternate) {
|
|
127
|
+
return evaluate(exp.alternate, env, functions);
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
Literal(exp) {
|
|
131
|
+
return exp.value;
|
|
132
|
+
},
|
|
133
|
+
LogicalExpression(exp, env, functions) {
|
|
134
|
+
const left = evaluate(exp.left, env, functions);
|
|
135
|
+
const right = evaluate(exp.right, env, functions);
|
|
136
|
+
return logicOps[exp.operator](left, right);
|
|
137
|
+
},
|
|
138
|
+
MemberExpression(exp, env, functions) {
|
|
139
|
+
if (!env) {
|
|
140
|
+
const obj = evaluate(exp.object);
|
|
141
|
+
const prop = evaluate(exp.property);
|
|
142
|
+
assertSafeProperty(prop);
|
|
143
|
+
return `${obj}.${prop}`;
|
|
144
|
+
}
|
|
145
|
+
const obj = evaluate(exp.object, env, functions);
|
|
146
|
+
if (exp.computed) {
|
|
147
|
+
const prop = evaluate(exp.property, env, functions);
|
|
148
|
+
assertSafeProperty(String(prop));
|
|
149
|
+
return obj[prop];
|
|
150
|
+
}
|
|
151
|
+
const prop = evaluate(exp.property);
|
|
152
|
+
assertSafeProperty(prop);
|
|
153
|
+
return obj[prop];
|
|
154
|
+
},
|
|
155
|
+
ObjectExpression(exp, env, functions) {
|
|
156
|
+
const result = {};
|
|
157
|
+
for (const prop of exp.properties) {
|
|
158
|
+
if (prop.type === "SpreadElement") {
|
|
159
|
+
const spread = evaluate(prop.argument, env, functions);
|
|
160
|
+
Object.assign(result, spread);
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
// Property — key can be Identifier or Literal
|
|
164
|
+
const key = prop.key.type === "Identifier" ? prop.key.name : prop.key.value;
|
|
165
|
+
result[key] = evaluate(prop.value, env, functions);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
},
|
|
170
|
+
Program(exp, env, functions) {
|
|
171
|
+
let result;
|
|
172
|
+
for (const node of exp.body) {
|
|
173
|
+
result = evaluate(node, env, functions);
|
|
174
|
+
}
|
|
175
|
+
return result;
|
|
176
|
+
},
|
|
177
|
+
ReturnStatement(exp, env, functions) {
|
|
178
|
+
return evaluate(exp.argument, env, functions);
|
|
179
|
+
},
|
|
180
|
+
TemplateLiteral(exp, env, functions) {
|
|
181
|
+
let result = "";
|
|
182
|
+
for (let i = 0; i < exp.quasis.length; i++) {
|
|
183
|
+
result += exp.quasis[i].value.cooked;
|
|
184
|
+
if (i < exp.expressions.length) {
|
|
185
|
+
result += String(evaluate(exp.expressions[i], env, functions));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return result;
|
|
189
|
+
},
|
|
190
|
+
UnaryExpression(exp, env, functions) {
|
|
191
|
+
const arg = evaluate(exp.argument, env, functions);
|
|
192
|
+
switch (exp.operator) {
|
|
193
|
+
case "!":
|
|
194
|
+
return !arg;
|
|
195
|
+
case "-":
|
|
196
|
+
return -arg;
|
|
197
|
+
case "+":
|
|
198
|
+
return +arg;
|
|
199
|
+
case "typeof":
|
|
200
|
+
return typeof arg;
|
|
201
|
+
default:
|
|
202
|
+
throw new Error(`Unsupported unary operator: ${exp.operator}`);
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
VariableDeclaration(exp, env, functions) {
|
|
206
|
+
if (exp.kind === "var") {
|
|
207
|
+
const globalScope = env.getGlobalScope();
|
|
208
|
+
for (const dec of exp.declarations) {
|
|
209
|
+
evaluate(dec, globalScope, functions);
|
|
210
|
+
}
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
for (const dec of exp.declarations) {
|
|
214
|
+
evaluate(dec, env, functions);
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
VariableDeclarator(exp, env, functions) {
|
|
218
|
+
const name = evaluate(exp.id);
|
|
219
|
+
const value = exp.init ? evaluate(exp.init, env, functions) : undefined;
|
|
220
|
+
return env.def(name, value);
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
function evaluate(exp, env, functions) {
|
|
224
|
+
if (_maxSteps > 0 && ++_steps > _maxSteps) {
|
|
225
|
+
throw new Error("Execution limit exceeded");
|
|
226
|
+
}
|
|
227
|
+
if (evals[exp.type]) {
|
|
228
|
+
return evals[exp.type](exp, env, functions);
|
|
229
|
+
}
|
|
230
|
+
throw new Error("Cannot evaluate " + exp.type);
|
|
231
|
+
}
|
|
232
|
+
export default evaluate;
|