@openstage/monadyssey-fetch 3.0.0-rc.2 → 3.0.0-rc.3
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/dist/monadyssey-fetch.d.ts +148 -9
- package/dist/monadyssey-fetch.mjs +1115 -283
- package/dist/monadyssey-fetch.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"monadyssey-fetch.mjs","names":["responseHeaders","response","name","HttpErrorMessage","cause","kind","url","status","rawMessage","timeoutMs","HttpError","body","headers","after","guard","Option","isNativeBody","normalizeHeaders","entry","key","value","withContentType","_dropped","rest","isJsonContentType","media","contentType","serializeBody","method","HttpRequest","defaults","options","bodyReaders","readerFor","responseType","error","NO_BODY","failure","readJson","text","HttpResponse","IO","read","isAbort","HttpTransport","Interceptors","interceptors","interceptor","r","next","send","request","init","e","parseBlock","event","id","retry","data","line","block","colon","field","withLastEventId","_blockId","lastEventId","FrameBuffer","limit","chunk","searchFrom","blocks","decodeEvents","frames","bytes","events","current","frame","List","MIN_SERVER_RETRY_MS","MAX_DELAY_MS","MAX_BLOCK_CHARS","utf8ByteString","b","delay","onAbort","timer","resolve","signal","ms","SseSession","retryMs","parent","reader","mediaType","SseClient","config","open","prepared","session","defaultHeaders","readChunk","done","reconnectOr","reconnect","giveUp","made","step","opened","result","Stream","HttpClient","uri","opts","timeout","io","parsed","empty","transform"],"sources":["../src/http-error.ts","../src/http-request.ts","../src/http-response.ts","../src/http-transport.ts","../src/interceptors.ts","../src/sse.ts","../src/sse-client.ts","../src/http-client.ts"],"sourcesContent":["import { Option } from \"@openstage/monadyssey-core\";\n\n/**\n * How a request failed.\n * - `\"request\"`: the request could not be built — typically the body could not be serialized.\n * Nothing was sent.\n * - `\"response\"`: the server answered with a non-2xx status. `body` carries what it sent.\n * - `\"decode\"`: the server answered 2xx, but the body could not be used — it failed to parse, a\n * `transform` threw, or there was no body where one was expected (a `204`, say). `status` is the\n * real status and `cause` the underlying error.\n * - `\"network\"`: no response arrived — DNS failure, offline, CORS block, or a rejected interceptor.\n * - `\"timeout\"`: the client's `timeout` option fired before the response, or its body, completed.\n * The request may have reached the server.\n * - `\"aborted\"`: the request was aborted by something other than IO cancellation, such as an\n * interceptor's own signal (an IO cancelled via `fiber.cancel()` or `IO.timeout` ends as\n * `Cancelled`, not as an `HttpError`).\n *\n * New kinds may be added in a minor release, so give an exhaustive `switch` a `default` branch.\n */\nexport type HttpErrorKind = \"request\" | \"response\" | \"decode\" | \"network\" | \"timeout\" | \"aborted\";\n\n/**\n * @internal The response headers an `HttpError` carries. `Set-Cookie` is left out: browsers never\n * expose it, Node and Electron do, and an error that ends up in a log must not carry a session.\n */\nexport const responseHeaders = (response: Response): Record<string, string> => {\n try {\n return Object.fromEntries(\n Array.from(response.headers.entries()).filter(([name]) => name !== \"set-cookie\" && name !== \"set-cookie2\")\n );\n } catch {\n return {};\n }\n};\n\n/** @internal */\nexport const HttpErrorMessage = {\n describe: (cause: unknown): string =>\n cause instanceof Error\n ? cause.message\n : typeof cause === \"string\"\n ? cause\n : typeof cause === \"object\" && cause !== null && \"message\" in cause\n ? String((cause as { message: unknown }).message)\n : \"An unknown error occurred.\",\n\n /** Response errors keep the pre-3.0 wording; the other kinds carry no status. */\n format: (kind: HttpErrorKind, url: string, status: number, rawMessage: string, timeoutMs?: number): string => {\n switch (kind) {\n case \"response\":\n return `Request to '${url}' failed with status ${status} and message: ${rawMessage}.`;\n case \"decode\":\n return `Response from '${url}' (status ${status}) could not be decoded: ${rawMessage}.`;\n case \"request\":\n return `Request to '${url}' could not be sent: ${rawMessage}.`;\n case \"timeout\":\n return `Request to '${url}' timed out after ${timeoutMs} ms.`;\n case \"aborted\":\n return `Request to '${url}' was aborted before a response arrived: ${rawMessage}.`;\n default:\n return `Request to '${url}' failed before a response arrived: ${rawMessage}.`;\n }\n },\n};\n\n/**\n * Represents an HTTP error encountered during a request.\n *\n * Extends the native `Error` class with additional context: the transport outcome (`kind`), HTTP\n * status code, raw error message, response body, request URL, response headers, and the\n * underlying cause.\n *\n * `kind` tells the two facts apart that `status` alone cannot: \"the server said 500\" is\n * `kind: \"response\", status: 500`, while \"nothing answered\" is `kind: \"network\", status: 0`.\n * For every kind other than `\"response\"` and `\"decode\"`, `status` is `0`; `body` is `null` except\n * for `\"response\"`.\n *\n * `body`, `headers` and `url` hold what the server and the request contained, which may be sensitive\n * (a token in a query string, an error page echoing input); redact them before logging an error\n * outside a trusted sink. `Set-Cookie` is never carried.\n *\n * @example\n * client.post(\"/payments\", payment).mapErr((error) =>\n * error.kind === \"response\"\n * ? { kind: \"rejected\", status: error.status }\n * : { kind: \"outcomeUnknown\" } // the request may or may not have reached the server\n * );\n */\nexport class HttpError extends Error {\n /** The transport outcome. See {@link HttpErrorKind}. */\n public readonly kind: HttpErrorKind;\n /** The HTTP status code (`\"response\"` and `\"decode\"`), or `0` when no response arrived. */\n public readonly status: number;\n public readonly rawMessage: string;\n /** The parsed response body, or `null` when none was parsed. */\n public readonly body: unknown;\n public readonly url: string;\n public readonly headers?: Record<string, string>;\n /** The underlying exception, when there was one (a `TypeError` from `fetch`, a parse error, an abort reason). */\n public readonly cause?: unknown;\n /** The timeout that fired, in milliseconds. Set only when `kind === \"timeout\"`. */\n public readonly timeoutMs?: number;\n\n constructor(\n status: number,\n rawMessage: string,\n body: unknown,\n url: string,\n headers?: Record<string, string>,\n kind: HttpErrorKind = \"response\",\n cause?: unknown,\n timeoutMs?: number\n ) {\n super(HttpErrorMessage.format(kind, url, status, rawMessage, timeoutMs));\n this.name = \"HttpError\";\n this.kind = kind;\n this.status = status;\n this.rawMessage = rawMessage;\n this.body = body;\n this.url = url;\n this.headers = headers;\n this.cause = cause;\n this.timeoutMs = timeoutMs;\n }\n\n /**\n * An error for a request that received no response: DNS failure, offline, CORS block, or a\n * rejected interceptor. `status` is `0` and `body` is `null`.\n *\n * @param {string} url The request URL.\n * @param {unknown} cause The underlying exception (typically the `TypeError` thrown by `fetch`).\n */\n static network(url: string, cause: unknown): HttpError {\n return new HttpError(0, HttpErrorMessage.describe(cause), null, url, undefined, \"network\", cause);\n }\n\n /**\n * An error for a request whose `timeout` option fired before the response, or its body, completed.\n * `status` is `0`, `body` is `null`, and `timeoutMs` records the timeout.\n *\n * @param {string} url The request URL.\n * @param {number} after The timeout in milliseconds.\n */\n static timeout(url: string, after: number): HttpError {\n return new HttpError(0, `Request timed out after ${after} ms`, null, url, undefined, \"timeout\", undefined, after);\n }\n\n /**\n * An error for a 2xx response whose body could not be used: it failed to parse, a `transform`\n * threw, or there was no body where one was expected. `status` is the real status, `body` is\n * `null`, and `cause` carries the underlying error.\n *\n * @param {string} url The request URL.\n * @param {Response} response The response that could not be decoded.\n * @param {unknown} cause The parse error, the value a `transform` threw, or a description.\n */\n static decode(url: string, response: Response, cause: unknown): HttpError {\n return new HttpError(\n response.status,\n HttpErrorMessage.describe(cause),\n null,\n url,\n responseHeaders(response),\n \"decode\",\n cause\n );\n }\n\n /**\n * An error for a request that could not be built, so nothing was sent — typically a body that\n * could not be serialized. `status` is `0` and `body` is `null`.\n *\n * @param {string} url The request URL.\n * @param {unknown} cause The underlying exception (typically a `TypeError` from `JSON.stringify`).\n */\n static request(url: string, cause: unknown): HttpError {\n return new HttpError(0, HttpErrorMessage.describe(cause), null, url, undefined, \"request\", cause);\n }\n\n /**\n * An error for a request aborted by something other than IO cancellation, such as an\n * interceptor aborting the signal. `status` is `0` and `body` is `null`.\n *\n * @param {string} url The request URL.\n * @param {unknown} [cause] The abort reason, if any.\n */\n static aborted(url: string, cause?: unknown): HttpError {\n return new HttpError(0, HttpErrorMessage.describe(cause), null, url, undefined, \"aborted\", cause);\n }\n\n /**\n * Narrows the `unknown` error body to a concrete type using a runtime type guard.\n * Returns `Some(body)` if the guard passes, `None` otherwise — so the narrow is *checked*,\n * not asserted. This keeps the unsafe cast out of consumer code: the body stays `unknown`\n * by default (forcing a conscious narrow), and this is the safe way to perform it.\n *\n * @template T The expected body shape.\n * @param {(x: unknown) => x is T} guard A type guard validating the body's shape.\n * @returns {Option<T>} `Some(body)` if the guard matches, `None` otherwise.\n *\n * @example\n * interface ApiError { code: string; message: string }\n * const isApiError = (x: unknown): x is ApiError =>\n * typeof x === \"object\" && x !== null && \"code\" in x && \"message\" in x;\n *\n * httpError.bodyAs(isApiError).fold(\n * () => \"unrecognized error shape\",\n * (e) => `${e.code}: ${e.message}`\n * );\n */\n bodyAs<T>(guard: (x: unknown) => x is T): Option<NonNullable<T>> {\n return guard(this.body) ? Option.ofNullable(this.body) : Option.empty();\n }\n}\n","import { Credentials, Method, Options } from \"./options\";\n\n/** @internal */\nexport interface RequestDefaults {\n readonly headers: Record<string, string>;\n readonly credentials: Credentials;\n}\n\n/** @internal */\nexport interface PreparedRequest {\n readonly method: Method;\n readonly headers: Record<string, string>;\n readonly credentials: Credentials;\n readonly body: BodyInit | undefined;\n}\n\n/** Bodies `fetch` sends as-is: never JSON-encoded, never given an automatic content type. */\nconst isNativeBody = (body: unknown): boolean =>\n typeof body !== \"object\" ||\n body === null ||\n body instanceof FormData ||\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof URLSearchParams ||\n (typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream) ||\n ArrayBuffer.isView(body);\n\nconst normalizeHeaders = (headers: Record<string, string | undefined>): Record<string, string> =>\n Object.fromEntries(\n Object.entries(headers)\n .filter((entry): entry is [string, string] => entry[1] !== undefined)\n .map(([key, value]) => [key.toLowerCase(), value])\n );\n\n/** `FormData` must carry no content type so the browser can set the multipart boundary. */\nconst withContentType = (headers: Record<string, string>, body: unknown): Record<string, string> => {\n if (body instanceof FormData) {\n const { \"content-type\": _dropped, ...rest } = headers;\n return rest;\n }\n const autoJson = body != null && typeof body === \"object\" && !isNativeBody(body) && !(\"content-type\" in headers);\n return autoJson ? { ...headers, \"content-type\": \"application/json\" } : headers;\n};\n\n/**\n * `application/json`, with or without parameters (`; charset=utf-8`), or any `+json` suffix type\n * (`application/merge-patch+json`, `application/vnd.api+json`). Matching the exact string alone\n * would send an object declared as one of the others as `\"[object Object]\"`.\n */\nconst isJsonContentType = (contentType: string): boolean => {\n const media = contentType.split(\";\")[0].trim().toLowerCase();\n return media === \"application/json\" || media.endsWith(\"+json\");\n};\n\nconst serializeBody = (method: Method, body: unknown, headers: Record<string, string>): BodyInit | undefined =>\n method === \"GET\" || method === \"HEAD\" || body == null\n ? undefined\n : isNativeBody(body)\n ? (body as BodyInit)\n : isJsonContentType(headers[\"content-type\"])\n ? JSON.stringify(body)\n : (body as BodyInit);\n\n/** @internal */\nexport const HttpRequest = {\n isNativeBody,\n normalizeHeaders,\n\n /** Per-request headers win over defaults; names are lowercased; the body follows the content type. */\n prepare: (method: Method, options: Options<unknown>, defaults: RequestDefaults): PreparedRequest => {\n const headers = withContentType(\n normalizeHeaders({ ...defaults.headers, ...(options.headers ?? {}) }),\n options.body\n );\n return {\n method,\n headers,\n credentials: options.credentials ?? defaults.credentials,\n body: serializeBody(method, options.body, headers),\n };\n },\n};\n","import { IO, Option } from \"@openstage/monadyssey-core\";\nimport { HttpError, responseHeaders } from \"./http-error\";\nimport { Method, ResponseType } from \"./options\";\n\ntype BodyReader = (response: Response) => Promise<unknown>;\n\nconst bodyReaders = {\n json: (response) => response.json(),\n text: (response) => response.text(),\n blob: (response) => response.blob(),\n arrayBuffer: (response) => response.arrayBuffer(),\n formData: (response) => response.formData(),\n} satisfies Record<ResponseType, BodyReader>;\n\n/** An own-property lookup, so an untyped `responseType` such as `\"toString\"` is rejected. */\nconst readerFor = (responseType: ResponseType): Option<BodyReader> =>\n Object.prototype.hasOwnProperty.call(bodyReaders, responseType)\n ? Option.of(bodyReaders[responseType])\n : Option.empty<BodyReader>();\n\nconst headers = responseHeaders;\n\n/** The server answered 2xx but the body could not be used (`kind: \"decode\"`). */\nconst error = (cause: unknown, url: string, response: Response): HttpError => HttpError.decode(url, response, cause);\n\n/**\n * What {@link HttpResponse.read} yields when there is no body at all — distinct from a JSON body\n * that is literally `null`.\n *\n * @internal\n */\nexport const NO_BODY: unique symbol = Symbol(\"HttpResponse.noBody\");\n\n/** The server answered with a non-2xx status; the parsed body travels with the error. */\nconst failure = (response: Response, body: unknown, url: string): HttpError =>\n new HttpError(response.status, response.statusText, body, url, headers(response));\n\n/**\n * Reads a JSON body, yielding `NO_BODY` for an empty one. Responses that implement only `json()` —\n * hand-rolled mocks in consumers' tests — are read with it.\n */\nconst readJson = async (response: Response): Promise<unknown> => {\n if (typeof response.text !== \"function\") return response.json();\n const text = await response.text();\n return text.trim() === \"\" ? NO_BODY : JSON.parse(text);\n};\n\n/** @internal */\nexport const HttpResponse = {\n headers,\n error,\n failure,\n\n /**\n * Reads a successful body. Yields `NO_BODY` when there is none to read: `204`/`205`, a `HEAD`\n * request, or an empty body under `\"json\"` (e.g. `201 Created` / `202 Accepted` with nothing\n * attached). A body that cannot be parsed fails with `kind: \"decode\"`.\n */\n read: (\n response: Response,\n responseType: ResponseType,\n url: string,\n method?: Method\n ): IO<HttpError, unknown | typeof NO_BODY> =>\n IO.from(readerFor(responseType), () => error(`Unsupported response type: ${responseType}`, url, response)).flatMap(\n (read) =>\n IO.lift(\n async () => {\n if (response.status === 204 || response.status === 205 || method === \"HEAD\") return NO_BODY;\n if (responseType !== \"json\") return read(response);\n return readJson(response);\n },\n (cause) => error(cause, url, response)\n )\n ),\n\n /**\n * Fails with the error for a non-2xx response. The body is read leniently, so an error page\n * that is not JSON (an HTML 502 from a proxy, say) still travels with the error and the message\n * stays the status text: under `\"json\"` the text is parsed when it is JSON and kept as a string\n * otherwise; an unreadable or empty body is `null`.\n */\n readFailure: (response: Response, responseType: ResponseType, url: string): IO<HttpError, never> =>\n IO.promise<unknown>(async () => {\n try {\n if (responseType !== \"json\") {\n return await readerFor(responseType).fold(\n async () => null,\n (read) => read(response)\n );\n }\n // A response without `text()` (a hand-rolled mock) can only be read as JSON.\n if (typeof response.text !== \"function\") return await response.json();\n const text = await response.text();\n if (text.trim() === \"\") return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n } catch {\n return null;\n }\n }).flatMap((body) => IO.fail(failure(response, body, url))),\n};\n","import { HttpError } from \"./http-error\";\n\nconst isAbort = (e: unknown): boolean =>\n typeof e === \"object\" && e !== null && \"name\" in e && (e as { name: unknown }).name === \"AbortError\";\n\n/** @internal */\nexport const HttpTransport = {\n /** An interceptor may reject with a ready-made `HttpError`; it is passed through untouched. */\n error: (e: unknown, url: string): HttpError =>\n e instanceof HttpError ? e : isAbort(e) ? HttpError.aborted(url, e) : HttpError.network(url, e),\n\n /** A timeout means the caller stopped waiting and an abort means someone wanted it stopped: neither is retried. */\n isRetryable: (error: HttpError): boolean =>\n error.kind === \"network\" || (error.kind === \"response\" && error.status >= 500),\n};\n","import { HttpError } from \"./http-error\";\nimport { HttpInterceptor, InterceptedRequest } from \"./options\";\n\n/** @internal */\nexport type Send = (request: InterceptedRequest) => Promise<Response>;\n\n/** @internal */\nexport const Interceptors = {\n /** A right fold, so the first registered interceptor is outermost. */\n run: (interceptors: readonly HttpInterceptor[], request: InterceptedRequest, send: Send): Promise<Response> =>\n interceptors.reduceRight<Send>((next, interceptor) => (r) => interceptor.intercept(r, next), send)(request),\n\n /**\n * Builds the request interceptors see: headers normalised to a `Headers` instance. A header the\n * platform rejects (a CR, LF or NUL in a value, say) is a `kind: \"request\"` error: the request could\n * not be built and nothing was sent, so it is not retried as a network failure.\n */\n request: (\n url: string,\n init: Omit<RequestInit, \"headers\"> & { headers: Record<string, string> }\n ): InterceptedRequest => {\n let headers: Headers;\n try {\n headers = new Headers(init.headers);\n } catch (e) {\n throw HttpError.request(url, e);\n }\n return { url, init: { ...init, headers } };\n },\n\n /** The end of the chain. */\n fetch: (request: InterceptedRequest): Promise<Response> => fetch(request.url, request.init),\n};\n","import { List, Stream } from \"@openstage/monadyssey-core\";\nimport type { Pipe } from \"@openstage/monadyssey-core\";\n\n/**\n * A single server-sent event parsed from a text/event-stream response.\n *\n * @property id - The last event id in effect when the event was dispatched — set by the event's\n * own `id:` field or by an earlier one, as the spec's `MessageEvent.lastEventId`. Absent until\n * the server sends an `id:`; the empty string after the server resets it. Used to resume a stream.\n * @property event - The event type. Defaults to `\"message\"` when the server sends no `event:` field.\n * @property data - The event payload. Multiple `data:` lines are joined with a newline.\n * @property retry - The reconnection time in milliseconds, if the server sent a `retry:` field.\n */\nexport interface ServerSentEvent {\n readonly id?: string;\n readonly event: string;\n readonly data: string;\n readonly retry?: number;\n}\n\n/**\n * The effects of one block (the lines up to a blank line). A block may set the last event id or\n * the reconnection time without dispatching an event — e.g. a lone `retry: 5000` or `id: 42`.\n *\n * @internal\n */\nexport interface SseFrame {\n /** The event to dispatch, or `null` when the block has no `data:` field. */\n readonly event: ServerSentEvent | null;\n /** The last `id:` value in the block, if any. The empty string resets the last event id. */\n readonly id?: string;\n /** The last valid `retry:` value in the block, if any. */\n readonly retry?: number;\n}\n\nconst parseBlock = (block: string): SseFrame => {\n let event = \"\";\n let id: string | undefined;\n let retry: number | undefined;\n const data: string[] = [];\n\n for (const line of block.split(\"\\n\")) {\n if (line === \"\" || line.startsWith(\":\")) continue; // blank line or comment\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n switch (field) {\n case \"event\":\n event = value;\n break;\n case \"data\":\n data.push(value);\n break;\n case \"id\":\n // Per the spec, an id containing NUL is ignored.\n if (!value.includes(\"\\0\")) id = value;\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) retry = Number.parseInt(value, 10);\n break;\n default:\n break;\n }\n }\n\n return {\n event:\n data.length === 0\n ? null\n : {\n // An empty `event:` field means the default type, not the empty string.\n event: event || \"message\",\n data: data.join(\"\\n\"),\n ...(id !== undefined ? { id } : {}),\n ...(retry !== undefined ? { retry } : {}),\n },\n ...(id !== undefined ? { id } : {}),\n ...(retry !== undefined ? { retry } : {}),\n };\n};\n\n/**\n * `event` with `id` set to the last event id in effect (the spec's `lastEventId`), which persists\n * across events until the server changes it.\n *\n * @internal\n */\nexport const withLastEventId = (event: ServerSentEvent, lastEventId: string | undefined): ServerSentEvent => {\n const { id: _blockId, ...rest } = event;\n return lastEventId === undefined ? rest : { ...rest, id: lastEventId };\n};\n\n/**\n * Reassembles a byte stream into complete blocks; partial input and split multi-byte characters\n * are buffered. Call `reset` when a new connection begins. With a `limit`, an unterminated block\n * longer than that many characters throws `RangeError` (a hostile or broken server must not make the\n * buffer grow without bound); by default there is no limit.\n *\n * @internal\n */\nexport class FrameBuffer {\n private decoder = new TextDecoder(\"utf-8\");\n private buffered = \"\";\n\n constructor(private readonly limit: number = Infinity) {}\n /** The previous chunk ended in CR: a LF opening the next chunk belongs to that CRLF. */\n private skipLeadingLF = false;\n\n push(chunk: Uint8Array): SseFrame[] {\n let text = this.decoder.decode(chunk, { stream: true });\n if (text.length === 0) return [];\n if (this.skipLeadingLF && text.startsWith(\"\\n\")) text = text.slice(1);\n // A trailing CR ends its line now — holding it back until the next chunk would delay every\n // event on CR-only streams by a chunk. If a LF follows, it is skipped above.\n this.skipLeadingLF = text.endsWith(\"\\r\");\n // A block ends at the first `\\n\\n`; one may straddle the old buffer and this chunk, so the search\n // starts one character back. Without a delimiter the text is only appended, so a long block costs\n // one scan of each chunk rather than of everything buffered so far.\n const searchFrom = Math.max(0, this.buffered.length - 1);\n text = this.buffered + text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n if (text.indexOf(\"\\n\\n\", searchFrom) === -1) {\n this.buffered = text;\n this.checkLimit();\n return [];\n }\n const blocks = text.split(\"\\n\\n\");\n this.buffered = blocks.pop() ?? \"\";\n this.checkLimit();\n return blocks.map(parseBlock);\n }\n\n reset(): void {\n this.decoder = new TextDecoder(\"utf-8\");\n this.buffered = \"\";\n this.skipLeadingLF = false;\n }\n\n private checkLimit(): void {\n if (this.buffered.length > this.limit) {\n throw new RangeError(`An event block exceeds the ${this.limit}-character limit without ending`);\n }\n }\n}\n\n/**\n * A stream transformation that decodes raw response bytes into {@link ServerSentEvent}s, buffering\n * partial input across chunks. Single-use: each application maintains its own decoding state.\n *\n * @typeParam E - The error type carried by the surrounding stream.\n * @returns A pipe from a byte stream to a stream of parsed events.\n */\nexport const decodeEvents = <E>(): Pipe<E, Uint8Array, ServerSentEvent> => {\n const frames = new FrameBuffer();\n return (bytes: Stream<E, Uint8Array>) =>\n bytes.mapAccumulate<string | undefined, ServerSentEvent>(undefined, (lastEventId, chunk) => {\n const events: ServerSentEvent[] = [];\n let current = lastEventId;\n for (const frame of frames.push(chunk)) {\n if (frame.id !== undefined) current = frame.id;\n if (frame.event !== null) events.push(withLastEventId(frame.event, current));\n }\n return [current, List.from(events)] as const;\n });\n};\n","import { IO, Option, Schedule, Stream } from \"@openstage/monadyssey-core\";\nimport { HttpError } from \"./http-error\";\nimport { HttpRequest } from \"./http-request\";\nimport { HttpResponse } from \"./http-response\";\nimport { HttpTransport } from \"./http-transport\";\nimport { Interceptors } from \"./interceptors\";\nimport { Credentials, HttpInterceptor } from \"./options\";\nimport { FrameBuffer, ServerSentEvent, SseFrame, withLastEventId } from \"./sse\";\n\n/** A server-sent `retry:` below this is raised to it, so a misbehaving server cannot force a tight loop. */\nconst MIN_SERVER_RETRY_MS = 100;\n\n/** Largest delay `setTimeout` honours; anything above it (or Infinity) fires after ~1ms. */\nconst MAX_DELAY_MS = 2_147_483_647;\n\n/**\n * The longest event block (in UTF-16 code units, about 1 MiB of ASCII) buffered while waiting for its\n * terminating blank line. A server that never sends one would otherwise grow the buffer without bound;\n * reaching the limit fails the stream with `kind: \"decode\"`, which is not retried.\n */\nconst MAX_BLOCK_CHARS = 1_048_576;\n\n/** The `Last-Event-ID` value is the id UTF-8 encoded, byte for byte, as the EventSource spec sends it. */\nconst utf8ByteString = (id: string): string =>\n Array.from(new TextEncoder().encode(id), (b) => String.fromCharCode(b)).join(\"\");\n\ntype Reader = ReadableStreamDefaultReader<Uint8Array>;\n\n/** A cancellable sleep. The abort listener is removed when the timer fires, so waits do not accumulate listeners. */\nconst delay = (ms: number): IO<never, void> =>\n IO.promise<void>(\n (signal: AbortSignal) =>\n new Promise<void>((resolve) => {\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(\n () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n Math.min(ms, MAX_DELAY_MS)\n );\n signal.addEventListener(\"abort\", onAbort, { once: true });\n })\n );\n\n/**\n * Carried across reconnections within one run. Owns the one `AbortController` every connection\n * of the run is opened with, linked once to the run's signal; a connection registers a single\n * listener on it and removes it when closed, so listeners stay bounded however long the run lasts.\n */\nclass SseSession {\n readonly controller = new AbortController();\n readonly frames = new FrameBuffer(MAX_BLOCK_CHARS);\n readonly pending: SseFrame[] = [];\n lastEventId: string | undefined = undefined;\n retryMs: number;\n /** The server's `retry:` value, once received; it takes precedence over a `Schedule`'s delays. */\n serverRetryMs: number | undefined = undefined;\n /** Consecutive reconnects since the last delivered event. */\n reconnects = 0;\n /** The status of the current connection, for an error raised while reading it. */\n status = 200;\n private connection: { readonly reader: Reader; readonly unlink: () => void } | null = null;\n private readonly unlinkParent: () => void;\n\n constructor(retryMs: number, parent: AbortSignal) {\n this.retryMs = retryMs;\n const onAbort = () => this.controller.abort(parent.reason);\n parent.addEventListener(\"abort\", onAbort, { once: true });\n this.unlinkParent = () => parent.removeEventListener(\"abort\", onAbort);\n }\n\n get reader(): Reader | null {\n return this.connection?.reader ?? null;\n }\n\n attach(reader: Reader, status: number): void {\n this.status = status;\n const onAbort = () => reader.cancel().catch(() => {});\n this.controller.signal.addEventListener(\"abort\", onAbort, { once: true });\n this.connection = { reader, unlink: () => this.controller.signal.removeEventListener(\"abort\", onAbort) };\n this.frames.reset();\n }\n\n closeConnection(): void {\n if (this.connection) {\n this.connection.unlink();\n this.connection.reader.cancel().catch(() => {});\n this.connection = null;\n }\n }\n\n close(): void {\n this.closeConnection();\n this.unlinkParent();\n this.controller.abort();\n }\n}\n\n/** @internal */\nexport interface SseConfig {\n readonly url: string;\n readonly headers: Record<string, string>;\n readonly defaultHeaders: Record<string, string>;\n readonly credentials: Credentials;\n readonly interceptors: readonly HttpInterceptor[];\n readonly reconnect: boolean | Schedule;\n readonly retry: number;\n}\n\nconst mediaType = (contentType: string): string => contentType.split(\";\")[0].trim().toLowerCase();\n\nconst stream = (config: SseConfig): Stream<HttpError, ServerSentEvent> => {\n const { url, headers, defaultHeaders, credentials, interceptors, reconnect, retry } = config;\n\n type Opened = { readonly reader: Reader; readonly status: number };\n\n /** The reader for a new connection, or `null` when the server answered 204 (\"stop reconnecting\"). */\n const open = (session: SseSession): IO<HttpError, Opened | null> => {\n const prepared = HttpRequest.prepare(\n \"GET\",\n {\n headers: {\n ...headers,\n accept: \"text/event-stream\",\n // An empty id is how a server resets it: the header is sent only for a non-empty id.\n ...(session.lastEventId ? { \"last-event-id\": utf8ByteString(session.lastEventId) } : {}),\n },\n credentials,\n },\n { headers: defaultHeaders, credentials }\n );\n return IO.lift<HttpError, Response>(\n () =>\n Interceptors.run(\n interceptors,\n // `no-store`, as EventSource requests: a cached copy of a stream must never be replayed.\n Interceptors.request(url, { ...prepared, cache: \"no-store\", signal: session.controller.signal }),\n Interceptors.fetch\n ),\n (e: unknown) => HttpTransport.error(e, url)\n )\n .flatMap((response) => (response.ok ? IO.of(response) : HttpResponse.readFailure(response, \"text\", url)))\n .flatMap((response): IO<HttpError, Opened | null> => {\n if (response.status === 204) {\n void response.body?.cancel().catch(() => {});\n return IO.of(null);\n }\n // Not an event stream (e.g. an HTML login page or SPA fallback): fail without\n // reconnecting, instead of parsing nothing and reconnecting forever. A missing\n // content type is tolerated.\n const contentType = response.headers.get(\"content-type\");\n if (contentType !== null && mediaType(contentType) !== \"text/event-stream\") {\n void response.body?.cancel().catch(() => {});\n return IO.fail(HttpResponse.error(`Expected text/event-stream, got ${contentType}`, url, response));\n }\n return response.body === null\n ? IO.fail<HttpError, Opened>(HttpResponse.error(\"Response has no body\", url, response))\n : IO.of({ reader: response.body.getReader(), status: response.status });\n });\n };\n\n const readChunk = (reader: Reader): IO<HttpError, ReadableStreamReadResult<Uint8Array>> =>\n IO.lift(\n () => reader.read(),\n (e: unknown) => HttpTransport.error(e, url)\n );\n\n type EventStep = Option<[ServerSentEvent, SseSession]>;\n const done = IO.of<EventStep>(Option.empty());\n\n /**\n * Reconnects after the scheduled delay, or gives up (`giveUp`) when reconnection is off or the\n * `Schedule` allows no further attempt. A server `retry:` value, once received, is the delay.\n */\n const reconnectOr = (session: SseSession, giveUp: IO<HttpError, EventStep>): IO<HttpError, EventStep> => {\n if (reconnect === false) return giveUp;\n const made = session.reconnects + 1;\n if (reconnect !== true && !reconnect.allowsAttempt(made)) return giveUp;\n const ms = session.serverRetryMs ?? (reconnect === true ? session.retryMs : reconnect.delayAfter(made));\n session.reconnects = made;\n return delay(ms).flatMap(() => step(session));\n };\n\n const step = (session: SseSession): IO<HttpError, EventStep> => {\n while (session.pending.length > 0) {\n const frame = session.pending.shift() as SseFrame;\n // `id:` and `retry:` take effect even in a block that dispatches no event.\n if (frame.id !== undefined) session.lastEventId = frame.id;\n if (frame.retry !== undefined) session.serverRetryMs = Math.max(frame.retry, MIN_SERVER_RETRY_MS);\n if (frame.event !== null) {\n session.reconnects = 0;\n return IO.of(\n Option.of<[ServerSentEvent, SseSession]>([withLastEventId(frame.event, session.lastEventId), session])\n );\n }\n }\n\n const reader = session.reader;\n if (reader === null) {\n return open(session).foldM<HttpError, EventStep>(\n (error) => (HttpTransport.isRetryable(error) ? reconnectOr(session, IO.fail(error)) : IO.fail(error)),\n (opened) => {\n if (opened === null) return done;\n session.attach(opened.reader, opened.status);\n return step(session);\n }\n );\n }\n\n return readChunk(reader).foldM<HttpError, EventStep>(\n (error) => {\n session.closeConnection();\n return HttpTransport.isRetryable(error) ? reconnectOr(session, IO.fail(error)) : IO.fail(error);\n },\n (result) => {\n if (result.done) {\n session.closeConnection();\n return reconnectOr(session, done);\n }\n let frames: SseFrame[];\n try {\n frames = session.frames.push(result.value);\n } catch (e) {\n // The block limit: the server is not sending an event stream we can read; stop for good.\n session.closeConnection();\n return IO.fail(\n new HttpError(session.status, String((e as Error).message), null, url, undefined, \"decode\", e)\n );\n }\n // One push per frame: spreading a chunk that holds hundreds of thousands of frames overflows the stack.\n for (const frame of frames) session.pending.push(frame);\n return step(session);\n }\n );\n };\n\n return Stream.bracket<HttpError, HttpError, SseSession, ServerSentEvent>(\n IO.promise(async (signal: AbortSignal) => new SseSession(retry, signal)),\n (session) => Stream.unfoldEval(session, step),\n (session) => IO.sync(() => session.close())\n );\n};\n\n/** @internal */\nexport const SseClient = { stream };\n","import { IO, Option, Stream } from \"@openstage/monadyssey-core\";\nimport { HttpError } from \"./http-error\";\nimport { HttpRequest, PreparedRequest } from \"./http-request\";\nimport { HttpResponse, NO_BODY } from \"./http-response\";\nimport { HttpTransport } from \"./http-transport\";\nimport { Interceptors } from \"./interceptors\";\nimport { SseClient } from \"./sse-client\";\nimport {\n Credentials,\n Exact,\n HttpClientConfig,\n HttpInterceptor,\n Method,\n Options,\n SendOptions,\n SseOptions,\n} from \"./options\";\nimport { ServerSentEvent } from \"./sse\";\n\n/** Options for a request that expects no body back, or `Option` of one. */\ntype OptionalBody<A> = Options<A> & { empty: \"option\" };\n/** Options for a request whose body is required (the default). */\ntype RequiredBody<A> = Options<A> & { empty?: \"error\" };\n\n/**\n * A composable HTTP client that wraps the native `fetch` API, returning `IO` instances instead of\n * Promises. Each instance carries its own configuration (base URL, interceptors, default headers,\n * timeout, credentials), so different parts of an application can use independently configured\n * clients.\n *\n * Three kinds of call, by what you want back:\n * - **the decoded body** — `get`, `post`, `put`, `patch`, `delete`, `fetch` return\n * `IO<HttpError, A>`. A response with no body (`204`, an empty `200`) fails with\n * `kind: \"decode\"`, since a value was expected; pass `{ empty: \"option\" }` when absence is\n * legitimate, to get `IO<HttpError, Option<A>>`.\n * - **nothing** — `send(method, uri, { body })` returns `IO<HttpError, void>` for actions whose\n * response body you do not read (publish, archive, leave …); any body, or none, is fine.\n * - **the `Response`** — `raw(method, uri, options?)` returns `IO<HttpError, Response>` for\n * status codes, headers or streaming.\n *\n * Every non-2xx response fails with `kind: \"response\"`, whichever you use. Cancellation is\n * supported: when the IO is cancelled (via a fiber or `timeout`), the underlying `fetch` is\n * aborted through its `AbortSignal`.\n *\n * `A` is what you claim the body is; the JSON is not checked unless you pass a `transform` that\n * validates it (a schema's `parse`, say) — a throw there fails with `kind: \"decode\"`.\n *\n * **Default credentials:** `same-origin`, matching the platform `fetch` default. Set\n * `credentials: \"include\"` explicitly per-client or per-request if you need cookies to flow\n * cross-origin.\n *\n * @example\n * const api = new HttpClient({\n * baseUrl: \"https://api.example.com\",\n * interceptors: [authInterceptor],\n * timeout: 5000,\n * });\n *\n * const users = api.get<User[]>(\"/users\"); // IO<HttpError, User[]>\n * const avatar = api.get<Avatar>(\"/me/avatar\", { empty: \"option\" }); // IO<HttpError, Option<Avatar>>\n * const leave = api.send(\"POST\", `/communities/${slug}/leave`); // IO<HttpError, void>\n */\nexport class HttpClient {\n private readonly interceptors: readonly HttpInterceptor[];\n private readonly baseUrl: string | undefined;\n private readonly defaultHeaders: Record<string, string>;\n private readonly defaultTimeout: number | undefined;\n private readonly defaultCredentials: Credentials;\n\n /**\n * Creates a new HttpClient with the given configuration.\n *\n * @param {HttpClientConfig} config - Configuration for the client.\n */\n constructor(config: HttpClientConfig = {}) {\n this.interceptors = Object.freeze([...(config.interceptors ?? [])]);\n this.baseUrl = config.baseUrl;\n this.defaultHeaders = config.defaultHeaders ?? {};\n this.defaultTimeout = config.timeout;\n this.defaultCredentials = config.credentials ?? \"same-origin\";\n }\n\n /**\n * Performs a GET request and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n get<A = unknown>(uri: string, options: Omit<OptionalBody<A>, \"body\">): IO<HttpError, Option<NonNullable<A>>>;\n get<A = unknown>(uri: string, options?: Omit<RequiredBody<A>, \"body\">): IO<HttpError, A>;\n get<A = unknown>(uri: string, options: Omit<Options<A>, \"body\"> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"GET\", options);\n }\n\n /**\n * Performs a POST request and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {unknown} [body] - The request payload.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n post<A = unknown>(uri: string, body: unknown, options: OptionalBody<A>): IO<HttpError, Option<NonNullable<A>>>;\n post<A = unknown>(uri: string, body?: unknown, options?: RequiredBody<A>): IO<HttpError, A>;\n post<A = unknown>(uri: string, body?: unknown, options: Options<A> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"POST\", { ...options, body });\n }\n\n /**\n * Performs a PUT request and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {unknown} [body] - The request payload.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n put<A = unknown>(uri: string, body: unknown, options: OptionalBody<A>): IO<HttpError, Option<NonNullable<A>>>;\n put<A = unknown>(uri: string, body?: unknown, options?: RequiredBody<A>): IO<HttpError, A>;\n put<A = unknown>(uri: string, body?: unknown, options: Options<A> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"PUT\", { ...options, body });\n }\n\n /**\n * Performs a PATCH request and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {unknown} [body] - The request payload.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n patch<A = unknown>(uri: string, body: unknown, options: OptionalBody<A>): IO<HttpError, Option<NonNullable<A>>>;\n patch<A = unknown>(uri: string, body?: unknown, options?: RequiredBody<A>): IO<HttpError, A>;\n patch<A = unknown>(uri: string, body?: unknown, options: Options<A> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"PATCH\", { ...options, body });\n }\n\n /**\n * Performs a DELETE request and decodes the body. For a DELETE that answers `204 No Content`,\n * use `send(\"DELETE\", uri)` instead.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n delete<A = unknown>(uri: string, options: Omit<OptionalBody<A>, \"body\">): IO<HttpError, Option<NonNullable<A>>>;\n delete<A = unknown>(uri: string, options?: Omit<RequiredBody<A>, \"body\">): IO<HttpError, A>;\n delete<A = unknown>(uri: string, options: Omit<Options<A>, \"body\"> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"DELETE\", options);\n }\n\n /**\n * Performs a request with any method and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {Method} method - The HTTP method.\n * @param {Options<A>} [options] - Request options, including `body`; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n fetch<A = unknown>(uri: string, method: Method, options: OptionalBody<A>): IO<HttpError, Option<NonNullable<A>>>;\n fetch<A = unknown>(uri: string, method: Method, options?: RequiredBody<A>): IO<HttpError, A>;\n fetch<A = unknown>(uri: string, method: Method, options: Options<A> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, method, options);\n }\n\n /**\n * Performs a request whose response body you do not need — an action such as publish,\n * archive or leave. Succeeds with `void` for any 2xx, with or without a body (which is\n * discarded); a non-2xx response fails with `kind: \"response\"` and its body.\n *\n * @param {Method} method - The HTTP method.\n * @param {string} uri - The URL or path to request.\n * @param {SendOptions} [options] - Headers, credentials, timeout and body. Every key must be one of\n * `SendOptions`: a payload passed here by mistake (`send(\"POST\", url, article)`) is rejected at\n * compile time; it belongs in `{ body: article }`. A `GET` or `HEAD` request with a body throws\n * `TypeError` where it is built.\n * @returns {IO<HttpError, void>}\n *\n * @example\n * client.send(\"POST\", `/api/v1/communities/${slug}/leave`);\n * client.send(\"PUT\", `/api/v1/articles/${id}`, { body: article });\n * client.send(\"DELETE\", `/api/v1/passkeys/${id}`, { headers: { \"X-Step-Up\": token } });\n */\n send<O extends SendOptions>(method: Method, uri: string, options?: Exact<O, SendOptions>): IO<HttpError, void> {\n const url = this.resolveUrl(uri);\n const opts: SendOptions = options ?? {};\n return this.withTimeout(\n url,\n opts.timeout,\n this.exchange(url, method, opts).flatMap((response) =>\n response.ok\n ? IO.sync(() => void response.body?.cancel().catch(() => {}))\n : HttpResponse.readFailure(response, \"json\", url)\n )\n );\n }\n\n /**\n * Performs a request and yields the `Response` itself, for status codes, headers or streaming.\n * A non-2xx response still fails with `kind: \"response\"` (its body read into the error); a 2xx\n * `Response` is returned unread. When you only need the status or headers, cancel the body\n * (`response.body?.cancel()`) so the connection is released; `send` does this for you.\n *\n * @param {Method} method - The HTTP method.\n * @param {string} uri - The URL or path to request.\n * @param {SendOptions} [options] - Headers, credentials, timeout and body; every key must be one of\n * `SendOptions`, as for `send`.\n * @returns {IO<HttpError, Response>}\n *\n * @example\n * client.raw(\"POST\", \"/api/v1/communities\", { body: input }).map((r) => r.headers.get(\"Location\"));\n */\n raw<O extends SendOptions>(method: Method, uri: string, options?: Exact<O, SendOptions>): IO<HttpError, Response> {\n const url = this.resolveUrl(uri);\n const opts: SendOptions = options ?? {};\n return this.withTimeout(\n url,\n opts.timeout,\n this.exchange(url, method, opts).flatMap((response) =>\n response.ok ? IO.of(response) : HttpResponse.readFailure(response, \"json\", url)\n )\n );\n }\n\n /**\n * Opens a server-sent-events stream and emits each {@link ServerSentEvent} as it arrives.\n *\n * The request goes through the same pipeline as every other method, so headers (including\n * `Authorization`), credentials, interceptors, and the base URL all apply. No request timeout is\n * used — the connection is long-lived. Cancelling the terminal `IO` (via `fork`/`timeout`) aborts\n * the connection and releases resources.\n *\n * By default the stream reconnects automatically when the connection ends or fails with a\n * retryable error (network error or `5xx`), resuming with `Last-Event-ID` and re-applying headers\n * and credentials on each attempt; terminal `4xx` responses (including auth failures) end the\n * stream. See {@link SseOptions} to configure or disable this.\n *\n * @param {string} uri - The URL or path to connect to.\n * @param {SseOptions} [options] - Headers, credentials, and reconnection settings.\n * @returns {Stream<HttpError, ServerSentEvent>} A stream of parsed events.\n * @throws {RangeError} If `options.retry` is negative or `NaN`.\n *\n * @example\n * const events = client.sse(\"/events\", { headers: { Authorization: `Bearer ${token}` } });\n * await events.runForEach((event) => IO.sync(() => handle(event))).unsafeRun();\n */\n sse(uri: string, options: SseOptions = {}): Stream<HttpError, ServerSentEvent> {\n // A negative or NaN delay is a programming error; left through, `setTimeout` would treat it\n // as 0 and reconnect in a tight loop.\n if (options.retry !== undefined && !(options.retry >= 0)) {\n throw new RangeError(`HttpClient.sse: retry must be a non-negative number of milliseconds, got ${options.retry}`);\n }\n return SseClient.stream({\n url: this.resolveUrl(uri),\n headers: options.headers ?? {},\n defaultHeaders: this.defaultHeaders,\n credentials: options.credentials ?? this.defaultCredentials,\n interceptors: this.interceptors,\n reconnect: options.reconnect ?? true,\n retry: options.retry ?? 3000,\n });\n }\n\n private resolveUrl(uri: string): string {\n // Absolute only with a scheme followed by `//` (or a data:/blob: URL). `new URL()` also\n // accepts `items:batchGet` or `localhost:3000` as absolute, which would bypass `baseUrl`.\n if (!this.baseUrl || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(uri) || /^(data|blob):/i.test(uri)) return uri;\n const base = this.baseUrl.endsWith(\"/\") ? this.baseUrl.slice(0, -1) : this.baseUrl;\n const path = uri.startsWith(\"/\") ? uri : `/${uri}`;\n return `${base}${path}`;\n }\n\n /** Prepares the request, runs it through the interceptors and `fetch`, and yields the `Response`. */\n private exchange(url: string, method: Method, options: SendOptions): IO<HttpError, Response> {\n if ((method === \"GET\" || method === \"HEAD\") && options.body != null) {\n // A programming error, so it throws where the request is built instead of being dropped.\n throw new TypeError(`A ${method} request cannot have a body (${url})`);\n }\n const defaults = { headers: this.defaultHeaders, credentials: this.defaultCredentials };\n const prepare: IO<HttpError, PreparedRequest> = IO.lift(\n () => HttpRequest.prepare(method, options, defaults),\n (e: unknown) => HttpError.request(url, e)\n );\n return prepare.flatMap((prepared) =>\n IO.cancellable(\n (signal: AbortSignal) =>\n Interceptors.run(this.interceptors, Interceptors.request(url, { ...prepared, signal }), Interceptors.fetch),\n (e: unknown) => HttpTransport.error(e, url)\n )\n );\n }\n\n private withTimeout<A>(url: string, timeout: number | undefined, io: IO<HttpError, A>): IO<HttpError, A> {\n const ms = timeout ?? this.defaultTimeout;\n return ms == null ? io : io.timeout(ms, () => HttpError.timeout(url, ms));\n }\n\n private request<A>(uri: string, method: Method, options: Options<A>): IO<HttpError, A | Option<NonNullable<A>>> {\n const url = this.resolveUrl(uri);\n const { responseType = \"json\", transform = (data: unknown) => data as A, empty = \"error\" } = options;\n\n const decode = (response: Response): IO<HttpError, A | Option<NonNullable<A>>> =>\n response.ok\n ? HttpResponse.read(response, responseType, url, method).flatMap((parsed) => {\n if (parsed === NO_BODY) {\n return empty === \"option\"\n ? IO.of(Option.empty<NonNullable<A>>())\n : IO.fail(\n HttpError.decode(\n url,\n response,\n `expected a response body, got none (status ${response.status}); use send() or { empty: \"option\" }`\n )\n );\n }\n return IO.lift<HttpError, A>(\n () => transform(parsed),\n (e: unknown) => HttpError.decode(url, response, e)\n ).map((value) => (empty === \"option\" ? Option.ofNullable(value) : value));\n })\n : HttpResponse.readFailure(response, responseType, url);\n\n return this.withTimeout(url, options.timeout, this.exchange(url, method, options).flatMap(decode));\n }\n}\n"],"mappings":";;AAyBA,IAAaA,KAAmB,MAA+C;CAC7E,IAAI;EACF,OAAO,OAAO,YACZ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MAAW/E,IACNgF,MAAU,WACb3E,EAAG,GAAG1B,EAAO,MAAsB,CAAC,IACpC0B,EAAG,KACD/B,EAAU,OACRJ,GACAL,GACA,8CAA8CA,EAAS,OAAO,qCAChE,CACF,IAECwC,EAAG,WACF4E,EAAUF,CAAM,IACrB,MAAezG,EAAU,OAAOJ,GAAKL,GAAU,CAAC,CACnD,CAAC,CAAC,KAAK,MAAWmH,MAAU,WAAWrG,EAAO,WAAWK,CAAK,IAAIA,CAAM,CACzE,IACDoB,EAAa,YAAYvC,GAAUiC,GAAc5B,CAAG,CAEsC,CAAC;CACnG;AACF"}
|
|
1
|
+
{"version":3,"file":"monadyssey-fetch.mjs","names":[],"sources":["../src/http-error.ts","../src/http-request.ts","../src/http-response.ts","../src/url.ts","../src/http-transport.ts","../src/interceptors.ts","../src/sse.ts","../src/sse-client.ts","../src/http-client.ts"],"sourcesContent":["import { Option } from \"@openstage/monadyssey-core\";\nimport type { Method } from \"./options\";\n\n/**\n * How a request failed.\n * - `\"request\"`: the request could not be built — typically the body could not be serialized.\n * Nothing was sent.\n * - `\"response\"`: the server answered with a non-2xx status. `body` carries what it sent.\n * - `\"decode\"`: the server answered 2xx, but the body could not be used — it failed to parse, a\n * `transform` threw, or there was no body where one was expected (a `204`, say). `status` is the\n * real status and `cause` the underlying error.\n * - `\"network\"`: no response arrived — DNS failure, offline, CORS block, or a rejected interceptor.\n * - `\"timeout\"`: the client's `timeout` option fired before the response, or its body, completed.\n * The request may have reached the server.\n * - `\"aborted\"`: the request was aborted by something other than IO cancellation, such as an\n * interceptor's own signal (an IO cancelled via `fiber.cancel()` or `IO.timeout` ends as\n * `Cancelled`, not as an `HttpError`).\n * - `\"redirect\"`: the server answered with a redirect and the request's `redirect` setting is\n * `\"error\"`. The redirect was not followed. `status` is the redirect status, or `0` in a browser,\n * which hides it.\n * - `\"tooLarge\"`: the server answered 2xx with a body larger than the request's `maxBodyBytes`.\n * Reading stopped at the limit. `status` is the real status and `body` is `null`.\n *\n * New kinds may be added in a minor release, so give an exhaustive `switch` a `default` branch.\n */\nexport type HttpErrorKind =\n \"request\" | \"response\" | \"decode\" | \"network\" | \"timeout\" | \"aborted\" | \"redirect\" | \"tooLarge\";\n\n/** @internal What an `HttpError` holds besides its message, and how the client fills it in. */\nexport const HttpErrorFields = {\n /**\n * The response headers an `HttpError` carries. `Set-Cookie` is left out: browsers never expose it,\n * Node and Electron do, and an error that ends up in a log must not carry a session.\n */\n responseHeaders: (response: Response): Record<string, string> => {\n try {\n return Object.fromEntries(\n Array.from(response.headers.entries()).filter(([name]) => name !== \"set-cookie\" && name !== \"set-cookie2\")\n );\n } catch {\n return {};\n }\n },\n\n /** A read-only property that enumeration and `JSON.stringify` skip. */\n hidden: (value: unknown): PropertyDescriptor => ({\n value,\n enumerable: false,\n writable: false,\n configurable: true,\n }),\n\n /**\n * Records the request method on an error the client returns, unless it already has one (an\n * `HttpError` an interceptor built with its own).\n */\n withMethod: (error: HttpError, method: Method): HttpError => {\n if (error.method === undefined) (error as { method?: Method }).method = method;\n return error;\n },\n};\n\n/** @internal */\nexport const HttpErrorMessage = {\n /** Ends `text` with exactly one period, so a cause that has its own does not give \"..\". */\n sentence: (text: string): string => (text.endsWith(\".\") ? text : `${text}.`),\n\n /**\n * `text` with every character that is not plain visible text written as an escape, `\\uXXXX` or\n * `\\u{XXXXX}` by code point: controls, format characters (bidirectional marks and overrides,\n * zero-width characters, the BOM, tag characters), line and paragraph separators, lone\n * surrogates and variation selectors. A backslash is written `\\\\`, so text that spells an escape\n * cannot pass for one. A status text, a URL or a parser's message can come from the server;\n * written raw to a log or a terminal it could forge lines, move the cursor, or change what is\n * shown.\n */\n printable: (text: string): string =>\n text.replace(/[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}\\p{Cs}\\u{FE00}-\\u{FE0F}\\u{E0100}-\\u{E01EF}\\\\]/gu, (c) => {\n if (c === \"\\\\\") return \"\\\\\\\\\";\n const code = c.codePointAt(0)!;\n return code > 0xffff ? `\\\\u{${code.toString(16)}}` : `\\\\u${code.toString(16).padStart(4, \"0\")}`;\n }),\n\n describe: (cause: unknown): string =>\n cause instanceof Error\n ? cause.message\n : typeof cause === \"string\"\n ? cause\n : typeof cause === \"object\" && cause !== null && \"message\" in cause\n ? String((cause as { message: unknown }).message)\n : \"An unknown error occurred.\",\n\n /** Response errors keep the pre-3.0 wording; the other kinds carry no status. */\n format: (kind: HttpErrorKind, rawUrl: string, status: number, rawText: string, timeoutMs?: number): string => {\n const url = HttpErrorMessage.printable(rawUrl);\n const rawMessage = HttpErrorMessage.printable(rawText);\n switch (kind) {\n case \"response\":\n return `Request to '${url}' failed with status ${status} and message: ${HttpErrorMessage.sentence(rawMessage)}`;\n case \"decode\":\n return `Response from '${url}' (status ${status}) could not be decoded: ${HttpErrorMessage.sentence(rawMessage)}`;\n case \"request\":\n return `Request to '${url}' could not be sent: ${HttpErrorMessage.sentence(rawMessage)}`;\n case \"timeout\":\n return `Request to '${url}' timed out after ${timeoutMs} ms.`;\n case \"aborted\":\n return `Request to '${url}' was aborted before a response arrived: ${HttpErrorMessage.sentence(rawMessage)}`;\n case \"redirect\":\n return `Request to '${url}' was redirected (status ${status}), and redirects are refused.`;\n case \"tooLarge\":\n return `Response from '${url}' (status ${status}) is too large: ${HttpErrorMessage.sentence(rawMessage)}`;\n default:\n return `Request to '${url}' failed before a response arrived: ${HttpErrorMessage.sentence(rawMessage)}`;\n }\n },\n};\n\n/**\n * What {@link HttpError.summary} returns: the parts of an error that are safe to log. It never holds\n * the URL's path or query, the body, the headers, the message or the cause.\n */\nexport type HttpErrorSummary = {\n readonly kind: HttpErrorKind;\n readonly status: number;\n /** The request method, when the error came from an `HttpClient`. */\n readonly method?: Method;\n /** The host and port of the URL, without credentials. Absent for a relative URL. */\n readonly host?: string;\n /** The timeout that fired. Present only for `kind: \"timeout\"`. */\n readonly timeoutMs?: number;\n};\n\n/**\n * Represents an HTTP error encountered during a request.\n *\n * Extends the native `Error` class with additional context: the transport outcome (`kind`), HTTP\n * status code, raw error message, response body, request URL, response headers, and the\n * underlying cause.\n *\n * `kind` tells the two facts apart that `status` alone cannot: \"the server said 500\" is\n * `kind: \"response\", status: 500`, while \"nothing answered\" is `kind: \"network\", status: 0`.\n * For every kind other than `\"response\"`, `\"decode\"`, `\"redirect\"` and `\"tooLarge\"`, `status` is `0`;\n * `body` is `null` except for `\"response\"`.\n *\n * `message`, `rawMessage`, `body`, `headers`, `url` and `cause` hold what the server and the request\n * contained, which may be sensitive (a token in a query string, an error page echoing input, part of\n * a body in a parse error, a request header value the platform rejected); log {@link HttpError.summary} instead outside a trusted sink.\n * `Set-Cookie` is never carried.\n *\n * @example\n * client.post(\"/payments\", payment).mapErr((error) =>\n * error.kind === \"response\"\n * ? { kind: \"rejected\", status: error.status }\n * : { kind: \"outcomeUnknown\" } // the request may or may not have reached the server\n * );\n */\nexport class HttpError extends Error {\n /** The transport outcome. See {@link HttpErrorKind}. */\n public readonly kind: HttpErrorKind;\n /** The HTTP status code (`\"response\"` and `\"decode\"`), or `0` when no response arrived. */\n public readonly status: number;\n declare public readonly rawMessage: string;\n /** The parsed response body, or `null` when none was parsed. */\n declare public readonly body: unknown;\n declare public readonly url: string;\n /** The request method. Set by `HttpClient` on every error it returns. */\n public readonly method?: Method;\n declare public readonly headers?: Record<string, string>;\n /** The underlying exception, when there was one (a `TypeError` from `fetch`, a parse error, an abort reason). */\n declare public readonly cause?: unknown;\n /** The timeout that fired, in milliseconds. Set only when `kind === \"timeout\"`. */\n public readonly timeoutMs?: number;\n\n constructor(\n status: number,\n rawMessage: string,\n body: unknown,\n url: string,\n headers?: Record<string, string>,\n kind: HttpErrorKind = \"response\",\n cause?: unknown,\n timeoutMs?: number\n ) {\n super(HttpErrorMessage.format(kind, url, status, rawMessage, timeoutMs));\n this.name = \"HttpError\";\n this.kind = kind;\n this.status = status;\n this.timeoutMs = timeoutMs;\n // What the request and the server contained stays readable but is not enumerable, so\n // `JSON.stringify` and logger serializers that copy own enumerable properties leave it out.\n Object.defineProperties(this, {\n rawMessage: HttpErrorFields.hidden(rawMessage),\n body: HttpErrorFields.hidden(body),\n url: HttpErrorFields.hidden(url),\n headers: HttpErrorFields.hidden(headers),\n cause: HttpErrorFields.hidden(cause),\n });\n }\n\n /**\n * An error for a request that received no response: DNS failure, offline, CORS block, or a\n * rejected interceptor. `status` is `0` and `body` is `null`.\n *\n * @param {string} url The request URL.\n * @param {unknown} cause The underlying exception (typically the `TypeError` thrown by `fetch`).\n */\n static network(url: string, cause: unknown): HttpError {\n return new HttpError(0, HttpErrorMessage.describe(cause), null, url, undefined, \"network\", cause);\n }\n\n /**\n * An error for a request whose `timeout` option fired before the response, or its body, completed.\n * `status` is `0`, `body` is `null`, and `timeoutMs` records the timeout.\n *\n * @param {string} url The request URL.\n * @param {number} after The timeout in milliseconds.\n */\n static timeout(url: string, after: number): HttpError {\n return new HttpError(0, `Request timed out after ${after} ms`, null, url, undefined, \"timeout\", undefined, after);\n }\n\n /**\n * An error for a 2xx response whose body could not be used: it failed to parse, a `transform`\n * threw, or there was no body where one was expected. `status` is the real status, `body` is\n * `null`, and `cause` carries the underlying error.\n *\n * @param {string} url The request URL.\n * @param {Response} response The response that could not be decoded.\n * @param {unknown} cause The parse error, the value a `transform` threw, or a description.\n */\n static decode(url: string, response: Response, cause: unknown): HttpError {\n return new HttpError(\n response.status,\n HttpErrorMessage.describe(cause),\n null,\n url,\n HttpErrorFields.responseHeaders(response),\n \"decode\",\n cause\n );\n }\n\n /**\n * An error for a request that could not be built, so nothing was sent — typically a body that\n * could not be serialized. `status` is `0` and `body` is `null`.\n *\n * @param {string} url The request URL.\n * @param {unknown} cause The underlying exception (typically a `TypeError` from `JSON.stringify`).\n */\n static request(url: string, cause: unknown): HttpError {\n return new HttpError(0, HttpErrorMessage.describe(cause), null, url, undefined, \"request\", cause);\n }\n\n /**\n * An error for a request aborted by something other than IO cancellation, such as an\n * interceptor aborting the signal. `status` is `0` and `body` is `null`.\n *\n * @param {string} url The request URL.\n * @param {unknown} [cause] The abort reason, if any.\n */\n static aborted(url: string, cause?: unknown): HttpError {\n return new HttpError(0, HttpErrorMessage.describe(cause), null, url, undefined, \"aborted\", cause);\n }\n\n /**\n * An error for a redirect that the request's `redirect: \"error\"` setting refused. The redirect\n * was not followed. `status` is the redirect status (`0` in a browser, which hides it), `body` is\n * `null`, and `headers` are the redirect's own (its `Location`, where the platform exposes it).\n *\n * @param {string} url The request URL.\n * @param {Response} response The redirect response.\n */\n static redirect(url: string, response: Response): HttpError {\n return new HttpError(\n response.status,\n \"Redirects are refused\",\n null,\n url,\n HttpErrorFields.responseHeaders(response),\n \"redirect\"\n );\n }\n\n /**\n * An error for a 2xx response whose body is larger than the request's `maxBodyBytes`. Reading\n * stopped at the limit. `status` is the real status and `body` is `null`.\n *\n * @param {string} url The request URL.\n * @param {Response} response The response whose body was too large.\n * @param {number} maxBodyBytes The limit, in bytes.\n */\n static tooLarge(url: string, response: Response, maxBodyBytes: number): HttpError {\n return new HttpError(\n response.status,\n `the body is larger than ${maxBodyBytes} bytes`,\n null,\n url,\n HttpErrorFields.responseHeaders(response),\n \"tooLarge\"\n );\n }\n\n /**\n * Narrows the `unknown` error body to a concrete type using a runtime type guard.\n * Returns `Some(body)` if the guard passes, `None` otherwise — so the narrow is *checked*,\n * not asserted. This keeps the unsafe cast out of consumer code: the body stays `unknown`\n * by default (forcing a conscious narrow), and this is the safe way to perform it.\n *\n * @template T The expected body shape.\n * @param {(x: unknown) => x is T} guard A type guard validating the body's shape.\n * @returns {Option<T>} `Some(body)` if the guard matches, `None` otherwise.\n *\n * @example\n * interface ApiError { code: string; message: string }\n * const isApiError = (x: unknown): x is ApiError =>\n * typeof x === \"object\" && x !== null && \"code\" in x && \"message\" in x;\n *\n * httpError.bodyAs(isApiError).fold(\n * () => \"unrecognized error shape\",\n * (e) => `${e.code}: ${e.message}`\n * );\n */\n bodyAs<T>(guard: (x: unknown) => x is T): Option<NonNullable<T>> {\n return guard(this.body) ? Option.ofNullable(this.body) : Option.empty();\n }\n\n /**\n * The parts of this error that are safe to log: the kind, the status, the method, the host (with\n * its port, without credentials) and, for a timeout, `timeoutMs`. It never holds the URL's path or\n * query, the body, the headers, the message or the cause.\n *\n * @returns {HttpErrorSummary} The summary.\n *\n * @example\n * client.get(\"/users/42?token=…\").tapErr((error) => logger.warn(\"user lookup failed\", error.summary()));\n * // { kind: \"response\", status: 404, method: \"GET\", host: \"api.example.com\" }\n */\n summary(): HttpErrorSummary {\n let host: string | undefined;\n try {\n host = new URL(this.url).host || undefined;\n } catch {\n host = undefined;\n }\n return {\n kind: this.kind,\n status: this.status,\n ...(this.method !== undefined ? { method: this.method } : {}),\n ...(host !== undefined ? { host } : {}),\n ...(this.timeoutMs !== undefined ? { timeoutMs: this.timeoutMs } : {}),\n };\n }\n}\n","import { Credentials, Method, Options } from \"./options\";\n\n/** @internal */\nexport interface RequestDefaults {\n readonly headers: Record<string, string>;\n readonly credentials: Credentials;\n}\n\n/** @internal */\nexport interface PreparedRequest {\n readonly method: Method;\n readonly headers: Record<string, string>;\n readonly credentials: Credentials;\n readonly body: BodyInit | undefined;\n}\n\n/** @internal */\nexport const HttpRequest = {\n /** Bodies `fetch` sends as-is: never JSON-encoded, never given an automatic content type. */\n isNativeBody: (body: unknown): boolean =>\n typeof body !== \"object\" ||\n body === null ||\n body instanceof FormData ||\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof URLSearchParams ||\n (typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream) ||\n ArrayBuffer.isView(body),\n\n normalizeHeaders: (headers: Record<string, string | undefined>): Record<string, string> =>\n Object.fromEntries(\n Object.entries(headers)\n .filter((entry): entry is [string, string] => entry[1] !== undefined)\n .map(([key, value]) => [key.toLowerCase(), value])\n ),\n\n /** `FormData` must carry no content type so the browser can set the multipart boundary. */\n withContentType: (headers: Record<string, string>, body: unknown): Record<string, string> => {\n if (body instanceof FormData) {\n const { \"content-type\": _dropped, ...rest } = headers;\n return rest;\n }\n const autoJson =\n body != null && typeof body === \"object\" && !HttpRequest.isNativeBody(body) && !(\"content-type\" in headers);\n return autoJson ? { ...headers, \"content-type\": \"application/json\" } : headers;\n },\n\n /**\n * `application/json`, with or without parameters (`; charset=utf-8`), or any `+json` suffix type\n * (`application/merge-patch+json`, `application/vnd.api+json`). Matching the exact string alone\n * would send an object declared as one of the others as `\"[object Object]\"`.\n */\n isJsonContentType: (contentType: string): boolean => {\n const media = contentType.split(\";\")[0].trim().toLowerCase();\n return media === \"application/json\" || media.endsWith(\"+json\");\n },\n\n serializeBody: (method: Method, body: unknown, headers: Record<string, string>): BodyInit | undefined =>\n method === \"GET\" || method === \"HEAD\" || body == null\n ? undefined\n : HttpRequest.isNativeBody(body)\n ? (body as BodyInit)\n : HttpRequest.isJsonContentType(headers[\"content-type\"])\n ? JSON.stringify(body)\n : (body as BodyInit),\n\n /** Per-request headers win over defaults; names are lowercased; the body follows the content type. */\n prepare: (method: Method, options: Options<unknown>, defaults: RequestDefaults): PreparedRequest => {\n const headers = HttpRequest.withContentType(\n HttpRequest.normalizeHeaders({ ...defaults.headers, ...(options.headers ?? {}) }),\n options.body\n );\n return {\n method,\n headers,\n credentials: options.credentials ?? defaults.credentials,\n body: HttpRequest.serializeBody(method, options.body, headers),\n };\n },\n};\n","import { IO, Option } from \"@openstage/monadyssey-core\";\nimport { HttpError, HttpErrorFields } from \"./http-error\";\nimport { Method, ResponseType } from \"./options\";\n\ntype BodyReader = (response: Response) => Promise<unknown>;\n\nconst bodyReaders = {\n json: (response) => response.json(),\n text: (response) => response.text(),\n blob: (response) => response.blob(),\n arrayBuffer: (response) => response.arrayBuffer(),\n formData: (response) => response.formData(),\n} satisfies Record<ResponseType, BodyReader>;\n\n/**\n * What {@link HttpResponse.read} yields when there is no body at all — distinct from a JSON body\n * that is literally `null`.\n *\n * @internal\n */\nexport const NO_BODY: unique symbol = Symbol(\"HttpResponse.noBody\");\n\n/** What {@link HttpResponse.readBytes} yields for a body larger than the limit. */\nconst TOO_LARGE: unique symbol = Symbol(\"HttpResponse.tooLarge\");\n\n/**\n * How much of an error (non-2xx) body is read when the request sets no `maxBodyBytes`. An error\n * body is a diagnostic, so a server that sends an endless one must not hold the request or grow\n * memory without bound.\n */\nconst DEFAULT_ERROR_BODY_BYTES = 64 * 1024;\n\n/** One piece of a body, read one at a time; `stop` releases the source early. */\ninterface Chunks {\n next(): Promise<IteratorResult<unknown>>;\n stop(): void;\n}\n\n/** Decodes bytes read under a limit as the platform's own body readers would. */\nconst fromBytes = {\n json: (bytes) => {\n const text = HttpResponse.utf8(bytes);\n return text.trim() === \"\" ? NO_BODY : JSON.parse(text);\n },\n text: (bytes) => HttpResponse.utf8(bytes),\n blob: (bytes, response) => new Blob([bytes], { type: response.headers.get(\"content-type\") ?? \"\" }),\n arrayBuffer: (bytes) => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),\n formData: (bytes, response) =>\n new Response(bytes, { headers: { \"content-type\": response.headers.get(\"content-type\") ?? \"\" } }).formData(),\n} satisfies Record<ResponseType, (bytes: Uint8Array<ArrayBuffer>, response: Response) => unknown>;\n\n/** @internal */\nexport const HttpResponse = {\n headers: HttpErrorFields.responseHeaders,\n\n /** The server answered 2xx but the body could not be used (`kind: \"decode\"`). */\n error: (cause: unknown, url: string, response: Response): HttpError => HttpError.decode(url, response, cause),\n\n /** The server answered with a non-2xx status; the parsed body travels with the error. */\n failure: (response: Response, body: unknown, url: string): HttpError =>\n new HttpError(response.status, response.statusText, body, url, HttpResponse.headers(response)),\n\n /** An own-property lookup, so an untyped `responseType` such as `\"toString\"` is rejected. */\n readerFor: (responseType: ResponseType): Option<BodyReader> =>\n Object.prototype.hasOwnProperty.call(bodyReaders, responseType)\n ? Option.of(bodyReaders[responseType])\n : Option.empty<BodyReader>(),\n\n /**\n * Reads a JSON body, yielding `NO_BODY` for an empty one. Responses that implement only `json()` —\n * hand-rolled mocks in consumers' tests — are read with it.\n */\n readJson: async (response: Response): Promise<unknown> => {\n if (typeof response.text !== \"function\") return response.json();\n const text = await response.text();\n return text.trim() === \"\" ? NO_BODY : JSON.parse(text);\n },\n\n utf8: (bytes: Uint8Array): string => new TextDecoder().decode(bytes),\n\n /**\n * Whether a body chunk is bytes. Read from the type tag, not with `instanceof`: a body created in\n * another realm (a test DOM, an iframe, a `vm` context) carries that realm's `Uint8Array`. A Node\n * `Buffer` is a `Uint8Array` too.\n */\n isBytes: (value: unknown): value is Uint8Array => Object.prototype.toString.call(value) === \"[object Uint8Array]\",\n\n /** The pieces of a body that can be read one at a time: a `ReadableStream`, or an async iterable (a Node `Readable`). */\n chunksOf: (body: unknown): Chunks | undefined => {\n if (typeof (body as { getReader?: unknown } | null)?.getReader === \"function\") {\n const reader = (body as ReadableStream<unknown>).getReader();\n return { next: () => reader.read(), stop: () => void reader.cancel().catch(() => {}) };\n }\n if (typeof (body as { [Symbol.asyncIterator]?: unknown } | null)?.[Symbol.asyncIterator] === \"function\") {\n const iterator = (body as AsyncIterable<unknown>)[Symbol.asyncIterator]();\n return {\n next: () => iterator.next(),\n stop: () => {\n try {\n void Promise.resolve(iterator.return?.()).catch(() => {});\n } catch {\n // The body is being abandoned; a source that cannot return has nothing left to release.\n }\n },\n };\n }\n return undefined;\n },\n\n /**\n * Reads the body as bytes, and stops once it passes `limit`: reading is cancelled and `TOO_LARGE`\n * is returned. A `Content-Length` already above the limit returns `TOO_LARGE` without reading. A\n * piece that is not bytes cannot be counted, so it fails the read rather than slipping past the\n * limit.\n */\n readBytes: async (response: Response, limit: number): Promise<Uint8Array | typeof TOO_LARGE> => {\n const chunks = response.body === null ? undefined : HttpResponse.chunksOf(response.body);\n const declared = Number(response.headers?.get(\"content-length\") ?? undefined);\n if (declared > limit) {\n chunks?.stop();\n return TOO_LARGE;\n }\n if (chunks === undefined) return new Uint8Array(0);\n const pieces: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await chunks.next();\n if (done === true) break;\n if (!HttpResponse.isBytes(value)) {\n chunks.stop();\n throw new TypeError(\"a response body chunk is not bytes\");\n }\n size += value.byteLength;\n if (size > limit) {\n chunks.stop();\n return TOO_LARGE;\n }\n pieces.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const piece of pieces) {\n bytes.set(piece, offset);\n offset += piece.byteLength;\n }\n return bytes;\n },\n\n /** A finite limit: one that bytes are counted against. */\n finite: (limit: number | undefined): limit is number => limit !== undefined && limit !== Infinity,\n\n /**\n * Whether the body can be counted as it is read: no body at all, a `ReadableStream`, or an async\n * iterable. Checking does not touch the body.\n */\n countable: (response: Response): boolean => {\n const body: unknown = response.body;\n return (\n body === null ||\n typeof (body as { getReader?: unknown } | undefined)?.getReader === \"function\" ||\n typeof (body as { [Symbol.asyncIterator]?: unknown } | undefined)?.[Symbol.asyncIterator] === \"function\"\n );\n },\n\n /**\n * Reads a successful body. Yields `NO_BODY` when there is none to read: `204`/`205`, a `HEAD`\n * request, or an empty body under `\"json\"` (e.g. `201 Created` / `202 Accepted` with nothing\n * attached). A body that cannot be parsed fails with `kind: \"decode\"`.\n */\n read: (\n response: Response,\n responseType: ResponseType,\n url: string,\n method?: Method,\n maxBodyBytes?: number\n ): IO<HttpError, unknown | typeof NO_BODY> =>\n IO.from(HttpResponse.readerFor(responseType), () =>\n HttpResponse.error(`Unsupported response type: ${responseType}`, url, response)\n ).flatMap((read) =>\n IO.lift(\n async () => {\n if (response.status === 204 || response.status === 205 || method === \"HEAD\") return NO_BODY;\n if (HttpResponse.finite(maxBodyBytes)) {\n // A limit that cannot be counted fails closed rather than reading the body whole.\n if (!HttpResponse.countable(response)) {\n throw new TypeError(\"maxBodyBytes needs a response whose body is a ReadableStream\");\n }\n const bytes = await HttpResponse.readBytes(response, maxBodyBytes);\n if (bytes === TOO_LARGE) throw TOO_LARGE;\n return fromBytes[responseType](bytes as Uint8Array<ArrayBuffer>, response);\n }\n if (responseType !== \"json\") return read(response);\n return HttpResponse.readJson(response);\n },\n (cause) =>\n cause === TOO_LARGE\n ? HttpError.tooLarge(url, response, maxBodyBytes!)\n : HttpResponse.error(cause, url, response)\n )\n ),\n\n /**\n * Fails with the error for a non-2xx response. The body is read leniently, so an error page\n * that is not JSON (an HTML 502 from a proxy, say) still travels with the error and the message\n * stays the status text: under `\"json\"` the text is parsed when it is JSON and kept as a string\n * otherwise; an unreadable or empty body is `null`. At most `maxBodyBytes` of it is read, or\n * 64 KiB when the request sets none; a longer body is dropped (`null`).\n */\n readFailure: (\n response: Response,\n responseType: ResponseType,\n url: string,\n maxBodyBytes?: number\n ): IO<HttpError, never> =>\n IO.promise<unknown>(async () => {\n const limit = maxBodyBytes ?? DEFAULT_ERROR_BODY_BYTES;\n try {\n // A body that cannot be counted is dropped. Only a hand-rolled response with no `body` at\n // all (a test double) is still read whole under the default cap.\n if (HttpResponse.finite(limit) && !HttpResponse.countable(response)) {\n if (response.body !== undefined || HttpResponse.finite(maxBodyBytes)) return null;\n } else if (HttpResponse.finite(limit)) {\n // An error body past the limit is dropped; the status still reaches the caller.\n const bytes = await HttpResponse.readBytes(response, limit);\n if (bytes === TOO_LARGE) return null;\n if (responseType !== \"json\") return await fromBytes[responseType](bytes as Uint8Array<ArrayBuffer>, response);\n const text = HttpResponse.utf8(bytes);\n if (text.trim() === \"\") return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n if (responseType !== \"json\") {\n return await HttpResponse.readerFor(responseType).fold(\n async () => null,\n (read) => read(response)\n );\n }\n // A response without `text()` (a hand-rolled mock) can only be read as JSON.\n if (typeof response.text !== \"function\") return await response.json();\n const text = await response.text();\n if (text.trim() === \"\") return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n } catch {\n return null;\n }\n }).flatMap((body) => IO.fail(HttpResponse.failure(response, body, url))),\n};\n","import { HttpError } from \"./http-error\";\n\n/** @internal How the client reads and checks request URLs before sending them. */\nexport const HttpUrl = {\n /**\n * The base URL a browser's `fetch` reads every URL against: the document's base URL (which a\n * `<base href>` changes), else the page's address. None outside a browser.\n */\n pageBase: (): string | undefined => {\n const scope = globalThis as { document?: { baseURI?: unknown }; location?: { href?: unknown } };\n try {\n const base = scope.document?.baseURI;\n if (typeof base === \"string\") return base;\n const href = scope.location?.href;\n return typeof href === \"string\" ? href : undefined;\n } catch {\n // A runtime with no page address may throw when it is read (Deno without `--location`).\n return undefined;\n }\n },\n\n /** `url` read by the WHATWG parser, against `base` when given; `undefined` when it cannot be read. */\n parse: (url: string, base?: string): URL | undefined => {\n try {\n return new URL(url, base);\n } catch {\n return undefined;\n }\n },\n\n /**\n * `url` read as `fetch` will: against the page's base URL in a browser, on its own elsewhere. A\n * browser reads `https:host/x` against the page too, as a path on the page's own origin.\n */\n parseForFetch: (url: string): URL | undefined => {\n const base = HttpUrl.pageBase();\n return base === undefined ? HttpUrl.parse(url) : HttpUrl.parse(url, base);\n },\n\n /**\n * The `kind: \"request\"` error for a URL that carries credentials, or `undefined`. The URL is read\n * by the WHATWG parser that `fetch` uses, so every form it accepts is caught (leading whitespace,\n * tabs, missing slashes, backslashes, protocol-relative). The error's URL leaves the credentials\n * out.\n */\n refuseCredentials: (url: string): HttpError | undefined => {\n // Read with no base, as Node's `fetch` does, and against a base, as a browser's does: `http:/u:p@h`\n // is an absolute URL with credentials on its own, but a path against an `http:` base. Outside a\n // browser a placeholder base still recognises a protocol-relative `//user:password@host`.\n for (const parsed of [HttpUrl.parse(url), HttpUrl.parse(url, HttpUrl.pageBase() ?? \"http://localhost/\")]) {\n if (parsed === undefined || (parsed.username === \"\" && parsed.password === \"\")) continue;\n parsed.username = \"\";\n parsed.password = \"\";\n return HttpError.request(\n parsed.href,\n new TypeError(\"the URL carries credentials; send them in a header instead\")\n );\n }\n return undefined;\n },\n\n /**\n * The origins of an `allowedOrigins` list. An entry must be exactly an origin\n * (`https://api.example.com`, a port allowed); a path, query, fragment or credentials throws\n * `RangeError`.\n */\n originsOf: (entries: readonly string[]): ReadonlySet<string> => {\n const origins = new Set<string>();\n for (const entry of entries) {\n const parsed = HttpUrl.parse(entry);\n const exact =\n parsed !== undefined &&\n parsed.origin !== \"null\" &&\n parsed.pathname === \"/\" &&\n parsed.search === \"\" &&\n parsed.hash === \"\" &&\n parsed.username === \"\" &&\n parsed.password === \"\" &&\n !/\\/[^/]/.test(entry.replace(/^[a-z][a-z\\d+.-]*:\\/\\//i, \"\"));\n if (!exact) {\n throw new RangeError(\n `HttpClient: allowedOrigins entries must be origins such as \"https://api.example.com\", got ${entry}`\n );\n }\n origins.add(parsed.origin);\n }\n return origins;\n },\n\n /** Whether `url` is read by `fetch` as one of `allowed`'s origins. */\n allowedOrigin: (url: string, allowed: ReadonlySet<string>): boolean => {\n const parsed = HttpUrl.parseForFetch(url);\n return parsed !== undefined && allowed.has(parsed.origin);\n },\n\n /** The `kind: \"request\"` error for a URL whose origin is not in `allowed`, or `undefined`. */\n refuseOrigin: (url: string, allowed: ReadonlySet<string> | undefined): HttpError | undefined => {\n if (allowed === undefined || HttpUrl.allowedOrigin(url, allowed)) return undefined;\n const parsed = HttpUrl.parseForFetch(url);\n const origin = parsed === undefined ? \"an unreadable URL\" : `the origin ${parsed.origin}`;\n return HttpError.request(url, new TypeError(`${origin} is not in allowedOrigins`));\n },\n\n /** The first reason to refuse `url` before sending it: credentials, then its origin. */\n refuseUrl: (url: string, allowed: ReadonlySet<string> | undefined): HttpError | undefined =>\n HttpUrl.refuseCredentials(url) ?? HttpUrl.refuseOrigin(url, allowed),\n};\n","import { HttpError } from \"./http-error\";\nimport type { Send } from \"./interceptors\";\nimport { Redirect } from \"./options\";\nimport { HttpUrl } from \"./url\";\n\n/** The statuses `fetch` follows as redirects; a `304` (or `300`) is not one. */\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\n/** @internal */\nexport const HttpTransport = {\n /** Whether `e` is the platform's abort error. */\n isAbort: (e: unknown): boolean =>\n typeof e === \"object\" && e !== null && \"name\" in e && (e as { name: unknown }).name === \"AbortError\",\n\n /** An interceptor may reject with a ready-made `HttpError`; it is passed through untouched. */\n error: (e: unknown, url: string): HttpError =>\n e instanceof HttpError ? e : HttpTransport.isAbort(e) ? HttpError.aborted(url, e) : HttpError.network(url, e),\n\n /**\n * The `redirect` init for a setting: `\"error\"` sends `\"manual\"`, so the client sees the redirect\n * and fails it as `kind: \"redirect\"` (the platform's own `\"error\"` rejects with a `TypeError` that\n * looks like a network failure). No setting leaves the platform default.\n */\n redirectInit: (redirect: Redirect | undefined): { redirect?: RequestRedirect } =>\n redirect === undefined ? {} : { redirect: redirect === \"error\" ? \"manual\" : \"follow\" },\n\n /**\n * The end of the chain checks the URL `fetch` will actually get, so an interceptor cannot add\n * credentials to it, or send it to an origin outside `allowed`, either. Under `allowed`, `fetch`\n * gets the absolute URL that was checked, so it has nothing left to read differently.\n */\n guardUrl:\n (send: Send, allowed: ReadonlySet<string> | undefined): Send =>\n (request) => {\n const url: unknown = request.url;\n if (typeof url !== \"string\") {\n return Promise.reject(HttpError.request(\"[not a string]\", new TypeError(\"the request URL is not a string\")));\n }\n const refused = HttpUrl.refuseUrl(url, allowed);\n if (refused !== undefined) return Promise.reject(refused);\n return send(allowed === undefined ? request : { ...request, url: HttpUrl.parseForFetch(url)!.href });\n },\n\n /**\n * The end of the chain under a setting: `\"error\"` sends `redirect: \"manual\"` whatever the\n * interceptors left in `init`, so an interceptor that rebuilds or changes it cannot turn the\n * refusal off.\n */\n enforceRedirect: (redirect: Redirect | undefined, send: Send): Send =>\n redirect === \"error\" ? (request) => send({ ...request, init: { ...request.init, redirect: \"manual\" } }) : send,\n\n /**\n * The error for a response that is a redirect the setting refuses, or `undefined`. Under\n * `\"manual\"`, Node returns the redirect itself and a browser returns an `opaqueredirect` response.\n * A response that was already followed (`redirected`, from a `fetch` that ignores\n * `init.redirect`) is refused too.\n */\n refusedRedirect: (redirect: Redirect | undefined, response: Response, url: string): HttpError | undefined => {\n if (redirect !== \"error\") return undefined;\n if (response.type !== \"opaqueredirect\" && !REDIRECT_STATUSES.has(response.status) && response.redirected !== true) {\n return undefined;\n }\n void response.body?.cancel().catch(() => {});\n return HttpError.redirect(url, response);\n },\n\n /** A timeout means the caller stopped waiting and an abort means someone wanted it stopped: neither is retried. */\n isRetryable: (error: HttpError): boolean =>\n error.kind === \"network\" || (error.kind === \"response\" && error.status >= 500),\n};\n","import { HttpError } from \"./http-error\";\nimport { HttpInterceptor, InterceptedRequest } from \"./options\";\n\n/** @internal */\nexport type Send = (request: InterceptedRequest) => Promise<Response>;\n\n/** @internal */\nexport const Interceptors = {\n /** A right fold, so the first registered interceptor is outermost. */\n run: (interceptors: readonly HttpInterceptor[], request: InterceptedRequest, send: Send): Promise<Response> =>\n interceptors.reduceRight<Send>((next, interceptor) => (r) => interceptor.intercept(r, next), send)(request),\n\n /**\n * Builds the request interceptors see: headers normalised to a `Headers` instance. A header the\n * platform rejects (a CR, LF or NUL in a value, say) is a `kind: \"request\"` error: the request could\n * not be built and nothing was sent, so it is not retried as a network failure. So is an absolute\n * URL that carries credentials (`https://user:password@host/`), which `fetch` refuses; the error's\n * URL leaves the credentials out.\n */\n request: (\n url: string,\n init: Omit<RequestInit, \"headers\"> & { headers: Record<string, string> }\n ): InterceptedRequest => {\n let headers: Headers;\n try {\n headers = new Headers(init.headers);\n } catch (e) {\n throw HttpError.request(url, e);\n }\n return { url, init: { ...init, headers } };\n },\n\n /**\n * The end of the chain: `custom`, or the global `fetch` as it is when the request is sent. Called\n * without a receiver, as the platform `fetch` requires.\n */\n transport:\n (custom: typeof globalThis.fetch | undefined): Send =>\n (request: InterceptedRequest): Promise<Response> =>\n (custom ?? fetch)(request.url, request.init),\n};\n","import { List, Stream } from \"@openstage/monadyssey-core\";\nimport type { Pipe } from \"@openstage/monadyssey-core\";\n\n/**\n * A single server-sent event parsed from a text/event-stream response.\n *\n * @property id - The last event id in effect when the event was dispatched — set by the event's\n * own `id:` field or by an earlier one, as the spec's `MessageEvent.lastEventId`. Absent until\n * the server sends an `id:`; the empty string after the server resets it. Used to resume a stream.\n * @property event - The event type. Defaults to `\"message\"` when the server sends no `event:` field.\n * @property data - The event payload. Multiple `data:` lines are joined with a newline.\n * @property retry - The reconnection time in milliseconds, if the server sent a `retry:` field.\n */\nexport interface ServerSentEvent {\n readonly id?: string;\n readonly event: string;\n readonly data: string;\n readonly retry?: number;\n}\n\n/**\n * The effects of one block (the lines up to a blank line). A block may set the last event id or\n * the reconnection time without dispatching an event — e.g. a lone `retry: 5000` or `id: 42`.\n *\n * @internal\n */\nexport interface SseFrame {\n /** The event to dispatch, or `null` when the block has no `data:` field. */\n readonly event: ServerSentEvent | null;\n /** The last `id:` value in the block, if any. The empty string resets the last event id. */\n readonly id?: string;\n /** The last valid `retry:` value in the block, if any. */\n readonly retry?: number;\n}\n\n/** @internal How a block of event-stream text becomes a frame and an event. */\nexport const SseEvents = {\n /** One block (the text between two blank lines) as a frame. */\n parseBlock: (block: string): SseFrame => {\n let event = \"\";\n let id: string | undefined;\n let retry: number | undefined;\n const data: string[] = [];\n\n for (const line of block.split(\"\\n\")) {\n if (line === \"\" || line.startsWith(\":\")) continue; // blank line or comment\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n switch (field) {\n case \"event\":\n event = value;\n break;\n case \"data\":\n data.push(value);\n break;\n case \"id\":\n // Per the spec, an id containing NUL is ignored.\n if (!value.includes(\"\\0\")) id = value;\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) retry = Number.parseInt(value, 10);\n break;\n default:\n break;\n }\n }\n\n return {\n event:\n data.length === 0\n ? null\n : {\n // An empty `event:` field means the default type, not the empty string.\n event: event || \"message\",\n data: data.join(\"\\n\"),\n ...(id !== undefined ? { id } : {}),\n ...(retry !== undefined ? { retry } : {}),\n },\n ...(id !== undefined ? { id } : {}),\n ...(retry !== undefined ? { retry } : {}),\n };\n },\n\n /**\n * `event` with `id` set to the last event id in effect (the spec's `lastEventId`), which persists\n * across events until the server changes it.\n */\n withLastEventId: (event: ServerSentEvent, lastEventId: string | undefined): ServerSentEvent => {\n const { id: _blockId, ...rest } = event;\n return lastEventId === undefined ? rest : { ...rest, id: lastEventId };\n },\n};\n\n/**\n * Reassembles a byte stream into complete blocks; partial input and split multi-byte characters\n * are buffered. Call `reset` when a new connection begins. With a `limit`, an unterminated block\n * longer than that many characters throws `RangeError` (a hostile or broken server must not make the\n * buffer grow without bound); by default there is no limit.\n *\n * @internal\n */\nexport class FrameBuffer {\n private decoder = new TextDecoder(\"utf-8\");\n /**\n * The unfinished block, in the pieces it arrived in. Joining them only once a block ends keeps a\n * long block that arrives in tiny chunks linear: appending to one string and searching it would\n * copy everything buffered so far on every chunk.\n */\n private pieces: string[] = [];\n private size = 0;\n /** The last character buffered, so a `\\n\\n` split across two chunks is found. */\n private lastChar = \"\";\n\n constructor(private readonly limit: number = Infinity) {}\n /** The previous chunk ended in CR: a LF opening the next chunk belongs to that CRLF. */\n private skipLeadingLF = false;\n\n push(chunk: Uint8Array): SseFrame[] {\n let text = this.decoder.decode(chunk, { stream: true });\n if (text.length === 0) return [];\n if (this.skipLeadingLF && text.startsWith(\"\\n\")) text = text.slice(1);\n // A trailing CR ends its line now — holding it back until the next chunk would delay every\n // event on CR-only streams by a chunk. If a LF follows, it is skipped above.\n this.skipLeadingLF = text.endsWith(\"\\r\");\n if (text.length === 0) return [];\n text = text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n // A block ends at the first `\\n\\n`, which may straddle the buffered text and this chunk.\n const ends = text.indexOf(\"\\n\\n\") !== -1 || (this.lastChar === \"\\n\" && text.startsWith(\"\\n\"));\n if (!ends) {\n this.pieces.push(text);\n this.size += text.length;\n this.lastChar = text[text.length - 1];\n this.checkLimit();\n return [];\n }\n this.pieces.push(text);\n const blocks = this.pieces.join(\"\").split(\"\\n\\n\");\n const rest = blocks.pop() ?? \"\";\n this.pieces = rest === \"\" ? [] : [rest];\n this.size = rest.length;\n this.lastChar = rest === \"\" ? \"\" : rest[rest.length - 1];\n this.checkLimit();\n return blocks.map(SseEvents.parseBlock);\n }\n\n reset(): void {\n this.decoder = new TextDecoder(\"utf-8\");\n this.pieces = [];\n this.size = 0;\n this.lastChar = \"\";\n this.skipLeadingLF = false;\n }\n\n private checkLimit(): void {\n if (this.size > this.limit) {\n throw new RangeError(`An event block exceeds the ${this.limit}-character limit without ending`);\n }\n }\n}\n\n/**\n * @internal The longest event block (in UTF-16 code units, about 1 MiB of ASCII) buffered while\n * waiting for its terminating blank line. A source that never sends one would otherwise grow the\n * buffer without bound.\n */\nexport const MAX_BLOCK_CHARS = 1_048_576;\n\n/** Options for {@link decodeEvents}. */\nexport interface DecodeEventsOptions {\n /**\n * The longest event block, in characters, buffered while waiting for its end. A positive\n * integer or `Infinity`; defaults to 1,048,576, the limit `sse()` uses.\n */\n readonly maxBlockChars?: number;\n}\n\n/**\n * A stream transformation that decodes raw response bytes into {@link ServerSentEvent}s, buffering\n * partial input across chunks. Single-use: each application maintains its own decoding state.\n *\n * A block that passes `maxBlockChars` without ending fails the stream with a `RangeError` defect:\n * the input is not an event stream this decoder can read, and the surrounding error type `E` has no\n * case for it.\n *\n * @typeParam E - The error type carried by the surrounding stream.\n * @param options - `maxBlockChars`: the longest block buffered (default 1,048,576).\n * @returns A pipe from a byte stream to a stream of parsed events.\n * @throws {RangeError} If `maxBlockChars` is not a positive integer or `Infinity`.\n */\nexport const decodeEvents = <E>(options: DecodeEventsOptions = {}): Pipe<E, Uint8Array, ServerSentEvent> => {\n const limit = options.maxBlockChars ?? MAX_BLOCK_CHARS;\n if (limit !== Infinity && !(Number.isInteger(limit) && limit > 0)) {\n throw new RangeError(`decodeEvents: maxBlockChars must be a positive integer or Infinity, got ${limit}`);\n }\n const frames = new FrameBuffer(limit);\n return (bytes: Stream<E, Uint8Array>) =>\n bytes.mapAccumulate<string | undefined, ServerSentEvent>(undefined, (lastEventId, chunk) => {\n const events: ServerSentEvent[] = [];\n let current = lastEventId;\n for (const frame of frames.push(chunk)) {\n if (frame.id !== undefined) current = frame.id;\n if (frame.event !== null) events.push(SseEvents.withLastEventId(frame.event, current));\n }\n return [current, List.from(events)] as const;\n });\n};\n","import { IO, Option, Schedule, Stream } from \"@openstage/monadyssey-core\";\nimport { HttpError } from \"./http-error\";\nimport { HttpRequest } from \"./http-request\";\nimport { HttpResponse } from \"./http-response\";\nimport { HttpTransport } from \"./http-transport\";\nimport { Interceptors, Send } from \"./interceptors\";\nimport { Credentials, HttpInterceptor, Redirect } from \"./options\";\nimport { FrameBuffer, MAX_BLOCK_CHARS, ServerSentEvent, SseEvents, SseFrame } from \"./sse\";\n\n/** A server-sent `retry:` below this is raised to it, so a misbehaving server cannot force a tight loop. */\nconst MIN_SERVER_RETRY_MS = 100;\n\n/** Largest delay `setTimeout` honours; anything above it (or Infinity) fires after ~1ms. */\nconst MAX_DELAY_MS = 2_147_483_647;\n\ntype Reader = ReadableStreamDefaultReader<Uint8Array>;\n\n/**\n * Carried across reconnections within one run. Owns the one `AbortController` every connection\n * of the run is opened with, linked once to the run's signal; a connection registers a single\n * listener on it and removes it when closed, so listeners stay bounded however long the run lasts.\n */\nclass SseSession {\n readonly controller = new AbortController();\n /** Reaching the block limit fails the stream with `kind: \"decode\"`, which is not retried. */\n readonly frames = new FrameBuffer(MAX_BLOCK_CHARS);\n /**\n * Frames parsed but not yet handled, read from `next` on: a chunk can hold hundreds of thousands\n * of frames, and `Array.shift()` on each would cost time quadratic in the chunk size.\n */\n pending: SseFrame[] = [];\n next = 0;\n lastEventId: string | undefined = undefined;\n retryMs: number;\n /** The server's `retry:` value, once received: the delay, or with a `Schedule` a lower bound of it. */\n serverRetryMs: number | undefined = undefined;\n /** Consecutive reconnects since the last delivered event. */\n reconnects = 0;\n /** The status of the current connection, for an error raised while reading it. */\n status = 200;\n private connection: { readonly reader: Reader; readonly unlink: () => void } | null = null;\n private readonly unlinkParent: () => void;\n\n constructor(retryMs: number, parent: AbortSignal) {\n this.retryMs = retryMs;\n const onAbort = () => this.controller.abort(parent.reason);\n parent.addEventListener(\"abort\", onAbort, { once: true });\n this.unlinkParent = () => parent.removeEventListener(\"abort\", onAbort);\n }\n\n get reader(): Reader | null {\n return this.connection?.reader ?? null;\n }\n\n attach(reader: Reader, status: number): void {\n this.status = status;\n const onAbort = () => reader.cancel().catch(() => {});\n this.controller.signal.addEventListener(\"abort\", onAbort, { once: true });\n this.connection = { reader, unlink: () => this.controller.signal.removeEventListener(\"abort\", onAbort) };\n this.frames.reset();\n }\n\n closeConnection(): void {\n if (this.connection) {\n this.connection.unlink();\n this.connection.reader.cancel().catch(() => {});\n this.connection = null;\n }\n }\n\n close(): void {\n this.closeConnection();\n this.unlinkParent();\n this.controller.abort();\n }\n}\n\n/** @internal */\nexport interface SseConfig {\n readonly url: string;\n readonly headers: Record<string, string>;\n readonly defaultHeaders: Record<string, string>;\n readonly credentials: Credentials;\n readonly interceptors: readonly HttpInterceptor[];\n readonly transport: Send;\n readonly redirect: Redirect | undefined;\n readonly maxBodyBytes: number | undefined;\n readonly reconnect: boolean | Schedule;\n readonly retry: number;\n}\n\n/** @internal */\nexport const SseClient = {\n /** The `Last-Event-ID` value is the id UTF-8 encoded, byte for byte, as the EventSource spec sends it. */\n utf8ByteString: (id: string): string =>\n Array.from(new TextEncoder().encode(id), (b) => String.fromCharCode(b)).join(\"\"),\n\n /** A cancellable sleep. The abort listener is removed when the timer fires, so waits do not accumulate listeners. */\n delay: (ms: number): IO<never, void> =>\n IO.promise<void>(\n (signal: AbortSignal) =>\n new Promise<void>((resolve) => {\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(\n () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n Math.min(ms, MAX_DELAY_MS)\n );\n signal.addEventListener(\"abort\", onAbort, { once: true });\n })\n ),\n\n /** The media type of a `Content-Type` value, without its parameters. */\n mediaType: (contentType: string): string => contentType.split(\";\")[0].trim().toLowerCase(),\n\n /** The events of a server-sent-events stream, reconnecting as `config` says. */\n stream: (config: SseConfig): Stream<HttpError, ServerSentEvent> => {\n const {\n url,\n headers,\n defaultHeaders,\n credentials,\n interceptors,\n transport,\n redirect,\n maxBodyBytes,\n reconnect,\n retry,\n } = config;\n\n type Opened = { readonly reader: Reader; readonly status: number };\n\n /** The reader for a new connection, or `null` when the server answered 204 (\"stop reconnecting\"). */\n const open = (session: SseSession): IO<HttpError, Opened | null> => {\n const prepared = HttpRequest.prepare(\n \"GET\",\n {\n headers: {\n ...headers,\n accept: \"text/event-stream\",\n // An empty id is how a server resets it: the header is sent only for a non-empty id.\n ...(session.lastEventId ? { \"last-event-id\": SseClient.utf8ByteString(session.lastEventId) } : {}),\n },\n credentials,\n },\n { headers: defaultHeaders, credentials }\n );\n return IO.lift<HttpError, Response>(\n () =>\n Interceptors.run(\n interceptors,\n // `no-store`, as EventSource requests: a cached copy of a stream must never be replayed.\n Interceptors.request(url, {\n ...prepared,\n ...HttpTransport.redirectInit(redirect),\n cache: \"no-store\",\n signal: session.controller.signal,\n }),\n HttpTransport.enforceRedirect(redirect, transport)\n ),\n (e: unknown) => HttpTransport.error(e, url)\n )\n .flatMap((response) => {\n const refused = HttpTransport.refusedRedirect(redirect, response, url);\n if (refused !== undefined) return IO.fail<HttpError, Response>(refused);\n return response.ok ? IO.of(response) : HttpResponse.readFailure(response, \"text\", url, maxBodyBytes);\n })\n .flatMap((response): IO<HttpError, Opened | null> => {\n if (response.status === 204) {\n void response.body?.cancel().catch(() => {});\n return IO.of(null);\n }\n // Not an event stream (e.g. an HTML login page or SPA fallback): fail without\n // reconnecting, instead of parsing nothing and reconnecting forever. A missing\n // content type is tolerated.\n const contentType = response.headers.get(\"content-type\");\n if (contentType !== null && SseClient.mediaType(contentType) !== \"text/event-stream\") {\n void response.body?.cancel().catch(() => {});\n return IO.fail(HttpResponse.error(`Expected text/event-stream, got ${contentType}`, url, response));\n }\n return response.body === null\n ? IO.fail<HttpError, Opened>(HttpResponse.error(\"Response has no body\", url, response))\n : IO.of({ reader: response.body.getReader(), status: response.status });\n });\n };\n\n const readChunk = (reader: Reader): IO<HttpError, ReadableStreamReadResult<Uint8Array>> =>\n IO.lift(\n () => reader.read(),\n (e: unknown) => HttpTransport.error(e, url)\n );\n\n type EventStep = Option<[ServerSentEvent, SseSession]>;\n const done = IO.of<EventStep>(Option.empty());\n\n /**\n * Reconnects after the scheduled delay, or gives up (`giveUp`) when reconnection is off or the\n * `Schedule` allows no further attempt. A server `retry:` value, once received, is the delay.\n */\n const reconnectOr = (session: SseSession, giveUp: IO<HttpError, EventStep>): IO<HttpError, EventStep> => {\n if (reconnect === false) return giveUp;\n const made = session.reconnects + 1;\n if (reconnect !== true && !reconnect.allowsAttempt(made)) return giveUp;\n // With a Schedule, the client's backoff is a floor: a server `retry:` value can lengthen the\n // delay but not shorten it. Without one, the server's value is the delay, as for EventSource.\n const ms =\n reconnect === true\n ? (session.serverRetryMs ?? session.retryMs)\n : Math.max(session.serverRetryMs ?? 0, reconnect.delayAfter(made));\n session.reconnects = made;\n return SseClient.delay(ms).flatMap(() => step(session));\n };\n\n const step = (session: SseSession): IO<HttpError, EventStep> => {\n while (session.next < session.pending.length) {\n const frame = session.pending[session.next++];\n // `id:` and `retry:` take effect even in a block that dispatches no event.\n if (frame.id !== undefined) session.lastEventId = frame.id;\n if (frame.retry !== undefined) session.serverRetryMs = Math.max(frame.retry, MIN_SERVER_RETRY_MS);\n if (frame.event !== null) {\n session.reconnects = 0;\n return IO.of(\n Option.of<[ServerSentEvent, SseSession]>([\n SseEvents.withLastEventId(frame.event, session.lastEventId),\n session,\n ])\n );\n }\n }\n session.pending = [];\n session.next = 0;\n\n const reader = session.reader;\n if (reader === null) {\n return open(session).foldM<HttpError, EventStep>(\n (error) => (HttpTransport.isRetryable(error) ? reconnectOr(session, IO.fail(error)) : IO.fail(error)),\n (opened) => {\n if (opened === null) return done;\n session.attach(opened.reader, opened.status);\n return step(session);\n }\n );\n }\n\n return readChunk(reader).foldM<HttpError, EventStep>(\n (error) => {\n session.closeConnection();\n return HttpTransport.isRetryable(error) ? reconnectOr(session, IO.fail(error)) : IO.fail(error);\n },\n (result) => {\n if (result.done) {\n session.closeConnection();\n return reconnectOr(session, done);\n }\n let frames: SseFrame[];\n try {\n frames = session.frames.push(result.value);\n } catch (e) {\n // The block limit: the server is not sending an event stream we can read; stop for good.\n session.closeConnection();\n return IO.fail(\n new HttpError(session.status, String((e as Error).message), null, url, undefined, \"decode\", e)\n );\n }\n // One push per frame: spreading a chunk that holds hundreds of thousands of frames overflows\n // the stack. A frame with no event, id or retry (an empty block, a comment) changes nothing.\n for (const frame of frames) {\n if (frame.event !== null || frame.id !== undefined || frame.retry !== undefined)\n session.pending.push(frame);\n }\n return step(session);\n }\n );\n };\n\n return Stream.bracket<HttpError, HttpError, SseSession, ServerSentEvent>(\n IO.promise(async (signal: AbortSignal) => new SseSession(retry, signal)),\n (session) => Stream.unfoldEval(session, step),\n (session) => IO.sync(() => session.close())\n );\n },\n};\n","import { IO, Option, Stream } from \"@openstage/monadyssey-core\";\nimport { HttpError, HttpErrorFields } from \"./http-error\";\nimport { HttpRequest, PreparedRequest } from \"./http-request\";\nimport { HttpResponse, NO_BODY } from \"./http-response\";\nimport { HttpTransport } from \"./http-transport\";\nimport { HttpUrl } from \"./url\";\nimport { Interceptors, Send } from \"./interceptors\";\nimport { SseClient } from \"./sse-client\";\nimport {\n Credentials,\n Exact,\n HttpClientConfig,\n HttpInterceptor,\n Method,\n Options,\n Redirect,\n SendOptions,\n SseOptions,\n} from \"./options\";\nimport { ServerSentEvent } from \"./sse\";\n\n/** Options for a request that expects no body back, or `Option` of one. */\ntype OptionalBody<A> = Options<A> & { empty: \"option\" };\n/** Options for a request whose body is required (the default). */\ntype RequiredBody<A> = Options<A> & { empty?: \"error\" };\n\n/**\n * A composable HTTP client that wraps the native `fetch` API, returning `IO` instances instead of\n * Promises. Each instance carries its own configuration (base URL, interceptors, default headers,\n * timeout, credentials), so different parts of an application can use independently configured\n * clients.\n *\n * Three kinds of call, by what you want back:\n * - **the decoded body** — `get`, `post`, `put`, `patch`, `delete`, `fetch` return\n * `IO<HttpError, A>`. A response with no body (`204`, an empty `200`) fails with\n * `kind: \"decode\"`, since a value was expected; pass `{ empty: \"option\" }` when absence is\n * legitimate, to get `IO<HttpError, Option<A>>`.\n * - **nothing** — `send(method, uri, { body })` returns `IO<HttpError, void>` for actions whose\n * response body you do not read (publish, archive, leave …); any body, or none, is fine.\n * - **the `Response`** — `raw(method, uri, options?)` returns `IO<HttpError, Response>` for\n * status codes, headers or streaming.\n *\n * Every non-2xx response fails with `kind: \"response\"`, whichever you use. Cancellation is\n * supported: when the IO is cancelled (via a fiber or `timeout`), the underlying `fetch` is\n * aborted through its `AbortSignal`.\n *\n * `A` is what you claim the body is; the JSON is not checked unless you pass a `transform` that\n * validates it (a schema's `parse`, say) — a throw there fails with `kind: \"decode\"`.\n *\n * **Default credentials:** `same-origin`, matching the platform `fetch` default. Set\n * `credentials: \"include\"` explicitly per-client or per-request if you need cookies to flow\n * cross-origin.\n *\n * @example\n * const api = new HttpClient({\n * baseUrl: \"https://api.example.com\",\n * interceptors: [authInterceptor],\n * timeout: 5000,\n * });\n *\n * const users = api.get<User[]>(\"/users\"); // IO<HttpError, User[]>\n * const avatar = api.get<Avatar>(\"/me/avatar\", { empty: \"option\" }); // IO<HttpError, Option<Avatar>>\n * const leave = api.send(\"POST\", `/communities/${slug}/leave`); // IO<HttpError, void>\n */\nexport class HttpClient {\n private readonly interceptors: readonly HttpInterceptor[];\n private readonly baseUrl: string | undefined;\n private readonly defaultHeaders: Record<string, string>;\n private readonly defaultTimeout: number | undefined;\n private readonly defaultCredentials: Credentials;\n private readonly defaultRedirect: Redirect | undefined;\n private readonly defaultMaxBodyBytes: number | undefined;\n private readonly allowedOrigins: ReadonlySet<string> | undefined;\n private readonly transport: Send;\n\n /**\n * Creates a new HttpClient with the given configuration.\n *\n * @param {HttpClientConfig} config - Configuration for the client.\n */\n constructor(config: HttpClientConfig = {}) {\n this.interceptors = Object.freeze([...(config.interceptors ?? [])]);\n this.baseUrl = config.baseUrl;\n this.defaultHeaders = config.defaultHeaders ?? {};\n this.defaultTimeout = config.timeout;\n this.defaultCredentials = config.credentials ?? \"same-origin\";\n this.allowedOrigins = config.allowedOrigins === undefined ? undefined : HttpUrl.originsOf(config.allowedOrigins);\n if (this.allowedOrigins !== undefined && this.baseUrl !== undefined) {\n if (!HttpUrl.allowedOrigin(this.baseUrl, this.allowedOrigins)) {\n throw new RangeError(`HttpClient: the baseUrl's origin must be in allowedOrigins, got ${this.baseUrl}`);\n }\n }\n this.defaultRedirect = this.redirectOf(config.redirect);\n this.defaultMaxBodyBytes = HttpClient.checkMaxBodyBytes(config.maxBodyBytes);\n this.transport = HttpTransport.guardUrl(Interceptors.transport(config.fetch), this.allowedOrigins);\n }\n\n /**\n * Performs a GET request and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n get<A = unknown>(uri: string, options: Omit<OptionalBody<A>, \"body\">): IO<HttpError, Option<NonNullable<A>>>;\n get<A = unknown>(uri: string, options?: Omit<RequiredBody<A>, \"body\">): IO<HttpError, A>;\n get<A = unknown>(uri: string, options: Omit<Options<A>, \"body\"> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"GET\", options);\n }\n\n /**\n * Performs a POST request and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {unknown} [body] - The request payload.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n post<A = unknown>(uri: string, body: unknown, options: OptionalBody<A>): IO<HttpError, Option<NonNullable<A>>>;\n post<A = unknown>(uri: string, body?: unknown, options?: RequiredBody<A>): IO<HttpError, A>;\n post<A = unknown>(uri: string, body?: unknown, options: Options<A> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"POST\", { ...options, body });\n }\n\n /**\n * Performs a PUT request and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {unknown} [body] - The request payload.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n put<A = unknown>(uri: string, body: unknown, options: OptionalBody<A>): IO<HttpError, Option<NonNullable<A>>>;\n put<A = unknown>(uri: string, body?: unknown, options?: RequiredBody<A>): IO<HttpError, A>;\n put<A = unknown>(uri: string, body?: unknown, options: Options<A> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"PUT\", { ...options, body });\n }\n\n /**\n * Performs a PATCH request and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {unknown} [body] - The request payload.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n patch<A = unknown>(uri: string, body: unknown, options: OptionalBody<A>): IO<HttpError, Option<NonNullable<A>>>;\n patch<A = unknown>(uri: string, body?: unknown, options?: RequiredBody<A>): IO<HttpError, A>;\n patch<A = unknown>(uri: string, body?: unknown, options: Options<A> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"PATCH\", { ...options, body });\n }\n\n /**\n * Performs a DELETE request and decodes the body. For a DELETE that answers `204 No Content`,\n * use `send(\"DELETE\", uri)` instead.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {Options<A>} [options] - Request options; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n delete<A = unknown>(uri: string, options: Omit<OptionalBody<A>, \"body\">): IO<HttpError, Option<NonNullable<A>>>;\n delete<A = unknown>(uri: string, options?: Omit<RequiredBody<A>, \"body\">): IO<HttpError, A>;\n delete<A = unknown>(uri: string, options: Omit<Options<A>, \"body\"> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, \"DELETE\", options);\n }\n\n /**\n * Performs a request with any method and decodes the body.\n *\n * @template A - The type of the decoded body.\n * @param {string} uri - The URL or path to request.\n * @param {Method} method - The HTTP method.\n * @param {Options<A>} [options] - Request options, including `body`; `{ empty: \"option\" }` yields `Option<A>`.\n * @returns {IO<HttpError, A>} The decoded body.\n */\n fetch<A = unknown>(uri: string, method: Method, options: OptionalBody<A>): IO<HttpError, Option<NonNullable<A>>>;\n fetch<A = unknown>(uri: string, method: Method, options?: RequiredBody<A>): IO<HttpError, A>;\n fetch<A = unknown>(uri: string, method: Method, options: Options<A> = {}): IO<HttpError, A | Option<NonNullable<A>>> {\n return this.request<A>(uri, method, options);\n }\n\n /**\n * Performs a request whose response body you do not need — an action such as publish,\n * archive or leave. Succeeds with `void` for any 2xx, with or without a body (which is\n * discarded); a non-2xx response fails with `kind: \"response\"` and its body.\n *\n * @param {Method} method - The HTTP method.\n * @param {string} uri - The URL or path to request.\n * @param {SendOptions} [options] - Headers, credentials, timeout and body. Every key must be one of\n * `SendOptions`: a payload passed here by mistake (`send(\"POST\", url, article)`) is rejected at\n * compile time; it belongs in `{ body: article }`. A `GET` or `HEAD` request with a body throws\n * `TypeError` where it is built.\n * @returns {IO<HttpError, void>}\n *\n * @example\n * client.send(\"POST\", `/api/v1/communities/${slug}/leave`);\n * client.send(\"PUT\", `/api/v1/articles/${id}`, { body: article });\n * client.send(\"DELETE\", `/api/v1/passkeys/${id}`, { headers: { \"X-Step-Up\": token } });\n */\n send<O extends SendOptions>(method: Method, uri: string, options?: Exact<O, SendOptions>): IO<HttpError, void> {\n const url = this.resolveUrl(uri);\n const refused = HttpUrl.refuseUrl(url, this.allowedOrigins);\n if (refused !== undefined) return IO.fail(HttpErrorFields.withMethod(refused, method));\n const opts: SendOptions = options ?? {};\n const maxBodyBytes = this.maxBodyBytes(opts);\n return this.withTimeout(\n url,\n opts.timeout,\n this.exchange(url, method, opts).flatMap((response) =>\n response.ok\n ? IO.sync(() => void response.body?.cancel().catch(() => {}))\n : HttpResponse.readFailure(response, \"json\", url, maxBodyBytes)\n )\n ).mapErr((e) => HttpErrorFields.withMethod(e, method));\n }\n\n /**\n * Performs a request and yields the `Response` itself, for status codes, headers or streaming.\n * A non-2xx response still fails with `kind: \"response\"` (its body read into the error); a 2xx\n * `Response` is returned unread. When you only need the status or headers, cancel the body\n * (`response.body?.cancel()`) so the connection is released; `send` does this for you.\n *\n * @param {Method} method - The HTTP method.\n * @param {string} uri - The URL or path to request.\n * @param {SendOptions} [options] - Headers, credentials, timeout and body; every key must be one of\n * `SendOptions`, as for `send`.\n * @returns {IO<HttpError, Response>}\n *\n * @example\n * client.raw(\"POST\", \"/api/v1/communities\", { body: input }).map((r) => r.headers.get(\"Location\"));\n */\n raw<O extends SendOptions>(method: Method, uri: string, options?: Exact<O, SendOptions>): IO<HttpError, Response> {\n const url = this.resolveUrl(uri);\n const refused = HttpUrl.refuseUrl(url, this.allowedOrigins);\n if (refused !== undefined) return IO.fail(HttpErrorFields.withMethod(refused, method));\n const opts: SendOptions = options ?? {};\n const maxBodyBytes = this.maxBodyBytes(opts);\n return this.withTimeout(\n url,\n opts.timeout,\n this.exchange(url, method, opts).flatMap((response) =>\n response.ok ? IO.of(response) : HttpResponse.readFailure(response, \"json\", url, maxBodyBytes)\n )\n ).mapErr((e) => HttpErrorFields.withMethod(e, method));\n }\n\n /**\n * Opens a server-sent-events stream and emits each {@link ServerSentEvent} as it arrives.\n *\n * The request goes through the same pipeline as every other method, so headers (including\n * `Authorization`), credentials, interceptors, and the base URL all apply. No request timeout is\n * used — the connection is long-lived. Cancelling the terminal `IO` (via `fork`/`timeout`) aborts\n * the connection and releases resources.\n *\n * By default the stream reconnects automatically when the connection ends or fails with a\n * retryable error (network error or `5xx`), resuming with `Last-Event-ID` and re-applying headers\n * and credentials on each attempt; terminal `4xx` responses (including auth failures) end the\n * stream. See {@link SseOptions} to configure or disable this.\n *\n * @param {string} uri - The URL or path to connect to.\n * @param {SseOptions} [options] - Headers, credentials, and reconnection settings.\n * @returns {Stream<HttpError, ServerSentEvent>} A stream of parsed events.\n * @throws {RangeError} If `options.retry` is negative or `NaN`.\n *\n * @example\n * const events = client.sse(\"/events\", { headers: { Authorization: `Bearer ${token}` } });\n * await events.runForEach((event) => IO.sync(() => handle(event))).unsafeRun();\n */\n sse(uri: string, options: SseOptions = {}): Stream<HttpError, ServerSentEvent> {\n // A negative or NaN delay is a programming error; left through, `setTimeout` would treat it\n // as 0 and reconnect in a tight loop.\n if (options.retry !== undefined && !(options.retry >= 0)) {\n throw new RangeError(`HttpClient.sse: retry must be a non-negative number of milliseconds, got ${options.retry}`);\n }\n const url = this.resolveUrl(uri);\n const refused = HttpUrl.refuseUrl(url, this.allowedOrigins);\n if (refused !== undefined)\n return Stream.eval(IO.fail<HttpError, ServerSentEvent>(HttpErrorFields.withMethod(refused, \"GET\")));\n return SseClient.stream({\n url,\n headers: options.headers ?? {},\n defaultHeaders: this.defaultHeaders,\n credentials: options.credentials ?? this.defaultCredentials,\n interceptors: this.interceptors,\n transport: this.transport,\n redirect: this.redirectOf(options.redirect ?? this.defaultRedirect),\n maxBodyBytes: this.defaultMaxBodyBytes,\n reconnect: options.reconnect ?? true,\n retry: options.retry ?? 3000,\n }).mapErr((e) => HttpErrorFields.withMethod(e, \"GET\"));\n }\n\n /** A `maxBodyBytes` setting, or a `RangeError` when it is not a positive integer or `Infinity`. */\n private static checkMaxBodyBytes(limit: number | undefined): number | undefined {\n if (limit !== undefined && limit !== Infinity && !(Number.isInteger(limit) && limit > 0)) {\n throw new RangeError(`HttpClient: maxBodyBytes must be a positive integer or Infinity, got ${limit}`);\n }\n return limit;\n }\n\n /**\n * The `redirect` setting a request runs under: `\"error\"` under `allowedOrigins`, where `\"follow\"`\n * throws `RangeError`, since `fetch` would send the request, its headers and its body to every\n * origin on the way before the client could see where it ended.\n */\n private redirectOf(redirect: Redirect | undefined): Redirect | undefined {\n if (this.allowedOrigins === undefined) return redirect;\n if (redirect === \"follow\") {\n throw new RangeError('HttpClient: redirect \"follow\" cannot be used with allowedOrigins');\n }\n return \"error\";\n }\n\n /** The request's limit, else the client's; checked where the request is built. */\n private maxBodyBytes(options: { readonly maxBodyBytes?: number }): number | undefined {\n return HttpClient.checkMaxBodyBytes(options.maxBodyBytes) ?? this.defaultMaxBodyBytes;\n }\n\n private resolveUrl(uri: string): string {\n // Absolute only with a scheme followed by `//` (or a data:/blob: URL). `new URL()` also\n // accepts `items:batchGet` or `localhost:3000` as absolute, which would bypass `baseUrl`.\n if (!this.baseUrl || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(uri) || /^(data|blob):/i.test(uri)) return uri;\n const base = this.baseUrl.endsWith(\"/\") ? this.baseUrl.slice(0, -1) : this.baseUrl;\n const path = uri.startsWith(\"/\") ? uri : `/${uri}`;\n // Under a root base (\"/\") the path is the whole URL, and two slashes or backslashes at its\n // front (the URL parser skips tabs and newlines) would read as another host.\n return base === \"\" ? path.replace(/^[/\\\\\\t\\n\\r]+/, \"/\") : `${base}${path}`;\n }\n\n /** Prepares the request, runs it through the interceptors and `fetch`, and yields the `Response`. */\n private exchange(url: string, method: Method, options: SendOptions): IO<HttpError, Response> {\n if ((method === \"GET\" || method === \"HEAD\") && options.body != null) {\n // A programming error, so it throws where the request is built instead of being dropped.\n throw new TypeError(`A ${method} request cannot have a body (${url})`);\n }\n const defaults = { headers: this.defaultHeaders, credentials: this.defaultCredentials };\n const redirect = this.redirectOf(options.redirect ?? this.defaultRedirect);\n const prepare: IO<HttpError, PreparedRequest> = IO.lift(\n () => HttpRequest.prepare(method, options, defaults),\n (e: unknown) => HttpError.request(url, e)\n );\n return prepare.flatMap((prepared) =>\n IO.cancellable(\n (signal: AbortSignal) =>\n Interceptors.run(\n this.interceptors,\n Interceptors.request(url, { ...prepared, ...HttpTransport.redirectInit(redirect), signal }),\n HttpTransport.enforceRedirect(redirect, this.transport)\n ),\n (e: unknown) => HttpTransport.error(e, url)\n ).flatMap((response) => {\n const refused = HttpTransport.refusedRedirect(redirect, response, url);\n return refused === undefined ? IO.of(response) : IO.fail(refused);\n })\n );\n }\n\n private withTimeout<A>(url: string, timeout: number | undefined, io: IO<HttpError, A>): IO<HttpError, A> {\n const ms = timeout ?? this.defaultTimeout;\n return ms == null ? io : io.timeout(ms, () => HttpError.timeout(url, ms));\n }\n\n private request<A>(uri: string, method: Method, options: Options<A>): IO<HttpError, A | Option<NonNullable<A>>> {\n const url = this.resolveUrl(uri);\n const refused = HttpUrl.refuseUrl(url, this.allowedOrigins);\n if (refused !== undefined) return IO.fail(HttpErrorFields.withMethod(refused, method));\n const { responseType = \"json\", transform = (data: unknown) => data as A, empty = \"error\" } = options;\n const maxBodyBytes = this.maxBodyBytes(options);\n\n const decode = (response: Response): IO<HttpError, A | Option<NonNullable<A>>> =>\n response.ok\n ? HttpResponse.read(response, responseType, url, method, maxBodyBytes).flatMap((parsed) => {\n if (parsed === NO_BODY) {\n return empty === \"option\"\n ? IO.of(Option.empty<NonNullable<A>>())\n : IO.fail(\n HttpError.decode(\n url,\n response,\n `expected a response body, got none (status ${response.status}); use send() or { empty: \"option\" }`\n )\n );\n }\n return IO.lift<HttpError, A>(\n () => transform(parsed),\n (e: unknown) => HttpError.decode(url, response, e)\n ).map((value) => (empty === \"option\" ? Option.ofNullable(value) : value));\n })\n : HttpResponse.readFailure(response, responseType, url, maxBodyBytes);\n\n return this.withTimeout(url, options.timeout, this.exchange(url, method, options).flatMap(decode)).mapErr((e) =>\n HttpErrorFields.withMethod(e, method)\n );\n }\n}\n"],"mappings":";;;AA6BA,IAAa,kBAAkB;;;;;CAK7B,kBAAkB,aAA+C;EAC/D,IAAI;GACF,OAAO,OAAO,YACZ,MAAM,KAAK,SAAS,QAAQ,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,SAAS,gBAAgB,SAAS,aAAa,CAC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AC7F,MAAM,eAAe,KAAK,aAAa,OAAO;EAE9C,MAAM,UAAU,aACd,SAAS,KACL,aAAa,KAAK,UAAU,cAAc,KAAK,QAAQ,YAAY,CAAC,CAAC,SAAS,WAAW;GACvF,IAAI,WAAW,SACb,OAAO,UAAU,WACb,GAAG,GAAG,OAAO,MAAsB,CAAC,IACpC,GAAG,KACD,UAAU,OACR,KACA,UACA,8CAA8C,SAAS,OAAO,qCAChE,CACF;GAEN,OAAO,GAAG,WACF,UAAU,MAAM,IACrB,MAAe,UAAU,OAAO,KAAK,UAAU,CAAC,CACnD,CAAC,CAAC,KAAK,UAAW,UAAU,WAAW,OAAO,WAAW,KAAK,IAAI,KAAM;EAC1E,CAAC,IACD,aAAa,YAAY,UAAU,cAAc,KAAK,YAAY;EAExE,OAAO,KAAK,YAAY,KAAK,QAAQ,SAAS,KAAK,SAAS,KAAK,QAAQ,OAAO,CAAC,CAAC,QAAQ,MAAM,CAAC,CAAC,CAAC,QAAQ,MACzG,gBAAgB,WAAW,GAAG,MAAM,CACtC;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openstage/monadyssey-fetch",
|
|
3
|
-
"version": "3.0.0-rc.
|
|
3
|
+
"version": "3.0.0-rc.3",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -43,6 +43,6 @@
|
|
|
43
43
|
"prettier:fix": "npm run prettier -- --write"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
|
-
"@openstage/monadyssey-core": "^3.0.0-rc.
|
|
46
|
+
"@openstage/monadyssey-core": "^3.0.0-rc.3"
|
|
47
47
|
}
|
|
48
48
|
}
|