scriptable 0.2.0 → 0.2.2

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.
@@ -1,192 +0,0 @@
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
-
13
- function assertSafeParts(parts: string[]): void {
14
- for (const part of parts) {
15
- if (BLOCKED_PROPS.has(part)) {
16
- throw new Error(`Access to property '${part}' is not allowed`);
17
- }
18
- }
19
- }
20
-
21
- // First segment walks the scope chain (env.vars is Object.create(parent.vars))
22
- // so `obj.method()` still resolves when `obj` lives in an enclosing scope.
23
- // Subsequent segments use hasOwn to prevent user-land objects from leaking
24
- // Object.prototype members through the lookup (e.g. `obj.toString`).
25
- function deepHas(obj: any, parts: string[]): boolean {
26
- assertSafeParts(parts);
27
- if (parts.length === 0) return false;
28
- if (!(parts[0] in obj)) return false;
29
- let current = obj[parts[0]];
30
- for (let i = 1; i < parts.length; i++) {
31
- if (current == null || typeof current !== "object") return false;
32
- if (!Object.prototype.hasOwnProperty.call(current, parts[i])) return false;
33
- current = current[parts[i]];
34
- }
35
- return true;
36
- }
37
-
38
- function deepGet(obj: any, parts: string[]): any {
39
- assertSafeParts(parts);
40
- let current = obj;
41
- for (const part of parts) {
42
- if (current == null) return undefined;
43
- current = current[part];
44
- }
45
- return current;
46
- }
47
-
48
- function deepSet(obj: any, parts: string[], value: any): void {
49
- assertSafeParts(parts);
50
- let current = obj;
51
- for (let i = 0; i < parts.length - 1; i++) {
52
- if (current[parts[i]] == null || typeof current[parts[i]] !== "object") {
53
- current[parts[i]] = {};
54
- }
55
- current = current[parts[i]];
56
- }
57
- current[parts[parts.length - 1]] = value;
58
- }
59
-
60
- export interface Loc {
61
- line: number;
62
- column: number;
63
- }
64
-
65
- // Per-run execution state. Shared across every scope in a single interpreter
66
- // run via Environment.runtime. Replaces the previous module-global counter,
67
- // so concurrent or re-entrant runs can't clobber each other's budgets.
68
- export class Runtime {
69
- steps: number = 0;
70
- maxSteps: number;
71
- maxAllocSize: number;
72
- // Absolute deadline in ms (Date.now()). 0 means "no deadline".
73
- deadline: number;
74
-
75
- constructor(
76
- maxSteps: number = 0,
77
- maxAllocSize: number = 0,
78
- maxDurationMs: number = 0
79
- ) {
80
- this.maxSteps = maxSteps;
81
- this.maxAllocSize = maxAllocSize;
82
- this.deadline = maxDurationMs > 0 ? Date.now() + maxDurationMs : 0;
83
- }
84
-
85
- step(): void {
86
- // Wall-clock deadline guards against hostile workloads where a single
87
- // native builtin call (e.g. sort on a 1M-element array) burns CPU without
88
- // advancing the step counter. Checked between interpreter steps — a single
89
- // long native call can overshoot the deadline by up to that call's
90
- // duration, but subsequent work is rejected.
91
- if (this.deadline && Date.now() > this.deadline) {
92
- throw new Error("Execution time exceeded");
93
- }
94
- if (this.maxSteps === 0) return;
95
- if (++this.steps > this.maxSteps) {
96
- throw new Error("Execution limit exceeded");
97
- }
98
- }
99
-
100
- // String doubling and array spread/concat can grow exponentially in a handful
101
- // of steps — 26 string doublings reach V8's ~512 MiB string-length ceiling in
102
- // under a dozen statements. Check the size of every value produced by a
103
- // handler so one run can't allocate unbounded memory.
104
- checkSize(value: unknown): void {
105
- if (this.maxAllocSize === 0) return;
106
- if (typeof value === "string") {
107
- if (value.length > this.maxAllocSize) {
108
- throw new Error(
109
- `String length ${value.length} exceeds maxAllocSize (${this.maxAllocSize})`
110
- );
111
- }
112
- } else if (Array.isArray(value)) {
113
- if (value.length > this.maxAllocSize) {
114
- throw new Error(
115
- `Array length ${value.length} exceeds maxAllocSize (${this.maxAllocSize})`
116
- );
117
- }
118
- }
119
- }
120
-
121
- // Caller-projected length — used before growing an array via spread, so we
122
- // reject the growth rather than wait for V8's per-call argument stack limit
123
- // (which fires at ~65K args on push(...spread), a much lower ceiling than
124
- // maxAllocSize is designed to enforce).
125
- checkLength(projected: number): void {
126
- if (this.maxAllocSize === 0) return;
127
- if (projected > this.maxAllocSize) {
128
- throw new Error(
129
- `Length ${projected} exceeds maxAllocSize (${this.maxAllocSize})`
130
- );
131
- }
132
- }
133
- }
134
-
135
- export default class Environment {
136
- vars: Record<string, any>;
137
- parent: Environment | null;
138
- runtime: Runtime;
139
-
140
- constructor(parent?: Environment, runtime?: Runtime) {
141
- this.vars = Object.create(parent ? parent.vars : null);
142
- this.parent = parent || null;
143
- this.runtime = parent ? parent.runtime : runtime ?? new Runtime();
144
- }
145
-
146
- extend(): Environment {
147
- return new Environment(this);
148
- }
149
-
150
- getGlobalScope(): Environment {
151
- let scope: Environment = this;
152
- while (scope.parent) {
153
- scope = scope.parent;
154
- }
155
- return scope;
156
- }
157
-
158
- lookup(name: string): Environment {
159
- let scope: Environment = this;
160
- while (scope.parent) {
161
- if (Object.prototype.hasOwnProperty.call(scope.vars, name)) {
162
- return scope;
163
- }
164
- scope = scope.parent;
165
- }
166
- return scope;
167
- }
168
-
169
- defined(path: string[]): boolean {
170
- return deepHas(this.vars, path);
171
- }
172
-
173
- get(path: string[], loc: Loc): any {
174
- if (deepHas(this.vars, path)) {
175
- return deepGet(this.vars, path);
176
- }
177
- throw new ReferenceError(
178
- `"${path.join(".")}" is not defined (${loc.line}:${loc.column})`
179
- );
180
- }
181
-
182
- set(path: string[], value: any, loc: Loc): any {
183
- const scope = this.lookup(path[0]);
184
- deepSet(scope.vars, path, value);
185
- return value;
186
- }
187
-
188
- def(path: string[], value: any): any {
189
- deepSet(this.vars, path, value);
190
- return value;
191
- }
192
- }
package/src/evaluate.ts DELETED
@@ -1,414 +0,0 @@
1
- import type { Node } from "acorn";
2
- import binaryOps from "./binary-ops.js";
3
- import type Environment from "./environment.js";
4
- import type { FunctionMap } from "./builtin-functions.js";
5
-
6
- type AnyNode = Node & Record<string, any>;
7
-
8
- // Properties that enable sandbox escape (prototype chain → Function constructor)
9
- // or prototype pollution. Blocked in both MemberExpression and deep path access.
10
- const BLOCKED_PROPS = new Set([
11
- "constructor",
12
- "__proto__",
13
- "prototype",
14
- "__defineGetter__",
15
- "__defineSetter__",
16
- "__lookupGetter__",
17
- "__lookupSetter__",
18
- ]);
19
-
20
- function assertSafeProperty(prop: string): void {
21
- if (BLOCKED_PROPS.has(prop)) {
22
- throw new Error(`Access to property '${prop}' is not allowed`);
23
- }
24
- }
25
-
26
- // Sentinel thrown by ReturnStatement and caught at the nearest function
27
- // boundary (makeFunc). Without this, a `return` nested inside an `if` (or
28
- // any non-ReturnStatement node) would be evaluated but the enclosing
29
- // BlockStatement would keep iterating the remaining statements — so
30
- // `function f(n) { if (n==0) return 1; f(0); return n; }` would fall
31
- // through to `f(0)` after the guarded return and recurse forever.
32
- class ReturnValue {
33
- constructor(public value: any) {}
34
- }
35
-
36
- function loc(exp: AnyNode) {
37
- return exp.loc!.start;
38
- }
39
-
40
- // Resolve an LHS or callee expression to an array of path segments. Used by
41
- // AssignmentExpression target and CallExpression callee. Unlike full
42
- // evaluation, this walks Identifier → name and stitches member accesses into
43
- // a segment list; but it *does* evaluate the key of a computed member
44
- // (`a[k]`) in the runtime env so the path reflects the actual property being
45
- // addressed. Returning segments (not a dotted string) keeps dot-containing
46
- // keys like `a["x.y"]` as a single segment — a dotted string would be
47
- // re-split on the way through deepSet and write to `a.x.y` instead.
48
- function evalAsPath(
49
- exp: AnyNode,
50
- env: Environment,
51
- functions: FunctionMap
52
- ): string[] {
53
- if (exp.type === "Identifier") return [exp.name];
54
- if (exp.type === "Literal") return [String(exp.value)];
55
- if (exp.type === "MemberExpression") {
56
- const objParts = evalAsPath(exp.object, env, functions);
57
- const propStr = exp.computed
58
- ? String(evaluate(exp.property, env, functions))
59
- : String((exp.property as AnyNode).name);
60
- assertSafeProperty(propStr);
61
- return [...objParts, propStr];
62
- }
63
- throw new Error("Cannot evaluate " + exp.type + " as assignment target");
64
- }
65
-
66
- function makeFunc(
67
- params: string[],
68
- body: AnyNode,
69
- env: Environment,
70
- functions: FunctionMap
71
- ) {
72
- // Fresh scope per invocation — a scope hoisted to closure creation time was
73
- // shared across every call, so recursion overwrote the caller's params and
74
- // any let/const it had set on the function scope. `env` is the closure's
75
- // captured lexical parent; extend it anew on every call.
76
- return (...args: any[]) => {
77
- const scope = env.extend();
78
- params.forEach((param, idx) => {
79
- scope.def([param], idx < args.length ? args[idx] : false);
80
- });
81
- try {
82
- return evaluate(body, scope, functions);
83
- } catch (err) {
84
- if (err instanceof ReturnValue) return err.value;
85
- throw err;
86
- }
87
- };
88
- }
89
-
90
- const evals: Record<
91
- string,
92
- (exp: AnyNode, env: Environment, functions: FunctionMap) => any
93
- > = {
94
- ArrowFunctionExpression(exp, env, functions) {
95
- const params = exp.params.map((param: AnyNode) => evaluate(param));
96
- return makeFunc(params, exp.body, env, functions);
97
- },
98
-
99
- ArrayExpression(exp, env, functions) {
100
- const result: any[] = [];
101
- for (const el of exp.elements) {
102
- if (el && el.type === "SpreadElement") {
103
- const spread = evaluate(el.argument, env, functions);
104
- // Check projected length before growing. push(...spread) hits V8's
105
- // argument-stack limit (~65K) well below maxAllocSize, so enforce here
106
- // and grow via a loop instead.
107
- const addLen =
108
- spread && typeof spread.length === "number" ? spread.length : 0;
109
- env.runtime.checkLength(result.length + addLen);
110
- for (const item of spread) result.push(item);
111
- } else if (el) {
112
- result.push(evaluate(el, env, functions));
113
- }
114
- }
115
- return result;
116
- },
117
-
118
- AssignmentExpression(exp, env, functions) {
119
- // Previously the operator was ignored, so `a += 1` silently behaved as
120
- // `a = 1`. Compound ops now read the current value, combine with the rhs
121
- // via the matching binary op, and write back. Logical compounds
122
- // (`||=`, `&&=`, `??=`) short-circuit: rhs is only evaluated and written
123
- // when the gate condition holds.
124
- const target = evalAsPath(exp.left, env, functions);
125
- if (exp.operator === "=") {
126
- return env.set(target, evaluate(exp.right, env, functions), loc(exp));
127
- }
128
- const current = env.get(target, loc(exp));
129
- if (exp.operator === "||=") {
130
- return current || env.set(target, evaluate(exp.right, env, functions), loc(exp));
131
- }
132
- if (exp.operator === "&&=") {
133
- return current && env.set(target, evaluate(exp.right, env, functions), loc(exp));
134
- }
135
- if (exp.operator === "??=") {
136
- return current ?? env.set(target, evaluate(exp.right, env, functions), loc(exp));
137
- }
138
- const op = exp.operator.slice(0, -1);
139
- if (!binaryOps[op]) {
140
- throw new Error(`Unsupported assignment operator: ${exp.operator}`);
141
- }
142
- const rhs = evaluate(exp.right, env, functions);
143
- return env.set(target, binaryOps[op](current, rhs), loc(exp));
144
- },
145
-
146
- BinaryExpression(exp, env, functions) {
147
- const left = evaluate(exp.left, env, functions);
148
- const right = evaluate(exp.right, env, functions);
149
- return binaryOps[exp.operator](left, right);
150
- },
151
-
152
- BlockStatement(exp, env, functions) {
153
- const scope = env.extend();
154
- let result;
155
- for (const part of exp.body) {
156
- result = evaluate(part, scope, functions);
157
- }
158
- return result;
159
- },
160
-
161
- CallExpression(exp, env, functions) {
162
- // Path-based resolution for static callees (Identifier / MemberExpression)
163
- // lets us look up builtins in the `functions` map and dotted-path names in
164
- // env. For dynamic callees (e.g. `f()()`, `(() => 1)()`), evaluate the
165
- // callee as a value and call it directly if it's a function.
166
- let fn: Function | undefined;
167
- let name: string | undefined;
168
- if (
169
- exp.callee.type === "Identifier" ||
170
- exp.callee.type === "MemberExpression"
171
- ) {
172
- const path = evalAsPath(exp.callee, env, functions);
173
- name = path.join(".");
174
- // hasOwn, not `functions[name]`: a plain-object `functions` map inherits
175
- // from Object.prototype, so `functions["constructor"]` would resolve to
176
- // `Object`, `functions["toString"]` to `Object.prototype.toString`, etc.
177
- // Not directly exploitable today (returned wrappers can't reach blocked
178
- // props) but a foot-gun the moment a builtin shares a name with an
179
- // Object.prototype member.
180
- if (Object.prototype.hasOwnProperty.call(functions, name)) {
181
- fn = functions[name];
182
- } else if (env.defined(path)) {
183
- const value = env.get(path, loc(exp));
184
- if (typeof value === "function") fn = value;
185
- }
186
- } else {
187
- const value = evaluate(exp.callee, env, functions);
188
- if (typeof value === "function") fn = value;
189
- }
190
-
191
- // Collect args, handling spread. Same V8 argument-stack consideration
192
- // as ArrayExpression — cap projected length and grow via a loop.
193
- const args: any[] = [];
194
- for (const arg of exp.arguments) {
195
- if (arg.type === "SpreadElement") {
196
- const spread = evaluate(arg.argument, env, functions);
197
- const addLen =
198
- spread && typeof spread.length === "number" ? spread.length : 0;
199
- env.runtime.checkLength(args.length + addLen);
200
- for (const item of spread) args.push(item);
201
- } else {
202
- args.push(evaluate(arg, env, functions));
203
- }
204
- }
205
-
206
- if (fn) return fn(...args);
207
- const l = loc(exp);
208
- throw new Error(
209
- `${name ?? exp.callee.type} is not a function (${l.line}:${l.column})`
210
- );
211
- },
212
-
213
- ConditionalExpression(exp, env, functions) {
214
- const test = evaluate(exp.test, env, functions);
215
- return test
216
- ? evaluate(exp.consequent, env, functions)
217
- : evaluate(exp.alternate, env, functions);
218
- },
219
-
220
- ExpressionStatement(exp, env, functions) {
221
- return evaluate(exp.expression, env, functions);
222
- },
223
-
224
- FunctionDeclaration(exp, env, functions) {
225
- const name = evaluate(exp.id);
226
- const params = exp.params.map((param: AnyNode) => evaluate(param));
227
- env.set([name], makeFunc(params, exp.body, env, functions), loc(exp));
228
- },
229
-
230
- Identifier(exp, env) {
231
- if (env) {
232
- return env.get([exp.name], loc(exp));
233
- }
234
- return exp.name;
235
- },
236
-
237
- IfStatement(exp, env, functions) {
238
- const test = evaluate(exp.test, env, functions);
239
- if (test) {
240
- return evaluate(exp.consequent, env, functions);
241
- }
242
- if (exp.alternate) {
243
- return evaluate(exp.alternate, env, functions);
244
- }
245
- },
246
-
247
- Literal(exp) {
248
- return exp.value;
249
- },
250
-
251
- LogicalExpression(exp, env, functions) {
252
- // Short-circuit: `a || b` must not evaluate `b` when `a` is truthy, and
253
- // `a && b` must not evaluate `b` when `a` is falsy. Previously both sides
254
- // were evaluated eagerly, which broke the common `guard && action` idiom.
255
- const left = evaluate(exp.left, env, functions);
256
- switch (exp.operator) {
257
- case "||":
258
- return left || evaluate(exp.right, env, functions);
259
- case "&&":
260
- return left && evaluate(exp.right, env, functions);
261
- case "??":
262
- return left ?? evaluate(exp.right, env, functions);
263
- default:
264
- throw new Error(`Unsupported logical operator: ${exp.operator}`);
265
- }
266
- },
267
-
268
- MemberExpression(exp, env, functions) {
269
- const obj = evaluate(exp.object, env, functions);
270
- if (exp.computed) {
271
- const prop = evaluate(exp.property, env, functions);
272
- assertSafeProperty(String(prop));
273
- return obj[prop];
274
- }
275
- const prop = evaluate(exp.property);
276
- assertSafeProperty(prop);
277
- return obj[prop];
278
- },
279
-
280
- ObjectExpression(exp, env, functions) {
281
- const result: Record<string, any> = {};
282
- // Track own-key count so we can bound via checkLength without an O(N)
283
- // Object.keys(result).length call on every iteration.
284
- let ownCount = 0;
285
- for (const prop of exp.properties) {
286
- if (prop.type === "SpreadElement") {
287
- const spread = evaluate(prop.argument, env, functions);
288
- // Object.assign invokes setters, which includes Object.prototype's
289
- // __proto__ setter when source has own __proto__. Copy own enumerable
290
- // keys manually and drop blocked keys so a spread can't set the
291
- // prototype of result or plant a booby-trapped own "constructor".
292
- if (spread != null && typeof spread === "object") {
293
- const keys = Object.keys(spread);
294
- // Project before writing: `reduce(arr, (a,k) => ({...a,[k]:k}), {})`
295
- // grows the accumulator by one key per step and would otherwise run
296
- // until maxSteps exhausts, leaving a maxSteps-sized object behind.
297
- env.runtime.checkLength(ownCount + keys.length);
298
- for (const key of keys) {
299
- if (!BLOCKED_PROPS.has(key)) {
300
- if (!Object.prototype.hasOwnProperty.call(result, key)) {
301
- ownCount++;
302
- }
303
- result[key] = (spread as Record<string, any>)[key];
304
- }
305
- }
306
- }
307
- } else {
308
- // Property — non-computed keys are Identifier (shorthand/name) or
309
- // Literal; computed keys (`{[expr]: v}`) require evaluating the
310
- // expression. The previous code ignored `computed`, so `{[k]: v}`
311
- // silently used the identifier NAME "k" instead of its value.
312
- let key: string;
313
- if (prop.computed) {
314
- key = String(evaluate(prop.key, env, functions));
315
- } else if (prop.key.type === "Identifier") {
316
- key = prop.key.name;
317
- } else {
318
- key = String(prop.key.value);
319
- }
320
- // Block "__proto__", "constructor", etc. as keys so user code can't
321
- // set the prototype of a fresh object via literal syntax, and so an
322
- // object leaving the sandbox can't carry a booby-trapped "constructor"
323
- // into the caller's scope.
324
- assertSafeProperty(key);
325
- if (!Object.prototype.hasOwnProperty.call(result, key)) {
326
- env.runtime.checkLength(ownCount + 1);
327
- ownCount++;
328
- }
329
- result[key] = evaluate(prop.value, env, functions);
330
- }
331
- }
332
- return result;
333
- },
334
-
335
- Program(exp, env, functions) {
336
- let result;
337
- for (const node of exp.body) {
338
- result = evaluate(node, env, functions);
339
- }
340
- return result;
341
- },
342
-
343
- ReturnStatement(exp, env, functions) {
344
- // Throw a sentinel so control unwinds to the nearest function boundary
345
- // regardless of which nested construct (if/block/etc.) contains the return.
346
- throw new ReturnValue(
347
- exp.argument ? evaluate(exp.argument, env, functions) : undefined
348
- );
349
- },
350
-
351
- TemplateLiteral(exp, env, functions) {
352
- let result = "";
353
- for (let i = 0; i < exp.quasis.length; i++) {
354
- result += exp.quasis[i].value.cooked;
355
- if (i < exp.expressions.length) {
356
- result += String(evaluate(exp.expressions[i], env, functions));
357
- }
358
- }
359
- return result;
360
- },
361
-
362
- UnaryExpression(exp, env, functions) {
363
- const arg = evaluate(exp.argument, env, functions);
364
- switch (exp.operator) {
365
- case "!":
366
- return !arg;
367
- case "-":
368
- return -arg;
369
- case "+":
370
- return +arg;
371
- case "typeof":
372
- return typeof arg;
373
- default:
374
- throw new Error(`Unsupported unary operator: ${exp.operator}`);
375
- }
376
- },
377
-
378
- VariableDeclaration(exp, env, functions) {
379
- if (exp.kind === "var") {
380
- const globalScope = env.getGlobalScope();
381
- for (const dec of exp.declarations) {
382
- evaluate(dec, globalScope, functions);
383
- }
384
- return;
385
- }
386
- for (const dec of exp.declarations) {
387
- evaluate(dec, env, functions);
388
- }
389
- },
390
-
391
- VariableDeclarator(exp, env, functions) {
392
- const name = evaluate(exp.id);
393
- const value = exp.init ? evaluate(exp.init, env, functions) : undefined;
394
- return env.def([name], value);
395
- },
396
- };
397
-
398
- function evaluate(exp: AnyNode, env?: any, functions?: any): any {
399
- // env is absent when we're resolving a static path (AssignmentExpression
400
- // target, CallExpression callee, function/variable names, params). Those
401
- // branches don't execute user code, so the counter only needs to run here.
402
- if (env) env.runtime.step();
403
- if (evals[exp.type]) {
404
- const result = evals[exp.type](exp, env, functions);
405
- // checkSize inspects strings and arrays; other return types are no-ops.
406
- // Covers both interpreter-built values (BinaryExpression +, TemplateLiteral,
407
- // ArrayExpression) and builtin results (CallExpression).
408
- if (env) env.runtime.checkSize(result);
409
- return result;
410
- }
411
- throw new Error("Cannot evaluate " + exp.type);
412
- }
413
-
414
- export default evaluate;
package/src/index.ts DELETED
@@ -1,83 +0,0 @@
1
- import * as acorn from "acorn";
2
- import evaluate from "./evaluate.js";
3
- import builtinFuncs from "./builtin-functions.js";
4
- import type { FunctionMap } from "./builtin-functions.js";
5
- import Environment, { Runtime } from "./environment.js";
6
-
7
- function parse(code: string) {
8
- return acorn.parse(code, {
9
- ecmaVersion: "latest",
10
- sourceType: "script",
11
- locations: true,
12
- });
13
- }
14
-
15
- export interface RunnerOptions {
16
- functions?: FunctionMap;
17
- maxSteps?: number;
18
- /**
19
- * Maximum length (in UTF-16 code units) of the source string. The step
20
- * counter only bounds execution; parsing a multi-megabyte string still
21
- * consumes proportional CPU and memory inside acorn before the interpreter
22
- * runs. Set to 0 to disable. Defaults to 64 KiB.
23
- */
24
- maxCodeSize?: number;
25
- /**
26
- * Maximum length of any string or array value produced during a run, and
27
- * maximum key count of any object literal. String concatenation, array
28
- * spread, and object spread-accumulation can grow exponentially in a handful
29
- * of steps, well within the step budget. Set to 0 to disable. Defaults to
30
- * 1,000,000 (strings ≤ 1M UTF-16 units ≈ 2 MB; arrays ≤ 1M elements;
31
- * objects ≤ 1M keys).
32
- */
33
- maxAllocSize?: number;
34
- /**
35
- * Maximum wall-clock duration of a single run, in milliseconds. Checked
36
- * between interpreter steps — a single long native builtin call (e.g.
37
- * `sort` on a large array) can overshoot the deadline by up to its own
38
- * duration, but subsequent interpreter work is rejected. Set to 0 to
39
- * disable. Defaults to 0 (disabled); set to a positive value for hostile
40
- * multi-tenant workloads.
41
- */
42
- maxDurationMs?: number;
43
- }
44
-
45
- export interface RunResult {
46
- result: any;
47
- env: Record<string, any>;
48
- }
49
-
50
- const DEFAULT_MAX_STEPS = 100_000;
51
- const DEFAULT_MAX_CODE_SIZE = 64 * 1024;
52
- const DEFAULT_MAX_ALLOC_SIZE = 1_000_000;
53
- const DEFAULT_MAX_DURATION_MS = 0;
54
-
55
- export default function runner({
56
- functions = builtinFuncs,
57
- maxSteps = DEFAULT_MAX_STEPS,
58
- maxCodeSize = DEFAULT_MAX_CODE_SIZE,
59
- maxAllocSize = DEFAULT_MAX_ALLOC_SIZE,
60
- maxDurationMs = DEFAULT_MAX_DURATION_MS,
61
- }: RunnerOptions = {}) {
62
- return (code: string, env: Record<string, any> = {}, debug?: boolean): RunResult => {
63
- if (maxCodeSize > 0 && code.length > maxCodeSize) {
64
- throw new Error(
65
- `Source exceeds maxCodeSize (${code.length} > ${maxCodeSize})`
66
- );
67
- }
68
- const ast = parse(code);
69
- debug && console.log(JSON.stringify(ast.body, null, 2));
70
- const globalEnv = new Environment(
71
- undefined,
72
- new Runtime(maxSteps, maxAllocSize, maxDurationMs)
73
- );
74
- Object.keys(env).forEach((key) => {
75
- globalEnv.def([key], env[key]);
76
- });
77
- const result = evaluate(ast, globalEnv, functions);
78
- return { result, env: globalEnv.vars };
79
- };
80
- }
81
-
82
- export { Environment, Runtime };
83
- export type { FunctionMap };
package/tsconfig.json DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "ES2020",
5
- "moduleResolution": "bundler",
6
- "declaration": true,
7
- "outDir": "dist",
8
- "rootDir": "src",
9
- "strict": true,
10
- "esModuleInterop": true,
11
- "skipLibCheck": true,
12
- "forceConsistentCasingInFileNames": true
13
- },
14
- "include": ["src"],
15
- "exclude": ["src/__tests__"]
16
- }