| 26 | } |
| 27 | |
| 28 | async execute<T = unknown>(code: string): Promise<ExecutionResult<T>> { |
| 29 | if (this.disposed) { |
| 30 | return { |
| 31 | success: false, |
| 32 | error: { |
| 33 | name: 'DisposedError', |
| 34 | message: 'Context has been disposed', |
| 35 | }, |
| 36 | logs: [], |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // Clear previous logs |
| 41 | this.logs.length = 0 |
| 42 | |
| 43 | try { |
| 44 | // Wrap user code in async IIFE |
| 45 | const wrappedCode = wrapCode(code) |
| 46 | |
| 47 | // Compile the script |
| 48 | const script = await this.isolate.compileScript(wrappedCode) |
| 49 | |
| 50 | // Run with timeout |
| 51 | const result = await script.run(this.context, { |
| 52 | timeout: this.timeout, |
| 53 | promise: true, |
| 54 | }) |
| 55 | |
| 56 | // Parse result if it's a JSON string (from our serialization) |
| 57 | let parsedResult: T |
| 58 | if (typeof result === 'string') { |
| 59 | try { |
| 60 | parsedResult = JSON.parse(result) as T |
| 61 | } catch { |
| 62 | parsedResult = result as T |
| 63 | } |
| 64 | } else { |
| 65 | parsedResult = result as T |
| 66 | } |
| 67 | |
| 68 | return { |
| 69 | success: true, |
| 70 | value: parsedResult, |
| 71 | logs: [...this.logs], |
| 72 | } |
| 73 | } catch (error) { |
| 74 | return { |
| 75 | success: false, |
| 76 | error: normalizeError(error), |
| 77 | logs: [...this.logs], |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | dispose(): Promise<void> { |
| 83 | if (!this.disposed) { |