@ricsam/isolate-runtime 0.1.9 → 0.1.11
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/README.md +2 -2
- package/dist/cjs/index.cjs +177 -21
- package/dist/cjs/index.cjs.map +3 -3
- package/dist/cjs/internal.cjs +2 -4
- package/dist/cjs/internal.cjs.map +2 -2
- package/dist/cjs/package.json +1 -1
- package/dist/mjs/index.mjs +179 -19
- package/dist/mjs/index.mjs.map +3 -3
- package/dist/mjs/internal.mjs +1 -2
- package/dist/mjs/internal.mjs.map +2 -2
- package/dist/mjs/package.json +1 -1
- package/dist/types/index.d.ts +8 -45
- package/package.json +1 -1
package/dist/mjs/index.mjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
// @bun
|
|
2
1
|
// packages/runtime/src/index.ts
|
|
3
2
|
import ivm from "isolated-vm";
|
|
4
3
|
import { setupCore } from "@ricsam/isolate-core";
|
|
@@ -16,6 +15,10 @@ import {
|
|
|
16
15
|
getTestCount as getTestCountInContext
|
|
17
16
|
} from "@ricsam/isolate-test-environment";
|
|
18
17
|
import { setupPlaywright } from "@ricsam/isolate-playwright";
|
|
18
|
+
import {
|
|
19
|
+
marshalValue,
|
|
20
|
+
unmarshalValue
|
|
21
|
+
} from "@ricsam/isolate-protocol";
|
|
19
22
|
import { setupCore as setupCore2 } from "@ricsam/isolate-core";
|
|
20
23
|
import { setupConsole as setupConsole2 } from "@ricsam/isolate-console";
|
|
21
24
|
import {
|
|
@@ -41,6 +44,152 @@ import {
|
|
|
41
44
|
export * from "./internal.mjs";
|
|
42
45
|
var iteratorSessions = new Map;
|
|
43
46
|
var nextIteratorId = 1;
|
|
47
|
+
var ISOLATE_MARSHAL_CODE = `
|
|
48
|
+
(function() {
|
|
49
|
+
// Marshal a value (JavaScript → Ref)
|
|
50
|
+
function marshalForHost(value, depth = 0) {
|
|
51
|
+
if (depth > 100) throw new Error('Maximum marshalling depth exceeded');
|
|
52
|
+
|
|
53
|
+
if (value === null) return null;
|
|
54
|
+
if (value === undefined) return { __type: 'UndefinedRef' };
|
|
55
|
+
|
|
56
|
+
const type = typeof value;
|
|
57
|
+
if (type === 'string' || type === 'number' || type === 'boolean') return value;
|
|
58
|
+
if (type === 'bigint') return { __type: 'BigIntRef', value: value.toString() };
|
|
59
|
+
if (type === 'function') throw new Error('Cannot marshal functions from isolate');
|
|
60
|
+
if (type === 'symbol') throw new Error('Cannot marshal Symbol values');
|
|
61
|
+
|
|
62
|
+
if (type === 'object') {
|
|
63
|
+
if (value instanceof Date) {
|
|
64
|
+
return { __type: 'DateRef', timestamp: value.getTime() };
|
|
65
|
+
}
|
|
66
|
+
if (value instanceof RegExp) {
|
|
67
|
+
return { __type: 'RegExpRef', source: value.source, flags: value.flags };
|
|
68
|
+
}
|
|
69
|
+
if (value instanceof URL) {
|
|
70
|
+
return { __type: 'URLRef', href: value.href };
|
|
71
|
+
}
|
|
72
|
+
if (typeof Headers !== 'undefined' && value instanceof Headers) {
|
|
73
|
+
const pairs = [];
|
|
74
|
+
value.forEach((v, k) => pairs.push([k, v]));
|
|
75
|
+
return { __type: 'HeadersRef', pairs };
|
|
76
|
+
}
|
|
77
|
+
if (value instanceof Uint8Array) {
|
|
78
|
+
return { __type: 'Uint8ArrayRef', data: Array.from(value) };
|
|
79
|
+
}
|
|
80
|
+
if (value instanceof ArrayBuffer) {
|
|
81
|
+
return { __type: 'Uint8ArrayRef', data: Array.from(new Uint8Array(value)) };
|
|
82
|
+
}
|
|
83
|
+
if (typeof Request !== 'undefined' && value instanceof Request) {
|
|
84
|
+
throw new Error('Cannot marshal Request from isolate. Use fetch callback instead.');
|
|
85
|
+
}
|
|
86
|
+
if (typeof Response !== 'undefined' && value instanceof Response) {
|
|
87
|
+
throw new Error('Cannot marshal Response from isolate. Return plain objects instead.');
|
|
88
|
+
}
|
|
89
|
+
if (typeof File !== 'undefined' && value instanceof File) {
|
|
90
|
+
throw new Error('Cannot marshal File from isolate.');
|
|
91
|
+
}
|
|
92
|
+
if (typeof Blob !== 'undefined' && value instanceof Blob) {
|
|
93
|
+
throw new Error('Cannot marshal Blob from isolate.');
|
|
94
|
+
}
|
|
95
|
+
if (typeof FormData !== 'undefined' && value instanceof FormData) {
|
|
96
|
+
throw new Error('Cannot marshal FormData from isolate.');
|
|
97
|
+
}
|
|
98
|
+
if (Array.isArray(value)) {
|
|
99
|
+
return value.map(v => marshalForHost(v, depth + 1));
|
|
100
|
+
}
|
|
101
|
+
// Plain object
|
|
102
|
+
const result = {};
|
|
103
|
+
for (const key of Object.keys(value)) {
|
|
104
|
+
result[key] = marshalForHost(value[key], depth + 1);
|
|
105
|
+
}
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Unmarshal a value (Ref → JavaScript)
|
|
112
|
+
function unmarshalFromHost(value, depth = 0) {
|
|
113
|
+
if (depth > 100) throw new Error('Maximum unmarshalling depth exceeded');
|
|
114
|
+
|
|
115
|
+
if (value === null) return null;
|
|
116
|
+
if (typeof value !== 'object') return value;
|
|
117
|
+
|
|
118
|
+
if (value.__type) {
|
|
119
|
+
switch (value.__type) {
|
|
120
|
+
case 'UndefinedRef': return undefined;
|
|
121
|
+
case 'DateRef': return new Date(value.timestamp);
|
|
122
|
+
case 'RegExpRef': return new RegExp(value.source, value.flags);
|
|
123
|
+
case 'BigIntRef': return BigInt(value.value);
|
|
124
|
+
case 'URLRef': return new URL(value.href);
|
|
125
|
+
case 'HeadersRef': return new Headers(value.pairs);
|
|
126
|
+
case 'Uint8ArrayRef': return new Uint8Array(value.data);
|
|
127
|
+
case 'RequestRef': {
|
|
128
|
+
const init = {
|
|
129
|
+
method: value.method,
|
|
130
|
+
headers: value.headers,
|
|
131
|
+
body: value.body ? new Uint8Array(value.body) : null,
|
|
132
|
+
};
|
|
133
|
+
if (value.mode) init.mode = value.mode;
|
|
134
|
+
if (value.credentials) init.credentials = value.credentials;
|
|
135
|
+
if (value.cache) init.cache = value.cache;
|
|
136
|
+
if (value.redirect) init.redirect = value.redirect;
|
|
137
|
+
if (value.referrer) init.referrer = value.referrer;
|
|
138
|
+
if (value.referrerPolicy) init.referrerPolicy = value.referrerPolicy;
|
|
139
|
+
if (value.integrity) init.integrity = value.integrity;
|
|
140
|
+
return new Request(value.url, init);
|
|
141
|
+
}
|
|
142
|
+
case 'ResponseRef': {
|
|
143
|
+
return new Response(value.body ? new Uint8Array(value.body) : null, {
|
|
144
|
+
status: value.status,
|
|
145
|
+
statusText: value.statusText,
|
|
146
|
+
headers: value.headers,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
case 'FileRef': {
|
|
150
|
+
if (!value.name) {
|
|
151
|
+
return new Blob([new Uint8Array(value.data)], { type: value.type });
|
|
152
|
+
}
|
|
153
|
+
return new File([new Uint8Array(value.data)], value.name, {
|
|
154
|
+
type: value.type,
|
|
155
|
+
lastModified: value.lastModified,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
case 'FormDataRef': {
|
|
159
|
+
const fd = new FormData();
|
|
160
|
+
for (const [key, entry] of value.entries) {
|
|
161
|
+
if (typeof entry === 'string') {
|
|
162
|
+
fd.append(key, entry);
|
|
163
|
+
} else {
|
|
164
|
+
const file = unmarshalFromHost(entry, depth + 1);
|
|
165
|
+
fd.append(key, file);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return fd;
|
|
169
|
+
}
|
|
170
|
+
default:
|
|
171
|
+
// Unknown ref type, return as-is
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (Array.isArray(value)) {
|
|
177
|
+
return value.map(v => unmarshalFromHost(v, depth + 1));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Plain object - recursively unmarshal
|
|
181
|
+
const result = {};
|
|
182
|
+
for (const key of Object.keys(value)) {
|
|
183
|
+
result[key] = unmarshalFromHost(value[key], depth + 1);
|
|
184
|
+
}
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Expose as globals
|
|
189
|
+
globalThis.__marshalForHost = marshalForHost;
|
|
190
|
+
globalThis.__unmarshalFromHost = unmarshalFromHost;
|
|
191
|
+
})();
|
|
192
|
+
`;
|
|
44
193
|
async function setupCustomFunctions(context, customFunctions) {
|
|
45
194
|
const global = context.global;
|
|
46
195
|
const invokeCallbackRef = new ivm.Reference(async (name, argsJson) => {
|
|
@@ -54,10 +203,12 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
54
203
|
}
|
|
55
204
|
});
|
|
56
205
|
}
|
|
57
|
-
const
|
|
206
|
+
const rawArgs = JSON.parse(argsJson);
|
|
207
|
+
const args = unmarshalValue(rawArgs);
|
|
58
208
|
try {
|
|
59
209
|
const result = def.type === "async" ? await def.fn(...args) : def.fn(...args);
|
|
60
|
-
|
|
210
|
+
const marshalledResult = await marshalValue(result);
|
|
211
|
+
return JSON.stringify({ ok: true, value: marshalledResult });
|
|
61
212
|
} catch (error) {
|
|
62
213
|
const err = error;
|
|
63
214
|
return JSON.stringify({
|
|
@@ -79,7 +230,8 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
79
230
|
});
|
|
80
231
|
}
|
|
81
232
|
try {
|
|
82
|
-
const
|
|
233
|
+
const rawArgs = JSON.parse(argsJson);
|
|
234
|
+
const args = unmarshalValue(rawArgs);
|
|
83
235
|
const fn = def.fn;
|
|
84
236
|
const iterator = fn(...args);
|
|
85
237
|
const iteratorId = nextIteratorId++;
|
|
@@ -110,10 +262,11 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
110
262
|
if (result.done) {
|
|
111
263
|
iteratorSessions.delete(iteratorId);
|
|
112
264
|
}
|
|
265
|
+
const marshalledValue = await marshalValue(result.value);
|
|
113
266
|
return JSON.stringify({
|
|
114
267
|
ok: true,
|
|
115
268
|
done: result.done,
|
|
116
|
-
value:
|
|
269
|
+
value: marshalledValue
|
|
117
270
|
});
|
|
118
271
|
} catch (error) {
|
|
119
272
|
const err = error;
|
|
@@ -131,10 +284,12 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
131
284
|
return JSON.stringify({ ok: true, done: true, value: undefined });
|
|
132
285
|
}
|
|
133
286
|
try {
|
|
134
|
-
const
|
|
287
|
+
const rawValue = valueJson ? JSON.parse(valueJson) : undefined;
|
|
288
|
+
const value = unmarshalValue(rawValue);
|
|
135
289
|
const result = await session.iterator.return?.(value);
|
|
136
290
|
iteratorSessions.delete(iteratorId);
|
|
137
|
-
|
|
291
|
+
const marshalledValue = await marshalValue(result?.value);
|
|
292
|
+
return JSON.stringify({ ok: true, done: true, value: marshalledValue });
|
|
138
293
|
} catch (error) {
|
|
139
294
|
const err = error;
|
|
140
295
|
iteratorSessions.delete(iteratorId);
|
|
@@ -163,10 +318,11 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
163
318
|
});
|
|
164
319
|
const result = await session.iterator.throw?.(error);
|
|
165
320
|
iteratorSessions.delete(iteratorId);
|
|
321
|
+
const marshalledValue = await marshalValue(result?.value);
|
|
166
322
|
return JSON.stringify({
|
|
167
323
|
ok: true,
|
|
168
324
|
done: result?.done ?? true,
|
|
169
|
-
value:
|
|
325
|
+
value: marshalledValue
|
|
170
326
|
});
|
|
171
327
|
} catch (error) {
|
|
172
328
|
const err = error;
|
|
@@ -178,18 +334,20 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
178
334
|
}
|
|
179
335
|
});
|
|
180
336
|
global.setSync("__iter_throw", iterThrowRef);
|
|
337
|
+
context.evalSync(ISOLATE_MARSHAL_CODE);
|
|
181
338
|
for (const name of Object.keys(customFunctions)) {
|
|
182
339
|
const def = customFunctions[name];
|
|
183
340
|
if (def.type === "async") {
|
|
184
341
|
context.evalSync(`
|
|
185
342
|
globalThis.${name} = async function(...args) {
|
|
343
|
+
const marshalledArgs = __marshalForHost(args);
|
|
186
344
|
const resultJson = __customFn_invoke.applySyncPromise(
|
|
187
345
|
undefined,
|
|
188
|
-
["${name}", JSON.stringify(
|
|
346
|
+
["${name}", JSON.stringify(marshalledArgs)]
|
|
189
347
|
);
|
|
190
348
|
const result = JSON.parse(resultJson);
|
|
191
349
|
if (result.ok) {
|
|
192
|
-
return result.value;
|
|
350
|
+
return __unmarshalFromHost(result.value);
|
|
193
351
|
} else {
|
|
194
352
|
const error = new Error(result.error.message);
|
|
195
353
|
error.name = result.error.name;
|
|
@@ -200,13 +358,14 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
200
358
|
} else if (def.type === "sync") {
|
|
201
359
|
context.evalSync(`
|
|
202
360
|
globalThis.${name} = function(...args) {
|
|
361
|
+
const marshalledArgs = __marshalForHost(args);
|
|
203
362
|
const resultJson = __customFn_invoke.applySyncPromise(
|
|
204
363
|
undefined,
|
|
205
|
-
["${name}", JSON.stringify(
|
|
364
|
+
["${name}", JSON.stringify(marshalledArgs)]
|
|
206
365
|
);
|
|
207
366
|
const result = JSON.parse(resultJson);
|
|
208
367
|
if (result.ok) {
|
|
209
|
-
return result.value;
|
|
368
|
+
return __unmarshalFromHost(result.value);
|
|
210
369
|
} else {
|
|
211
370
|
const error = new Error(result.error.message);
|
|
212
371
|
error.name = result.error.name;
|
|
@@ -217,7 +376,8 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
217
376
|
} else if (def.type === "asyncIterator") {
|
|
218
377
|
context.evalSync(`
|
|
219
378
|
globalThis.${name} = function(...args) {
|
|
220
|
-
const
|
|
379
|
+
const marshalledArgs = __marshalForHost(args);
|
|
380
|
+
const startResult = JSON.parse(__iter_start.applySyncPromise(undefined, ["${name}", JSON.stringify(marshalledArgs)]));
|
|
221
381
|
if (!startResult.ok) {
|
|
222
382
|
throw Object.assign(new Error(startResult.error.message), { name: startResult.error.name });
|
|
223
383
|
}
|
|
@@ -229,18 +389,18 @@ async function setupCustomFunctions(context, customFunctions) {
|
|
|
229
389
|
if (!result.ok) {
|
|
230
390
|
throw Object.assign(new Error(result.error.message), { name: result.error.name });
|
|
231
391
|
}
|
|
232
|
-
return { done: result.done, value: result.value };
|
|
392
|
+
return { done: result.done, value: __unmarshalFromHost(result.value) };
|
|
233
393
|
},
|
|
234
394
|
async return(v) {
|
|
235
|
-
const result = JSON.parse(__iter_return.applySyncPromise(undefined, [iteratorId, JSON.stringify(v)]));
|
|
236
|
-
return { done: true, value: result.value };
|
|
395
|
+
const result = JSON.parse(__iter_return.applySyncPromise(undefined, [iteratorId, JSON.stringify(__marshalForHost(v))]));
|
|
396
|
+
return { done: true, value: __unmarshalFromHost(result.value) };
|
|
237
397
|
},
|
|
238
398
|
async throw(e) {
|
|
239
399
|
const result = JSON.parse(__iter_throw.applySyncPromise(undefined, [iteratorId, JSON.stringify({ message: e.message, name: e.name })]));
|
|
240
400
|
if (!result.ok) {
|
|
241
401
|
throw Object.assign(new Error(result.error.message), { name: result.error.name });
|
|
242
402
|
}
|
|
243
|
-
return { done: result.done, value: result.value };
|
|
403
|
+
return { done: result.done, value: __unmarshalFromHost(result.value) };
|
|
244
404
|
}
|
|
245
405
|
};
|
|
246
406
|
};
|
|
@@ -322,7 +482,7 @@ async function createRuntime(options) {
|
|
|
322
482
|
consoleHandler({
|
|
323
483
|
type: "browserOutput",
|
|
324
484
|
level: event.level,
|
|
325
|
-
|
|
485
|
+
stdout: event.stdout,
|
|
326
486
|
timestamp: event.timestamp
|
|
327
487
|
});
|
|
328
488
|
}
|
|
@@ -505,4 +665,4 @@ export {
|
|
|
505
665
|
createNodeFileSystemHandler
|
|
506
666
|
};
|
|
507
667
|
|
|
508
|
-
//# debugId=
|
|
668
|
+
//# debugId=8F7A91864B6F594B64756E2164756E21
|
package/dist/mjs/index.mjs.map
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import ivm from \"isolated-vm\";\nimport { setupCore } from \"@ricsam/isolate-core\";\nimport { setupConsole } from \"@ricsam/isolate-console\";\nimport { setupEncoding } from \"@ricsam/isolate-encoding\";\nimport { setupTimers } from \"@ricsam/isolate-timers\";\nimport { setupPath } from \"@ricsam/isolate-path\";\nimport { setupCrypto } from \"@ricsam/isolate-crypto\";\nimport { setupFetch } from \"@ricsam/isolate-fetch\";\nimport { setupFs } from \"@ricsam/isolate-fs\";\nimport {\n setupTestEnvironment,\n runTests as runTestsInContext,\n hasTests as hasTestsInContext,\n getTestCount as getTestCountInContext,\n} from \"@ricsam/isolate-test-environment\";\nimport { setupPlaywright } from \"@ricsam/isolate-playwright\";\n\nimport type { ConsoleOptions, ConsoleHandle } from \"@ricsam/isolate-console\";\nimport type {\n FetchOptions,\n FetchHandle,\n DispatchRequestOptions,\n UpgradeRequest,\n WebSocketCommand,\n} from \"@ricsam/isolate-fetch\";\nimport type { FsOptions, FsHandle } from \"@ricsam/isolate-fs\";\nimport type { CoreHandle } from \"@ricsam/isolate-core\";\nimport type { EncodingHandle } from \"@ricsam/isolate-encoding\";\nimport type { TimersHandle } from \"@ricsam/isolate-timers\";\nimport type { PathHandle } from \"@ricsam/isolate-path\";\nimport type { CryptoHandle } from \"@ricsam/isolate-crypto\";\nimport type {\n TestEnvironmentHandle,\n RunResults,\n TestEnvironmentOptions,\n TestEvent,\n SuiteInfo,\n SuiteResult,\n TestInfo,\n TestResult,\n TestError,\n} from \"@ricsam/isolate-test-environment\";\nimport type {\n PlaywrightHandle,\n NetworkRequestInfo,\n NetworkResponseInfo,\n BrowserConsoleLogEntry,\n PlaywrightEvent,\n} from \"@ricsam/isolate-playwright\";\nimport type {\n ConsoleCallbacks,\n ConsoleEntry,\n FetchCallback,\n ModuleLoaderCallback,\n CustomFunctionDefinition,\n CustomFunctions,\n CustomAsyncGeneratorFunction,\n DispatchOptions,\n} from \"@ricsam/isolate-protocol\";\n\n// Re-export shared types from protocol\nexport type {\n ConsoleCallbacks,\n ConsoleEntry,\n FetchCallback,\n ModuleLoaderCallback,\n CustomFunction,\n CustomFunctionDefinition,\n CustomFunctions,\n DispatchOptions,\n} from \"@ricsam/isolate-protocol\";\n\n/**\n * Options for creating a runtime.\n */\nexport interface RuntimeOptions {\n /** Memory limit in megabytes (optional) */\n memoryLimitMB?: number;\n /** Console callback handlers */\n console?: ConsoleCallbacks;\n /** Fetch callback handler */\n fetch?: FetchCallback;\n /**\n * File system options.\n * Note: For local runtime, this uses FsOptions with getDirectory returning a FileSystemHandler.\n * For remote runtime (isolate-client), use FileSystemCallbacks instead.\n */\n fs?: FsOptions;\n /** Module loader callback for resolving dynamic imports */\n moduleLoader?: ModuleLoaderCallback;\n /** Custom functions callable from within the isolate */\n customFunctions?: CustomFunctions;\n /** Current working directory for path.resolve(). Defaults to \"/\" */\n cwd?: string;\n /** Enable test environment (describe, it, expect, etc.) */\n testEnvironment?: boolean | TestEnvironmentOptions;\n /** Playwright options - user provides page object */\n playwright?: PlaywrightOptions;\n}\n\n/**\n * Options for playwright in local runtime.\n */\nexport interface PlaywrightOptions {\n /** Playwright Page object - user launches browser and creates page */\n page: import(\"playwright\").Page;\n /** Default timeout for operations (default: 30000ms) */\n timeout?: number;\n /** Base URL for relative navigation */\n baseUrl?: string;\n /** If true, browser console logs are routed through console handler (or printed to stdout if no handler) */\n console?: boolean;\n /** Unified event callback for all playwright events */\n onEvent?: (event: PlaywrightEvent) => void;\n}\n\n/**\n * Runtime fetch handle - provides access to fetch/serve operations.\n */\nexport interface RuntimeFetchHandle {\n /** Dispatch HTTP request to serve() handler */\n dispatchRequest(\n request: Request,\n options?: DispatchRequestOptions\n ): Promise<Response>;\n /** Check if isolate requested WebSocket upgrade */\n getUpgradeRequest(): UpgradeRequest | null;\n /** Dispatch WebSocket open event to isolate */\n dispatchWebSocketOpen(connectionId: string): void;\n /** Dispatch WebSocket message event to isolate */\n dispatchWebSocketMessage(\n connectionId: string,\n message: string | ArrayBuffer\n ): void;\n /** Dispatch WebSocket close event to isolate */\n dispatchWebSocketClose(\n connectionId: string,\n code: number,\n reason: string\n ): void;\n /** Dispatch WebSocket error event to isolate */\n dispatchWebSocketError(connectionId: string, error: Error): void;\n /** Register callback for WebSocket commands from isolate */\n onWebSocketCommand(callback: (cmd: WebSocketCommand) => void): () => void;\n /** Check if serve() has been called */\n hasServeHandler(): boolean;\n /** Check if there are active WebSocket connections */\n hasActiveConnections(): boolean;\n}\n\n/**\n * Runtime timers handle - provides access to timer operations.\n * Timers fire automatically based on real time.\n */\nexport interface RuntimeTimersHandle {\n /** Clear all pending timers */\n clearAll(): void;\n}\n\n/**\n * Runtime console handle - provides access to console state.\n */\nexport interface RuntimeConsoleHandle {\n /** Reset all console state (timers, counters, group depth) */\n reset(): void;\n /** Get console.time() timers */\n getTimers(): Map<string, number>;\n /** Get console.count() counters */\n getCounters(): Map<string, number>;\n /** Get current console.group() nesting depth */\n getGroupDepth(): number;\n}\n\n/**\n * Runtime test environment handle - provides access to test execution.\n */\nexport interface RuntimeTestEnvironmentHandle {\n /** Run all registered tests */\n runTests(timeout?: number): Promise<RunResults>;\n /** Check if any tests are registered */\n hasTests(): boolean;\n /** Get count of registered tests */\n getTestCount(): number;\n /** Reset test state */\n reset(): void;\n}\n\n/**\n * Runtime playwright handle - provides access to browser data collection.\n */\nexport interface RuntimePlaywrightHandle {\n /** Get collected browser data (console logs, network requests/responses) */\n getCollectedData(): CollectedData;\n /** Clear collected browser data */\n clearCollectedData(): void;\n}\n\n/**\n * Collected browser data from playwright.\n */\nexport interface CollectedData {\n /** Browser console logs (from the page, not sandbox) */\n browserConsoleLogs: BrowserConsoleLogEntry[];\n networkRequests: NetworkRequestInfo[];\n networkResponses: NetworkResponseInfo[];\n}\n\n/**\n * Options for eval() method.\n */\nexport interface EvalOptions {\n /** Filename for stack traces */\n filename?: string;\n /** Maximum execution time in milliseconds. If exceeded, throws a timeout error. */\n maxExecutionMs?: number;\n}\n\n/**\n * Runtime handle - the main interface for interacting with the isolate.\n */\nexport interface RuntimeHandle {\n /** Unique runtime identifier */\n readonly id: string;\n /** Execute code as ES module (supports top-level await) */\n eval(code: string, filenameOrOptions?: string | EvalOptions): Promise<void>;\n /** Dispose all resources */\n dispose(): Promise<void>;\n\n /** Fetch handle - access to fetch/serve operations */\n readonly fetch: RuntimeFetchHandle;\n /** Timers handle - access to timer operations */\n readonly timers: RuntimeTimersHandle;\n /** Console handle - access to console state */\n readonly console: RuntimeConsoleHandle;\n /** Test environment handle - access to test execution (throws if not enabled) */\n readonly testEnvironment: RuntimeTestEnvironmentHandle;\n /** Playwright handle - access to playwright operations (throws if not configured) */\n readonly playwright: RuntimePlaywrightHandle;\n}\n\n// Internal state for runtime\ninterface RuntimeState {\n isolate: ivm.Isolate;\n context: ivm.Context;\n handles: {\n core?: CoreHandle;\n console?: ConsoleHandle;\n encoding?: EncodingHandle;\n timers?: TimersHandle;\n path?: PathHandle;\n crypto?: CryptoHandle;\n fetch?: FetchHandle;\n fs?: FsHandle;\n testEnvironment?: TestEnvironmentHandle;\n playwright?: PlaywrightHandle;\n };\n moduleCache: Map<string, ivm.Module>;\n moduleLoader?: ModuleLoaderCallback;\n customFunctions?: CustomFunctions;\n customFnInvokeRef?: ivm.Reference<\n (name: string, argsJson: string) => Promise<string>\n >;\n}\n\n// Iterator session tracking for async iterator custom functions\ninterface IteratorSession {\n iterator: AsyncGenerator<unknown, unknown, unknown>;\n}\n\nconst iteratorSessions = new Map<number, IteratorSession>();\nlet nextIteratorId = 1;\n\n/**\n * Setup custom functions as globals in the isolate context.\n * Each function directly calls the host callback when invoked.\n */\nasync function setupCustomFunctions(\n context: ivm.Context,\n customFunctions: CustomFunctions\n): Promise<ivm.Reference<(name: string, argsJson: string) => Promise<string>>> {\n const global = context.global;\n\n // Reference that invokes the callback and returns the result\n const invokeCallbackRef = new ivm.Reference(\n async (name: string, argsJson: string): Promise<string> => {\n const def = customFunctions[name];\n if (!def) {\n return JSON.stringify({\n ok: false,\n error: {\n message: `Custom function '${name}' not found`,\n name: \"Error\",\n },\n });\n }\n const args = JSON.parse(argsJson) as unknown[];\n try {\n const result =\n def.type === \"async\" ? await def.fn(...args) : def.fn(...args);\n return JSON.stringify({ ok: true, value: result });\n } catch (error: unknown) {\n const err = error as Error;\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__customFn_invoke\", invokeCallbackRef);\n\n // Iterator start: creates iterator, stores in session, returns iteratorId\n const iterStartRef = new ivm.Reference(\n async (name: string, argsJson: string): Promise<string> => {\n const def = customFunctions[name];\n if (!def || def.type !== \"asyncIterator\") {\n return JSON.stringify({\n ok: false,\n error: {\n message: `Async iterator function '${name}' not found`,\n name: \"Error\",\n },\n });\n }\n try {\n const args = JSON.parse(argsJson) as unknown[];\n const fn = def.fn as CustomAsyncGeneratorFunction;\n const iterator = fn(...args);\n const iteratorId = nextIteratorId++;\n iteratorSessions.set(iteratorId, { iterator });\n return JSON.stringify({ ok: true, iteratorId });\n } catch (error: unknown) {\n const err = error as Error;\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__iter_start\", iterStartRef);\n\n // Iterator next: calls iterator.next(), returns {done, value}\n const iterNextRef = new ivm.Reference(\n async (iteratorId: number): Promise<string> => {\n const session = iteratorSessions.get(iteratorId);\n if (!session) {\n return JSON.stringify({\n ok: false,\n error: {\n message: `Iterator session ${iteratorId} not found`,\n name: \"Error\",\n },\n });\n }\n try {\n const result = await session.iterator.next();\n if (result.done) {\n iteratorSessions.delete(iteratorId);\n }\n return JSON.stringify({\n ok: true,\n done: result.done,\n value: result.value,\n });\n } catch (error: unknown) {\n const err = error as Error;\n iteratorSessions.delete(iteratorId);\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__iter_next\", iterNextRef);\n\n // Iterator return: calls iterator.return(), cleans up session\n const iterReturnRef = new ivm.Reference(\n async (iteratorId: number, valueJson: string): Promise<string> => {\n const session = iteratorSessions.get(iteratorId);\n if (!session) {\n return JSON.stringify({ ok: true, done: true, value: undefined });\n }\n try {\n const value = valueJson ? JSON.parse(valueJson) : undefined;\n const result = await session.iterator.return?.(value);\n iteratorSessions.delete(iteratorId);\n return JSON.stringify({ ok: true, done: true, value: result?.value });\n } catch (error: unknown) {\n const err = error as Error;\n iteratorSessions.delete(iteratorId);\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__iter_return\", iterReturnRef);\n\n // Iterator throw: calls iterator.throw(), cleans up session\n const iterThrowRef = new ivm.Reference(\n async (iteratorId: number, errorJson: string): Promise<string> => {\n const session = iteratorSessions.get(iteratorId);\n if (!session) {\n return JSON.stringify({\n ok: false,\n error: {\n message: `Iterator session ${iteratorId} not found`,\n name: \"Error\",\n },\n });\n }\n try {\n const errorData = JSON.parse(errorJson) as {\n message: string;\n name: string;\n };\n const error = Object.assign(new Error(errorData.message), {\n name: errorData.name,\n });\n const result = await session.iterator.throw?.(error);\n iteratorSessions.delete(iteratorId);\n return JSON.stringify({\n ok: true,\n done: result?.done ?? true,\n value: result?.value,\n });\n } catch (error: unknown) {\n const err = error as Error;\n iteratorSessions.delete(iteratorId);\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__iter_throw\", iterThrowRef);\n\n // Create wrapper functions for each custom function\n for (const name of Object.keys(customFunctions)) {\n const def = customFunctions[name]!;\n\n if (def.type === \"async\") {\n // Async function: use applySyncPromise and async function wrapper\n context.evalSync(`\n globalThis.${name} = async function(...args) {\n const resultJson = __customFn_invoke.applySyncPromise(\n undefined,\n [\"${name}\", JSON.stringify(args)]\n );\n const result = JSON.parse(resultJson);\n if (result.ok) {\n return result.value;\n } else {\n const error = new Error(result.error.message);\n error.name = result.error.name;\n throw error;\n }\n };\n `);\n } else if (def.type === \"sync\") {\n // Sync function: use applySyncPromise (to await the host) but wrap in regular function\n // The function blocks until the host responds, but returns the value directly (not a Promise)\n context.evalSync(`\n globalThis.${name} = function(...args) {\n const resultJson = __customFn_invoke.applySyncPromise(\n undefined,\n [\"${name}\", JSON.stringify(args)]\n );\n const result = JSON.parse(resultJson);\n if (result.ok) {\n return result.value;\n } else {\n const error = new Error(result.error.message);\n error.name = result.error.name;\n throw error;\n }\n };\n `);\n } else if (def.type === \"asyncIterator\") {\n // Async iterator function: returns an async iterable object\n context.evalSync(`\n globalThis.${name} = function(...args) {\n const startResult = JSON.parse(__iter_start.applySyncPromise(undefined, [\"${name}\", JSON.stringify(args)]));\n if (!startResult.ok) {\n throw Object.assign(new Error(startResult.error.message), { name: startResult.error.name });\n }\n const iteratorId = startResult.iteratorId;\n return {\n [Symbol.asyncIterator]() { return this; },\n async next() {\n const result = JSON.parse(__iter_next.applySyncPromise(undefined, [iteratorId]));\n if (!result.ok) {\n throw Object.assign(new Error(result.error.message), { name: result.error.name });\n }\n return { done: result.done, value: result.value };\n },\n async return(v) {\n const result = JSON.parse(__iter_return.applySyncPromise(undefined, [iteratorId, JSON.stringify(v)]));\n return { done: true, value: result.value };\n },\n async throw(e) {\n const result = JSON.parse(__iter_throw.applySyncPromise(undefined, [iteratorId, JSON.stringify({ message: e.message, name: e.name })]));\n if (!result.ok) {\n throw Object.assign(new Error(result.error.message), { name: result.error.name });\n }\n return { done: result.done, value: result.value };\n }\n };\n };\n `);\n }\n }\n\n return invokeCallbackRef;\n}\n\n/**\n * Create a module resolver function for local execution.\n */\nfunction createModuleResolver(\n state: RuntimeState\n): (specifier: string, referrer: ivm.Module) => Promise<ivm.Module> {\n return async (\n specifier: string,\n _referrer: ivm.Module\n ): Promise<ivm.Module> => {\n // Check cache first\n const cached = state.moduleCache.get(specifier);\n if (cached) return cached;\n\n if (!state.moduleLoader) {\n throw new Error(\n `No module loader registered. Cannot import: ${specifier}`\n );\n }\n\n // Invoke module loader to get source code\n const code = await state.moduleLoader(specifier);\n\n // Compile the module\n const mod = await state.isolate.compileModule(code, {\n filename: specifier,\n });\n\n // Cache before instantiation (for circular dependencies)\n state.moduleCache.set(specifier, mod);\n\n // Instantiate with recursive resolver\n const resolver = createModuleResolver(state);\n await mod.instantiate(state.context, resolver);\n\n return mod;\n };\n}\n\n/**\n * Convert FetchCallback to FetchOptions\n */\nfunction convertFetchCallback(callback?: FetchCallback): FetchOptions {\n if (!callback) {\n return {};\n }\n return {\n onFetch: async (request: Request): Promise<Response> => {\n // Wrap the result in a Promise to handle both sync and async callbacks\n return Promise.resolve(callback(request));\n },\n };\n}\n\n/**\n * Create a fully configured isolated-vm runtime\n *\n * Sets up all WHATWG APIs: fetch, fs, console, crypto, encoding, timers\n *\n * @example\n * const runtime = await createRuntime({\n * console: { log: (...args) => console.log(\"[isolate]\", ...args) },\n * fetch: async (request) => fetch(request),\n * });\n *\n * await runtime.eval(`\n * console.log(\"Hello from sandbox!\");\n * const response = await fetch(\"https://example.com\");\n * `);\n *\n * await runtime.dispose();\n */\nexport async function createRuntime(\n options?: RuntimeOptions\n): Promise<RuntimeHandle> {\n const opts = options ?? {};\n\n // Generate unique ID\n const id = crypto.randomUUID();\n\n // Create isolate with optional memory limit\n const isolate = new ivm.Isolate({\n memoryLimit: opts.memoryLimitMB,\n });\n const context = await isolate.createContext();\n\n // Initialize state\n const state: RuntimeState = {\n isolate,\n context,\n handles: {},\n moduleCache: new Map(),\n moduleLoader: opts.moduleLoader,\n customFunctions: opts.customFunctions,\n };\n\n // Setup all APIs in order\n // Core must be first as it provides Blob, File, streams, URL, etc.\n state.handles.core = await setupCore(context);\n\n // Console\n state.handles.console = await setupConsole(context, opts.console);\n\n // Encoding (btoa/atob)\n state.handles.encoding = await setupEncoding(context);\n\n // Timers (setTimeout, setInterval)\n state.handles.timers = await setupTimers(context);\n\n // Path module\n state.handles.path = await setupPath(context, { cwd: opts.cwd });\n\n // Crypto (randomUUID, getRandomValues)\n state.handles.crypto = await setupCrypto(context);\n\n // Fetch API - convert callback to options\n state.handles.fetch = await setupFetch(\n context,\n convertFetchCallback(opts.fetch)\n );\n\n // File system (only if handler provided)\n if (opts.fs) {\n state.handles.fs = await setupFs(context, opts.fs);\n }\n\n // Setup custom functions\n if (opts.customFunctions) {\n state.customFnInvokeRef = await setupCustomFunctions(\n context,\n opts.customFunctions\n );\n }\n\n // Setup test environment (if enabled)\n if (opts.testEnvironment) {\n const testEnvOptions: TestEnvironmentOptions | undefined =\n typeof opts.testEnvironment === \"object\"\n ? opts.testEnvironment\n : undefined;\n state.handles.testEnvironment = await setupTestEnvironment(\n context,\n testEnvOptions\n );\n }\n\n // Setup playwright (if page provided) - AFTER test environment so expect can be extended\n if (opts.playwright) {\n // Determine event handler\n // If console: true and we have a console handler, wrap onEvent to route browser logs\n let eventCallback = opts.playwright.onEvent;\n\n if (opts.playwright.console && opts.console?.onEntry) {\n const originalCallback = eventCallback;\n const consoleHandler = opts.console.onEntry;\n eventCallback = (event) => {\n // Call original callback if provided\n if (originalCallback) {\n originalCallback(event);\n }\n // Route browser console logs through console handler as browserOutput entry\n if (event.type === \"browserConsoleLog\") {\n consoleHandler({\n type: \"browserOutput\",\n level: event.level,\n args: event.args,\n timestamp: event.timestamp,\n });\n }\n };\n }\n\n state.handles.playwright = await setupPlaywright(context, {\n page: opts.playwright.page,\n timeout: opts.playwright.timeout,\n baseUrl: opts.playwright.baseUrl,\n // Don't print directly if routing through console handler\n console: opts.playwright.console && !opts.console?.onEntry,\n onEvent: eventCallback,\n });\n }\n\n // Create fetch handle wrapper\n const fetchHandle: RuntimeFetchHandle = {\n async dispatchRequest(\n request: Request,\n options?: DispatchRequestOptions\n ): Promise<Response> {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.dispatchRequest(request, options);\n },\n getUpgradeRequest() {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.getUpgradeRequest();\n },\n dispatchWebSocketOpen(connectionId: string) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n state.handles.fetch.dispatchWebSocketOpen(connectionId);\n },\n dispatchWebSocketMessage(\n connectionId: string,\n message: string | ArrayBuffer\n ) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n state.handles.fetch.dispatchWebSocketMessage(connectionId, message);\n },\n dispatchWebSocketClose(connectionId: string, code: number, reason: string) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n state.handles.fetch.dispatchWebSocketClose(connectionId, code, reason);\n },\n dispatchWebSocketError(connectionId: string, error: Error) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n state.handles.fetch.dispatchWebSocketError(connectionId, error);\n },\n onWebSocketCommand(callback: (cmd: WebSocketCommand) => void) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.onWebSocketCommand(callback);\n },\n hasServeHandler() {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.hasServeHandler();\n },\n hasActiveConnections() {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.hasActiveConnections();\n },\n };\n\n // Create timers handle wrapper\n const timersHandle: RuntimeTimersHandle = {\n clearAll() {\n state.handles.timers?.clearAll();\n },\n };\n\n // Create console handle wrapper\n const consoleHandle: RuntimeConsoleHandle = {\n reset() {\n state.handles.console?.reset();\n },\n getTimers() {\n return state.handles.console?.getTimers() ?? new Map();\n },\n getCounters() {\n return state.handles.console?.getCounters() ?? new Map();\n },\n getGroupDepth() {\n return state.handles.console?.getGroupDepth() ?? 0;\n },\n };\n\n // Create test environment handle wrapper\n const testEnvironmentHandle: RuntimeTestEnvironmentHandle = {\n async runTests(_timeout?: number): Promise<RunResults> {\n if (!state.handles.testEnvironment) {\n throw new Error(\n \"Test environment not enabled. Set testEnvironment: true in createRuntime options.\"\n );\n }\n // Note: timeout parameter reserved for future use\n return runTestsInContext(state.context);\n },\n hasTests(): boolean {\n if (!state.handles.testEnvironment) {\n throw new Error(\n \"Test environment not enabled. Set testEnvironment: true in createRuntime options.\"\n );\n }\n return hasTestsInContext(state.context);\n },\n getTestCount(): number {\n if (!state.handles.testEnvironment) {\n throw new Error(\n \"Test environment not enabled. Set testEnvironment: true in createRuntime options.\"\n );\n }\n return getTestCountInContext(state.context);\n },\n reset() {\n state.handles.testEnvironment?.dispose();\n },\n };\n\n // Create playwright handle wrapper\n const playwrightHandle: RuntimePlaywrightHandle = {\n getCollectedData(): CollectedData {\n if (!state.handles.playwright) {\n throw new Error(\n \"Playwright not configured. Provide playwright.page in createRuntime options.\"\n );\n }\n return {\n browserConsoleLogs: state.handles.playwright.getBrowserConsoleLogs(),\n networkRequests: state.handles.playwright.getNetworkRequests(),\n networkResponses: state.handles.playwright.getNetworkResponses(),\n };\n },\n clearCollectedData() {\n state.handles.playwright?.clearCollected();\n },\n };\n\n return {\n id,\n\n // Module handles\n fetch: fetchHandle,\n timers: timersHandle,\n console: consoleHandle,\n testEnvironment: testEnvironmentHandle,\n playwright: playwrightHandle,\n\n async eval(\n code: string,\n filenameOrOptions?: string | EvalOptions\n ): Promise<void> {\n // Parse options\n const options =\n typeof filenameOrOptions === \"string\"\n ? { filename: filenameOrOptions }\n : filenameOrOptions;\n\n // Compile as ES module\n const mod = await state.isolate.compileModule(code, {\n filename: options?.filename ?? \"<eval>\",\n });\n\n // Instantiate with module resolver\n const resolver = createModuleResolver(state);\n await mod.instantiate(state.context, resolver);\n\n // Evaluate the module with optional timeout\n await mod.evaluate(\n options?.maxExecutionMs\n ? { timeout: options.maxExecutionMs }\n : undefined\n );\n },\n\n async dispose(): Promise<void> {\n // Dispose custom function reference\n if (state.customFnInvokeRef) {\n state.customFnInvokeRef.release();\n }\n\n // Dispose all handles (in reverse order of setup)\n state.handles.playwright?.dispose();\n state.handles.testEnvironment?.dispose();\n state.handles.fs?.dispose();\n state.handles.fetch?.dispose();\n state.handles.crypto?.dispose();\n state.handles.path?.dispose();\n state.handles.timers?.dispose();\n state.handles.encoding?.dispose();\n state.handles.console?.dispose();\n state.handles.core?.dispose();\n\n // Clear module cache\n state.moduleCache.clear();\n\n // Release context and dispose isolate\n state.context.release();\n state.isolate.dispose();\n },\n };\n}\n\n// Re-export all package types and functions\nexport { setupCore } from \"@ricsam/isolate-core\";\nexport type { CoreHandle, SetupCoreOptions } from \"@ricsam/isolate-core\";\n\nexport { setupConsole } from \"@ricsam/isolate-console\";\nexport {\n simpleConsoleHandler,\n type SimpleConsoleCallbacks,\n} from \"@ricsam/isolate-console/utils\";\nexport type {\n ConsoleHandle,\n ConsoleOptions,\n ConsoleEntry as ConsoleEntryFromConsole,\n} from \"@ricsam/isolate-console\";\n\nexport { setupCrypto } from \"@ricsam/isolate-crypto\";\nexport type { CryptoHandle } from \"@ricsam/isolate-crypto\";\n\nexport { setupEncoding } from \"@ricsam/isolate-encoding\";\nexport type { EncodingHandle } from \"@ricsam/isolate-encoding\";\n\nexport { setupFetch } from \"@ricsam/isolate-fetch\";\nexport type {\n FetchHandle,\n FetchOptions,\n WebSocketCommand,\n UpgradeRequest,\n} from \"@ricsam/isolate-fetch\";\n\nexport { setupFs, createNodeFileSystemHandler } from \"@ricsam/isolate-fs\";\nexport type {\n FsHandle,\n FsOptions,\n FileSystemHandler,\n NodeFileSystemHandlerOptions,\n} from \"@ricsam/isolate-fs\";\n\nexport { setupPath } from \"@ricsam/isolate-path\";\nexport type { PathHandle, PathOptions } from \"@ricsam/isolate-path\";\n\nexport { setupTimers } from \"@ricsam/isolate-timers\";\nexport type { TimersHandle } from \"@ricsam/isolate-timers\";\n\nexport {\n setupTestEnvironment,\n runTests,\n hasTests,\n getTestCount,\n} from \"@ricsam/isolate-test-environment\";\nexport type {\n TestEnvironmentHandle,\n TestEnvironmentOptions,\n RunResults,\n TestResult,\n TestInfo,\n TestError,\n TestEvent,\n SuiteInfo,\n SuiteResult,\n} from \"@ricsam/isolate-test-environment\";\n\nexport {\n setupPlaywright,\n createPlaywrightHandler,\n} from \"@ricsam/isolate-playwright\";\nexport type {\n PlaywrightHandle,\n PlaywrightSetupOptions,\n PlaywrightCallback,\n PlaywrightEvent,\n NetworkRequestInfo,\n NetworkResponseInfo,\n BrowserConsoleLogEntry,\n} from \"@ricsam/isolate-playwright\";\n\nexport * from \"./internal.mjs\";\n"
|
|
5
|
+
"import ivm from \"isolated-vm\";\nimport { setupCore } from \"@ricsam/isolate-core\";\nimport { setupConsole } from \"@ricsam/isolate-console\";\nimport { setupEncoding } from \"@ricsam/isolate-encoding\";\nimport { setupTimers } from \"@ricsam/isolate-timers\";\nimport { setupPath } from \"@ricsam/isolate-path\";\nimport { setupCrypto } from \"@ricsam/isolate-crypto\";\nimport { setupFetch } from \"@ricsam/isolate-fetch\";\nimport { setupFs } from \"@ricsam/isolate-fs\";\nimport {\n setupTestEnvironment,\n runTests as runTestsInContext,\n hasTests as hasTestsInContext,\n getTestCount as getTestCountInContext,\n} from \"@ricsam/isolate-test-environment\";\nimport { setupPlaywright } from \"@ricsam/isolate-playwright\";\n\nimport type { ConsoleOptions, ConsoleHandle } from \"@ricsam/isolate-console\";\nimport type {\n FetchOptions,\n FetchHandle,\n DispatchRequestOptions,\n UpgradeRequest,\n WebSocketCommand,\n} from \"@ricsam/isolate-fetch\";\nimport type { FsOptions, FsHandle } from \"@ricsam/isolate-fs\";\nimport type { CoreHandle } from \"@ricsam/isolate-core\";\nimport type { EncodingHandle } from \"@ricsam/isolate-encoding\";\nimport type { TimersHandle } from \"@ricsam/isolate-timers\";\nimport type { PathHandle } from \"@ricsam/isolate-path\";\nimport type { CryptoHandle } from \"@ricsam/isolate-crypto\";\nimport type {\n TestEnvironmentHandle,\n RunResults,\n TestEnvironmentOptions,\n TestEvent,\n SuiteInfo,\n SuiteResult,\n TestInfo,\n TestResult,\n TestError,\n} from \"@ricsam/isolate-test-environment\";\nimport type {\n PlaywrightHandle,\n NetworkRequestInfo,\n NetworkResponseInfo,\n BrowserConsoleLogEntry,\n PlaywrightEvent,\n} from \"@ricsam/isolate-playwright\";\nimport type {\n ConsoleCallbacks,\n ConsoleEntry,\n FetchCallback,\n ModuleLoaderCallback,\n CustomFunctionDefinition,\n CustomFunctions,\n CustomAsyncGeneratorFunction,\n DispatchOptions,\n EvalOptions as ProtocolEvalOptions,\n PlaywrightOptions as ProtocolPlaywrightOptions,\n BaseRuntimeOptions,\n} from \"@ricsam/isolate-protocol\";\nimport {\n marshalValue,\n unmarshalValue,\n} from \"@ricsam/isolate-protocol\";\n\n// Re-export shared types from protocol\nexport type {\n ConsoleCallbacks,\n ConsoleEntry,\n FetchCallback,\n ModuleLoaderCallback,\n CustomFunction,\n CustomFunctionDefinition,\n CustomFunctions,\n DispatchOptions,\n} from \"@ricsam/isolate-protocol\";\n\n// Re-export shared types with local aliases for backward compatibility\nexport type EvalOptions = ProtocolEvalOptions;\nexport type PlaywrightOptions = ProtocolPlaywrightOptions;\n\n/**\n * Options for creating a runtime.\n * Extends BaseRuntimeOptions and adds runtime-specific fs type.\n */\nexport interface RuntimeOptions<T extends Record<string, any[]> = Record<string, unknown[]>>\n extends BaseRuntimeOptions<T> {\n /**\n * File system options.\n * Note: For local runtime, this uses FsOptions with getDirectory returning a FileSystemHandler.\n * For remote runtime (isolate-client), use FileSystemCallbacks instead.\n */\n fs?: FsOptions;\n}\n\n/**\n * Runtime fetch handle - provides access to fetch/serve operations.\n */\nexport interface RuntimeFetchHandle {\n /** Dispatch HTTP request to serve() handler */\n dispatchRequest(\n request: Request,\n options?: DispatchRequestOptions\n ): Promise<Response>;\n /** Check if isolate requested WebSocket upgrade */\n getUpgradeRequest(): UpgradeRequest | null;\n /** Dispatch WebSocket open event to isolate */\n dispatchWebSocketOpen(connectionId: string): void;\n /** Dispatch WebSocket message event to isolate */\n dispatchWebSocketMessage(\n connectionId: string,\n message: string | ArrayBuffer\n ): void;\n /** Dispatch WebSocket close event to isolate */\n dispatchWebSocketClose(\n connectionId: string,\n code: number,\n reason: string\n ): void;\n /** Dispatch WebSocket error event to isolate */\n dispatchWebSocketError(connectionId: string, error: Error): void;\n /** Register callback for WebSocket commands from isolate */\n onWebSocketCommand(callback: (cmd: WebSocketCommand) => void): () => void;\n /** Check if serve() has been called */\n hasServeHandler(): boolean;\n /** Check if there are active WebSocket connections */\n hasActiveConnections(): boolean;\n}\n\n/**\n * Runtime timers handle - provides access to timer operations.\n * Timers fire automatically based on real time.\n */\nexport interface RuntimeTimersHandle {\n /** Clear all pending timers */\n clearAll(): void;\n}\n\n/**\n * Runtime console handle - provides access to console state.\n */\nexport interface RuntimeConsoleHandle {\n /** Reset all console state (timers, counters, group depth) */\n reset(): void;\n /** Get console.time() timers */\n getTimers(): Map<string, number>;\n /** Get console.count() counters */\n getCounters(): Map<string, number>;\n /** Get current console.group() nesting depth */\n getGroupDepth(): number;\n}\n\n/**\n * Runtime test environment handle - provides access to test execution.\n */\nexport interface RuntimeTestEnvironmentHandle {\n /** Run all registered tests */\n runTests(timeout?: number): Promise<RunResults>;\n /** Check if any tests are registered */\n hasTests(): boolean;\n /** Get count of registered tests */\n getTestCount(): number;\n /** Reset test state */\n reset(): void;\n}\n\n/**\n * Runtime playwright handle - provides access to browser data collection.\n */\nexport interface RuntimePlaywrightHandle {\n /** Get collected browser data (console logs, network requests/responses) */\n getCollectedData(): CollectedData;\n /** Clear collected browser data */\n clearCollectedData(): void;\n}\n\n/**\n * Collected browser data from playwright.\n */\nexport interface CollectedData {\n /** Browser console logs (from the page, not sandbox) */\n browserConsoleLogs: BrowserConsoleLogEntry[];\n networkRequests: NetworkRequestInfo[];\n networkResponses: NetworkResponseInfo[];\n}\n\n/**\n * Runtime handle - the main interface for interacting with the isolate.\n */\nexport interface RuntimeHandle {\n /** Unique runtime identifier */\n readonly id: string;\n /** Execute code as ES module (supports top-level await) */\n eval(code: string, filenameOrOptions?: string | EvalOptions): Promise<void>;\n /** Dispose all resources */\n dispose(): Promise<void>;\n\n /** Fetch handle - access to fetch/serve operations */\n readonly fetch: RuntimeFetchHandle;\n /** Timers handle - access to timer operations */\n readonly timers: RuntimeTimersHandle;\n /** Console handle - access to console state */\n readonly console: RuntimeConsoleHandle;\n /** Test environment handle - access to test execution (throws if not enabled) */\n readonly testEnvironment: RuntimeTestEnvironmentHandle;\n /** Playwright handle - access to playwright operations (throws if not configured) */\n readonly playwright: RuntimePlaywrightHandle;\n}\n\n// Internal state for runtime\ninterface RuntimeState {\n isolate: ivm.Isolate;\n context: ivm.Context;\n handles: {\n core?: CoreHandle;\n console?: ConsoleHandle;\n encoding?: EncodingHandle;\n timers?: TimersHandle;\n path?: PathHandle;\n crypto?: CryptoHandle;\n fetch?: FetchHandle;\n fs?: FsHandle;\n testEnvironment?: TestEnvironmentHandle;\n playwright?: PlaywrightHandle;\n };\n moduleCache: Map<string, ivm.Module>;\n moduleLoader?: ModuleLoaderCallback;\n customFunctions?: CustomFunctions;\n customFnInvokeRef?: ivm.Reference<\n (name: string, argsJson: string) => Promise<string>\n >;\n}\n\n// Iterator session tracking for async iterator custom functions\ninterface IteratorSession {\n iterator: AsyncGenerator<unknown, unknown, unknown>;\n}\n\nconst iteratorSessions = new Map<number, IteratorSession>();\nlet nextIteratorId = 1;\n\n/**\n * Lightweight marshalling code to inject into the isolate.\n * Converts JavaScript types to Ref objects for type-preserving serialization.\n */\nconst ISOLATE_MARSHAL_CODE = `\n(function() {\n // Marshal a value (JavaScript → Ref)\n function marshalForHost(value, depth = 0) {\n if (depth > 100) throw new Error('Maximum marshalling depth exceeded');\n\n if (value === null) return null;\n if (value === undefined) return { __type: 'UndefinedRef' };\n\n const type = typeof value;\n if (type === 'string' || type === 'number' || type === 'boolean') return value;\n if (type === 'bigint') return { __type: 'BigIntRef', value: value.toString() };\n if (type === 'function') throw new Error('Cannot marshal functions from isolate');\n if (type === 'symbol') throw new Error('Cannot marshal Symbol values');\n\n if (type === 'object') {\n if (value instanceof Date) {\n return { __type: 'DateRef', timestamp: value.getTime() };\n }\n if (value instanceof RegExp) {\n return { __type: 'RegExpRef', source: value.source, flags: value.flags };\n }\n if (value instanceof URL) {\n return { __type: 'URLRef', href: value.href };\n }\n if (typeof Headers !== 'undefined' && value instanceof Headers) {\n const pairs = [];\n value.forEach((v, k) => pairs.push([k, v]));\n return { __type: 'HeadersRef', pairs };\n }\n if (value instanceof Uint8Array) {\n return { __type: 'Uint8ArrayRef', data: Array.from(value) };\n }\n if (value instanceof ArrayBuffer) {\n return { __type: 'Uint8ArrayRef', data: Array.from(new Uint8Array(value)) };\n }\n if (typeof Request !== 'undefined' && value instanceof Request) {\n throw new Error('Cannot marshal Request from isolate. Use fetch callback instead.');\n }\n if (typeof Response !== 'undefined' && value instanceof Response) {\n throw new Error('Cannot marshal Response from isolate. Return plain objects instead.');\n }\n if (typeof File !== 'undefined' && value instanceof File) {\n throw new Error('Cannot marshal File from isolate.');\n }\n if (typeof Blob !== 'undefined' && value instanceof Blob) {\n throw new Error('Cannot marshal Blob from isolate.');\n }\n if (typeof FormData !== 'undefined' && value instanceof FormData) {\n throw new Error('Cannot marshal FormData from isolate.');\n }\n if (Array.isArray(value)) {\n return value.map(v => marshalForHost(v, depth + 1));\n }\n // Plain object\n const result = {};\n for (const key of Object.keys(value)) {\n result[key] = marshalForHost(value[key], depth + 1);\n }\n return result;\n }\n return value;\n }\n\n // Unmarshal a value (Ref → JavaScript)\n function unmarshalFromHost(value, depth = 0) {\n if (depth > 100) throw new Error('Maximum unmarshalling depth exceeded');\n\n if (value === null) return null;\n if (typeof value !== 'object') return value;\n\n if (value.__type) {\n switch (value.__type) {\n case 'UndefinedRef': return undefined;\n case 'DateRef': return new Date(value.timestamp);\n case 'RegExpRef': return new RegExp(value.source, value.flags);\n case 'BigIntRef': return BigInt(value.value);\n case 'URLRef': return new URL(value.href);\n case 'HeadersRef': return new Headers(value.pairs);\n case 'Uint8ArrayRef': return new Uint8Array(value.data);\n case 'RequestRef': {\n const init = {\n method: value.method,\n headers: value.headers,\n body: value.body ? new Uint8Array(value.body) : null,\n };\n if (value.mode) init.mode = value.mode;\n if (value.credentials) init.credentials = value.credentials;\n if (value.cache) init.cache = value.cache;\n if (value.redirect) init.redirect = value.redirect;\n if (value.referrer) init.referrer = value.referrer;\n if (value.referrerPolicy) init.referrerPolicy = value.referrerPolicy;\n if (value.integrity) init.integrity = value.integrity;\n return new Request(value.url, init);\n }\n case 'ResponseRef': {\n return new Response(value.body ? new Uint8Array(value.body) : null, {\n status: value.status,\n statusText: value.statusText,\n headers: value.headers,\n });\n }\n case 'FileRef': {\n if (!value.name) {\n return new Blob([new Uint8Array(value.data)], { type: value.type });\n }\n return new File([new Uint8Array(value.data)], value.name, {\n type: value.type,\n lastModified: value.lastModified,\n });\n }\n case 'FormDataRef': {\n const fd = new FormData();\n for (const [key, entry] of value.entries) {\n if (typeof entry === 'string') {\n fd.append(key, entry);\n } else {\n const file = unmarshalFromHost(entry, depth + 1);\n fd.append(key, file);\n }\n }\n return fd;\n }\n default:\n // Unknown ref type, return as-is\n break;\n }\n }\n\n if (Array.isArray(value)) {\n return value.map(v => unmarshalFromHost(v, depth + 1));\n }\n\n // Plain object - recursively unmarshal\n const result = {};\n for (const key of Object.keys(value)) {\n result[key] = unmarshalFromHost(value[key], depth + 1);\n }\n return result;\n }\n\n // Expose as globals\n globalThis.__marshalForHost = marshalForHost;\n globalThis.__unmarshalFromHost = unmarshalFromHost;\n})();\n`;\n\n/**\n * Setup custom functions as globals in the isolate context.\n * Each function directly calls the host callback when invoked.\n */\nasync function setupCustomFunctions(\n context: ivm.Context,\n customFunctions: CustomFunctions\n): Promise<ivm.Reference<(name: string, argsJson: string) => Promise<string>>> {\n const global = context.global;\n\n // Reference that invokes the callback and returns the result\n const invokeCallbackRef = new ivm.Reference(\n async (name: string, argsJson: string): Promise<string> => {\n const def = customFunctions[name];\n if (!def) {\n return JSON.stringify({\n ok: false,\n error: {\n message: `Custom function '${name}' not found`,\n name: \"Error\",\n },\n });\n }\n // Unmarshal args from isolate (converts Refs back to JavaScript types)\n const rawArgs = JSON.parse(argsJson) as unknown[];\n const args = unmarshalValue(rawArgs) as unknown[];\n try {\n const result =\n def.type === \"async\" ? await def.fn(...args) : def.fn(...args);\n // Marshal result for isolate (converts JavaScript types to Refs)\n const marshalledResult = await marshalValue(result);\n return JSON.stringify({ ok: true, value: marshalledResult });\n } catch (error: unknown) {\n const err = error as Error;\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__customFn_invoke\", invokeCallbackRef);\n\n // Iterator start: creates iterator, stores in session, returns iteratorId\n const iterStartRef = new ivm.Reference(\n async (name: string, argsJson: string): Promise<string> => {\n const def = customFunctions[name];\n if (!def || def.type !== \"asyncIterator\") {\n return JSON.stringify({\n ok: false,\n error: {\n message: `Async iterator function '${name}' not found`,\n name: \"Error\",\n },\n });\n }\n try {\n // Unmarshal args from isolate\n const rawArgs = JSON.parse(argsJson) as unknown[];\n const args = unmarshalValue(rawArgs) as unknown[];\n const fn = def.fn as CustomAsyncGeneratorFunction;\n const iterator = fn(...args);\n const iteratorId = nextIteratorId++;\n iteratorSessions.set(iteratorId, { iterator });\n return JSON.stringify({ ok: true, iteratorId });\n } catch (error: unknown) {\n const err = error as Error;\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__iter_start\", iterStartRef);\n\n // Iterator next: calls iterator.next(), returns {done, value}\n const iterNextRef = new ivm.Reference(\n async (iteratorId: number): Promise<string> => {\n const session = iteratorSessions.get(iteratorId);\n if (!session) {\n return JSON.stringify({\n ok: false,\n error: {\n message: `Iterator session ${iteratorId} not found`,\n name: \"Error\",\n },\n });\n }\n try {\n const result = await session.iterator.next();\n if (result.done) {\n iteratorSessions.delete(iteratorId);\n }\n // Marshal value for isolate\n const marshalledValue = await marshalValue(result.value);\n return JSON.stringify({\n ok: true,\n done: result.done,\n value: marshalledValue,\n });\n } catch (error: unknown) {\n const err = error as Error;\n iteratorSessions.delete(iteratorId);\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__iter_next\", iterNextRef);\n\n // Iterator return: calls iterator.return(), cleans up session\n const iterReturnRef = new ivm.Reference(\n async (iteratorId: number, valueJson: string): Promise<string> => {\n const session = iteratorSessions.get(iteratorId);\n if (!session) {\n return JSON.stringify({ ok: true, done: true, value: undefined });\n }\n try {\n // Unmarshal value from isolate\n const rawValue = valueJson ? JSON.parse(valueJson) : undefined;\n const value = unmarshalValue(rawValue);\n const result = await session.iterator.return?.(value);\n iteratorSessions.delete(iteratorId);\n // Marshal value for isolate\n const marshalledValue = await marshalValue(result?.value);\n return JSON.stringify({ ok: true, done: true, value: marshalledValue });\n } catch (error: unknown) {\n const err = error as Error;\n iteratorSessions.delete(iteratorId);\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__iter_return\", iterReturnRef);\n\n // Iterator throw: calls iterator.throw(), cleans up session\n const iterThrowRef = new ivm.Reference(\n async (iteratorId: number, errorJson: string): Promise<string> => {\n const session = iteratorSessions.get(iteratorId);\n if (!session) {\n return JSON.stringify({\n ok: false,\n error: {\n message: `Iterator session ${iteratorId} not found`,\n name: \"Error\",\n },\n });\n }\n try {\n const errorData = JSON.parse(errorJson) as {\n message: string;\n name: string;\n };\n const error = Object.assign(new Error(errorData.message), {\n name: errorData.name,\n });\n const result = await session.iterator.throw?.(error);\n iteratorSessions.delete(iteratorId);\n // Marshal value for isolate\n const marshalledValue = await marshalValue(result?.value);\n return JSON.stringify({\n ok: true,\n done: result?.done ?? true,\n value: marshalledValue,\n });\n } catch (error: unknown) {\n const err = error as Error;\n iteratorSessions.delete(iteratorId);\n return JSON.stringify({\n ok: false,\n error: { message: err.message, name: err.name },\n });\n }\n }\n );\n\n global.setSync(\"__iter_throw\", iterThrowRef);\n\n // Inject marshalling helpers into the isolate\n context.evalSync(ISOLATE_MARSHAL_CODE);\n\n // Create wrapper functions for each custom function\n for (const name of Object.keys(customFunctions)) {\n const def = customFunctions[name]!;\n\n if (def.type === \"async\") {\n // Async function: use applySyncPromise and async function wrapper\n context.evalSync(`\n globalThis.${name} = async function(...args) {\n const marshalledArgs = __marshalForHost(args);\n const resultJson = __customFn_invoke.applySyncPromise(\n undefined,\n [\"${name}\", JSON.stringify(marshalledArgs)]\n );\n const result = JSON.parse(resultJson);\n if (result.ok) {\n return __unmarshalFromHost(result.value);\n } else {\n const error = new Error(result.error.message);\n error.name = result.error.name;\n throw error;\n }\n };\n `);\n } else if (def.type === \"sync\") {\n // Sync function: use applySyncPromise (to await the host) but wrap in regular function\n // The function blocks until the host responds, but returns the value directly (not a Promise)\n context.evalSync(`\n globalThis.${name} = function(...args) {\n const marshalledArgs = __marshalForHost(args);\n const resultJson = __customFn_invoke.applySyncPromise(\n undefined,\n [\"${name}\", JSON.stringify(marshalledArgs)]\n );\n const result = JSON.parse(resultJson);\n if (result.ok) {\n return __unmarshalFromHost(result.value);\n } else {\n const error = new Error(result.error.message);\n error.name = result.error.name;\n throw error;\n }\n };\n `);\n } else if (def.type === \"asyncIterator\") {\n // Async iterator function: returns an async iterable object\n context.evalSync(`\n globalThis.${name} = function(...args) {\n const marshalledArgs = __marshalForHost(args);\n const startResult = JSON.parse(__iter_start.applySyncPromise(undefined, [\"${name}\", JSON.stringify(marshalledArgs)]));\n if (!startResult.ok) {\n throw Object.assign(new Error(startResult.error.message), { name: startResult.error.name });\n }\n const iteratorId = startResult.iteratorId;\n return {\n [Symbol.asyncIterator]() { return this; },\n async next() {\n const result = JSON.parse(__iter_next.applySyncPromise(undefined, [iteratorId]));\n if (!result.ok) {\n throw Object.assign(new Error(result.error.message), { name: result.error.name });\n }\n return { done: result.done, value: __unmarshalFromHost(result.value) };\n },\n async return(v) {\n const result = JSON.parse(__iter_return.applySyncPromise(undefined, [iteratorId, JSON.stringify(__marshalForHost(v))]));\n return { done: true, value: __unmarshalFromHost(result.value) };\n },\n async throw(e) {\n const result = JSON.parse(__iter_throw.applySyncPromise(undefined, [iteratorId, JSON.stringify({ message: e.message, name: e.name })]));\n if (!result.ok) {\n throw Object.assign(new Error(result.error.message), { name: result.error.name });\n }\n return { done: result.done, value: __unmarshalFromHost(result.value) };\n }\n };\n };\n `);\n }\n }\n\n return invokeCallbackRef;\n}\n\n/**\n * Create a module resolver function for local execution.\n */\nfunction createModuleResolver(\n state: RuntimeState\n): (specifier: string, referrer: ivm.Module) => Promise<ivm.Module> {\n return async (\n specifier: string,\n _referrer: ivm.Module\n ): Promise<ivm.Module> => {\n // Check cache first\n const cached = state.moduleCache.get(specifier);\n if (cached) return cached;\n\n if (!state.moduleLoader) {\n throw new Error(\n `No module loader registered. Cannot import: ${specifier}`\n );\n }\n\n // Invoke module loader to get source code\n const code = await state.moduleLoader(specifier);\n\n // Compile the module\n const mod = await state.isolate.compileModule(code, {\n filename: specifier,\n });\n\n // Cache before instantiation (for circular dependencies)\n state.moduleCache.set(specifier, mod);\n\n // Instantiate with recursive resolver\n const resolver = createModuleResolver(state);\n await mod.instantiate(state.context, resolver);\n\n return mod;\n };\n}\n\n/**\n * Convert FetchCallback to FetchOptions\n */\nfunction convertFetchCallback(callback?: FetchCallback): FetchOptions {\n if (!callback) {\n return {};\n }\n return {\n onFetch: async (request: Request): Promise<Response> => {\n // Wrap the result in a Promise to handle both sync and async callbacks\n return Promise.resolve(callback(request));\n },\n };\n}\n\n/**\n * Create a fully configured isolated-vm runtime\n *\n * Sets up all WHATWG APIs: fetch, fs, console, crypto, encoding, timers\n *\n * @example\n * const runtime = await createRuntime({\n * console: { log: (...args) => console.log(\"[isolate]\", ...args) },\n * fetch: async (request) => fetch(request),\n * });\n *\n * await runtime.eval(`\n * console.log(\"Hello from sandbox!\");\n * const response = await fetch(\"https://example.com\");\n * `);\n *\n * await runtime.dispose();\n */\nexport async function createRuntime<T extends Record<string, any[]> = Record<string, unknown[]>>(\n options?: RuntimeOptions<T>\n): Promise<RuntimeHandle> {\n const opts = options ?? {};\n\n // Generate unique ID\n const id = crypto.randomUUID();\n\n // Create isolate with optional memory limit\n const isolate = new ivm.Isolate({\n memoryLimit: opts.memoryLimitMB,\n });\n const context = await isolate.createContext();\n\n // Initialize state\n const state: RuntimeState = {\n isolate,\n context,\n handles: {},\n moduleCache: new Map(),\n moduleLoader: opts.moduleLoader,\n customFunctions: opts.customFunctions as CustomFunctions<Record<string, unknown[]>>,\n };\n\n // Setup all APIs in order\n // Core must be first as it provides Blob, File, streams, URL, etc.\n state.handles.core = await setupCore(context);\n\n // Console\n state.handles.console = await setupConsole(context, opts.console);\n\n // Encoding (btoa/atob)\n state.handles.encoding = await setupEncoding(context);\n\n // Timers (setTimeout, setInterval)\n state.handles.timers = await setupTimers(context);\n\n // Path module\n state.handles.path = await setupPath(context, { cwd: opts.cwd });\n\n // Crypto (randomUUID, getRandomValues)\n state.handles.crypto = await setupCrypto(context);\n\n // Fetch API - convert callback to options\n state.handles.fetch = await setupFetch(\n context,\n convertFetchCallback(opts.fetch)\n );\n\n // File system (only if handler provided)\n if (opts.fs) {\n state.handles.fs = await setupFs(context, opts.fs);\n }\n\n // Setup custom functions\n if (opts.customFunctions) {\n state.customFnInvokeRef = await setupCustomFunctions(\n context,\n opts.customFunctions as CustomFunctions<Record<string, unknown[]>>\n );\n }\n\n // Setup test environment (if enabled)\n if (opts.testEnvironment) {\n const testEnvOptions: TestEnvironmentOptions | undefined =\n typeof opts.testEnvironment === \"object\"\n ? opts.testEnvironment\n : undefined;\n state.handles.testEnvironment = await setupTestEnvironment(\n context,\n testEnvOptions\n );\n }\n\n // Setup playwright (if page provided) - AFTER test environment so expect can be extended\n if (opts.playwright) {\n // Determine event handler\n // If console: true and we have a console handler, wrap onEvent to route browser logs\n let eventCallback = opts.playwright.onEvent;\n\n if (opts.playwright.console && opts.console?.onEntry) {\n const originalCallback = eventCallback;\n const consoleHandler = opts.console.onEntry;\n eventCallback = (event) => {\n // Call original callback if provided\n if (originalCallback) {\n originalCallback(event);\n }\n // Route browser console logs through console handler as browserOutput entry\n if (event.type === \"browserConsoleLog\") {\n consoleHandler({\n type: \"browserOutput\",\n level: event.level,\n stdout: event.stdout,\n timestamp: event.timestamp,\n });\n }\n };\n }\n\n state.handles.playwright = await setupPlaywright(context, {\n page: opts.playwright.page,\n timeout: opts.playwright.timeout,\n baseUrl: opts.playwright.baseUrl,\n // Don't print directly if routing through console handler\n console: opts.playwright.console && !opts.console?.onEntry,\n onEvent: eventCallback,\n });\n }\n\n // Create fetch handle wrapper\n const fetchHandle: RuntimeFetchHandle = {\n async dispatchRequest(\n request: Request,\n options?: DispatchRequestOptions\n ): Promise<Response> {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.dispatchRequest(request, options);\n },\n getUpgradeRequest() {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.getUpgradeRequest();\n },\n dispatchWebSocketOpen(connectionId: string) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n state.handles.fetch.dispatchWebSocketOpen(connectionId);\n },\n dispatchWebSocketMessage(\n connectionId: string,\n message: string | ArrayBuffer\n ) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n state.handles.fetch.dispatchWebSocketMessage(connectionId, message);\n },\n dispatchWebSocketClose(connectionId: string, code: number, reason: string) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n state.handles.fetch.dispatchWebSocketClose(connectionId, code, reason);\n },\n dispatchWebSocketError(connectionId: string, error: Error) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n state.handles.fetch.dispatchWebSocketError(connectionId, error);\n },\n onWebSocketCommand(callback: (cmd: WebSocketCommand) => void) {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.onWebSocketCommand(callback);\n },\n hasServeHandler() {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.hasServeHandler();\n },\n hasActiveConnections() {\n if (!state.handles.fetch) {\n throw new Error(\"Fetch handle not available\");\n }\n return state.handles.fetch.hasActiveConnections();\n },\n };\n\n // Create timers handle wrapper\n const timersHandle: RuntimeTimersHandle = {\n clearAll() {\n state.handles.timers?.clearAll();\n },\n };\n\n // Create console handle wrapper\n const consoleHandle: RuntimeConsoleHandle = {\n reset() {\n state.handles.console?.reset();\n },\n getTimers() {\n return state.handles.console?.getTimers() ?? new Map();\n },\n getCounters() {\n return state.handles.console?.getCounters() ?? new Map();\n },\n getGroupDepth() {\n return state.handles.console?.getGroupDepth() ?? 0;\n },\n };\n\n // Create test environment handle wrapper\n const testEnvironmentHandle: RuntimeTestEnvironmentHandle = {\n async runTests(_timeout?: number): Promise<RunResults> {\n if (!state.handles.testEnvironment) {\n throw new Error(\n \"Test environment not enabled. Set testEnvironment: true in createRuntime options.\"\n );\n }\n // Note: timeout parameter reserved for future use\n return runTestsInContext(state.context);\n },\n hasTests(): boolean {\n if (!state.handles.testEnvironment) {\n throw new Error(\n \"Test environment not enabled. Set testEnvironment: true in createRuntime options.\"\n );\n }\n return hasTestsInContext(state.context);\n },\n getTestCount(): number {\n if (!state.handles.testEnvironment) {\n throw new Error(\n \"Test environment not enabled. Set testEnvironment: true in createRuntime options.\"\n );\n }\n return getTestCountInContext(state.context);\n },\n reset() {\n state.handles.testEnvironment?.dispose();\n },\n };\n\n // Create playwright handle wrapper\n const playwrightHandle: RuntimePlaywrightHandle = {\n getCollectedData(): CollectedData {\n if (!state.handles.playwright) {\n throw new Error(\n \"Playwright not configured. Provide playwright.page in createRuntime options.\"\n );\n }\n return {\n browserConsoleLogs: state.handles.playwright.getBrowserConsoleLogs(),\n networkRequests: state.handles.playwright.getNetworkRequests(),\n networkResponses: state.handles.playwright.getNetworkResponses(),\n };\n },\n clearCollectedData() {\n state.handles.playwright?.clearCollected();\n },\n };\n\n return {\n id,\n\n // Module handles\n fetch: fetchHandle,\n timers: timersHandle,\n console: consoleHandle,\n testEnvironment: testEnvironmentHandle,\n playwright: playwrightHandle,\n\n async eval(\n code: string,\n filenameOrOptions?: string | EvalOptions\n ): Promise<void> {\n // Parse options\n const options =\n typeof filenameOrOptions === \"string\"\n ? { filename: filenameOrOptions }\n : filenameOrOptions;\n\n // Compile as ES module\n const mod = await state.isolate.compileModule(code, {\n filename: options?.filename ?? \"<eval>\",\n });\n\n // Instantiate with module resolver\n const resolver = createModuleResolver(state);\n await mod.instantiate(state.context, resolver);\n\n // Evaluate the module with optional timeout\n await mod.evaluate(\n options?.maxExecutionMs\n ? { timeout: options.maxExecutionMs }\n : undefined\n );\n },\n\n async dispose(): Promise<void> {\n // Dispose custom function reference\n if (state.customFnInvokeRef) {\n state.customFnInvokeRef.release();\n }\n\n // Dispose all handles (in reverse order of setup)\n state.handles.playwright?.dispose();\n state.handles.testEnvironment?.dispose();\n state.handles.fs?.dispose();\n state.handles.fetch?.dispose();\n state.handles.crypto?.dispose();\n state.handles.path?.dispose();\n state.handles.timers?.dispose();\n state.handles.encoding?.dispose();\n state.handles.console?.dispose();\n state.handles.core?.dispose();\n\n // Clear module cache\n state.moduleCache.clear();\n\n // Release context and dispose isolate\n state.context.release();\n state.isolate.dispose();\n },\n };\n}\n\n// Re-export all package types and functions\nexport { setupCore } from \"@ricsam/isolate-core\";\nexport type { CoreHandle, SetupCoreOptions } from \"@ricsam/isolate-core\";\n\nexport { setupConsole } from \"@ricsam/isolate-console\";\nexport {\n simpleConsoleHandler,\n type SimpleConsoleCallbacks,\n} from \"@ricsam/isolate-console/utils\";\nexport type {\n ConsoleHandle,\n ConsoleOptions,\n ConsoleEntry as ConsoleEntryFromConsole,\n} from \"@ricsam/isolate-console\";\n\nexport { setupCrypto } from \"@ricsam/isolate-crypto\";\nexport type { CryptoHandle } from \"@ricsam/isolate-crypto\";\n\nexport { setupEncoding } from \"@ricsam/isolate-encoding\";\nexport type { EncodingHandle } from \"@ricsam/isolate-encoding\";\n\nexport { setupFetch } from \"@ricsam/isolate-fetch\";\nexport type {\n FetchHandle,\n FetchOptions,\n WebSocketCommand,\n UpgradeRequest,\n} from \"@ricsam/isolate-fetch\";\n\nexport { setupFs, createNodeFileSystemHandler } from \"@ricsam/isolate-fs\";\nexport type {\n FsHandle,\n FsOptions,\n FileSystemHandler,\n NodeFileSystemHandlerOptions,\n} from \"@ricsam/isolate-fs\";\n\nexport { setupPath } from \"@ricsam/isolate-path\";\nexport type { PathHandle, PathOptions } from \"@ricsam/isolate-path\";\n\nexport { setupTimers } from \"@ricsam/isolate-timers\";\nexport type { TimersHandle } from \"@ricsam/isolate-timers\";\n\nexport {\n setupTestEnvironment,\n runTests,\n hasTests,\n getTestCount,\n} from \"@ricsam/isolate-test-environment\";\nexport type {\n TestEnvironmentHandle,\n TestEnvironmentOptions,\n RunResults,\n TestResult,\n TestInfo,\n TestError,\n TestEvent,\n SuiteInfo,\n SuiteResult,\n} from \"@ricsam/isolate-test-environment\";\n\nexport {\n setupPlaywright,\n createPlaywrightHandler,\n} from \"@ricsam/isolate-playwright\";\nexport type {\n PlaywrightHandle,\n PlaywrightSetupOptions,\n PlaywrightCallback,\n PlaywrightEvent,\n NetworkRequestInfo,\n NetworkResponseInfo,\n BrowserConsoleLogEntry,\n} from \"@ricsam/isolate-playwright\";\n\nexport * from \"./internal.mjs\";\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": ";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAAA,cAEE;AAAA,cACA;AAAA,kBACA;AAAA;AAEF;AAg4BA,sBAAS;AAGT,yBAAS;AACT;AAAA;AAAA;AAUA,wBAAS;AAGT,0BAAS;AAGT,uBAAS;AAQT,oBAAS;AAQT,sBAAS;AAGT,wBAAS;AAGT;AAAA,0BACE;AAAA;AAAA;AAAA;AAAA;AAiBF;AAAA,qBACE;AAAA;AAAA;AAAA;AAaF;AA5sBA,IAAM,mBAAmB,IAAI;AAC7B,IAAI,iBAAiB;AAMrB,eAAe,oBAAoB,CACjC,SACA,iBAC6E;AAAA,EAC7E,MAAM,SAAS,QAAQ;AAAA,EAGvB,MA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BAAmB;AAAA,QAC3B,MAAM,kBAAkB,QAAQ;AAAA,MAClC;AAAA,MAGA,MAAM,QAAQ,YAAY,QAAQ;AAAA,MAClC,MAAM,QAAQ,iBAAiB,QAAQ;AAAA,MACvC,MAAM,QAAQ,IAAI,QAAQ;AAAA,MAC1B,MAAM,QAAQ,OAAO,QAAQ;AAAA,MAC7B,MAAM,QAAQ,QAAQ,QAAQ;AAAA,MAC9B,MAAM,QAAQ,MAAM,QAAQ;AAAA,MAC5B,MAAM,QAAQ,QAAQ,QAAQ;AAAA,MAC9B,MAAM,QAAQ,UAAU,QAAQ;AAAA,MAChC,MAAM,QAAQ,SAAS,QAAQ;AAAA,MAC/B,MAAM,QAAQ,MAAM,QAAQ;AAAA,MAG5B,MAAM,YAAY,MAAM;AAAA,MAGxB,MAAM,QAAQ,QAAQ;AAAA,MACtB,MAAM,QAAQ,QAAQ;AAAA;AAAA,EAE1B;AAAA;",
|
|
8
|
+
"debugId": "8F7A91864B6F594B64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/dist/mjs/internal.mjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
// @bun
|
|
2
1
|
// packages/runtime/src/internal.ts
|
|
3
2
|
import ivm from "isolated-vm";
|
|
4
3
|
import { setupCore } from "@ricsam/isolate-core";
|
|
@@ -50,4 +49,4 @@ export {
|
|
|
50
49
|
createInternalRuntime
|
|
51
50
|
};
|
|
52
51
|
|
|
53
|
-
//# debugId=
|
|
52
|
+
//# debugId=FB0D9A4AF0B7DEC464756E2164756E21
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Internal APIs for @ricsam/isolate-runtime\n *\n * These are not part of the public API and may change without notice.\n * Only used by @ricsam/isolate-daemon internally.\n */\n\nimport ivm from \"isolated-vm\";\nimport { setupCore } from \"@ricsam/isolate-core\";\nimport { setupConsole } from \"@ricsam/isolate-console\";\nimport { setupEncoding } from \"@ricsam/isolate-encoding\";\nimport { setupTimers } from \"@ricsam/isolate-timers\";\nimport { setupPath } from \"@ricsam/isolate-path\";\nimport { setupCrypto } from \"@ricsam/isolate-crypto\";\nimport { setupFetch } from \"@ricsam/isolate-fetch\";\nimport { setupFs } from \"@ricsam/isolate-fs\";\n\nimport type { ConsoleOptions, ConsoleHandle } from \"@ricsam/isolate-console\";\nimport type { FetchOptions, FetchHandle } from \"@ricsam/isolate-fetch\";\nimport type { FsOptions, FsHandle } from \"@ricsam/isolate-fs\";\nimport type { CoreHandle } from \"@ricsam/isolate-core\";\nimport type { EncodingHandle } from \"@ricsam/isolate-encoding\";\nimport type { TimersHandle } from \"@ricsam/isolate-timers\";\nimport type { PathHandle } from \"@ricsam/isolate-path\";\nimport type { CryptoHandle } from \"@ricsam/isolate-crypto\";\n\n/**\n * @internal Options for creating a legacy runtime.\n */\nexport interface InternalRuntimeOptions {\n memoryLimitMB?: number;\n console?: ConsoleOptions;\n fetch?: FetchOptions;\n fs?: FsOptions;\n /** Current working directory for path.resolve(). Defaults to \"/\" */\n cwd?: string;\n}\n\n/**\n * @internal Runtime handle with direct isolate/context access.\n * Used by isolate-daemon for low-level operations.\n */\nexport interface InternalRuntimeHandle {\n readonly isolate: ivm.Isolate;\n readonly context: ivm.Context;\n readonly fetch: FetchHandle;\n readonly timers: TimersHandle;\n readonly console: ConsoleHandle;\n dispose(): void;\n}\n\n/**\n * @internal Create a runtime with direct access to isolate and context.\n * This is for internal use by @ricsam/isolate-daemon only.\n */\nexport async function createInternalRuntime(\n options?: InternalRuntimeOptions\n): Promise<InternalRuntimeHandle> {\n const opts = options ?? {};\n\n const isolate = new ivm.Isolate({\n memoryLimit: opts.memoryLimitMB,\n });\n\n const context = await isolate.createContext();\n\n // Setup all APIs\n const handles: {\n core?: CoreHandle;\n console?: ConsoleHandle;\n encoding?: EncodingHandle;\n timers?: TimersHandle;\n path?: PathHandle;\n crypto?: CryptoHandle;\n fetch?: FetchHandle;\n fs?: FsHandle;\n } = {};\n\n handles.core = await setupCore(context);\n handles.console = await setupConsole(context, opts.console);\n handles.encoding = await setupEncoding(context);\n handles.timers = await setupTimers(context);\n handles.path = await setupPath(context, { cwd: opts.cwd });\n handles.crypto = await setupCrypto(context);\n handles.fetch = await setupFetch(context, opts.fetch);\n\n if (opts.fs) {\n handles.fs = await setupFs(context, opts.fs);\n }\n\n return {\n isolate,\n context,\n fetch: handles.fetch,\n timers: handles.timers!,\n console: handles.console!,\n dispose() {\n handles.fs?.dispose();\n handles.fetch?.dispose();\n handles.crypto?.dispose();\n handles.path?.dispose();\n handles.timers?.dispose();\n handles.encoding?.dispose();\n handles.console?.dispose();\n handles.core?.dispose();\n context.release();\n isolate.dispose();\n },\n };\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": ";AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAwCA,eAAsB,qBAAqB,CACzC,SACgC;AAAA,EAChC,MAAM,OAAO,WAAW,CAAC;AAAA,EAEzB,MAAM,UAAU,IAAI,IAAI,QAAQ;AAAA,IAC9B,aAAa,KAAK;AAAA,EACpB,CAAC;AAAA,EAED,MAAM,UAAU,MAAM,QAAQ,cAAc;AAAA,EAG5C,MAAM,UASF,CAAC;AAAA,EAEL,QAAQ,OAAO,MAAM,UAAU,OAAO;AAAA,EACtC,QAAQ,UAAU,MAAM,aAAa,SAAS,KAAK,OAAO;AAAA,EAC1D,QAAQ,WAAW,MAAM,cAAc,OAAO;AAAA,EAC9C,QAAQ,SAAS,MAAM,YAAY,OAAO;AAAA,EAC1C,QAAQ,OAAO,MAAM,UAAU,SAAS,EAAE,KAAK,KAAK,IAAI,CAAC;AAAA,EACzD,QAAQ,SAAS,MAAM,YAAY,OAAO;AAAA,EAC1C,QAAQ,QAAQ,MAAM,WAAW,SAAS,KAAK,KAAK;AAAA,EAEpD,IAAI,KAAK,IAAI;AAAA,IACX,QAAQ,KAAK,MAAM,QA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