@cloudflare/tanstack-ai 0.1.2 → 0.1.4
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 +42 -0
- package/dist/_tsup-dts-rollup.d.cts +13 -4
- package/dist/_tsup-dts-rollup.d.ts +13 -4
- package/dist/adapters/anthropic.cjs +3 -3
- package/dist/adapters/anthropic.js +2 -2
- package/dist/adapters/grok.cjs +3 -3
- package/dist/adapters/grok.js +2 -2
- package/dist/adapters/openai.cjs +3 -3
- package/dist/adapters/openai.js +2 -2
- package/dist/adapters/openrouter.cjs +3 -3
- package/dist/adapters/openrouter.js +2 -2
- package/dist/adapters/workers-ai-image.cjs +3 -3
- package/dist/adapters/workers-ai-image.js +2 -2
- package/dist/adapters/workers-ai-summarize.cjs +3 -3
- package/dist/adapters/workers-ai-summarize.js +2 -2
- package/dist/adapters/workers-ai-transcription.cjs +3 -3
- package/dist/adapters/workers-ai-transcription.js +2 -2
- package/dist/adapters/workers-ai-tts.cjs +3 -3
- package/dist/adapters/workers-ai-tts.js +2 -2
- package/dist/adapters/workers-ai.cjs +3 -3
- package/dist/adapters/workers-ai.js +2 -2
- package/dist/{chunk-LG2I3ANT.cjs → chunk-32U73O6E.cjs} +49 -33
- package/dist/chunk-32U73O6E.cjs.map +1 -0
- package/dist/{chunk-ZHTFBZXJ.cjs → chunk-3PJHW45X.cjs} +6 -6
- package/dist/{chunk-ZHTFBZXJ.cjs.map → chunk-3PJHW45X.cjs.map} +1 -1
- package/dist/{chunk-T5KPTTLK.js → chunk-DG46OSFY.js} +2 -2
- package/dist/{chunk-IDPLTBQX.cjs → chunk-H24HFVUJ.cjs} +6 -6
- package/dist/{chunk-IDPLTBQX.cjs.map → chunk-H24HFVUJ.cjs.map} +1 -1
- package/dist/{chunk-JK5ZFOZZ.js → chunk-I2MCLFJ5.js} +2 -2
- package/dist/{chunk-OKU3GB5P.js → chunk-IPEZXCDR.js} +2 -2
- package/dist/{chunk-ARLHMZ5B.cjs → chunk-KDVHOUEP.cjs} +6 -6
- package/dist/{chunk-ARLHMZ5B.cjs.map → chunk-KDVHOUEP.cjs.map} +1 -1
- package/dist/{chunk-UWBO33IG.cjs → chunk-KW27GIQL.cjs} +5 -5
- package/dist/{chunk-UWBO33IG.cjs.map → chunk-KW27GIQL.cjs.map} +1 -1
- package/dist/{chunk-7KZQWFUE.cjs → chunk-MMTLH53H.cjs} +3 -3
- package/dist/chunk-MMTLH53H.cjs.map +1 -0
- package/dist/{chunk-DSBHOQQ4.js → chunk-MOAWHNNP.js} +2 -2
- package/dist/chunk-MOAWHNNP.js.map +1 -0
- package/dist/{chunk-3KUHT3K6.js → chunk-NSWLVANP.js} +46 -30
- package/dist/chunk-NSWLVANP.js.map +1 -0
- package/dist/{chunk-Y7W7NDVS.js → chunk-OGAH3FYW.js} +2 -2
- package/dist/{chunk-2QN5XFI2.js → chunk-QMRONSLN.js} +2 -2
- package/dist/{chunk-5A2F2QCL.js → chunk-RWLCEKT6.js} +2 -2
- package/dist/{chunk-O7MBRPCW.js → chunk-S5QBHI6O.js} +26 -29
- package/dist/chunk-S5QBHI6O.js.map +1 -0
- package/dist/{chunk-ICHJ2G63.cjs → chunk-TG4UQPGB.cjs} +3 -3
- package/dist/{chunk-ICHJ2G63.cjs.map → chunk-TG4UQPGB.cjs.map} +1 -1
- package/dist/{chunk-7SKFZ4SU.cjs → chunk-U2PMR3PT.cjs} +5 -5
- package/dist/{chunk-7SKFZ4SU.cjs.map → chunk-U2PMR3PT.cjs.map} +1 -1
- package/dist/{chunk-IMURYJRF.cjs → chunk-U5NL4EM4.cjs} +33 -36
- package/dist/chunk-U5NL4EM4.cjs.map +1 -0
- package/dist/{chunk-AYTKQRE4.cjs → chunk-XFQ3QESX.cjs} +6 -6
- package/dist/{chunk-AYTKQRE4.cjs.map → chunk-XFQ3QESX.cjs.map} +1 -1
- package/dist/{chunk-DZZVI4W5.js → chunk-ZJMMBD6H.js} +2 -2
- package/dist/index.cjs +11 -11
- package/dist/index.js +10 -10
- package/package.json +11 -10
- package/dist/chunk-3KUHT3K6.js.map +0 -1
- package/dist/chunk-7KZQWFUE.cjs.map +0 -1
- package/dist/chunk-DSBHOQQ4.js.map +0 -1
- package/dist/chunk-IMURYJRF.cjs.map +0 -1
- package/dist/chunk-LG2I3ANT.cjs.map +0 -1
- package/dist/chunk-O7MBRPCW.js.map +0 -1
- /package/dist/{chunk-T5KPTTLK.js.map → chunk-DG46OSFY.js.map} +0 -0
- /package/dist/{chunk-JK5ZFOZZ.js.map → chunk-I2MCLFJ5.js.map} +0 -0
- /package/dist/{chunk-OKU3GB5P.js.map → chunk-IPEZXCDR.js.map} +0 -0
- /package/dist/{chunk-Y7W7NDVS.js.map → chunk-OGAH3FYW.js.map} +0 -0
- /package/dist/{chunk-2QN5XFI2.js.map → chunk-QMRONSLN.js.map} +0 -0
- /package/dist/{chunk-5A2F2QCL.js.map → chunk-RWLCEKT6.js.map} +0 -0
- /package/dist/{chunk-DZZVI4W5.js.map → chunk-ZJMMBD6H.js.map} +0 -0
|
@@ -54,7 +54,9 @@ function createGatewayFetch(provider, config, headers = {}) {
|
|
|
54
54
|
query
|
|
55
55
|
};
|
|
56
56
|
if (provider === "workers-ai") {
|
|
57
|
-
request.endpoint
|
|
57
|
+
if (!request.endpoint.startsWith("run/")) {
|
|
58
|
+
request.endpoint = `run/${query.model}`;
|
|
59
|
+
}
|
|
58
60
|
delete query.model;
|
|
59
61
|
delete query.instructions;
|
|
60
62
|
}
|
|
@@ -85,27 +87,10 @@ function normalizeMessagesForBinding(messages) {
|
|
|
85
87
|
if (normalized.content === null || normalized.content === void 0) {
|
|
86
88
|
normalized.content = "";
|
|
87
89
|
}
|
|
88
|
-
if (normalized.tool_call_id && typeof normalized.tool_call_id === "string") {
|
|
89
|
-
normalized.tool_call_id = sanitizeToolCallId(normalized.tool_call_id);
|
|
90
|
-
}
|
|
91
|
-
if (Array.isArray(normalized.tool_calls)) {
|
|
92
|
-
normalized.tool_calls = normalized.tool_calls.map(
|
|
93
|
-
(tc) => {
|
|
94
|
-
if (tc.id && typeof tc.id === "string") {
|
|
95
|
-
return { ...tc, id: sanitizeToolCallId(tc.id) };
|
|
96
|
-
}
|
|
97
|
-
return tc;
|
|
98
|
-
}
|
|
99
|
-
);
|
|
100
|
-
}
|
|
101
90
|
return normalized;
|
|
102
91
|
});
|
|
103
92
|
}
|
|
104
|
-
function
|
|
105
|
-
const alphanumeric = id.replace(/[^a-zA-Z0-9]/g, "");
|
|
106
|
-
return alphanumeric.slice(0, 9).padEnd(9, "0");
|
|
107
|
-
}
|
|
108
|
-
function createWorkersAiBindingFetch(binding) {
|
|
93
|
+
function createWorkersAiBindingFetch(binding, options) {
|
|
109
94
|
return async (_input, init) => {
|
|
110
95
|
if (!_optionalChain([init, 'optionalAccess', _3 => _3.body])) {
|
|
111
96
|
return new Response("No body", { status: 400 });
|
|
@@ -129,7 +114,11 @@ function createWorkersAiBindingFetch(binding) {
|
|
|
129
114
|
if (typeof body.max_tokens === "number") inputs.max_tokens = body.max_tokens;
|
|
130
115
|
if (body.response_format) inputs.response_format = body.response_format;
|
|
131
116
|
if (stream) inputs.stream = true;
|
|
132
|
-
const result = await binding.run(
|
|
117
|
+
const result = await binding.run(
|
|
118
|
+
model,
|
|
119
|
+
inputs,
|
|
120
|
+
_optionalChain([options, 'optionalAccess', _4 => _4.extraHeaders]) ? { extraHeaders: options.extraHeaders } : void 0
|
|
121
|
+
);
|
|
133
122
|
if (stream && result instanceof ReadableStream) {
|
|
134
123
|
const transformed = transformWorkersAiStream(
|
|
135
124
|
result,
|
|
@@ -153,11 +142,11 @@ function createWorkersAiBindingFetch(binding) {
|
|
|
153
142
|
finishReason = "tool_calls";
|
|
154
143
|
message.tool_calls = responseObj.tool_calls.map(
|
|
155
144
|
(tc) => ({
|
|
156
|
-
id:
|
|
145
|
+
id: tc.id || crypto.randomUUID(),
|
|
157
146
|
type: "function",
|
|
158
147
|
function: {
|
|
159
|
-
name: _optionalChain([tc, 'access',
|
|
160
|
-
arguments: typeof (_nullishCoalesce(_optionalChain([tc, 'access',
|
|
148
|
+
name: _optionalChain([tc, 'access', _5 => _5.function, 'optionalAccess', _6 => _6.name]) || tc.name || "",
|
|
149
|
+
arguments: typeof (_nullishCoalesce(_optionalChain([tc, 'access', _7 => _7.function, 'optionalAccess', _8 => _8.arguments]), () => ( tc.arguments))) === "string" ? _nullishCoalesce(_optionalChain([tc, 'access', _9 => _9.function, 'optionalAccess', _10 => _10.arguments]), () => ( tc.arguments)) : JSON.stringify(_nullishCoalesce(_nullishCoalesce(_optionalChain([tc, 'access', _11 => _11.function, 'optionalAccess', _12 => _12.arguments]), () => ( tc.arguments)), () => ( {})))
|
|
161
150
|
}
|
|
162
151
|
})
|
|
163
152
|
);
|
|
@@ -182,7 +171,7 @@ function transformWorkersAiStream(source, model) {
|
|
|
182
171
|
let buffer = "";
|
|
183
172
|
let hasToolCalls = false;
|
|
184
173
|
let isOpenAiFormat = false;
|
|
185
|
-
const
|
|
174
|
+
const toolCallState = /* @__PURE__ */ new Map();
|
|
186
175
|
return source.pipeThrough(
|
|
187
176
|
new TransformStream({
|
|
188
177
|
transform(chunk, controller) {
|
|
@@ -198,16 +187,24 @@ function transformWorkersAiStream(source, model) {
|
|
|
198
187
|
const parsed = JSON.parse(data);
|
|
199
188
|
if (parsed.choices !== void 0) {
|
|
200
189
|
isOpenAiFormat = true;
|
|
201
|
-
const choice = _optionalChain([parsed, 'access',
|
|
202
|
-
if (_optionalChain([choice, 'optionalAccess',
|
|
190
|
+
const choice = _optionalChain([parsed, 'access', _13 => _13.choices, 'optionalAccess', _14 => _14[0]]);
|
|
191
|
+
if (_optionalChain([choice, 'optionalAccess', _15 => _15.delta, 'optionalAccess', _16 => _16.tool_calls])) {
|
|
203
192
|
hasToolCalls = true;
|
|
204
193
|
for (const tc of choice.delta.tool_calls) {
|
|
205
|
-
|
|
206
|
-
|
|
194
|
+
const tcIndex = _nullishCoalesce(tc.index, () => ( 0));
|
|
195
|
+
if (!toolCallState.has(tcIndex)) {
|
|
196
|
+
const id = tc.id || `call${streamId}${tcIndex}`;
|
|
197
|
+
toolCallState.set(tcIndex, {
|
|
198
|
+
id,
|
|
199
|
+
name: _optionalChain([tc, 'access', _17 => _17.function, 'optionalAccess', _18 => _18.name]) || ""
|
|
200
|
+
});
|
|
201
|
+
tc.id = id;
|
|
202
|
+
} else {
|
|
203
|
+
delete tc.id;
|
|
207
204
|
}
|
|
208
205
|
}
|
|
209
206
|
}
|
|
210
|
-
if (_optionalChain([choice, 'optionalAccess',
|
|
207
|
+
if (_optionalChain([choice, 'optionalAccess', _19 => _19.finish_reason]) === "tool_calls") {
|
|
211
208
|
hasToolCalls = true;
|
|
212
209
|
}
|
|
213
210
|
controller.enqueue(
|
|
@@ -240,18 +237,18 @@ function transformWorkersAiStream(source, model) {
|
|
|
240
237
|
if (Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {
|
|
241
238
|
for (const tc of parsed.tool_calls) {
|
|
242
239
|
const tcIndex = _nullishCoalesce(tc.index, () => ( 0));
|
|
243
|
-
const tcName = _nullishCoalesce(_nullishCoalesce(_optionalChain([tc, 'access',
|
|
244
|
-
const tcArgs = _nullishCoalesce(_nullishCoalesce(_optionalChain([tc, 'access',
|
|
240
|
+
const tcName = _nullishCoalesce(_nullishCoalesce(_optionalChain([tc, 'access', _20 => _20.function, 'optionalAccess', _21 => _21.name]), () => ( tc.name)), () => ( null));
|
|
241
|
+
const tcArgs = _nullishCoalesce(_nullishCoalesce(_optionalChain([tc, 'access', _22 => _22.function, 'optionalAccess', _23 => _23.arguments]), () => ( tc.arguments)), () => ( null));
|
|
245
242
|
const tcId = _nullishCoalesce(tc.id, () => ( null));
|
|
246
243
|
if (!tcId && !tcName && (!tcArgs || tcArgs === "")) continue;
|
|
247
244
|
hasToolCalls = true;
|
|
248
245
|
const toolCallDelta = {
|
|
249
246
|
index: tcIndex
|
|
250
247
|
};
|
|
251
|
-
if (!
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
toolCallDelta.id =
|
|
248
|
+
if (!toolCallState.has(tcIndex)) {
|
|
249
|
+
const id = tcId || `call${streamId}${tcIndex}`;
|
|
250
|
+
toolCallState.set(tcIndex, { id, name: tcName || "" });
|
|
251
|
+
toolCallDelta.id = id;
|
|
255
252
|
toolCallDelta.type = "function";
|
|
256
253
|
toolCallDelta.function = {
|
|
257
254
|
name: tcName || "",
|
|
@@ -324,4 +321,4 @@ function transformWorkersAiStream(source, model) {
|
|
|
324
321
|
|
|
325
322
|
|
|
326
323
|
exports.isDirectBindingConfig = isDirectBindingConfig; exports.isDirectCredentialsConfig = isDirectCredentialsConfig; exports.validateWorkersAiConfig = validateWorkersAiConfig; exports.createGatewayFetch = createGatewayFetch; exports.createWorkersAiBindingFetch = createWorkersAiBindingFetch;
|
|
327
|
-
//# sourceMappingURL=chunk-
|
|
324
|
+
//# sourceMappingURL=chunk-U5NL4EM4.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-U5NL4EM4.cjs","../src/utils/create-fetcher.ts"],"names":[],"mappings":"AAAA;AC4HO,SAAS,qBAAA,CACf,MAAA,EACyC;AAGzC,EAAA,OACC,UAAA,GAAa,OAAA,GACb,OAAQ,MAAA,CAAO,OAAA,CAA+C,QAAA,IAAY,UAAA;AAE5E;AAGO,SAAS,yBAAA,CACf,MAAA,EAC6C;AAC7C,EAAA,OAAO,YAAA,GAAe,OAAA,GAAU,SAAA,GAAY,OAAA,GAAU,CAAA,CAAE,YAAA,GAAe,MAAA,CAAA;AACxE;AAGO,SAAS,eAAA,CAAgB,MAAA,EAAkE;AACjG,EAAA,GAAA,CAAI,YAAA,GAAe,MAAA,EAAQ,OAAO,IAAA;AAElC,EAAA,OAAO,UAAA,GAAa,OAAA,GAAU,CAAC,qBAAA,CAAsB,MAAM,CAAA;AAC5D;AAWO,SAAS,uBAAA,CAAwB,MAAA,E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AA;AACS,YAAA;AACR,cAAA;AACQ,gBAAA;AACC,gBAAA;AACsB,gBAAA;AAC/B,cAAA;AACD,YAAA;AACD,UAAA;AACkC,UAAA;AAAmC;AAAO;AAC7E,QAAA;AAGkC,QAAA;AACnC,MAAA;AACA,IAAA;AACF,EAAA;AACD;ADxT8C;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-U5NL4EM4.cjs","sourcesContent":[null,"// ---------------------------------------------------------------------------\n// AI Gateway types (for third-party providers + Workers AI through gateway)\n// ---------------------------------------------------------------------------\n\nexport interface CloudflareAiGateway {\n\trun(request: unknown): Promise<Response>;\n}\n\nexport interface AiGatewayBindingConfig {\n\t/**\n\t * The AI Gateway binding\n\t * @example\n\t * env.AI.gateway('my-gateway-id')\n\t */\n\tbinding: CloudflareAiGateway;\n\t/**\n\t * The Provider API Key if you want to manually pass it, ignore if using Unified Billing or BYOK.\n\t */\n\tapiKey?: string;\n}\n\nexport type AiGatewayCredentialsConfig = {\n\t/**\n\t * The Cloudflare account ID\n\t */\n\taccountId: string;\n\t/**\n\t * The AI Gateway ID\n\t */\n\tgatewayId: string;\n} & (\n\t| {\n\t\t\t/** Cloudflare API Key for AI Gateway */\n\t\t\tcfApiKey: string;\n\t\t\tapiKey?: string;\n\t }\n\t| {\n\t\t\t/** Provider API Key */\n\t\t\tapiKey: string;\n\t\t\t/** Cloudflare API Key for AI Gateway */\n\t\t\tcfApiKey?: string;\n\t }\n);\n\nexport interface AiGatewayConfig {\n\tskipCache?: boolean;\n\tcacheTtl?: number;\n\tcustomCacheKey?: string;\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type AiGatewayAdapterConfig = (AiGatewayBindingConfig | AiGatewayCredentialsConfig) &\n\tAiGatewayConfig;\n\n// ---------------------------------------------------------------------------\n// Plain Workers AI types (direct binding or REST, no gateway)\n// ---------------------------------------------------------------------------\n\n/**\n * The Workers AI binding interface (env.AI).\n * Accepts a model name and inputs, returns results directly.\n * Includes `gateway()` which is present on `env.AI` but not on `env.AI.gateway(id)`,\n * enabling structural discrimination from `CloudflareAiGateway`.\n */\nexport interface WorkersAiBinding {\n\trun(\n\t\tmodel: string,\n\t\tinputs: Record<string, unknown>,\n\t\toptions?: Record<string, unknown>,\n\t): Promise<unknown>;\n\tgateway(gatewayId: string): CloudflareAiGateway;\n}\n\nexport interface WorkersAiDirectBindingConfig {\n\t/**\n\t * The Workers AI binding (env.AI).\n\t * @example\n\t * { binding: env.AI }\n\t */\n\tbinding: WorkersAiBinding;\n}\n\nexport interface WorkersAiDirectCredentialsConfig {\n\t/**\n\t * The Cloudflare account ID\n\t */\n\taccountId: string;\n\t/**\n\t * The Cloudflare API key for Workers AI\n\t */\n\tapiKey: string;\n}\n\n/**\n * Config for Workers AI adapters. Supports four modes:\n * - Plain binding: `{ binding: env.AI }`\n * - Plain REST: `{ accountId, apiKey }`\n * - AI Gateway binding: `{ binding: env.AI.gateway(id) }`\n * - AI Gateway REST: `{ accountId, gatewayId, ... }`\n *\n * The third union member intersects `AiGatewayAdapterConfig` with `{ apiKey?: string }`.\n * For the gateway binding variant, `AiGatewayBindingConfig` already includes `apiKey?`,\n * so the intersection is redundant there. For the gateway credentials variant, this\n * `apiKey` represents the Workers AI token (used in the `Authorization` header to the\n * upstream provider), distinct from `cfApiKey` (used in the `cf-aig-authorization`\n * header for authenticated gateways).\n */\nexport type WorkersAiAdapterConfig = (\n\t| WorkersAiDirectBindingConfig\n\t| WorkersAiDirectCredentialsConfig\n\t| (AiGatewayAdapterConfig & { apiKey?: string })\n) & {\n\t/**\n\t * Session affinity key for prefix-cache optimization.\n\t * Routes requests with the same key to the same backend replica.\n\t */\n\tsessionAffinity?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Config detection helpers\n// ---------------------------------------------------------------------------\n\n/** Returns true if this is a plain Workers AI binding config (`{ binding: env.AI }`) */\nexport function isDirectBindingConfig(\n\tconfig: WorkersAiAdapterConfig,\n): config is WorkersAiDirectBindingConfig {\n\t// env.AI has a .gateway() method; env.AI.gateway(id) does not.\n\t// This distinguishes direct bindings from AI Gateway bindings.\n\treturn (\n\t\t\"binding\" in config &&\n\t\ttypeof (config.binding as unknown as Record<string, unknown>).gateway === \"function\"\n\t);\n}\n\n/** Returns true if this is a plain Workers AI REST config (accountId + apiKey, no gatewayId) */\nexport function isDirectCredentialsConfig(\n\tconfig: WorkersAiAdapterConfig,\n): config is WorkersAiDirectCredentialsConfig {\n\treturn \"accountId\" in config && \"apiKey\" in config && !(\"gatewayId\" in config);\n}\n\n/** Returns true if this is an AI Gateway config (has gateway binding or `gatewayId`) */\nexport function isGatewayConfig(config: WorkersAiAdapterConfig): config is AiGatewayAdapterConfig {\n\tif (\"gatewayId\" in config) return true;\n\t// Has `binding` but NOT a direct Workers AI binding (no .gateway method)\n\treturn \"binding\" in config && !isDirectBindingConfig(config);\n}\n\n// ---------------------------------------------------------------------------\n// Config validation\n// ---------------------------------------------------------------------------\n\n/**\n * Validates that a WorkersAiAdapterConfig contains a valid configuration.\n * Throws an error if neither a binding, credentials (accountId + apiKey),\n * nor a gateway configuration is provided.\n */\nexport function validateWorkersAiConfig(config: WorkersAiAdapterConfig): void {\n\tif (\n\t\t!isDirectBindingConfig(config) &&\n\t\t!isDirectCredentialsConfig(config) &&\n\t\t!isGatewayConfig(config)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Invalid Workers AI configuration: you must provide either a binding (e.g. { binding: env.AI }), \" +\n\t\t\t\t\"credentials ({ accountId, apiKey }), or a gateway configuration ({ binding: env.AI.gateway(id) } \" +\n\t\t\t\t\"or { accountId, gatewayId }).\",\n\t\t);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// createGatewayFetch -- for routing through AI Gateway\n// ---------------------------------------------------------------------------\n\nexport function createGatewayFetch(\n\tprovider: string,\n\tconfig: AiGatewayAdapterConfig,\n\theaders: Record<string, string> = {},\n): typeof fetch {\n\treturn (input, init) => {\n\t\tlet query: Record<string, unknown> = {};\n\n\t\tconst url =\n\t\t\ttypeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n\t\tconst urlObj = new URL(url);\n\n\t\t// Extract endpoint path (remove /v1/ prefix if present)\n\t\tconst endpoint = urlObj.pathname.replace(/^\\/v1\\//, \"\").replace(/^\\//, \"\") + urlObj.search;\n\n\t\tif (init?.body) {\n\t\t\ttry {\n\t\t\t\tquery = JSON.parse(init.body as string);\n\t\t\t} catch {\n\t\t\t\tquery = { _raw: init.body };\n\t\t\t}\n\t\t}\n\n\t\tconst cacheHeaders: Record<string, string> = {};\n\n\t\tif (\"skipCache\" in config && config.skipCache) {\n\t\t\tcacheHeaders[\"cf-aig-skip-cache\"] = \"true\";\n\t\t}\n\n\t\tif (typeof config.cacheTtl === \"number\") {\n\t\t\tcacheHeaders[\"cf-aig-cache-ttl\"] = String(config.cacheTtl);\n\t\t}\n\n\t\tif (typeof config.customCacheKey === \"string\") {\n\t\t\tcacheHeaders[\"cf-aig-cache-key\"] = config.customCacheKey;\n\t\t}\n\n\t\tif (typeof config.metadata === \"object\") {\n\t\t\tcacheHeaders[\"cf-aig-metadata\"] = JSON.stringify(config.metadata);\n\t\t}\n\n\t\tconst request: {\n\t\t\tprovider: string;\n\t\t\tendpoint: string;\n\t\t\theaders: Record<string, string>;\n\t\t\tquery: Record<string, unknown>;\n\t\t} = {\n\t\t\tprovider,\n\t\t\tendpoint,\n\t\t\theaders: {\n\t\t\t\t...(init?.headers as Record<string, string> | undefined),\n\t\t\t\t...headers,\n\t\t\t\t...cacheHeaders,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tquery,\n\t\t};\n\n\t\tif (provider === \"workers-ai\") {\n\t\t\tif (!request.endpoint.startsWith(\"run/\")) {\n\t\t\t\trequest.endpoint = `run/${query.model}`;\n\t\t\t}\n\t\t\tdelete query.model;\n\t\t\tdelete query.instructions;\n\t\t}\n\n\t\tif (config.apiKey) {\n\t\t\trequest.headers[\"authorization\"] = `Bearer ${config.apiKey}`;\n\t\t}\n\n\t\tif (\"binding\" in config) {\n\t\t\treturn config.binding.run(request);\n\t\t}\n\n\t\treturn fetch(\n\t\t\t`https://gateway.ai.cloudflare.com/v1/${config.accountId}/${config.gatewayId}`,\n\t\t\t{\n\t\t\t\t...init,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...headers,\n\t\t\t\t\t...cacheHeaders,\n\t\t\t\t\t...(config.cfApiKey\n\t\t\t\t\t\t? { \"cf-aig-authorization\": `Bearer ${config.cfApiKey}` }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(request),\n\t\t\t},\n\t\t);\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// createWorkersAiBindingFetch -- shim that makes env.AI look like an OpenAI endpoint\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize messages before passing to Workers AI binding.\n *\n * The binding has strict schema validation that may differ from the OpenAI API:\n * - `content` must not be null\n *\n * Content arrays (with image_url parts) are passed through as-is since the\n * Workers AI binding accepts them at runtime for vision-capable models.\n */\nfunction normalizeMessagesForBinding(\n\tmessages: Record<string, unknown>[],\n): Record<string, unknown>[] {\n\treturn messages.map((msg) => {\n\t\tconst normalized = { ...msg };\n\n\t\t// content: null → content: \"\"\n\t\tif (normalized.content === null || normalized.content === undefined) {\n\t\t\tnormalized.content = \"\";\n\t\t}\n\n\t\treturn normalized;\n\t});\n}\n\n/**\n * Creates a fetch function that intercepts OpenAI SDK requests and translates them\n * to Workers AI binding calls (env.AI.run). This allows the WorkersAiTextAdapter\n * to use the OpenAI SDK against a plain Workers AI binding.\n *\n * NOTE: The `input` URL parameter is intentionally ignored. The model name and all\n * request parameters are extracted from the JSON body, matching Workers AI's\n * `binding.run(model, inputs)` calling convention.\n */\nexport function createWorkersAiBindingFetch(\n\tbinding: WorkersAiBinding,\n\toptions?: { extraHeaders?: Record<string, string> },\n): typeof fetch {\n\treturn async (_input, init) => {\n\t\tif (!init?.body) {\n\t\t\treturn new Response(\"No body\", { status: 400 });\n\t\t}\n\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = JSON.parse(init.body as string);\n\t\t} catch {\n\t\t\treturn new Response(\"Invalid JSON body\", { status: 400 });\n\t\t}\n\n\t\tconst model = body.model as string;\n\t\tconst stream = body.stream as boolean | undefined;\n\n\t\t// Build Workers AI inputs from OpenAI format\n\t\tconst inputs: Record<string, unknown> = {};\n\t\tif (body.messages) {\n\t\t\tinputs.messages = normalizeMessagesForBinding(\n\t\t\t\tbody.messages as Record<string, unknown>[],\n\t\t\t);\n\t\t}\n\t\tif (body.tools) inputs.tools = body.tools;\n\t\tif (typeof body.temperature === \"number\") inputs.temperature = body.temperature;\n\t\tif (typeof body.max_tokens === \"number\") inputs.max_tokens = body.max_tokens;\n\t\tif (body.response_format) inputs.response_format = body.response_format;\n\t\tif (stream) inputs.stream = true;\n\n\t\tconst result = await binding.run(\n\t\t\tmodel,\n\t\t\tinputs,\n\t\t\toptions?.extraHeaders ? { extraHeaders: options.extraHeaders } : undefined,\n\t\t);\n\n\t\tif (stream && result instanceof ReadableStream) {\n\t\t\t// Workers AI returns an SSE stream with `data: {\"response\":\"chunk\"}` format.\n\t\t\t// Transform it to OpenAI-compatible SSE format.\n\t\t\tconst transformed = transformWorkersAiStream(\n\t\t\t\tresult as ReadableStream<Uint8Array>,\n\t\t\t\tmodel,\n\t\t\t);\n\t\t\treturn new Response(transformed, {\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/event-stream\",\n\t\t\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Graceful degradation: some models return a complete (non-streaming)\n\t\t// response even when `stream: true` is requested. Fall through to the\n\t\t// non-streaming wrapper which produces a valid OpenAI Chat Completion\n\t\t// response that the SDK can consume.\n\n\t\t// Non-streaming: Workers AI returns { response: \"text\", tool_calls?: [...] }\n\t\t// Wrap into OpenAI Chat Completion format.\n\t\tconst responseObj =\n\t\t\ttypeof result === \"object\" && result !== null\n\t\t\t\t? (result as Record<string, unknown>)\n\t\t\t\t: { response: String(result) };\n\n\t\tconst responseText = typeof responseObj.response === \"string\" ? responseObj.response : \"\";\n\n\t\tconst message: Record<string, unknown> = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: responseText,\n\t\t};\n\t\tlet finishReason = \"stop\";\n\n\t\t// Handle tool calls if present in Workers AI response\n\t\tif (Array.isArray(responseObj.tool_calls) && responseObj.tool_calls.length > 0) {\n\t\t\tfinishReason = \"tool_calls\";\n\t\t\tmessage.tool_calls = responseObj.tool_calls.map(\n\t\t\t\t(tc: {\n\t\t\t\t\tid?: string;\n\t\t\t\t\tname?: string;\n\t\t\t\t\targuments: unknown;\n\t\t\t\t\tfunction?: { name: string; arguments?: unknown };\n\t\t\t\t}) => ({\n\t\t\t\t\tid: tc.id || crypto.randomUUID(),\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: tc.function?.name || tc.name || \"\",\n\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\ttypeof (tc.function?.arguments ?? tc.arguments) === \"string\"\n\t\t\t\t\t\t\t\t? ((tc.function?.arguments ?? tc.arguments) as string)\n\t\t\t\t\t\t\t\t: JSON.stringify(tc.function?.arguments ?? tc.arguments ?? {}),\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tconst openAiResponse = {\n\t\t\tid: `workers-ai-${crypto.randomUUID()}`,\n\t\t\tobject: \"chat.completion\",\n\t\t\tcreated: Math.floor(Date.now() / 1000),\n\t\t\tmodel,\n\t\t\tchoices: [{ index: 0, message, finish_reason: finishReason }],\n\t\t};\n\n\t\treturn new Response(JSON.stringify(openAiResponse), {\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t});\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Stream transformer: Workers AI SSE -> OpenAI-compatible SSE\n// Uses TransformStream for proper backpressure.\n// ---------------------------------------------------------------------------\n\n/**\n * Transforms a Workers AI SSE stream (data: {\"response\":\"chunk\"}) into\n * an OpenAI-compatible SSE stream (data: {\"choices\":[{\"delta\":{\"content\":\"chunk\"}}]}).\n *\n * Workers AI binding streams tool calls in an OpenAI-like nested format:\n * { tool_calls: [{ id, type, index, function: { name, arguments } }] }\n * Arguments are streamed incrementally across multiple SSE chunks, so the\n * transformer must forward them as incremental deltas rather than a single blob.\n */\nfunction transformWorkersAiStream(\n\tsource: ReadableStream<Uint8Array>,\n\tmodel: string,\n): ReadableStream<Uint8Array> {\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\t// Generate a stable ID and timestamp for the entire stream, matching OpenAI's\n\t// convention where all chunks in a single response share the same id/created.\n\tconst streamId = `workers-ai-${crypto.randomUUID()}`;\n\tconst created = Math.floor(Date.now() / 1000);\n\tlet buffer = \"\";\n\tlet hasToolCalls = false;\n\t// When true, the source stream is already in OpenAI format (some models\n\t// like Qwen3, Kimi K2.5 stream OpenAI-compatible SSE through the binding).\n\t// In that case, flush() should only emit [DONE] and skip the finish chunk.\n\tlet isOpenAiFormat = false;\n\t// Track tool call state per index: store the generated/assigned ID so that\n\t// subsequent argument deltas use the same ID (matching the working streaming.ts pattern).\n\tconst toolCallState = new Map<number, { id: string; name: string }>();\n\n\treturn source.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tbuffer += decoder.decode(chunk, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tconst trimmed = line.trim();\n\t\t\t\t\tif (!trimmed || !trimmed.startsWith(\"data: \")) continue;\n\t\t\t\t\tconst data = trimmed.slice(6);\n\n\t\t\t\t\t// Swallow source [DONE]; we emit our own in flush()\n\t\t\t\t\tif (data === \"[DONE]\") continue;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst parsed = JSON.parse(data);\n\n\t\t\t\t\t\t// Some models (Qwen3, Kimi K2.5) return OpenAI-compatible format\n\t\t\t\t\t\t// directly through the binding, with `choices[].delta.content` and\n\t\t\t\t\t\t// optional `reasoning_content`. Detect this and pass through as-is.\n\t\t\t\t\t\tif (parsed.choices !== undefined) {\n\t\t\t\t\t\t\t// Already OpenAI format — pass through but ensure each tool call\n\t\t\t\t\t\t\t// index gets a unique, stable ID across all chunks.\n\t\t\t\t\t\t\tisOpenAiFormat = true;\n\t\t\t\t\t\t\tconst choice = parsed.choices?.[0];\n\t\t\t\t\t\t\tif (choice?.delta?.tool_calls) {\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\t\t\t\t\t\t\t\tfor (const tc of choice.delta.tool_calls) {\n\t\t\t\t\t\t\t\t\tconst tcIndex = tc.index ?? 0;\n\t\t\t\t\t\t\t\t\tif (!toolCallState.has(tcIndex)) {\n\t\t\t\t\t\t\t\t\t\t// First chunk for this index — generate/store unique ID\n\t\t\t\t\t\t\t\t\t\tconst id = tc.id || `call${streamId}${tcIndex}`;\n\t\t\t\t\t\t\t\t\t\ttoolCallState.set(tcIndex, {\n\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\tname: tc.function?.name || \"\",\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\ttc.id = id;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t// Subsequent chunk — reuse stored ID, remove id from delta\n\t\t\t\t\t\t\t\t\t\t// (OpenAI format only sends id in first chunk)\n\t\t\t\t\t\t\t\t\t\tdelete tc.id;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (choice?.finish_reason === \"tool_calls\") {\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(parsed)}\\n\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// --- Workers AI native format handling below ---\n\n\t\t\t\t\t\t// Text content\n\t\t\t\t\t\tif (parsed.response != null && parsed.response !== \"\") {\n\t\t\t\t\t\t\tconst openAiChunk = {\n\t\t\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\t\t\tcreated,\n\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\t\t\tdelta: { content: parsed.response },\n\t\t\t\t\t\t\t\t\t\tfinish_reason: null,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(openAiChunk)}\\n\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Tool calls — Workers AI binding streams these incrementally:\n\t\t\t\t\t\t// Chunk A: { id, type, index, function: { name } } — start\n\t\t\t\t\t\t// Chunk B: { index, function: { arguments: \"partial...\" } } — args delta\n\t\t\t\t\t\t// Chunk C: { index, function: { arguments: \"rest...\" } } — args delta\n\t\t\t\t\t\t// Chunk D: { id: null, type: null, index, function: { name: null, arguments: \"\" } } — finalize (skip)\n\t\t\t\t\t\tif (Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n\t\t\t\t\t\t\tfor (const tc of parsed.tool_calls) {\n\t\t\t\t\t\t\t\tconst tcIndex = tc.index ?? 0;\n\n\t\t\t\t\t\t\t\t// Resolve name and arguments from either nested or flat format\n\t\t\t\t\t\t\t\tconst tcName = tc.function?.name ?? tc.name ?? null;\n\t\t\t\t\t\t\t\tconst tcArgs = tc.function?.arguments ?? tc.arguments ?? null;\n\t\t\t\t\t\t\t\tconst tcId = tc.id ?? null;\n\n\t\t\t\t\t\t\t\t// Skip finalization chunks where everything is null/empty\n\t\t\t\t\t\t\t\tif (!tcId && !tcName && (!tcArgs || tcArgs === \"\")) continue;\n\n\t\t\t\t\t\t\t\thasToolCalls = true;\n\n\t\t\t\t\t\t\t\t// Build the OpenAI-compatible tool_calls delta\n\t\t\t\t\t\t\t\tconst toolCallDelta: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t\tindex: tcIndex,\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tif (!toolCallState.has(tcIndex)) {\n\t\t\t\t\t\t\t\t\t// First chunk for this tool call index — emit id, type, name.\n\t\t\t\t\t\t\t\t\tconst id = tcId || `call${streamId}${tcIndex}`;\n\t\t\t\t\t\t\t\t\ttoolCallState.set(tcIndex, { id, name: tcName || \"\" });\n\t\t\t\t\t\t\t\t\ttoolCallDelta.id = id;\n\t\t\t\t\t\t\t\t\ttoolCallDelta.type = \"function\";\n\t\t\t\t\t\t\t\t\ttoolCallDelta.function = {\n\t\t\t\t\t\t\t\t\t\tname: tcName || \"\",\n\t\t\t\t\t\t\t\t\t\t// Include arguments if they arrive in the same chunk\n\t\t\t\t\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\t\t\t\t\ttcArgs != null\n\t\t\t\t\t\t\t\t\t\t\t\t? typeof tcArgs === \"string\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t? tcArgs\n\t\t\t\t\t\t\t\t\t\t\t\t\t: JSON.stringify(tcArgs)\n\t\t\t\t\t\t\t\t\t\t\t\t: \"\",\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Subsequent chunks — only include arguments delta\n\t\t\t\t\t\t\t\t\tif (tcArgs != null && tcArgs !== \"\") {\n\t\t\t\t\t\t\t\t\t\ttoolCallDelta.function = {\n\t\t\t\t\t\t\t\t\t\t\targuments:\n\t\t\t\t\t\t\t\t\t\t\t\ttypeof tcArgs === \"string\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t? tcArgs\n\t\t\t\t\t\t\t\t\t\t\t\t\t: JSON.stringify(tcArgs),\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcontinue; // Nothing useful to forward\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst toolChunk = {\n\t\t\t\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\t\t\t\tcreated,\n\t\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\t\t\t\tdelta: { tool_calls: [toolCallDelta] },\n\t\t\t\t\t\t\t\t\t\t\tfinish_reason: null,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\t\tencoder.encode(`data: ${JSON.stringify(toolChunk)}\\n\\n`),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t// Log malformed SSE events for debugging; don't break the stream.\n\t\t\t\t\t\tconsole.warn(\"[tanstack-ai] failed to parse SSE event:\", data, e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tif (!isOpenAiFormat) {\n\t\t\t\t\t// Workers AI native format: emit a finish chunk with stop/tool_calls\n\t\t\t\t\tconst finalChunk = {\n\t\t\t\t\t\tid: streamId,\n\t\t\t\t\t\tobject: \"chat.completion.chunk\",\n\t\t\t\t\t\tcreated,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tchoices: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tindex: 0,\n\t\t\t\t\t\t\t\tdelta: {},\n\t\t\t\t\t\t\t\tfinish_reason: hasToolCalls ? \"tool_calls\" : \"stop\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t\tcontroller.enqueue(encoder.encode(`data: ${JSON.stringify(finalChunk)}\\n\\n`));\n\t\t\t\t}\n\t\t\t\t// OpenAI format already includes its own finish_reason in the stream.\n\t\t\t\t// Either way, emit a [DONE] sentinel.\n\t\t\t\tcontroller.enqueue(encoder.encode(\"data: [DONE]\\n\\n\"));\n\t\t\t},\n\t\t}),\n\t);\n}\n"]}
|
|
@@ -10,7 +10,7 @@ var _chunk7HSUHP63cjs = require('./chunk-7HSUHP63.cjs');
|
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
var
|
|
13
|
+
var _chunkU5NL4EM4cjs = require('./chunk-U5NL4EM4.cjs');
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
var _chunk4DE2IREAcjs = require('./chunk-4DE2IREA.cjs');
|
|
@@ -22,7 +22,7 @@ var WorkersAiTranscriptionAdapter = class extends _adapters.BaseTranscriptionAda
|
|
|
22
22
|
super({}, model);
|
|
23
23
|
_chunk4DE2IREAcjs.__publicField.call(void 0, this, "name", "workers-ai-transcription");
|
|
24
24
|
_chunk4DE2IREAcjs.__publicField.call(void 0, this, "adapterConfig");
|
|
25
|
-
|
|
25
|
+
_chunkU5NL4EM4cjs.validateWorkersAiConfig.call(void 0, config);
|
|
26
26
|
this.adapterConfig = config;
|
|
27
27
|
}
|
|
28
28
|
async transcribe(options) {
|
|
@@ -32,10 +32,10 @@ var WorkersAiTranscriptionAdapter = class extends _adapters.BaseTranscriptionAda
|
|
|
32
32
|
if (language) extra.language = language;
|
|
33
33
|
if (prompt) extra.initial_prompt = prompt;
|
|
34
34
|
const audioPayload = this.buildAudioPayload(audioBytes, audio);
|
|
35
|
-
if (
|
|
35
|
+
if (_chunkU5NL4EM4cjs.isDirectBindingConfig.call(void 0, this.adapterConfig)) {
|
|
36
36
|
return this.transcribeViaBinding(audioPayload, extra);
|
|
37
37
|
}
|
|
38
|
-
if (
|
|
38
|
+
if (_chunkU5NL4EM4cjs.isDirectCredentialsConfig.call(void 0, this.adapterConfig)) {
|
|
39
39
|
if (this.model === "@cf/deepgram/nova-3") {
|
|
40
40
|
return this.transcribeViaRestBinary(audioBytes, audio, extra);
|
|
41
41
|
}
|
|
@@ -106,7 +106,7 @@ var WorkersAiTranscriptionAdapter = class extends _adapters.BaseTranscriptionAda
|
|
|
106
106
|
}
|
|
107
107
|
async transcribeViaGateway(audioPayload, options) {
|
|
108
108
|
const gatewayConfig = this.adapterConfig;
|
|
109
|
-
const gatewayFetch =
|
|
109
|
+
const gatewayFetch = _chunkU5NL4EM4cjs.createGatewayFetch.call(void 0, "workers-ai", gatewayConfig);
|
|
110
110
|
const response = await gatewayFetch("https://api.cloudflare.com/v1/audio/transcriptions", {
|
|
111
111
|
method: "POST",
|
|
112
112
|
body: JSON.stringify({
|
|
@@ -215,4 +215,4 @@ function detectAudioContentType(audio) {
|
|
|
215
215
|
|
|
216
216
|
|
|
217
217
|
exports.WorkersAiTranscriptionAdapter = WorkersAiTranscriptionAdapter; exports.createWorkersAiTranscription = createWorkersAiTranscription;
|
|
218
|
-
//# sourceMappingURL=chunk-
|
|
218
|
+
//# sourceMappingURL=chunk-XFQ3QESX.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-AYTKQRE4.cjs","../src/adapters/workers-ai-transcription.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wD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ACD;AAaA;AACC,EAAA;AACC,IAAA;AAAuC,EAAA;AAGxC,EAAA;AAEC,IAAA;AACA,IAAA;AAAwC,EAAA;AAGzC,EAAA;AAEC,IAAA;AACA,IAAA;AACA,IAAA;AACC,MAAA;AAA8B,IAAA;AAE/B,IAAA;AAAuB,EAAA;AAGxB,EAAA;AACD;AASA;AAEC,EAAA;AACC,IAAA;AAAa,EAAA;AAKd,EAAA;AACD;AD1JA;AACA;AACA;AACA;AACA","file":"/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-AYTKQRE4.cjs","sourcesContent":[null,"import { BaseTranscriptionAdapter } from \"@tanstack/ai/adapters\";\nimport type { TranscriptionOptions, TranscriptionResult } from \"@tanstack/ai\";\nimport {\n\ttype WorkersAiAdapterConfig,\n\ttype WorkersAiDirectBindingConfig,\n\ttype WorkersAiDirectCredentialsConfig,\n\ttype AiGatewayAdapterConfig,\n\tcreateGatewayFetch,\n\tisDirectBindingConfig,\n\tisDirectCredentialsConfig,\n\tvalidateWorkersAiConfig,\n} from \"../utils/create-fetcher\";\nimport { workersAiRestFetch, workersAiRestFetchBinary } from \"../utils/workers-ai-rest\";\nimport { uint8ArrayToBase64 } from \"../utils/binary\";\n\n// ---------------------------------------------------------------------------\n// Model types\n// ---------------------------------------------------------------------------\n\n/**\n * Workers AI models that support speech-to-text transcription.\n *\n * Note: the typed `AiModels` interface in `@cloudflare/workers-types` may lag\n * behind what's deployed. We use a string union here that matches the known\n * models including Deepgram partner models.\n *\n * **Nova-3 note:** `@cf/deepgram/nova-3` uses a different input format than the\n * Whisper models. Via binding it accepts `{ audio: { body: base64, contentType } }`.\n * Via REST it requires multipart form data (not JSON). The adapter handles both.\n */\nexport type WorkersAiTranscriptionModel =\n\t| \"@cf/openai/whisper\"\n\t| \"@cf/openai/whisper-tiny-en\"\n\t| \"@cf/openai/whisper-large-v3-turbo\"\n\t| \"@cf/deepgram/nova-3\"\n\t| (string & {});\n\n// ---------------------------------------------------------------------------\n// WorkersAiTranscriptionAdapter\n// ---------------------------------------------------------------------------\n\nexport class WorkersAiTranscriptionAdapter extends BaseTranscriptionAdapter<WorkersAiTranscriptionModel> {\n\treadonly name = \"workers-ai-transcription\" as const;\n\tprivate adapterConfig: WorkersAiAdapterConfig;\n\n\tconstructor(config: WorkersAiAdapterConfig, model: WorkersAiTranscriptionModel) {\n\t\tsuper({}, model);\n\t\tvalidateWorkersAiConfig(config);\n\t\tthis.adapterConfig = config;\n\t}\n\n\tasync transcribe(options: TranscriptionOptions): Promise<TranscriptionResult> {\n\t\tconst { audio, language, prompt, modelOptions } = options;\n\n\t\t// Normalize audio to raw bytes\n\t\tconst audioBytes = await normalizeAudioToBytes(audio);\n\n\t\tconst extra: Record<string, unknown> = { ...modelOptions };\n\t\tif (language) extra.language = language;\n\t\tif (prompt) extra.initial_prompt = prompt;\n\n\t\t// Build the model-specific audio payload:\n\t\t// - Deepgram Nova-3 (binding): { audio: { body: base64, contentType: \"audio/...\" } }\n\t\t// - Deepgram Nova-3 (REST): multipart FormData (handled separately)\n\t\t// - Whisper Large v3 Turbo (REST/gateway): { audio: base64string }\n\t\t// - Other Whisper models (binding): { audio: number[] }\n\t\tconst audioPayload = this.buildAudioPayload(audioBytes, audio);\n\n\t\tif (isDirectBindingConfig(this.adapterConfig)) {\n\t\t\treturn this.transcribeViaBinding(audioPayload, extra);\n\t\t}\n\n\t\tif (isDirectCredentialsConfig(this.adapterConfig)) {\n\t\t\t// Nova-3 REST requires raw binary audio, not JSON\n\t\t\tif (this.model === \"@cf/deepgram/nova-3\") {\n\t\t\t\treturn this.transcribeViaRestBinary(audioBytes, audio, extra);\n\t\t\t}\n\t\t\treturn this.transcribeViaRest(audioPayload, extra);\n\t\t}\n\n\t\treturn this.transcribeViaGateway(audioPayload, extra);\n\t}\n\n\t/**\n\t * Build the audio field for the request payload, handling model-specific formats.\n\t *\n\t * - `@cf/deepgram/nova-3` requires `{ body: base64, contentType: \"audio/...\" }`\n\t * - `@cf/openai/whisper-large-v3-turbo` REST/gateway accepts a base64 string\n\t * - Other Whisper models accept `number[]` (binding) or base64 (REST)\n\t */\n\tprivate buildAudioPayload(\n\t\taudioBytes: number[],\n\t\toriginalAudio: string | File | Blob | ArrayBuffer,\n\t): Record<string, unknown> {\n\t\tif (this.model === \"@cf/deepgram/nova-3\") {\n\t\t\tconst b64 = uint8ArrayToBase64(new Uint8Array(audioBytes));\n\t\t\tconst contentType = detectAudioContentType(originalAudio);\n\t\t\treturn { audio: { body: b64, contentType } };\n\t\t}\n\n\t\tif (this.model === \"@cf/openai/whisper-large-v3-turbo\") {\n\t\t\treturn { audio: uint8ArrayToBase64(new Uint8Array(audioBytes)) };\n\t\t}\n\n\t\treturn { audio: audioBytes };\n\t}\n\n\tprivate async transcribeViaBinding(\n\t\taudioPayload: Record<string, unknown>,\n\t\toptions: Record<string, unknown>,\n\t): Promise<TranscriptionResult> {\n\t\tconst ai = (this.adapterConfig as WorkersAiDirectBindingConfig).binding;\n\t\tconst result = (await ai.run(this.model, {\n\t\t\t...audioPayload,\n\t\t\t...options,\n\t\t})) as Record<string, unknown>;\n\t\treturn this.normalizeResult(result);\n\t}\n\n\tprivate async transcribeViaRest(\n\t\taudioPayload: Record<string, unknown>,\n\t\toptions: Record<string, unknown>,\n\t): Promise<TranscriptionResult> {\n\t\tconst config = this.adapterConfig as WorkersAiDirectCredentialsConfig;\n\n\t\tconst response = await workersAiRestFetch(\n\t\t\tconfig,\n\t\t\tthis.model,\n\t\t\t{ ...audioPayload, ...options },\n\t\t\t{\n\t\t\t\tlabel: \"Workers AI transcription\",\n\t\t\t\tsignal: (options as { signal?: AbortSignal }).signal,\n\t\t\t},\n\t\t);\n\n\t\tconst data = (await response.json()) as {\n\t\t\tresult?: Record<string, unknown>;\n\t\t} & Record<string, unknown>;\n\n\t\t// Cloudflare REST API wraps responses in { success, result: {...} }.\n\t\t// Use `data.result` when present, fall back to `data` for direct responses.\n\t\treturn this.normalizeResult(data.result ?? data);\n\t}\n\n\t/**\n\t * Transcribe via REST using raw binary audio.\n\t * Required for models like Deepgram Nova-3 that expect raw audio bytes\n\t * with a Content-Type header (e.g. \"audio/wav\") instead of JSON.\n\t */\n\tprivate async transcribeViaRestBinary(\n\t\taudioBytes: number[],\n\t\toriginalAudio: string | File | Blob | ArrayBuffer,\n\t\toptions: Record<string, unknown>,\n\t): Promise<TranscriptionResult> {\n\t\tconst config = this.adapterConfig as WorkersAiDirectCredentialsConfig;\n\t\tconst contentType = detectAudioContentType(originalAudio);\n\n\t\tconst response = await workersAiRestFetchBinary(\n\t\t\tconfig,\n\t\t\tthis.model,\n\t\t\tnew Uint8Array(audioBytes),\n\t\t\tcontentType,\n\t\t\t{\n\t\t\t\tlabel: \"Workers AI transcription\",\n\t\t\t\tsignal: (options as { signal?: AbortSignal }).signal,\n\t\t\t},\n\t\t);\n\n\t\tconst data = (await response.json()) as {\n\t\t\tresult?: Record<string, unknown>;\n\t\t} & Record<string, unknown>;\n\n\t\treturn this.normalizeResult(data.result ?? data);\n\t}\n\n\tprivate async transcribeViaGateway(\n\t\taudioPayload: Record<string, unknown>,\n\t\toptions: Record<string, unknown>,\n\t): Promise<TranscriptionResult> {\n\t\tconst gatewayConfig = this.adapterConfig as AiGatewayAdapterConfig;\n\t\tconst gatewayFetch = createGatewayFetch(\"workers-ai\", gatewayConfig);\n\n\t\t// The URL here is a placeholder — createGatewayFetch for \"workers-ai\" extracts\n\t\t// the model from the body, sets it as the endpoint, and routes through the gateway.\n\t\t// The actual URL path is not used.\n\t\tconst response = await gatewayFetch(\"https://api.cloudflare.com/v1/audio/transcriptions\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tmodel: this.model,\n\t\t\t\t...audioPayload,\n\t\t\t\t...options,\n\t\t\t}),\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst errorText = await response.text();\n\t\t\tthrow new Error(\n\t\t\t\t`Workers AI transcription gateway request failed (${response.status}): ${errorText}`,\n\t\t\t);\n\t\t}\n\n\t\tconst data = (await response.json()) as Record<string, unknown>;\n\t\treturn this.normalizeResult(data);\n\t}\n\n\t/**\n\t * Normalize Workers AI transcription results into the standard\n\t * TanStack AI TranscriptionResult shape.\n\t *\n\t * Handles three response formats:\n\t * - Whisper: `{ text, words?, vtt? }`\n\t * - Whisper v3-turbo: `{ text, segments?, transcription_info? }`\n\t * - Deepgram Nova-3: `{ results: { channels: [{ alternatives: [{ transcript, words }] }] } }`\n\t */\n\tprivate normalizeResult(raw: Record<string, unknown>): TranscriptionResult {\n\t\t// Deepgram Nova-3 format: { results: { channels: [{ alternatives: [{ transcript, words }] }] } }\n\t\tconst results = raw.results as Record<string, unknown> | undefined;\n\t\tif (results?.channels) {\n\t\t\tconst channels = results.channels as Array<{\n\t\t\t\talternatives?: Array<{\n\t\t\t\t\ttranscript?: string;\n\t\t\t\t\tconfidence?: number;\n\t\t\t\t\twords?: Array<{ word: string; start: number; end: number; confidence: number }>;\n\t\t\t\t}>;\n\t\t\t}>;\n\t\t\tconst alt = channels?.[0]?.alternatives?.[0];\n\t\t\tconst text = alt?.transcript ?? \"\";\n\t\t\tconst result: TranscriptionResult = {\n\t\t\t\tid: this.generateId(),\n\t\t\t\tmodel: this.model,\n\t\t\t\ttext,\n\t\t\t};\n\t\t\tif (alt?.words && Array.isArray(alt.words)) {\n\t\t\t\tresult.words = alt.words.map((w) => ({\n\t\t\t\t\tword: w.word ?? \"\",\n\t\t\t\t\tstart: w.start ?? 0,\n\t\t\t\t\tend: w.end ?? 0,\n\t\t\t\t}));\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\t// Whisper format: { text, words?, vtt? }\n\t\t// Whisper v3-turbo format: { text, segments?, transcription_info? }\n\t\tconst result: TranscriptionResult = {\n\t\t\tid: this.generateId(),\n\t\t\tmodel: this.model,\n\t\t\ttext: (raw.text as string) ?? \"\",\n\t\t};\n\n\t\t// Language from transcription_info (whisper-large-v3-turbo)\n\t\tconst transcriptionInfo = raw.transcription_info as Record<string, unknown> | undefined;\n\t\tif (transcriptionInfo?.language) {\n\t\t\tresult.language = transcriptionInfo.language as string;\n\t\t}\n\n\t\t// Duration\n\t\tif (transcriptionInfo?.duration != null) {\n\t\t\tresult.duration = transcriptionInfo.duration as number;\n\t\t}\n\n\t\t// Segments (whisper-large-v3-turbo returns these)\n\t\tif (raw.segments && Array.isArray(raw.segments)) {\n\t\t\tresult.segments = raw.segments.map((seg: Record<string, unknown>, idx: number) => ({\n\t\t\t\tid: idx,\n\t\t\t\ttext: (seg.text as string) ?? \"\",\n\t\t\t\tstart: (seg.start as number) ?? 0,\n\t\t\t\tend: (seg.end as number) ?? 0,\n\t\t\t}));\n\t\t}\n\n\t\t// Words — basic whisper returns top-level words[], v3-turbo nests them in segments\n\t\tif (raw.words && Array.isArray(raw.words)) {\n\t\t\tresult.words = raw.words.map((w: Record<string, unknown>) => ({\n\t\t\t\tword: (w.word as string) ?? \"\",\n\t\t\t\tstart: (w.start as number) ?? 0,\n\t\t\t\tend: (w.end as number) ?? 0,\n\t\t\t}));\n\t\t}\n\n\t\treturn result;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a Workers AI transcription adapter for speech-to-text.\n *\n * Works with TanStack AI's `generateTranscription()` activity function:\n * ```ts\n * import { generateTranscription } from \"@tanstack/ai\";\n * import { createWorkersAiTranscription } from \"@cloudflare/tanstack-ai\";\n *\n * const adapter = createWorkersAiTranscription(\n * \"@cf/openai/whisper-large-v3-turbo\",\n * { binding: env.AI },\n * );\n *\n * const result = await generateTranscription({ adapter, audio: audioData });\n * // result.text — the transcribed text\n * ```\n *\n * Note: Factory takes `(model, config)` for ergonomics — the class constructor\n * uses `(config, model)` to match TanStack AI's upstream convention.\n */\nexport function createWorkersAiTranscription(\n\tmodel: WorkersAiTranscriptionModel,\n\tconfig: WorkersAiAdapterConfig,\n) {\n\treturn new WorkersAiTranscriptionAdapter(config, model);\n}\n\n// ---------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize various audio input formats into a number[] (raw bytes).\n *\n * Note: `File extends Blob`, so `File` instances are handled by the\n * `instanceof Blob` branch. `Blob.arrayBuffer()` always reads the full\n * contents regardless of any prior reads — there's no cursor to worry about.\n */\nasync function normalizeAudioToBytes(audio: string | File | Blob | ArrayBuffer): Promise<number[]> {\n\tif (audio instanceof ArrayBuffer) {\n\t\treturn Array.from(new Uint8Array(audio));\n\t}\n\n\tif (audio instanceof Blob) {\n\t\t// This also handles `File` (which extends Blob)\n\t\tconst buffer = await audio.arrayBuffer();\n\t\treturn Array.from(new Uint8Array(buffer));\n\t}\n\n\tif (typeof audio === \"string\") {\n\t\t// Assume base64 string — decode to bytes\n\t\tconst binary = atob(audio);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i);\n\t\t}\n\t\treturn Array.from(bytes);\n\t}\n\n\tthrow new Error(\"Unsupported audio format. Expected string, File, Blob, or ArrayBuffer.\");\n}\n\n/**\n * Detect the MIME type of the audio input for models that require it\n * (e.g., Deepgram Nova-3).\n *\n * - `File` / `Blob`: use the `.type` property (e.g., \"audio/wav\")\n * - `ArrayBuffer` / `string`: defaults to \"audio/wav\"\n */\nfunction detectAudioContentType(audio: string | File | Blob | ArrayBuffer): string {\n\t// File and Blob carry their own MIME type\n\tif (audio instanceof Blob && audio.type) {\n\t\treturn audio.type;\n\t}\n\n\t// For raw bytes, default to audio/wav — this is the most common\n\t// format for transcription inputs and what the E2E tests use.\n\treturn \"audio/wav\";\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-XFQ3QESX.cjs","../src/adapters/workers-ai-transcription.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AAC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C,EAAA;AAGzC,EAAA;AAEC,IAAA;AACA,IAAA;AACA,IAAA;AACC,MAAA;AAA8B,IAAA;AAE/B,IAAA;AAAuB,EAAA;AAGxB,EAAA;AACD;AASA;AAEC,EAAA;AACC,IAAA;AAAa,EAAA;AAKd,EAAA;AACD;AD1JA;AACA;AACA;AACA;AACA","file":"/home/runner/work/ai/ai/packages/tanstack-ai/dist/chunk-XFQ3QESX.cjs","sourcesContent":[null,"import { BaseTranscriptionAdapter } from \"@tanstack/ai/adapters\";\nimport type { TranscriptionOptions, TranscriptionResult } from \"@tanstack/ai\";\nimport {\n\ttype WorkersAiAdapterConfig,\n\ttype WorkersAiDirectBindingConfig,\n\ttype WorkersAiDirectCredentialsConfig,\n\ttype AiGatewayAdapterConfig,\n\tcreateGatewayFetch,\n\tisDirectBindingConfig,\n\tisDirectCredentialsConfig,\n\tvalidateWorkersAiConfig,\n} from \"../utils/create-fetcher\";\nimport { workersAiRestFetch, workersAiRestFetchBinary } from \"../utils/workers-ai-rest\";\nimport { uint8ArrayToBase64 } from \"../utils/binary\";\n\n// ---------------------------------------------------------------------------\n// Model types\n// ---------------------------------------------------------------------------\n\n/**\n * Workers AI models that support speech-to-text transcription.\n *\n * Note: the typed `AiModels` interface in `@cloudflare/workers-types` may lag\n * behind what's deployed. We use a string union here that matches the known\n * models including Deepgram partner models.\n *\n * **Nova-3 note:** `@cf/deepgram/nova-3` uses a different input format than the\n * Whisper models. Via binding it accepts `{ audio: { body: base64, contentType } }`.\n * Via REST it requires multipart form data (not JSON). The adapter handles both.\n */\nexport type WorkersAiTranscriptionModel =\n\t| \"@cf/openai/whisper\"\n\t| \"@cf/openai/whisper-tiny-en\"\n\t| \"@cf/openai/whisper-large-v3-turbo\"\n\t| \"@cf/deepgram/nova-3\"\n\t| (string & {});\n\n// ---------------------------------------------------------------------------\n// WorkersAiTranscriptionAdapter\n// ---------------------------------------------------------------------------\n\nexport class WorkersAiTranscriptionAdapter extends BaseTranscriptionAdapter<WorkersAiTranscriptionModel> {\n\treadonly name = \"workers-ai-transcription\" as const;\n\tprivate adapterConfig: WorkersAiAdapterConfig;\n\n\tconstructor(config: WorkersAiAdapterConfig, model: WorkersAiTranscriptionModel) {\n\t\tsuper({}, model);\n\t\tvalidateWorkersAiConfig(config);\n\t\tthis.adapterConfig = config;\n\t}\n\n\tasync transcribe(options: TranscriptionOptions): Promise<TranscriptionResult> {\n\t\tconst { audio, language, prompt, modelOptions } = options;\n\n\t\t// Normalize audio to raw bytes\n\t\tconst audioBytes = await normalizeAudioToBytes(audio);\n\n\t\tconst extra: Record<string, unknown> = { ...modelOptions };\n\t\tif (language) extra.language = language;\n\t\tif (prompt) extra.initial_prompt = prompt;\n\n\t\t// Build the model-specific audio payload:\n\t\t// - Deepgram Nova-3 (binding): { audio: { body: base64, contentType: \"audio/...\" } }\n\t\t// - Deepgram Nova-3 (REST): multipart FormData (handled separately)\n\t\t// - Whisper Large v3 Turbo (REST/gateway): { audio: base64string }\n\t\t// - Other Whisper models (binding): { audio: number[] }\n\t\tconst audioPayload = this.buildAudioPayload(audioBytes, audio);\n\n\t\tif (isDirectBindingConfig(this.adapterConfig)) {\n\t\t\treturn this.transcribeViaBinding(audioPayload, extra);\n\t\t}\n\n\t\tif (isDirectCredentialsConfig(this.adapterConfig)) {\n\t\t\t// Nova-3 REST requires raw binary audio, not JSON\n\t\t\tif (this.model === \"@cf/deepgram/nova-3\") {\n\t\t\t\treturn this.transcribeViaRestBinary(audioBytes, audio, extra);\n\t\t\t}\n\t\t\treturn this.transcribeViaRest(audioPayload, extra);\n\t\t}\n\n\t\treturn this.transcribeViaGateway(audioPayload, extra);\n\t}\n\n\t/**\n\t * Build the audio field for the request payload, handling model-specific formats.\n\t *\n\t * - `@cf/deepgram/nova-3` requires `{ body: base64, contentType: \"audio/...\" }`\n\t * - `@cf/openai/whisper-large-v3-turbo` REST/gateway accepts a base64 string\n\t * - Other Whisper models accept `number[]` (binding) or base64 (REST)\n\t */\n\tprivate buildAudioPayload(\n\t\taudioBytes: number[],\n\t\toriginalAudio: string | File | Blob | ArrayBuffer,\n\t): Record<string, unknown> {\n\t\tif (this.model === \"@cf/deepgram/nova-3\") {\n\t\t\tconst b64 = uint8ArrayToBase64(new Uint8Array(audioBytes));\n\t\t\tconst contentType = detectAudioContentType(originalAudio);\n\t\t\treturn { audio: { body: b64, contentType } };\n\t\t}\n\n\t\tif (this.model === \"@cf/openai/whisper-large-v3-turbo\") {\n\t\t\treturn { audio: uint8ArrayToBase64(new Uint8Array(audioBytes)) };\n\t\t}\n\n\t\treturn { audio: audioBytes };\n\t}\n\n\tprivate async transcribeViaBinding(\n\t\taudioPayload: Record<string, unknown>,\n\t\toptions: Record<string, unknown>,\n\t): Promise<TranscriptionResult> {\n\t\tconst ai = (this.adapterConfig as WorkersAiDirectBindingConfig).binding;\n\t\tconst result = (await ai.run(this.model, {\n\t\t\t...audioPayload,\n\t\t\t...options,\n\t\t})) as Record<string, unknown>;\n\t\treturn this.normalizeResult(result);\n\t}\n\n\tprivate async transcribeViaRest(\n\t\taudioPayload: Record<string, unknown>,\n\t\toptions: Record<string, unknown>,\n\t): Promise<TranscriptionResult> {\n\t\tconst config = this.adapterConfig as WorkersAiDirectCredentialsConfig;\n\n\t\tconst response = await workersAiRestFetch(\n\t\t\tconfig,\n\t\t\tthis.model,\n\t\t\t{ ...audioPayload, ...options },\n\t\t\t{\n\t\t\t\tlabel: \"Workers AI transcription\",\n\t\t\t\tsignal: (options as { signal?: AbortSignal }).signal,\n\t\t\t},\n\t\t);\n\n\t\tconst data = (await response.json()) as {\n\t\t\tresult?: Record<string, unknown>;\n\t\t} & Record<string, unknown>;\n\n\t\t// Cloudflare REST API wraps responses in { success, result: {...} }.\n\t\t// Use `data.result` when present, fall back to `data` for direct responses.\n\t\treturn this.normalizeResult(data.result ?? data);\n\t}\n\n\t/**\n\t * Transcribe via REST using raw binary audio.\n\t * Required for models like Deepgram Nova-3 that expect raw audio bytes\n\t * with a Content-Type header (e.g. \"audio/wav\") instead of JSON.\n\t */\n\tprivate async transcribeViaRestBinary(\n\t\taudioBytes: number[],\n\t\toriginalAudio: string | File | Blob | ArrayBuffer,\n\t\toptions: Record<string, unknown>,\n\t): Promise<TranscriptionResult> {\n\t\tconst config = this.adapterConfig as WorkersAiDirectCredentialsConfig;\n\t\tconst contentType = detectAudioContentType(originalAudio);\n\n\t\tconst response = await workersAiRestFetchBinary(\n\t\t\tconfig,\n\t\t\tthis.model,\n\t\t\tnew Uint8Array(audioBytes),\n\t\t\tcontentType,\n\t\t\t{\n\t\t\t\tlabel: \"Workers AI transcription\",\n\t\t\t\tsignal: (options as { signal?: AbortSignal }).signal,\n\t\t\t},\n\t\t);\n\n\t\tconst data = (await response.json()) as {\n\t\t\tresult?: Record<string, unknown>;\n\t\t} & Record<string, unknown>;\n\n\t\treturn this.normalizeResult(data.result ?? data);\n\t}\n\n\tprivate async transcribeViaGateway(\n\t\taudioPayload: Record<string, unknown>,\n\t\toptions: Record<string, unknown>,\n\t): Promise<TranscriptionResult> {\n\t\tconst gatewayConfig = this.adapterConfig as AiGatewayAdapterConfig;\n\t\tconst gatewayFetch = createGatewayFetch(\"workers-ai\", gatewayConfig);\n\n\t\t// The URL here is a placeholder — createGatewayFetch for \"workers-ai\" extracts\n\t\t// the model from the body, sets it as the endpoint, and routes through the gateway.\n\t\t// The actual URL path is not used.\n\t\tconst response = await gatewayFetch(\"https://api.cloudflare.com/v1/audio/transcriptions\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tmodel: this.model,\n\t\t\t\t...audioPayload,\n\t\t\t\t...options,\n\t\t\t}),\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst errorText = await response.text();\n\t\t\tthrow new Error(\n\t\t\t\t`Workers AI transcription gateway request failed (${response.status}): ${errorText}`,\n\t\t\t);\n\t\t}\n\n\t\tconst data = (await response.json()) as Record<string, unknown>;\n\t\treturn this.normalizeResult(data);\n\t}\n\n\t/**\n\t * Normalize Workers AI transcription results into the standard\n\t * TanStack AI TranscriptionResult shape.\n\t *\n\t * Handles three response formats:\n\t * - Whisper: `{ text, words?, vtt? }`\n\t * - Whisper v3-turbo: `{ text, segments?, transcription_info? }`\n\t * - Deepgram Nova-3: `{ results: { channels: [{ alternatives: [{ transcript, words }] }] } }`\n\t */\n\tprivate normalizeResult(raw: Record<string, unknown>): TranscriptionResult {\n\t\t// Deepgram Nova-3 format: { results: { channels: [{ alternatives: [{ transcript, words }] }] } }\n\t\tconst results = raw.results as Record<string, unknown> | undefined;\n\t\tif (results?.channels) {\n\t\t\tconst channels = results.channels as Array<{\n\t\t\t\talternatives?: Array<{\n\t\t\t\t\ttranscript?: string;\n\t\t\t\t\tconfidence?: number;\n\t\t\t\t\twords?: Array<{ word: string; start: number; end: number; confidence: number }>;\n\t\t\t\t}>;\n\t\t\t}>;\n\t\t\tconst alt = channels?.[0]?.alternatives?.[0];\n\t\t\tconst text = alt?.transcript ?? \"\";\n\t\t\tconst result: TranscriptionResult = {\n\t\t\t\tid: this.generateId(),\n\t\t\t\tmodel: this.model,\n\t\t\t\ttext,\n\t\t\t};\n\t\t\tif (alt?.words && Array.isArray(alt.words)) {\n\t\t\t\tresult.words = alt.words.map((w) => ({\n\t\t\t\t\tword: w.word ?? \"\",\n\t\t\t\t\tstart: w.start ?? 0,\n\t\t\t\t\tend: w.end ?? 0,\n\t\t\t\t}));\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\t// Whisper format: { text, words?, vtt? }\n\t\t// Whisper v3-turbo format: { text, segments?, transcription_info? }\n\t\tconst result: TranscriptionResult = {\n\t\t\tid: this.generateId(),\n\t\t\tmodel: this.model,\n\t\t\ttext: (raw.text as string) ?? \"\",\n\t\t};\n\n\t\t// Language from transcription_info (whisper-large-v3-turbo)\n\t\tconst transcriptionInfo = raw.transcription_info as Record<string, unknown> | undefined;\n\t\tif (transcriptionInfo?.language) {\n\t\t\tresult.language = transcriptionInfo.language as string;\n\t\t}\n\n\t\t// Duration\n\t\tif (transcriptionInfo?.duration != null) {\n\t\t\tresult.duration = transcriptionInfo.duration as number;\n\t\t}\n\n\t\t// Segments (whisper-large-v3-turbo returns these)\n\t\tif (raw.segments && Array.isArray(raw.segments)) {\n\t\t\tresult.segments = raw.segments.map((seg: Record<string, unknown>, idx: number) => ({\n\t\t\t\tid: idx,\n\t\t\t\ttext: (seg.text as string) ?? \"\",\n\t\t\t\tstart: (seg.start as number) ?? 0,\n\t\t\t\tend: (seg.end as number) ?? 0,\n\t\t\t}));\n\t\t}\n\n\t\t// Words — basic whisper returns top-level words[], v3-turbo nests them in segments\n\t\tif (raw.words && Array.isArray(raw.words)) {\n\t\t\tresult.words = raw.words.map((w: Record<string, unknown>) => ({\n\t\t\t\tword: (w.word as string) ?? \"\",\n\t\t\t\tstart: (w.start as number) ?? 0,\n\t\t\t\tend: (w.end as number) ?? 0,\n\t\t\t}));\n\t\t}\n\n\t\treturn result;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a Workers AI transcription adapter for speech-to-text.\n *\n * Works with TanStack AI's `generateTranscription()` activity function:\n * ```ts\n * import { generateTranscription } from \"@tanstack/ai\";\n * import { createWorkersAiTranscription } from \"@cloudflare/tanstack-ai\";\n *\n * const adapter = createWorkersAiTranscription(\n * \"@cf/openai/whisper-large-v3-turbo\",\n * { binding: env.AI },\n * );\n *\n * const result = await generateTranscription({ adapter, audio: audioData });\n * // result.text — the transcribed text\n * ```\n *\n * Note: Factory takes `(model, config)` for ergonomics — the class constructor\n * uses `(config, model)` to match TanStack AI's upstream convention.\n */\nexport function createWorkersAiTranscription(\n\tmodel: WorkersAiTranscriptionModel,\n\tconfig: WorkersAiAdapterConfig,\n) {\n\treturn new WorkersAiTranscriptionAdapter(config, model);\n}\n\n// ---------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize various audio input formats into a number[] (raw bytes).\n *\n * Note: `File extends Blob`, so `File` instances are handled by the\n * `instanceof Blob` branch. `Blob.arrayBuffer()` always reads the full\n * contents regardless of any prior reads — there's no cursor to worry about.\n */\nasync function normalizeAudioToBytes(audio: string | File | Blob | ArrayBuffer): Promise<number[]> {\n\tif (audio instanceof ArrayBuffer) {\n\t\treturn Array.from(new Uint8Array(audio));\n\t}\n\n\tif (audio instanceof Blob) {\n\t\t// This also handles `File` (which extends Blob)\n\t\tconst buffer = await audio.arrayBuffer();\n\t\treturn Array.from(new Uint8Array(buffer));\n\t}\n\n\tif (typeof audio === \"string\") {\n\t\t// Assume base64 string — decode to bytes\n\t\tconst binary = atob(audio);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i);\n\t\t}\n\t\treturn Array.from(bytes);\n\t}\n\n\tthrow new Error(\"Unsupported audio format. Expected string, File, Blob, or ArrayBuffer.\");\n}\n\n/**\n * Detect the MIME type of the audio input for models that require it\n * (e.g., Deepgram Nova-3).\n *\n * - `File` / `Blob`: use the `.type` property (e.g., \"audio/wav\")\n * - `ArrayBuffer` / `string`: defaults to \"audio/wav\"\n */\nfunction detectAudioContentType(audio: string | File | Blob | ArrayBuffer): string {\n\t// File and Blob carry their own MIME type\n\tif (audio instanceof Blob && audio.type) {\n\t\treturn audio.type;\n\t}\n\n\t// For raw bytes, default to audio/wav — this is the most common\n\t// format for transcription inputs and what the E2E tests use.\n\treturn \"audio/wav\";\n}\n"]}
|
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
isDirectBindingConfig,
|
|
11
11
|
isDirectCredentialsConfig,
|
|
12
12
|
validateWorkersAiConfig
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-S5QBHI6O.js";
|
|
14
14
|
import {
|
|
15
15
|
__publicField
|
|
16
16
|
} from "./chunk-V6TY7KAL.js";
|
|
@@ -95,4 +95,4 @@ export {
|
|
|
95
95
|
WorkersAiImageAdapter,
|
|
96
96
|
createWorkersAiImage
|
|
97
97
|
};
|
|
98
|
-
//# sourceMappingURL=chunk-
|
|
98
|
+
//# sourceMappingURL=chunk-ZJMMBD6H.js.map
|
package/dist/index.cjs
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkXFQ3QESXcjs = require('./chunk-XFQ3QESX.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkKDVHOUEPcjs = require('./chunk-KDVHOUEP.cjs');
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var _chunk32U73O6Ecjs = require('./chunk-32U73O6E.cjs');
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
|
|
14
|
-
var
|
|
14
|
+
var _chunkMMTLH53Hcjs = require('./chunk-MMTLH53H.cjs');
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
|
|
@@ -28,7 +28,7 @@ var _chunkV4LKHWJAcjs = require('./chunk-V4LKHWJA.cjs');
|
|
|
28
28
|
|
|
29
29
|
|
|
30
30
|
|
|
31
|
-
var
|
|
31
|
+
var _chunkKW27GIQLcjs = require('./chunk-KW27GIQL.cjs');
|
|
32
32
|
|
|
33
33
|
|
|
34
34
|
|
|
@@ -41,21 +41,21 @@ var _chunkUWBO33IGcjs = require('./chunk-UWBO33IG.cjs');
|
|
|
41
41
|
|
|
42
42
|
|
|
43
43
|
|
|
44
|
-
var
|
|
44
|
+
var _chunkTG4UQPGBcjs = require('./chunk-TG4UQPGB.cjs');
|
|
45
45
|
|
|
46
46
|
|
|
47
47
|
|
|
48
48
|
|
|
49
|
-
var
|
|
49
|
+
var _chunkU2PMR3PTcjs = require('./chunk-U2PMR3PT.cjs');
|
|
50
50
|
|
|
51
51
|
|
|
52
|
-
var
|
|
52
|
+
var _chunk3PJHW45Xcjs = require('./chunk-3PJHW45X.cjs');
|
|
53
53
|
require('./chunk-3VQDXJLW.cjs');
|
|
54
54
|
|
|
55
55
|
|
|
56
|
-
var
|
|
56
|
+
var _chunkH24HFVUJcjs = require('./chunk-H24HFVUJ.cjs');
|
|
57
57
|
require('./chunk-7HSUHP63.cjs');
|
|
58
|
-
require('./chunk-
|
|
58
|
+
require('./chunk-U5NL4EM4.cjs');
|
|
59
59
|
require('./chunk-4DE2IREA.cjs');
|
|
60
60
|
|
|
61
61
|
|
|
@@ -93,5 +93,5 @@ require('./chunk-4DE2IREA.cjs');
|
|
|
93
93
|
|
|
94
94
|
|
|
95
95
|
|
|
96
|
-
exports.ANTHROPIC_MODELS =
|
|
96
|
+
exports.ANTHROPIC_MODELS = _chunkMMTLH53Hcjs.ANTHROPIC_MODELS; exports.GROK_CHAT_MODELS = _chunkKW27GIQLcjs.GROK_CHAT_MODELS; exports.GROK_IMAGE_MODELS = _chunkKW27GIQLcjs.GROK_IMAGE_MODELS; exports.GeminiImageModels = _chunkV4LKHWJAcjs.GeminiImageModels; exports.GeminiSummarizeModels = _chunkV4LKHWJAcjs.GeminiSummarizeModels; exports.GeminiTTSModels = _chunkV4LKHWJAcjs.GeminiTTSModels; exports.GeminiTextModels = _chunkV4LKHWJAcjs.GeminiTextModels; exports.OPENAI_CHAT_MODELS = _chunkTG4UQPGBcjs.OPENAI_CHAT_MODELS; exports.OPENAI_IMAGE_MODELS = _chunkTG4UQPGBcjs.OPENAI_IMAGE_MODELS; exports.OPENAI_TRANSCRIPTION_MODELS = _chunkTG4UQPGBcjs.OPENAI_TRANSCRIPTION_MODELS; exports.OPENAI_TTS_MODELS = _chunkTG4UQPGBcjs.OPENAI_TTS_MODELS; exports.OPENAI_VIDEO_MODELS = _chunkTG4UQPGBcjs.OPENAI_VIDEO_MODELS; exports.createAnthropicChat = _chunkMMTLH53Hcjs.createAnthropicChat; exports.createAnthropicSummarize = _chunkMMTLH53Hcjs.createAnthropicSummarize; exports.createGeminiChat = _chunkV4LKHWJAcjs.createGeminiChat; exports.createGeminiImage = _chunkV4LKHWJAcjs.createGeminiImage; exports.createGeminiSummarize = _chunkV4LKHWJAcjs.createGeminiSummarize; exports.createGeminiTts = _chunkV4LKHWJAcjs.createGeminiTts; exports.createGrokChat = _chunkKW27GIQLcjs.createGrokChat; exports.createGrokImage = _chunkKW27GIQLcjs.createGrokImage; exports.createGrokSummarize = _chunkKW27GIQLcjs.createGrokSummarize; exports.createOpenAiChat = _chunkTG4UQPGBcjs.createOpenAiChat; exports.createOpenAiImage = _chunkTG4UQPGBcjs.createOpenAiImage; exports.createOpenAiSummarize = _chunkTG4UQPGBcjs.createOpenAiSummarize; exports.createOpenAiTranscription = _chunkTG4UQPGBcjs.createOpenAiTranscription; exports.createOpenAiTts = _chunkTG4UQPGBcjs.createOpenAiTts; exports.createOpenAiVideo = _chunkTG4UQPGBcjs.createOpenAiVideo; exports.createOpenRouterChat = _chunkU2PMR3PTcjs.createOpenRouterChat; exports.createOpenRouterImage = _chunkU2PMR3PTcjs.createOpenRouterImage; exports.createOpenRouterSummarize = _chunkU2PMR3PTcjs.createOpenRouterSummarize; exports.createWorkersAiChat = _chunk32U73O6Ecjs.createWorkersAiChat; exports.createWorkersAiImage = _chunk3PJHW45Xcjs.createWorkersAiImage; exports.createWorkersAiSummarize = _chunkH24HFVUJcjs.createWorkersAiSummarize; exports.createWorkersAiTranscription = _chunkXFQ3QESXcjs.createWorkersAiTranscription; exports.createWorkersAiTts = _chunkKDVHOUEPcjs.createWorkersAiTts;
|
|
97
97
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createWorkersAiTranscription
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-DG46OSFY.js";
|
|
4
4
|
import {
|
|
5
5
|
createWorkersAiTts
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-QMRONSLN.js";
|
|
7
7
|
import {
|
|
8
8
|
createWorkersAiChat
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-NSWLVANP.js";
|
|
10
10
|
import {
|
|
11
11
|
ANTHROPIC_MODELS,
|
|
12
12
|
createAnthropicChat,
|
|
13
13
|
createAnthropicSummarize
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-MOAWHNNP.js";
|
|
15
15
|
import {
|
|
16
16
|
GeminiImageModels,
|
|
17
17
|
GeminiSummarizeModels,
|
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
createGrokChat,
|
|
29
29
|
createGrokImage,
|
|
30
30
|
createGrokSummarize
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-OGAH3FYW.js";
|
|
32
32
|
import {
|
|
33
33
|
OPENAI_CHAT_MODELS,
|
|
34
34
|
OPENAI_IMAGE_MODELS,
|
|
@@ -41,21 +41,21 @@ import {
|
|
|
41
41
|
createOpenAiTranscription,
|
|
42
42
|
createOpenAiTts,
|
|
43
43
|
createOpenAiVideo
|
|
44
|
-
} from "./chunk-
|
|
44
|
+
} from "./chunk-RWLCEKT6.js";
|
|
45
45
|
import {
|
|
46
46
|
createOpenRouterChat,
|
|
47
47
|
createOpenRouterImage,
|
|
48
48
|
createOpenRouterSummarize
|
|
49
|
-
} from "./chunk-
|
|
49
|
+
} from "./chunk-I2MCLFJ5.js";
|
|
50
50
|
import {
|
|
51
51
|
createWorkersAiImage
|
|
52
|
-
} from "./chunk-
|
|
52
|
+
} from "./chunk-ZJMMBD6H.js";
|
|
53
53
|
import "./chunk-XU7YEPML.js";
|
|
54
54
|
import {
|
|
55
55
|
createWorkersAiSummarize
|
|
56
|
-
} from "./chunk-
|
|
56
|
+
} from "./chunk-IPEZXCDR.js";
|
|
57
57
|
import "./chunk-2VII5BK2.js";
|
|
58
|
-
import "./chunk-
|
|
58
|
+
import "./chunk-S5QBHI6O.js";
|
|
59
59
|
import "./chunk-V6TY7KAL.js";
|
|
60
60
|
export {
|
|
61
61
|
ANTHROPIC_MODELS,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/tanstack-ai",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "Use TanStack AI with Cloudflare Workers AI and AI Gateway",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -88,32 +88,33 @@
|
|
|
88
88
|
"access": "public"
|
|
89
89
|
},
|
|
90
90
|
"dependencies": {
|
|
91
|
-
"openai": "^6.
|
|
91
|
+
"openai": "^6.22.0"
|
|
92
92
|
},
|
|
93
93
|
"devDependencies": {
|
|
94
|
-
"@cloudflare/workers-types": "^4.
|
|
95
|
-
"@microsoft/api-extractor": "^7.
|
|
96
|
-
"@tanstack/ai": "^0.5.
|
|
97
|
-
"dotenv": "^17.
|
|
94
|
+
"@cloudflare/workers-types": "^4.20260227.0",
|
|
95
|
+
"@microsoft/api-extractor": "^7.57.1",
|
|
96
|
+
"@tanstack/ai": "^0.5.1",
|
|
97
|
+
"dotenv": "^17.3.1"
|
|
98
98
|
},
|
|
99
99
|
"peerDependencies": {
|
|
100
100
|
"@tanstack/ai": "^0.5.0"
|
|
101
101
|
},
|
|
102
102
|
"optionalDependencies": {
|
|
103
|
-
"@anthropic-ai/sdk": "^0.
|
|
104
|
-
"@google/genai": "^1.
|
|
103
|
+
"@anthropic-ai/sdk": "^0.78.0",
|
|
104
|
+
"@google/genai": "^1.42.0",
|
|
105
105
|
"@openrouter/sdk": "^0.8.0",
|
|
106
106
|
"@tanstack/ai-anthropic": "^0.5.0",
|
|
107
107
|
"@tanstack/ai-gemini": "^0.5.0",
|
|
108
108
|
"@tanstack/ai-grok": "^0.5.0",
|
|
109
109
|
"@tanstack/ai-openai": "^0.5.0",
|
|
110
|
-
"@tanstack/ai-openrouter": "^0.5.
|
|
110
|
+
"@tanstack/ai-openrouter": "^0.5.1"
|
|
111
111
|
},
|
|
112
112
|
"scripts": {
|
|
113
113
|
"build": "rm -rf dist && tsup --config tsup.config.ts",
|
|
114
114
|
"format": "biome format --write",
|
|
115
115
|
"type-check": "tsc --noEmit",
|
|
116
|
-
"test": "vitest",
|
|
116
|
+
"test": "vitest --run",
|
|
117
|
+
"test:watch": "vitest",
|
|
117
118
|
"test:ci": "vitest --watch=false",
|
|
118
119
|
"test:e2e": "vitest --config vitest.e2e.config.ts --watch=false",
|
|
119
120
|
"test:e2e:rest": "vitest --config vitest.e2e.config.ts --watch=false test/e2e/workers-ai-rest.e2e.test.ts",
|