forked from CodebuffAI/codebuff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.ts
More file actions
352 lines (329 loc) · 10.1 KB
/
Copy patherror.ts
File metadata and controls
352 lines (329 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
export type ErrorOr<T, E extends ErrorObject = ErrorObject> =
| Success<T>
| Failure<E>
export type Success<T> = {
success: true
value: T
}
export type Failure<E extends ErrorObject = ErrorObject> = {
success: false
error: E
}
/**
* Result type for prompt functions that can be aborted.
* Provides rich semantics to distinguish between successful completion and user abort.
*
* ## When to use `PromptResult<T>` vs `ErrorOr<T>`
*
* Use `PromptResult<T>` when:
* - The operation can be cancelled by the user (via AbortSignal)
* - An abort is an expected outcome, not an error
* - You need to distinguish between errors (which might trigger fallbacks) and
* user-initiated aborts (which should propagate immediately)
*
* Use `ErrorOr<T>` when:
* - The operation can fail with an error that should be handled
* - There's no concept of user-initiated abort
* - You want to return error details rather than throw
*
* ## Abort handling patterns
*
* 1. **Check and return early** - For graceful handling where abort means "stop, no error":
* ```ts
* const result = await promptAiSdk({ ... })
* if (result.aborted) return // or return null, false, etc.
* doSomething(result.value)
* ```
*
* 2. **Unwrap and throw** - For propagating aborts as exceptions:
* ```ts
* const value = unwrapPromptResult(await promptAiSdk({ ... }))
* // Throws if aborted, callers should use isAbortError() in catch blocks
* ```
*
* 3. **Rethrow in catch blocks** - Prevent swallowing abort errors:
* ```ts
* try {
* await someOperation()
* } catch (error) {
* if (isAbortError(error)) throw error // Don't swallow aborts
* // Handle other errors
* }
* ```
*/
export type PromptResult<T> = PromptSuccess<T> | PromptAborted
export type PromptSuccess<T> = {
aborted: false
value: T
}
export type PromptAborted = {
aborted: true
reason?: string
}
export type ErrorObject = {
name: string
message: string
stack?: string
/** HTTP status code from error.status (used by some libraries) */
status?: number
/** HTTP status code from error.statusCode (used by AI SDK and Codebuff errors) */
statusCode?: number
/** Optional machine-friendly error code, if available */
code?: string
/** Optional raw error object */
rawError?: string
/** Response body from API errors (AI SDK APICallError) */
responseBody?: string
/** URL that was called (API errors) */
url?: string
/** Whether the error is retryable (API errors) */
isRetryable?: boolean
/** Request body values that were sent (API errors) - stringified for safety */
requestBodyValues?: string
/** Cause of the error, if nested */
cause?: ErrorObject
}
export function success<T>(value: T): Success<T> {
return {
success: true,
value,
}
}
export function failure(error: unknown): Failure<ErrorObject> {
return {
success: false,
error: getErrorObject(error),
}
}
/**
* Create a successful prompt result.
*/
export function promptSuccess<T>(value: T): PromptSuccess<T> {
return {
aborted: false,
value,
}
}
/**
* Create an aborted prompt result.
*/
export function promptAborted(reason?: string): PromptAborted {
return {
aborted: true,
...(reason !== undefined && { reason }),
}
}
/**
* Standard error message for aborted requests.
* Use this constant when throwing abort errors to ensure consistency.
*/
export const ABORT_ERROR_MESSAGE = 'Request aborted'
/**
* Custom error class for abort errors.
* Use this class instead of generic Error for abort errors to ensure
* robust detection via isAbortError() (checks error.name === 'AbortError').
*/
export class AbortError extends Error {
constructor(reason?: string) {
super(reason ? `${ABORT_ERROR_MESSAGE}: ${reason}` : ABORT_ERROR_MESSAGE)
this.name = 'AbortError'
}
}
/**
* Check if an error is an abort error.
* Use this helper to detect abort errors in catch blocks.
*
* Detects both:
* - Errors with message starting with 'Request aborted' (thrown by our code via AbortError)
* - Native AbortError (thrown by fetch/AI SDK when AbortSignal is triggered)
*/
export function isAbortError(error: unknown): boolean {
if (!(error instanceof Error)) {
return false
}
// Check for our custom abort error message:
// - Exact match: 'Request aborted'
// - With reason: 'Request aborted: <reason>' (from AbortError class)
if (
error.message === ABORT_ERROR_MESSAGE ||
error.message.startsWith(`${ABORT_ERROR_MESSAGE}: `)
) {
return true
}
// Check for native AbortError (DOMException or Error with name 'AbortError')
// This is thrown by fetch, AI SDK, and other web APIs when AbortSignal is triggered
if (error.name === 'AbortError') {
return true
}
return false
}
/**
* Unwrap a PromptResult, returning the value if successful or throwing if aborted.
*
* Use this helper for consistent abort handling when you want aborts to propagate
* as exceptions. Callers should use `isAbortError()` in catch blocks to detect
* and handle abort errors appropriately (e.g., rethrow instead of logging as errors).
*
* @throws {AbortError} When result.aborted is true.
*/
export function unwrapPromptResult<T>(result: PromptResult<T>): T {
if (result.aborted) {
throw new AbortError(result.reason)
}
return result.value
}
/**
* Parses a JSON response body string from an API error to extract structured error details.
* Used to extract machine-readable error codes and human-readable messages from API responses
* (e.g., AI SDK's APICallError includes a responseBody with the server's JSON response).
*
* Returns extracted fields, or an empty object if the responseBody is not a valid JSON string
* with the expected shape.
*/
export function parseApiErrorResponseBody(responseBody: unknown): {
errorCode?: string
message?: string
countryCode?: string
countryBlockReason?: string
ipPrivacySignals?: string[]
} {
if (typeof responseBody !== 'string') return {}
try {
const parsed: unknown = JSON.parse(responseBody)
if (!parsed || typeof parsed !== 'object') return {}
const result: {
errorCode?: string
message?: string
countryCode?: string
countryBlockReason?: string
ipPrivacySignals?: string[]
} = {}
if (
'error' in parsed &&
typeof (parsed as { error: unknown }).error === 'string'
) {
result.errorCode = (parsed as { error: string }).error
}
if (
'message' in parsed &&
typeof (parsed as { message: unknown }).message === 'string'
) {
result.message = (parsed as { message: string }).message
}
if (
'countryCode' in parsed &&
typeof (parsed as { countryCode: unknown }).countryCode === 'string'
) {
result.countryCode = (parsed as { countryCode: string }).countryCode
}
if (
'countryBlockReason' in parsed &&
typeof (parsed as { countryBlockReason: unknown }).countryBlockReason ===
'string'
) {
result.countryBlockReason = (
parsed as { countryBlockReason: string }
).countryBlockReason
}
if ('ipPrivacySignals' in parsed) {
const signals = (parsed as { ipPrivacySignals: unknown }).ipPrivacySignals
if (Array.isArray(signals)) {
result.ipPrivacySignals = signals.filter(
(signal): signal is string => typeof signal === 'string',
)
}
}
return result
} catch {
return {}
}
}
// Extended error properties that various libraries add to Error objects
interface ExtendedErrorProperties {
status?: number
statusCode?: number
code?: string
// API error properties (AI SDK APICallError, etc.)
responseBody?: string
url?: string
isRetryable?: boolean
requestBodyValues?: Record<string, unknown>
cause?: unknown
}
/**
* Safely stringify an object, handling circular references and large objects.
*/
function safeStringify(value: unknown, maxLength = 10000): string | undefined {
if (value === undefined || value === null) return undefined
if (typeof value === 'string') return value.slice(0, maxLength)
try {
const seen = new WeakSet()
const str = JSON.stringify(
value,
(_, val) => {
if (typeof val === 'object' && val !== null) {
if (seen.has(val)) return '[Circular]'
seen.add(val)
}
return val
},
2,
)
return str?.slice(0, maxLength)
} catch {
return '[Unable to stringify]'
}
}
export function getErrorObject(
error: unknown,
options: { includeRawError?: boolean } = {},
): ErrorObject {
if (error instanceof Error) {
const extError = error as Error & Partial<ExtendedErrorProperties>
// Extract responseBody - could be string or object
let responseBody: string | undefined
if (extError.responseBody !== undefined) {
responseBody = safeStringify(extError.responseBody)
}
// Extract requestBodyValues - typically an object, stringify for logging
let requestBodyValues: string | undefined
if (
extError.requestBodyValues !== undefined &&
typeof extError.requestBodyValues === 'object'
) {
requestBodyValues = safeStringify(extError.requestBodyValues)
}
// Extract cause - recursively convert to ErrorObject if present
let cause: ErrorObject | undefined
if (extError.cause !== undefined) {
cause = getErrorObject(extError.cause, options)
}
return {
name: error.name,
message: error.message,
stack: error.stack,
status: typeof extError.status === 'number' ? extError.status : undefined,
statusCode:
typeof extError.statusCode === 'number'
? extError.statusCode
: undefined,
code: typeof extError.code === 'string' ? extError.code : undefined,
rawError: options.includeRawError
? safeStringify(error)
: undefined,
// API error fields
responseBody,
url: typeof extError.url === 'string' ? extError.url : undefined,
isRetryable:
typeof extError.isRetryable === 'boolean'
? extError.isRetryable
: undefined,
requestBodyValues,
cause,
}
}
return {
name: 'Error',
message: `${error}`,
}
}