Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

error-normalizer.ts

107 lines2.7 KB

1import type { NormalizedError } from '@tanstack/ai-code-mode'
2​
3const MEMORY_LIMIT_ERROR = 'MemoryLimitError'
4const STACK_OVERFLOW_ERROR = 'StackOverflowError'
5export const TIMEOUT_ERROR = 'TimeoutError'
6​
7/**
8 * Whether this normalized error indicates the QuickJS VM should not be reused
9 * (memory or stack limit exceeded). Timeouts are also terminal but take a
10 * separate release path (see `releaseAfterTimeout` in isolate-context).
11 */
12export function isFatalQuickJSLimitError(error: NormalizedError): boolean {
13 return (
14 error.name === MEMORY_LIMIT_ERROR || error.name === STACK_OVERFLOW_ERROR
15 )
17​
18/**
19 * Normalize various error types into a consistent format
20 */
21export function normalizeError(error: unknown): NormalizedError {
22 if (error instanceof Error) {
23 const msg = error.message
24 const lower = msg.toLowerCase()
25​
26 if (
27 lower.includes('out of memory') ||
28 lower.includes('memory alloc') ||
29 (error.name === 'InternalError' && lower.includes('memory'))
30 ) {
31 return {
32 name: MEMORY_LIMIT_ERROR,
33 message: 'Code execution exceeded memory limit',
34 stack: error.stack,
35 }
36 }
37​
38 if (lower.includes('stack overflow')) {
39 return {
40 name: STACK_OVERFLOW_ERROR,
41 message: 'Code execution exceeded stack size limit',
42 stack: error.stack,
43 }
44 }
45​
46 // QuickJS reports a fired interrupt handler as "InternalError: interrupted".
47 if (error.name === 'InternalError' && lower.includes('interrupted')) {
48 return {
49 name: TIMEOUT_ERROR,
50 message: 'Code execution timed out',
51 stack: error.stack,
52 }
53 }
54​
55 if (error.name === 'RuntimeError' && lower.includes('unreachable')) {
56 return {
57 name: 'WasmRuntimeError',
58 message: msg || 'WebAssembly runtime error',
59 stack: error.stack,
60 }
61 }
62​
63 return {
64 name: error.name,
65 message: error.message,
66 stack: error.stack,
67 }
68 }
69​
70 if (typeof error === 'string') {
71 return {
72 name: 'Error',
73 message: error,
74 }
75 }
76​
77 if (typeof error === 'object' && error !== null) {
78 const errObj = error as Record<string, unknown>
79 const name = String(errObj.name || 'Error')
80 const message = String(errObj.message || 'Unknown error')
81 if (
82 name === 'InternalError' &&
83 message.toLowerCase().includes('interrupted')
84 ) {
85 return {
86 name: TIMEOUT_ERROR,
87 message: 'Code execution timed out',
88 ...(errObj['stack'] !== undefined && {
89 stack: String(errObj['stack']),
90 }),
91 }
92 }
93​
94 return {
95 name,
96 message,
97 ...(errObj['stack'] !== undefined && {
98 stack: String(errObj['stack']),
99 }),
100 }
101 }
102​
103 return {
104 name: 'UnknownError',
105 message: String(error),
106 }