import type { ApiContract } from '@lokalise/api-contracts'; import type { HeadersSource, WretchInstance } from '../types.ts'; import { FallbackEventValidationError } from './errors.ts'; import type { FallbackTransport } from './types.ts'; /** How SSE payloads that do not match the contract's event schemas are handled. */ export type FallbackEventValidationMode = /** Deliver every frame unchecked. */ 'off' /** * Validate and report to `diagnostics.onEventSchemaError`, but deliver the * frame anyway. The default, and the only sound choice with * `streamMode: 'chunks'`: by the time app code sees a frame the core's * version gate has already advanced its watermark, so withholding it there * would leave a hole that the repair poll reads as a duplicate and drops. */ | 'report' /** * Withhold the frame from the core entirely **and end the stream**, so the * version watermark never advances past the hole and the repair snapshot * lands above it. Both halves are load-bearing: frames delivered after a * withheld one advance the watermark past the gap, and the repair poll then * arrives at or below it — where the reconciler reads it as a stale * duplicate and synthesizes nothing, leaving the withheld event lost for * good. * * The cost is a reconnect per rejected payload, which is the point: a stream * emitting bodies its own contract rejects is broken, and the polling * backbone carries the subscription meanwhile. Requires `streamMode: * 'events'`, which is where the framing — and therefore the decision — * happens before the core sees anything. */ | 'drop'; /** Which {@link FallbackStreamResponse} shape `openStream` resolves with. */ export type FallbackStreamMode = /** * Raw decoded text, framed by the core (default). Heartbeat comments reach * the core, so its `staleConnectionTimeoutMs` watchdog is byte-level, and * every frame keeps its own `id:` for the version gate. */ 'chunks' /** * Frames, framed here. The price of validating payloads before the core sees * them, paid in two places: * * - comment frames are consumed by the framing, so the stale-connection * watchdog degrades from byte-level to event-level; * - an `id:` or `retry:` that arrives with no `data:` reaches the core only * if a later frame on the same connection carries it out. In `'chunks'` * mode the core's own parser reads both per chunk regardless. * * Neither loss corrupts anything — an unreported cursor replays events the * version gate then dedupes, and an unreported `retry:` leaves the core on * its own backoff — but they are why `'chunks'` is the default. */ | 'events'; export type FallbackTransportDiagnostics = { /** Every snapshot poll that produced a response, including non-2xx ones. */ onSnapshot?: (info: { path: string; status: number; durationMs: number; }) => void; /** Every stream connect attempt that produced response headers. */ onStreamOpen?: (info: { path: string; status: number; contentType: string | undefined; lastEventId: string | undefined; }) => void; /** * An SSE payload did not match the contract. Silent schema drift is how a * push channel stops working without anyone noticing, so this is the hook to * wire to your error reporter. */ onEventSchemaError?: (error: FallbackEventValidationError) => void; /** * The stream sent an event the contract does not declare. Never dropped — * an unknown event is usually a newer server, not a broken one — but worth * counting: it means the contract and the emitter have diverged. */ onUndeclaredEvent?: (info: { path: string; event: string; }) => void; }; export type CreateFallbackTransportOptions = { /** * The dual-mode contract both channels use — one path serving JSON via * `Accept: application/json` and SSE via `Accept: text/event-stream`. * * Supplying it is what turns on validation: snapshots are parsed with the * contract's JSON schema for the responding status, and SSE payloads are * checked against its `sseResponse` event schemas. Without a contract the * transport still works, but bodies pass through unvalidated. */ contract?: ApiContract; /** Poll contract, when the poll and the stream live on separate contracts. */ snapshotContract?: ApiContract; /** Stream contract, when the poll and the stream live on separate contracts. */ streamContract?: ApiContract; /** Prefix prepended to both channels' paths, as in `sendByApiContract`. */ pathPrefix?: string; /** * Headers added to every request. Resolved **fresh for each poll and each * reconnect**, so a function here is how a rotating credential reaches the * retry that `onAuthChallenge` grants: refresh the token in the challenge * handler, and the retried request picks it up. */ headers?: HeadersSource; /** * `Accept` sent on the poll. Defaults to `application/json`; override only * for a vendored JSON media type (`application/json+01`) that the contract * declares. The stream's `Accept` is always `text/event-stream` — the branch * selection belongs to the transport, so any `accept` in the request headers * is overridden on both channels. */ snapshotAccept?: string; /** * Validate snapshot bodies against the contract schema. Default `true`. * Turning it off keeps the response shape unchecked, which puts the burden * of a wrong `version.ofSnapshot` back on runtime behaviour — prefer fixing * the schema. */ validateSnapshot?: boolean; /** * Require the snapshot's `content-type` to match a representation the * contract declares (default `true`). Mirrors `sendByApiContract`. */ strictContentType?: boolean; /** See {@link FallbackStreamMode}. Default `'chunks'`. */ streamMode?: FallbackStreamMode; /** * See {@link FallbackEventValidationMode}. Defaults to `'report'` when the * stream contract declares SSE event schemas, `'off'` otherwise. */ eventValidation?: FallbackEventValidationMode; diagnostics?: FallbackTransportDiagnostics; }; /** * Build a {@link FallbackTransport} over a `wretch` instance: the HTTP half of * `@opinionated-machine/sse-fallback`, which owns no HTTP of its own. * * `fetchSnapshot` requests the contract's JSON branch and validates the body; * `openStream` requests its SSE branch, forwards `Last-Event-ID` on reconnect, * and yields raw text chunks so the core's byte-level liveness watchdog works. * * Both channels follow the contract the core relies on: a non-2xx response * **resolves** (carrying the status, so `unretryableStatuses` and * `onAuthChallenge` can act on it) and only a genuinely unusable outcome * rejects — a network failure, or a snapshot that cannot be trusted. Neither * channel imposes its own deadline: the core bounds every wait * (`pollTimeoutMs`, `connectTimeoutMs`) through the `signal` it passes, and an * unbounded wait is exactly the silent failure this machinery exists to catch. * * @example * ```typescript * import { createResilientSubscription, defineFallbackBinding } from '@opinionated-machine/sse-fallback' * import { buildFallbackParams, createFallbackTransport } from '@lokalise/frontend-http-client' * * const binding = defineFallbackBinding(uploadStatusContract, { * snapshotToEvents: (snapshot) => * snapshot.status === 'completed' ? [{ event: 'uploadFinished', data: snapshot }] : [], * version: { ofSnapshot: (snapshot) => snapshot.version }, * terminalEvents: ['uploadFinished'], * }) * * const transport = createFallbackTransport(client, { * contract: uploadStatusContract, * headers: () => ({ authorization: `Bearer ${auth.token()}` }), * diagnostics: { onEventSchemaError: (error) => reportToBugsnag(error) }, * }) * * const subscription = createResilientSubscription(binding, { * transport, * params: buildFallbackParams(uploadStatusContract, { pathParams: { uploadId } }), * onAuthChallenge: async () => { * await auth.refresh() * return true * }, * }) * * const finished = await subscription.waitFor('uploadFinished') * ``` */ export declare function createFallbackTransport(wretch: WretchInstance, options?: CreateFallbackTransportOptions): FallbackTransport;