scriptable 0.0.6 → 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.
Files changed (40) hide show
  1. package/.claude/settings.local.json +10 -0
  2. package/README.md +139 -0
  3. package/dist/binary-ops.d.ts +2 -0
  4. package/dist/binary-ops.js +16 -0
  5. package/dist/builtin-functions.d.ts +3 -0
  6. package/dist/builtin-functions.js +151 -0
  7. package/dist/environment.d.ts +16 -0
  8. package/dist/environment.js +111 -0
  9. package/dist/evaluate.d.ts +5 -0
  10. package/dist/evaluate.js +232 -0
  11. package/dist/index.d.ts +13 -0
  12. package/dist/index.js +26 -0
  13. package/dist/logic-ops.d.ts +2 -0
  14. package/dist/logic-ops.js +5 -0
  15. package/package.json +17 -50
  16. package/src/__tests__/{break-out.js → break-out.test.ts} +3 -14
  17. package/src/__tests__/{builtin-functions-date.js → builtin-functions-date.test.ts} +30 -11
  18. package/src/__tests__/{builtin-functions.js → builtin-functions.test.ts} +2 -3
  19. package/src/__tests__/{expressions.js → expressions.test.ts} +2 -3
  20. package/src/__tests__/{functions.js → functions.test.ts} +7 -8
  21. package/src/__tests__/{logic.js → logic.test.ts} +2 -3
  22. package/src/__tests__/new-features.test.ts +158 -0
  23. package/src/__tests__/security.test.ts +399 -0
  24. package/src/__tests__/{variables.js → variables.test.ts} +3 -6
  25. package/src/binary-ops.ts +18 -0
  26. package/src/builtin-functions.ts +177 -0
  27. package/src/environment.ts +132 -0
  28. package/src/evaluate.ts +275 -0
  29. package/src/index.ts +42 -0
  30. package/src/logic-ops.ts +6 -0
  31. package/tsconfig.json +16 -0
  32. package/.npmignore +0 -1
  33. package/src/__tests__/index.js +0 -85
  34. package/src/binary-ops.js +0 -13
  35. package/src/builtin-functions.js +0 -58
  36. package/src/environment.js +0 -73
  37. package/src/evaluate.js +0 -174
  38. package/src/index.js +0 -26
  39. package/src/logic-ops.js +0 -6
  40. package/yarn.lock +0 -2632
