Skip to content
This repository was archived by the owner on May 28, 2024. It is now read-only.

Commit cbfb660

Browse files
committed
feat: add sandboxed eval function
1 parent cbeb160 commit cbfb660

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

index.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
(function (factory) {
2+
if (typeof module === "object" && typeof module.exports === "object") {
3+
var v = factory(require, exports);
4+
if (v !== undefined) module.exports = v;
5+
}
6+
else if (typeof define === "function" && define.amd) {
7+
define(["require", "exports"], factory);
8+
}
9+
})(function (require, exports) {
10+
"use strict";
11+
Object.defineProperty(exports, "__esModule", { value: true });
12+
const proxyCache = new WeakMap();
13+
exports.compile = (expression) => {
14+
const fn = new Function('scope', `with (scope) { return ${expression}; }`);
15+
return (scope) => {
16+
if (!proxyCache.has(scope)) {
17+
proxyCache.set(scope, new Proxy(scope, {
18+
has: () => true,
19+
get: (target, key) => {
20+
if (key === Symbol.unscopables || typeof key !== 'string') {
21+
return undefined;
22+
}
23+
return target[key];
24+
}
25+
}));
26+
}
27+
return fn(proxyCache.get(scope));
28+
};
29+
};
30+
});

index.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
interface Scope {
2+
[key: string]: any;
3+
}
4+
5+
const proxyCache: WeakMap<Scope, any> = new WeakMap();
6+
7+
export const compile = (expression: string): (scope: Scope) => any => {
8+
const fn = new Function('scope', `with (scope) { return ${expression}; }`);
9+
10+
return (scope: Scope): any => {
11+
if (!proxyCache.has(scope)) {
12+
proxyCache.set(
13+
scope,
14+
new Proxy(scope, {
15+
has: () => true,
16+
get: (target: Scope, key: unknown) => {
17+
if (key === Symbol.unscopables || typeof key !== 'string') {
18+
return undefined;
19+
}
20+
return target[key as string];
21+
}
22+
})
23+
);
24+
}
25+
return fn(proxyCache.get(scope));
26+
};
27+
};

tsconfig.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2015",
4+
"module": "umd",
5+
"strict": true,
6+
"lib": ["es2015"]
7+
}
8+
}

0 commit comments

Comments
 (0)