workers-ai-provider 3.2.0 → 3.3.0

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.
@@ -0,0 +1,70 @@
1
+ import { APICallError } from "@ai-sdk/provider";
2
+ import {
3
+ headersToObject,
4
+ isAbortError,
5
+ messageOf,
6
+ parseWorkersAIErrorCode,
7
+ WORKERS_AI_ERROR_CODE_TO_STATUS,
8
+ } from "@cloudflare/gateway-core";
9
+
10
+ // Re-exported from `@cloudflare/gateway-core` (single source of truth, shared
11
+ // with `@cloudflare/tanstack-ai`) so existing importers of this module keep
12
+ // working unchanged.
13
+ export { parseWorkersAIErrorCode, WORKERS_AI_ERROR_CODE_TO_STATUS };
14
+
15
+ /**
16
+ * Normalize an error thrown by the Workers AI **binding** (`env.AI.run`) into an
17
+ * `APICallError` so the AI SDK can classify and retry it.
18
+ *
19
+ * Cancellations (`AbortError` / `TimeoutError` / `ResponseAborted`, including
20
+ * `DOMException` aborts) and errors that are already an `APICallError` pass
21
+ * through unchanged. Everything else becomes an
22
+ * `APICallError`; when the internal code maps to a known HTTP status, that
23
+ * `statusCode` is attached and `APICallError` derives `isRetryable` from it.
24
+ * Unrecognized errors get no `statusCode`, so they stay non-retryable (the
25
+ * prior behavior).
26
+ */
27
+ export function normalizeBindingError(
28
+ error: unknown,
29
+ context: { model: string; requestBodyValues: unknown },
30
+ ): unknown {
31
+ if (APICallError.isInstance(error) || isAbortError(error)) {
32
+ return error;
33
+ }
34
+
35
+ const code = parseWorkersAIErrorCode(error);
36
+ const statusCode = code != null ? WORKERS_AI_ERROR_CODE_TO_STATUS[code] : undefined;
37
+ const message = messageOf(error);
38
+
39
+ return new APICallError({
40
+ message,
41
+ url: `workers-ai:binding/run/${context.model}`,
42
+ requestBodyValues: context.requestBodyValues,
43
+ statusCode,
44
+ responseBody: message,
45
+ cause: error,
46
+ ...(code != null ? { data: { workersAIErrorCode: code } } : {}),
47
+ });
48
+ }
49
+
50
+ /**
51
+ * Build an `APICallError` from a non-OK Workers AI **REST** response. The HTTP
52
+ * status is authoritative here, so `APICallError` derives `isRetryable` from it
53
+ * directly (429 / 5xx → retryable). Response headers are preserved so the AI
54
+ * SDK can honor `Retry-After`. The message keeps the historical
55
+ * `"Workers AI API error (<status> <statusText>): <body>"` shape.
56
+ */
57
+ export function apiCallErrorFromResponse(
58
+ response: Response,
59
+ errorBody: string,
60
+ context: { url: string; requestBodyValues: unknown },
61
+ ): APICallError {
62
+ return new APICallError({
63
+ message: `Workers AI API error (${response.status} ${response.statusText}): ${errorBody}`,
64
+ url: context.url,
65
+ requestBodyValues: context.requestBodyValues,
66
+ statusCode: response.status,
67
+ responseHeaders: headersToObject(response.headers),
68
+ responseBody: errorBody,
69
+ });
70
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ImageModelV3, SharedV3Warning } from "@ai-sdk/provider";
2
+ import { normalizeBindingError } from "./workersai-error";
2
3
  import type { WorkersAIImageSettings } from "./workersai-image-settings";
3
4
  import type { ImageGenerationModels } from "./workersai-models";
4
5
 
@@ -48,19 +49,26 @@ export class WorkersAIImageModel implements ImageModelV3 {
48
49
  }
49
50
 
50
51
  const generateImage = async () => {
51
- const output = (await this.config.binding.run(
52
- this.modelId as keyof AiModels,
53
- {
54
- height,
55
- prompt: prompt ?? "",
56
- seed,
57
- width,
58
- },
59
- {
52
+ const inputs = {
53
+ height,
54
+ prompt: prompt ?? "",
55
+ seed,
56
+ width,
57
+ };
58
+ let output: unknown;
59
+ try {
60
+ output = (await this.config.binding.run(this.modelId as keyof AiModels, inputs, {
60
61
  gateway: this.config.gateway,
61
62
  signal: abortSignal,
62
- } as AiOptions,
63
- )) as unknown;
63
+ } as AiOptions)) as unknown;
64
+ } catch (error) {
65
+ // Normalize binding failures (e.g. 3040 "out of capacity" → 429) into
66
+ // a retryable APICallError so the AI SDK's maxRetries can engage.
67
+ throw normalizeBindingError(error, {
68
+ model: this.modelId,
69
+ requestBodyValues: inputs,
70
+ });
71
+ }
64
72
 
65
73
  return toUint8Array(output);
66
74
  };
@@ -1,4 +1,5 @@
1
1
  import type { RerankingModelV3, SharedV3Warning } from "@ai-sdk/provider";
2
+ import { normalizeBindingError } from "./workersai-error";
2
3
  import type { WorkersAIRerankingSettings } from "./workersai-reranking-settings";
3
4
  import type { RerankingModels } from "./workersai-models";
4
5
 
@@ -49,11 +50,21 @@ export class WorkersAIRerankingModel implements RerankingModelV3 {
49
50
  inputs.top_k = topN;
50
51
  }
51
52
 
52
- const result = (await this.config.binding.run(
53
- this.modelId as Parameters<Ai["run"]>[0],
54
- inputs as Parameters<Ai["run"]>[1],
55
- { gateway: this.config.gateway, signal: abortSignal } as AiOptions,
56
- )) as Record<string, unknown>;
53
+ let result: Record<string, unknown>;
54
+ try {
55
+ result = (await this.config.binding.run(
56
+ this.modelId as Parameters<Ai["run"]>[0],
57
+ inputs as Parameters<Ai["run"]>[1],
58
+ { gateway: this.config.gateway, signal: abortSignal } as AiOptions,
59
+ )) as Record<string, unknown>;
60
+ } catch (error) {
61
+ // Normalize binding failures (e.g. 3040 "out of capacity" → 429) into a
62
+ // retryable APICallError so the AI SDK's maxRetries can engage.
63
+ throw normalizeBindingError(error, {
64
+ model: this.modelId,
65
+ requestBodyValues: inputs,
66
+ });
67
+ }
57
68
 
58
69
  // Workers AI returns { response: [{ id, score }] }
