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

us-egress.ts

37 lines1.6 KB

1import type { ProviderEnvironment } from './types.ts'
2​
3/** What `fetchJson` calls; the global `fetch` is one. */
4export type Fetcher = (url: string, init?: RequestInit) => Promise<Response>
5​
6/**
7 * A fetch that leaves Cloudflare from eastern North America (issue #356).
8 *
9 * Anthropic and Gemini refuse callers in regions they do not serve
10 * (`403 forbidden` / `400 User location is not supported`). Cron
11 * invocations run wherever Cloudflare has spare capacity, and `placement`
12 * only moves fetch handlers, so the models poll has no fixed location.
13 * A Durable Object is created near its `locationHint` on the first `get()`
14 * and does not move afterwards, so routing the keyed listing calls through
15 * one fixes where they egress. (The `us` jurisdiction would be a hard
16 * guarantee, but workerd does not implement it, so `bun run dev` would
17 * throw.)
18 *
19 * Outside the Workers runtime (bun scripts, node unit tests) there is no
20 * binding and the global fetch runs from the caller's own machine. Inside
21 * it, a missing binding is a config error and throws.
22 */
23export function usEgressFetch(env: ProviderEnvironment): Fetcher {
24 const ns = env.US_EGRESS
25 if (!ns) {
26 if (navigator.userAgent === 'Cloudflare-Workers')
27 throw new Error('US_EGRESS binding missing (wrangler.jsonc, issue #356)')
28 return fetch
29 }
30 const stub = ns.get(ns.idFromName('provider-egress'), {
31 locationHint: 'enam',
32 })
33 // workers-types' Request/Response and the DOM ones this file is typed
34 // with are the same runtime classes.
35 return async (url, init) =>
36 (await stub.fetch(url, init as never)) as unknown as Response