@@ -0,0 +1,132 @@
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
+ function deepHas(obj: any, path: string): boolean {
22
+ const parts = path.split(".");
23
+ assertSafeParts(parts);
24
+ let current = obj;
25
+ for (const part of parts) {
26
+ if (current == null || typeof current !== "object") return false;
27
+ if (!Object.prototype.hasOwnProperty.call(current, part)) return false;
28
+ current = current[part];
29
+ }
30
+ return true;
31
+ }
32
+
33
+ function deepGet(obj: any, path: string): any {
34
+ const parts = path.split(".");
35
+ assertSafeParts(parts);
36
+ let current = obj;
37
+ for (const part of parts) {
38
+ if (current == null) return undefined;
39
+ current = current[part];
40
+ }
41
+ return current;
42
+ }
43
+
44
+ function deepSet(obj: any, path: string, value: any): void {
45
+ const parts = path.split(".");
46
+ assertSafeParts(parts);
47
+ let current = obj;
48
+ for (let i = 0; i < parts.length - 1; i++) {
49
+ if (current[parts[i]] == null || typeof current[parts[i]] !== "object") {
50
+ current[parts[i]] = {};
51
+ }
52
+ current = current[parts[i]];
53
+ }
54
+ current[parts[parts.length - 1]] = value;
55
+ }
56
+
57
+ export interface Loc {
58
+ line: number;
59
+ column: number;
60
+ }
61
+
62
+ export default class Environment {
63
+ vars: Record<string, any>;
64
+ parent: Environment | null;
65
+
66
+ constructor(parent?: Environment) {
67
+ this.vars = Object.create(parent ? parent.vars : null);
68
+ this.parent = parent || null;
69
+ }
70
+
71
+ extend(): Environment {
72
+ return new Environment(this);
73
+ }
74
+
75
+ getGlobalScope(): Environment {
76
+ let scope: Environment = this;
77
+ while (scope.parent) {
78
+ scope = scope.parent;
79
+ }
80
+ return scope;
81
+ }
82
+
83
+ lookup(name: string): Environment {
84
+ let scope: Environment = this;
85
+ while (scope.parent) {
86
+ if (Object.prototype.hasOwnProperty.call(scope.vars, name)) {
87
+ return scope;
88
+ }
89
+ scope = scope.parent;
90
+ }
91
+ return scope;
92
+ }
93
+
94
+ defined(name: string): boolean {
95
+ if (name in this.vars) {
96
+ return true;
97
+ }
98
+ if (deepHas(this.vars, name)) {
99
+ return true;
100
+ }
101
+ return false;
102
+ }
103
+
104
+ get(name: string, loc: Loc): any {
105
+ if (name in this.vars) {
106
+ return this.vars[name];
107
+ }
108
+ if (deepHas(this.vars, name)) {
109
+ return deepGet(this.vars, name);
110
+ }
111
+ throw new ReferenceError(
112
+ `"${name}" is not defined (${loc.line}:${loc.column})`
113
+ );
114
+ }
115
+
116
+ set(name: string, value: any, loc: Loc): any {
117
+ const baseName = name.replace(/\..*/, "");
118
+ const scope = this.lookup(baseName);
119
+ if (!scope && this.parent) {
120
+ throw new ReferenceError(
121
+ `"${name}" is not defined (${loc.line}:${loc.column})`
122
+ );
123
+ }
124
+ deepSet((scope || this).vars, name, value);
125
+ return value;
126
+ }
127
+
128
+ def(name: string, value: any): any {
129
+ deepSet(this.vars, name, value);
130
+ return value;
131
+ }
132
+ }
@@ -0,0 +1,275 @@
1
+ import type { Node } from "acorn";
2
+ import binaryOps from "./binary-ops.js";
3
+ import logicOps from "./logic-ops.js";
4
+ import type Environment from "./environment.js";
5
+ import type { FunctionMap } from "./builtin-functions.js";
6
+
7
+ type AnyNode = Node & Record<string, any>;
8
+
9
+ // Properties that enable sandbox escape (prototype chain → Function constructor)
10
+ // or prototype pollution. Blocked in both MemberExpression and deep path access.
11
+ const BLOCKED_PROPS = new Set([
12
+ "constructor",
13
+ "__proto__",
14
+ "prototype",
15
+ "__defineGetter__",
16
+ "__defineSetter__",
17
+ "__lookupGetter__",
18
+ "__lookupSetter__",
19
+ ]);
20
+
21
+ function assertSafeProperty(prop: string): void {
22
+ if (BLOCKED_PROPS.has(prop)) {
23
+ throw new Error(`Access to property '${prop}' is not allowed`);
24
+ }
25
+ }
26
+
27
+ // Execution step counter — reset via resetStepCounter() before each run.
28
+ let _steps = 0;
29
+ let _maxSteps = 0;
30
+
31
+ export function resetStepCounter(maxSteps: number): void {
32
+ _steps = 0;
33
+ _maxSteps = maxSteps;
34
+ }
35
+
36
+ function loc(exp: AnyNode) {
37
+ return exp.loc!.start;
38
+ }
39
+
40
+ function makeFunc(
41
+ params: string[],
42
+ body: AnyNode,
43
+ env: Environment,
44
+ functions: FunctionMap
45
+ ) {
46
+ const scope = env.extend();
47
+ return (...args: any[]) => {
48
+ params.forEach((param, idx) => {
49
+ scope.def(param, idx < args.length ? args[idx] : false);
50
+ });
51
+ return evaluate(body, scope, functions);
52
+ };
53
+ }
54
+
55
+ const evals: Record<
56
+ string,
57
+ (exp: AnyNode, env: Environment, functions: FunctionMap) => any
58
+ > = {
59
+ ArrowFunctionExpression(exp, env, functions) {
60
+ const params = exp.params.map((param: AnyNode) => evaluate(param));
61
+ return makeFunc(params, exp.body, env, functions);
62
+ },
63
+
64
+ ArrayExpression(exp, env, functions) {
65
+ const result: any[] = [];
66
+ for (const el of exp.elements) {
67
+ if (el && el.type === "SpreadElement") {
68
+ const spread = evaluate(el.argument, env, functions);
69
+ result.push(...spread);
70
+ } else if (el) {
71
+ result.push(evaluate(el, env, functions));
72
+ }
73
+ }
74
+ return result;
75
+ },
76
+
77
+ AssignmentExpression(exp, env, functions) {
78
+ const target = evaluate(exp.left);
79
+ return env.set(target, evaluate(exp.right, env, functions), loc(exp));
80
+ },
81
+
82
+ BinaryExpression(exp, env, functions) {
83
+ const left = evaluate(exp.left, env, functions);
84
+ const right = evaluate(exp.right, env, functions);
85
+ return binaryOps[exp.operator](left, right);
86
+ },
87
+
88
+ BlockStatement(exp, env, functions) {
89
+ const scope = env.extend();
90
+ let result;
91
+ for (const part of exp.body) {
92
+ result = evaluate(part, scope, functions);
93
+ if (part.type === "ReturnStatement") {
94
+ break;
95
+ }
96
+ }
97
+ return result;
98
+ },
99
+
100
+ CallExpression(exp, env, functions) {
101
+ const func = evaluate(exp.callee);
102
+
103
+ // Collect args, handling spread
104
+ const args: any[] = [];
105
+ for (const arg of exp.arguments) {
106
+ if (arg.type === "SpreadElement") {
107
+ const spread = evaluate(arg.argument, env, functions);
108
+ args.push(...spread);
109
+ } else {
110
+ args.push(evaluate(arg, env, functions));
111
+ }
112
+ }
113
+
114
+ if (functions[func]) {
115
+ return functions[func](...args);
116
+ }
117
+
118
+ if (env.defined(func)) {
119
+ const customFunc = env.get(func, loc(exp));
120
+ if (typeof customFunc === "function") {
121
+ return customFunc(...args);
122
+ }
123
+ }
124
+ const l = loc(exp);
125
+ throw new Error(`${func} is not a function (${l.line}:${l.column})`);
126
+ },
127
+
128
+ ConditionalExpression(exp, env, functions) {
129
+ const test = evaluate(exp.test, env, functions);
130
+ return test
131
+ ? evaluate(exp.consequent, env, functions)
132
+ : evaluate(exp.alternate, env, functions);
133
+ },
134
+
135
+ ExpressionStatement(exp, env, functions) {
136
+ return evaluate(exp.expression, env, functions);
137
+ },
138
+
139
+ FunctionDeclaration(exp, env, functions) {
140
+ const name = evaluate(exp.id);
141
+ const params = exp.params.map((param: AnyNode) => evaluate(param));
142
+ env.set(name, makeFunc(params, exp.body, env, functions), loc(exp));
143
+ },
144
+
145
+ Identifier(exp, env) {
146
+ if (env) {
147
+ return env.get(exp.name, loc(exp));
148
+ }
149
+ return exp.name;
150
+ },
151
+
152
+ IfStatement(exp, env, functions) {
153
+ const test = evaluate(exp.test, env, functions);
154
+ if (test) {
155
+ return evaluate(exp.consequent, env, functions);
156
+ }
157
+ if (exp.alternate) {
158
+ return evaluate(exp.alternate, env, functions);
159
+ }
160
+ },
161
+
162
+ Literal(exp) {
163
+ return exp.value;
164
+ },
165
+
166
+ LogicalExpression(exp, env, functions) {
167
+ const left = evaluate(exp.left, env, functions);
168
+ const right = evaluate(exp.right, env, functions);
169
+ return logicOps[exp.operator](left, right);
170
+ },
171
+
172
+ MemberExpression(exp, env, functions) {
173
+ if (!env) {
174
+ const obj = evaluate(exp.object);
175
+ const prop = evaluate(exp.property);
176
+ assertSafeProperty(prop);
177
+ return `${obj}.${prop}`;
178
+ }
179
+ const obj = evaluate(exp.object, env, functions);
180
+ if (exp.computed) {
181
+ const prop = evaluate(exp.property, env, functions);
182
+ assertSafeProperty(String(prop));
183
+ return obj[prop];
184
+ }
185
+ const prop = evaluate(exp.property);
186
+ assertSafeProperty(prop);
187
+ return obj[prop];
188
+ },
189
+
190
+ ObjectExpression(exp, env, functions) {
191
+ const result: Record<string, any> = {};
192
+ for (const prop of exp.properties) {
193
+ if (prop.type === "SpreadElement") {
194
+ const spread = evaluate(prop.argument, env, functions);
195
+ Object.assign(result, spread);
196
+ } else {
197
+ // Property — key can be Identifier or Literal
198
+ const key =
199
+ prop.key.type === "Identifier" ? prop.key.name : prop.key.value;
200
+ result[key] = evaluate(prop.value, env, functions);
201
+ }
202
+ }
203
+ return result;
204
+ },
205
+
206
+ Program(exp, env, functions) {
207
+ let result;
208
+ for (const node of exp.body) {
209
+ result = evaluate(node, env, functions);
210
+ }
211
+ return result;
212
+ },
213
+
214
+ ReturnStatement(exp, env, functions) {
215
+ return evaluate(exp.argument, env, functions);
216
+ },
217
+
218
+ TemplateLiteral(exp, env, functions) {
219
+ let result = "";
220
+ for (let i = 0; i < exp.quasis.length; i++) {
221
+ result += exp.quasis[i].value.cooked;
222
+ if (i < exp.expressions.length) {
223
+ result += String(evaluate(exp.expressions[i], env, functions));
224
+ }
225
+ }
226
+ return result;
227
+ },
228
+
229
+ UnaryExpression(exp, env, functions) {
230
+ const arg = evaluate(exp.argument, env, functions);
231
+ switch (exp.operator) {
232
+ case "!":
233
+ return !arg;
234
+ case "-":
235
+ return -arg;
236
+ case "+":
237
+ return +arg;
238
+ case "typeof":
239
+ return typeof arg;
240
+ default:
241
+ throw new Error(`Unsupported unary operator: ${exp.operator}`);
242
+ }
243
+ },
244
+
245
+ VariableDeclaration(exp, env, functions) {
246
+ if (exp.kind === "var") {
247
+ const globalScope = env.getGlobalScope();
248
+ for (const dec of exp.declarations) {
249
+ evaluate(dec, globalScope, functions);
250
+ }
251
+ return;
252
+ }
253
+ for (const dec of exp.declarations) {
254
+ evaluate(dec, env, functions);
255
+ }
256
+ },
257
+
258
+ VariableDeclarator(exp, env, functions) {
259
+ const name = evaluate(exp.id);
260
+ const value = exp.init ? evaluate(exp.init, env, functions) : undefined;
261
+ return env.def(name, value);
262
+ },
263
+ };
264
+
265
+ function evaluate(exp: AnyNode, env?: any, functions?: any): any {
266
+ if (_maxSteps > 0 && ++_steps > _maxSteps) {
267
+ throw new Error("Execution limit exceeded");
268
+ }
269
+ if (evals[exp.type]) {
270
+ return evals[exp.type](exp, env, functions);
271
+ }
272
+ throw new Error("Cannot evaluate " + exp.type);
273
+ }
274
+
275
+ export default evaluate;
package/src/index.ts ADDED
@@ -0,0 +1,42 @@
1
+ import * as acorn from "acorn";
2
+ import evaluate, { resetStepCounter } from "./evaluate.js";
3
+ import builtinFuncs from "./builtin-functions.js";
4
+ import type { FunctionMap } from "./builtin-functions.js";
5
+ import Environment 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
+
20
+ export interface RunResult {
21
+ result: any;
22
+ env: Record<string, any>;
23
+ }
24
+
25
+ const DEFAULT_MAX_STEPS = 100_000;
26
+
27
+ export default function runner({ functions = builtinFuncs, maxSteps = DEFAULT_MAX_STEPS }: RunnerOptions = {}) {
28
+ return (code: string, env: Record<string, any> = {}, debug?: boolean): RunResult => {
29
+ const ast = parse(code);
30
+ debug && console.log(JSON.stringify(ast.body, null, 2));
31
+ resetStepCounter(maxSteps);
32
+ const globalEnv = new Environment();
33
+ Object.keys(env).forEach((key) => {
34
+ globalEnv.def(key, env[key]);
35
+ });
36
+ const result = evaluate(ast, globalEnv, functions);
37
+ return { result, env: globalEnv.vars };
38
+ };
39
+ }
40
+
41
+ export { Environment };
42
+ export type { FunctionMap };
@@ -0,0 +1,6 @@
1
+ const logicOps: Record<string, (l: unknown, r: unknown) => unknown> = {
2
+ "||": (l: any, r: any) => l || r,
3
+ "&&": (l: any, r: any) => l && r,
4
+ };
5
+
6
+ export default logicOps;
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
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
+ }
package/.npmignore DELETED
@@ -1 +0,0 @@
1
- node_modules/
@@ -1,85 +0,0 @@
1
- const runner = require("../");
2
-
3
- const run = runner();
4
-
5
- const DEBUG = true;
6
-
7
- const code = `
8
- /**
9
- * @param {String} who say hello to
10
- */
11
- function hello (who) {
12
- return "hello " + who;
13
- }
14
-
15
- // arrow function
16
- arrow = (str) => { return str + " =>"; }
17
-
18
- list = ["me", "myself"];
19
- push(list, "I");
20
-
21
- who = 0;
22
- greet1 = hello(who || "world");
23
-
24
- who = "Jason";
25
- greet2 = hello(who || "world");
26
-
27
- greet3 = arrow(hello(who || "world"));
28
-
29
- olsenTimezoneBrisbane = "Australia/Brisbane";
30
- olsenTimezoneLA = "America/Los_Angeles";
31
-
32
- dateNowUTC = currentDate();
33
- // Sat Aug 26 2017 22:56:08 GMT+0000
34
-
35
- dateNowBrisbane = currentDate(olsenTimezoneBrisbane);
36
- // Sun Aug 27 2017 08:56:08 GMT+1000
37
-
38
- dateNowLA = currentDate(olsenTimezoneLA);
39
- // Sat Aug 26 2017 19:52:35 GMT-0700
40
-
41
- nowFormattedUTC = formatDate(currentDate(), "MMM D YYYY h:mma z");
42
- // Aug 27 2017 2:56am UTC
43
-
44
- nowFormattedBrisbane = formatDate(currentDate(), "MMM D YYYY h:mma z", olsenTimezoneBrisbane);
45
- // Aug 27 2017 12:56pm AEST
46
-
47
- iso8601 = "2017-08-27T09:00:57.730+10:00";
48
-
49
- iso8601FormattedUTC = formatDate(iso8601, "MMM D YYYY h:mma z");
50
- // "Aug 26 2017 11:00pm UTC"
51
-
52
- iso8601FormattedLA = formatDate(iso8601, "MMM D YYYY h:mma z", olsenTimezoneLA);
53
- // "Aug 26 2017 4:00pm PDT"
54
-
55
- Date = (date) => formatDate(date, "MMM D YYYY h:mma z", olsenTimezoneLA);
56
-
57
- myDate = Date(iso8601);
58
- // "Aug 26 2017 4:00pm PDT"
59
- `;
60
-
61
- describe("docca-script", () => {
62
- it("runs a script", () => {
63
- const vars = {};
64
- const { env } = run(code, vars);
65
-
66
- expect(env.arrow).toBeInstanceOf(Function);
67
- expect(env.hello).toBeInstanceOf(Function);
68
-
69
- expect(env.list).toEqual(["me", "myself", "I"]);
70
-
71
- expect(env.greet1).toEqual("hello world");
72
-
73
- expect(env.greet2).toEqual("hello Jason");
74
-
75
- expect(env.greet3).toEqual("hello Jason =>");
76
-
77
- expect(/\+0000$/.test(`${env.dateNowUTC}`)).toBeTruthy();
78
- expect(/\+1000$/.test(`${env.dateNowBrisbane}`)).toBeTruthy();
79
- expect(/-0700$/.test(`${env.dateNowLA}`)).toBeTruthy();
80
-
81
- expect(env.iso8601FormattedUTC).toEqual("Aug 26 2017 11:00pm UTC");
82
- expect(env.iso8601FormattedLA).toEqual("Aug 26 2017 4:00pm PDT");
83
- expect(env.myDate).toEqual("Aug 26 2017 4:00pm PDT");
84
- });
85
- });
package/src/binary-ops.js DELETED
@@ -1,13 +0,0 @@
1
- const binaryOps = {
2
- "+": (l, r) => l + r,
3
- "-": (l, r) => l - r,
4
- "*": (l, r) => l * r,
5
- "/": (l, r) => l / r,
6
-
7
- ">": (l, r) => l > r,
8
- "<": (l, r) => l < r,
9
- "==": (l, r) => l === r,
10
- "!=": (l, r) => l !== r
11
- };
12
-
13
- module.exports = binaryOps;
@@ -1,58 +0,0 @@
1
- const moment = require("moment-timezone");
2
-
3
- const lodash = {
4
- array: require("lodash/array"),
5
- collection: require("lodash/collection"),
6
- math: require("lodash/math"),
7
- number: require("lodash/number"),
8
- object: require("lodash/object"),
9
- string: require("lodash/string")
10
- };
11
-
12
- function numberFormatter(...args) {
13
- return new Intl.NumberFormat(...args).format;
14
- }
15
-
16
- const functions = {
17
- push(...args) {
18
- const [target, item] = args;
19
- target.push(item);
20
- },
21
-
22
- shift(...args) {
23
- const [target] = args;
24
- return target.shift();
25
- },
26
-
27
- currentDate(...args) {
28
- const [tz] = args;
29
- return moment().tz(tz || "UTC");
30
- },
31
-
32
- formatDate(...args) {
33
- const [dateString, format, timezone] = args;
34
- const date = moment.tz(
35
- /^\d+$/.test(dateString) ? +dateString : dateString,
36
- timezone
37
- );
38
- return date.format(format);
39
- },
40
-
41
- numberFormatter,
42
-
43
- formatDollars: numberFormatter("en-us", {
44
- minimumFractionDigits: 2,
45
- maximumFractionDigits: 2
46
- })
47
- };
48
-
49
- // add lodash functions..
50
- lodash.object.forIn(lodash, category => {
51
- lodash.object.forIn(category, (func, key) => {
52
- functions[key] = (...args) => {
53
- return category[key](...args);
54
- };
55
- });
56
- });
57
-
58
- module.exports = functions;
@@ -1,73 +0,0 @@
1
- const _has = require("lodash/has");
2
- const _get = require("lodash/get");
3
- const _set = require("lodash/set");
4
-
5
- function Environment(parent) {
6
- this.vars = Object.create(parent ? parent.vars : null);
7
- this.parent = parent;
8
- }
9
-
10
- Environment.prototype = {
11
- extend() {
12
- return new Environment(this);
13
- },
14
- getGlobalScope() {
15
- let scope = this;
16
- while (scope.parent) {
17
- scope = scope.parent;
18
- }
19
- return scope;
20
- },
21
- lookup(name) {
22
- let scope = this;
23
- while (scope.parent) {
24
- if (Object.prototype.hasOwnProperty.call(scope.vars, name)) {
25
- return scope;
26
- }
27
- scope = scope.parent;
28
- }
29
- return scope;
30
- },
31
- defined(name) {
32
- if (name in this.vars) {
33
- return true;
34
- }
35
- // `has` does not include inherited properties
36
- // but does handle "deep" properties
37
- if (_has(this.vars, name)) {
38
- return true;
39
- }
40
- },
41
- get(name, loc) {
42
- // `in` includes inherited properties
43
- if (name in this.vars) {
44
- return this.vars[name];
45
- }
46
- // `has` does not include inherited properties
47
- // but does handle "deep" properties
48
- if (_has(this.vars, name)) {
49
- return _get(this.vars, name);
50
- }
51
- throw new ReferenceError(
52
- `"${name}" is not defined (${loc.line}:${loc.column})`
53
- );
54
- },
55
- set(name, value, loc) {
56
- const baseName = name.replace(/\..*/, "");
57
- let scope = this.lookup(baseName);
58
- // if (!scope) {
59
- if (!scope && this.parent) {
60
- throw new ReferenceError(
61
- `"${name}" is not defined (${loc.line}:${loc.column})`
62
- );
63
- }
64
- _set((scope || this).vars, name, value);
65
- return value;
66
- },
67
- def(name, value) {
68
- _set(this.vars, name, value);
69
- return value;
70
- }
71
- };
72
-
73
- module.exports = Environment;