59
70
  const response = result.response as Array<{ id?: number; score?: number }> | undefined;
@@ -1,4 +1,5 @@
1
1
  import type { SpeechModelV3, SharedV3Warning } from "@ai-sdk/provider";
2
+ import { apiCallErrorFromResponse, normalizeBindingError } from "./workersai-error";
2
3
  import type { WorkersAISpeechSettings } from "./workersai-speech-settings";
3
4
  import type { SpeechModels } from "./workersai-models";
4
5
 
@@ -56,19 +57,40 @@ export class WorkersAISpeechModel implements SpeechModelV3 {
56
57
  if (voice) inputs.voice = voice;
57
58
  if (speed != null) inputs.speed = speed;
58
59
 
59
- const result = await this.config.binding.run(
60
- this.modelId as Parameters<Ai["run"]>[0],
61
- inputs as Parameters<Ai["run"]>[1],
62
- {
63
- gateway: this.config.gateway,
64
- signal: abortSignal,
65
- // returnRawResponse prevents the createRun REST shim from trying
66
- // to JSON.parse binary audio. Real env.AI bindings don't recognize
67
- // this option it has no effect, and the binding returns the normal
68
- // binary result (Uint8Array/ReadableStream) which toUint8Array handles.
69
- returnRawResponse: true,
70
- } as AiOptions,
71
- );
60
+ let result: unknown;
61
+ try {
62
+ result = await this.config.binding.run(
63
+ this.modelId as Parameters<Ai["run"]>[0],
64
+ inputs as Parameters<Ai["run"]>[1],
65
+ {
66
+ gateway: this.config.gateway,
67
+ signal: abortSignal,
68
+ // returnRawResponse prevents the createRun REST shim from trying
69
+ // to JSON.parse binary audio. Real env.AI bindings don't recognize
70
+ // this option — it has no effect, and the binding returns the normal
71
+ // binary result (Uint8Array/ReadableStream) which toUint8Array handles.
72
+ returnRawResponse: true,
73
+ } as AiOptions,
74
+ );
75
+ } catch (error) {
76
+ // Normalize binding failures (e.g. 3040 "out of capacity" → 429) into a
77
+ // retryable APICallError so the AI SDK's maxRetries can engage.
78
+ throw normalizeBindingError(error, {
79
+ model: this.modelId,
80
+ requestBodyValues: inputs,
81
+ });
82
+ }
83
+
84
+ // The REST shim uses `returnRawResponse`, so it does NOT throw on a non-OK
85
+ // status — it hands back the raw Response. Without this guard the error body
86
+ // would be decoded as "audio". Surface it as a (retryable-aware) APICallError.
87
+ if (result instanceof Response && !result.ok) {
88
+ const errorBody = await result.text().catch(() => "<unable to read response body>");
89
+ throw apiCallErrorFromResponse(result, errorBody, {
90
+ url: `workers-ai:run/${this.modelId}`,
91
+ requestBodyValues: inputs,
92
+ });
93
+ }
72
94
 
73
95
  // Workers AI TTS returns binary audio in various formats:
74
96
  // - Binding: Uint8Array, ArrayBuffer, ReadableStream, or { audio: base64 }
@@ -2,6 +2,7 @@ import type { TranscriptionModelV3, SharedV3Warning } from "@ai-sdk/provider";
2
2
  import type { WorkersAITranscriptionSettings } from "./workersai-transcription-settings";
3
3
  import type { TranscriptionModels } from "./workersai-models";
4
4
  import { createRunBinary, type CreateRunConfig } from "./utils";
5
+ import { normalizeBindingError } from "./workersai-error";
5
6
 
6
7
  export type WorkersAITranscriptionConfig = {
7
8
  provider: string;
@@ -57,10 +58,20 @@ export class WorkersAITranscriptionModel implements TranscriptionModelV3 {
57
58
 
58
59
  let rawResult: unknown;
59
60
 
60
- if (isNova3) {
61
- rawResult = await this.runNova3(audioBytes, mediaType, abortSignal);
62
- } else {
63
- rawResult = await this.runWhisper(audioBytes, abortSignal);
61
+ try {
62
+ if (isNova3) {
63
+ rawResult = await this.runNova3(audioBytes, mediaType, abortSignal);
64
+ } else {
65
+ rawResult = await this.runWhisper(audioBytes, abortSignal);
66
+ }
67
+ } catch (error) {
68
+ // Normalize binding failures (e.g. 3040 "out of capacity" → 429) into a
69
+ // retryable APICallError so the AI SDK's maxRetries can engage. The
70
+ // REST binary path already throws an APICallError, which passes through.
71
+ throw normalizeBindingError(error, {
72
+ model: this.modelId,
73
+ requestBodyValues: { mediaType },
74
+ });
64
75
  }
65
76
 
66
77
  const result = rawResult as Record<string, unknown>;
@@ -1 +0,0 @@
1
- {"version":3,"file":"gateway-provider-1USFWm7c.mjs","names":[],"sources":["../src/errors.ts","../src/gateway-providers.ts","../src/gateway-provider.ts"],"sourcesContent":["/**\n * Typed errors for the gateway delegate.\n *\n * - {@link WorkersAIGatewayError} — a single dispatch failed. Carries a coarse\n * {@link GatewayErrorCode}, a `recoverable` hint (whether a retry/fallback is\n * worth attempting), and the parsed gateway/provider envelope.\n * - {@link WorkersAIFallbackError} — every model in a client-side fallback chain\n * failed. Carries the per-attempt tree so callers can see exactly what was\n * tried and why each leg failed.\n */\n\n/** Coarse classification of a gateway/provider failure. */\nexport type GatewayErrorCode =\n\t| \"auth\" // 401 / 403 — bad or missing key (BYOK), or unified billing not enabled\n\t| \"rate-limit\" // 429 — throttled\n\t| \"not-found\" // 404 — unknown model/endpoint (or expired resume buffer)\n\t| \"bad-request\" // 400 / 422 — malformed request\n\t| \"provider-error\" // 5xx — upstream provider failure\n\t| \"gateway-error\" // gateway/transport failure with no usable status\n\t| \"resume-expired\" // resume buffer TTL elapsed (404 from resume endpoint)\n\t| \"unknown\";\n\n/** Context attached to a {@link WorkersAIGatewayError}. */\nexport interface GatewayErrorContext {\n\t/** Gateway provider id (e.g. `\"openai\"`, `\"google-ai-studio\"`). */\n\tprovider?: string;\n\t/** Provider-native model id. */\n\tmodelId?: string;\n\t/** Transport the failed dispatch used. */\n\ttransport?: \"run\" | \"gateway\";\n\t/** HTTP status, if any. */\n\tstatus?: number | null;\n\t/** `cf-aig-log-id` for cross-referencing in the dashboard. */\n\tlogId?: string | null;\n\t/** `cf-aig-run-id`, if the run path issued one. */\n\trunId?: string | null;\n}\n\n/** Map an HTTP status to a {@link GatewayErrorCode} + recoverability hint. */\nexport function classifyStatus(status: number): {\n\tcode: GatewayErrorCode;\n\trecoverable: boolean;\n} {\n\tif (status === 401 || status === 403) return { code: \"auth\", recoverable: false };\n\tif (status === 429) return { code: \"rate-limit\", recoverable: true };\n\tif (status === 404) return { code: \"not-found\", recoverable: false };\n\tif (status === 400 || status === 422) return { code: \"bad-request\", recoverable: false };\n\tif (status >= 500) return { code: \"provider-error\", recoverable: true };\n\treturn { code: \"unknown\", recoverable: false };\n}\n\n/** Best-effort extraction of a human message from a CF/provider error envelope. */\nexport function extractErrorMessage(raw: unknown): string | undefined {\n\tif (typeof raw === \"string\") {\n\t\tconst trimmed = raw.trim();\n\t\tif (!trimmed) return undefined;\n\t\ttry {\n\t\t\treturn extractErrorMessage(JSON.parse(trimmed));\n\t\t} catch {\n\t\t\treturn trimmed.slice(0, 500);\n\t\t}\n\t}\n\tif (!raw || typeof raw !== \"object\") return undefined;\n\tconst obj = raw as Record<string, unknown>;\n\t// CF gateway envelope: { errors: [{ code, message }] }\n\tif (Array.isArray(obj.errors) && obj.errors.length > 0) {\n\t\tconst first = obj.errors[0] as Record<string, unknown>;\n\t\tif (typeof first?.message === \"string\") return first.message;\n\t}\n\t// Provider envelopes: { error: { message } } or { error: \"...\" } or { message }\n\tif (obj.error && typeof obj.error === \"object\") {\n\t\tconst err = obj.error as Record<string, unknown>;\n\t\tif (typeof err.message === \"string\") return err.message;\n\t}\n\tif (typeof obj.error === \"string\") return obj.error;\n\tif (typeof obj.message === \"string\") return obj.message;\n\treturn undefined;\n}\n\n/** A single dispatch failure through AI Gateway (run or gateway path). */\nexport class WorkersAIGatewayError extends Error {\n\treadonly code: GatewayErrorCode;\n\t/** Whether a retry or fallback to another model is worth attempting. */\n\treadonly recoverable: boolean;\n\treadonly status: number | null;\n\treadonly context: GatewayErrorContext;\n\t/** Parsed gateway/provider error envelope (or raw text). */\n\treadonly raw?: unknown;\n\toverride readonly cause?: unknown;\n\n\tconstructor(\n\t\tcode: GatewayErrorCode,\n\t\tmessage: string,\n\t\topts: {\n\t\t\trecoverable?: boolean;\n\t\t\tstatus?: number | null;\n\t\t\tcontext?: GatewayErrorContext;\n\t\t\traw?: unknown;\n\t\t\tcause?: unknown;\n\t\t} = {},\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WorkersAIGatewayError\";\n\t\tthis.code = code;\n\t\tthis.recoverable = opts.recoverable ?? false;\n\t\tthis.status = opts.status ?? null;\n\t\tthis.context = opts.context ?? {};\n\t\tthis.raw = opts.raw;\n\t\tthis.cause = opts.cause;\n\t}\n\n\t/**\n\t * Classify an arbitrary thrown value. Understands AI SDK `APICallError`\n\t * (reads `statusCode` / `responseBody` / `isRetryable`); falls back to a\n\t * recoverable `gateway-error` for transport/connection failures so a fallback\n\t * chain keeps trying.\n\t */\n\tstatic fromUnknown(e: unknown): WorkersAIGatewayError {\n\t\tif (e instanceof WorkersAIGatewayError) return e;\n\t\tconst obj = e && typeof e === \"object\" ? (e as Record<string, unknown>) : {};\n\t\tconst status = typeof obj.statusCode === \"number\" ? obj.statusCode : null;\n\t\tconst responseBody = typeof obj.responseBody === \"string\" ? obj.responseBody : undefined;\n\n\t\tif (status !== null) {\n\t\t\tconst classified = classifyStatus(status);\n\t\t\t// AI SDK already decides retryability per status; prefer it when present.\n\t\t\tconst recoverable =\n\t\t\t\ttypeof obj.isRetryable === \"boolean\" ? obj.isRetryable : classified.recoverable;\n\t\t\tconst message =\n\t\t\t\textractErrorMessage(responseBody) ??\n\t\t\t\t(e instanceof Error ? e.message : `Gateway dispatch failed (HTTP ${status}).`);\n\t\t\tlet raw: unknown = responseBody;\n\t\t\ttry {\n\t\t\t\traw = responseBody ? JSON.parse(responseBody) : responseBody;\n\t\t\t} catch {\n\t\t\t\t// keep raw text\n\t\t\t}\n\t\t\treturn new WorkersAIGatewayError(classified.code, message, {\n\t\t\t\trecoverable,\n\t\t\t\tstatus,\n\t\t\t\traw,\n\t\t\t\tcause: e,\n\t\t\t});\n\t\t}\n\n\t\treturn new WorkersAIGatewayError(\n\t\t\t\"gateway-error\",\n\t\t\te instanceof Error ? e.message : String(e),\n\t\t\t{ recoverable: true, cause: e },\n\t\t);\n\t}\n\n\t/** Build from an HTTP `Response` (reads the body for the envelope). */\n\tstatic async fromResponse(\n\t\tresp: Response,\n\t\tcontext: GatewayErrorContext = {},\n\t): Promise<WorkersAIGatewayError> {\n\t\tconst text = await resp.text().catch(() => \"\");\n\t\tconst { code, recoverable } = classifyStatus(resp.status);\n\t\tconst message =\n\t\t\textractErrorMessage(text) ?? `Gateway dispatch failed (HTTP ${resp.status}).`;\n\t\tlet raw: unknown = text;\n\t\ttry {\n\t\t\traw = text ? JSON.parse(text) : text;\n\t\t} catch {\n\t\t\t// keep raw text\n\t\t}\n\t\treturn new WorkersAIGatewayError(code, message, {\n\t\t\trecoverable,\n\t\t\tstatus: resp.status,\n\t\t\traw,\n\t\t\tcontext: {\n\t\t\t\t...context,\n\t\t\t\tstatus: resp.status,\n\t\t\t\tlogId: resp.headers.get(\"cf-aig-log-id\"),\n\t\t\t\trunId: resp.headers.get(\"cf-aig-run-id\"),\n\t\t\t},\n\t\t});\n\t}\n}\n\n/** One leg of a client-side fallback chain. */\nexport interface FallbackAttempt {\n\t/** The model slug attempted. */\n\tmodel: string;\n\t/** Transport used for this attempt. */\n\ttransport: \"run\" | \"gateway\";\n\t/** Whether this attempt succeeded. */\n\tok: boolean;\n\t/** HTTP status, if any. */\n\tstatus?: number | null;\n\t/** The classified error, when the attempt failed. */\n\terror?: WorkersAIGatewayError;\n}\n\n/** Every model in a client-side fallback chain failed. */\nexport class WorkersAIFallbackError extends Error {\n\t/** The ordered attempt tree (primary first, then each fallback). */\n\treadonly attempts: FallbackAttempt[];\n\n\tconstructor(attempts: FallbackAttempt[], message?: string) {\n\t\tconst tried = attempts.map((a) => a.model).join(\" → \");\n\t\tsuper(message ?? `All fallback models failed: ${tried}.`);\n\t\tthis.name = \"WorkersAIFallbackError\";\n\t\tthis.attempts = attempts;\n\t}\n\n\t/** The last (most recent) attempt's error, if any. */\n\tget lastError(): WorkersAIGatewayError | undefined {\n\t\tfor (let i = this.attempts.length - 1; i >= 0; i--) {\n\t\t\tconst e = this.attempts[i].error;\n\t\t\tif (e) return e;\n\t\t}\n\t\treturn undefined;\n\t}\n}\n","/**\n * Registry of Cloudflare AI Gateway providers.\n *\n * One table drives both delegate surfaces:\n *\n * - **Slug delegate** (`wai(\"openai/gpt-5\")`): `resolverKey` is the slug prefix\n * the user types. `runCatalog` providers dispatch through the resumable run\n * path (`env.AI.run`, unified billing, `cf-aig-run-id`); the rest go through\n * the gateway path (`env.AI.gateway().run`, BYOK, no resume). `wireFormat`\n * selects the built-in `@ai-sdk/*` parser; absent ⇒ the provider is reachable\n * only via the bring-your-own-provider wrapper (it isn't chat/completions\n * shaped, e.g. audio/image providers).\n * - **Bring-your-own-provider** (`createGatewayProvider`): `hostPattern` +\n * `transformEndpoint` map a wrapped provider's request URL to the gateway\n * `provider` id + endpoint path.\n *\n * Slugs mirror the AI Gateway provider directory\n * (developers.cloudflare.com/ai-gateway/usage/providers/); endpoint transforms\n * mirror `ai-gateway-provider`'s provider table. `runCatalog` / `billing` flags\n * follow the documented unified-billing list (OpenAI, Anthropic, Google AI\n * Studio, Google Vertex, xAI/Grok, Groq) and are otherwise conservative — the\n * e2e suite confirms them live, since resume is undocumented upstream.\n */\n\n/** Response wire format the slug delegate can parse with a built-in `@ai-sdk/*` provider. */\nexport type WireFormat = \"openai\" | \"anthropic\" | \"google\";\n\n/** How a provider is billed + keyed when reached through the gateway. */\nexport type Billing = \"unified\" | \"byok\";\n\nexport interface GatewayProviderInfo {\n\t/**\n\t * Slug prefix the user types in `wai(\"<resolverKey>/<model>\")`. For\n\t * `runCatalog` providers this is also the run-catalog author (so\n\t * `env.AI.run(\"<resolverKey>/<model>\")` resolves).\n\t */\n\tresolverKey: string;\n\t/** Provider id for the gateway universal endpoint (`env.AI.gateway().run([{ provider }])`). */\n\tgatewayProviderId: string;\n\t/**\n\t * Built-in parser wire format. `openai` covers the whole OpenAI-compatible\n\t * long tail (deepseek, grok, groq, mistral, perplexity, …). Absent ⇒ reachable\n\t * only via the bring-your-own-provider wrapper (provider-native, non-chat, or a\n\t * gateway-path URL shape we don't reproduce reliably from the slug delegate).\n\t */\n\twireFormat?: WireFormat;\n\t/**\n\t * Wire format the unified-billing **run path** (`env.AI.run`) emits for this\n\t * provider — which is NOT always the provider's native format. Cloudflare's\n\t * unified catalog normalizes most providers to OpenAI chat-completions (so\n\t * `google` is parsed with the `openai` plugin on the run path), but passes\n\t * **Anthropic through natively** (`content[].text`, native tool shape), so\n\t * anthropic must be parsed with the `anthropic` plugin. Defaults to `\"openai\"`\n\t * for run-catalog providers when omitted. Only meaningful when `runCatalog`.\n\t */\n\trunWireFormat?: WireFormat;\n\t/**\n\t * Base URL the wire-format builder should target so the request URL it\n\t * generates host-strips (via {@link transformEndpoint}) to the provider's\n\t * gateway-native endpoint. Omit to use the `@ai-sdk` provider's default (the\n\t * provider's own host — correct for `openai`/`anthropic`/`google`). Required\n\t * for OpenAI-wire providers that share the `openai` plugin but live on a\n\t * different host (deepseek, grok, groq, mistral, perplexity, …).\n\t */\n\tbaseURL?: string;\n\t/** On the unified-billing resumable run catalog (`env.AI.run`, `cf-aig-run-id`). */\n\trunCatalog: boolean;\n\t/**\n\t * Whether the provider has a gateway path (`env.AI.gateway().run`). `false` ⇒\n\t * **run-path only**: the provider is on the unified run catalog but is not a\n\t * native gateway provider, so caching, server-side fallback, and\n\t * `transport: \"gateway\"` are unavailable and the delegate rejects them with a\n\t * clear error (rather than failing upstream). Defaults to `true`.\n\t */\n\tgatewayPath?: boolean;\n\t/** Billing model when reached through the gateway. */\n\tbilling: Billing;\n\t/** Header(s) carrying the upstream provider key (stripped on the gateway path unless BYOK-forwarded). */\n\tauthHeaders: string[];\n\t/** Host matcher for bring-your-own-provider URL detection. */\n\thostPattern?: RegExp;\n\t/** Strip the provider host, leaving the gateway endpoint path (+ query). */\n\ttransformEndpoint?: (url: string) => string;\n}\n\n/** Strip a leading `https://<host>/` prefix, leaving the endpoint path + query. */\nfunction hostStrip(pattern: RegExp): (url: string) => string {\n\treturn (url: string) => url.replace(pattern, \"\");\n}\n\nconst OPENAI_HOST = /^https:\\/\\/api\\.openai\\.com\\//;\nconst ANTHROPIC_HOST = /^https:\\/\\/api\\.anthropic\\.com\\//;\nconst GOOGLE_HOST = /^https:\\/\\/generativelanguage\\.googleapis\\.com\\//;\nconst VERTEX_HOST = /^https:\\/\\/(?:[a-z0-9-]+-)?aiplatform\\.googleapis\\.com\\//;\nconst XAI_HOST = /^https:\\/\\/api\\.x\\.ai\\//;\nconst GROQ_HOST = /^https:\\/\\/api\\.groq\\.com\\/openai\\/v1\\//;\nconst DEEPSEEK_HOST = /^https:\\/\\/api\\.deepseek\\.com\\//;\nconst MISTRAL_HOST = /^https:\\/\\/api\\.mistral\\.ai\\//;\nconst PERPLEXITY_HOST = /^https:\\/\\/api\\.perplexity\\.ai\\//;\nconst CEREBRAS_HOST = /^https:\\/\\/api\\.cerebras\\.ai\\//;\nconst OPENROUTER_HOST = /^https:\\/\\/openrouter\\.ai\\/api\\//;\nconst FIREWORKS_HOST = /^https:\\/\\/api\\.fireworks\\.ai\\/inference\\/v1\\//;\nconst COHERE_HOST = /^https:\\/\\/api\\.cohere\\.(?:com|ai)\\//;\nconst REPLICATE_HOST = /^https:\\/\\/api\\.replicate\\.com\\//;\nconst HUGGINGFACE_HOST = /^https:\\/\\/api-inference\\.huggingface\\.co\\/models\\//;\nconst CARTESIA_HOST = /^https:\\/\\/api\\.cartesia\\.ai\\//;\nconst FAL_HOST = /^https:\\/\\/fal\\.run\\//;\nconst IDEOGRAM_HOST = /^https:\\/\\/api\\.ideogram\\.ai\\//;\nconst DEEPGRAM_HOST = /^https:\\/\\/api\\.deepgram\\.com\\//;\nconst ELEVENLABS_HOST = /^https:\\/\\/api\\.elevenlabs\\.io\\//;\nconst GROK_KEY = \"grok\";\n\n// Bedrock's URL carries the AWS region, which the gateway endpoint preserves as\n// `bedrock-runtime/<region>/<rest>` (mirrors ai-gateway-provider).\nconst BEDROCK_HOST = /^https:\\/\\/bedrock-runtime\\.(?<region>[^.]+)\\.amazonaws\\.com\\//;\nfunction bedrockTransform(url: string): string {\n\tconst m = url.match(\n\t\t/^https:\\/\\/bedrock-runtime\\.(?<region>[^.]+)\\.amazonaws\\.com\\/(?<rest>.*)$/,\n\t);\n\tif (!m?.groups) return url;\n\tconst { region, rest } = m.groups;\n\tif (!region || rest === undefined) return url;\n\treturn `bedrock-runtime/${region}/${rest}`;\n}\n\n// Azure's URL carries the resource + deployment, so it needs a bespoke transform\n// (mirrors ai-gateway-provider). Only used for bring-your-own-provider detection.\nconst AZURE_HOST =\n\t/^https:\\/\\/(?<resource>[^.]+)\\.openai\\.azure\\.com\\/openai\\/deployments\\/(?<deployment>[^/]+)\\/(?<rest>.*)$/;\nfunction azureTransform(url: string): string {\n\tconst m = url.match(AZURE_HOST);\n\tif (!m?.groups) return url;\n\tconst { resource, deployment, rest } = m.groups;\n\tif (!resource || !deployment || !rest) return url;\n\treturn `${resource}/${deployment}/${rest}`;\n}\n\n/**\n * The provider table. Order matters only for `detectProviderByUrl` (first match\n * wins); slugs are looked up by `resolverKey`.\n */\nexport const GATEWAY_PROVIDERS: GatewayProviderInfo[] = [\n\t// ---- Unified-billing run-catalog providers (resumable run path) ----\n\t{\n\t\tresolverKey: \"openai\",\n\t\tgatewayProviderId: \"openai\",\n\t\twireFormat: \"openai\",\n\t\trunCatalog: true,\n\t\tbilling: \"unified\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: OPENAI_HOST,\n\t\ttransformEndpoint: hostStrip(OPENAI_HOST),\n\t},\n\t{\n\t\tresolverKey: \"anthropic\",\n\t\tgatewayProviderId: \"anthropic\",\n\t\twireFormat: \"anthropic\",\n\t\t// Unified billing passes Anthropic through natively (unlike google, which it\n\t\t// normalizes to openai-wire), so the run path also speaks Anthropic Messages.\n\t\trunWireFormat: \"anthropic\",\n\t\trunCatalog: true,\n\t\tbilling: \"unified\",\n\t\tauthHeaders: [\"x-api-key\", \"authorization\"],\n\t\thostPattern: ANTHROPIC_HOST,\n\t\ttransformEndpoint: hostStrip(ANTHROPIC_HOST),\n\t},\n\t{\n\t\tresolverKey: \"google\",\n\t\tgatewayProviderId: \"google-ai-studio\",\n\t\t// Gateway path hits Gemini's native endpoint (google-wire); the unified run\n\t\t// path, however, returns openai-wire — so runWireFormat defaults to \"openai\".\n\t\twireFormat: \"google\",\n\t\trunCatalog: true,\n\t\tbilling: \"unified\",\n\t\tauthHeaders: [\"x-goog-api-key\", \"authorization\"],\n\t\thostPattern: GOOGLE_HOST,\n\t\ttransformEndpoint: hostStrip(GOOGLE_HOST),\n\t},\n\t{\n\t\tresolverKey: \"xai\",\n\t\tgatewayProviderId: GROK_KEY,\n\t\twireFormat: \"openai\",\n\t\t// Targeted so a forced gateway-path request host-strips correctly (the run\n\t\t// path, the default for xai, ignores this).\n\t\tbaseURL: \"https://api.x.ai/v1\",\n\t\trunCatalog: true,\n\t\tbilling: \"unified\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: XAI_HOST,\n\t\ttransformEndpoint: hostStrip(XAI_HOST),\n\t},\n\t{\n\t\tresolverKey: \"groq\",\n\t\tgatewayProviderId: \"groq\",\n\t\twireFormat: \"openai\",\n\t\t// Groq's gateway-native endpoint strips `/openai/v1/`, so the builder must\n\t\t// target that base or a forced gateway request doubles the prefix.\n\t\tbaseURL: \"https://api.groq.com/openai/v1\",\n\t\trunCatalog: true,\n\t\tbilling: \"unified\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: GROQ_HOST,\n\t\ttransformEndpoint: hostStrip(GROQ_HOST),\n\t},\n\t// Unified-catalog chat providers that are NOT in the native gateway directory:\n\t// they exist only on the resumable run path (env.AI.run, unified billing), so\n\t// there's no BYOK gateway path. Both return OpenAI chat-completions wire (so the\n\t// `openai` plugin parses them) and emit `cf-aig-run-id` on streams (resumable),\n\t// verified live against the default gateway. Forcing transport:\"gateway\" for\n\t// these errors upstream (no native provider) — that's expected.\n\t{\n\t\t// Alibaba Qwen, served via DashScope's OpenAI-compatible endpoint.\n\t\tresolverKey: \"alibaba\",\n\t\tgatewayProviderId: \"alibaba\",\n\t\twireFormat: \"openai\",\n\t\trunCatalog: true,\n\t\tgatewayPath: false,\n\t\tbilling: \"unified\",\n\t\tauthHeaders: [\"authorization\"],\n\t},\n\t{\n\t\t// MiniMax (M-series). OpenAI-wire with extra fields (reasoning_content,\n\t\t// audio_content) the openai parser ignores; core choices[].delta.content is standard.\n\t\tresolverKey: \"minimax\",\n\t\tgatewayProviderId: \"minimax\",\n\t\twireFormat: \"openai\",\n\t\trunCatalog: true,\n\t\tgatewayPath: false,\n\t\tbilling: \"unified\",\n\t\tauthHeaders: [\"authorization\"],\n\t},\n\t{\n\t\tresolverKey: \"google-vertex\",\n\t\tgatewayProviderId: \"google-vertex-ai\",\n\t\t// Vertex's URL carries project/location/publisher segments that the\n\t\t// `@ai-sdk/google` default (AI Studio) does not produce, so the slug\n\t\t// delegate can't shape it reliably — reach Vertex via createGatewayProvider.\n\t\trunCatalog: false,\n\t\tbilling: \"unified\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: VERTEX_HOST,\n\t\ttransformEndpoint: hostStrip(VERTEX_HOST),\n\t},\n\n\t// ---- OpenAI-compatible long tail (gateway path, BYOK) ----\n\t{\n\t\tresolverKey: \"deepseek\",\n\t\tgatewayProviderId: \"deepseek\",\n\t\twireFormat: \"openai\",\n\t\tbaseURL: \"https://api.deepseek.com\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: DEEPSEEK_HOST,\n\t\ttransformEndpoint: hostStrip(DEEPSEEK_HOST),\n\t},\n\t{\n\t\tresolverKey: \"mistral\",\n\t\tgatewayProviderId: \"mistral\",\n\t\twireFormat: \"openai\",\n\t\tbaseURL: \"https://api.mistral.ai/v1\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: MISTRAL_HOST,\n\t\ttransformEndpoint: hostStrip(MISTRAL_HOST),\n\t},\n\t{\n\t\tresolverKey: \"perplexity\",\n\t\tgatewayProviderId: \"perplexity-ai\",\n\t\twireFormat: \"openai\",\n\t\tbaseURL: \"https://api.perplexity.ai\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: PERPLEXITY_HOST,\n\t\ttransformEndpoint: hostStrip(PERPLEXITY_HOST),\n\t},\n\t{\n\t\tresolverKey: \"cerebras\",\n\t\tgatewayProviderId: \"cerebras\",\n\t\twireFormat: \"openai\",\n\t\tbaseURL: \"https://api.cerebras.ai/v1\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: CEREBRAS_HOST,\n\t\ttransformEndpoint: hostStrip(CEREBRAS_HOST),\n\t},\n\t{\n\t\tresolverKey: \"openrouter\",\n\t\tgatewayProviderId: \"openrouter\",\n\t\twireFormat: \"openai\",\n\t\tbaseURL: \"https://openrouter.ai/api/v1\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: OPENROUTER_HOST,\n\t\ttransformEndpoint: hostStrip(OPENROUTER_HOST),\n\t},\n\t{\n\t\t// Fireworks is OpenAI-compatible. Present on ai-gateway-provider (#409) but\n\t\t// not the current provider directory — treat as BYOK long-tail.\n\t\tresolverKey: \"fireworks\",\n\t\tgatewayProviderId: \"fireworks\",\n\t\twireFormat: \"openai\",\n\t\tbaseURL: \"https://api.fireworks.ai/inference/v1\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: FIREWORKS_HOST,\n\t\ttransformEndpoint: hostStrip(FIREWORKS_HOST),\n\t},\n\t// Providers whose gateway-path URL shape isn't reliably reproducible from the\n\t// shared openai builder (cohere's /compat surface, baseten's per-deployment\n\t// hosts, parallel, azure's resource/deployment path) are bring-your-own-provider\n\t// only — set your own @ai-sdk provider baseURL and route via createGatewayProvider.\n\t{\n\t\tresolverKey: \"cohere\",\n\t\tgatewayProviderId: \"cohere\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: COHERE_HOST,\n\t\ttransformEndpoint: hostStrip(COHERE_HOST),\n\t},\n\t{\n\t\t// Baseten serves per-deployment hosts, so there's no single detectable URL\n\t\t// shape — reach it with an explicit `provider` via createGatewayProvider.\n\t\tresolverKey: \"baseten\",\n\t\tgatewayProviderId: \"baseten\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t},\n\t{\n\t\tresolverKey: \"parallel\",\n\t\tgatewayProviderId: \"parallel\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\", \"x-api-key\"],\n\t},\n\t{\n\t\tresolverKey: \"azure-openai\",\n\t\tgatewayProviderId: \"azure-openai\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"api-key\", \"authorization\"],\n\t\thostPattern: AZURE_HOST,\n\t\ttransformEndpoint: azureTransform,\n\t},\n\n\t// ---- Provider-native only: reachable via the bring-your-own-provider wrapper ----\n\t// (no `wireFormat` ⇒ not auto-wired by the slug delegate)\n\t{\n\t\tresolverKey: \"aws-bedrock\",\n\t\tgatewayProviderId: \"aws-bedrock\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: BEDROCK_HOST,\n\t\ttransformEndpoint: bedrockTransform,\n\t},\n\t{\n\t\tresolverKey: \"huggingface\",\n\t\tgatewayProviderId: \"huggingface\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: HUGGINGFACE_HOST,\n\t\ttransformEndpoint: hostStrip(HUGGINGFACE_HOST),\n\t},\n\t{\n\t\tresolverKey: \"replicate\",\n\t\tgatewayProviderId: \"replicate\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: REPLICATE_HOST,\n\t\ttransformEndpoint: hostStrip(REPLICATE_HOST),\n\t},\n\t{\n\t\tresolverKey: \"fal\",\n\t\tgatewayProviderId: \"fal\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: FAL_HOST,\n\t\ttransformEndpoint: hostStrip(FAL_HOST),\n\t},\n\t{\n\t\tresolverKey: \"ideogram\",\n\t\tgatewayProviderId: \"ideogram\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\"],\n\t\thostPattern: IDEOGRAM_HOST,\n\t\ttransformEndpoint: hostStrip(IDEOGRAM_HOST),\n\t},\n\t{\n\t\tresolverKey: \"cartesia\",\n\t\tgatewayProviderId: \"cartesia\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\", \"x-api-key\"],\n\t\thostPattern: CARTESIA_HOST,\n\t\ttransformEndpoint: hostStrip(CARTESIA_HOST),\n\t},\n\t{\n\t\tresolverKey: \"deepgram\",\n\t\tgatewayProviderId: \"deepgram\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"authorization\", \"token\"],\n\t\thostPattern: DEEPGRAM_HOST,\n\t\ttransformEndpoint: hostStrip(DEEPGRAM_HOST),\n\t},\n\t{\n\t\tresolverKey: \"elevenlabs\",\n\t\tgatewayProviderId: \"elevenlabs\",\n\t\trunCatalog: false,\n\t\tbilling: \"byok\",\n\t\tauthHeaders: [\"xi-api-key\", \"authorization\"],\n\t\thostPattern: ELEVENLABS_HOST,\n\t\ttransformEndpoint: hostStrip(ELEVENLABS_HOST),\n\t},\n];\n\n/** Aliases that map a friendly slug prefix to a canonical `resolverKey`. */\nconst RESOLVER_ALIASES: Record<string, string> = {\n\t// xAI's run-catalog author is `xai`, but `grok` is the common name.\n\tgrok: \"xai\",\n\t\"google-ai-studio\": \"google\",\n\t\"google-vertex-ai\": \"google-vertex\",\n\tbedrock: \"aws-bedrock\",\n\tazure: \"azure-openai\",\n};\n\nconst BY_RESOLVER_KEY = new Map<string, GatewayProviderInfo>(\n\tGATEWAY_PROVIDERS.map((p) => [p.resolverKey, p]),\n);\n\n/** Look up a provider by the slug prefix the user typed (honoring aliases). */\nexport function findProviderBySlug(resolverKey: string): GatewayProviderInfo | undefined {\n\tconst canonical = RESOLVER_ALIASES[resolverKey] ?? resolverKey;\n\treturn BY_RESOLVER_KEY.get(canonical);\n}\n\n/** Detect the gateway provider from a wrapped provider's request URL (BYOG). */\nexport function detectProviderByUrl(url: string): GatewayProviderInfo | undefined {\n\treturn GATEWAY_PROVIDERS.find((p) => p.hostPattern?.test(url));\n}\n\n/** All slug keys with a built-in parser (auto-wireable by the slug delegate). */\nexport function wireableProviders(): GatewayProviderInfo[] {\n\treturn GATEWAY_PROVIDERS.filter((p) => p.wireFormat !== undefined);\n}\n","import { WorkersAIGatewayError } from \"./errors\";\nimport { detectProviderByUrl, type GatewayProviderInfo } from \"./gateway-providers\";\n\n/**\n * Bring-your-own-provider: route any `@ai-sdk/*` provider's HTTP traffic through\n * Cloudflare AI Gateway, without the catalog slug delegate. The provider keeps\n * its own request/response shaping; this only swaps the transport.\n *\n * Use it for providers the slug delegate cannot auto-wire (bedrock, replicate,\n * audio/image providers, anything provider-native), or when you want full control\n * of the underlying `@ai-sdk` provider. This is the gateway path only — BYOK and\n * caching are available, resume (`cf-aig-run-id`) is not.\n *\n * @example\n * ```ts\n * import { createOpenAI } from \"@ai-sdk/openai\";\n * import { createGatewayFetch } from \"workers-ai-provider/gateway\";\n *\n * const openai = createOpenAI({\n * apiKey: env.OPENAI_API_KEY, // forwarded when byok: true\n * fetch: createGatewayFetch({ binding: env.AI, gateway: \"my-gw\", byok: true }),\n * });\n * const model = openai(\"gpt-5\");\n * ```\n */\nexport interface GatewayFetchConfig {\n\t/** A Cloudflare AI binding (e.g. `env.AI`). */\n\tbinding: Ai;\n\t/** Gateway id (or options). */\n\tgateway: GatewayOptions | string;\n\t/**\n\t * Force a gateway provider id instead of detecting it from the request URL.\n\t * Required when the wrapped provider's host is not in the registry.\n\t */\n\tprovider?: string;\n\t/**\n\t * Forward the upstream provider key (Authorization / x-api-key / …) instead of\n\t * stripping it. Required for BYOK providers. Defaults to `false` (strip, so\n\t * unified billing / the gateway's stored key applies).\n\t */\n\tbyok?: boolean;\n\t/** Extra headers added to every gateway entry. */\n\textraHeaders?: Record<string, string>;\n\t/** Gateway-path response caching (seconds). */\n\tcacheTtl?: number;\n\t/** Bypass gateway cache. */\n\tskipCache?: boolean;\n}\n\nconst STRIP_HEADERS_BASE = new Set([\"content-length\", \"host\"]);\n\ninterface AiGatewayRunner {\n\trun(body: unknown, options?: Record<string, unknown>): Promise<Response>;\n}\n\nfunction asText(body: BodyInit | null | undefined): string {\n\tif (typeof body === \"string\") return body;\n\tif (body instanceof Uint8Array) return new TextDecoder().decode(body);\n\tif (body instanceof ArrayBuffer) return new TextDecoder().decode(body);\n\treturn \"{}\";\n}\n\nfunction headersToObject(h: HeadersInit | undefined): Record<string, string> {\n\tconst out: Record<string, string> = {};\n\tif (!h) return out;\n\tif (h instanceof Headers) {\n\t\tfor (const [k, v] of h) out[k] = v;\n\t} else if (Array.isArray(h)) {\n\t\tfor (const [k, v] of h) out[k] = v;\n\t} else {\n\t\tObject.assign(out, h);\n\t}\n\treturn out;\n}\n\n/**\n * A `fetch` that dispatches the wrapped provider's request through AI Gateway.\n * Detects the gateway provider id from the request URL (or uses `config.provider`),\n * strips the provider host to the endpoint path, and forwards the body verbatim.\n */\nexport function createGatewayFetch(config: GatewayFetchConfig): typeof globalThis.fetch {\n\tif (!config?.binding) {\n\t\tthrow new WorkersAIGatewayError(\n\t\t\t\"gateway-error\",\n\t\t\t\"createGatewayFetch requires a `binding` (e.g. { binding: env.AI }).\",\n\t\t);\n\t}\n\tconst gatewayId = typeof config.gateway === \"string\" ? config.gateway : config.gateway?.id;\n\tif (!gatewayId) {\n\t\tthrow new WorkersAIGatewayError(\n\t\t\t\"gateway-error\",\n\t\t\t'createGatewayFetch requires a `gateway` id (e.g. gateway: \"my-gateway\").',\n\t\t);\n\t}\n\n\treturn (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n\t\tconst rawUrl = typeof input === \"string\" ? input : input.toString();\n\n\t\tlet info: GatewayProviderInfo | undefined;\n\t\tif (config.provider) {\n\t\t\tinfo = undefined; // explicit provider id; no registry lookup needed\n\t\t} else {\n\t\t\tinfo = detectProviderByUrl(rawUrl);\n\t\t\tif (!info) {\n\t\t\t\tthrow new WorkersAIGatewayError(\n\t\t\t\t\t\"gateway-error\",\n\t\t\t\t\t`Could not detect a gateway provider from URL \"${rawUrl}\". ` +\n\t\t\t\t\t\t'Pass `provider: \"<gateway-provider-id>\"` explicitly.',\n\t\t\t\t\t{ recoverable: false },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst providerId = config.provider ?? (info as GatewayProviderInfo).gatewayProviderId;\n\t\tconst endpoint = info?.transformEndpoint\n\t\t\t? info.transformEndpoint(rawUrl)\n\t\t\t: rawUrl.replace(/^https?:\\/\\/[^/]+\\//, \"\");\n\t\tconst body = JSON.parse(asText(init?.body)) as Record<string, unknown>;\n\n\t\tconst strip = new Set(STRIP_HEADERS_BASE);\n\t\tif (!config.byok && info) for (const h of info.authHeaders) strip.add(h.toLowerCase());\n\n\t\tconst headers: Record<string, string> = {};\n\t\tfor (const [k, v] of Object.entries(headersToObject(init?.headers))) {\n\t\t\tif (!strip.has(k.toLowerCase())) headers[k] = v;\n\t\t}\n\t\tif (config.extraHeaders) Object.assign(headers, config.extraHeaders);\n\t\tif (config.cacheTtl !== undefined) headers[\"cf-aig-cache-ttl\"] = String(config.cacheTtl);\n\t\tif (config.skipCache) headers[\"cf-aig-skip-cache\"] = \"true\";\n\n\t\tconst entry = { provider: providerId, endpoint, headers, query: body };\n\t\tconst gw = (config.binding as unknown as { gateway(id: string): AiGatewayRunner }).gateway(\n\t\t\tgatewayId,\n\t\t);\n\t\tconst runOptions: Record<string, unknown> = {};\n\t\tif (init?.signal) runOptions.signal = init.signal;\n\t\treturn gw.run([entry], runOptions);\n\t}) as typeof globalThis.fetch;\n}\n\n/**\n * Wrap an `@ai-sdk/*` provider factory so its traffic flows through AI Gateway.\n * A thin convenience over {@link createGatewayFetch} — it injects the gateway\n * `fetch` (and a placeholder `apiKey` unless you supply one for BYOK).\n *\n * @example\n * ```ts\n * import { createOpenAI } from \"@ai-sdk/openai\";\n * import { createGatewayProvider } from \"workers-ai-provider/gateway\";\n *\n * const openai = createGatewayProvider(createOpenAI, {\n * binding: env.AI,\n * gateway: \"my-gw\",\n * });\n * const model = openai(\"gpt-5\");\n * ```\n */\nexport function createGatewayProvider<T>(\n\tfactory: (opts: { apiKey?: string; baseURL?: string; fetch: typeof globalThis.fetch }) => T,\n\tconfig: GatewayFetchConfig & { apiKey?: string; baseURL?: string },\n): T {\n\treturn factory({\n\t\tapiKey: config.apiKey ?? \"unused\",\n\t\t...(config.baseURL ? { baseURL: config.baseURL } : {}),\n\t\tfetch: createGatewayFetch(config),\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,eAAe,QAG7B;CACD,IAAI,WAAW,OAAO,WAAW,KAAK,OAAO;EAAE,MAAM;EAAQ,aAAa;CAAM;CAChF,IAAI,WAAW,KAAK,OAAO;EAAE,MAAM;EAAc,aAAa;CAAK;CACnE,IAAI,WAAW,KAAK,OAAO;EAAE,MAAM;EAAa,aAAa;CAAM;CACnE,IAAI,WAAW,OAAO,WAAW,KAAK,OAAO;EAAE,MAAM;EAAe,aAAa;CAAM;CACvF,IAAI,UAAU,KAAK,OAAO;EAAE,MAAM;EAAkB,aAAa;CAAK;CACtE,OAAO;EAAE,MAAM;EAAW,aAAa;CAAM;AAC9C;;AAGA,SAAgB,oBAAoB,KAAkC;CACrE,IAAI,OAAO,QAAQ,UAAU;EAC5B,MAAM,UAAU,IAAI,KAAK;EACzB,IAAI,CAAC,SAAS,OAAO,KAAA;EACrB,IAAI;GACH,OAAO,oBAAoB,KAAK,MAAM,OAAO,CAAC;EAC/C,QAAQ;GACP,OAAO,QAAQ,MAAM,GAAG,GAAG;EAC5B;CACD;CACA,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO,KAAA;CAC5C,MAAM,MAAM;CAEZ,IAAI,MAAM,QAAQ,IAAI,MAAM,KAAK,IAAI,OAAO,SAAS,GAAG;EACvD,MAAM,QAAQ,IAAI,OAAO;EACzB,IAAI,OAAO,OAAO,YAAY,UAAU,OAAO,MAAM;CACtD;CAEA,IAAI,IAAI,SAAS,OAAO,IAAI,UAAU,UAAU;EAC/C,MAAM,MAAM,IAAI;EAChB,IAAI,OAAO,IAAI,YAAY,UAAU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