@openstage/monadyssey-fetch 3.0.0-rc.3 → 3.0.0-rc.4

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.
@@ -82,7 +82,7 @@ declare type Exact<T, Shape> = T & {
82
82
  *
83
83
  * const users = api.get<User[]>("/users"); // IO<HttpError, User[]>
84
84
  * const avatar = api.get<Avatar>("/me/avatar", { empty: "option" }); // IO<HttpError, Option<Avatar>>
85
- * const leave = api.send("POST", `/communities/${slug}/leave`); // IO<HttpError, void>
85
+ * const leave = api.send("POST", HttpPath.of`/communities/${slug}/leave`); // IO<HttpError, void>
86
86
  */
87
87
  export declare class HttpClient {
88
88
  private readonly interceptors;
@@ -179,9 +179,9 @@ export declare class HttpClient {
179
179
  * @returns {IO<HttpError, void>}
180
180
  *
181
181
  * @example
182
- * client.send("POST", `/api/v1/communities/${slug}/leave`);
183
- * client.send("PUT", `/api/v1/articles/${id}`, { body: article });
184
- * client.send("DELETE", `/api/v1/passkeys/${id}`, { headers: { "X-Step-Up": token } });
182
+ * client.send("POST", HttpPath.of`/api/v1/communities/${slug}/leave`);
183
+ * client.send("PUT", HttpPath.of`/api/v1/articles/${id}`, { body: article });
184
+ * client.send("DELETE", HttpPath.of`/api/v1/passkeys/${id}`, { headers: { "X-Step-Up": token } });
185
185
  */
186
186
  send<O extends SendOptions>(method: Method, uri: string, options?: Exact<O, SendOptions>): IO<HttpError, void>;
187
187
  /**
@@ -253,7 +253,11 @@ export declare type HttpClientConfig = {
253
253
  baseUrl?: string;
254
254
  /** Interceptors applied in registration order (first registered = outermost). Immutable after construction. */
255
255
  interceptors?: HttpInterceptor[];
256
- /** Default headers merged into every request. Per-request headers take precedence. */
256
+ /**
257
+ * Default headers merged into every request. Per-request headers take precedence. They also go to
258
+ * a redirect target, even on another origin: `fetch` removes only `Authorization` and `Cookie`.
259
+ * For a secret in a custom header, set `allowedOrigins` or `redirect: "error"`.
260
+ */
257
261
  defaultHeaders?: Record<string, string>;
258
262
  /** Default timeout in milliseconds for all requests; none by default. Can be overridden per-request. */
259
263
  timeout?: number;
@@ -267,7 +271,8 @@ export declare type HttpClientConfig = {
267
271
  */
268
272
  redirect?: Redirect;
269
273
  /**
270
- * The largest response body, in bytes, a request reads; none by default. Reading stops at the
274
+ * The largest response body, in bytes, a request reads; none by default, as with the platform
275
+ * `fetch`. A client that calls servers you do not control should set one. Reading stops at the
271
276
  * limit: a 2xx body past it fails with `kind: "tooLarge"`, and a non-2xx body past it is dropped
272
277
  * (`body: null`). A `Content-Length` above the limit fails before reading. `raw()` hands the body
273
278
  * to you unread, and server-sent events are not limited, except for an error response's body.
@@ -473,6 +478,10 @@ export declare type HttpErrorSummary = {
473
478
  /**
474
479
  * An HTTP interceptor that can modify or handle a request before, and its response after, the
475
480
  * outgoing `fetch` call.
481
+ *
482
+ * A header an interceptor adds goes to a redirect target too, even on another origin, unless it is
483
+ * `Authorization` or `Cookie`. For a secret in a custom header, set `allowedOrigins` or
484
+ * `redirect: "error"` on the client.
476
485
  */
477
486
  export declare interface HttpInterceptor {
478
487
  /**
@@ -493,6 +502,28 @@ export declare interface HttpInterceptor {
493
502
  intercept(request: InterceptedRequest, next: (request: InterceptedRequest) => Promise<Response>): Promise<Response>;
494
503
  }
495
504
 
505
+ /** Builds request paths from values that may come from users. */
506
+ export declare const HttpPath: {
507
+ /**
508
+ * Builds a path from a template, encoding each value with `encodeURIComponent`, so a value cannot
509
+ * add a `/`, a `?` or a `#`. Encoding alone does not stop `..`: the URL parser reads a segment `..`
510
+ * (or `%2e%2e`) as the parent and removes the segment before it. So a value that makes a path
511
+ * segment `.`, `..` or empty throws `TypeError` where the path is built. In the query and the
512
+ * fragment, values are only encoded: there, any value is allowed. Dot segments written in the
513
+ * template itself are left as they are.
514
+ *
515
+ * @param strings The template's text.
516
+ * @param values The values, each a string or a number.
517
+ * @returns The path, with every value encoded.
518
+ * @throws {TypeError} When a value makes a path segment `.`, `..` or empty.
519
+ *
520
+ * @example
521
+ * client.send("POST", HttpPath.of`/communities/${slug}/leave`); // a slug "../admin" stays one segment
522
+ * client.get(HttpPath.of`/search?q=${term}&page=${page}`);
523
+ */
524
+ of: (strings: TemplateStringsArray, ...values: readonly PathValue[]) => string;
525
+ };
526
+
496
527
  /**
497
528
  * A request as seen by an {@link HttpInterceptor}: the resolved URL and the `fetch` options.
498
529
  * `init.headers` is always a `Headers` instance — copy it with `new Headers(request.init.headers)`
@@ -543,6 +574,9 @@ export declare type Options<A = unknown> = RequestOptions & {
543
574
  empty?: "error" | "option";
544
575
  };
545
576
 
577
+ /** A value `HttpPath.of` puts into a path: one with a single, obvious text form. */
578
+ export declare type PathValue = string | number;
579
+
546
580
  /**
547
581
  * What to do when the server answers with a redirect (`301`, `302`, `303`, `307` or `308`):
548
582
  * - `"follow"`: follow it, as `fetch` does by default;
@@ -48,9 +48,18 @@ var HttpErrorMessage = {
48
48
  return code > 65535 ? `\\u{${code.toString(16)}}` : `\\u${code.toString(16).padStart(4, "0")}`;
49
49
  }),
50
50
  describe: (cause) => cause instanceof Error ? cause.message : typeof cause === "string" ? cause : typeof cause === "object" && cause !== null && "message" in cause ? String(cause.message) : "An unknown error occurred.",
51
+ /**
52
+ * `url` cut after its first `?` or `#`, with `…` in place of the rest. A query or a fragment can hold
53
+ * a token or a signature, and the message reaches logs and error trackers through `message`,
54
+ * `stack` and `util.inspect`; the full URL stays in the error's `url`.
55
+ */
56
+ withoutQuery: (url) => {
57
+ const cut = url.search(/[?#]/);
58
+ return cut === -1 ? url : `${url.slice(0, cut + 1)}…`;
59
+ },
51
60
  /** Response errors keep the pre-3.0 wording; the other kinds carry no status. */
52
61
  format: (kind, rawUrl, status, rawText, timeoutMs) => {
53
- const url = HttpErrorMessage.printable(rawUrl);
62
+ const url = HttpErrorMessage.printable(HttpErrorMessage.withoutQuery(rawUrl));
54
63
  const rawMessage = HttpErrorMessage.printable(rawText);
55
64
  switch (kind) {
56
65
  case "response": return `Request to '${url}' failed with status ${status} and message: ${HttpErrorMessage.sentence(rawMessage)}`;
@@ -985,7 +994,7 @@ var SseClient = {
985
994
  *
986
995
  * const users = api.get<User[]>("/users"); // IO<HttpError, User[]>
987
996
  * const avatar = api.get<Avatar>("/me/avatar", { empty: "option" }); // IO<HttpError, Option<Avatar>>
988
- * const leave = api.send("POST", `/communities/${slug}/leave`); // IO<HttpError, void>
997
+ * const leave = api.send("POST", HttpPath.of`/communities/${slug}/leave`); // IO<HttpError, void>
989
998
  */
990
999
  var HttpClient = class HttpClient {
991
1000
  interceptors;
@@ -1057,9 +1066,9 @@ var HttpClient = class HttpClient {
1057
1066
  * @returns {IO<HttpError, void>}
1058
1067
  *
1059
1068
  * @example
1060
- * client.send("POST", `/api/v1/communities/${slug}/leave`);
1061
- * client.send("PUT", `/api/v1/articles/${id}`, { body: article });
1062
- * client.send("DELETE", `/api/v1/passkeys/${id}`, { headers: { "X-Step-Up": token } });
1069
+ * client.send("POST", HttpPath.of`/api/v1/communities/${slug}/leave`);
1070
+ * client.send("PUT", HttpPath.of`/api/v1/articles/${id}`, { body: article });
1071
+ * client.send("DELETE", HttpPath.of`/api/v1/passkeys/${id}`, { headers: { "X-Step-Up": token } });
1063
1072
  */
1064
1073
  send(method, uri, options) {
1065
1074
  const url = this.resolveUrl(uri);
@@ -1191,6 +1200,52 @@ var HttpClient = class HttpClient {
1191
1200
  return this.withTimeout(url, options.timeout, this.exchange(url, method, options).flatMap(decode)).mapErr((e) => HttpErrorFields.withMethod(e, method));
1192
1201
  }
1193
1202
  };
1194
- export { HttpClient, HttpError, decodeEvents };
1203
+ // src/http-path.ts
1204
+ /** A path segment the URL parser reads as "this directory", "the parent", or nothing. */
1205
+ var DOT_OR_EMPTY = /^(\.|\.\.|)$/;
1206
+ /** Builds request paths from values that may come from users. */
1207
+ var HttpPath = {
1208
+ /**
1209
+ * Builds a path from a template, encoding each value with `encodeURIComponent`, so a value cannot
1210
+ * add a `/`, a `?` or a `#`. Encoding alone does not stop `..`: the URL parser reads a segment `..`
1211
+ * (or `%2e%2e`) as the parent and removes the segment before it. So a value that makes a path
1212
+ * segment `.`, `..` or empty throws `TypeError` where the path is built. In the query and the
1213
+ * fragment, values are only encoded: there, any value is allowed. Dot segments written in the
1214
+ * template itself are left as they are.
1215
+ *
1216
+ * @param strings The template's text.
1217
+ * @param values The values, each a string or a number.
1218
+ * @returns The path, with every value encoded.
1219
+ * @throws {TypeError} When a value makes a path segment `.`, `..` or empty.
1220
+ *
1221
+ * @example
1222
+ * client.send("POST", HttpPath.of`/communities/${slug}/leave`); // a slug "../admin" stays one segment
1223
+ * client.get(HttpPath.of`/search?q=${term}&page=${page}`);
1224
+ */
1225
+ of: (strings, ...values) => {
1226
+ let path = strings[0];
1227
+ const placed = [];
1228
+ values.forEach((value, i) => {
1229
+ const start = path.length;
1230
+ path += encodeURIComponent(String(value));
1231
+ placed.push({
1232
+ start,
1233
+ end: path.length
1234
+ });
1235
+ path += strings[i + 1];
1236
+ });
1237
+ const query = path.search(/[?#]/);
1238
+ const end = query === -1 ? path.length : query;
1239
+ let start = 0;
1240
+ while (start <= end) {
1241
+ const slash = path.indexOf("/", start);
1242
+ const stop = slash === -1 || slash > end ? end : slash;
1243
+ const segment = path.slice(start, stop);
1244
+ if (placed.some((p) => p.start >= start && p.end <= stop) && DOT_OR_EMPTY.test(segment.replace(/%2e/gi, "."))) throw new TypeError(`HttpPath.of: a value makes the path segment ${JSON.stringify(segment)}, which the URL parser reads as the same directory, the parent directory, or an empty segment`);
1245
+ start = stop + 1;
1246
+ }
1247
+ return path;
1248
+ } };
1249
+ export { HttpClient, HttpError, HttpPath, decodeEvents };
1195
1250
 
1196
1251
  //# sourceMappingURL=monadyssey-fetch.mjs.map
@@ -1 +1 @@
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,CAC3G;EACF,QAAQ;GACN,OAAO,CAAC;EACV;CACF;;CAGA,SAAS,WAAwC;EAC/C;EACA,YAAY;EACZ,UAAU;EACV,cAAc;CAChB;;;;;CAMA,aAAa,OAAkB,WAA8B;EAC3D,IAAI,MAAM,WAAW,KAAA,GAAW,MAA+B,SAAS;EACxE,OAAO;CACT;AACF;;AAGA,IAAa,mBAAmB;;CAE9B,WAAW,SAA0B,KAAK,SAAS,GAAG,IAAI,OAAO,GAAG,KAAK;;;;;;;;;;CAWzE,YAAY,SACV,KAAK,QAAQ,6EAA6E,MAAM;EAC9F,IAAI,MAAM,MAAM,OAAO;EACvB,MAAM,OAAO,EAAE,YAAY,CAAC;EAC5B,OAAO,OAAO,QAAS,OAAO,KAAK,SAAS,EAAE,EAAE,KAAK,MAAM,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;CAC9F,CAAC;CAEH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,CAAC,CAAC,QAAQ,MAAM,CAAC,CAAC,CAAC,QAAQ,MACzG,gBAAgB,WAAW,GAAG,MAAM,CACtC;CACF;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","../src/http-path.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 /**\n * `url` cut after its first `?` or `#`, with `…` in place of the rest. A query or a fragment can hold\n * a token or a signature, and the message reaches logs and error trackers through `message`,\n * `stack` and `util.inspect`; the full URL stays in the error's `url`.\n */\n withoutQuery: (url: string): string => {\n const cut = url.search(/[?#]/);\n return cut === -1 ? url : `${url.slice(0, cut + 1)}…`;\n },\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(HttpErrorMessage.withoutQuery(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\", HttpPath.of`/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\", HttpPath.of`/api/v1/communities/${slug}/leave`);\n * client.send(\"PUT\", HttpPath.of`/api/v1/articles/${id}`, { body: article });\n * client.send(\"DELETE\", HttpPath.of`/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","/** A value `HttpPath.of` puts into a path: one with a single, obvious text form. */\nexport type PathValue = string | number;\n\n/** Where a value landed in the built path: from `start` to `end`. */\ntype Placed = { readonly start: number; readonly end: number };\n\n/** A path segment the URL parser reads as \"this directory\", \"the parent\", or nothing. */\nconst DOT_OR_EMPTY = /^(\\.|\\.\\.|)$/;\n\n/** Builds request paths from values that may come from users. */\nexport const HttpPath = {\n /**\n * Builds a path from a template, encoding each value with `encodeURIComponent`, so a value cannot\n * add a `/`, a `?` or a `#`. Encoding alone does not stop `..`: the URL parser reads a segment `..`\n * (or `%2e%2e`) as the parent and removes the segment before it. So a value that makes a path\n * segment `.`, `..` or empty throws `TypeError` where the path is built. In the query and the\n * fragment, values are only encoded: there, any value is allowed. Dot segments written in the\n * template itself are left as they are.\n *\n * @param strings The template's text.\n * @param values The values, each a string or a number.\n * @returns The path, with every value encoded.\n * @throws {TypeError} When a value makes a path segment `.`, `..` or empty.\n *\n * @example\n * client.send(\"POST\", HttpPath.of`/communities/${slug}/leave`); // a slug \"../admin\" stays one segment\n * client.get(HttpPath.of`/search?q=${term}&page=${page}`);\n */\n of: (strings: TemplateStringsArray, ...values: readonly PathValue[]): string => {\n let path = strings[0];\n const placed: Placed[] = [];\n values.forEach((value, i) => {\n const start = path.length;\n path += encodeURIComponent(String(value));\n placed.push({ start, end: path.length });\n path += strings[i + 1];\n });\n const query = path.search(/[?#]/);\n const end = query === -1 ? path.length : query;\n let start = 0;\n while (start <= end) {\n const slash = path.indexOf(\"/\", start);\n const stop = slash === -1 || slash > end ? end : slash;\n const segment = path.slice(start, stop);\n const holdsValue = placed.some((p) => p.start >= start && p.end <= stop);\n if (holdsValue && DOT_OR_EMPTY.test(segment.replace(/%2e/gi, \".\"))) {\n throw new TypeError(\n `HttpPath.of: a value makes the path segment ${JSON.stringify(segment)}, which the URL parser ` +\n \"reads as the same directory, the parent directory, or an empty segment\"\n );\n }\n start = stop + 1;\n }\n return path;\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,CAC3G;EACF,QAAQ;GACN,OAAO,CAAC;E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,SAAS,KAAK;EACnB,MAAM,QAAQ,KAAK,QAAQ,KAAK,KAAK;EACrC,MAAM,OAAO,UAAU,MAAM,QAAQ,MAAM,MAAM;EACjD,MAAM,UAAU,KAAK,MAAM,OAAO,IAAI;EAEtC,IADmB,OAAO,MAAM,MAAM,EAAE,SAAS,SAAS,EAAE,OAAO,IAC/D,KAAc,aAAa,KAAK,QAAQ,QAAQ,SAAS,GAAG,CAAC,GAC/D,MAAM,IAAI,UACR,+CAA+C,KAAK,UAAU,OAAO,EAAE,8FAEzE;EAEF,QAAQ,OAAO;CACjB;CACA,OAAO;AACT,EACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openstage/monadyssey-fetch",
3
- "version": "3.0.0-rc.3",
3
+ "version": "3.0.0-rc.4",
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.3"
46
+ "@openstage/monadyssey-core": "^3.0.0-rc.4"
47
47
  }
48
48
  }