import { AbortError, EngineError, EngineErrorCode, parseObjectNumberRanges, type ObjectNumberRange, type PageRef, type PageRenderOptions, type PageRenderRaster, type SerializedEngineError, type TokenSource, } from '@embedpdf/engine-core/runtime'; import { API_VERSION, applyCdnAccess, EngineErrorSchema, type CdnAccessInfoForApply, } from '@embedpdf/engine-core/wire'; import { askedToken, fixedToken, keptToken, type TokenKeeper } from './tokenKeeper'; /** CloudPDF SaaS: where an engine connects when it names no server of its own. */ export const CLOUDPDF_SAAS_URL = 'https://engine.cloudpdf.com'; export interface HttpClientOptions { /** Where your CloudPDF runs: your own `@cloudpdf/server`, or CloudPDF SaaS * ({@link CLOUDPDF_SAAS_URL}) when left out. */ baseUrl?: string; /** * Optional bearer token. Either a string or a function that gives one: the client calls it * when it first needs a token, keeps that token, and calls it again in the background a minute * before the expiry the token carries, so a short-lived token never runs out, no request waits * for a renewal, and the function runs once per token, not once per request. A server that * refuses the kept token (401) gets the request again with the next one. When absent, requests go out without an `Authorization` header: * useful for the public-share scenario where the doc-scoped token is provided per-`open` and * the engine itself has no engine-level credentials. */ token?: TokenSource; /** * `false` asks a `token` function every time instead of keeping its token: for a function that * keeps and renews its own, as a grant session does. Default `true`. */ keepToken?: boolean; /** * The open document's session id, sent as `X-Engine-Session-Id` where the * server reads it: on writes, `/access`, the event stream and the bulk * reservation (see {@link RequestOptions}). The server keeps the editing * session's object numbers under it, and stores it on a write's audit * row, so the document's own stream can drop its echoes. Each open * document has its own (see {@link HttpClient.forDocument}); the engine's * client has none. */ sessionId?: string; /** Replace the global fetch (e.g. in Node tests with undici). */ fetch?: typeof globalThis.fetch; /** * Document affinity key: `X-CloudPDF-Doc` is sent by default on * origin-bound doc requests so consistent-hash load balancers can pin * a document's traffic to one warm replica. Routing hints are * unconditional client behavior — whether they are used is the * operator's choice at the load balancer, never the app's. Derived * from the request path (`/v1/docs/:docId/…` — the same extraction * the Helm chart's uri-mode fallback uses); never sent on * CDN-rewritten requests. * * `false` is an escape hatch, not a feature toggle: use it only * against a stale server whose CORS allowlist predates the header * (browser preflights would fail) or behind a proxy that rejects * unknown request headers. */ docAffinityHeader?: boolean; /** Observability: fired once per transport-level retry (engine busy / * restarting). Lets apps count sheds without wrapping every call. */ onRetry?: (info: { path: string; code: string; attempt: number; waitMs: number }) => void; /** * Read through a CDN when the server offers one. Default `true`. `false` * reads everything from the server itself, CDN credentials or not: for * code running next to it (a server module, a backend in the same * network), where the CDN only adds a hop. */ cdn?: boolean; /** * Where raw page pixels come from, when this client runs inside the server * it talks to (a server module's): `page(ref).render.raw()` draws through * it. Absent everywhere else: over the network the cloud API serves * images, not raw pixels. */ renderRaw?: RawPageSource; } /** Draws one page to raw pixels, next to the engine. */ export type RawPageSource = ( page: PageRef, options: PageRenderOptions, signal: AbortSignal, ) => Promise; /** * Per-document binding for CDN URL rewriting. `CloudDocumentHandle` * calls `setCdnAccess` after `/v1/access` succeeds; the HttpClient * then runs every outgoing request through `applyCdnAccess` so * granted resources are routed to the CDN with the matching signed * query params (or cookies/auth header for the cookie/header * adapter modes). * * Set to `null` when the session is reset or when `/access` was * never called (public-share with no CDN configured). */ export interface CdnBinding { readonly cdn: CdnAccessInfoForApply | null; readonly docId: string; readonly layerName: string; } /** * What a write sends beside its request: its `opId` as `Idempotency-Key`, * so a retry is answered with what the first try committed, and how many * object numbers to top the editing session up by. */ export interface WriteRequest { /** Absent for a request of changes: its body names each change by its own `opId`. */ readonly opId?: string; /** `EmbedPDF-Reserve-Object-Numbers`, when more than 0. */ readonly reserveObjectNumbers?: number; /** Called with the numbers the response hands out (`EmbedPDF-Object-Numbers`). */ readonly onObjectNumbers?: (ranges: ObjectNumberRange[]) => void; } /** How one request is sent, beyond its path and body. */ export interface RequestOptions { /** * A write: sent as the editing session with its `Idempotency-Key`, and * sent again with the same key after a network failure. */ readonly write?: WriteRequest; /** Sent as the editing session though not a write: `/access`, the bulk reservation. */ readonly session?: boolean; /** Sent to the server itself, never to a CDN in front of it, whatever the path. */ readonly origin?: boolean; } /** A raw-bytes response plus its headers. */ export interface HttpFileResponse { bytes: Uint8Array; headers: Headers; } export class HttpClient { private readonly base: string; private tokens: TokenKeeper | null; private readonly fetchFn: typeof globalThis.fetch; private readonly docAffinityHeader: boolean; private readonly onRetry: HttpClientOptions['onRetry']; private static readonly MAX_RETRIES = 2; private static readonly RETRY_AFTER_CAP_MS = 5_000; private static readonly RETRY_AFTER_DEFAULT_MS = 1_000; /** A write whose request failed on the network is sent again after these waits. */ private static readonly NETWORK_RETRY_MS = [250, 1_000, 3_000]; /** The open document's session id; `null` on the engine's own client. */ readonly sessionId: string | null; private cdnBinding: CdnBinding | null = null; private readonly engineChangedListeners = new Set<() => void>(); private serverVersionSeen: string | null = null; constructor(private readonly options: HttpClientOptions) { this.base = (options.baseUrl ?? CLOUDPDF_SAAS_URL).replace(/\/$/, ''); this.tokens = tokenKeeperOf(options.token, options.keepToken ?? true); this.sessionId = options.sessionId ?? null; this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis); this.docAffinityHeader = options.docAffinityHeader ?? true; this.onRetry = options.onRetry; } /** * Call `listener` when the server answers a cached read with another * engine value than its URL named (`EmbedPDF-Engine`). Returns the * unsubscribe. */ onEngineChanged(listener: () => void): () => void { this.engineChangedListeners.add(listener); return () => this.engineChangedListeners.delete(listener); } /** Normalized server base URL (no trailing slash). */ get baseUrl(): string { return this.base; } /** * The version the server says it is (`EmbedPDF-Server-Version`), from its * last live answer; `null` before one. Only an answer nothing may store is * believed: a cached one names the server that produced it once, which can * be another version. `/head`, read as a document opens, is a live answer. */ get serverVersion(): string | null { return this.serverVersionSeen; } /** * The fetch implementation this client sends requests through (injected * or global). Exposed so sibling transports spawned per-open — the * grant-session exchange, most of all — ride the same fetch the engine * was configured with (test doubles, SSR `Origin`-attaching wrappers). */ get fetchImpl(): typeof globalThis.fetch { return this.fetchFn; } /** Whether reads may go through a CDN the server offers (`cdn` option). */ get usesCdn(): boolean { return this.options.cdn !== false; } /** Where this client's raw page pixels come from; absent outside the server. */ get renderRaw(): RawPageSource | undefined { return this.options.renderRaw; } /** * A client for one open document: this client's settings, the document's * own editing session, its own CDN binding, and `token` as its bearer * when the open names one (else this client's, and the token this client * keeps). Two open documents never share object numbers, event echoes or * a CDN binding, even two opens of the same document on one engine. */ forDocument({ sessionId, token, keepToken, }: { sessionId: string; token?: TokenSource; keepToken?: boolean; }): HttpClient { const client = new HttpClient({ ...this.options, ...(token !== undefined ? { token } : {}), ...(keepToken !== undefined ? { keepToken } : {}), sessionId, }); if (token === undefined) client.tokens = this.tokens; return client; } /** * Raw streaming GET (the SSE channel). Same auth/session headers and * error mapping as every other request; the caller owns the body stream. */ async stream( path: string, headers: Record, signal: AbortSignal, ): Promise { return this.request( path, { method: 'GET', headers: new Headers({ Accept: 'text/event-stream', ...headers }), signal }, { session: true }, ); } /** * Install (or clear) the per-session CDN binding. Pass `null` to * route everything to origin again — useful on session close or * when an adapter swap happens mid-session (rare). * * The HttpClient stays dumb about when to do this; the cloud * document handle pushes the binding in after /access succeeds. * * Side effect: in the browser, signedCookies are written to * `document.cookie` once per setCdnAccess call so the CDN edge * receives them on subsequent fetches. Outside the browser signed * cookies are ignored: this client keeps no cookie jar. */ setCdnAccess(binding: CdnBinding | null): void { this.cdnBinding = binding; if (binding?.cdn?.signedCookies && typeof globalThis.document !== 'undefined') { for (const cookie of binding.cdn.signedCookies) { const parts = [`${cookie.name}=${cookie.value}`]; parts.push(`Path=${cookie.path ?? '/'}`); if (cookie.domain) parts.push(`Domain=${cookie.domain}`); if (cookie.expires) parts.push(`Expires=${new Date(cookie.expires * 1000).toUTCString()}`); parts.push('SameSite=None', 'Secure'); globalThis.document.cookie = parts.join('; '); } } } /** Current CDN binding (or null). Exposed for diagnostics/tests. */ get currentCdnBinding(): CdnBinding | null { return this.cdnBinding; } absoluteUrl(path: string): string { return `${this.baseUrl}${path}`; } /** * One of the server's routes as it is, for a caller that reads the response * itself, such as a server module's routes: with the token (fresh for each * request), the document's affinity header and the busy retries, always to * the server and never to a CDN, and answering whatever the status. */ async fetchRoute(path: string, init: RequestInit = {}): Promise { const headers = new Headers(init.headers ?? {}); if (!headers.has('Accept')) headers.set('Accept', '*/*'); return this.request(path, { ...init, headers }, { origin: true }); } async getBlob(path: string, signal: AbortSignal): Promise { const res = await this.request(path, { method: 'GET', signal }); if (!res.ok) await this.throwFromBody(res); return await res.blob(); } async getBytes(path: string, signal: AbortSignal): Promise { const res = await this.request(path, { method: 'GET', headers: new Headers({ Accept: 'application/pdf' }), signal, }); if (!res.ok) await this.throwFromBody(res); return new Uint8Array(await res.arrayBuffer()); } /** * Resolve the current bearer token: the kept one, or the token function's * next. Used by the cloud engine to read doc-scoped claims **without** * verifying — the server is the verifier of record. Throws when no token * is configured. */ async currentToken(): Promise { if (!this.tokens) { throw new EngineError(EngineErrorCode.InvalidArg, 'http client has no token configured'); } return await this.tokens.token(); } async getJson(path: string, parser: (raw: unknown) => T, signal: AbortSignal): Promise { const res = await this.request(path, { method: 'GET', signal }); return await this.parseJsonResponse(res, parser); } /** * GET a versioned URL with transparent stale-version recovery. If * the server returns 404 (the well-known "this version is gone" * signal for content-addressed reads), call `onStaleVersion` (which * the caller wires to a manifest refresh), then re-resolve `buildPath` * and retry the GET exactly once. Any non-404 error propagates. * * The retry budget is hard-capped at 1: after a refresh, if the * server's idea of the current version is still ahead of the * client's view, the second request fails normally — this matches * the CDN cache invariant ("a versioned URL's bytes are immutable * for its lifetime"). */ async getJsonWithRefresh( buildPath: (signal: AbortSignal) => Promise, parser: (raw: unknown) => T, onStaleVersion: (signal: AbortSignal) => Promise, signal: AbortSignal, ): Promise { const initialPath = await buildPath(signal); try { return await this.getJson(initialPath, parser, signal); } catch (err) { if (!EngineError.is(err, EngineErrorCode.NotFound)) throw err; await onStaleVersion(signal); const retryPath = await buildPath(signal); return await this.getJson(retryPath, parser, signal); } } /** * GET a `multipart/form-data` body and parse it with the platform's * `Response.formData()` (works in browsers and undici). Text parts come * back as strings, parts with a filename as `Blob`s. */ async getFormData(path: string, signal: AbortSignal): Promise { const res = await this.request(path, { method: 'GET', headers: new Headers({ Accept: 'multipart/form-data' }), signal, }); if (!res.ok) await this.throwFromBody(res); return await res.formData(); } /** * `getFormData` with the same single-retry stale-version recovery as * {@link getJsonWithRefresh}: a 404 on a versioned URL triggers * `onStaleVersion` (a manifest refresh) and one re-resolve + retry. */ async getFormDataWithRefresh( buildPath: (signal: AbortSignal) => Promise, onStaleVersion: (signal: AbortSignal) => Promise, signal: AbortSignal, ): Promise { const initialPath = await buildPath(signal); try { return await this.getFormData(initialPath, signal); } catch (err) { if (!EngineError.is(err, EngineErrorCode.NotFound)) throw err; await onStaleVersion(signal); const retryPath = await buildPath(signal); return await this.getFormData(retryPath, signal); } } /** * `getBlob` with the same single-retry stale-version recovery as * {@link getJsonWithRefresh}: a 404 on a versioned URL triggers * `onStaleVersion` (a manifest refresh) and one re-resolve + retry. * Render blobs ride this rail: a scope flip re-resolves the * doc-vs-layer path family instead of failing on a stale URL. */ async getBlobWithRefresh( buildPath: (signal: AbortSignal) => Promise, onStaleVersion: (signal: AbortSignal) => Promise, signal: AbortSignal, ): Promise { const initialPath = await buildPath(signal); try { return await this.getBlob(initialPath, signal); } catch (err) { if (!EngineError.is(err, EngineErrorCode.NotFound)) throw err; await onStaleVersion(signal); const retryPath = await buildPath(signal); return await this.getBlob(retryPath, signal); } } /** GET raw bytes plus the response headers (attachment-file leaves). */ async getFile(path: string, signal: AbortSignal): Promise { const res = await this.request(path, { method: 'GET', signal }); if (!res.ok) await this.throwFromBody(res); return { bytes: new Uint8Array(await res.arrayBuffer()), headers: res.headers }; } /** * `getFile` with the same single-retry stale-version recovery as * {@link getJsonWithRefresh}: a 404 on a versioned URL triggers * `onStaleVersion` (a manifest refresh) and one re-resolve + retry. */ async getFileWithRefresh( buildPath: (signal: AbortSignal) => Promise, onStaleVersion: (signal: AbortSignal) => Promise, signal: AbortSignal, ): Promise { const initialPath = await buildPath(signal); try { return await this.getFile(initialPath, signal); } catch (err) { if (!EngineError.is(err, EngineErrorCode.NotFound)) throw err; await onStaleVersion(signal); const retryPath = await buildPath(signal); return await this.getFile(retryPath, signal); } } async postMultipartJson( path: string, body: FormData, parser: (raw: unknown) => T, signal: AbortSignal, options: RequestOptions = {}, ): Promise { const res = await this.request(path, { method: 'POST', body, signal }, options); return await this.parseJsonResponse(res, parser); } /** PATCH counterpart of {@link postMultipartJson} (binary-carrying mutations). */ async patchMultipartJson( path: string, body: FormData, parser: (raw: unknown) => T, signal: AbortSignal, options: RequestOptions = {}, ): Promise { const res = await this.request(path, { method: 'PATCH', body, signal }, options); return await this.parseJsonResponse(res, parser); } async postJson( path: string, body: unknown, parser: (raw: unknown) => T, signal: AbortSignal, options: RequestOptions = {}, ): Promise { const res = await this.requestJson(path, 'POST', body, signal, options); return await this.parseJsonResponse(res, parser); } async putJson( path: string, body: unknown, parser: (raw: unknown) => T, signal: AbortSignal, options: RequestOptions = {}, ): Promise { return this.parseJsonResponse( await this.requestJson(path, 'PUT', body, signal, options), parser, ); } /** POST a JSON body and parse a `multipart/form-data` response (a large annotation export). */ async postJsonFormData(path: string, body: unknown, signal: AbortSignal): Promise { const res = await this.request(path, { method: 'POST', body: JSON.stringify(body), headers: new Headers({ 'Content-Type': 'application/json', Accept: 'multipart/form-data', }), signal, }); if (!res.ok) await this.throwFromBody(res); return await res.formData(); } /** POST a JSON body and return the raw binary response (pages.extract). */ async postJsonBytes(path: string, body: unknown, signal: AbortSignal): Promise { const res = await this.requestJson(path, 'POST', body, signal); if (!res.ok) await this.throwFromBody(res); return new Uint8Array(await res.arrayBuffer()); } /** POST a raw binary body (FDF/XFDF import) and parse the JSON response. */ async postBytesJson( path: string, bytes: Uint8Array, contentType: string, parser: (raw: unknown) => T, signal: AbortSignal, options: RequestOptions = {}, ): Promise { const headers = new Headers({ 'Content-Type': contentType }); // Copy into a fresh ArrayBuffer: `bytes` may be a view over a larger // (or SharedArrayBuffer-backed) buffer, which fetch bodies reject. const body = new Uint8Array(bytes).buffer as ArrayBuffer; const res = await this.request(path, { method: 'POST', body, headers, signal }, options); return await this.parseJsonResponse(res, parser); } async patchJson( path: string, body: unknown, parser: (raw: unknown) => T, signal: AbortSignal, options: RequestOptions = {}, ): Promise { const res = await this.requestJson(path, 'PATCH', body, signal, options); return await this.parseJsonResponse(res, parser); } async deleteJson( path: string, parser: (raw: unknown) => T, signal: AbortSignal, options: RequestOptions = {}, ): Promise { const res = await this.request(path, { method: 'DELETE', signal }, options); return await this.parseJsonResponse(res, parser); } private requestJson( path: string, method: 'POST' | 'PATCH' | 'PUT', body: unknown, signal: AbortSignal, options: RequestOptions = {}, ): Promise { const headers = new Headers({ 'Content-Type': 'application/json' }); return this.request( path, { method, body: JSON.stringify(body ?? {}), headers, signal }, options, ); } private async request( path: string, init: RequestInit, options: RequestOptions = {}, ): Promise { const { url, extraHeader, routedToCdn } = this.resolveOutgoing( path, init.method ?? 'GET', options.origin === true, ); const headers = new Headers(init.headers ?? {}); let token = this.tokens ? await this.tokens.token() : null; if (token !== null) headers.set('Authorization', `Bearer ${token}`); if (!headers.has('Accept')) headers.set('Accept', 'application/json'); // The session header only where the server reads it: on any other read // it would turn a plain CDN request into one that needs a preflight. const { write } = options; if (this.sessionId && (write || options.session)) { headers.set('X-Engine-Session-Id', this.sessionId); } if (write) { if (write.opId !== undefined) headers.set('Idempotency-Key', write.opId); if (write.reserveObjectNumbers && write.reserveObjectNumbers > 0) { headers.set('EmbedPDF-Reserve-Object-Numbers', String(write.reserveObjectNumbers)); } } if (extraHeader) headers.set(extraHeader.name, extraHeader.value); // The version this client speaks, on every request to the server itself. // A CDN serves cached reads, whose answers never depend on it, and there // the header would cost every URL a CORS preflight. if (!routedToCdn) headers.set('EmbedPDF-Version', API_VERSION); // Document affinity key: origin-bound doc requests only (a CDN GET is a // "simple" request today — a custom header would create preflights // for zero routing value). Same extraction as the chart's uri-mode // regex, so the header tier and the ingress fallback cannot disagree. if (this.docAffinityHeader && !routedToCdn) { const doc = /^\/v1\/docs\/([^/]+)\//.exec(path); if (doc) headers.set('X-CloudPDF-Doc', decodeURIComponent(doc[1]!)); } // Code-keyed backpressure retry: Only our own 503s (`EngineBusy` = // shed before dispatch, `EngineRestarting` = the apply never landed) // — both mean nothing happened, so retrying is method-agnostic-safe, // mutations included. A foreign 503 is returned without a retry. for (let attempt = 0, networkFailures = 0, refusedOnce = false; ; attempt++) { let res: Response; try { res = await this.execute(url, { ...init, headers }); } catch (err) { // A write that may or may not have landed goes again under the same // key: the server answers a repeat with what the first one committed. const wait = HttpClient.NETWORK_RETRY_MS[networkFailures]; if ( !write || wait === undefined || !EngineError.is(err, EngineErrorCode.Network) || isStreamBody(init.body ?? null) ) { throw err; } networkFailures++; const waitMs = wait * (0.9 + 0.2 * Math.random()); this.onRetry?.({ path, code: EngineErrorCode.Network, attempt, waitMs }); await sleepRacingAbort(waitMs, init.signal ?? null); continue; } // A refused token was kept past its time (revoked, or a clock ahead of // the server's): once, the request goes again with the next token. A // refused request changed nothing, so a write is safe to repeat. if ( res.status === 401 && token !== null && !refusedOnce && !isStreamBody(init.body ?? null) && this.tokens?.refused(token) ) { refusedOnce = true; token = await this.tokens.token(); headers.set('Authorization', `Bearer ${token}`); continue; } const serverVersion = res.headers.get('EmbedPDF-Server-Version'); if (serverVersion !== null && isLiveAnswer(res)) this.serverVersionSeen = serverVersion; // The server answered with another engine value than the URL named: // its values moved, and `/head` has the new ones. if (res.ok && res.headers.has('EmbedPDF-Engine')) { for (const listener of this.engineChangedListeners) listener(); } if (res.ok && write?.onObjectNumbers) { const ranges = parseObjectNumberRanges(res.headers.get('EmbedPDF-Object-Numbers')); if (ranges.length > 0) write.onObjectNumbers(ranges); } if ( res.status !== 503 || attempt >= HttpClient.MAX_RETRIES || isStreamBody(init.body ?? null) ) { return res; } const code = await peekErrorCode(res); if (code === null || !RETRYABLE_503.has(code)) return res; const hinted = Number(res.headers.get('retry-after')); const base = Number.isFinite(hinted) ? Math.min(Math.max(hinted, 0) * 1000, HttpClient.RETRY_AFTER_CAP_MS) : HttpClient.RETRY_AFTER_DEFAULT_MS; const waitMs = base * (0.9 + 0.2 * Math.random()); this.onRetry?.({ path, code, attempt, waitMs }); await sleepRacingAbort(waitMs, init.signal ?? null); } } private async execute(url: string, init: RequestInit): Promise { try { return await this.fetchFn(url, init); } catch (err) { // undici's fetch propagates whatever was passed to AbortController.abort(). // Anything that arrives while signal.aborted is true is an abort, regardless // of the wire-shape (DOMException, plain Error, string, ...). if (init.signal?.aborted) { throw new AbortError(init.signal.reason ?? err); } if ((err as { name?: string } | null)?.name === 'AbortError') { throw new AbortError((err as Error).message); } throw new EngineError( EngineErrorCode.Network, `network error: ${(err as Error)?.message ?? err}`, { cause: err, }, ); } } private async parseJsonResponse(res: Response, parser: (raw: unknown) => T): Promise { if (!res.ok) await this.throwFromBody(res); const json: unknown = await res.json().catch(() => ({})); try { return parser(json); } catch (err) { throw new EngineError( EngineErrorCode.WireFormat, `unexpected response shape: ${(err as Error)?.message ?? err}`, { cause: err, }, ); } } /** * Decide where this request actually goes. With no CDN binding (or * binding's `cdn` is null), or with the CDN turned off (`cdn: false`), * every request stays on origin, and so does every request that isn't a * read (`GET`, `HEAD`): a write must reach the server itself, whatever * read its path looks like. Otherwise * `applyCdnAccess` decides per-request based on the resource the * path resolves to (and whether the caller's scope granted CDN * access to it). */ private resolveOutgoing( path: string, method: string, origin = false, ): { url: string; extraHeader: { name: string; value: string } | null; routedToCdn: boolean; } { const read = method === 'GET' || method === 'HEAD'; if (origin || !read || !this.usesCdn || !this.cdnBinding || !this.cdnBinding.cdn) { return { url: `${this.baseUrl}${path}`, extraHeader: null, routedToCdn: false }; } const applied = applyCdnAccess({ path, originUrl: this.baseUrl, docId: this.cdnBinding.docId, layerName: this.cdnBinding.layerName, cdn: this.cdnBinding.cdn, }); return { url: applied.url, extraHeader: applied.routedToCdn && applied.authHeader ? applied.authHeader : null, routedToCdn: applied.routedToCdn, }; } private async throwFromBody(res: Response): Promise { let payload: unknown; try { payload = await res.json(); } catch { payload = null; } const code = mapStatusToCode(res.status); if (payload && typeof payload === 'object' && 'error' in payload) { const inner = (payload as { error: unknown }).error; const parsed = trySerialized(inner); if (parsed) { // A code this client doesn't know reads as `Unknown`: the status says more. const known = parsed.code === EngineErrorCode.Unknown ? code : parsed.code; throw new EngineError(known, parsed.message, { details: parsed.details }); } const msg = typeof inner === 'object' && inner && 'message' in inner ? String((inner as { message: unknown }).message) : `HTTP ${res.status}`; throw new EngineError(code, msg, { details: { status: res.status } }); } throw new EngineError(code, `HTTP ${res.status}`, { details: { status: res.status } }); } } function mapStatusToCode(status: number): EngineErrorCode { if (status === 401) return EngineErrorCode.Unauthenticated; if (status === 403) return EngineErrorCode.Forbidden; // A conflict whose body names no code: the layer moved under the write. if (status === 409) return EngineErrorCode.LayerVersionConflict; if (status === 404) return EngineErrorCode.NotFound; // A request body past the server's limit, refused before any route runs. if (status === 413) return EngineErrorCode.PayloadTooLarge; if (status === 422) return EngineErrorCode.DocOpenFailed; if (status === 499) return EngineErrorCode.Aborted; if (status === 400) return EngineErrorCode.InvalidArg; return EngineErrorCode.Unknown; } function trySerialized(value: unknown): SerializedEngineError | null { const result = EngineErrorSchema.safeParse(value); return result.success ? result.data : null; } const RETRYABLE_503 = new Set(['EngineBusy', 'EngineRestarting']); /** Whether nothing may store the answer (`Cache-Control: no-store`): the server gave it just now. */ function isLiveAnswer(res: Response): boolean { return /(^|,)\s*no-store\s*(,|$)/i.test(res.headers.get('cache-control') ?? ''); } function isStreamBody(body: BodyInit | null): boolean { return typeof ReadableStream !== 'undefined' && body instanceof ReadableStream; } /** Read the error code from a 503 body without consuming the response. */ async function peekErrorCode(res: Response): Promise { try { const payload = (await res.clone().json()) as { error?: { code?: unknown } } | null; const code = payload?.error?.code; return typeof code === 'string' ? code : null; } catch { return null; } } function sleepRacingAbort(ms: number, signal: AbortSignal | null): Promise { return new Promise((resolve, reject) => { if (signal?.aborted) { reject(new AbortError(signal.reason ?? 'aborted')); return; } const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms); const onAbort = (): void => { clearTimeout(timer); reject(new AbortError(signal?.reason ?? 'aborted')); }; signal?.addEventListener('abort', onAbort, { once: true }); }); } /** Where a client's token comes from: a literal, a function it keeps the answer of, or none. */ function tokenKeeperOf(token: TokenSource | undefined, keep: boolean): TokenKeeper | null { if (token === undefined) return null; if (typeof token !== 'function') return fixedToken(token); return keep ? keptToken(token) : askedToken(token); }