* Execute code on the kernel and collect outputs.
(code: string, callbacks?: ExecutionCallbacks)
| 118 | * Execute code on the kernel and collect outputs. |
| 119 | */ |
| 120 | async execute(code: string, callbacks?: ExecutionCallbacks): Promise<ExecutionResult> { |
| 121 | if (!this.kernel) { |
| 122 | throw new Error('Kernel not connected. Call connect() first.') |
| 123 | } |
| 124 | |
| 125 | return new Promise((resolve, reject) => { |
| 126 | const outputs: IOutput[] = [] |
| 127 | let executionCount: number | null = null |
| 128 | |
| 129 | const future = this.kernel?.requestExecute({ code }) |
| 130 | if (!future) { |
| 131 | reject(new Error('Failed to execute code on kernel')) |
| 132 | return |
| 133 | } |
| 134 | |
| 135 | callbacks?.onStart?.() |
| 136 | |
| 137 | future.onIOPub = msg => { |
| 138 | const msgType = msg.header.msg_type |
| 139 | |
| 140 | if (msgType === 'execute_input') { |
| 141 | executionCount = (msg.content as { execution_count?: number }).execution_count ?? null |
| 142 | } else if (['stream', 'execute_result', 'display_data', 'error'].includes(msgType)) { |
| 143 | const output = this.messageToOutput(msg) |
| 144 | outputs.push(output) |
| 145 | callbacks?.onOutput?.(output) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | future.done |
| 150 | .then(() => { |
| 151 | const hasError = outputs.some(o => o.output_type === 'error') |
| 152 | const result: ExecutionResult = { |
| 153 | success: !hasError, |
| 154 | outputs, |
| 155 | executionCount, |
| 156 | } |
| 157 | callbacks?.onDone?.(result) |
| 158 | resolve(result) |
| 159 | }) |
| 160 | .catch(reject) |
| 161 | .finally(() => future?.dispose()) |
| 162 | }) |
| 163 | } |
| 164 | |
| 165 | /** |
| 166 | * Disconnect from the kernel and clean up resources. |
no test coverage detected