(output: unknown, options?: ExtractOutputTextOptions)
| 12 | * Returns null if the output type is unrecognized or has no textual representation. |
| 13 | */ |
| 14 | export function extractOutputText(output: unknown, options?: ExtractOutputTextOptions): string | null { |
| 15 | const outResult = unknownObjectSchema.safeParse(output) |
| 16 | if (!outResult.success) return null |
| 17 | const out = outResult.data |
| 18 | |
| 19 | if (out.output_type === 'stream' && typeof out.text === 'string') { |
| 20 | return out.text |
| 21 | } |
| 22 | |
| 23 | if (out.output_type === 'execute_result' || out.output_type === 'display_data') { |
| 24 | const dataResult = unknownObjectSchema.safeParse(out.data) |
| 25 | const data = dataResult.success ? dataResult.data : undefined |
| 26 | if (data?.['text/plain']) { |
| 27 | return String(data['text/plain']) |
| 28 | } |
| 29 | if (data?.['text/html']) { |
| 30 | return '[HTML output]' |
| 31 | } |
| 32 | if (data?.['image/png'] || data?.['image/jpeg']) { |
| 33 | return '[Image output]' |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | if (out.output_type === 'error') { |
| 38 | const ename = String(out.ename || 'Error') |
| 39 | const evalue = String(out.evalue || '') |
| 40 | let text = `Error: ${ename}: ${evalue}` |
| 41 | if (options?.includeTraceback && Array.isArray(out.traceback)) { |
| 42 | text += |
| 43 | '\n' + |
| 44 | (out.traceback as string[]) |
| 45 | // biome-ignore lint/suspicious/noControlCharactersInRegex: strip ANSI escape sequences from traceback |
| 46 | .map(line => line.replace(/\x1b\[[0-9;]*m/g, '')) |
| 47 | .join('\n') |
| 48 | } |
| 49 | return text |
| 50 | } |
| 51 | |
| 52 | return null |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Extract human-readable text from an array of Jupyter-style output objects. |
no outgoing calls
no test coverage detected