@memberjunction/code-execution 4.2.0 → 4.3.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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @memberjunction/code-execution@4.2.0 build
2
+ > @memberjunction/code-execution@4.3.0 build
3
3
  > tsc && tsc-alias -f
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @memberjunction/code-execution
2
2
 
3
+ ## 4.3.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [564e1af]
8
+ - @memberjunction/core@4.3.0
9
+ - @memberjunction/global@4.3.0
10
+
3
11
  ## 4.2.0
4
12
 
5
13
  ### Patch Changes
package/package.json CHANGED
@@ -1,17 +1,19 @@
1
1
  {
2
2
  "name": "@memberjunction/code-execution",
3
3
  "type": "module",
4
- "version": "4.2.0",
4
+ "version": "4.3.0",
5
5
  "description": "Sandboxed code execution service for MemberJunction actions and agents",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
8
8
  "scripts": {
9
9
  "build": "tsc && tsc-alias -f",
10
- "watch": "tsc --watch"
10
+ "watch": "tsc --watch",
11
+ "test": "vitest run",
12
+ "test:watch": "vitest"
11
13
  },
12
14
  "dependencies": {
13
- "@memberjunction/core": "4.2.0",
14
- "@memberjunction/global": "4.2.0",
15
+ "@memberjunction/core": "4.3.0",
16
+ "@memberjunction/global": "4.3.0",
15
17
  "isolated-vm": "^6.0.2",
16
18
  "lodash": "^4.17.23",
17
19
  "date-fns": "^3.0.0",
@@ -26,7 +28,8 @@
26
28
  "@types/papaparse": "^5.5.2",
27
29
  "@types/uuid": "^11.0.0",
28
30
  "@types/validator": "^13.15.10",
29
- "typescript": "^5.9.3"
31
+ "typescript": "^5.9.3",
32
+ "vitest": "^4.0.18"
30
33
  },
31
34
  "keywords": [
32
35
  "memberjunction",
@@ -0,0 +1,241 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { CodeExecutionService } from '../CodeExecutionService';
3
+ import { CodeExecutionParams, CodeExecutionResult } from '../types';
4
+ import { WorkerPool } from '../WorkerPool';
5
+
6
+ // Mock the WorkerPool to avoid actually forking child processes
7
+ vi.mock('../WorkerPool', () => {
8
+ const MockWorkerPool = vi.fn().mockImplementation(function () {
9
+ return {
10
+ initialize: vi.fn().mockResolvedValue(undefined),
11
+ execute: vi.fn().mockResolvedValue({
12
+ success: true,
13
+ output: 'test output',
14
+ executionTimeMs: 10
15
+ }),
16
+ getStats: vi.fn().mockReturnValue({
17
+ totalWorkers: 2,
18
+ activeWorkers: 2,
19
+ busyWorkers: 0,
20
+ queueLength: 0
21
+ }),
22
+ shutdown: vi.fn().mockResolvedValue(undefined)
23
+ };
24
+ });
25
+
26
+ return {
27
+ WorkerPool: MockWorkerPool
28
+ };
29
+ });
30
+
31
+ describe('CodeExecutionService', () => {
32
+ let service: CodeExecutionService;
33
+ let mockPoolInstance: ReturnType<typeof getMockPool>;
34
+
35
+ function getMockPool() {
36
+ // Access the mocked pool instance through the service
37
+ const pool = (service as Record<string, unknown>)['workerPool'] as {
38
+ initialize: ReturnType<typeof vi.fn>;
39
+ execute: ReturnType<typeof vi.fn>;
40
+ getStats: ReturnType<typeof vi.fn>;
41
+ shutdown: ReturnType<typeof vi.fn>;
42
+ };
43
+ return pool;
44
+ }
45
+
46
+ beforeEach(() => {
47
+ vi.clearAllMocks();
48
+ service = new CodeExecutionService();
49
+ mockPoolInstance = getMockPool();
50
+ });
51
+
52
+ describe('constructor', () => {
53
+ it('should create a service with default options', () => {
54
+ const svc = new CodeExecutionService();
55
+ expect(svc).toBeDefined();
56
+ expect(WorkerPool).toHaveBeenCalledWith({});
57
+ });
58
+
59
+ it('should pass options to WorkerPool', () => {
60
+ const options = { poolSize: 4, maxQueueSize: 50 };
61
+ const svc = new CodeExecutionService(options);
62
+ expect(svc).toBeDefined();
63
+ expect(WorkerPool).toHaveBeenCalledWith(options);
64
+ });
65
+
66
+ it('should not be initialized on construction', () => {
67
+ const svc = new CodeExecutionService();
68
+ const initialized = (svc as Record<string, unknown>)['initialized'];
69
+ expect(initialized).toBe(false);
70
+ });
71
+ });
72
+
73
+ describe('initialize', () => {
74
+ it('should initialize the worker pool', async () => {
75
+ await service.initialize();
76
+ expect(mockPoolInstance.initialize).toHaveBeenCalledOnce();
77
+ });
78
+
79
+ it('should set initialized flag to true', async () => {
80
+ await service.initialize();
81
+ const initialized = (service as Record<string, unknown>)['initialized'];
82
+ expect(initialized).toBe(true);
83
+ });
84
+
85
+ it('should not initialize twice on repeated calls', async () => {
86
+ await service.initialize();
87
+ await service.initialize();
88
+ expect(mockPoolInstance.initialize).toHaveBeenCalledOnce();
89
+ });
90
+ });
91
+
92
+ describe('execute', () => {
93
+ it('should auto-initialize if not already initialized', async () => {
94
+ const params: CodeExecutionParams = {
95
+ code: 'output = 42;',
96
+ language: 'javascript'
97
+ };
98
+
99
+ await service.execute(params);
100
+ expect(mockPoolInstance.initialize).toHaveBeenCalledOnce();
101
+ });
102
+
103
+ it('should not re-initialize on second execute call', async () => {
104
+ const params: CodeExecutionParams = {
105
+ code: 'output = 42;',
106
+ language: 'javascript'
107
+ };
108
+
109
+ await service.execute(params);
110
+ await service.execute(params);
111
+ expect(mockPoolInstance.initialize).toHaveBeenCalledOnce();
112
+ });
113
+
114
+ it('should return error for empty code', async () => {
115
+ const params: CodeExecutionParams = {
116
+ code: '',
117
+ language: 'javascript'
118
+ };
119
+
120
+ const result = await service.execute(params);
121
+
122
+ expect(result.success).toBe(false);
123
+ expect(result.error).toContain('Code parameter is required');
124
+ expect(result.errorType).toBe('RUNTIME_ERROR');
125
+ });
126
+
127
+ it('should return error for non-string code', async () => {
128
+ const params = {
129
+ code: null,
130
+ language: 'javascript'
131
+ } as unknown as CodeExecutionParams;
132
+
133
+ const result = await service.execute(params);
134
+
135
+ expect(result.success).toBe(false);
136
+ expect(result.error).toContain('Code parameter is required');
137
+ });
138
+
139
+ it('should return error for unsupported language', async () => {
140
+ const params = {
141
+ code: 'print("hello")',
142
+ language: 'python'
143
+ } as unknown as CodeExecutionParams;
144
+
145
+ const result = await service.execute(params);
146
+
147
+ expect(result.success).toBe(false);
148
+ expect(result.error).toContain('Unsupported language');
149
+ expect(result.error).toContain('python');
150
+ expect(result.errorType).toBe('RUNTIME_ERROR');
151
+ });
152
+
153
+ it('should delegate valid requests to worker pool', async () => {
154
+ const params: CodeExecutionParams = {
155
+ code: 'output = 42;',
156
+ language: 'javascript'
157
+ };
158
+
159
+ const result = await service.execute(params);
160
+
161
+ expect(mockPoolInstance.execute).toHaveBeenCalledWith(params);
162
+ expect(result.success).toBe(true);
163
+ expect(result.output).toBe('test output');
164
+ });
165
+
166
+ it('should pass input data to worker pool', async () => {
167
+ const params: CodeExecutionParams = {
168
+ code: 'output = input.name;',
169
+ language: 'javascript',
170
+ inputData: { name: 'test' }
171
+ };
172
+
173
+ await service.execute(params);
174
+ expect(mockPoolInstance.execute).toHaveBeenCalledWith(params);
175
+ });
176
+
177
+ it('should pass timeout and memory limit to worker pool', async () => {
178
+ const params: CodeExecutionParams = {
179
+ code: 'output = 1;',
180
+ language: 'javascript',
181
+ timeoutSeconds: 10,
182
+ memoryLimitMB: 64
183
+ };
184
+
185
+ await service.execute(params);
186
+ expect(mockPoolInstance.execute).toHaveBeenCalledWith(params);
187
+ });
188
+
189
+ it('should not call execute on worker pool for invalid params', async () => {
190
+ const params: CodeExecutionParams = {
191
+ code: '',
192
+ language: 'javascript'
193
+ };
194
+
195
+ await service.execute(params);
196
+ expect(mockPoolInstance.execute).not.toHaveBeenCalled();
197
+ });
198
+ });
199
+
200
+ describe('getStats', () => {
201
+ it('should delegate to worker pool getStats', () => {
202
+ const stats = service.getStats();
203
+
204
+ expect(mockPoolInstance.getStats).toHaveBeenCalledOnce();
205
+ expect(stats.totalWorkers).toBe(2);
206
+ expect(stats.activeWorkers).toBe(2);
207
+ expect(stats.busyWorkers).toBe(0);
208
+ expect(stats.queueLength).toBe(0);
209
+ });
210
+ });
211
+
212
+ describe('shutdown', () => {
213
+ it('should shut down the worker pool when initialized', async () => {
214
+ await service.initialize();
215
+ await service.shutdown();
216
+
217
+ expect(mockPoolInstance.shutdown).toHaveBeenCalledOnce();
218
+ });
219
+
220
+ it('should set initialized to false after shutdown', async () => {
221
+ await service.initialize();
222
+ await service.shutdown();
223
+
224
+ const initialized = (service as Record<string, unknown>)['initialized'];
225
+ expect(initialized).toBe(false);
226
+ });
227
+
228
+ it('should not shut down if never initialized', async () => {
229
+ await service.shutdown();
230
+ expect(mockPoolInstance.shutdown).not.toHaveBeenCalled();
231
+ });
232
+
233
+ it('should allow re-initialization after shutdown', async () => {
234
+ await service.initialize();
235
+ await service.shutdown();
236
+ await service.initialize();
237
+
238
+ expect(mockPoolInstance.initialize).toHaveBeenCalledTimes(2);
239
+ });
240
+ });
241
+ });
@@ -0,0 +1,365 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { WorkerPool, WorkerPoolOptions } from '../WorkerPool';
3
+ import { CodeExecutionParams } from '../types';
4
+ import { EventEmitter } from 'events';
5
+
6
+ // Mock @memberjunction/core
7
+ vi.mock('@memberjunction/core', () => ({
8
+ LogError: vi.fn(),
9
+ LogStatus: vi.fn()
10
+ }));
11
+
12
+ // Create a mock ChildProcess class that extends EventEmitter
13
+ class MockChildProcess extends EventEmitter {
14
+ killed = false;
15
+ pid = Math.floor(Math.random() * 10000);
16
+
17
+ send = vi.fn().mockReturnValue(true);
18
+ kill = vi.fn().mockImplementation((signal?: string) => {
19
+ this.killed = true;
20
+ // Simulate async exit
21
+ setImmediate(() => this.emit('exit', signal === 'SIGKILL' ? 1 : 0, signal || 'SIGTERM'));
22
+ });
23
+
24
+ // Simulate sending ready message after creation
25
+ simulateReady() {
26
+ setImmediate(() => this.emit('message', { type: 'ready' }));
27
+ }
28
+
29
+ // Simulate sending a result message
30
+ simulateResult(result: Record<string, unknown>) {
31
+ this.emit('message', { type: 'result', result });
32
+ }
33
+
34
+ // Simulate sending an error message
35
+ simulateError(error: string) {
36
+ this.emit('message', { type: 'error', error });
37
+ }
38
+
39
+ // Simulate crash (exit with non-zero)
40
+ simulateCrash(code = 1, signal: string | null = null) {
41
+ this.emit('exit', code, signal);
42
+ }
43
+ }
44
+
45
+ // Mock child_process.fork
46
+ vi.mock('child_process', () => ({
47
+ fork: vi.fn()
48
+ }));
49
+
50
+ import { fork } from 'child_process';
51
+
52
+ const mockedFork = vi.mocked(fork);
53
+
54
+ describe('WorkerPool', () => {
55
+ let pool: WorkerPool;
56
+ let mockProcesses: MockChildProcess[];
57
+
58
+ beforeEach(() => {
59
+ vi.clearAllMocks();
60
+ mockProcesses = [];
61
+
62
+ // Set up fork to create mock child processes that auto-send ready
63
+ mockedFork.mockImplementation(() => {
64
+ const proc = new MockChildProcess();
65
+ mockProcesses.push(proc);
66
+ proc.simulateReady();
67
+ return proc as unknown as ReturnType<typeof fork>;
68
+ });
69
+ });
70
+
71
+ afterEach(async () => {
72
+ // Clean up any active pools
73
+ if (pool) {
74
+ try {
75
+ await pool.shutdown();
76
+ } catch {
77
+ // Ignore shutdown errors in cleanup
78
+ }
79
+ }
80
+ });
81
+
82
+ describe('constructor', () => {
83
+ it('should accept default options', () => {
84
+ pool = new WorkerPool();
85
+ expect(pool).toBeDefined();
86
+ });
87
+
88
+ it('should accept custom pool size', () => {
89
+ pool = new WorkerPool({ poolSize: 4 });
90
+ expect(pool).toBeDefined();
91
+ });
92
+
93
+ it('should accept all configuration options', () => {
94
+ const options: WorkerPoolOptions = {
95
+ poolSize: 3,
96
+ maxCrashesPerWorker: 5,
97
+ crashTimeWindow: 120000,
98
+ maxQueueSize: 200
99
+ };
100
+ pool = new WorkerPool(options);
101
+ expect(pool).toBeDefined();
102
+ });
103
+ });
104
+
105
+ describe('initialize', () => {
106
+ it('should create the expected number of worker processes', async () => {
107
+ pool = new WorkerPool({ poolSize: 3 });
108
+ await pool.initialize();
109
+
110
+ expect(mockedFork).toHaveBeenCalledTimes(3);
111
+ });
112
+
113
+ it('should create 2 workers by default', async () => {
114
+ pool = new WorkerPool();
115
+ await pool.initialize();
116
+
117
+ expect(mockedFork).toHaveBeenCalledTimes(2);
118
+ });
119
+
120
+ it('should fork worker.js file', async () => {
121
+ pool = new WorkerPool({ poolSize: 1 });
122
+ await pool.initialize();
123
+
124
+ expect(mockedFork).toHaveBeenCalledWith(
125
+ expect.stringContaining('worker.js'),
126
+ [],
127
+ expect.objectContaining({
128
+ stdio: ['ignore', 'inherit', 'inherit', 'ipc']
129
+ })
130
+ );
131
+ });
132
+
133
+ it('should wait for ready message from each worker', async () => {
134
+ pool = new WorkerPool({ poolSize: 2 });
135
+ await pool.initialize();
136
+
137
+ // If we got here without hanging, workers sent ready messages
138
+ expect(mockProcesses).toHaveLength(2);
139
+ });
140
+ });
141
+
142
+ describe('execute', () => {
143
+ beforeEach(async () => {
144
+ pool = new WorkerPool({ poolSize: 2 });
145
+ await pool.initialize();
146
+ });
147
+
148
+ it('should send execute message to an available worker', async () => {
149
+ const params: CodeExecutionParams = {
150
+ code: 'output = 42;',
151
+ language: 'javascript'
152
+ };
153
+
154
+ // Set up to resolve when the worker sends back a result
155
+ const executePromise = pool.execute(params);
156
+
157
+ // Find the worker that received the message
158
+ const calledProc = mockProcesses.find(p => p.send.mock.calls.length > 0);
159
+ expect(calledProc).toBeDefined();
160
+
161
+ // Verify the sent message
162
+ const sentMessage = calledProc!.send.mock.calls[0][0] as Record<string, unknown>;
163
+ expect(sentMessage.type).toBe('execute');
164
+ expect(sentMessage.params).toEqual(params);
165
+
166
+ // Simulate the result coming back
167
+ calledProc!.simulateResult({ success: true, output: 42 });
168
+
169
+ const result = await executePromise;
170
+ expect(result).toEqual({ success: true, output: 42 });
171
+ });
172
+
173
+ it('should return error when pool is shutting down', async () => {
174
+ // Trigger shutdown
175
+ const shutdownPromise = pool.shutdown();
176
+
177
+ const params: CodeExecutionParams = {
178
+ code: 'output = 1;',
179
+ language: 'javascript'
180
+ };
181
+
182
+ const result = await pool.execute(params);
183
+
184
+ expect(result.success).toBe(false);
185
+ expect(result.error).toContain('shutting down');
186
+ expect(result.errorType).toBe('RUNTIME_ERROR');
187
+
188
+ await shutdownPromise;
189
+ });
190
+
191
+ it('should return error when queue is full', async () => {
192
+ pool = new WorkerPool({ poolSize: 1, maxQueueSize: 1 });
193
+ await pool.initialize();
194
+
195
+ // Make the single worker busy
196
+ const params1: CodeExecutionParams = { code: 'output = 1;', language: 'javascript' };
197
+ pool.execute(params1).catch(() => { /* will be rejected on shutdown */ }); // First request takes the worker
198
+
199
+ // Second request should be queued
200
+ const params2: CodeExecutionParams = { code: 'output = 2;', language: 'javascript' };
201
+ pool.execute(params2).catch(() => { /* will be resolved/rejected on shutdown */ }); // Fills the queue
202
+
203
+ // Third request should fail because queue is full
204
+ const params3: CodeExecutionParams = { code: 'output = 3;', language: 'javascript' };
205
+ const result = await pool.execute(params3);
206
+
207
+ expect(result.success).toBe(false);
208
+ expect(result.error).toContain('queue is full');
209
+ expect(result.errorType).toBe('RUNTIME_ERROR');
210
+ });
211
+
212
+ it('should use default timeout of 30 seconds with 5s buffer', async () => {
213
+ const params: CodeExecutionParams = {
214
+ code: 'output = 1;',
215
+ language: 'javascript'
216
+ // No timeoutSeconds specified -> defaults to 30
217
+ };
218
+
219
+ const executePromise = pool.execute(params);
220
+
221
+ // Resolve immediately to avoid waiting for actual timeout
222
+ const calledProc = mockProcesses.find(p => p.send.mock.calls.length > 0);
223
+ calledProc!.simulateResult({ success: true, output: 1 });
224
+
225
+ const result = await executePromise;
226
+ expect(result.success).toBe(true);
227
+ });
228
+
229
+ it('should pass custom timeout to request', async () => {
230
+ const params: CodeExecutionParams = {
231
+ code: 'output = 1;',
232
+ language: 'javascript',
233
+ timeoutSeconds: 10
234
+ };
235
+
236
+ const executePromise = pool.execute(params);
237
+
238
+ const calledProc = mockProcesses.find(p => p.send.mock.calls.length > 0);
239
+ calledProc!.simulateResult({ success: true, output: 1 });
240
+
241
+ const result = await executePromise;
242
+ expect(result.success).toBe(true);
243
+ });
244
+ });
245
+
246
+ describe('getStats', () => {
247
+ it('should report correct stats before initialization', () => {
248
+ pool = new WorkerPool({ poolSize: 3 });
249
+ const stats = pool.getStats();
250
+
251
+ expect(stats.totalWorkers).toBe(3);
252
+ expect(stats.activeWorkers).toBe(0);
253
+ expect(stats.busyWorkers).toBe(0);
254
+ expect(stats.queueLength).toBe(0);
255
+ });
256
+
257
+ it('should report correct stats after initialization', async () => {
258
+ pool = new WorkerPool({ poolSize: 2 });
259
+ await pool.initialize();
260
+
261
+ const stats = pool.getStats();
262
+
263
+ expect(stats.totalWorkers).toBe(2);
264
+ expect(stats.activeWorkers).toBe(2);
265
+ expect(stats.busyWorkers).toBe(0);
266
+ expect(stats.queueLength).toBe(0);
267
+ });
268
+
269
+ it('should report busy workers correctly', async () => {
270
+ pool = new WorkerPool({ poolSize: 2 });
271
+ await pool.initialize();
272
+
273
+ // Start an execution without resolving it
274
+ const params: CodeExecutionParams = {
275
+ code: 'output = 1;',
276
+ language: 'javascript'
277
+ };
278
+ pool.execute(params).catch(() => { /* will be rejected on shutdown */ }); // Don't await - leave worker busy
279
+
280
+ const stats = pool.getStats();
281
+ expect(stats.busyWorkers).toBe(1);
282
+ });
283
+ });
284
+
285
+ describe('shutdown', () => {
286
+ it('should reject queued requests on shutdown', async () => {
287
+ pool = new WorkerPool({ poolSize: 1 });
288
+ await pool.initialize();
289
+
290
+ // Make worker busy
291
+ const params1: CodeExecutionParams = { code: 'output = 1;', language: 'javascript' };
292
+ pool.execute(params1).catch(() => { /* will be rejected when worker crashes during shutdown */ });
293
+
294
+ // Queue another request
295
+ const params2: CodeExecutionParams = { code: 'output = 2;', language: 'javascript' };
296
+ const queuedPromise = pool.execute(params2);
297
+
298
+ // Shutdown
299
+ await pool.shutdown();
300
+
301
+ // The queued request should have been resolved with error
302
+ const result = await queuedPromise;
303
+ expect(result.success).toBe(false);
304
+ expect(result.error).toContain('shutting down');
305
+ });
306
+
307
+ it('should kill all worker processes', async () => {
308
+ pool = new WorkerPool({ poolSize: 2 });
309
+ await pool.initialize();
310
+
311
+ await pool.shutdown();
312
+
313
+ for (const proc of mockProcesses) {
314
+ expect(proc.kill).toHaveBeenCalled();
315
+ }
316
+ });
317
+
318
+ it('should handle workers that are already killed', async () => {
319
+ pool = new WorkerPool({ poolSize: 1 });
320
+ await pool.initialize();
321
+
322
+ // Pre-kill the worker
323
+ mockProcesses[0].killed = true;
324
+
325
+ // Should not throw
326
+ await expect(pool.shutdown()).resolves.not.toThrow();
327
+ });
328
+ });
329
+
330
+ describe('worker crash handling', () => {
331
+ it('should handle worker crash during execution', async () => {
332
+ pool = new WorkerPool({ poolSize: 1, maxCrashesPerWorker: 3 });
333
+ await pool.initialize();
334
+
335
+ const params: CodeExecutionParams = {
336
+ code: 'while(true) {}',
337
+ language: 'javascript'
338
+ };
339
+
340
+ const executePromise = pool.execute(params);
341
+
342
+ // Simulate the worker crashing
343
+ mockProcesses[0].simulateCrash(1, 'SIGSEGV');
344
+
345
+ // The promise should reject because the worker crashed
346
+ await expect(executePromise).rejects.toThrow('Worker process crashed');
347
+ });
348
+
349
+ it('should attempt to restart crashed workers', async () => {
350
+ pool = new WorkerPool({ poolSize: 1, maxCrashesPerWorker: 5 });
351
+ await pool.initialize();
352
+
353
+ const initialForkCount = mockedFork.mock.calls.length;
354
+
355
+ // Simulate crash (not during execution)
356
+ mockProcesses[0].simulateCrash(1, null);
357
+
358
+ // Wait for restart attempt
359
+ await new Promise(resolve => setTimeout(resolve, 50));
360
+
361
+ // Should have tried to create a new worker
362
+ expect(mockedFork.mock.calls.length).toBeGreaterThan(initialForkCount);
363
+ });
364
+ });
365
+ });
@@ -0,0 +1,207 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { ALLOWED_MODULES, isModuleAllowed, getAllowedModuleNames, getLibrarySource } from '../libraries';
3
+
4
+ // Mock fs for bundled library loading
5
+ vi.mock('fs', () => ({
6
+ default: {
7
+ readFileSync: vi.fn().mockReturnValue('var math = {}; var Papa = {}; var jStat = {};')
8
+ }
9
+ }));
10
+
11
+ // Mock url module for ESM __dirname workaround
12
+ vi.mock('url', () => ({
13
+ fileURLToPath: vi.fn().mockReturnValue('/fake/path/libraries/index.ts')
14
+ }));
15
+
16
+ describe('Libraries', () => {
17
+ describe('ALLOWED_MODULES', () => {
18
+ it('should contain all expected modules', () => {
19
+ expect(ALLOWED_MODULES).toContain('lodash');
20
+ expect(ALLOWED_MODULES).toContain('date-fns');
21
+ expect(ALLOWED_MODULES).toContain('mathjs');
22
+ expect(ALLOWED_MODULES).toContain('papaparse');
23
+ expect(ALLOWED_MODULES).toContain('jstat');
24
+ expect(ALLOWED_MODULES).toContain('uuid');
25
+ expect(ALLOWED_MODULES).toContain('validator');
26
+ });
27
+
28
+ it('should have exactly 7 allowed modules', () => {
29
+ expect(ALLOWED_MODULES).toHaveLength(7);
30
+ });
31
+
32
+ it('should be a readonly tuple', () => {
33
+ // The array should not contain any dangerous modules
34
+ const dangerousModules = ['fs', 'path', 'http', 'https', 'net', 'child_process', 'os', 'process'];
35
+ for (const mod of dangerousModules) {
36
+ expect(ALLOWED_MODULES).not.toContain(mod);
37
+ }
38
+ });
39
+ });
40
+
41
+ describe('isModuleAllowed', () => {
42
+ it('should return true for all allowed modules', () => {
43
+ for (const mod of ALLOWED_MODULES) {
44
+ expect(isModuleAllowed(mod)).toBe(true);
45
+ }
46
+ });
47
+
48
+ it('should return false for blocked modules', () => {
49
+ expect(isModuleAllowed('fs')).toBe(false);
50
+ expect(isModuleAllowed('http')).toBe(false);
51
+ expect(isModuleAllowed('child_process')).toBe(false);
52
+ expect(isModuleAllowed('net')).toBe(false);
53
+ expect(isModuleAllowed('os')).toBe(false);
54
+ expect(isModuleAllowed('process')).toBe(false);
55
+ });
56
+
57
+ it('should return false for arbitrary module names', () => {
58
+ expect(isModuleAllowed('express')).toBe(false);
59
+ expect(isModuleAllowed('axios')).toBe(false);
60
+ expect(isModuleAllowed('shell')).toBe(false);
61
+ });
62
+
63
+ it('should return false for empty string', () => {
64
+ expect(isModuleAllowed('')).toBe(false);
65
+ });
66
+
67
+ it('should be case-sensitive', () => {
68
+ expect(isModuleAllowed('Lodash')).toBe(false);
69
+ expect(isModuleAllowed('LODASH')).toBe(false);
70
+ expect(isModuleAllowed('UUID')).toBe(false);
71
+ });
72
+
73
+ it('should act as a type guard', () => {
74
+ const moduleName: string = 'lodash';
75
+ if (isModuleAllowed(moduleName)) {
76
+ // Inside this block, moduleName should be typed as AllowedModule
77
+ const allowed: typeof ALLOWED_MODULES[number] = moduleName;
78
+ expect(allowed).toBe('lodash');
79
+ }
80
+ });
81
+ });
82
+
83
+ describe('getAllowedModuleNames', () => {
84
+ it('should return an array of all allowed module names', () => {
85
+ const names = getAllowedModuleNames();
86
+ expect(names).toHaveLength(7);
87
+ expect(names).toContain('lodash');
88
+ expect(names).toContain('date-fns');
89
+ expect(names).toContain('uuid');
90
+ expect(names).toContain('validator');
91
+ });
92
+
93
+ it('should return a copy, not the original array', () => {
94
+ const names1 = getAllowedModuleNames();
95
+ const names2 = getAllowedModuleNames();
96
+ expect(names1).not.toBe(names2);
97
+ expect(names1).toEqual(names2);
98
+ });
99
+
100
+ it('should return string array', () => {
101
+ const names = getAllowedModuleNames();
102
+ for (const name of names) {
103
+ expect(typeof name).toBe('string');
104
+ }
105
+ });
106
+ });
107
+
108
+ describe('getLibrarySource', () => {
109
+ it('should return null for non-allowed modules', () => {
110
+ expect(getLibrarySource('fs')).toBeNull();
111
+ expect(getLibrarySource('http')).toBeNull();
112
+ expect(getLibrarySource('nonexistent')).toBeNull();
113
+ });
114
+
115
+ it('should return a string for lodash', () => {
116
+ const source = getLibrarySource('lodash');
117
+ expect(source).not.toBeNull();
118
+ expect(typeof source).toBe('string');
119
+ });
120
+
121
+ it('should return lodash source with expected functions', () => {
122
+ const source = getLibrarySource('lodash')!;
123
+ expect(source).toContain('chunk');
124
+ expect(source).toContain('compact');
125
+ expect(source).toContain('flatten');
126
+ expect(source).toContain('uniq');
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');
137
+ });
138
+
139
+ it('should return date-fns source with expected functions', () => {
140
+ const source = getLibrarySource('date-fns')!;
141
+ expect(source).not.toBeNull();
142
+ expect(source).toContain('format');
143
+ expect(source).toContain('addDays');
144
+ expect(source).toContain('subDays');
145
+ expect(source).toContain('addMonths');
146
+ expect(source).toContain('differenceInDays');
147
+ expect(source).toContain('isAfter');
148
+ expect(source).toContain('isBefore');
149
+ expect(source).toContain('startOfDay');
150
+ expect(source).toContain('endOfDay');
151
+ expect(source).toContain('parseISO');
152
+ });
153
+
154
+ it('should return uuid source with v4 function', () => {
155
+ const source = getLibrarySource('uuid')!;
156
+ expect(source).not.toBeNull();
157
+ expect(source).toContain('v4');
158
+ expect(source).toContain('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');
159
+ });
160
+
161
+ it('should return validator source with validation functions', () => {
162
+ const source = getLibrarySource('validator')!;
163
+ expect(source).not.toBeNull();
164
+ expect(source).toContain('isEmail');
165
+ expect(source).toContain('isURL');
166
+ expect(source).toContain('isNumeric');
167
+ expect(source).toContain('isAlpha');
168
+ expect(source).toContain('isAlphanumeric');
169
+ expect(source).toContain('isEmpty');
170
+ expect(source).toContain('isLength');
171
+ expect(source).toContain('matches');
172
+ });
173
+
174
+ it('should return wrapped IIFE for inline libraries', () => {
175
+ const lodashSource = getLibrarySource('lodash')!;
176
+ // Should be wrapped in an IIFE that returns the object
177
+ expect(lodashSource).toMatch(/^\(function\(\)/);
178
+ expect(lodashSource).toContain('return _');
179
+
180
+ const dateFnsSource = getLibrarySource('date-fns')!;
181
+ expect(dateFnsSource).toMatch(/^\(function\(\)/);
182
+ expect(dateFnsSource).toContain('return dateFns');
183
+ });
184
+
185
+ it('should return wrapped IIFE for bundled mathjs', () => {
186
+ const source = getLibrarySource('mathjs');
187
+ expect(source).not.toBeNull();
188
+ expect(source).toContain('return math');
189
+ });
190
+
191
+ it('should return wrapped IIFE for bundled papaparse', () => {
192
+ const source = getLibrarySource('papaparse');
193
+ expect(source).not.toBeNull();
194
+ expect(source).toContain('return Papa');
195
+ });
196
+
197
+ it('should return wrapped IIFE for bundled jstat', () => {
198
+ const source = getLibrarySource('jstat');
199
+ expect(source).not.toBeNull();
200
+ expect(source).toContain('return jStat');
201
+ });
202
+
203
+ it('should return null for empty string', () => {
204
+ expect(getLibrarySource('')).toBeNull();
205
+ });
206
+ });
207
+ });
@@ -0,0 +1,172 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import type { CodeExecutionParams, CodeExecutionResult, JavaScriptExecutionOptions, SandboxContext } from '../types';
3
+
4
+ /**
5
+ * Type-level tests to verify the shape of exported interfaces.
6
+ * These tests validate that types are properly structured and compile correctly.
7
+ * Since interfaces have no runtime representation, we test by creating conforming objects.
8
+ */
9
+ describe('Types', () => {
10
+ describe('CodeExecutionParams', () => {
11
+ it('should require code and language', () => {
12
+ const params: CodeExecutionParams = {
13
+ code: 'console.log("hello")',
14
+ language: 'javascript'
15
+ };
16
+ expect(params.code).toBe('console.log("hello")');
17
+ expect(params.language).toBe('javascript');
18
+ });
19
+
20
+ it('should allow optional inputData', () => {
21
+ const params: CodeExecutionParams = {
22
+ code: 'output = input.x;',
23
+ language: 'javascript',
24
+ inputData: { x: 42 }
25
+ };
26
+ expect(params.inputData).toEqual({ x: 42 });
27
+ });
28
+
29
+ it('should allow optional timeoutSeconds', () => {
30
+ const params: CodeExecutionParams = {
31
+ code: '',
32
+ language: 'javascript',
33
+ timeoutSeconds: 10
34
+ };
35
+ expect(params.timeoutSeconds).toBe(10);
36
+ });
37
+
38
+ it('should allow optional memoryLimitMB', () => {
39
+ const params: CodeExecutionParams = {
40
+ code: '',
41
+ language: 'javascript',
42
+ memoryLimitMB: 64
43
+ };
44
+ expect(params.memoryLimitMB).toBe(64);
45
+ });
46
+
47
+ it('should allow all optional fields together', () => {
48
+ const params: CodeExecutionParams = {
49
+ code: 'output = input.count * 2;',
50
+ language: 'javascript',
51
+ inputData: { count: 5 },
52
+ timeoutSeconds: 15,
53
+ memoryLimitMB: 256
54
+ };
55
+ expect(params.code).toBeDefined();
56
+ expect(params.inputData).toBeDefined();
57
+ expect(params.timeoutSeconds).toBe(15);
58
+ expect(params.memoryLimitMB).toBe(256);
59
+ });
60
+ });
61
+
62
+ describe('CodeExecutionResult', () => {
63
+ it('should represent a successful result', () => {
64
+ const result: CodeExecutionResult = {
65
+ success: true,
66
+ output: 42,
67
+ logs: ['[LOG] Hello'],
68
+ executionTimeMs: 150
69
+ };
70
+ expect(result.success).toBe(true);
71
+ expect(result.output).toBe(42);
72
+ expect(result.logs).toHaveLength(1);
73
+ });
74
+
75
+ it('should represent a failed result with error', () => {
76
+ const result: CodeExecutionResult = {
77
+ success: false,
78
+ error: 'Something went wrong',
79
+ errorType: 'RUNTIME_ERROR'
80
+ };
81
+ expect(result.success).toBe(false);
82
+ expect(result.error).toBeDefined();
83
+ expect(result.errorType).toBe('RUNTIME_ERROR');
84
+ });
85
+
86
+ it('should support all error types', () => {
87
+ const errorTypes: CodeExecutionResult['errorType'][] = [
88
+ 'TIMEOUT',
89
+ 'MEMORY_LIMIT',
90
+ 'SYNTAX_ERROR',
91
+ 'RUNTIME_ERROR',
92
+ 'SECURITY_ERROR'
93
+ ];
94
+
95
+ for (const errorType of errorTypes) {
96
+ const result: CodeExecutionResult = {
97
+ success: false,
98
+ error: `Error of type ${errorType}`,
99
+ errorType
100
+ };
101
+ expect(result.errorType).toBe(errorType);
102
+ }
103
+ });
104
+
105
+ it('should allow minimal success result', () => {
106
+ const result: CodeExecutionResult = {
107
+ success: true
108
+ };
109
+ expect(result.success).toBe(true);
110
+ expect(result.output).toBeUndefined();
111
+ expect(result.logs).toBeUndefined();
112
+ expect(result.error).toBeUndefined();
113
+ });
114
+
115
+ it('should allow output with various data types', () => {
116
+ const stringResult: CodeExecutionResult = { success: true, output: 'hello' };
117
+ expect(stringResult.output).toBe('hello');
118
+
119
+ const numberResult: CodeExecutionResult = { success: true, output: 3.14 };
120
+ expect(numberResult.output).toBe(3.14);
121
+
122
+ const objectResult: CodeExecutionResult = { success: true, output: { key: 'value' } };
123
+ expect(objectResult.output).toEqual({ key: 'value' });
124
+
125
+ const arrayResult: CodeExecutionResult = { success: true, output: [1, 2, 3] };
126
+ expect(arrayResult.output).toEqual([1, 2, 3]);
127
+
128
+ const nullResult: CodeExecutionResult = { success: true, output: null };
129
+ expect(nullResult.output).toBeNull();
130
+ });
131
+ });
132
+
133
+ describe('JavaScriptExecutionOptions', () => {
134
+ it('should require timeout and memoryLimit', () => {
135
+ const options: JavaScriptExecutionOptions = {
136
+ timeout: 30,
137
+ memoryLimit: 128
138
+ };
139
+ expect(options.timeout).toBe(30);
140
+ expect(options.memoryLimit).toBe(128);
141
+ });
142
+
143
+ it('should allow optional allowedLibraries', () => {
144
+ const options: JavaScriptExecutionOptions = {
145
+ timeout: 30,
146
+ memoryLimit: 128,
147
+ allowedLibraries: ['lodash', 'uuid']
148
+ };
149
+ expect(options.allowedLibraries).toEqual(['lodash', 'uuid']);
150
+ });
151
+ });
152
+
153
+ describe('SandboxContext', () => {
154
+ it('should define input, output, and console', () => {
155
+ const context: SandboxContext = {
156
+ input: { data: [1, 2, 3] },
157
+ output: null,
158
+ console: {
159
+ log: () => {},
160
+ error: () => {},
161
+ warn: () => {},
162
+ info: () => {}
163
+ }
164
+ };
165
+ expect(context.input).toBeDefined();
166
+ expect(context.console.log).toBeDefined();
167
+ expect(context.console.error).toBeDefined();
168
+ expect(context.console.warn).toBeDefined();
169
+ expect(context.console.info).toBeDefined();
170
+ });
171
+ });
172
+ });
package/tsconfig.json CHANGED
@@ -5,5 +5,5 @@
5
5
  "rootDir": "src"
6
6
  },
7
7
  "include": ["src/**/*"],
8
- "exclude": ["node_modules"]
8
+ "exclude": ["node_modules", "src/__tests__"]
9
9
  }
@@ -0,0 +1,3 @@
1
+ import { defineProject, mergeConfig } from 'vitest/config';
2
+ import sharedConfig from '../../../vitest.shared';
3
+ export default mergeConfig(sharedConfig, defineProject({ test: { environment: 'node' } }));