@memberjunction/code-execution 5.29.0 → 5.30.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/.turbo/turbo-build.log +6 -2
- package/CHANGELOG.md +16 -0
- package/dist/WorkerPool.d.ts +39 -1
- package/dist/WorkerPool.d.ts.map +1 -1
- package/dist/WorkerPool.js +305 -22
- package/dist/WorkerPool.js.map +1 -1
- package/dist/libraries/bundled-libs/date-fns.js +3 -0
- package/dist/libraries/bundled-libs/jstat.js +1 -0
- package/dist/libraries/bundled-libs/lodash.js +140 -0
- package/dist/libraries/bundled-libs/mathjs.js +3 -0
- package/dist/libraries/bundled-libs/papaparse.js +7 -0
- package/dist/libraries/bundled-libs/uuid.js +43 -0
- package/dist/libraries/bundled-libs/validator.js +23 -0
- package/dist/libraries/index.js +128 -7
- package/dist/libraries/index.js.map +1 -1
- package/dist/types/index.d.ts +106 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/worker.d.ts +22 -0
- package/dist/worker.d.ts.map +1 -1
- package/dist/worker.js +194 -4
- package/dist/worker.js.map +1 -1
- package/package.json +5 -4
- package/src/WorkerPool.ts +398 -26
- package/src/__tests__/WorkerPool.test.ts +7 -3
- package/src/__tests__/bridge.test.ts +188 -0
- package/src/__tests__/libraries.test.ts +13 -17
- package/src/libraries/index.ts +129 -7
- package/src/types/index.ts +129 -5
- package/src/worker.ts +255 -8
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* End-to-end bridge tests for the CodeExecution sandbox.
|
|
3
|
+
*
|
|
4
|
+
* These tests exercise the REAL isolated-vm + child-process path so we can
|
|
5
|
+
* verify the bridge protocol actually works: sandbox code calls
|
|
6
|
+
* `__bridgeCall(name, args)`, the worker routes it to the host, the host
|
|
7
|
+
* invokes the registered handler, the response travels back, and the
|
|
8
|
+
* sandbox's `await` resolves with the result.
|
|
9
|
+
*
|
|
10
|
+
* These tests import from the compiled `dist/` output rather than `src/`
|
|
11
|
+
* because `WorkerPool.fork()` resolves `worker.js` relative to its own
|
|
12
|
+
* module location via `import.meta.url` — running vitest against the TS
|
|
13
|
+
* source would look for a sibling `src/worker.js` file that doesn't exist.
|
|
14
|
+
*
|
|
15
|
+
* Because they fork real Node processes they're slower than our other unit
|
|
16
|
+
* tests; each test has a generous timeout.
|
|
17
|
+
*/
|
|
18
|
+
import { describe, it, expect, afterAll } from 'vitest';
|
|
19
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
20
|
+
// @ts-ignore - built output has no .d.ts index.js entry for tests
|
|
21
|
+
import { CodeExecutionService } from '../../dist/index.js';
|
|
22
|
+
|
|
23
|
+
describe('CodeExecution bridge (end-to-end)', () => {
|
|
24
|
+
// One service for the whole suite so we amortize the worker-pool startup
|
|
25
|
+
// cost across tests. Shut it down in afterAll.
|
|
26
|
+
const service = new CodeExecutionService({ poolSize: 1 });
|
|
27
|
+
|
|
28
|
+
afterAll(async () => {
|
|
29
|
+
await (service as unknown as { workerPool: { shutdown: () => Promise<void> } }).workerPool.shutdown();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('round-trips a simple bridge call', async () => {
|
|
33
|
+
const result = await service.execute({
|
|
34
|
+
code: `
|
|
35
|
+
const echo = await __bridgeCall('__echo', { msg: 'hello' });
|
|
36
|
+
output = echo;
|
|
37
|
+
`,
|
|
38
|
+
language: 'javascript',
|
|
39
|
+
bridgeHandlers: {
|
|
40
|
+
__echo: async (args: unknown) => args
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
expect(result.success).toBe(true);
|
|
45
|
+
expect(result.output).toEqual({ msg: 'hello' });
|
|
46
|
+
}, 15000);
|
|
47
|
+
|
|
48
|
+
it('rejects when sandbox calls an unregistered handler', async () => {
|
|
49
|
+
const result = await service.execute({
|
|
50
|
+
code: `
|
|
51
|
+
try {
|
|
52
|
+
await __bridgeCall('nope', {});
|
|
53
|
+
output = { unexpected: true };
|
|
54
|
+
} catch (err) {
|
|
55
|
+
output = { error: err.message };
|
|
56
|
+
}
|
|
57
|
+
`,
|
|
58
|
+
language: 'javascript',
|
|
59
|
+
bridgeHandlers: { __echo: async (a: unknown) => a }
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
expect(result.success).toBe(true);
|
|
63
|
+
expect(result.output).toHaveProperty('error');
|
|
64
|
+
expect(String(result.output.error)).toContain("'nope'");
|
|
65
|
+
}, 15000);
|
|
66
|
+
|
|
67
|
+
it('propagates handler-thrown errors to the sandbox', async () => {
|
|
68
|
+
const result = await service.execute({
|
|
69
|
+
code: `
|
|
70
|
+
try {
|
|
71
|
+
await __bridgeCall('boom', {});
|
|
72
|
+
output = { unexpected: true };
|
|
73
|
+
} catch (err) {
|
|
74
|
+
output = { error: err.message };
|
|
75
|
+
}
|
|
76
|
+
`,
|
|
77
|
+
language: 'javascript',
|
|
78
|
+
bridgeHandlers: {
|
|
79
|
+
boom: async () => {
|
|
80
|
+
throw new Error('explosion');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
expect(result.success).toBe(true);
|
|
86
|
+
expect(result.output.error).toBe('explosion');
|
|
87
|
+
}, 15000);
|
|
88
|
+
|
|
89
|
+
it('supports Promise.all with concurrent bridge calls correlated by callId', async () => {
|
|
90
|
+
const result = await service.execute({
|
|
91
|
+
code: `
|
|
92
|
+
const [a, b, c] = await Promise.all([
|
|
93
|
+
__bridgeCall('double', 3),
|
|
94
|
+
__bridgeCall('double', 7),
|
|
95
|
+
__bridgeCall('double', 11)
|
|
96
|
+
]);
|
|
97
|
+
output = { a, b, c };
|
|
98
|
+
`,
|
|
99
|
+
language: 'javascript',
|
|
100
|
+
bridgeHandlers: {
|
|
101
|
+
double: async (args: unknown) => (args as number) * 2
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
expect(result.success).toBe(true);
|
|
106
|
+
expect(result.output).toEqual({ a: 6, b: 14, c: 22 });
|
|
107
|
+
}, 15000);
|
|
108
|
+
|
|
109
|
+
it('enforces maxBridgeCalls', async () => {
|
|
110
|
+
const result = await service.execute({
|
|
111
|
+
code: `
|
|
112
|
+
const attempts = [];
|
|
113
|
+
let failedWith = null;
|
|
114
|
+
for (let i = 0; i < 5; i++) {
|
|
115
|
+
try {
|
|
116
|
+
const r = await __bridgeCall('ping', i);
|
|
117
|
+
attempts.push(r);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
failedWith = err.message;
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
output = { attempts, failedWith };
|
|
124
|
+
`,
|
|
125
|
+
language: 'javascript',
|
|
126
|
+
maxBridgeCalls: 3,
|
|
127
|
+
bridgeHandlers: {
|
|
128
|
+
ping: async (n: unknown) => `pong-${n}`
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
expect(result.success).toBe(true);
|
|
133
|
+
expect(result.output.attempts).toEqual(['pong-0', 'pong-1', 'pong-2']);
|
|
134
|
+
expect(String(result.output.failedWith)).toContain('maxBridgeCalls=3');
|
|
135
|
+
}, 15000);
|
|
136
|
+
|
|
137
|
+
it('aborts in-flight bridge calls when the caller aborts', async () => {
|
|
138
|
+
const controller = new AbortController();
|
|
139
|
+
// A handler that never resolves — we want the sandbox to be suspended
|
|
140
|
+
// on the `await` when the abort fires.
|
|
141
|
+
const resultPromise = service.execute({
|
|
142
|
+
code: `
|
|
143
|
+
try {
|
|
144
|
+
await __bridgeCall('hang', {});
|
|
145
|
+
output = { unexpected: true };
|
|
146
|
+
} catch (err) {
|
|
147
|
+
output = { error: err.message };
|
|
148
|
+
}
|
|
149
|
+
`,
|
|
150
|
+
language: 'javascript',
|
|
151
|
+
timeoutSeconds: 10,
|
|
152
|
+
abortSignal: controller.signal,
|
|
153
|
+
bridgeHandlers: {
|
|
154
|
+
hang: () => new Promise<never>(() => {})
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// Let the sandbox enter the await before aborting.
|
|
159
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
160
|
+
controller.abort('user cancelled');
|
|
161
|
+
|
|
162
|
+
const result = await resultPromise;
|
|
163
|
+
expect(result.success).toBe(false);
|
|
164
|
+
expect(result.errorType).toBe('TIMEOUT');
|
|
165
|
+
expect(String(result.error)).toContain('user cancelled');
|
|
166
|
+
}, 20000);
|
|
167
|
+
|
|
168
|
+
it('leaves subsequent executions unaffected after a bridge failure', async () => {
|
|
169
|
+
const failing = await service.execute({
|
|
170
|
+
code: `
|
|
171
|
+
try { await __bridgeCall('fail', {}); output = 'no'; }
|
|
172
|
+
catch (e) { output = e.message; }
|
|
173
|
+
`,
|
|
174
|
+
language: 'javascript',
|
|
175
|
+
bridgeHandlers: { fail: async () => { throw new Error('nope'); } }
|
|
176
|
+
});
|
|
177
|
+
expect(failing.success).toBe(true);
|
|
178
|
+
expect(failing.output).toBe('nope');
|
|
179
|
+
|
|
180
|
+
const recovering = await service.execute({
|
|
181
|
+
code: `output = await __bridgeCall('ok', 42);`,
|
|
182
|
+
language: 'javascript',
|
|
183
|
+
bridgeHandlers: { ok: async (n: unknown) => (n as number) + 1 }
|
|
184
|
+
});
|
|
185
|
+
expect(recovering.success).toBe(true);
|
|
186
|
+
expect(recovering.output).toBe(43);
|
|
187
|
+
}, 20000);
|
|
188
|
+
});
|
|
@@ -118,22 +118,18 @@ describe('Libraries', () => {
|
|
|
118
118
|
expect(typeof source).toBe('string');
|
|
119
119
|
});
|
|
120
120
|
|
|
121
|
-
it('should return lodash
|
|
121
|
+
it('should return bundled lodash wrapped in module-shim IIFE', () => {
|
|
122
|
+
// NOTE: fs.readFileSync is mocked at the top of this test file, so the
|
|
123
|
+
// "source" we get here is our IIFE wrapper around the stub content —
|
|
124
|
+
// NOT the real ~73KB lodash bundle. We assert the shape of the wrapper
|
|
125
|
+
// (proves we switched away from the old hand-coded subset). End-to-end
|
|
126
|
+
// behavior of real lodash is exercised by Runtime action integration
|
|
127
|
+
// tests, not here.
|
|
122
128
|
const source = getLibrarySource('lodash')!;
|
|
123
|
-
expect(source).toContain('
|
|
124
|
-
expect(source).toContain('
|
|
125
|
-
|
|
126
|
-
expect(source).toContain('
|
|
127
|
-
expect(source).toContain('groupBy');
|
|
128
|
-
expect(source).toContain('keyBy');
|
|
129
|
-
expect(source).toContain('sortBy');
|
|
130
|
-
expect(source).toContain('pick');
|
|
131
|
-
expect(source).toContain('omit');
|
|
132
|
-
expect(source).toContain('get');
|
|
133
|
-
expect(source).toContain('set');
|
|
134
|
-
expect(source).toContain('sum');
|
|
135
|
-
expect(source).toContain('mean');
|
|
136
|
-
expect(source).toContain('cloneDeep');
|
|
129
|
+
expect(source).toContain('const module = { exports: {} }');
|
|
130
|
+
expect(source).toContain('return module.exports');
|
|
131
|
+
// Old subset signature absent — we no longer wire up getLodashSource().
|
|
132
|
+
expect(source).not.toContain('chunk: function(array');
|
|
137
133
|
});
|
|
138
134
|
|
|
139
135
|
it('should return date-fns source with expected functions', () => {
|
|
@@ -173,9 +169,9 @@ describe('Libraries', () => {
|
|
|
173
169
|
|
|
174
170
|
it('should return wrapped IIFE for inline libraries', () => {
|
|
175
171
|
const lodashSource = getLibrarySource('lodash')!;
|
|
176
|
-
//
|
|
172
|
+
// Lodash is now the bundled UMD wrapped in our module-shim IIFE.
|
|
177
173
|
expect(lodashSource).toMatch(/^\(function\(\)/);
|
|
178
|
-
expect(lodashSource).toContain('return
|
|
174
|
+
expect(lodashSource).toContain('return module.exports');
|
|
179
175
|
|
|
180
176
|
const dateFnsSource = getLibrarySource('date-fns')!;
|
|
181
177
|
expect(dateFnsSource).toMatch(/^\(function\(\)/);
|
package/src/libraries/index.ts
CHANGED
|
@@ -57,7 +57,7 @@ export function getLibrarySource(moduleName: string): string | null {
|
|
|
57
57
|
|
|
58
58
|
switch (moduleName) {
|
|
59
59
|
case 'lodash':
|
|
60
|
-
return
|
|
60
|
+
return getBundledLodashSource();
|
|
61
61
|
case 'date-fns':
|
|
62
62
|
return getDateFnsSource();
|
|
63
63
|
case 'mathjs':
|
|
@@ -104,6 +104,56 @@ function getLodashSource(): string {
|
|
|
104
104
|
return [...new Set(array)];
|
|
105
105
|
},
|
|
106
106
|
|
|
107
|
+
// Min/Max — commonly reached for in numeric-summary style Runtime
|
|
108
|
+
// actions. Return undefined for empty arrays (matches real lodash).
|
|
109
|
+
min: function(array) {
|
|
110
|
+
if (!array || array.length === 0) return undefined;
|
|
111
|
+
let m = array[0];
|
|
112
|
+
for (let i = 1; i < array.length; i++) {
|
|
113
|
+
if (array[i] < m) m = array[i];
|
|
114
|
+
}
|
|
115
|
+
return m;
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
max: function(array) {
|
|
119
|
+
if (!array || array.length === 0) return undefined;
|
|
120
|
+
let m = array[0];
|
|
121
|
+
for (let i = 1; i < array.length; i++) {
|
|
122
|
+
if (array[i] > m) m = array[i];
|
|
123
|
+
}
|
|
124
|
+
return m;
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
minBy: function(array, iteratee) {
|
|
128
|
+
if (!array || array.length === 0) return undefined;
|
|
129
|
+
const fn = typeof iteratee === 'function' ? iteratee : (x) => x[iteratee];
|
|
130
|
+
let best = array[0];
|
|
131
|
+
let bestScore = fn(best);
|
|
132
|
+
for (let i = 1; i < array.length; i++) {
|
|
133
|
+
const score = fn(array[i]);
|
|
134
|
+
if (score < bestScore) {
|
|
135
|
+
best = array[i];
|
|
136
|
+
bestScore = score;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return best;
|
|
140
|
+
},
|
|
141
|
+
|
|
142
|
+
maxBy: function(array, iteratee) {
|
|
143
|
+
if (!array || array.length === 0) return undefined;
|
|
144
|
+
const fn = typeof iteratee === 'function' ? iteratee : (x) => x[iteratee];
|
|
145
|
+
let best = array[0];
|
|
146
|
+
let bestScore = fn(best);
|
|
147
|
+
for (let i = 1; i < array.length; i++) {
|
|
148
|
+
const score = fn(array[i]);
|
|
149
|
+
if (score > bestScore) {
|
|
150
|
+
best = array[i];
|
|
151
|
+
bestScore = score;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return best;
|
|
155
|
+
},
|
|
156
|
+
|
|
107
157
|
difference: function(array, ...values) {
|
|
108
158
|
const others = new Set(values.flat());
|
|
109
159
|
return array.filter(x => !others.has(x));
|
|
@@ -155,6 +205,26 @@ function getLodashSource(): string {
|
|
|
155
205
|
});
|
|
156
206
|
},
|
|
157
207
|
|
|
208
|
+
// orderBy is like sortBy but supports per-iteratee asc/desc direction.
|
|
209
|
+
// Signature: orderBy(collection, iteratees, orders) where iteratees
|
|
210
|
+
// and orders are parallel arrays (or both scalars). Direction strings
|
|
211
|
+
// default to 'asc' when not supplied.
|
|
212
|
+
orderBy: function(collection, iteratees, orders) {
|
|
213
|
+
const itList = Array.isArray(iteratees) ? iteratees : [iteratees];
|
|
214
|
+
const orderList = Array.isArray(orders) ? orders : (orders ? [orders] : []);
|
|
215
|
+
const resolveFn = (it) => typeof it === 'function' ? it : x => x[it];
|
|
216
|
+
return [...collection].sort((a, b) => {
|
|
217
|
+
for (let i = 0; i < itList.length; i++) {
|
|
218
|
+
const fn = resolveFn(itList[i]);
|
|
219
|
+
const dir = (orderList[i] ?? 'asc') === 'desc' ? -1 : 1;
|
|
220
|
+
const aVal = fn(a);
|
|
221
|
+
const bVal = fn(b);
|
|
222
|
+
if (aVal !== bVal) return aVal < bVal ? -1 * dir : 1 * dir;
|
|
223
|
+
}
|
|
224
|
+
return 0;
|
|
225
|
+
});
|
|
226
|
+
},
|
|
227
|
+
|
|
158
228
|
// Object functions
|
|
159
229
|
pick: function(object, ...paths) {
|
|
160
230
|
const keys = paths.flat();
|
|
@@ -242,15 +312,34 @@ function getDateFnsSource(): string {
|
|
|
242
312
|
const dateFns = {
|
|
243
313
|
format: function(date, formatStr) {
|
|
244
314
|
const d = new Date(date);
|
|
315
|
+
const monthsLong = ['January','February','March','April','May','June','July','August','September','October','November','December'];
|
|
316
|
+
const monthsShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
|
|
317
|
+
const daysLong = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
|
|
318
|
+
const daysShort = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
|
|
319
|
+
const month = d.getMonth();
|
|
320
|
+
const dow = d.getDay();
|
|
321
|
+
// Supported tokens are listed longest-first in the regex so that
|
|
322
|
+
// e.g. 'MMMM' is matched before 'MMM' / 'MM' / 'M'.
|
|
323
|
+
// NOTE: this shim has no literal-escape support, so we deliberately
|
|
324
|
+
// omit ambiguous single-letter tokens from real date-fns (a/h/H/m/s
|
|
325
|
+
// bare) that collide with common English letters in format strings.
|
|
326
|
+
// Users who need time formatting can use the padded HH:mm:ss forms.
|
|
245
327
|
const tokens = {
|
|
246
328
|
'yyyy': d.getFullYear(),
|
|
247
|
-
'
|
|
248
|
-
'
|
|
249
|
-
'
|
|
250
|
-
'
|
|
251
|
-
'
|
|
329
|
+
'yy': String(d.getFullYear()).slice(-2),
|
|
330
|
+
'MMMM': monthsLong[month],
|
|
331
|
+
'MMM': monthsShort[month],
|
|
332
|
+
'MM': String(month + 1).padStart(2, '0'),
|
|
333
|
+
'M': String(month + 1),
|
|
334
|
+
'dd': String(d.getDate()).padStart(2, '0'),
|
|
335
|
+
'd': String(d.getDate()),
|
|
336
|
+
'EEEE': daysLong[dow],
|
|
337
|
+
'EEE': daysShort[dow],
|
|
338
|
+
'HH': String(d.getHours()).padStart(2, '0'),
|
|
339
|
+
'mm': String(d.getMinutes()).padStart(2, '0'),
|
|
340
|
+
'ss': String(d.getSeconds()).padStart(2, '0')
|
|
252
341
|
};
|
|
253
|
-
return formatStr.replace(/yyyy|MM|dd|HH|mm|ss/g, match => tokens[match]);
|
|
342
|
+
return formatStr.replace(/yyyy|yy|MMMM|MMM|MM|M|dd|d|EEEE|EEE|HH|mm|ss/g, match => tokens[match]);
|
|
254
343
|
},
|
|
255
344
|
|
|
256
345
|
addDays: function(date, days) {
|
|
@@ -383,6 +472,39 @@ function getValidatorSource(): string {
|
|
|
383
472
|
`.trim();
|
|
384
473
|
}
|
|
385
474
|
|
|
475
|
+
/**
|
|
476
|
+
* Load the bundled full lodash UMD build (~73KB). We used to hand-roll
|
|
477
|
+
* a tiny subset here, but the subset was missing the most foundational
|
|
478
|
+
* helpers (`map`, `filter`, `forEach`, `reduce`, `find`, `some`, `every`,
|
|
479
|
+
* `keys`, `values`, `each`, `includes`) — so any Runtime action that
|
|
480
|
+
* called `_.map(...)` crashed with "_.map is not a function". The inline
|
|
481
|
+
* subset stays in this file below as `getLodashSource()` for reference /
|
|
482
|
+
* fallback only; it is no longer wired up.
|
|
483
|
+
*
|
|
484
|
+
* Lodash's UMD epilogue looks for `module.exports` before falling back to
|
|
485
|
+
* a global. We provide a shim `module` and return `module.exports` so the
|
|
486
|
+
* sandbox gets the full lodash object exactly as `require('lodash')` would
|
|
487
|
+
* hand back in node.
|
|
488
|
+
*/
|
|
489
|
+
function getBundledLodashSource(): string {
|
|
490
|
+
const libPath = path.join(__dirname, 'bundled-libs', 'lodash.js');
|
|
491
|
+
const source = fs.readFileSync(libPath, 'utf8');
|
|
492
|
+
// Lodash's UMD defines `ue` (the module-exports branch it actually writes
|
|
493
|
+
// to) as `ee && typeof module == "object" && ... && module`, where
|
|
494
|
+
// `ee = typeof exports == "object" && exports && ...`. So it short-circuits
|
|
495
|
+
// to the global branch (`re._=be`, synthesized root) if `exports` is
|
|
496
|
+
// undefined in scope — even when `module` is present. Both shims are
|
|
497
|
+
// required, and they must share storage (`const exports = module.exports`)
|
|
498
|
+
// so whichever path lodash picks, `module.exports` ends up holding the
|
|
499
|
+
// real lodash object.
|
|
500
|
+
return `(function() {
|
|
501
|
+
const module = { exports: {} };
|
|
502
|
+
const exports = module.exports;
|
|
503
|
+
${source}
|
|
504
|
+
return module.exports;
|
|
505
|
+
})()`;
|
|
506
|
+
}
|
|
507
|
+
|
|
386
508
|
/**
|
|
387
509
|
* mathjs implementation
|
|
388
510
|
* Provides comprehensive mathematics and statistics functions
|
package/src/types/index.ts
CHANGED
|
@@ -1,32 +1,83 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* A host-side bridge handler function. Registered per-execution via
|
|
3
|
+
* `CodeExecutionService.execute({ bridgeHandlers, ... })` and invoked when
|
|
4
|
+
* sandboxed code calls `__bridgeCall(name, args)`. The handler receives the
|
|
5
|
+
* args (already JSON-round-tripped, so primitives + plain objects only) and
|
|
6
|
+
* returns any JSON-serializable value; it may also throw, in which case the
|
|
7
|
+
* sandbox's `await __bridgeCall(...)` rejects with the error's message.
|
|
8
|
+
*
|
|
9
|
+
* The handler runs in the **host process**, not the sandbox. It has full
|
|
10
|
+
* access to MJ's services, DB, and filesystem — so higher layers
|
|
11
|
+
* (RuntimeActionBridge in @memberjunction/action-runtime) are responsible
|
|
12
|
+
* for enforcing per-Runtime-action permission scopes before each call
|
|
13
|
+
* reaches this point.
|
|
14
|
+
*/
|
|
15
|
+
export type BridgeHandler = (args: unknown) => Promise<unknown> | unknown;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A name → handler map passed to `CodeExecutionService.execute()` for a
|
|
19
|
+
* single invocation. The sandbox can only call names that are present in
|
|
20
|
+
* this map; unknown names reject with a "handler not registered" error.
|
|
21
|
+
*/
|
|
22
|
+
export type BridgeHandlerMap = Record<string, BridgeHandler>;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Parameters for code execution.
|
|
26
|
+
*
|
|
27
|
+
* `bridgeHandlers` is the ONLY field that is NOT sent over IPC — functions
|
|
28
|
+
* can't be serialized across the process boundary. The host keeps the map
|
|
29
|
+
* alive for the duration of this execution and uses it to service
|
|
30
|
+
* `bridge-call` messages coming back from the worker.
|
|
3
31
|
*/
|
|
4
32
|
export interface CodeExecutionParams {
|
|
5
33
|
/**
|
|
6
34
|
* The code to execute
|
|
7
35
|
*/
|
|
8
36
|
code: string;
|
|
9
|
-
|
|
37
|
+
|
|
10
38
|
/**
|
|
11
39
|
* Programming language (currently only 'javascript' supported)
|
|
12
40
|
*/
|
|
13
41
|
language: 'javascript';
|
|
14
|
-
|
|
42
|
+
|
|
15
43
|
/**
|
|
16
44
|
* Input data available to the code via 'input' variable
|
|
17
45
|
*/
|
|
18
46
|
inputData?: any;
|
|
19
|
-
|
|
47
|
+
|
|
20
48
|
/**
|
|
21
49
|
* Maximum execution time in seconds (default: 30)
|
|
22
50
|
*/
|
|
23
51
|
timeoutSeconds?: number;
|
|
24
|
-
|
|
52
|
+
|
|
25
53
|
/**
|
|
26
54
|
* Memory limit in MB (default: 128)
|
|
27
55
|
* Note: Memory limiting requires Node.js flags, enforced at process level
|
|
28
56
|
*/
|
|
29
57
|
memoryLimitMB?: number;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Optional map of bridge handlers to expose to sandbox code as
|
|
61
|
+
* `__bridgeCall(name, args)`. When present, the sandbox can make async
|
|
62
|
+
* round-trips to the host for each registered name. Host-side only — not
|
|
63
|
+
* sent over IPC. See {@link BridgeHandler}.
|
|
64
|
+
*/
|
|
65
|
+
bridgeHandlers?: BridgeHandlerMap;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Optional cap on the number of bridge calls a single execution may
|
|
69
|
+
* make (default: 100). The (N+1)th call rejects with a BRIDGE_LIMIT
|
|
70
|
+
* error. Prevents runaway loops inside sandbox code.
|
|
71
|
+
*/
|
|
72
|
+
maxBridgeCalls?: number;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Optional AbortSignal for upstream cancellation. When aborted, any
|
|
76
|
+
* in-flight `await __bridgeCall(...)` inside the sandbox rejects and
|
|
77
|
+
* the sandbox script is left to wind down (we don't dispose the isolate
|
|
78
|
+
* mid-execution — see design notes in the plan).
|
|
79
|
+
*/
|
|
80
|
+
abortSignal?: AbortSignal;
|
|
30
81
|
}
|
|
31
82
|
|
|
32
83
|
/**
|
|
@@ -84,6 +135,79 @@ export interface JavaScriptExecutionOptions {
|
|
|
84
135
|
allowedLibraries?: string[];
|
|
85
136
|
}
|
|
86
137
|
|
|
138
|
+
/**
|
|
139
|
+
* IPC message types for worker/host communication.
|
|
140
|
+
*
|
|
141
|
+
* Existing: `execute`, `result`, `error`, `ready`.
|
|
142
|
+
* NEW for the bridge: `bridge-call` (worker→host), `bridge-response`
|
|
143
|
+
* (host→worker), `abort` (host→worker).
|
|
144
|
+
*/
|
|
145
|
+
|
|
146
|
+
/** Host → Worker: run this code. */
|
|
147
|
+
export interface ExecuteIpcMessage {
|
|
148
|
+
type: 'execute';
|
|
149
|
+
requestId: string;
|
|
150
|
+
/** The IPC-safe subset of `CodeExecutionParams` (no `bridgeHandlers`). */
|
|
151
|
+
params: Omit<CodeExecutionParams, 'bridgeHandlers' | 'abortSignal'>;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Worker → Host: execution finished cleanly. */
|
|
155
|
+
export interface ResultIpcMessage {
|
|
156
|
+
type: 'result';
|
|
157
|
+
requestId: string;
|
|
158
|
+
result: CodeExecutionResult;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Worker → Host: execution threw before the handler could assemble a result. */
|
|
162
|
+
export interface ErrorIpcMessage {
|
|
163
|
+
type: 'error';
|
|
164
|
+
requestId: string;
|
|
165
|
+
error: string;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Worker → Host: sandbox code wants the host to service a bridge call. */
|
|
169
|
+
export interface BridgeCallIpcMessage {
|
|
170
|
+
type: 'bridge-call';
|
|
171
|
+
requestId: string;
|
|
172
|
+
/** Unique per call so Promise.all-style concurrency is correlated correctly. */
|
|
173
|
+
callId: string;
|
|
174
|
+
/** Name registered in the execution's `bridgeHandlers` map. */
|
|
175
|
+
functionName: string;
|
|
176
|
+
/** JSON-round-tripped args. */
|
|
177
|
+
args: unknown;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Host → Worker: result of a bridge call. One of `result` | `error` is populated. */
|
|
181
|
+
export interface BridgeResponseIpcMessage {
|
|
182
|
+
type: 'bridge-response';
|
|
183
|
+
requestId: string;
|
|
184
|
+
callId: string;
|
|
185
|
+
result?: unknown;
|
|
186
|
+
error?: string;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Host → Worker: abort in-flight bridge calls for this requestId. */
|
|
190
|
+
export interface AbortIpcMessage {
|
|
191
|
+
type: 'abort';
|
|
192
|
+
requestId: string;
|
|
193
|
+
reason: string;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Worker → Host: initial ready signal (no requestId). */
|
|
197
|
+
export interface ReadyIpcMessage {
|
|
198
|
+
type: 'ready';
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Host → Worker message types. */
|
|
202
|
+
export type HostToWorkerMessage = ExecuteIpcMessage | BridgeResponseIpcMessage | AbortIpcMessage;
|
|
203
|
+
|
|
204
|
+
/** Worker → Host message types. */
|
|
205
|
+
export type WorkerToHostMessage =
|
|
206
|
+
| ResultIpcMessage
|
|
207
|
+
| ErrorIpcMessage
|
|
208
|
+
| BridgeCallIpcMessage
|
|
209
|
+
| ReadyIpcMessage;
|
|
210
|
+
|
|
87
211
|
/**
|
|
88
212
|
* Sandbox context provided to executed code
|
|
89
213
|
*/
|