(
config: QuickJSIsolateDriverConfig = {},
)
| 69 | * ``` |
| 70 | */ |
| 71 | export function createQuickJSIsolateDriver( |
| 72 | config: QuickJSIsolateDriverConfig = {}, |
| 73 | ): IsolateDriver { |
| 74 | const defaultTimeout = config.timeout ?? 30000 |
| 75 | const defaultMemoryLimit = config.memoryLimit ?? DEFAULT_MEMORY_LIMIT_MB |
| 76 | const defaultMaxStackSize = |
| 77 | config.maxStackSize ?? DEFAULT_MAX_STACK_SIZE_BYTES |
| 78 | |
| 79 | return { |
| 80 | async createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> { |
| 81 | const timeout = isolateConfig.timeout ?? defaultTimeout |
| 82 | const memoryLimitMb = isolateConfig.memoryLimit ?? defaultMemoryLimit |
| 83 | const maxStackSizeBytes = defaultMaxStackSize |
| 84 | |
| 85 | // Create async QuickJS context (supports async host functions) |
| 86 | const vm = await newAsyncContext() |
| 87 | |
| 88 | // Enforce heap and stack limits so OOM/stack overflow surface as JS errors |
| 89 | // instead of growing WASM memory until the host process OOMs. |
| 90 | vm.runtime.setMemoryLimit(memoryLimitMb * 1024 * 1024) |
| 91 | vm.runtime.setMaxStackSize(maxStackSizeBytes) |
| 92 | |
| 93 | // Set up console.log capture |
| 94 | const logs: Array<string> = [] |
| 95 | |
| 96 | // Create console object |
| 97 | const consoleObj = vm.newObject() |
| 98 | |
| 99 | // Helper to create console methods |
| 100 | const createConsoleMethod = (prefix: string) => { |
| 101 | return vm.newFunction(`console.${prefix}`, (...args) => { |
| 102 | const parts = args.map((arg) => { |
| 103 | const str = vm.getString(arg) |
| 104 | return str |
| 105 | }) |
| 106 | const msg = prefix ? `${prefix}: ${parts.join(' ')}` : parts.join(' ') |
| 107 | logs.push(msg) |
| 108 | }) |
| 109 | } |
| 110 | |
| 111 | const logFn = createConsoleMethod('') |
| 112 | const errorFn = createConsoleMethod('ERROR') |
| 113 | const warnFn = createConsoleMethod('WARN') |
| 114 | const infoFn = createConsoleMethod('INFO') |
| 115 | |
| 116 | vm.setProp(consoleObj, 'log', logFn) |
| 117 | vm.setProp(consoleObj, 'error', errorFn) |
| 118 | vm.setProp(consoleObj, 'warn', warnFn) |
| 119 | vm.setProp(consoleObj, 'info', infoFn) |
| 120 | vm.setProp(vm.global, 'console', consoleObj) |
| 121 | |
| 122 | // Dispose console handles |
| 123 | logFn.dispose() |
| 124 | errorFn.dispose() |
| 125 | warnFn.dispose() |
| 126 | infoFn.dispose() |
| 127 | consoleObj.dispose() |
| 128 |
no outgoing calls