@providerprotocol/ai 0.0.22 → 0.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +188 -6
- package/dist/anthropic/index.d.ts +1 -1
- package/dist/anthropic/index.js +30 -25
- package/dist/anthropic/index.js.map +1 -1
- package/dist/{chunk-7WYBJPJJ.js → chunk-55X3W2MN.js} +4 -3
- package/dist/chunk-55X3W2MN.js.map +1 -0
- package/dist/chunk-73IIE3QT.js +120 -0
- package/dist/chunk-73IIE3QT.js.map +1 -0
- package/dist/{chunk-M4BMM5IB.js → chunk-MF5ETY5O.js} +13 -4
- package/dist/chunk-MF5ETY5O.js.map +1 -0
- package/dist/{chunk-RFWLEFAB.js → chunk-QNJO7DSD.js} +61 -16
- package/dist/chunk-QNJO7DSD.js.map +1 -0
- package/dist/{chunk-RS7C25LS.js → chunk-SBCATNHA.js} +9 -5
- package/dist/chunk-SBCATNHA.js.map +1 -0
- package/dist/{chunk-I2VHCGQE.js → chunk-Z6DKC37J.js} +6 -5
- package/dist/chunk-Z6DKC37J.js.map +1 -0
- package/dist/google/index.d.ts +3 -2
- package/dist/google/index.js +38 -33
- package/dist/google/index.js.map +1 -1
- package/dist/http/index.d.ts +2 -2
- package/dist/http/index.js +3 -3
- package/dist/index.d.ts +8 -6
- package/dist/index.js +81 -121
- package/dist/index.js.map +1 -1
- package/dist/ollama/index.d.ts +5 -2
- package/dist/ollama/index.js +34 -29
- package/dist/ollama/index.js.map +1 -1
- package/dist/openai/index.d.ts +1 -1
- package/dist/openai/index.js +58 -53
- package/dist/openai/index.js.map +1 -1
- package/dist/openrouter/index.d.ts +1 -1
- package/dist/openrouter/index.js +57 -52
- package/dist/openrouter/index.js.map +1 -1
- package/dist/{provider-DWEAzeM5.d.ts → provider-DR1yins0.d.ts} +148 -52
- package/dist/proxy/index.d.ts +2 -2
- package/dist/proxy/index.js +11 -9
- package/dist/proxy/index.js.map +1 -1
- package/dist/{retry-DmPmqZL6.d.ts → retry-DJiqAslw.d.ts} +1 -1
- package/dist/{stream-DbkLOIbJ.d.ts → stream-BuTrqt_j.d.ts} +90 -38
- package/dist/xai/index.d.ts +1 -1
- package/dist/xai/index.js +71 -66
- package/dist/xai/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-7WYBJPJJ.js.map +0 -1
- package/dist/chunk-I2VHCGQE.js.map +0 -1
- package/dist/chunk-M4BMM5IB.js.map +0 -1
- package/dist/chunk-RFWLEFAB.js.map +0 -1
- package/dist/chunk-RS7C25LS.js.map +0 -1
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// src/types/stream.ts
|
|
2
|
+
var StreamEventType = {
|
|
3
|
+
/** Incremental text output */
|
|
4
|
+
TextDelta: "text_delta",
|
|
5
|
+
/** Incremental reasoning/thinking output */
|
|
6
|
+
ReasoningDelta: "reasoning_delta",
|
|
7
|
+
/** Incremental image data */
|
|
8
|
+
ImageDelta: "image_delta",
|
|
9
|
+
/** Incremental audio data */
|
|
10
|
+
AudioDelta: "audio_delta",
|
|
11
|
+
/** Incremental video data */
|
|
12
|
+
VideoDelta: "video_delta",
|
|
13
|
+
/** Incremental tool call data (arguments being streamed) */
|
|
14
|
+
ToolCallDelta: "tool_call_delta",
|
|
15
|
+
/** Tool execution has started (may be emitted after completion in some implementations) */
|
|
16
|
+
ToolExecutionStart: "tool_execution_start",
|
|
17
|
+
/** Tool execution has completed */
|
|
18
|
+
ToolExecutionEnd: "tool_execution_end",
|
|
19
|
+
/** Beginning of a message */
|
|
20
|
+
MessageStart: "message_start",
|
|
21
|
+
/** End of a message */
|
|
22
|
+
MessageStop: "message_stop",
|
|
23
|
+
/** Beginning of a content block */
|
|
24
|
+
ContentBlockStart: "content_block_start",
|
|
25
|
+
/** End of a content block */
|
|
26
|
+
ContentBlockStop: "content_block_stop"
|
|
27
|
+
};
|
|
28
|
+
function createStreamResult(generator, turnPromiseOrFactory, abortController) {
|
|
29
|
+
let cachedTurn = null;
|
|
30
|
+
const getTurn = () => {
|
|
31
|
+
if (typeof turnPromiseOrFactory === "function") {
|
|
32
|
+
if (!cachedTurn) {
|
|
33
|
+
cachedTurn = turnPromiseOrFactory();
|
|
34
|
+
}
|
|
35
|
+
return cachedTurn;
|
|
36
|
+
}
|
|
37
|
+
return turnPromiseOrFactory;
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
[Symbol.asyncIterator]() {
|
|
41
|
+
return generator;
|
|
42
|
+
},
|
|
43
|
+
get turn() {
|
|
44
|
+
return getTurn();
|
|
45
|
+
},
|
|
46
|
+
abort() {
|
|
47
|
+
abortController.abort();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function textDelta(text, index = 0) {
|
|
52
|
+
return {
|
|
53
|
+
type: StreamEventType.TextDelta,
|
|
54
|
+
index,
|
|
55
|
+
delta: { text }
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function toolCallDelta(toolCallId, toolName, argumentsJson, index = 0) {
|
|
59
|
+
return {
|
|
60
|
+
type: StreamEventType.ToolCallDelta,
|
|
61
|
+
index,
|
|
62
|
+
delta: { toolCallId, toolName, argumentsJson }
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function messageStart() {
|
|
66
|
+
return {
|
|
67
|
+
type: StreamEventType.MessageStart,
|
|
68
|
+
index: 0,
|
|
69
|
+
delta: {}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function messageStop() {
|
|
73
|
+
return {
|
|
74
|
+
type: StreamEventType.MessageStop,
|
|
75
|
+
index: 0,
|
|
76
|
+
delta: {}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function contentBlockStart(index) {
|
|
80
|
+
return {
|
|
81
|
+
type: StreamEventType.ContentBlockStart,
|
|
82
|
+
index,
|
|
83
|
+
delta: {}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function contentBlockStop(index) {
|
|
87
|
+
return {
|
|
88
|
+
type: StreamEventType.ContentBlockStop,
|
|
89
|
+
index,
|
|
90
|
+
delta: {}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function toolExecutionStart(toolCallId, toolName, timestamp, index = 0) {
|
|
94
|
+
return {
|
|
95
|
+
type: StreamEventType.ToolExecutionStart,
|
|
96
|
+
index,
|
|
97
|
+
delta: { toolCallId, toolName, timestamp }
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function toolExecutionEnd(toolCallId, toolName, result, isError, timestamp, index = 0) {
|
|
101
|
+
return {
|
|
102
|
+
type: StreamEventType.ToolExecutionEnd,
|
|
103
|
+
index,
|
|
104
|
+
delta: { toolCallId, toolName, result, isError, timestamp }
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export {
|
|
109
|
+
StreamEventType,
|
|
110
|
+
createStreamResult,
|
|
111
|
+
textDelta,
|
|
112
|
+
toolCallDelta,
|
|
113
|
+
messageStart,
|
|
114
|
+
messageStop,
|
|
115
|
+
contentBlockStart,
|
|
116
|
+
contentBlockStop,
|
|
117
|
+
toolExecutionStart,
|
|
118
|
+
toolExecutionEnd
|
|
119
|
+
};
|
|
120
|
+
//# sourceMappingURL=chunk-73IIE3QT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types/stream.ts"],"sourcesContent":["/**\n * @fileoverview Streaming types for real-time LLM responses.\n *\n * Defines the event types and interfaces for streaming LLM inference,\n * including text deltas, tool call deltas, and control events.\n *\n * @module types/stream\n */\n\nimport type { Turn } from './turn.ts';\n\n/**\n * Stream event type constants.\n *\n * Use these constants instead of raw strings for type-safe event handling:\n *\n * @example\n * ```typescript\n * import { StreamEventType } from 'upp';\n *\n * for await (const event of stream) {\n * if (event.type === StreamEventType.TextDelta) {\n * process.stdout.write(event.delta.text ?? '');\n * }\n * }\n * ```\n */\nexport const StreamEventType = {\n /** Incremental text output */\n TextDelta: 'text_delta',\n /** Incremental reasoning/thinking output */\n ReasoningDelta: 'reasoning_delta',\n /** Incremental image data */\n ImageDelta: 'image_delta',\n /** Incremental audio data */\n AudioDelta: 'audio_delta',\n /** Incremental video data */\n VideoDelta: 'video_delta',\n /** Incremental tool call data (arguments being streamed) */\n ToolCallDelta: 'tool_call_delta',\n /** Tool execution has started (may be emitted after completion in some implementations) */\n ToolExecutionStart: 'tool_execution_start',\n /** Tool execution has completed */\n ToolExecutionEnd: 'tool_execution_end',\n /** Beginning of a message */\n MessageStart: 'message_start',\n /** End of a message */\n MessageStop: 'message_stop',\n /** Beginning of a content block */\n ContentBlockStart: 'content_block_start',\n /** End of a content block */\n ContentBlockStop: 'content_block_stop',\n} as const;\n\n/**\n * Stream event type discriminator union.\n *\n * This type is derived from {@link StreamEventType} constants. Use `StreamEventType.TextDelta`\n * for constants or `type MyType = StreamEventType` for type annotations.\n */\nexport type StreamEventType = (typeof StreamEventType)[keyof typeof StreamEventType];\n\n/**\n * Event delta data payload.\n *\n * Contains the type-specific data for a streaming event.\n * Different fields are populated depending on the event type.\n */\nexport interface EventDelta {\n /** Incremental text content (for text_delta, reasoning_delta) */\n text?: string;\n\n /** Incremental binary data (for image_delta, audio_delta, video_delta) */\n data?: Uint8Array;\n\n /** Tool call identifier (for tool_call_delta, tool_execution_start/end) */\n toolCallId?: string;\n\n /** Tool name (for tool_call_delta, tool_execution_start/end) */\n toolName?: string;\n\n /** Incremental JSON arguments string (for tool_call_delta) */\n argumentsJson?: string;\n\n /** Tool execution result (for tool_execution_end) */\n result?: unknown;\n\n /** Whether tool execution resulted in an error (for tool_execution_end) */\n isError?: boolean;\n\n /** Timestamp in milliseconds (for tool_execution_start/end) */\n timestamp?: number;\n}\n\n/**\n * A single streaming event from the LLM.\n *\n * Events are emitted in order as the model generates output,\n * allowing for real-time display of responses.\n *\n * @example\n * ```typescript\n * import { StreamEventType } from 'upp';\n *\n * for await (const event of stream) {\n * if (event.type === StreamEventType.TextDelta) {\n * process.stdout.write(event.delta.text ?? '');\n * } else if (event.type === StreamEventType.ToolCallDelta) {\n * console.log('Tool:', event.delta.toolName);\n * }\n * }\n * ```\n */\nexport interface StreamEvent {\n /** Event type discriminator */\n type: StreamEventType;\n\n /** Index of the content block this event belongs to */\n index: number;\n\n /** Event-specific data payload */\n delta: EventDelta;\n}\n\n/**\n * Stream result - an async iterable that also provides the final turn.\n *\n * Allows consuming streaming events while also awaiting the complete\n * Turn result after streaming finishes.\n *\n * @typeParam TData - Type of the structured output data\n *\n * @example\n * ```typescript\n * import { StreamEventType } from 'upp';\n *\n * const stream = instance.stream('Tell me a story');\n *\n * // Consume streaming events\n * for await (const event of stream) {\n * if (event.type === StreamEventType.TextDelta) {\n * process.stdout.write(event.delta.text ?? '');\n * }\n * }\n *\n * // Get the complete turn after streaming\n * const turn = await stream.turn;\n * console.log('\\n\\nTokens used:', turn.usage.totalTokens);\n * ```\n */\nexport interface StreamResult<TData = unknown>\n extends AsyncIterable<StreamEvent> {\n /**\n * Promise that resolves to the complete Turn after streaming finishes.\n * Rejects if the stream is aborted or terminated early.\n */\n readonly turn: Promise<Turn<TData>>;\n\n /**\n * Aborts the stream, stopping further events and cancelling the request.\n * This will cause {@link StreamResult.turn} to reject.\n */\n abort(): void;\n}\n\n/**\n * Creates a StreamResult from an async generator and completion promise.\n *\n * @typeParam TData - Type of the structured output data\n * @param generator - Async generator that yields stream events\n * @param turnPromiseOrFactory - Promise or factory that resolves to the complete Turn\n * @param abortController - Controller for aborting the stream\n * @returns A StreamResult that can be iterated and awaited\n *\n * @example\n * ```typescript\n * const abortController = new AbortController();\n * const stream = createStreamResult(\n * eventGenerator(),\n * turnPromise,\n * abortController\n * );\n * ```\n */\nexport function createStreamResult<TData = unknown>(\n generator: AsyncGenerator<StreamEvent, void, unknown>,\n turnPromiseOrFactory: Promise<Turn<TData>> | (() => Promise<Turn<TData>>),\n abortController: AbortController\n): StreamResult<TData> {\n let cachedTurn: Promise<Turn<TData>> | null = null;\n\n const getTurn = (): Promise<Turn<TData>> => {\n // Lazily build the turn promise to avoid work (or rejections) when unused.\n if (typeof turnPromiseOrFactory === 'function') {\n if (!cachedTurn) {\n cachedTurn = turnPromiseOrFactory();\n }\n return cachedTurn;\n }\n\n return turnPromiseOrFactory;\n };\n\n return {\n [Symbol.asyncIterator]() {\n return generator;\n },\n get turn() {\n return getTurn();\n },\n abort() {\n abortController.abort();\n },\n };\n}\n\n/**\n * Creates a text delta stream event.\n *\n * @param text - The incremental text content\n * @param index - Content block index (default: 0)\n * @returns A text_delta StreamEvent\n */\nexport function textDelta(text: string, index = 0): StreamEvent {\n return {\n type: StreamEventType.TextDelta,\n index,\n delta: { text },\n };\n}\n\n/**\n * Creates a tool call delta stream event.\n *\n * @param toolCallId - Unique identifier for the tool call\n * @param toolName - Name of the tool being called\n * @param argumentsJson - Incremental JSON arguments string\n * @param index - Content block index (default: 0)\n * @returns A tool_call_delta StreamEvent\n */\nexport function toolCallDelta(\n toolCallId: string,\n toolName: string,\n argumentsJson: string,\n index = 0\n): StreamEvent {\n return {\n type: StreamEventType.ToolCallDelta,\n index,\n delta: { toolCallId, toolName, argumentsJson },\n };\n}\n\n/**\n * Creates a message start stream event.\n *\n * @returns A message_start StreamEvent\n */\nexport function messageStart(): StreamEvent {\n return {\n type: StreamEventType.MessageStart,\n index: 0,\n delta: {},\n };\n}\n\n/**\n * Creates a message stop stream event.\n *\n * @returns A message_stop StreamEvent\n */\nexport function messageStop(): StreamEvent {\n return {\n type: StreamEventType.MessageStop,\n index: 0,\n delta: {},\n };\n}\n\n/**\n * Creates a content block start stream event.\n *\n * @param index - The content block index starting\n * @returns A content_block_start StreamEvent\n */\nexport function contentBlockStart(index: number): StreamEvent {\n return {\n type: StreamEventType.ContentBlockStart,\n index,\n delta: {},\n };\n}\n\n/**\n * Creates a content block stop stream event.\n *\n * @param index - The content block index stopping\n * @returns A content_block_stop StreamEvent\n */\nexport function contentBlockStop(index: number): StreamEvent {\n return {\n type: StreamEventType.ContentBlockStop,\n index,\n delta: {},\n };\n}\n\n/**\n * Creates a tool execution start stream event.\n *\n * @param toolCallId - Unique identifier for the tool call\n * @param toolName - Name of the tool being executed\n * @param timestamp - Start timestamp in milliseconds\n * @param index - Content block index (default: 0)\n * @returns A tool_execution_start StreamEvent\n */\nexport function toolExecutionStart(\n toolCallId: string,\n toolName: string,\n timestamp: number,\n index = 0\n): StreamEvent {\n return {\n type: StreamEventType.ToolExecutionStart,\n index,\n delta: { toolCallId, toolName, timestamp },\n };\n}\n\n/**\n * Creates a tool execution end stream event.\n *\n * @param toolCallId - Unique identifier for the tool call\n * @param toolName - Name of the tool that was executed\n * @param result - The result from the tool execution\n * @param isError - Whether the execution resulted in an error\n * @param timestamp - End timestamp in milliseconds\n * @param index - Content block index (default: 0)\n * @returns A tool_execution_end StreamEvent\n */\nexport function toolExecutionEnd(\n toolCallId: string,\n toolName: string,\n result: unknown,\n isError: boolean,\n timestamp: number,\n index = 0\n): StreamEvent {\n return {\n type: StreamEventType.ToolExecutionEnd,\n index,\n delta: { toolCallId, toolName, result, isError, timestamp },\n };\n}\n"],"mappings":";AA2BO,IAAM,kBAAkB;AAAA;AAAA,EAE7B,WAAW;AAAA;AAAA,EAEX,gBAAgB;AAAA;AAAA,EAEhB,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA,EAEZ,eAAe;AAAA;AAAA,EAEf,oBAAoB;AAAA;AAAA,EAEpB,kBAAkB;AAAA;AAAA,EAElB,cAAc;AAAA;AAAA,EAEd,aAAa;AAAA;AAAA,EAEb,mBAAmB;AAAA;AAAA,EAEnB,kBAAkB;AACpB;AAoIO,SAAS,mBACd,WACA,sBACA,iBACqB;AACrB,MAAI,aAA0C;AAE9C,QAAM,UAAU,MAA4B;AAE1C,QAAI,OAAO,yBAAyB,YAAY;AAC9C,UAAI,CAAC,YAAY;AACf,qBAAa,qBAAqB;AAAA,MACpC;AACA,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,CAAC,O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[]}
|
|
@@ -11,6 +11,14 @@ function generateId() {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
// src/types/messages.ts
|
|
14
|
+
var MessageRole = {
|
|
15
|
+
/** User message */
|
|
16
|
+
User: "user",
|
|
17
|
+
/** Assistant/model response */
|
|
18
|
+
Assistant: "assistant",
|
|
19
|
+
/** Tool execution result */
|
|
20
|
+
ToolResult: "tool_result"
|
|
21
|
+
};
|
|
14
22
|
var Message = class {
|
|
15
23
|
/** Unique message identifier */
|
|
16
24
|
id;
|
|
@@ -133,13 +141,13 @@ var ToolResultMessage = class extends Message {
|
|
|
133
141
|
}
|
|
134
142
|
};
|
|
135
143
|
function isUserMessage(msg) {
|
|
136
|
-
return msg.type ===
|
|
144
|
+
return msg.type === MessageRole.User;
|
|
137
145
|
}
|
|
138
146
|
function isAssistantMessage(msg) {
|
|
139
|
-
return msg.type ===
|
|
147
|
+
return msg.type === MessageRole.Assistant;
|
|
140
148
|
}
|
|
141
149
|
function isToolResultMessage(msg) {
|
|
142
|
-
return msg.type ===
|
|
150
|
+
return msg.type === MessageRole.ToolResult;
|
|
143
151
|
}
|
|
144
152
|
|
|
145
153
|
// src/core/provider-handlers.ts
|
|
@@ -227,6 +235,7 @@ export {
|
|
|
227
235
|
resolveEmbeddingHandler,
|
|
228
236
|
resolveImageHandler,
|
|
229
237
|
generateId,
|
|
238
|
+
MessageRole,
|
|
230
239
|
Message,
|
|
231
240
|
UserMessage,
|
|
232
241
|
AssistantMessage,
|
|
@@ -236,4 +245,4 @@ export {
|
|
|
236
245
|
isToolResultMessage,
|
|
237
246
|
createProvider
|
|
238
247
|
};
|
|
239
|
-
//# sourceMappingURL=chunk-
|
|
248
|
+
//# sourceMappingURL=chunk-MF5ETY5O.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/id.ts","../src/types/messages.ts","../src/core/provider-handlers.ts","../src/core/provider.ts"],"sourcesContent":["/**\n * @fileoverview ID generation utilities for the Universal Provider Protocol.\n *\n * Provides functions for generating unique identifiers used throughout UPP,\n * including message IDs, tool call IDs, and other internal references.\n *\n * @module utils/id\n */\n\n/**\n * Generates a unique UUID v4 identifier.\n *\n * Uses the native `crypto.randomUUID()` when available for cryptographically\n * secure randomness. Falls back to a Math.random-based implementation for\n * environments without Web Crypto API support.\n *\n * @returns A UUID v4 string in the format `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`\n *\n * @example\n * ```typescript\n * const messageId = generateId();\n * // => \"f47ac10b-58cc-4372-a567-0e02b2c3d479\"\n * ```\n */\nexport function generateId(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Generates a short alphanumeric identifier.\n *\n * Creates a 12-character random string using alphanumeric characters (a-z, A-Z, 0-9).\n * Useful for tool call IDs and other cases where a full UUID is not required.\n *\n * @param prefix - Optional prefix to prepend to the generated ID\n * @returns A string containing the prefix followed by 12 random alphanumeric characters\n *\n * @example\n * ```typescript\n * const toolCallId = generateShortId('call_');\n * // => \"call_aB3xY9mK2pQr\"\n *\n * const simpleId = generateShortId();\n * // => \"Tz4wN8vL1sHj\"\n * ```\n */\nexport function generateShortId(prefix = ''): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let result = prefix;\n for (let i = 0; i < 12; i++) {\n result += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n return result;\n}\n","/**\n * @fileoverview Message types for conversation history.\n *\n * Defines the message classes used to represent conversation turns\n * between users and assistants, including support for multimodal\n * content and tool calls.\n *\n * @module types/messages\n */\n\nimport { generateId } from '../utils/id.ts';\nimport type {\n ContentBlock,\n TextBlock,\n ImageBlock,\n AudioBlock,\n VideoBlock,\n UserContent,\n AssistantContent,\n} from './content.ts';\nimport type { ToolCall, ToolResult } from './tool.ts';\n\n/**\n * Message serialized to JSON format.\n * Picks common fields from Message, converts timestamp to string.\n */\nexport type MessageJSON = Pick<Message, 'id' | 'type' | 'metadata'> & {\n timestamp: string;\n content: ContentBlock[];\n toolCalls?: ToolCall[];\n results?: ToolResult[];\n};\n\n/**\n * Message role/type constants.\n *\n * Use these constants instead of raw strings for type-safe message handling:\n *\n * @example\n * ```typescript\n * import { MessageRole, isUserMessage } from 'upp';\n *\n * if (message.type === MessageRole.User) {\n * console.log('User said:', message.text);\n * } else if (message.type === MessageRole.Assistant) {\n * console.log('Assistant replied:', message.text);\n * }\n * ```\n */\nexport const MessageRole = {\n /** User message */\n User: 'user',\n /** Assistant/model response */\n Assistant: 'assistant',\n /** Tool execution result */\n ToolResult: 'tool_result',\n} as const;\n\n/**\n * Message type discriminator union.\n *\n * This type is derived from {@link MessageRole} constants. The name `MessageType`\n * is kept for backward compatibility; `MessageRole` works as both the const\n * object and this type.\n */\nexport type MessageType = (typeof MessageRole)[keyof typeof MessageRole];\n\n/**\n * Type alias for MessageType, allowing `MessageRole` to work as both const and type.\n */\nexport type MessageRole = MessageType;\n\n/**\n * Provider-namespaced metadata for messages.\n *\n * Each provider can attach its own metadata under its namespace,\n * preventing conflicts between different providers.\n *\n * @example\n * ```typescript\n * const metadata: MessageMetadata = {\n * openai: { model: 'gpt-4', finishReason: 'stop' },\n * anthropic: { model: 'claude-3', stopReason: 'end_turn' }\n * };\n * ```\n */\nexport interface MessageMetadata {\n [provider: string]: Record<string, unknown> | undefined;\n}\n\n/**\n * Options for constructing messages.\n */\nexport interface MessageOptions {\n /** Custom message ID (auto-generated if not provided) */\n id?: string;\n\n /** Provider-specific metadata */\n metadata?: MessageMetadata;\n}\n\n/**\n * Abstract base class for all message types.\n *\n * Provides common functionality for user, assistant, and tool result\n * messages, including content accessors and metadata handling.\n *\n * @example\n * ```typescript\n * // Access text content from any message\n * const text = message.text;\n *\n * // Access images\n * const images = message.images;\n * ```\n */\nexport abstract class Message {\n /** Unique message identifier */\n readonly id: string;\n\n /** Timestamp when the message was created */\n readonly timestamp: Date;\n\n /** Provider-specific metadata, namespaced by provider name */\n readonly metadata?: MessageMetadata;\n\n /** Message type discriminator (implemented by subclasses) */\n abstract readonly type: MessageType;\n\n /**\n * Returns the content blocks for this message.\n * Implemented by subclasses to provide type-specific content.\n */\n protected abstract getContent(): ContentBlock[];\n\n /**\n * Creates a new message instance.\n *\n * @param options - Optional message ID and metadata\n */\n constructor(options?: MessageOptions) {\n this.id = options?.id ?? generateId();\n this.timestamp = new Date();\n this.metadata = options?.metadata;\n }\n\n /**\n * Concatenated text content from all text blocks.\n * Blocks are joined with double newlines.\n */\n get text(): string {\n return this.getContent()\n .filter((block): block is TextBlock => block.type === 'text')\n .map((block) => block.text)\n .join('\\n\\n');\n }\n\n /**\n * All image content blocks in this message.\n */\n get images(): ImageBlock[] {\n return this.getContent().filter((block): block is ImageBlock => block.type === 'image');\n }\n\n /**\n * All audio content blocks in this message.\n */\n get audio(): AudioBlock[] {\n return this.getContent().filter((block): block is AudioBlock => block.type === 'audio');\n }\n\n /**\n * All video content blocks in this message.\n */\n get video(): VideoBlock[] {\n return this.getContent().filter((block): block is VideoBlock => block.type === 'video');\n }\n}\n\n/**\n * User input message.\n *\n * Represents a message from the user, which can contain text and/or\n * multimodal content like images, audio, or video.\n *\n * @example\n * ```typescript\n * // Simple text message\n * const msg = new UserMessage('Hello, world!');\n *\n * // Multimodal message\n * const msg = new UserMessage([\n * { type: 'text', text: 'What is in this image?' },\n * { type: 'image', source: { type: 'url', url: '...' }, mimeType: 'image/png' }\n * ]);\n * ```\n */\nexport class UserMessage extends Message {\n /** Message type discriminator */\n readonly type = 'user' as const;\n\n /** Content blocks in this message */\n readonly content: UserContent[];\n\n /**\n * Creates a new user message.\n *\n * @param content - String (converted to TextBlock) or array of content blocks\n * @param options - Optional message ID and metadata\n */\n constructor(content: string | UserContent[], options?: MessageOptions) {\n super(options);\n if (typeof content === 'string') {\n this.content = [{ type: 'text', text: content }];\n } else {\n this.content = content;\n }\n }\n\n protected getContent(): ContentBlock[] {\n return this.content;\n }\n}\n\n/**\n * Assistant response message.\n *\n * Represents a response from the AI assistant, which may contain\n * text, media content, and/or tool call requests.\n *\n * @example\n * ```typescript\n * // Simple text response\n * const msg = new AssistantMessage('Hello! How can I help?');\n *\n * // Response with tool calls\n * const msg = new AssistantMessage(\n * 'Let me check the weather...',\n * [{ toolCallId: 'call_1', toolName: 'get_weather', arguments: { location: 'NYC' } }]\n * );\n * ```\n */\nexport class AssistantMessage extends Message {\n /** Message type discriminator */\n readonly type = 'assistant' as const;\n\n /** Content blocks in this message */\n readonly content: AssistantContent[];\n\n /** Tool calls requested by the model (if any) */\n readonly toolCalls?: ToolCall[];\n\n /**\n * Creates a new assistant message.\n *\n * @param content - String (converted to TextBlock) or array of content blocks\n * @param toolCalls - Tool calls requested by the model\n * @param options - Optional message ID and metadata\n */\n constructor(\n content: string | AssistantContent[],\n toolCalls?: ToolCall[],\n options?: MessageOptions\n ) {\n super(options);\n if (typeof content === 'string') {\n this.content = [{ type: 'text', text: content }];\n } else {\n this.content = content;\n }\n this.toolCalls = toolCalls;\n }\n\n protected getContent(): ContentBlock[] {\n return this.content;\n }\n\n /**\n * Whether this message contains tool call requests.\n */\n get hasToolCalls(): boolean {\n return this.toolCalls !== undefined && this.toolCalls.length > 0;\n }\n}\n\n/**\n * Tool execution result message.\n *\n * Contains the results of executing one or more tool calls,\n * sent back to the model for further processing.\n *\n * @example\n * ```typescript\n * const msg = new ToolResultMessage([\n * { toolCallId: 'call_1', result: { temperature: 72, conditions: 'sunny' } },\n * { toolCallId: 'call_2', result: 'File not found', isError: true }\n * ]);\n * ```\n */\nexport class ToolResultMessage extends Message {\n /** Message type discriminator */\n readonly type = 'tool_result' as const;\n\n /** Results from tool executions */\n readonly results: ToolResult[];\n\n /**\n * Creates a new tool result message.\n *\n * @param results - Array of tool execution results\n * @param options - Optional message ID and metadata\n */\n constructor(results: ToolResult[], options?: MessageOptions) {\n super(options);\n this.results = results;\n }\n\n protected getContent(): ContentBlock[] {\n return this.results.map((result) => ({\n type: 'text' as const,\n text:\n typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result),\n }));\n }\n}\n\n/**\n * Type guard for UserMessage.\n *\n * @param msg - The message to check\n * @returns True if the message is a UserMessage\n *\n * @example\n * ```typescript\n * if (isUserMessage(msg)) {\n * console.log('User said:', msg.text);\n * }\n * ```\n */\nexport function isUserMessage(msg: Message): msg is UserMessage {\n return msg.type === MessageRole.User;\n}\n\n/**\n * Type guard for AssistantMessage.\n *\n * @param msg - The message to check\n * @returns True if the message is an AssistantMessage\n *\n * @example\n * ```typescript\n * if (isAssistantMessage(msg)) {\n * console.log('Assistant said:', msg.text);\n * if (msg.hasToolCalls) {\n * console.log('Tool calls:', msg.toolCalls);\n * }\n * }\n * ```\n */\nexport function isAssistantMessage(msg: Message): msg is AssistantMessage {\n return msg.type === MessageRole.Assistant;\n}\n\n/**\n * Type guard for ToolResultMessage.\n *\n * @param msg - The message to check\n * @returns True if the message is a ToolResultMessage\n *\n * @example\n * ```typescript\n * if (isToolResultMessage(msg)) {\n * for (const result of msg.results) {\n * console.log(`Tool ${result.toolCallId}:`, result.result);\n * }\n * }\n * ```\n */\nexport function isToolResultMessage(msg: Message): msg is ToolResultMessage {\n return msg.type === MessageRole.ToolResult;\n}\n","/**\n * @fileoverview Internal handler registry and resolver utilities.\n *\n * @module core/provider-handlers\n */\n\nimport type {\n ProviderIdentity,\n LLMHandler,\n EmbeddingHandler,\n ImageHandler,\n} from '../types/provider.ts';\n\n/**\n * Resolver for dynamically selecting LLM handlers based on model options.\n *\n * Used by providers that support multiple API modes (e.g., OpenAI with responses/completions).\n * The resolver eliminates shared mutable state by storing the mode on the ModelReference\n * and resolving the correct handler at request time.\n *\n * @typeParam TOptions - Provider-specific options type\n */\nexport interface LLMHandlerResolver<TOptions = unknown> {\n /** Map of mode identifiers to their corresponding LLM handlers */\n handlers: Record<string, LLMHandler>;\n /** The default mode when options don't specify one */\n defaultMode: string;\n /** Function to extract the mode from provider options */\n getMode: (options: TOptions | undefined) => string;\n}\n\n/**\n * Type guard to check if a value is an LLMHandlerResolver.\n */\nexport function isHandlerResolver<TOptions>(\n value: LLMHandler | LLMHandlerResolver<TOptions> | undefined\n): value is LLMHandlerResolver<TOptions> {\n return value !== undefined && 'handlers' in value && 'getMode' in value;\n}\n\ntype ProviderHandlers<TOptions = unknown> = {\n llm?: LLMHandler;\n embedding?: EmbeddingHandler;\n image?: ImageHandler;\n llmResolver?: LLMHandlerResolver<TOptions>;\n};\n\nconst providerHandlers = new WeakMap<object, ProviderHandlers<unknown>>();\n\n/**\n * Registers handler implementations for a provider.\n */\nexport function registerProviderHandlers<TOptions>(\n provider: ProviderIdentity,\n handlers: ProviderHandlers<TOptions>\n): void {\n providerHandlers.set(provider as object, handlers as ProviderHandlers<unknown>);\n}\n\nfunction getProviderHandlers<TOptions>(\n provider: ProviderIdentity\n): ProviderHandlers<TOptions> | undefined {\n return providerHandlers.get(provider as object) as ProviderHandlers<TOptions> | undefined;\n}\n\n/**\n * Resolves the correct LLM handler based on model reference options.\n *\n * For providers with multiple LLM handlers (e.g., OpenAI with responses/completions APIs),\n * this function determines which handler to use based on the options stored on the\n * ModelReference. This eliminates race conditions from shared mutable state.\n *\n * For providers with a single LLM handler, this simply returns that handler.\n *\n * @typeParam TOptions - Provider-specific options type\n * @param provider - The provider to resolve the handler from\n * @param options - The options from the ModelReference\n * @returns The resolved LLM handler, or undefined if LLM is not supported\n *\n * @internal\n */\nexport function resolveLLMHandler<TOptions = unknown>(\n provider: ProviderIdentity,\n options: TOptions | undefined\n): LLMHandler | undefined {\n const handlers = getProviderHandlers(provider);\n const resolver = handlers?.llmResolver;\n\n if (resolver) {\n const mode = resolver.getMode(options);\n return resolver.handlers[mode] ?? handlers?.llm;\n }\n\n return handlers?.llm;\n}\n\n/**\n * Resolves the embedding handler for a provider, if supported.\n *\n * @internal\n */\nexport function resolveEmbeddingHandler<TParams = unknown>(\n provider: ProviderIdentity\n): EmbeddingHandler<TParams> | undefined {\n const handlers = getProviderHandlers(provider);\n return handlers?.embedding as EmbeddingHandler<TParams> | undefined;\n}\n\n/**\n * Resolves the image handler for a provider, if supported.\n *\n * @internal\n */\nexport function resolveImageHandler<TParams = unknown>(\n provider: ProviderIdentity\n): ImageHandler<TParams> | undefined {\n const handlers = getProviderHandlers(provider);\n return handlers?.image as ImageHandler<TParams> | undefined;\n}\n","/**\n * @fileoverview Base provider interface and factory for the Universal Provider Protocol.\n *\n * This module provides the foundation for creating AI providers that conform to the\n * UPP specification. Providers are callable functions that create model references\n * and register internal handlers for LLM, embedding, and image modalities.\n *\n * @module core/provider\n */\n\nimport type {\n Provider,\n ModelReference,\n LLMHandler,\n EmbeddingHandler,\n ImageHandler,\n LLMProvider,\n EmbeddingProvider,\n ImageProvider,\n} from '../types/provider.ts';\nimport type { LLMHandlerResolver } from './provider-handlers.ts';\nimport { isHandlerResolver, registerProviderHandlers } from './provider-handlers.ts';\n\n\n/**\n * Configuration options for creating a new provider.\n *\n * @typeParam TOptions - Provider-specific options type\n *\n * @example\n * ```typescript\n * // Simple provider with single handler\n * const options: CreateProviderOptions = {\n * name: 'my-provider',\n * version: '1.0.0',\n * handlers: {\n * llm: createLLMHandler(),\n * embedding: createEmbeddingHandler(),\n * },\n * };\n *\n * // Provider with multiple LLM handlers (API modes)\n * const options: CreateProviderOptions<OpenAIOptions> = {\n * name: 'openai',\n * version: '1.0.0',\n * handlers: {\n * llm: {\n * handlers: { responses: handler1, completions: handler2 },\n * defaultMode: 'responses',\n * getMode: (opts) => opts?.api ?? 'responses',\n * },\n * },\n * };\n * ```\n */\nexport interface CreateProviderOptions<TOptions = unknown> {\n /** Unique identifier for the provider */\n name: string;\n /** Semantic version string for the provider implementation */\n version: string;\n /** Handlers for supported modalities (LLM, embedding, image generation) */\n handlers: {\n /** Handler for language model completions, or resolver for multi-handler providers */\n llm?: LLMHandler | LLMHandlerResolver<TOptions>;\n /** Handler for text embeddings */\n embedding?: EmbeddingHandler;\n /** Handler for image generation */\n image?: ImageHandler;\n };\n /**\n * Custom function to create model references from options.\n * Use this to map provider options to providerConfig (e.g., betas to headers).\n */\n createModelReference?: (\n modelId: string,\n options: TOptions | undefined,\n provider: Provider<TOptions>\n ) => ModelReference<TOptions>;\n}\n\n\n/**\n * Creates a provider factory function with registered modality handlers.\n *\n * The returned provider is a callable function that creates model references\n * when invoked with a model ID. It exposes `name` and `version` metadata.\n *\n * @typeParam TOptions - Provider-specific options type (defaults to unknown)\n * @param options - Provider configuration including name, version, and handlers\n * @returns A callable Provider with handlers registered internally\n *\n * @example\n * ```typescript\n * // Create a basic provider\n * const anthropic = createProvider({\n * name: 'anthropic',\n * version: '1.0.0',\n * handlers: { llm: createLLMHandler() },\n * });\n *\n * // Use the provider to create a model reference\n * const model = anthropic('claude-sonnet-4-20250514');\n *\n * // Provider with custom options type\n * interface MyOptions { apiVersion?: 'v1' | 'v2' }\n * const myProvider = createProvider<MyOptions>({\n * name: 'my-provider',\n * version: '1.0.0',\n * handlers: { llm: handler },\n * });\n *\n * // Provider with multiple LLM handlers (API modes)\n * const openai = createProvider<OpenAIOptions>({\n * name: 'openai',\n * version: '1.0.0',\n * handlers: {\n * llm: {\n * handlers: { responses: responsesHandler, completions: completionsHandler },\n * defaultMode: 'responses',\n * getMode: (opts) => opts?.api ?? 'responses',\n * },\n * },\n * });\n * ```\n */\nexport function createProvider<TOptions = unknown>(\n options: CreateProviderOptions<TOptions>\n): Provider<TOptions> {\n // Resolve the default LLM handler for capabilities/bind\n const llmInput = options.handlers.llm;\n const hasResolver = isHandlerResolver<TOptions>(llmInput);\n const defaultLLMHandler = hasResolver ? llmInput.handlers[llmInput.defaultMode] : llmInput;\n\n if (hasResolver && !defaultLLMHandler) {\n throw new Error(\n `Provider '${options.name}' LLM resolver defaultMode '${llmInput.defaultMode}' has no handler`\n );\n }\n\n // Create the factory function\n const fn = function (modelId: string, modelOptions?: TOptions): ModelReference<TOptions> {\n if (options.createModelReference) {\n return options.createModelReference(modelId, modelOptions, provider);\n }\n // Default: store options on the reference for handler resolution\n return { modelId, provider, options: modelOptions };\n };\n\n Object.defineProperties(fn, {\n name: {\n value: options.name,\n writable: false,\n configurable: true,\n },\n version: {\n value: options.version,\n writable: false,\n configurable: true,\n },\n });\n\n const provider = fn as Provider<TOptions>;\n\n // If there's a resolver, set provider on all handlers\n if (hasResolver) {\n for (const handler of Object.values(llmInput.handlers)) {\n handler._setProvider?.(provider as unknown as LLMProvider);\n }\n } else if (defaultLLMHandler?._setProvider) {\n defaultLLMHandler._setProvider(provider as unknown as LLMProvider);\n }\n\n if (options.handlers.embedding?._setProvider) {\n options.handlers.embedding._setProvider(provider as unknown as EmbeddingProvider);\n }\n if (options.handlers.image?._setProvider) {\n options.handlers.image._setProvider(provider as unknown as ImageProvider);\n }\n\n registerProviderHandlers(provider, {\n llm: defaultLLMHandler,\n embedding: options.handlers.embedding,\n image: options.handlers.image,\n ...(hasResolver ? { llmResolver: llmInput } : {}),\n });\n\n return provider;\n}\n"],"mappings":";AAwBO,SAAS,aAAqB;AACnC,MAAI,OAAO,WAAW,eAAe,OAAO,YAAY;AACtD,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO,uCAAuC,QAAQ,SAAS,CAAC,MAAM;AACpE,UAAM,IAAK,KAAK,OAAO,IAAI,KAAM;AACjC,UAAM,IAAI,MAAM,MAAM,IAAK,IAAI,IAAO;AACtC,WAAO,EAAE,SAAS,EAAE;AAAA,EACtB,CAAC;AACH;;;ACeO,IAAM,cAAc;AAAA;AAAA,EAEzB,MAAM;AAAA;AAAA,EAEN,WAAW;AAAA;AAAA,EAEX,YAAY;AACd;AA4DO,IAAe,UAAf,MAAuB;AAAA;AAAA,EAEnB;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;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AAC5C,YAAQ,SAAS,UAAU,aAAa,QAAwC;AAAA,EAClF;AACA,MAAI,QAAQ,SAAS,OAAO,cAAc;AACxC,YAAQ,SAAS,MAAM,aAAa,QAAoC;AAAA,EAC1E;AAEA,2BAAyB,UAAU;AAAA,IACjC,KAAK;AAAA,IACL,WAAW,QAAQ,SAAS;AAAA,IAC5B,OAAO,QAAQ,SAAS;AAAA,IACxB,GAAI,cAAc,EAAE,aAAa,SAAS,IAAI,CAAC;AAAA,EACjD,CAAC;AAED,SAAO;AACT;","names":[]}
|
|
@@ -1,4 +1,42 @@
|
|
|
1
1
|
// src/types/errors.ts
|
|
2
|
+
var ErrorCode = {
|
|
3
|
+
/** API key is invalid or expired */
|
|
4
|
+
AuthenticationFailed: "AUTHENTICATION_FAILED",
|
|
5
|
+
/** Rate limit exceeded, retry after delay */
|
|
6
|
+
RateLimited: "RATE_LIMITED",
|
|
7
|
+
/** Input exceeds model's context window */
|
|
8
|
+
ContextLengthExceeded: "CONTEXT_LENGTH_EXCEEDED",
|
|
9
|
+
/** Requested model does not exist */
|
|
10
|
+
ModelNotFound: "MODEL_NOT_FOUND",
|
|
11
|
+
/** Request parameters are malformed */
|
|
12
|
+
InvalidRequest: "INVALID_REQUEST",
|
|
13
|
+
/** Provider returned an unexpected response format */
|
|
14
|
+
InvalidResponse: "INVALID_RESPONSE",
|
|
15
|
+
/** Content was blocked by safety filters */
|
|
16
|
+
ContentFiltered: "CONTENT_FILTERED",
|
|
17
|
+
/** Account quota or credits exhausted */
|
|
18
|
+
QuotaExceeded: "QUOTA_EXCEEDED",
|
|
19
|
+
/** Provider-specific error not covered by other codes */
|
|
20
|
+
ProviderError: "PROVIDER_ERROR",
|
|
21
|
+
/** Network connectivity issue */
|
|
22
|
+
NetworkError: "NETWORK_ERROR",
|
|
23
|
+
/** Request exceeded timeout limit */
|
|
24
|
+
Timeout: "TIMEOUT",
|
|
25
|
+
/** Request was cancelled via AbortSignal */
|
|
26
|
+
Cancelled: "CANCELLED"
|
|
27
|
+
};
|
|
28
|
+
var ModalityType = {
|
|
29
|
+
/** Large language model for text generation */
|
|
30
|
+
LLM: "llm",
|
|
31
|
+
/** Text/image embedding model */
|
|
32
|
+
Embedding: "embedding",
|
|
33
|
+
/** Image generation model */
|
|
34
|
+
Image: "image",
|
|
35
|
+
/** Audio processing/generation model */
|
|
36
|
+
Audio: "audio",
|
|
37
|
+
/** Video processing/generation model */
|
|
38
|
+
Video: "video"
|
|
39
|
+
};
|
|
2
40
|
var UPPError = class _UPPError extends Error {
|
|
3
41
|
/** Normalized error code for programmatic handling */
|
|
4
42
|
code;
|
|
@@ -86,33 +124,33 @@ function toError(value) {
|
|
|
86
124
|
function statusToErrorCode(status) {
|
|
87
125
|
switch (status) {
|
|
88
126
|
case 400:
|
|
89
|
-
return
|
|
127
|
+
return ErrorCode.InvalidRequest;
|
|
90
128
|
case 402:
|
|
91
|
-
return
|
|
129
|
+
return ErrorCode.QuotaExceeded;
|
|
92
130
|
case 401:
|
|
93
131
|
case 403:
|
|
94
|
-
return
|
|
132
|
+
return ErrorCode.AuthenticationFailed;
|
|
95
133
|
case 404:
|
|
96
|
-
return
|
|
134
|
+
return ErrorCode.ModelNotFound;
|
|
97
135
|
case 408:
|
|
98
|
-
return
|
|
136
|
+
return ErrorCode.Timeout;
|
|
99
137
|
case 409:
|
|
100
|
-
return
|
|
138
|
+
return ErrorCode.InvalidRequest;
|
|
101
139
|
case 422:
|
|
102
|
-
return
|
|
140
|
+
return ErrorCode.InvalidRequest;
|
|
103
141
|
case 413:
|
|
104
|
-
return
|
|
142
|
+
return ErrorCode.ContextLengthExceeded;
|
|
105
143
|
case 451:
|
|
106
|
-
return
|
|
144
|
+
return ErrorCode.ContentFiltered;
|
|
107
145
|
case 429:
|
|
108
|
-
return
|
|
146
|
+
return ErrorCode.RateLimited;
|
|
109
147
|
case 500:
|
|
110
148
|
case 502:
|
|
111
149
|
case 503:
|
|
112
150
|
case 504:
|
|
113
|
-
return
|
|
151
|
+
return ErrorCode.ProviderError;
|
|
114
152
|
default:
|
|
115
|
-
return
|
|
153
|
+
return ErrorCode.ProviderError;
|
|
116
154
|
}
|
|
117
155
|
}
|
|
118
156
|
async function normalizeHttpError(response, provider, modality) {
|
|
@@ -142,7 +180,7 @@ async function normalizeHttpError(response, provider, modality) {
|
|
|
142
180
|
function networkError(error, provider, modality) {
|
|
143
181
|
return new UPPError(
|
|
144
182
|
`Network error: ${error.message}`,
|
|
145
|
-
|
|
183
|
+
ErrorCode.NetworkError,
|
|
146
184
|
provider,
|
|
147
185
|
modality,
|
|
148
186
|
void 0,
|
|
@@ -152,13 +190,18 @@ function networkError(error, provider, modality) {
|
|
|
152
190
|
function timeoutError(timeout, provider, modality) {
|
|
153
191
|
return new UPPError(
|
|
154
192
|
`Request timed out after ${timeout}ms`,
|
|
155
|
-
|
|
193
|
+
ErrorCode.Timeout,
|
|
156
194
|
provider,
|
|
157
195
|
modality
|
|
158
196
|
);
|
|
159
197
|
}
|
|
160
198
|
function cancelledError(provider, modality) {
|
|
161
|
-
return new UPPError(
|
|
199
|
+
return new UPPError(
|
|
200
|
+
"Request was cancelled",
|
|
201
|
+
ErrorCode.Cancelled,
|
|
202
|
+
provider,
|
|
203
|
+
modality
|
|
204
|
+
);
|
|
162
205
|
}
|
|
163
206
|
|
|
164
207
|
// src/http/fetch.ts
|
|
@@ -320,6 +363,8 @@ function parseRetryAfter(headerValue, maxSeconds) {
|
|
|
320
363
|
}
|
|
321
364
|
|
|
322
365
|
export {
|
|
366
|
+
ErrorCode,
|
|
367
|
+
ModalityType,
|
|
323
368
|
UPPError,
|
|
324
369
|
toError,
|
|
325
370
|
statusToErrorCode,
|
|
@@ -330,4 +375,4 @@ export {
|
|
|
330
375
|
doFetch,
|
|
331
376
|
doStreamFetch
|
|
332
377
|
};
|
|
333
|
-
//# sourceMappingURL=chunk-
|
|
378
|
+
//# sourceMappingURL=chunk-QNJO7DSD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types/errors.ts","../src/utils/error.ts","../src/http/errors.ts","../src/http/fetch.ts"],"sourcesContent":["/**\n * @fileoverview Error types for the Unified Provider Protocol.\n *\n * Provides normalized error codes and a unified error class for handling\n * errors across different AI providers in a consistent manner.\n *\n * @module types/errors\n */\n\n/**\n * Error code constants for cross-provider error handling.\n *\n * Use these constants instead of raw strings for type-safe error handling:\n *\n * @example\n * ```typescript\n * import { ErrorCode } from 'upp';\n *\n * try {\n * await llm.generate('Hello');\n * } catch (error) {\n * if (error instanceof UPPError) {\n * switch (error.code) {\n * case ErrorCode.RateLimited:\n * await delay(error.retryAfter);\n * break;\n * case ErrorCode.AuthenticationFailed:\n * throw new Error('Invalid API key');\n * }\n * }\n * }\n * ```\n */\nexport const ErrorCode = {\n /** API key is invalid or expired */\n AuthenticationFailed: 'AUTHENTICATION_FAILED',\n /** Rate limit exceeded, retry after delay */\n RateLimited: 'RATE_LIMITED',\n /** Input exceeds model's context window */\n ContextLengthExceeded: 'CONTEXT_LENGTH_EXCEEDED',\n /** Requested model does not exist */\n ModelNotFound: 'MODEL_NOT_FOUND',\n /** Request parameters are malformed */\n InvalidRequest: 'INVALID_REQUEST',\n /** Provider returned an unexpected response format */\n InvalidResponse: 'INVALID_RESPONSE',\n /** Content was blocked by safety filters */\n ContentFiltered: 'CONTENT_FILTERED',\n /** Account quota or credits exhausted */\n QuotaExceeded: 'QUOTA_EXCEEDED',\n /** Provider-specific error not covered by other codes */\n ProviderError: 'PROVIDER_ERROR',\n /** Network connectivity issue */\n NetworkError: 'NETWORK_ERROR',\n /** Request exceeded timeout limit */\n Timeout: 'TIMEOUT',\n /** Request was cancelled via AbortSignal */\n Cancelled: 'CANCELLED',\n} as const;\n\n/**\n * Error code discriminator union.\n *\n * This type is derived from {@link ErrorCode} constants. Use `ErrorCode.RateLimited`\n * for constants or `type MyCode = ErrorCode` for type annotations.\n */\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\n/**\n * Modality type constants.\n *\n * Use these constants for type-safe modality handling:\n *\n * @example\n * ```typescript\n * import { ModalityType } from 'upp';\n *\n * if (provider.modality === ModalityType.LLM) {\n * // Handle LLM provider\n * }\n * ```\n */\nexport const ModalityType = {\n /** Large language model for text generation */\n LLM: 'llm',\n /** Text/image embedding model */\n Embedding: 'embedding',\n /** Image generation model */\n Image: 'image',\n /** Audio processing/generation model */\n Audio: 'audio',\n /** Video processing/generation model */\n Video: 'video',\n} as const;\n\n/**\n * Modality type discriminator union.\n *\n * This type is derived from {@link ModalityType} constants. The name `Modality`\n * is kept for backward compatibility; `ModalityType` works as both the const\n * object and this type.\n */\nexport type Modality = (typeof ModalityType)[keyof typeof ModalityType];\n\n/**\n * Type alias for Modality, allowing `ModalityType` to work as both const and type.\n */\nexport type ModalityType = Modality;\n\n/**\n * Unified Provider Protocol Error.\n *\n * All provider-specific errors are normalized to this type, providing\n * a consistent interface for error handling across different AI providers.\n *\n * @example\n * ```typescript\n * import { ErrorCode, ModalityType } from 'upp';\n *\n * throw new UPPError(\n * 'API key is invalid',\n * ErrorCode.AuthenticationFailed,\n * 'openai',\n * ModalityType.LLM,\n * 401\n * );\n * ```\n *\n * @example\n * ```typescript\n * import { ErrorCode, ModalityType } from 'upp';\n *\n * // Wrapping a provider error\n * try {\n * await openai.chat.completions.create({ ... });\n * } catch (err) {\n * throw new UPPError(\n * 'OpenAI request failed',\n * ErrorCode.ProviderError,\n * 'openai',\n * ModalityType.LLM,\n * err.status,\n * err\n * );\n * }\n * ```\n */\nexport class UPPError extends Error {\n /** Normalized error code for programmatic handling */\n readonly code: ErrorCode;\n\n /** Name of the provider that generated the error */\n readonly provider: string;\n\n /** The modality that was being used when the error occurred */\n readonly modality: Modality;\n\n /** HTTP status code from the provider's response, if available */\n readonly statusCode?: number;\n\n /** The original error that caused this UPPError, if wrapping another error */\n override readonly cause?: Error;\n\n /** Error class name, always 'UPPError' */\n override readonly name = 'UPPError';\n\n /**\n * Creates a new UPPError instance.\n *\n * @param message - Human-readable error description\n * @param code - Normalized error code for programmatic handling\n * @param provider - Name of the provider that generated the error\n * @param modality - The modality that was being used\n * @param statusCode - HTTP status code from the provider's response\n * @param cause - The original error being wrapped\n */\n constructor(\n message: string,\n code: ErrorCode,\n provider: string,\n modality: Modality,\n statusCode?: number,\n cause?: Error\n ) {\n super(message);\n this.code = code;\n this.provider = provider;\n this.modality = modality;\n this.statusCode = statusCode;\n this.cause = cause;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, UPPError);\n }\n }\n\n /**\n * Creates a string representation of the error.\n *\n * @returns Formatted error string including code, message, provider, and modality\n */\n override toString(): string {\n let str = `UPPError [${this.code}]: ${this.message}`;\n str += ` (provider: ${this.provider}, modality: ${this.modality}`;\n if (this.statusCode) {\n str += `, status: ${this.statusCode}`;\n }\n str += ')';\n return str;\n }\n\n /**\n * Converts the error to a JSON-serializable object.\n *\n * @returns Plain object representation suitable for logging or transmission\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n provider: this.provider,\n modality: this.modality,\n statusCode: this.statusCode,\n cause: this.cause?.message,\n };\n }\n}\n","/**\n * @fileoverview Error normalization utilities.\n *\n * @module utils/error\n */\n\n/**\n * Converts an unknown thrown value into an Error instance.\n *\n * @param value - Unknown error value\n * @returns An Error instance\n */\nexport function toError(value: unknown): Error {\n if (value instanceof Error) {\n return value;\n }\n if (typeof value === 'string') {\n return new Error(value);\n }\n if (typeof value === 'object' && value !== null && 'message' in value) {\n const message = (value as { message?: unknown }).message;\n if (typeof message === 'string') {\n return new Error(message);\n }\n }\n return new Error(String(value));\n}\n","/**\n * HTTP error handling and normalization utilities.\n * @module http/errors\n */\n\nimport {\n UPPError,\n ErrorCode,\n type Modality,\n} from '../types/errors.ts';\nimport { toError } from '../utils/error.ts';\n\n/**\n * Maps HTTP status codes to standardized UPP error codes.\n *\n * This function provides consistent error categorization across all providers:\n * - 400 -> INVALID_REQUEST (bad request format or parameters)\n * - 401, 403 -> AUTHENTICATION_FAILED (invalid or missing credentials)\n * - 404 -> MODEL_NOT_FOUND (requested model does not exist)\n * - 408 -> TIMEOUT (request timed out)\n * - 413 -> CONTEXT_LENGTH_EXCEEDED (input too long)\n * - 429 -> RATE_LIMITED (too many requests)\n * - 5xx -> PROVIDER_ERROR (server-side issues)\n *\n * @param status - HTTP status code from the response\n * @returns The corresponding UPP ErrorCode\n *\n * @example\n * ```typescript\n * const errorCode = statusToErrorCode(429);\n * // Returns 'RATE_LIMITED'\n *\n * const serverError = statusToErrorCode(503);\n * // Returns 'PROVIDER_ERROR'\n * ```\n */\nexport function statusToErrorCode(status: number): ErrorCode {\n switch (status) {\n case 400:\n return ErrorCode.InvalidRequest;\n case 402:\n return ErrorCode.QuotaExceeded;\n case 401:\n case 403:\n return ErrorCode.AuthenticationFailed;\n case 404:\n return ErrorCode.ModelNotFound;\n case 408:\n return ErrorCode.Timeout;\n case 409:\n return ErrorCode.InvalidRequest;\n case 422:\n return ErrorCode.InvalidRequest;\n case 413:\n return ErrorCode.ContextLengthExceeded;\n case 451:\n return ErrorCode.ContentFiltered;\n case 429:\n return ErrorCode.RateLimited;\n case 500:\n case 502:\n case 503:\n case 504:\n return ErrorCode.ProviderError;\n default:\n return ErrorCode.ProviderError;\n }\n}\n\n/**\n * Normalizes HTTP error responses into standardized UPPError objects.\n *\n * This function performs several operations:\n * 1. Maps the HTTP status code to an appropriate ErrorCode\n * 2. Attempts to extract a meaningful error message from the response body\n * 3. Handles various provider-specific error response formats\n *\n * Supported error message formats:\n * - `{ error: { message: \"...\" } }` (OpenAI, Anthropic)\n * - `{ message: \"...\" }` (simple format)\n * - `{ error: { error: { message: \"...\" } } }` (nested format)\n * - `{ detail: \"...\" }` (FastAPI style)\n * - Plain text body (if under 200 characters)\n *\n * @param response - The HTTP Response object with non-2xx status\n * @param provider - Provider identifier for error context\n * @param modality - Request modality for error context\n * @returns A UPPError with normalized code and message\n *\n * @example\n * ```typescript\n * if (!response.ok) {\n * const error = await normalizeHttpError(response, 'openai', 'llm');\n * // error.code might be 'RATE_LIMITED' for 429\n * // error.message contains provider's error message\n * throw error;\n * }\n * ```\n */\nexport async function normalizeHttpError(\n response: Response,\n provider: string,\n modality: Modality\n): Promise<UPPError> {\n const code = statusToErrorCode(response.status);\n let message = `HTTP ${response.status}: ${response.statusText}`;\n let bodyReadError: Error | undefined;\n\n try {\n const body = await response.text();\n if (body) {\n try {\n const json = JSON.parse(body);\n const extractedMessage =\n json.error?.message ||\n json.message ||\n json.error?.error?.message ||\n json.detail;\n\n if (extractedMessage) {\n message = extractedMessage;\n }\n } catch {\n if (body.length < 200) {\n message = body;\n }\n }\n }\n } catch (error) {\n bodyReadError = toError(error);\n }\n\n return new UPPError(message, code, provider, modality, response.status, bodyReadError);\n}\n\n/**\n * Creates a UPPError for network failures (DNS, connection, etc.).\n *\n * Use this when the request fails before receiving any HTTP response,\n * such as DNS resolution failures, connection refused, or network unreachable.\n *\n * @param error - The underlying Error that caused the failure\n * @param provider - Provider identifier for error context\n * @param modality - Request modality for error context\n * @returns A UPPError with NETWORK_ERROR code and the original error attached\n */\nexport function networkError(\n error: Error,\n provider: string,\n modality: Modality\n): UPPError {\n return new UPPError(\n `Network error: ${error.message}`,\n ErrorCode.NetworkError,\n provider,\n modality,\n undefined,\n error\n );\n}\n\n/**\n * Creates a UPPError for request timeout.\n *\n * Use this when the request exceeds the configured timeout duration\n * and is aborted by the AbortController.\n *\n * @param timeout - The timeout duration in milliseconds that was exceeded\n * @param provider - Provider identifier for error context\n * @param modality - Request modality for error context\n * @returns A UPPError with TIMEOUT code\n */\nexport function timeoutError(\n timeout: number,\n provider: string,\n modality: Modality\n): UPPError {\n return new UPPError(\n `Request timed out after ${timeout}ms`,\n ErrorCode.Timeout,\n provider,\n modality\n );\n}\n\n/**\n * Creates a UPPError for user-initiated request cancellation.\n *\n * Use this when the request is aborted via a user-provided AbortSignal,\n * distinct from timeout-based cancellation.\n *\n * @param provider - Provider identifier for error context\n * @param modality - Request modality for error context\n * @returns A UPPError with CANCELLED code\n */\nexport function cancelledError(provider: string, modality: Modality): UPPError {\n return new UPPError(\n 'Request was cancelled',\n ErrorCode.Cancelled,\n provider,\n modality\n );\n}\n","/**\n * HTTP fetch utilities with retry, timeout, and error normalization.\n * @module http/fetch\n */\n\nimport type { ProviderConfig, RetryStrategy } from '../types/provider.ts';\nimport type { Modality } from '../types/errors.ts';\nimport { UPPError } from '../types/errors.ts';\nimport {\n normalizeHttpError,\n networkError,\n timeoutError,\n cancelledError,\n} from './errors.ts';\nimport { toError } from '../utils/error.ts';\n\n/** Default request timeout in milliseconds (2 minutes). */\nconst DEFAULT_TIMEOUT = 120000;\nconst MAX_RETRY_AFTER_SECONDS = 3600;\n\ntype ForkableRetryStrategy = RetryStrategy & {\n fork: () => RetryStrategy | undefined;\n};\n\nfunction hasFork(strategy: RetryStrategy | undefined): strategy is ForkableRetryStrategy {\n return !!strategy && typeof (strategy as { fork?: unknown }).fork === 'function';\n}\n\n/**\n * Executes an HTTP fetch request with automatic retry, timeout handling, and error normalization.\n *\n * This function wraps the standard fetch API with additional capabilities:\n * - Configurable timeout with automatic request cancellation (per attempt)\n * - Retry strategy support (exponential backoff, linear, token bucket, etc.)\n * - Pre-request delay support for rate limiting strategies\n * - Automatic Retry-After header parsing and handling\n * - Error normalization to UPPError format\n *\n * @param url - The URL to fetch\n * @param init - Standard fetch RequestInit options (method, headers, body, etc.)\n * @param config - Provider configuration containing fetch customization, timeout, and retry strategy\n * @param provider - Provider identifier for error context (e.g., 'openai', 'anthropic')\n * @param modality - Request modality for error context (e.g., 'llm', 'embedding', 'image')\n * @returns The successful Response object\n *\n * @throws {UPPError} RATE_LIMITED - When rate limited and retries exhausted\n * @throws {UPPError} NETWORK_ERROR - When a network failure occurs\n * @throws {UPPError} TIMEOUT - When the request times out\n * @throws {UPPError} CANCELLED - When the request is aborted via signal\n * @throws {UPPError} Various codes based on HTTP status (see statusToErrorCode)\n *\n * @example\n * ```typescript\n * const response = await doFetch(\n * 'https://api.openai.com/v1/chat/completions',\n * {\n * method: 'POST',\n * headers: { 'Authorization': 'Bearer sk-...' },\n * body: JSON.stringify({ model: 'gpt-4', messages: [] })\n * },\n * { timeout: 30000, retryStrategy: new ExponentialBackoff() },\n * 'openai',\n * 'llm'\n * );\n * ```\n */\nexport async function doFetch(\n url: string,\n init: RequestInit,\n config: ProviderConfig,\n provider: string,\n modality: Modality\n): Promise<Response> {\n const fetchFn = config.fetch ?? fetch;\n const timeout = config.timeout ?? DEFAULT_TIMEOUT;\n const baseStrategy = config.retryStrategy;\n const strategy = hasFork(baseStrategy) ? baseStrategy.fork() : baseStrategy;\n\n let attempt = 0;\n\n while (true) {\n attempt++;\n\n if (strategy?.beforeRequest) {\n const delay = await strategy.beforeRequest();\n if (delay > 0) {\n await sleep(delay);\n }\n }\n\n let response: Response;\n try {\n response = await fetchWithTimeout(\n fetchFn,\n url,\n init,\n timeout,\n provider,\n modality\n );\n } catch (error) {\n if (error instanceof UPPError) {\n if (strategy) {\n const delay = await strategy.onRetry(error, attempt);\n if (delay !== null) {\n await sleep(delay);\n continue;\n }\n }\n throw error;\n }\n\n const uppError = networkError(toError(error), provider, modality);\n\n if (strategy) {\n const delay = await strategy.onRetry(uppError, attempt);\n if (delay !== null) {\n await sleep(delay);\n continue;\n }\n }\n\n throw uppError;\n }\n\n if (!response.ok) {\n const error = await normalizeHttpError(response, provider, modality);\n\n const retryAfterSeconds = parseRetryAfter(\n response.headers.get('Retry-After'),\n config.retryAfterMaxSeconds ?? MAX_RETRY_AFTER_SECONDS\n );\n if (retryAfterSeconds !== null && strategy && 'setRetryAfter' in strategy) {\n (strategy as { setRetryAfter: (s: number) => void }).setRetryAfter(\n retryAfterSeconds\n );\n }\n\n if (strategy) {\n const delay = await strategy.onRetry(error, attempt);\n if (delay !== null) {\n await sleep(delay);\n continue;\n }\n }\n\n throw error;\n }\n\n strategy?.reset?.();\n\n return response;\n }\n}\n\n/**\n * Executes a fetch request with configurable timeout.\n *\n * Creates an AbortController to cancel the request if it exceeds the timeout.\n * Properly handles both user-provided abort signals and timeout-based cancellation,\n * throwing appropriate error types for each case.\n *\n * @param fetchFn - The fetch function to use (allows custom implementations)\n * @param url - The URL to fetch\n * @param init - Standard fetch RequestInit options\n * @param timeout - Maximum time in milliseconds before aborting\n * @param provider - Provider identifier for error context\n * @param modality - Request modality for error context\n * @returns The Response from the fetch call\n *\n * @throws {UPPError} TIMEOUT - When the timeout is exceeded\n * @throws {UPPError} CANCELLED - When cancelled via user-provided signal\n * @throws {Error} Network errors are passed through unchanged\n */\nasync function fetchWithTimeout(\n fetchFn: typeof fetch,\n url: string,\n init: RequestInit,\n timeout: number,\n provider: string,\n modality: Modality\n): Promise<Response> {\n const existingSignal = init.signal;\n\n // Check if already aborted before starting\n if (existingSignal?.aborted) {\n throw cancelledError(provider, modality);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const onAbort = () => controller.abort();\n if (existingSignal) {\n existingSignal.addEventListener('abort', onAbort, { once: true });\n }\n\n try {\n const response = await fetchFn(url, {\n ...init,\n signal: controller.signal,\n });\n return response;\n } catch (error) {\n if (toError(error).name === 'AbortError') {\n if (existingSignal?.aborted) {\n throw cancelledError(provider, modality);\n }\n throw timeoutError(timeout, provider, modality);\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n if (existingSignal) {\n existingSignal.removeEventListener('abort', onAbort);\n }\n }\n}\n\n/**\n * Delays execution for a specified duration.\n *\n * @param ms - Duration to sleep in milliseconds\n * @returns Promise that resolves after the specified delay\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Executes an HTTP fetch request for streaming responses.\n *\n * Unlike {@link doFetch}, this function returns the response immediately without\n * checking the HTTP status. This is necessary for Server-Sent Events (SSE) and\n * other streaming protocols where error information may be embedded in the stream.\n *\n * The caller is responsible for:\n * - Checking response.ok and handling HTTP errors\n * - Parsing the response stream (e.g., using parseSSEStream)\n * - Handling stream-specific error conditions\n *\n * Retries are not performed for streaming requests since partial data may have\n * already been consumed by the caller.\n *\n * @param url - The URL to fetch\n * @param init - Standard fetch RequestInit options\n * @param config - Provider configuration containing fetch customization and timeout\n * @param provider - Provider identifier for error context\n * @param modality - Request modality for error context\n * @returns The Response object (may have non-2xx status)\n *\n * @throws {UPPError} NETWORK_ERROR - When a network failure occurs\n * @throws {UPPError} TIMEOUT - When the request times out\n * @throws {UPPError} CANCELLED - When the request is aborted via signal\n *\n * @example\n * ```typescript\n * const response = await doStreamFetch(\n * 'https://api.openai.com/v1/chat/completions',\n * {\n * method: 'POST',\n * headers: { 'Authorization': 'Bearer sk-...' },\n * body: JSON.stringify({ model: 'gpt-4', messages: [], stream: true })\n * },\n * { timeout: 120000 },\n * 'openai',\n * 'llm'\n * );\n *\n * if (!response.ok) {\n * throw await normalizeHttpError(response, 'openai', 'llm');\n * }\n *\n * for await (const event of parseSSEStream(response.body!)) {\n * console.log(event);\n * }\n * ```\n */\nexport async function doStreamFetch(\n url: string,\n init: RequestInit,\n config: ProviderConfig,\n provider: string,\n modality: Modality\n): Promise<Response> {\n const fetchFn = config.fetch ?? fetch;\n const timeout = config.timeout ?? DEFAULT_TIMEOUT;\n const baseStrategy = config.retryStrategy;\n const strategy = hasFork(baseStrategy) ? baseStrategy.fork() : baseStrategy;\n\n if (strategy?.beforeRequest) {\n const delay = await strategy.beforeRequest();\n if (delay > 0) {\n await sleep(delay);\n }\n }\n\n try {\n const response = await fetchWithTimeout(\n fetchFn,\n url,\n init,\n timeout,\n provider,\n modality\n );\n return response;\n } catch (error) {\n if (error instanceof UPPError) {\n throw error;\n }\n throw networkError(toError(error), provider, modality);\n }\n}\n\n/**\n * Parses Retry-After header values into seconds.\n *\n * Supports both delta-seconds and HTTP-date formats.\n */\nfunction parseRetryAfter(headerValue: string | null, maxSeconds: number): number | null {\n if (!headerValue) {\n return null;\n }\n\n const seconds = parseInt(headerValue, 10);\n if (!Number.isNaN(seconds)) {\n return Math.min(maxSeconds, Math.max(0, seconds));\n }\n\n const dateMillis = Date.parse(headerValue);\n if (Number.isNaN(dateMillis)) {\n return null;\n }\n\n const deltaMs = dateMillis - Date.now();\n if (deltaMs <= 0) {\n return 0;\n }\n\n const deltaSeconds = Math.ceil(deltaMs / 1000);\n return Math.min(maxSeconds, Math.max(0, deltaSeconds));\n}\n"],"mappings":";AAiCO,IAAM,YAAY;AAAA;AAAA,EAEvB,sBAAsB;AAAA;AAAA,EAEtB,aAAa;AAAA;AAAA,EAEb,uBAAuB;AAAA;AAAA,EAEvB,eAAe;AAAA;AAAA,EAEf,gBAAgB;AAAA;AAAA,EAEhB,iBAAiB;AAAA;AAAA,EAEjB,iBAAiB;AAAA;AAAA,EAEjB,eAAe;AAAA;AAAA,EAEf,eAAe;AAAA;AAAA,EAEf,cAAc;AAAA;AAAA,EAEd,SAAS;AAAA;AAAA,EAET,WAAW;AACb;AAwBO,IAAM,eAAe;AAAA;AAAA,EAE1B,KAAK;AAAA;AAAA,EAEL,WAAW;AAAA;AAAA,EAEX,OAAO;AAAA;AAAA,EAEP,OAAO;AAAA;AAAA,EAEP,OAAO;AACT;AAsDO,IAAM,WAAN,MAAM,kBAAiB,MAAM;AAAA;AAAA,EAEzB;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGS;AAAA;AAAA,EAGA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYzB,YACE,SACA,MACA,UACA,UACA,YACA,OACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,WAAW;AAChB,SAAK,aAAa;AAClB,SAAK,QAAQ;AAEb,QAAI,MAAM,mBAAmB;AAC3B,YAAM,kBAAkB,MAAM,SAAQ;AAAA,IACxC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOS,WAAmB;AAC1B,QAAI,MA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eAAe,OAAO;AAC5B,QAAM,WAAW,QAAQ,YAAY,IAAI,aAAa,KAAK,IAAI;AAE/D,MAAI,UAAU,eAAe;AAC3B,UAAM,QAAQ,MAAM,SAAS,cAAc;AAC3C,QAAI,QAAQ,GAAG;AACb,YAAM,MAAM,KAAK;AAAA,IACnB;AAAA,EACF;AAEA,MAAI;AACF,UAAM,WAAW,MAAM;AAAA,MACrB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,iBAAiB,UAAU;AAC7B,YAAM;AAAA,IACR;AACA,UAAM,aAAa,QAAQ,KAAK,GAAG,UAAU,QAAQ;AAAA,EACvD;AACF;AAOA,SAAS,gBAAgB,aAA4B,YAAmC;AACtF,MAAI,CAAC,aAAa;AAChB,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,SAAS,aAAa,EAAE;AACxC,MAAI,CAAC,OAAO,MAAM,OAAO,GAAG;AAC1B,WAAO,KAAK,IAAI,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC;AAAA,EAClD;AAEA,QAAM,aAAa,KAAK,MAAM,WAAW;AACzC,MAAI,OAAO,MAAM,UAAU,GAAG;AAC5B,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,aAAa,KAAK,IAAI;AACtC,MAAI,WAAW,GAAG;AAChB,WAAO;AAAA,EACT;AAEA,QAAM,eAAe,KAAK,KAAK,UAAU,GAAI;AAC7C,SAAO,KAAK,IAAI,YAAY,KAAK,IAAI,GAAG,YAAY,CAAC;AACvD;","names":[]}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ErrorCode
|
|
3
|
+
} from "./chunk-QNJO7DSD.js";
|
|
4
|
+
|
|
1
5
|
// src/http/retry.ts
|
|
2
6
|
var ExponentialBackoff = class {
|
|
3
7
|
maxAttempts;
|
|
@@ -47,7 +51,7 @@ var ExponentialBackoff = class {
|
|
|
47
51
|
* @returns True if the error is transient and retryable
|
|
48
52
|
*/
|
|
49
53
|
isRetryable(error) {
|
|
50
|
-
return error.code ===
|
|
54
|
+
return error.code === ErrorCode.RateLimited || error.code === ErrorCode.NetworkError || error.code === ErrorCode.Timeout || error.code === ErrorCode.ProviderError;
|
|
51
55
|
}
|
|
52
56
|
};
|
|
53
57
|
var LinearBackoff = class {
|
|
@@ -87,7 +91,7 @@ var LinearBackoff = class {
|
|
|
87
91
|
* @returns True if the error is transient and retryable
|
|
88
92
|
*/
|
|
89
93
|
isRetryable(error) {
|
|
90
|
-
return error.code ===
|
|
94
|
+
return error.code === ErrorCode.RateLimited || error.code === ErrorCode.NetworkError || error.code === ErrorCode.Timeout || error.code === ErrorCode.ProviderError;
|
|
91
95
|
}
|
|
92
96
|
};
|
|
93
97
|
var NoRetry = class {
|
|
@@ -161,7 +165,7 @@ var TokenBucket = class {
|
|
|
161
165
|
if (attempt > this.maxAttempts) {
|
|
162
166
|
return null;
|
|
163
167
|
}
|
|
164
|
-
if (error.code !==
|
|
168
|
+
if (error.code !== ErrorCode.RateLimited) {
|
|
165
169
|
return null;
|
|
166
170
|
}
|
|
167
171
|
const msPerToken = 1e3 / this.refillRate;
|
|
@@ -240,7 +244,7 @@ var RetryAfterStrategy = class _RetryAfterStrategy {
|
|
|
240
244
|
if (attempt > this.maxAttempts) {
|
|
241
245
|
return null;
|
|
242
246
|
}
|
|
243
|
-
if (error.code !==
|
|
247
|
+
if (error.code !== ErrorCode.RateLimited) {
|
|
244
248
|
return null;
|
|
245
249
|
}
|
|
246
250
|
const delay = this.lastRetryAfter ?? this.fallbackDelay;
|
|
@@ -256,4 +260,4 @@ export {
|
|
|
256
260
|
TokenBucket,
|
|
257
261
|
RetryAfterStrategy
|
|
258
262
|
};
|
|
259
|
-
//# sourceMappingURL=chunk-
|
|
263
|
+
//# sourceMappingURL=chunk-SBCATNHA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/http/retry.ts"],"sourcesContent":["/**\n * Retry strategies for handling transient failures in HTTP requests.\n * @module http/retry\n */\n\nimport type { RetryStrategy } from '../types/provider.ts';\nimport { ErrorCode, type UPPError } from '../types/errors.ts';\n\n/**\n * Implements exponential backoff with optional jitter for retry delays.\n *\n * The delay between retries doubles with each attempt, helping to:\n * - Avoid overwhelming servers during outages\n * - Reduce thundering herd effects when many clients retry simultaneously\n * - Give transient issues time to resolve\n *\n * Delay formula: min(baseDelay * 2^(attempt-1), maxDelay)\n * With jitter: delay * random(0.5, 1.0)\n *\n * Only retries on transient errors: RATE_LIMITED, NETWORK_ERROR, TIMEOUT, PROVIDER_ERROR\n *\n * @implements {RetryStrategy}\n *\n * @example\n * ```typescript\n * // Default configuration (3 retries, 1s base, 30s max, jitter enabled)\n * const retry = new ExponentialBackoff();\n *\n * // Custom configuration\n * const customRetry = new ExponentialBackoff({\n * maxAttempts: 5, // Up to 5 retry attempts\n * baseDelay: 500, // Start with 500ms delay\n * maxDelay: 60000, // Cap at 60 seconds\n * jitter: false // Disable random jitter\n * });\n *\n * // Use with provider\n * const provider = createOpenAI({\n * retryStrategy: customRetry\n * });\n * ```\n */\nexport class ExponentialBackoff implements RetryStrategy {\n private maxAttempts: number;\n private baseDelay: number;\n private maxDelay: number;\n private jitter: boolean;\n\n /**\n * Creates a new ExponentialBackoff instance.\n *\n * @param options - Configuration options\n * @param options.maxAttempts - Maximum number of retry attempts (default: 3)\n * @param options.baseDelay - Initial delay in milliseconds (default: 1000)\n * @param options.maxDelay - Maximum delay cap in milliseconds (default: 30000)\n * @param options.jitter - Whether to add random jitter to delays (default: true)\n */\n constructor(options: {\n maxAttempts?: number;\n baseDelay?: number;\n maxDelay?: number;\n jitter?: boolean;\n } = {}) {\n this.maxAttempts = options.maxAttempts ?? 3;\n this.baseDelay = options.baseDelay ?? 1000;\n this.maxDelay = options.maxDelay ?? 30000;\n this.jitter = options.jitter ?? true;\n }\n\n /**\n * Determines whether to retry and calculates the delay.\n *\n * @param error - The error that triggered the retry\n * @param attempt - Current attempt number (1-indexed)\n * @returns Delay in milliseconds before next retry, or null to stop retrying\n */\n onRetry(error: UPPError, attempt: number): number | null {\n if (attempt > this.maxAttempts) {\n return null;\n }\n\n if (!this.isRetryable(error)) {\n return null;\n }\n\n let delay = this.baseDelay * Math.pow(2, attempt - 1);\n delay = Math.min(delay, this.maxDelay);\n\n if (this.jitter) {\n delay = delay * (0.5 + Math.random());\n }\n\n return Math.floor(delay);\n }\n\n /**\n * Checks if an error is eligible for retry.\n *\n * @param error - The error to evaluate\n * @returns True if the error is transient and retryable\n */\n private isRetryable(error: UPPError): boolean {\n return (\n error.code === ErrorCode.RateLimited ||\n error.code === ErrorCode.NetworkError ||\n error.code === ErrorCode.Timeout ||\n error.code === ErrorCode.ProviderError\n );\n }\n}\n\n/**\n * Implements linear backoff where delays increase proportionally with each attempt.\n *\n * Unlike exponential backoff, linear backoff increases delays at a constant rate:\n * - Attempt 1: delay * 1 (e.g., 1000ms)\n * - Attempt 2: delay * 2 (e.g., 2000ms)\n * - Attempt 3: delay * 3 (e.g., 3000ms)\n *\n * This strategy is simpler and more predictable than exponential backoff,\n * suitable for scenarios where gradual delay increase is preferred over\n * aggressive backoff.\n *\n * Only retries on transient errors: RATE_LIMITED, NETWORK_ERROR, TIMEOUT, PROVIDER_ERROR\n *\n * @implements {RetryStrategy}\n *\n * @example\n * ```typescript\n * // Default configuration (3 retries, 1s delay increment)\n * const retry = new LinearBackoff();\n *\n * // Custom configuration\n * const customRetry = new LinearBackoff({\n * maxAttempts: 4, // Up to 4 retry attempts\n * delay: 2000 // 2s, 4s, 6s, 8s delays\n * });\n *\n * // Use with provider\n * const provider = createAnthropic({\n * retryStrategy: customRetry\n * });\n * ```\n */\nexport class LinearBackoff implements RetryStrategy {\n private maxAttempts: number;\n private delay: number;\n\n /**\n * Creates a new LinearBackoff instance.\n *\n * @param options - Configuration options\n * @param options.maxAttempts - Maximum number of retry attempts (default: 3)\n * @param options.delay - Base delay multiplier in milliseconds (default: 1000)\n */\n constructor(options: {\n maxAttempts?: number;\n delay?: number;\n } = {}) {\n this.maxAttempts = options.maxAttempts ?? 3;\n this.delay = options.delay ?? 1000;\n }\n\n /**\n * Determines whether to retry and calculates the linear delay.\n *\n * @param error - The error that triggered the retry\n * @param attempt - Current attempt number (1-indexed)\n * @returns Delay in milliseconds (delay * attempt), or null to stop retrying\n */\n onRetry(error: UPPError, attempt: number): number | null {\n if (attempt > this.maxAttempts) {\n return null;\n }\n\n if (!this.isRetryable(error)) {\n return null;\n }\n\n return this.delay * attempt;\n }\n\n /**\n * Checks if an error is eligible for retry.\n *\n * @param error - The error to evaluate\n * @returns True if the error is transient and retryable\n */\n private isRetryable(error: UPPError): boolean {\n return (\n error.code === ErrorCode.RateLimited ||\n error.code === ErrorCode.NetworkError ||\n error.code === ErrorCode.Timeout ||\n error.code === ErrorCode.ProviderError\n );\n }\n}\n\n/**\n * Disables all retry behavior, failing immediately on any error.\n *\n * Use this strategy when:\n * - Retries are handled at a higher level in your application\n * - You want immediate failure feedback\n * - The operation is not idempotent\n * - Time sensitivity requires fast failure\n *\n * @implements {RetryStrategy}\n *\n * @example\n * ```typescript\n * // Disable retries for time-sensitive operations\n * const provider = createOpenAI({\n * retryStrategy: new NoRetry()\n * });\n * ```\n */\nexport class NoRetry implements RetryStrategy {\n /**\n * Always returns null to indicate no retry should be attempted.\n *\n * @returns Always returns null\n */\n onRetry(_error: UPPError, _attempt: number): null {\n return null;\n }\n}\n\n/**\n * Implements token bucket rate limiting with automatic refill.\n *\n * The token bucket algorithm provides smooth rate limiting by:\n * - Maintaining a bucket of tokens that replenish over time\n * - Consuming one token per request\n * - Delaying requests when the bucket is empty\n * - Allowing burst traffic up to the bucket capacity\n *\n * This is particularly useful for:\n * - Client-side rate limiting to avoid hitting API rate limits\n * - Smoothing request patterns to maintain consistent throughput\n * - Preventing accidental API abuse\n *\n * Unlike other retry strategies, TokenBucket implements {@link beforeRequest}\n * to proactively delay requests before they are made.\n *\n * @implements {RetryStrategy}\n *\n * @example\n * ```typescript\n * // Allow 10 requests burst, refill 1 token per second\n * const bucket = new TokenBucket({\n * maxTokens: 10, // Burst capacity\n * refillRate: 1, // Tokens per second\n * maxAttempts: 3 // Retry attempts on rate limit\n * });\n *\n * // Aggressive rate limiting: 5 req/s sustained\n * const strictBucket = new TokenBucket({\n * maxTokens: 5,\n * refillRate: 5\n * });\n *\n * // Use with provider\n * const provider = createOpenAI({\n * retryStrategy: bucket\n * });\n * ```\n */\nexport class TokenBucket implements RetryStrategy {\n private tokens: number;\n private maxTokens: number;\n private refillRate: number;\n private lastRefill: number;\n private maxAttempts: number;\n private lock: Promise<void>;\n\n /**\n * Creates a new TokenBucket instance.\n *\n * @param options - Configuration options\n * @param options.maxTokens - Maximum bucket capacity (default: 10)\n * @param options.refillRate - Tokens added per second (default: 1)\n * @param options.maxAttempts - Maximum retry attempts on rate limit (default: 3)\n */\n constructor(options: {\n maxTokens?: number;\n refillRate?: number;\n maxAttempts?: number;\n } = {}) {\n this.maxTokens = options.maxTokens ?? 10;\n this.refillRate = options.refillRate ?? 1;\n this.maxAttempts = options.maxAttempts ?? 3;\n this.tokens = this.maxTokens;\n this.lastRefill = Date.now();\n this.lock = Promise.resolve();\n }\n\n /**\n * Called before each request to consume a token or calculate wait time.\n *\n * Refills the bucket based on elapsed time, then either:\n * - Returns 0 if a token is available (consumed immediately)\n * - Returns the wait time in milliseconds until the next token\n *\n * This method may allow tokens to go negative to reserve future capacity\n * and avoid concurrent callers oversubscribing the same refill.\n *\n * @returns Delay in milliseconds before the request can proceed\n */\n beforeRequest(): Promise<number> {\n return this.withLock(() => {\n this.refill();\n\n if (this.tokens >= 1) {\n this.tokens -= 1;\n return 0;\n }\n\n const deficit = 1 - this.tokens;\n const msPerToken = 1000 / this.refillRate;\n this.tokens -= 1;\n return Math.ceil(deficit * msPerToken);\n });\n }\n\n /**\n * Handles retry logic for rate-limited requests.\n *\n * Only retries on RATE_LIMITED errors, waiting for bucket refill.\n *\n * @param error - The error that triggered the retry\n * @param attempt - Current attempt number (1-indexed)\n * @returns Delay in milliseconds (time for 2 tokens), or null to stop\n */\n onRetry(error: UPPError, attempt: number): number | null {\n if (attempt > this.maxAttempts) {\n return null;\n }\n\n if (error.code !== ErrorCode.RateLimited) {\n return null;\n }\n\n const msPerToken = 1000 / this.refillRate;\n return Math.ceil(msPerToken * 2);\n }\n\n /**\n * Resets the bucket to full capacity.\n *\n * Called automatically on successful requests to restore available tokens.\n */\n reset(): void {\n void this.withLock(() => {\n this.tokens = this.maxTokens;\n this.lastRefill = Date.now();\n });\n }\n\n /**\n * Refills the bucket based on elapsed time since last refill.\n */\n private refill(): void {\n const now = Date.now();\n const elapsed = (now - this.lastRefill) / 1000;\n const newTokens = elapsed * this.refillRate;\n\n this.tokens = Math.min(this.maxTokens, this.tokens + newTokens);\n this.lastRefill = now;\n }\n\n private async withLock<T>(fn: () => T | Promise<T>): Promise<T> {\n const next = this.lock.then(fn, fn);\n this.lock = next.then(() => undefined, () => undefined);\n return next;\n }\n}\n\n/**\n * Respects server-provided Retry-After headers for optimal retry timing.\n *\n * When servers return a 429 (Too Many Requests) response, they often include\n * a Retry-After header indicating when the client should retry. This strategy\n * uses that information for precise retry timing.\n *\n * Benefits over fixed backoff strategies:\n * - Follows server recommendations for optimal retry timing\n * - Avoids retrying too early and wasting requests\n * - Adapts to dynamic rate limit windows\n *\n * If no Retry-After header is provided, falls back to a configurable delay.\n * Only retries on RATE_LIMITED errors.\n *\n * @implements {RetryStrategy}\n *\n * @example\n * ```typescript\n * // Use server-recommended retry timing\n * const retryAfter = new RetryAfterStrategy({\n * maxAttempts: 5, // Retry up to 5 times\n * fallbackDelay: 10000 // 10s fallback if no header\n * });\n *\n * // The doFetch function automatically calls setRetryAfter\n * // when a Retry-After header is present in the response\n *\n * const provider = createOpenAI({\n * retryStrategy: retryAfter\n * });\n * ```\n */\nexport class RetryAfterStrategy implements RetryStrategy {\n private maxAttempts: number;\n private fallbackDelay: number;\n private lastRetryAfter?: number;\n\n /**\n * Creates a new RetryAfterStrategy instance.\n *\n * @param options - Configuration options\n * @param options.maxAttempts - Maximum number of retry attempts (default: 3)\n * @param options.fallbackDelay - Delay in ms when no Retry-After header (default: 5000)\n */\n constructor(options: {\n maxAttempts?: number;\n fallbackDelay?: number;\n } = {}) {\n this.maxAttempts = options.maxAttempts ?? 3;\n this.fallbackDelay = options.fallbackDelay ?? 5000;\n }\n\n /**\n * Creates a request-scoped copy of this strategy.\n */\n fork(): RetryAfterStrategy {\n return new RetryAfterStrategy({\n maxAttempts: this.maxAttempts,\n fallbackDelay: this.fallbackDelay,\n });\n }\n\n /**\n * Sets the retry delay from a Retry-After header value.\n *\n * Called by doFetch when a Retry-After header is present in the response.\n * The value is used for the next onRetry call and then cleared.\n *\n * @param seconds - The Retry-After value in seconds\n */\n setRetryAfter(seconds: number): void {\n this.lastRetryAfter = seconds * 1000;\n }\n\n /**\n * Determines retry delay using Retry-After header or fallback.\n *\n * @param error - The error that triggered the retry\n * @param attempt - Current attempt number (1-indexed)\n * @returns Delay from Retry-After header or fallback, null to stop\n */\n onRetry(error: UPPError, attempt: number): number | null {\n if (attempt > this.maxAttempts) {\n return null;\n }\n\n if (error.code !== ErrorCode.RateLimited) {\n return null;\n }\n\n const delay = this.lastRetryAfter ?? this.fallbackDelay;\n this.lastRetryAfter = undefined;\n return delay;\n }\n}\n"],"mappings":";;;;;AA0CO,IAAM,qBAAN,MAAkD;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWR,YAAY,UAKR,CAAC,GAAG;AACN,SAAK,cAAc,QAAQ,eAAe;AAC1C,SAAK,YAAY,QAAQ,aAAa;AACtC,SAAK,WAAW,QAAQ,YAAY;AACpC,SAAK,SAAS,QAAQ,UAAU;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,QAAQ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
4
|
toError
|
|
4
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-QNJO7DSD.js";
|
|
5
6
|
|
|
6
7
|
// src/http/json.ts
|
|
7
8
|
async function parseJsonResponse(response, provider, modality) {
|
|
@@ -12,7 +13,7 @@ async function parseJsonResponse(response, provider, modality) {
|
|
|
12
13
|
const cause = toError(error);
|
|
13
14
|
throw new UPPError(
|
|
14
15
|
"Failed to read response body",
|
|
15
|
-
|
|
16
|
+
ErrorCode.InvalidResponse,
|
|
16
17
|
provider,
|
|
17
18
|
modality,
|
|
18
19
|
response.status,
|
|
@@ -22,7 +23,7 @@ async function parseJsonResponse(response, provider, modality) {
|
|
|
22
23
|
if (!bodyText) {
|
|
23
24
|
throw new UPPError(
|
|
24
25
|
"Empty response body",
|
|
25
|
-
|
|
26
|
+
ErrorCode.InvalidResponse,
|
|
26
27
|
provider,
|
|
27
28
|
modality,
|
|
28
29
|
response.status
|
|
@@ -34,7 +35,7 @@ async function parseJsonResponse(response, provider, modality) {
|
|
|
34
35
|
const cause = toError(error);
|
|
35
36
|
throw new UPPError(
|
|
36
37
|
"Failed to parse JSON response",
|
|
37
|
-
|
|
38
|
+
ErrorCode.InvalidResponse,
|
|
38
39
|
provider,
|
|
39
40
|
modality,
|
|
40
41
|
response.status,
|
|
@@ -46,4 +47,4 @@ async function parseJsonResponse(response, provider, modality) {
|
|
|
46
47
|
export {
|
|
47
48
|
parseJsonResponse
|
|
48
49
|
};
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
50
|
+
//# sourceMappingURL=chunk-Z6DKC37J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/http/json.ts"],"sourcesContent":["/**\n * @fileoverview JSON response parsing utilities.\n *\n * @module http/json\n */\n\nimport { ErrorCode, UPPError, type Modality } from '../types/errors.ts';\nimport { toError } from '../utils/error.ts';\n\n/**\n * Parses a JSON response body with normalized error handling.\n *\n * @typeParam T - Expected JSON shape\n * @param response - Fetch response to parse\n * @param provider - Provider identifier for error context\n * @param modality - Modality for error context\n * @returns Parsed JSON object\n * @throws {UPPError} INVALID_RESPONSE when JSON parsing fails or body is empty\n */\nexport async function parseJsonResponse<T>(\n response: Response,\n provider: string,\n modality: Modality\n): Promise<T> {\n let bodyText: string;\n try {\n bodyText = await response.text();\n } catch (error) {\n const cause = toError(error);\n throw new UPPError(\n 'Failed to read response body',\n ErrorCode.InvalidResponse,\n provider,\n modality,\n response.status,\n cause\n );\n }\n\n if (!bodyText) {\n throw new UPPError(\n 'Empty response body',\n ErrorCode.InvalidResponse,\n provider,\n modality,\n response.status\n );\n }\n\n try {\n return JSON.parse(bodyText) as T;\n } catch (error) {\n const cause = toError(error);\n throw new UPPError(\n 'Failed to parse JSON response',\n ErrorCode.InvalidResponse,\n provider,\n modality,\n response.status,\n cause\n );\n }\n}\n"],"mappings":";;;;;;;AAmBA,eAAsB,kBACpB,UACA,UACA,UACY;AACZ,MAAI;AACJ,MAAI;AACF,eAAW,MAAM,SAAS,KAAK;AAAA,EACjC,SAAS,OAAO;AACd,UAAM,QAAQ,QAAQ,KAAK;AAC3B,UAAM,IAAI;AAAA,MACR;AAAA,MACA,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA,SAAS;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAAC,UAAU;AACb,UAAM,IAAI;AAAA,MACR;AAAA,MACA,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA,SAAS;AAAA,IACX;AAAA,EACF;AAEA,MAAI;AACF,WAAO,KAAK,MAAM,QAAQ;AAAA,EAC5B,SAAS,OAAO;AACd,UAAM,QAAQ,QAAQ,KAAK;AAC3B,UAAM,IAAI;AAAA,MACR;AAAA,MACA,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA,SAAS;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/google/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ProviderConfig, g as Provider } from '../provider-
|
|
1
|
+
import { a as ProviderConfig, g as Provider } from '../provider-DR1yins0.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Provider-specific parameters for Google Gemini API requests.
|
|
@@ -893,6 +893,7 @@ interface GoogleEmbedParams {
|
|
|
893
893
|
* ```typescript
|
|
894
894
|
* import { google } from './providers/google';
|
|
895
895
|
* import { llm } from './core/llm';
|
|
896
|
+
* import { StreamEventType } from './types/stream';
|
|
896
897
|
*
|
|
897
898
|
* const gemini = llm({
|
|
898
899
|
* model: google('gemini-1.5-pro'),
|
|
@@ -904,7 +905,7 @@ interface GoogleEmbedParams {
|
|
|
904
905
|
*
|
|
905
906
|
* const stream = gemini.stream('Tell me a story');
|
|
906
907
|
* for await (const event of stream) {
|
|
907
|
-
* if (event.type ===
|
|
908
|
+
* if (event.type === StreamEventType.TextDelta) {
|
|
908
909
|
* process.stdout.write(event.delta.text ?? '');
|
|
909
910
|
* }
|
|
910
911
|
* }
|