@craftainer/crud-sdk 0.7.1 → 0.8.1

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.
@@ -0,0 +1,232 @@
1
+ //#region src/errors.ts
2
+ /**
3
+ * Error hierarchy: client-side errors and RFC 9457 problem details (ADR-0004).
4
+ * Mirrors the Python SDK class for class.
5
+ */
6
+ /** Base class of every error this package throws on purpose. */
7
+ var CrudError = class extends Error {
8
+ constructor(message, options) {
9
+ super(message, options);
10
+ this.name = new.target.name;
11
+ }
12
+ };
13
+ /** The call was refused before any request was sent. */
14
+ var ClientError = class extends CrudError {};
15
+ /** The resource does not support the operation (manifest capability or path missing). */
16
+ var CapabilityError = class extends ClientError {};
17
+ /** A filter, sort or paging argument is not valid for the resource. */
18
+ var InvalidQueryError = class extends ClientError {};
19
+ /**
20
+ * A request carrying an `Authorization` header was about to go over plain
21
+ * `http:` to a non-loopback host. Nothing was sent. Use `https:`, or opt in
22
+ * with `allowInsecureHttp`.
23
+ */
24
+ var InsecureTransportError = class extends ClientError {};
25
+ /** The discovery document or the manifest is missing, unusable or of an unknown version. */
26
+ var ManifestError = class extends ClientError {};
27
+ /** The manifest lists no such resource for this caller. */
28
+ var UnknownResourceError = class extends ClientError {};
29
+ /** A successful response whose body is not the JSON the client expects; `cause` holds the parse error. */
30
+ var ResponseError = class extends CrudError {};
31
+ /** The request never produced a response; `cause` holds the transport error. */
32
+ var ConnectionFailed = class extends CrudError {};
33
+ const NO_TYPE = "about:blank";
34
+ /** Longest server-supplied text kept in `Error.message`; the full value stays on `detail` / `errors`. */
35
+ const MAX_MESSAGE_TEXT = 200;
36
+ function clip(text) {
37
+ return text.length > MAX_MESSAGE_TEXT ? `${text.slice(0, MAX_MESSAGE_TEXT)}...` : text;
38
+ }
39
+ /**
40
+ * A URL for an error message: no credentials, query or fragment (filter values
41
+ * can be personal data and error messages travel to toasts and telemetry).
42
+ */
43
+ function describeUrl(url) {
44
+ try {
45
+ const parsed = new URL(url);
46
+ parsed.username = "";
47
+ parsed.password = "";
48
+ parsed.search = "";
49
+ parsed.hash = "";
50
+ return parsed.href;
51
+ } catch {
52
+ return url.replace(/[?#].*$/s, "").replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i, "$1");
53
+ }
54
+ }
55
+ /** An error response, as RFC 9457 problem details. */
56
+ var ProblemError = class extends CrudError {
57
+ status;
58
+ title;
59
+ detail;
60
+ type;
61
+ instance;
62
+ errors;
63
+ headers;
64
+ response;
65
+ constructor(init) {
66
+ const errors = init.errors ?? [];
67
+ let message = `${init.status} ${clip(init.title)}`;
68
+ if (init.detail) message += `: ${clip(init.detail)}`;
69
+ else if (errors.length > 0) message += `: ${clip(errors.map((e) => `${e.loc.join(".")}: ${e.msg}`).join("; "))}`;
70
+ super(message);
71
+ this.status = init.status;
72
+ this.title = init.title;
73
+ this.detail = init.detail;
74
+ this.type = init.type ?? NO_TYPE;
75
+ this.instance = init.instance;
76
+ this.errors = errors;
77
+ this.headers = init.headers ?? new Headers();
78
+ this.response = init.response;
79
+ }
80
+ };
81
+ /** 400. */
82
+ var BadRequest = class extends ProblemError {};
83
+ /** 401; `wwwAuthenticate` keeps the challenge. */
84
+ var Unauthorized = class extends ProblemError {
85
+ get wwwAuthenticate() {
86
+ return this.headers.get("www-authenticate") ?? void 0;
87
+ }
88
+ };
89
+ /** 403. */
90
+ var Forbidden = class extends ProblemError {};
91
+ /** 404. */
92
+ var NotFound = class extends ProblemError {};
93
+ /** 412: a stale `If-Match`. */
94
+ var PreconditionFailed = class extends ProblemError {};
95
+ /** 422; `errors` holds normalized `{loc, msg, type}` entries. */
96
+ var ValidationFailed = class extends ProblemError {};
97
+ /** 423. */
98
+ var Locked = class extends ProblemError {};
99
+ /** 429; `retryAfter` is the `Retry-After` header in seconds, when it is a number. */
100
+ var RateLimited = class extends ProblemError {
101
+ get retryAfter() {
102
+ const raw = this.headers.get("retry-after");
103
+ if (raw === null || raw.trim() === "") return;
104
+ const seconds = Number(raw);
105
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : void 0;
106
+ }
107
+ };
108
+ /** 5xx. */
109
+ var ServerError = class extends ProblemError {};
110
+ const BY_STATUS = /* @__PURE__ */ new Map([
111
+ [400, BadRequest],
112
+ [401, Unauthorized],
113
+ [403, Forbidden],
114
+ [404, NotFound],
115
+ [412, PreconditionFailed],
116
+ [422, ValidationFailed],
117
+ [423, Locked],
118
+ [429, RateLimited]
119
+ ]);
120
+ const PHRASES = /* @__PURE__ */ new Map([
121
+ [100, "Continue"],
122
+ [101, "Switching Protocols"],
123
+ [102, "Processing"],
124
+ [103, "Early Hints"],
125
+ [200, "OK"],
126
+ [201, "Created"],
127
+ [202, "Accepted"],
128
+ [203, "Non-Authoritative Information"],
129
+ [204, "No Content"],
130
+ [205, "Reset Content"],
131
+ [206, "Partial Content"],
132
+ [207, "Multi-Status"],
133
+ [208, "Already Reported"],
134
+ [226, "IM Used"],
135
+ [300, "Multiple Choices"],
136
+ [301, "Moved Permanently"],
137
+ [302, "Found"],
138
+ [303, "See Other"],
139
+ [304, "Not Modified"],
140
+ [305, "Use Proxy"],
141
+ [307, "Temporary Redirect"],
142
+ [308, "Permanent Redirect"],
143
+ [400, "Bad Request"],
144
+ [401, "Unauthorized"],
145
+ [402, "Payment Required"],
146
+ [403, "Forbidden"],
147
+ [404, "Not Found"],
148
+ [405, "Method Not Allowed"],
149
+ [406, "Not Acceptable"],
150
+ [407, "Proxy Authentication Required"],
151
+ [408, "Request Timeout"],
152
+ [409, "Conflict"],
153
+ [410, "Gone"],
154
+ [411, "Length Required"],
155
+ [412, "Precondition Failed"],
156
+ [413, "Content Too Large"],
157
+ [414, "URI Too Long"],
158
+ [415, "Unsupported Media Type"],
159
+ [416, "Range Not Satisfiable"],
160
+ [417, "Expectation Failed"],
161
+ [418, "I'm a Teapot"],
162
+ [421, "Misdirected Request"],
163
+ [422, "Unprocessable Content"],
164
+ [423, "Locked"],
165
+ [424, "Failed Dependency"],
166
+ [425, "Too Early"],
167
+ [426, "Upgrade Required"],
168
+ [428, "Precondition Required"],
169
+ [429, "Too Many Requests"],
170
+ [431, "Request Header Fields Too Large"],
171
+ [451, "Unavailable For Legal Reasons"],
172
+ [500, "Internal Server Error"],
173
+ [501, "Not Implemented"],
174
+ [502, "Bad Gateway"],
175
+ [503, "Service Unavailable"],
176
+ [504, "Gateway Timeout"],
177
+ [505, "HTTP Version Not Supported"],
178
+ [506, "Variant Also Negotiates"],
179
+ [507, "Insufficient Storage"],
180
+ [508, "Loop Detected"],
181
+ [510, "Not Extended"],
182
+ [511, "Network Authentication Required"]
183
+ ]);
184
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
185
+ function normalizeErrors(items) {
186
+ return items.map((item) => {
187
+ if (isObject(item)) return {
188
+ loc: Array.isArray(item["loc"]) ? item["loc"] : [],
189
+ msg: String(item["msg"] ?? ""),
190
+ type: String(item["type"] ?? "")
191
+ };
192
+ return {
193
+ loc: [],
194
+ msg: String(item),
195
+ type: ""
196
+ };
197
+ });
198
+ }
199
+ /**
200
+ * Builds the matching `ProblemError` subclass from an error response. A body
201
+ * that is not a JSON object yields a synthesized problem from the status
202
+ * phrase. Reads a clone, so `response.body` stays readable.
203
+ */
204
+ async function problemFromResponse(response) {
205
+ const status = response.status;
206
+ const phrase = PHRASES.get(status) ?? "Error";
207
+ let parsed;
208
+ try {
209
+ parsed = JSON.parse(await response.clone().text());
210
+ } catch {
211
+ parsed = void 0;
212
+ }
213
+ const body = isObject(parsed) ? parsed : {};
214
+ const rawDetail = body["detail"];
215
+ const rawErrors = Array.isArray(rawDetail) ? rawDetail : body["errors"];
216
+ const Cls = BY_STATUS.get(status) ?? (status >= 500 ? ServerError : ProblemError);
217
+ const instance = body["instance"];
218
+ return new Cls({
219
+ status,
220
+ title: String(body["title"] || phrase),
221
+ detail: typeof rawDetail === "string" ? rawDetail : void 0,
222
+ type: String(body["type"] || NO_TYPE),
223
+ instance: typeof instance === "string" ? instance : void 0,
224
+ errors: Array.isArray(rawErrors) ? normalizeErrors(rawErrors) : [],
225
+ headers: response.headers,
226
+ response
227
+ });
228
+ }
229
+ //#endregion
230
+ export { Unauthorized as _, CrudError as a, describeUrl as b, InvalidQueryError as c, NotFound as d, PreconditionFailed as f, ServerError as g, ResponseError as h, ConnectionFailed as i, Locked as l, RateLimited as m, CapabilityError as n, Forbidden as o, ProblemError as p, ClientError as r, InsecureTransportError as s, BadRequest as t, ManifestError as u, UnknownResourceError as v, problemFromResponse as x, ValidationFailed as y };
231
+
232
+ //# sourceMappingURL=errors-ZdOt0_zk.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-ZdOt0_zk.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Error hierarchy: client-side errors and RFC 9457 problem details (ADR-0004).\n * Mirrors the Python SDK class for class.\n */\n\n/** Base class of every error this package throws on purpose. */\nexport class CrudError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** The call was refused before any request was sent. */\nexport class ClientError extends CrudError {}\n\n/** The resource does not support the operation (manifest capability or path missing). */\nexport class CapabilityError extends ClientError {}\n\n/** A filter, sort or paging argument is not valid for the resource. */\nexport class InvalidQueryError extends ClientError {}\n\n/**\n * A request carrying an `Authorization` header was about to go over plain\n * `http:` to a non-loopback host. Nothing was sent. Use `https:`, or opt in\n * with `allowInsecureHttp`.\n */\nexport class InsecureTransportError extends ClientError {}\n\n/** The discovery document or the manifest is missing, unusable or of an unknown version. */\nexport class ManifestError extends ClientError {}\n\n/** The manifest lists no such resource for this caller. */\nexport class UnknownResourceError extends ClientError {}\n\n/** A successful response whose body is not the JSON the client expects; `cause` holds the parse error. */\nexport class ResponseError extends CrudError {}\n\n/** The request never produced a response; `cause` holds the transport error. */\nexport class ConnectionFailed extends CrudError {}\n\n/** One normalized validation error (`422`). */\nexport interface ProblemDetail {\n readonly loc: readonly (string | number)[];\n readonly msg: string;\n readonly type: string;\n}\n\n/** Members of a {@link ProblemError}. */\nexport interface ProblemInit {\n readonly status: number;\n readonly title: string;\n readonly detail?: string | undefined;\n readonly type?: string | undefined;\n readonly instance?: string | undefined;\n readonly errors?: readonly ProblemDetail[] | undefined;\n readonly headers?: Headers | undefined;\n readonly response?: Response | undefined;\n}\n\nconst NO_TYPE = \"about:blank\";\n\n/** Longest server-supplied text kept in `Error.message`; the full value stays on `detail` / `errors`. */\nconst MAX_MESSAGE_TEXT = 200;\n\nfunction clip(text: string): string {\n return text.length > MAX_MESSAGE_TEXT\n ? `${text.slice(0, MAX_MESSAGE_TEXT)}...`\n : text;\n}\n\n/**\n * A URL for an error message: no credentials, query or fragment (filter values\n * can be personal data and error messages travel to toasts and telemetry).\n */\nexport function describeUrl(url: string): string {\n try {\n const parsed = new URL(url);\n parsed.username = \"\";\n parsed.password = \"\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return parsed.href;\n } catch {\n return url\n .replace(/[?#].*$/s, \"\")\n .replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/]*@/i, \"$1\");\n }\n}\n\n/** An error response, as RFC 9457 problem details. */\nexport class ProblemError extends CrudError {\n readonly status: number;\n readonly title: string;\n readonly detail: string | undefined;\n readonly type: string;\n readonly instance: string | undefined;\n readonly errors: readonly ProblemDetail[];\n readonly headers: Headers;\n readonly response: Response | undefined;\n\n constructor(init: ProblemInit) {\n const errors = init.errors ?? [];\n let message = `${init.status} ${clip(init.title)}`;\n if (init.detail) {\n message += `: ${clip(init.detail)}`;\n } else if (errors.length > 0) {\n message += `: ${clip(errors.map((e) => `${e.loc.join(\".\")}: ${e.msg}`).join(\"; \"))}`;\n }\n super(message);\n this.status = init.status;\n this.title = init.title;\n this.detail = init.detail;\n this.type = init.type ?? NO_TYPE;\n this.instance = init.instance;\n this.errors = errors;\n this.headers = init.headers ?? new Headers();\n this.response = init.response;\n }\n}\n\n/** 400. */\nexport class BadRequest extends ProblemError {}\n\n/** 401; `wwwAuthenticate` keeps the challenge. */\nexport class Unauthorized extends ProblemError {\n get wwwAuthenticate(): string | undefined {\n return this.headers.get(\"www-authenticate\") ?? undefined;\n }\n}\n\n/** 403. */\nexport class Forbidden extends ProblemError {}\n\n/** 404. */\nexport class NotFound extends ProblemError {}\n\n/** 412: a stale `If-Match`. */\nexport class PreconditionFailed extends ProblemError {}\n\n/** 422; `errors` holds normalized `{loc, msg, type}` entries. */\nexport class ValidationFailed extends ProblemError {}\n\n/** 423. */\nexport class Locked extends ProblemError {}\n\n/** 429; `retryAfter` is the `Retry-After` header in seconds, when it is a number. */\nexport class RateLimited extends ProblemError {\n get retryAfter(): number | undefined {\n const raw = this.headers.get(\"retry-after\");\n if (raw === null || raw.trim() === \"\") {\n return undefined;\n }\n const seconds = Number(raw);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;\n }\n}\n\n/** 5xx. */\nexport class ServerError extends ProblemError {}\n\nconst BY_STATUS: ReadonlyMap<number, typeof ProblemError> = new Map([\n [400, BadRequest],\n [401, Unauthorized],\n [403, Forbidden],\n [404, NotFound],\n [412, PreconditionFailed],\n [422, ValidationFailed],\n [423, Locked],\n [429, RateLimited],\n]);\n\n// Python's `http.HTTPStatus` phrases, so both SDKs synthesize the same title.\nconst PHRASES: ReadonlyMap<number, string> = new Map([\n [100, \"Continue\"],\n [101, \"Switching Protocols\"],\n [102, \"Processing\"],\n [103, \"Early Hints\"],\n [200, \"OK\"],\n [201, \"Created\"],\n [202, \"Accepted\"],\n [203, \"Non-Authoritative Information\"],\n [204, \"No Content\"],\n [205, \"Reset Content\"],\n [206, \"Partial Content\"],\n [207, \"Multi-Status\"],\n [208, \"Already Reported\"],\n [226, \"IM Used\"],\n [300, \"Multiple Choices\"],\n [301, \"Moved Permanently\"],\n [302, \"Found\"],\n [303, \"See Other\"],\n [304, \"Not Modified\"],\n [305, \"Use Proxy\"],\n [307, \"Temporary Redirect\"],\n [308, \"Permanent Redirect\"],\n [400, \"Bad Request\"],\n [401, \"Unauthorized\"],\n [402, \"Payment Required\"],\n [403, \"Forbidden\"],\n [404, \"Not Found\"],\n [405, \"Method Not Allowed\"],\n [406, \"Not Acceptable\"],\n [407, \"Proxy Authentication Required\"],\n [408, \"Request Timeout\"],\n [409, \"Conflict\"],\n [410, \"Gone\"],\n [411, \"Length Required\"],\n [412, \"Precondition Failed\"],\n [413, \"Content Too Large\"],\n [414, \"URI Too Long\"],\n [415, \"Unsupported Media Type\"],\n [416, \"Range Not Satisfiable\"],\n [417, \"Expectation Failed\"],\n [418, \"I'm a Teapot\"],\n [421, \"Misdirected Request\"],\n [422, \"Unprocessable Content\"],\n [423, \"Locked\"],\n [424, \"Failed Dependency\"],\n [425, \"Too Early\"],\n [426, \"Upgrade Required\"],\n [428, \"Precondition Required\"],\n [429, \"Too Many Requests\"],\n [431, \"Request Header Fields Too Large\"],\n [451, \"Unavailable For Legal Reasons\"],\n [500, \"Internal Server Error\"],\n [501, \"Not Implemented\"],\n [502, \"Bad Gateway\"],\n [503, \"Service Unavailable\"],\n [504, \"Gateway Timeout\"],\n [505, \"HTTP Version Not Supported\"],\n [506, \"Variant Also Negotiates\"],\n [507, \"Insufficient Storage\"],\n [508, \"Loop Detected\"],\n [510, \"Not Extended\"],\n [511, \"Network Authentication Required\"],\n]);\n\ntype Obj = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is Obj =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction normalizeErrors(items: readonly unknown[]): ProblemDetail[] {\n return items.map((item) => {\n if (isObject(item)) {\n return {\n loc: Array.isArray(item[\"loc\"])\n ? (item[\"loc\"] as (string | number)[])\n : [],\n msg: String(item[\"msg\"] ?? \"\"),\n type: String(item[\"type\"] ?? \"\"),\n };\n }\n return { loc: [], msg: String(item), type: \"\" };\n });\n}\n\n/**\n * Builds the matching `ProblemError` subclass from an error response. A body\n * that is not a JSON object yields a synthesized problem from the status\n * phrase. Reads a clone, so `response.body` stays readable.\n */\nexport async function problemFromResponse(\n response: Response,\n): Promise<ProblemError> {\n const status = response.status;\n const phrase = PHRASES.get(status) ?? \"Error\";\n let parsed: unknown;\n try {\n parsed = JSON.parse(await response.clone().text());\n } catch {\n parsed = undefined;\n }\n const body: Obj = isObject(parsed) ? parsed : {};\n const rawDetail = body[\"detail\"];\n const rawErrors = Array.isArray(rawDetail) ? rawDetail : body[\"errors\"];\n const Cls =\n BY_STATUS.get(status) ?? (status >= 500 ? ServerError : ProblemError);\n const instance = body[\"instance\"];\n return new Cls({\n status,\n title: String(body[\"title\"] || phrase),\n detail: typeof rawDetail === \"string\" ? rawDetail : undefined,\n type: String(body[\"type\"] || NO_TYPE),\n instance: typeof instance === \"string\" ? instance : undefined,\n errors: Array.isArray(rawErrors) ? normalizeErrors(rawErrors) : [],\n headers: response.headers,\n response,\n });\n}\n"],"mappings":";;;;;;AAMA,IAAa,YAAb,cAA+B,MAAM;CACnC,YAAY,SAAiB,SAAwB;EACnD,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO,WAAW;CACzB;AACF;;AAGA,IAAa,cAAb,cAAiC,UAAU,CAAC;;AAG5C,IAAa,kBAAb,cAAqC,YAAY,CAAC;;AAGlD,IAAa,oBAAb,cAAuC,YAAY,CAAC;;;;;;AAOpD,IAAa,yBAAb,cAA4C,YAAY,CAAC;;AAGzD,IAAa,gBAAb,cAAmC,YAAY,CAAC;;AAGhD,IAAa,uBAAb,cAA0C,YAAY,CAAC;;AAGvD,IAAa,gBAAb,cAAmC,UAAU,CAAC;;AAG9C,IAAa,mBAAb,cAAsC,UAAU,CAAC;AAqBjD,MAAM,UAAU;;AAGhB,MAAM,mBAAmB;AAEzB,SAAS,KAAK,MAAsB;CAClC,OAAO,KAAK,SAAS,mBACjB,GAAG,KAAK,MAAM,GAAG,gBAAgB,EAAE,OACnC;AACN;;;;;AAMA,SAAgB,YAAY,KAAqB;CAC/C,IAAI;EACF,MAAM,SAAS,IAAI,IAAI,GAAG;EAC1B,OAAO,WAAW;EAClB,OAAO,WAAW;EAClB,OAAO,SAA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;;AAOA,eAAsB,oBACpB,UACuB;CACvB,MAAM,SAAS,SAAS;CACxB,MAAM,SAAS,QAAQ,IAAI,MAAM,KAAK;CACtC,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,MAAM,SAAS,MAAM,CAAC,CAAC,KAAK,CAAC;CACnD,QAAQ;EACN,SAAS,KAAA;CACX;CACA,MAAM,OAAY,SAAS,MAAM,IAAI,SAAS,CAAC;CAC/C,MAAM,YAAY,KAAK;CACvB,MAAM,YAAY,MAAM,QAAQ,SAAS,IAAI,YAAY,KAAK;CAC9D,MAAM,MACJ,UAAU,IAAI,MAAM,MAAM,UAAU,MAAM,cAAc;CAC1D,MAAM,WAAW,KAAK;CACtB,OAAO,IAAI,IAAI;EACb;EACA,OAAO,OAAO,KAAK,YAAY,MAAM;EACrC,QAAQ,OAAO,cAAc,WAAW,YAAY,KAAA;EACpD,MAAM,OAAO,KAAK,WAAW,OAAO;EACpC,UAAU,OAAO,aAAa,WAAW,WAAW,KAAA;EACpD,QAAQ,MAAM,QAAQ,SAAS,IAAI,gBAAgB,SAAS,IAAI,CAAC;EACjE,SAAS,SAAS;EAClB;CACF,CAAC;AACH"}
@@ -1,3 +1,4 @@
1
+ import { b as describeUrl } from "./errors-ZdOt0_zk.mjs";
1
2
  //#region src/cache/policy.ts
2
3
  function seconds(value) {
3
4
  return typeof value === "number" && Number.isFinite(value) ? Math.max(value, 0) : 0;
@@ -452,6 +453,8 @@ const BACKOFF_START_MS = 1e3;
452
453
  const BACKOFF_MAX_MS = 3e4;
453
454
  const DEFAULT_KEEPALIVE_S = 15;
454
455
  const DEAD_AFTER_KEEPALIVES = 3;
456
+ /** Cap on the SSE parser's buffered characters (one unterminated line or event); past it the stream is dropped. */
457
+ const MAX_BUFFER_CHARS = 1048576;
455
458
  /** `setTimeout` clamps a longer delay to 1 ms, which would declare the stream dead at once. */
456
459
  const MAX_TIMER_MS = 2 ** 31 - 1;
457
460
  const ACTIONS = /* @__PURE__ */ new Set([
@@ -493,7 +496,7 @@ function warnOnDifferingOptions(hub, later) {
493
496
  const first = hubSettings(hub.events);
494
497
  const next = hubSettings(later.events);
495
498
  const differing = Object.keys(first).filter((key) => first[key] !== next[key]);
496
- if (differing.length > 0) console.warn(`crud-sdk: the event hub for ${hub.url} was opened with other events options; the first subscriber's win and these are ignored: ${differing.join(", ")}`);
499
+ if (differing.length > 0) console.warn(`crud-sdk: the event hub for ${describeUrl(hub.url)} was opened with other events options; the first subscriber's win and these are ignored: ${differing.join(", ")}`);
497
500
  }
498
501
  const registry = /* @__PURE__ */ new WeakMap();
499
502
  function sleep(ms, signal) {
@@ -608,16 +611,32 @@ var Hub = class {
608
611
  const reader = response.body.getReader();
609
612
  const decoder = new TextDecoder();
610
613
  const pending = [];
611
- const parser = createParser({ onEvent: (message) => {
612
- pending.push(message);
613
- } });
614
+ let overflow = false;
615
+ const parser = createParser({
616
+ maxBufferSize: MAX_BUFFER_CHARS,
617
+ onEvent: (message) => {
618
+ pending.push(message);
619
+ },
620
+ onError: (error) => {
621
+ overflow ||= error.type === "max-buffer-size-exceeded";
622
+ }
623
+ });
624
+ const closed = new Promise((_resolve, reject) => {
625
+ conn.signal.addEventListener("abort", () => {
626
+ reject(/* @__PURE__ */ new Error("event stream closed"));
627
+ }, { once: true });
628
+ });
629
+ closed.catch(() => void 0);
614
630
  for (;;) {
615
631
  const { done, value } = await reader.read();
616
632
  if (done) return;
617
- parser.feed(decoder.decode(value, { stream: true }));
618
- clearTimeout(timer);
619
- for (const message of pending.splice(0)) await this.handle(message);
620
633
  arm();
634
+ parser.feed(decoder.decode(value, { stream: true }));
635
+ for (const message of pending.splice(0)) {
636
+ arm();
637
+ await Promise.race([this.handle(message), closed]);
638
+ }
639
+ if (overflow) throw new Error("event stream line or event too large");
621
640
  }
622
641
  } finally {
623
642
  clearTimeout(timer);
@@ -709,4 +728,4 @@ function subscribeEvents(options) {
709
728
  //#endregion
710
729
  export { tanstackCachePolicy as a, cachePolicyFromManifest as i, subscribeEvents as n, resetOnce as r, getEventHub as t };
711
730
 
712
- //# sourceMappingURL=events-Dfz-rzC8.mjs.map
731
+ //# sourceMappingURL=events-swCOTQOS.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"events-Dfz-rzC8.mjs","names":[],"sources":["../src/cache/policy.ts","../src/reset-once.ts","../node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/errors.js","../node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/parse.js","../src/events.ts"],"sourcesContent":["/** Per-resource cache policy, defaulted from the manifest `cache` hints. */\n\n/**\n * How one resource is cached. Times are seconds. `maxAge` and\n * `staleWhileRevalidate` only take effect while the resource's SSE stream is\n * running; without it every read revalidates. `statsTtl` bounds the staleness\n * of `stats`/`predict` on its own, as the server caches those bodies for the\n * same time. `revalidateOnly` means no fresh window and no\n * stale-while-revalidate.\n */\nexport interface CachePolicy {\n readonly enabled: boolean;\n readonly maxAge: number;\n readonly statsTtl: number;\n readonly staleWhileRevalidate: number;\n readonly etag: boolean;\n readonly revalidateOnly: boolean;\n}\n\n/** The manifest resource members a policy reads (I1); everything else is ignored. */\nexport interface ManifestCacheHints {\n readonly cache?: {\n readonly max_age?: unknown;\n readonly stats_ttl?: unknown;\n readonly stale_while_revalidate?: unknown;\n readonly etag?: unknown;\n readonly revalidate_only?: unknown;\n } | null;\n}\n\nfunction seconds(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(value, 0)\n : 0;\n}\n\n/** Build a policy from a manifest resource object; `overrides` win over the hints. */\nexport function cachePolicyFromManifest(\n resource: ManifestCacheHints,\n overrides: Partial<CachePolicy> = {},\n): CachePolicy {\n const hints = resource.cache ?? {};\n return {\n enabled: overrides.enabled ?? true,\n maxAge: overrides.maxAge ?? seconds(hints.max_age),\n statsTtl: overrides.statsTtl ?? seconds(hints.stats_ttl),\n staleWhileRevalidate:\n overrides.staleWhileRevalidate ?? seconds(hints.stale_while_revalidate),\n etag: overrides.etag ?? hints.etag !== false,\n revalidateOnly: overrides.revalidateOnly ?? hints.revalidate_only === true,\n };\n}\n\n/**\n * The policy to use under TanStack Query: its `staleTime` decides freshness,\n * so the SDK cache only revalidates (ETag/304) unless told otherwise.\n */\nexport function tanstackCachePolicy(\n resource: ManifestCacheHints,\n overrides: Partial<CachePolicy> = {},\n): CachePolicy {\n return cachePolicyFromManifest(resource, {\n revalidateOnly: true,\n ...overrides,\n });\n}\n","/**\n * \"Reset once per target per connection\" (ADR 0002). A subscriber that is told\n * about a connection runs its reset through here; a second subscriber with the\n * same target (the same cache, or the same QueryClient, and resource) on the\n * same connection joins the first one's reset instead of running another.\n */\nimport type { EventConnection } from \"./events.ts\";\n\nconst ledger = new WeakMap<\n EventConnection,\n WeakMap<object, Map<string, Promise<void>>>\n>();\n\n/**\n * Runs `reset` unless `owner`/`key` was already reset on `connection`; resolves\n * when that reset is done, whoever started it. A failed reset is forgotten so\n * a later subscriber can retry.\n */\nexport function resetOnce(\n connection: EventConnection,\n owner: object,\n key: string,\n reset: () => Promise<void> | void,\n): Promise<void> {\n let owners = ledger.get(connection);\n if (owners === undefined) {\n owners = new WeakMap();\n ledger.set(connection, owners);\n }\n let keys = owners.get(owner);\n if (keys === undefined) {\n keys = new Map();\n owners.set(owner, keys);\n }\n const done = keys.get(key);\n if (done !== undefined) {\n return done;\n }\n const started = (async (): Promise<void> => {\n await reset();\n })();\n keys.set(key, started);\n const forget = keys;\n started.catch(() => {\n forget.delete(key);\n });\n return started;\n}\n","/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n constructor(message, options) {\n super(message);\n this.name = 'ParseError';\n this.type = options.type;\n this.field = options.field;\n this.value = options.value;\n this.line = options.line;\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport { ParseError } from './errors.js';\n// ASCII codes used in the hot parsing paths.\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst MAX_FIELD_PREFIX_LENGTH = 6;\n/**\n * Creates a new EventSource parser.\n *\n * @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})\n * and options like `maxBufferSize` (see {@link ParserConfig}).\n *\n * @returns A new EventSource parser, with `feed` and `reset` methods.\n * @public\n */\nexport function createParser(config) {\n if (typeof config === 'function') {\n throw new TypeError('`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?');\n }\n const { maxBufferSize, onComment, onError, onEvent, onId, onRetry } = config;\n // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n // Stored as an array of fragments and only joined when a line terminator arrives.\n // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n // server that emits one giant content block). Buffering as fragments + joining once\n // makes the same workload linear.\n const pendingFragments = [];\n // Running total of `pendingFragments` lengths, kept in sync with the array so the\n // `maxBufferSize` check doesn't have to walk the fragment list on every feed.\n let pendingFragmentsLength = 0;\n // Empty or partial leading BOM; undefined once the BOM check is complete.\n let bomPrefix = '';\n let id;\n let data = '';\n let dataLines = 0;\n let eventType;\n // Set after a `maxBufferSize` overflow. Once tripped, `feed()` throws until\n // `reset()` is called — see the comment on `maxBufferSize` in `ParserConfig`.\n let terminated = false;\n let skippingLine = false;\n // Set when a line (parsed or discarded) was terminated by a trailing `\\r` at the very\n // end of a chunk. That `\\r` is ambiguous: it may be a bare-CR terminator or the first\n // half of a `\\r\\n` whose `\\n` lands in the next chunk. The line itself is complete\n // either way, but we must remember to swallow a single leading `\\n` from the next\n // chunk so the pair is treated as one terminator rather than a blank line (which\n // would dispatch an event prematurely).\n let skipNextLineFeed = false;\n /**\n * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n * not yet form a complete line are held back and prepended to the next chunk,\n * so callers can pass arbitrary slices of the stream without worrying about\n * line boundaries.\n *\n * Per the SSE spec, one leading UTF-8 BOM is stripped before parsing,\n * even when split across chunks. This handles both the raw 3-byte form (0xEF 0xBB\n * 0xBF) and a single decoded U+FEFF, so a leading BOM is ignored regardless of\n * how the caller decoded the bytes.\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n */\n function feed(chunk) {\n if (terminated) {\n throw new Error('Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.');\n }\n if (bomPrefix !== undefined) {\n chunk = bomPrefix + chunk;\n // Wait only while the input could still be a raw BOM. Empty chunks must\n // not finish the check, and a mismatched prefix must remain ordinary input.\n if (chunk === '' || chunk === '\\xEF' || chunk === '\\xEF\\xBB') {\n bomPrefix = chunk;\n return;\n }\n bomPrefix = undefined;\n // Strip exactly one leading BOM, in decoded or raw byte-valued form.\n chunk = chunk.replace(/^(?:\\uFEFF|\\xEF\\xBB\\xBF)/, '');\n }\n // Rare resume states from a prior chunk boundary: a pending `\\r\\n` split or a\n // line being discarded. Single combined check keeps the hot path to one branch;\n // the actual handling lives out-of-line in `resumeAfterSkip`.\n if (skippingLine || skipNextLineFeed) {\n chunk = resumeAfterSkip(chunk);\n if (!chunk) {\n return;\n }\n }\n // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n // straight to `processLines`, exactly like the original implementation.\n // Zero new work in the common case (every chunk ends with `\\n\\n`).\n if (!pendingFragments.length) {\n const trailing = processLines(chunk);\n if (trailing !== '') {\n storeTrailing(trailing);\n }\n checkForBufferOverflow();\n return;\n }\n // We have a buffered prefix. If this chunk also has no terminator, append\n // to the buffer without concatenating — that's the O(N²) trap we're\n // avoiding (large single `data:` payload split across many tiny chunks).\n if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n if (pendingFragmentsLength < MAX_FIELD_PREFIX_LENGTH) {\n const head = pendingFragments.join('') +\n chunk.slice(0, MAX_FIELD_PREFIX_LENGTH - pendingFragmentsLength);\n if (!shouldBufferTrailing(head)) {\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n skippingLine = true;\n return;\n }\n }\n pendingFragments.push(chunk);\n pendingFragmentsLength += chunk.length;\n checkForBufferOverflow();\n return;\n }\n // Terminator arrived. Join the accumulated fragments + this chunk once,\n // process, and buffer any new trailing partial line.\n pendingFragments.push(chunk);\n const input = pendingFragments.join('');\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n storeTrailing(processLines(input));\n checkForBufferOverflow();\n }\n // Out-of-line handler for the rare post-boundary states. `skipNextLineFeed` means a\n // line (parsed or discarded) ended with a trailing `\\r` at the previous chunk boundary,\n // so a single leading `\\n` must be swallowed to consume a split `\\r\\n` as one terminator.\n // `skippingLine` means we are discarding an invalid line until its terminator arrives.\n // The two states are mutually exclusive. Returns the remaining chunk to parse ('' if\n // this chunk was fully consumed).\n function resumeAfterSkip(chunk) {\n if (chunk.length === 0) {\n return chunk;\n }\n if (skipNextLineFeed) {\n skipNextLineFeed = false;\n return chunk.charCodeAt(0) === LF ? chunk.slice(1) : chunk;\n }\n const crIndex = chunk.indexOf('\\r');\n const lfIndex = chunk.indexOf('\\n');\n const lineEnd = crIndex === -1 ? lfIndex : lfIndex === -1 ? crIndex : crIndex < lfIndex ? crIndex : lfIndex;\n if (lineEnd === -1) {\n return '';\n }\n // Trailing `\\r` at the very end of the chunk: defer the CRLF/CR decision to the\n // next chunk (see `skipNextLineFeed`) rather than greedily consuming just the `\\r`.\n if (lineEnd === chunk.length - 1 && chunk.charCodeAt(lineEnd) === CR) {\n skippingLine = false;\n skipNextLineFeed = true;\n return '';\n }\n skippingLine = false;\n return chunk.slice(lineEnd + (chunk.charCodeAt(lineEnd) === CR && chunk.charCodeAt(lineEnd + 1) === LF ? 2 : 1));\n }\n function storeTrailing(trailing) {\n if (!trailing)\n return;\n // A trailing that ends with `\\r` is not a partial line: the `\\r` terminates it,\n // and only the CRLF-vs-CR ambiguity remains (the matching `\\n` may start the next\n // chunk). Parse the completed line now — buffering it could grow unbounded through\n // the no-terminator append path, and discarding it would eat the terminator and\n // make skip mode swallow the next line.\n if (trailing.charCodeAt(trailing.length - 1) === CR) {\n parseLine(trailing, 0, trailing.length - 1);\n if (checkForBufferOverflow())\n return;\n skipNextLineFeed = true;\n return;\n }\n if (shouldBufferTrailing(trailing)) {\n pendingFragments.push(trailing);\n pendingFragmentsLength = trailing.length;\n return;\n }\n skippingLine = true;\n }\n function shouldBufferTrailing(trailing) {\n const firstCharCode = trailing.charCodeAt(0);\n return ((firstCharCode === 58 && !!onComment) ||\n (firstCharCode === 100 && isPotentialField(trailing, 'data')) ||\n (firstCharCode === 101 && isPotentialField(trailing, 'event')) ||\n (firstCharCode === 105 && isPotentialField(trailing, 'id')) ||\n (firstCharCode === 114 && isPotentialField(trailing, 'retry')));\n }\n // Returns true when parsing must stop for the current chunk (the parser was already\n // terminated or has just overflowed), and false when processing can continue.\n function checkForBufferOverflow() {\n if (terminated)\n return true;\n if (maxBufferSize === undefined)\n return false;\n if (pendingFragmentsLength + data.length <= maxBufferSize)\n return false;\n terminated = true;\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n skippingLine = false;\n skipNextLineFeed = false;\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: 'max-buffer-size-exceeded',\n }));\n return true;\n }\n /**\n * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n * Returns any trailing bytes that did not terminate with a line break, so the\n * caller can prepend them to the next chunk.\n *\n * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n * present in the chunk. The slow path is spec-correct but does more work per line.\n */\n function processLines(chunk) {\n let searchIndex = 0;\n // Fast path: LF-only chunk (the common case for typical SSE servers).\n // We can scan forward with a single `indexOf('\\n')` per line and inline\n // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n // the slow path needs.\n if (chunk.indexOf('\\r') === -1) {\n let lfIndex = chunk.indexOf('\\n', searchIndex);\n while (lfIndex !== -1) {\n // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n // and reset the buffered fields. This is hoisted out of `parseLine` because\n // it's the single most common line shape after `data:` lines.\n if (searchIndex === lfIndex) {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n if (dataLines > 0) {\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({ id, event: eventType, data });\n }\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n searchIndex = lfIndex + 1;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n // `data:` line — append the value to the event's data buffer.\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5;\n const value = chunk.slice(valueStart, lfIndex);\n // Fast path within a fast path: if this is the first data line AND the\n // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n // without ever writing to the `data` buffer. This is the shape of a\n // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n // hot enough to be worth the duplication.\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({ id, event: eventType, data: value });\n id = undefined;\n data = '';\n eventType = undefined;\n searchIndex = lfIndex + 2;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n continue;\n }\n // Multi-line data: concatenate with newline separator per spec.\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n }\n else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n // `event:` line — set the event type for the next dispatch. Per spec,\n // an empty value resets `event type` to its default (undefined here).\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || undefined;\n }\n else {\n // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n // fields, or malformed lines. These are rarer and go through the full\n // per-line parser, which handles the SSE field grammar in detail.\n parseLine(chunk, searchIndex, lfIndex);\n }\n if (checkForBufferOverflow())\n return '';\n searchIndex = lfIndex + 1;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n // the nearest `\\r` and `\\n` and picking whichever comes first.\n while (searchIndex < chunk.length) {\n const crIndex = chunk.indexOf('\\r', searchIndex);\n const lfIndex = chunk.indexOf('\\n', searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1) {\n lineEnd = crIndex < lfIndex ? crIndex : lfIndex;\n }\n else if (crIndex !== -1) {\n // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n // in the next chunk. Defer until we see more input.\n if (crIndex === chunk.length - 1) {\n lineEnd = -1;\n }\n else {\n lineEnd = crIndex;\n }\n }\n else if (lfIndex !== -1) {\n lineEnd = lfIndex;\n }\n if (lineEnd === -1) {\n break;\n }\n parseLine(chunk, searchIndex, lineEnd);\n if (checkForBufferOverflow())\n return '';\n searchIndex = lineEnd + 1;\n // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n // pair is treated as a single terminator rather than an empty line.\n if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n searchIndex++;\n }\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5;\n const value = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined;\n return;\n }\n // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n if (firstCharCode === 105 &&\n chunk.charCodeAt(start + 1) === 100 &&\n chunk.charCodeAt(start + 2) === 58) {\n // 'id:'.length === 3, 'id: '.length === 4\n const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0'))\n id = value;\n return;\n }\n // Comment line — ':' = 58\n if (firstCharCode === 58) {\n if (onComment) {\n const line = chunk.slice(start, end);\n // skip ':' (+1), or ': ' (+2) when a space follows\n onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end);\n const fieldSeparatorIndex = line.indexOf(':');\n if (fieldSeparatorIndex === -1) {\n processField(line, '', line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex);\n // skip ':' (+1), or ': ' (+2) when a space follows\n const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;\n const value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n // Field names must be compared literally, with no case folding performed.\n switch (field) {\n case 'event':\n // Set the `event type` buffer to field value\n eventType = value || undefined;\n break;\n case 'data':\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n break;\n case 'id':\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0'))\n id = value;\n break;\n case 'retry':\n // If the field value consists of only ASCII digits, then interpret the field value as an\n // integer in base ten, and set the event stream's reconnection time to that integer.\n // Otherwise, ignore the field.\n if (/^\\d+$/.test(value)) {\n onRetry === null || onRetry === void 0 ? void 0 : onRetry(parseInt(value, 10));\n }\n else {\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: 'invalid-retry',\n value,\n line,\n }));\n }\n break;\n default:\n // Otherwise, the field is ignored.\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`, { type: 'unknown-field', field, value, line }));\n break;\n }\n }\n function dispatchEvent() {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n if (dataLines > 0) {\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({\n id,\n event: eventType,\n data,\n });\n }\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join('');\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n bomPrefix = '';\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n terminated = false;\n skippingLine = false;\n skipNextLineFeed = false;\n }\n return { feed, reset };\n}\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return (firstCharCode === 100 &&\n chunk.charCodeAt(i + 1) === 97 &&\n chunk.charCodeAt(i + 2) === 116 &&\n chunk.charCodeAt(i + 3) === 97 &&\n chunk.charCodeAt(i + 4) === 58);\n}\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return (firstCharCode === 101 &&\n chunk.charCodeAt(i + 1) === 118 &&\n chunk.charCodeAt(i + 2) === 101 &&\n chunk.charCodeAt(i + 3) === 110 &&\n chunk.charCodeAt(i + 4) === 116 &&\n chunk.charCodeAt(i + 5) === 58);\n}\nfunction isPotentialField(line, field) {\n let i = 1;\n while (i < line.length && i < field.length) {\n if (line.charCodeAt(i) !== field.charCodeAt(i)) {\n return false;\n }\n i++;\n }\n return line.length <= field.length || line.charCodeAt(field.length) === 58;\n}\n//# sourceMappingURL=parse.js.map","/**\n * SSE subscriber that turns `GET {base_path}/events` into callbacks.\n *\n * One connection per (fetch, url), reference-counted and fanned out to every\n * subscriber. The caller passes an already authenticated `fetch`: this is\n * fetch streaming, not `EventSource`, because `EventSource` cannot send an\n * Authorization header. Frames carry no `event:` name: the first has\n * `id: 0` and `{\"subscriber_id\": ...}`; later ones are record events. A\n * reconnect passes `?{resume_param}=<subscriber_id>` explicitly (never\n * `Last-Event-ID`, which the server would read as a subscriber id) when the\n * stream replays, and always tells subscribers to reset, so the gap is\n * covered even without replay. A stream silent for three keep-alive\n * intervals is dead and is reconnected with exponential backoff and jitter.\n * Events invalidate; they never apply snapshots.\n *\n * A hub is shared by every subscriber of the same (fetch, url) and the first\n * subscriber's options win: the keep-alive, resume parameter, replay mode and\n * resource label of later subscribers are ignored. In development\n * (`process.env.NODE_ENV !== \"production\"`) a later subscriber whose options\n * differ gets a `console.warn` naming the URL and the fields.\n *\n * Every connection has an identity (an opaque {@link EventConnection}) that\n * the hub passes to `onReset` (for the connect reset) and to `onStatus(true)`.\n * A subscriber that joins an already connected hub, or during the handshake's\n * reset fan-out, gets no connect reset; it sees `onStatus(true)` with a\n * connection it was never reset for and resets itself (see `invalidateOnEvents`\n * and `bridgeEvents`).\n */\nimport { createParser } from \"eventsource-parser\";\nimport type { EventSourceMessage } from \"eventsource-parser\";\nimport type { CrudEvent, MaybePromise } from \"./interfaces.ts\";\n\n/** The manifest's `capabilities.events` object (I1), plain. */\nexport interface EventsConfig {\n /** The server's event label, not the manifest name. */\n readonly resource: string;\n readonly path?: string;\n readonly resume_param?: string;\n /** `persistent` resumes by subscriber id; anything else (`none`) does not. A plain string, as on the wire. */\n readonly replay?: string;\n readonly keepalive_seconds?: number;\n}\n\n/** Opaque identity of one connection of a hub; a new one per connect. */\nexport type EventConnection = object;\n\n/**\n * What a subscriber wants to hear. A handler that throws must not kill the\n * stream, so errors are swallowed; handlers run one after another, in order.\n */\nexport interface EventHandlers {\n onEvent(event: CrudEvent): MaybePromise<void>;\n /**\n * After every connect (the first included), and for an event with no usable\n * record id: clear the resource. `connection` is set for the connect reset\n * only, and is the same object `onStatus(true)` then receives.\n */\n onReset?(connection?: EventConnection): MaybePromise<void>;\n /**\n * `true` when the stream is connected, `false` on any loss, exit or\n * unsubscribe. `connection` identifies the connection when `connected`.\n * A subscriber that joined after the connect reset gets `true` without\n * having been sent `onReset` for that connection.\n */\n onStatus?(\n connected: boolean,\n connection?: EventConnection,\n ): MaybePromise<void>;\n}\n\n/** A shared event stream: `subscribe` returns the (idempotent) unsubscribe. */\nexport interface EventHub {\n subscribe(handlers: EventHandlers): () => void;\n}\n\nexport interface EventHubOptions {\n /** Authenticated; shared hubs are keyed by this function and `url`. */\n readonly fetch: typeof fetch;\n /** Absolute URL of the events endpoint. */\n readonly url: string;\n /**\n * Used only by the first subscriber of a hub (first wins): a later\n * subscriber's differing `resource`, `resume_param`, `replay` or\n * `keepalive_seconds` is ignored, with a development `console.warn`.\n */\n readonly events: EventsConfig;\n /** Jitter source in `[0, 1)`; defaults to `Math.random`. */\n readonly random?: () => number;\n}\n\nexport interface SubscribeEventsOptions extends EventHubOptions, EventHandlers {\n /** Aborting unsubscribes. */\n readonly signal?: AbortSignal;\n}\n\nconst BACKOFF_START_MS = 1000;\nconst BACKOFF_MAX_MS = 30_000;\nconst DEFAULT_KEEPALIVE_S = 15;\nconst DEAD_AFTER_KEEPALIVES = 3;\n/** `setTimeout` clamps a longer delay to 1 ms, which would declare the stream dead at once. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\nconst ACTIONS: ReadonlySet<unknown> = new Set([\n \"create\",\n \"update\",\n \"delete\",\n \"restore\",\n]);\n\n/**\n * The keep-alive interval in seconds. Zero, negative and non-finite values\n * are invalid and treated as unset, so the default applies (as the WHATWG SSE\n * spec ignores an invalid `retry` value instead of acting on it); otherwise a\n * dead-stream deadline of 0 would reconnect forever.\n */\nfunction keepaliveSeconds(events: EventsConfig): number {\n const value = events.keepalive_seconds;\n return value !== undefined && Number.isFinite(value) && value > 0\n ? value\n : DEFAULT_KEEPALIVE_S;\n}\n\n/** The `events` fields that change what a hub does, with defaults applied. */\nfunction hubSettings(events: EventsConfig): Record<string, unknown> {\n return {\n resource: events.resource,\n resume_param: events.resume_param ?? \"subscriber_id\",\n replay: events.replay,\n keepalive_seconds: keepaliveSeconds(events),\n };\n}\n\n/** `process.env.NODE_ENV` is replaced by bundlers; without it (no `process`) assume development. */\nfunction inDevelopment(): boolean {\n try {\n return process.env.NODE_ENV !== \"production\";\n } catch {\n return true;\n }\n}\n\n/** Warns, in development, that a later subscriber's options differ from the hub's. */\nfunction warnOnDifferingOptions(\n hub: EventHubOptions,\n later: EventHubOptions,\n): void {\n if (!inDevelopment()) {\n return;\n }\n const first = hubSettings(hub.events);\n const next = hubSettings(later.events);\n const differing = Object.keys(first).filter(\n (key) => first[key] !== next[key],\n );\n if (differing.length > 0) {\n console.warn(\n `crud-sdk: the event hub for ${hub.url} was opened with other events options; ` +\n `the first subscriber's win and these are ignored: ${differing.join(\", \")}`,\n );\n }\n}\n\nconst registry = new WeakMap<typeof fetch, Map<string, Hub>>();\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n const done = (): void => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nclass Hub {\n private readonly handlers = new Set<EventHandlers>();\n private readonly options: EventHubOptions;\n private readonly onEmpty: () => void;\n private controller: AbortController | undefined;\n private connected = false;\n private connection: EventConnection | undefined;\n private subscriberId: string | undefined;\n private attempt = 0;\n\n constructor(options: EventHubOptions, onEmpty: () => void) {\n this.options = options;\n this.onEmpty = onEmpty;\n }\n\n subscribe(handlers: EventHandlers, requested: EventHubOptions): () => void {\n if (this.handlers.size > 0) {\n warnOnDifferingOptions(this.options, requested);\n }\n // The same object may subscribe twice; give each subscription its own identity.\n const entry: EventHandlers = {\n onEvent: (event) => handlers.onEvent(event),\n onReset: (connection) => handlers.onReset?.(connection),\n onStatus: (connected, connection) =>\n handlers.onStatus?.(connected, connection),\n };\n this.handlers.add(entry);\n if (this.controller === undefined) {\n this.controller = new AbortController();\n void this.run(this.controller.signal);\n } else if (this.connected) {\n void this.guard(() => entry.onStatus?.(true, this.connection));\n }\n return () => {\n if (!this.handlers.delete(entry)) {\n return;\n }\n void this.guard(() => entry.onStatus?.(false));\n if (this.handlers.size === 0) {\n // Abort the live stream instead of waiting for the next frame.\n this.controller?.abort();\n this.controller = undefined;\n this.onEmpty();\n }\n };\n }\n\n private async guard(\n call: () => MaybePromise<void> | undefined,\n ): Promise<void> {\n try {\n await call();\n } catch {\n // A failing subscriber must not take the stream down.\n }\n }\n\n private async fan(\n call: (handlers: EventHandlers) => MaybePromise<void> | undefined,\n ): Promise<void> {\n // A snapshot, so a subscriber added during dispatch waits for the next\n // one; one removed meanwhile (its unsubscribe already ran) is skipped.\n for (const handlers of Array.from(this.handlers)) {\n if (this.handlers.has(handlers)) {\n await this.guard(() => call(handlers));\n }\n }\n }\n\n private async setConnected(\n connected: boolean,\n connection?: EventConnection,\n ): Promise<void> {\n if (this.connected === connected) {\n return;\n }\n this.connected = connected;\n this.connection = connected ? connection : undefined;\n await this.fan((handlers) => handlers.onStatus?.(connected, connection));\n }\n\n private backoff(): number {\n const base = Math.min(BACKOFF_START_MS * 2 ** this.attempt, BACKOFF_MAX_MS);\n this.attempt += 1;\n const jitter = (this.options.random ?? Math.random)();\n return Math.min(base * (1 + 0.5 * jitter), BACKOFF_MAX_MS);\n }\n\n /** Connect, read and reconnect until aborted. */\n private async run(signal: AbortSignal): Promise<void> {\n try {\n while (!signal.aborted) {\n try {\n await this.readOnce(signal);\n } catch {\n // Lost, refused or dead: reconnect below.\n }\n await this.setConnected(false);\n await sleep(this.backoff(), signal);\n }\n } finally {\n // On any exit, tell the subscribers so the freshness gate closes.\n await this.setConnected(false);\n }\n }\n\n private resumeUrl(): string {\n const { url, events } = this.options;\n if (events.replay !== \"persistent\" || this.subscriberId === undefined) {\n return url;\n }\n const param = events.resume_param ?? \"subscriber_id\";\n const separator = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${separator}${encodeURIComponent(param)}=${encodeURIComponent(this.subscriberId)}`;\n }\n\n private async readOnce(signal: AbortSignal): Promise<void> {\n const deadMs = Math.min(\n keepaliveSeconds(this.options.events) * DEAD_AFTER_KEEPALIVES * 1000,\n MAX_TIMER_MS,\n );\n const conn = new AbortController();\n const abortConn = (): void => {\n conn.abort();\n };\n signal.addEventListener(\"abort\", abortConn, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const arm = (): void => {\n clearTimeout(timer);\n timer = setTimeout(abortConn, deadMs);\n };\n try {\n arm();\n const response = await this.options.fetch(this.resumeUrl(), {\n headers: { accept: \"text/event-stream\" },\n signal: conn.signal,\n });\n if (!response.ok || response.body === null) {\n throw new Error(`event stream refused: HTTP ${response.status}`);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const pending: EventSourceMessage[] = [];\n const parser = createParser({\n onEvent: (message) => {\n pending.push(message);\n },\n });\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n parser.feed(decoder.decode(value, { stream: true }));\n // Any byte, keep-alive comments included, proves the stream is alive.\n // Handlers may be slow and nothing is read meanwhile, so the timer is\n // paused while they run and restarts once they are done.\n clearTimeout(timer);\n for (const message of pending.splice(0)) {\n await this.handle(message);\n }\n arm();\n }\n } finally {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", abortConn);\n conn.abort(); // release the connection on every way out\n }\n }\n\n private async handle(message: EventSourceMessage): Promise<void> {\n let data: unknown;\n try {\n data = JSON.parse(message.data);\n } catch {\n return;\n }\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return;\n }\n const record = data as Record<string, unknown>;\n if (\"subscriber_id\" in record) {\n this.subscriberId = String(record[\"subscriber_id\"]);\n this.attempt = 0;\n // Every connect, the first included: entries stored before this stream\n // (an earlier page session, a persisted store) may predate server changes.\n // A subscriber that joins while this fans out is not in it; it gets\n // `onStatus(true)` with this connection and resets itself.\n const connection: EventConnection = {};\n const present = new Set(this.handlers);\n await this.fan((handlers) => handlers.onReset?.(connection));\n if (this.connected) {\n // A repeated handshake on a live stream: whoever joined during the\n // fan-out was told about the old connection only.\n this.connection = connection;\n for (const handlers of Array.from(this.handlers)) {\n if (!present.has(handlers)) {\n await this.guard(() => handlers.onStatus?.(true, connection));\n }\n }\n } else {\n await this.setConnected(true, connection);\n }\n return;\n }\n if (record[\"resource\"] !== this.options.events.resource) {\n return;\n }\n const action = record[\"action\"];\n const recordId = record[\"record_id\"];\n if (!ACTIONS.has(action) || !Number.isInteger(recordId)) {\n await this.fan((handlers) => handlers.onReset?.());\n return;\n }\n const snapshot = record[\"snapshot\"];\n const event: CrudEvent = {\n resource: String(record[\"resource\"]),\n recordId: recordId as number,\n action: action as CrudEvent[\"action\"],\n snapshot:\n typeof snapshot === \"object\" && snapshot !== null\n ? (snapshot as Record<string, unknown>)\n : {},\n timestamp: String(record[\"timestamp\"] ?? \"\"),\n };\n await this.fan((handlers) => handlers.onEvent(event));\n }\n}\n\n/**\n * The shared hub for `(fetch, url)`: the first subscriber opens the stream,\n * the last one aborts it. A later subscribe after that opens a fresh one.\n *\n * The first subscriber's `events` options win while the hub lives. A later\n * subscriber whose `resource`, `resume_param`, `replay` or `keepalive_seconds`\n * differ is served by the same stream with the first's values, and in\n * development (`process.env.NODE_ENV !== \"production\"`) gets a `console.warn`\n * naming the URL and the differing fields.\n */\nexport function getEventHub(options: EventHubOptions): EventHub {\n return {\n subscribe(handlers) {\n let hubs = registry.get(options.fetch);\n if (hubs === undefined) {\n hubs = new Map();\n registry.set(options.fetch, hubs);\n }\n const byUrl = hubs;\n let hub = byUrl.get(options.url);\n if (hub === undefined) {\n hub = new Hub(options, () => {\n byUrl.delete(options.url);\n });\n byUrl.set(options.url, hub);\n }\n return hub.subscribe(handlers, options);\n },\n };\n}\n\n/**\n * Subscribe to one resource's event stream. Returns the unsubscribe; the\n * last unsubscribe aborts the stream. `signal` aborting unsubscribes too.\n */\nexport function subscribeEvents(options: SubscribeEventsOptions): () => void {\n const { signal } = options;\n if (signal?.aborted === true) {\n return () => undefined;\n }\n const unsubscribe = getEventHub(options).subscribe(options);\n signal?.addEventListener(\"abort\", unsubscribe, { once: true });\n return () => {\n signal?.removeEventListener(\"abort\", unsubscribe);\n unsubscribe();\n };\n}\n"],"ignoreList":[2,3],"mappings":";AA8BA,SAAS,QAAQ,OAAwB;CACvC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IACrD,KAAK,IAAI,OAAO,CAAC,IACjB;AACN;;AAGA,SAAgB,wBACd,UACA,YAAkC,CAAC,GACtB;CACb,MAAM,QAAQ,SAAS,SAAS,CAAC;CACjC,OAAO;EACL,SAAS,UAAU,WAAW;EAC9B,QAAQ,UAAU,UAAU,QAAQ,MAAM,OAAO;EACjD,UAAU,UAAU,YAAY,QAAQ,MAAM,SAAS;EACvD,sBACE,UAAU,wBAAwB,QAAQ,MAAM,sBAAsB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f,SAAS,IAAI,QAAQ,OAAO,IAAI;EAClC;EACA,MAAM,QAAQ;EACd,IAAI,MAAM,MAAM,IAAI,QAAQ,GAAG;EAC/B,IAAI,QAAQ,KAAA,GAAW;GACrB,MAAM,IAAI,IAAI,eAAe;IAC3B,MAAM,OAAO,QAAQ,GAAG;GAC1B,CAAC;GACD,MAAM,IAAI,QAAQ,KAAK,GAAG;EAC5B;EACA,OAAO,IAAI,UAAU,UAAU,OAAO;CACxC,EACF;AACF;;;;;AAMA,SAAgB,gBAAgB,SAA6C;CAC3E,MAAM,EAAE,WAAW;CACnB,IAAI,QAAQ,YAAY,MACtB,aAAa,KAAA;CAEf,MAAM,cAAc,YAAY,OAAO,CAAC,CAAC,UAAU,OAAO;CAC1D,QAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,KAAK,CAAC;CAC7D,aAAa;EACX,QAAQ,oBAAoB,SAAS,WAAW;EAChD,YAAY;CACd;AACF"}
1
+ {"version":3,"file":"events-swCOTQOS.mjs","names":[],"sources":["../src/cache/policy.ts","../src/reset-once.ts","../node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/errors.js","../node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/parse.js","../src/events.ts"],"sourcesContent":["/** Per-resource cache policy, defaulted from the manifest `cache` hints. */\n\n/**\n * How one resource is cached. Times are seconds. `maxAge` and\n * `staleWhileRevalidate` only take effect while the resource's SSE stream is\n * running; without it every read revalidates. `statsTtl` bounds the staleness\n * of `stats`/`predict` on its own, as the server caches those bodies for the\n * same time. `revalidateOnly` means no fresh window and no\n * stale-while-revalidate.\n */\nexport interface CachePolicy {\n readonly enabled: boolean;\n readonly maxAge: number;\n readonly statsTtl: number;\n readonly staleWhileRevalidate: number;\n readonly etag: boolean;\n readonly revalidateOnly: boolean;\n}\n\n/** The manifest resource members a policy reads (I1); everything else is ignored. */\nexport interface ManifestCacheHints {\n readonly cache?: {\n readonly max_age?: unknown;\n readonly stats_ttl?: unknown;\n readonly stale_while_revalidate?: unknown;\n readonly etag?: unknown;\n readonly revalidate_only?: unknown;\n } | null;\n}\n\nfunction seconds(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(value, 0)\n : 0;\n}\n\n/** Build a policy from a manifest resource object; `overrides` win over the hints. */\nexport function cachePolicyFromManifest(\n resource: ManifestCacheHints,\n overrides: Partial<CachePolicy> = {},\n): CachePolicy {\n const hints = resource.cache ?? {};\n return {\n enabled: overrides.enabled ?? true,\n maxAge: overrides.maxAge ?? seconds(hints.max_age),\n statsTtl: overrides.statsTtl ?? seconds(hints.stats_ttl),\n staleWhileRevalidate:\n overrides.staleWhileRevalidate ?? seconds(hints.stale_while_revalidate),\n etag: overrides.etag ?? hints.etag !== false,\n revalidateOnly: overrides.revalidateOnly ?? hints.revalidate_only === true,\n };\n}\n\n/**\n * The policy to use under TanStack Query: its `staleTime` decides freshness,\n * so the SDK cache only revalidates (ETag/304) unless told otherwise.\n */\nexport function tanstackCachePolicy(\n resource: ManifestCacheHints,\n overrides: Partial<CachePolicy> = {},\n): CachePolicy {\n return cachePolicyFromManifest(resource, {\n revalidateOnly: true,\n ...overrides,\n });\n}\n","/**\n * \"Reset once per target per connection\" (ADR 0002). A subscriber that is told\n * about a connection runs its reset through here; a second subscriber with the\n * same target (the same cache, or the same QueryClient, and resource) on the\n * same connection joins the first one's reset instead of running another.\n */\nimport type { EventConnection } from \"./events.ts\";\n\nconst ledger = new WeakMap<\n EventConnection,\n WeakMap<object, Map<string, Promise<void>>>\n>();\n\n/**\n * Runs `reset` unless `owner`/`key` was already reset on `connection`; resolves\n * when that reset is done, whoever started it. A failed reset is forgotten so\n * a later subscriber can retry.\n */\nexport function resetOnce(\n connection: EventConnection,\n owner: object,\n key: string,\n reset: () => Promise<void> | void,\n): Promise<void> {\n let owners = ledger.get(connection);\n if (owners === undefined) {\n owners = new WeakMap();\n ledger.set(connection, owners);\n }\n let keys = owners.get(owner);\n if (keys === undefined) {\n keys = new Map();\n owners.set(owner, keys);\n }\n const done = keys.get(key);\n if (done !== undefined) {\n return done;\n }\n const started = (async (): Promise<void> => {\n await reset();\n })();\n keys.set(key, started);\n const forget = keys;\n started.catch(() => {\n forget.delete(key);\n });\n return started;\n}\n","/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n constructor(message, options) {\n super(message);\n this.name = 'ParseError';\n this.type = options.type;\n this.field = options.field;\n this.value = options.value;\n this.line = options.line;\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport { ParseError } from './errors.js';\n// ASCII codes used in the hot parsing paths.\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst MAX_FIELD_PREFIX_LENGTH = 6;\n/**\n * Creates a new EventSource parser.\n *\n * @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})\n * and options like `maxBufferSize` (see {@link ParserConfig}).\n *\n * @returns A new EventSource parser, with `feed` and `reset` methods.\n * @public\n */\nexport function createParser(config) {\n if (typeof config === 'function') {\n throw new TypeError('`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?');\n }\n const { maxBufferSize, onComment, onError, onEvent, onId, onRetry } = config;\n // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n // Stored as an array of fragments and only joined when a line terminator arrives.\n // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n // server that emits one giant content block). Buffering as fragments + joining once\n // makes the same workload linear.\n const pendingFragments = [];\n // Running total of `pendingFragments` lengths, kept in sync with the array so the\n // `maxBufferSize` check doesn't have to walk the fragment list on every feed.\n let pendingFragmentsLength = 0;\n // Empty or partial leading BOM; undefined once the BOM check is complete.\n let bomPrefix = '';\n let id;\n let data = '';\n let dataLines = 0;\n let eventType;\n // Set after a `maxBufferSize` overflow. Once tripped, `feed()` throws until\n // `reset()` is called — see the comment on `maxBufferSize` in `ParserConfig`.\n let terminated = false;\n let skippingLine = false;\n // Set when a line (parsed or discarded) was terminated by a trailing `\\r` at the very\n // end of a chunk. That `\\r` is ambiguous: it may be a bare-CR terminator or the first\n // half of a `\\r\\n` whose `\\n` lands in the next chunk. The line itself is complete\n // either way, but we must remember to swallow a single leading `\\n` from the next\n // chunk so the pair is treated as one terminator rather than a blank line (which\n // would dispatch an event prematurely).\n let skipNextLineFeed = false;\n /**\n * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n * not yet form a complete line are held back and prepended to the next chunk,\n * so callers can pass arbitrary slices of the stream without worrying about\n * line boundaries.\n *\n * Per the SSE spec, one leading UTF-8 BOM is stripped before parsing,\n * even when split across chunks. This handles both the raw 3-byte form (0xEF 0xBB\n * 0xBF) and a single decoded U+FEFF, so a leading BOM is ignored regardless of\n * how the caller decoded the bytes.\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n */\n function feed(chunk) {\n if (terminated) {\n throw new Error('Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.');\n }\n if (bomPrefix !== undefined) {\n chunk = bomPrefix + chunk;\n // Wait only while the input could still be a raw BOM. Empty chunks must\n // not finish the check, and a mismatched prefix must remain ordinary input.\n if (chunk === '' || chunk === '\\xEF' || chunk === '\\xEF\\xBB') {\n bomPrefix = chunk;\n return;\n }\n bomPrefix = undefined;\n // Strip exactly one leading BOM, in decoded or raw byte-valued form.\n chunk = chunk.replace(/^(?:\\uFEFF|\\xEF\\xBB\\xBF)/, '');\n }\n // Rare resume states from a prior chunk boundary: a pending `\\r\\n` split or a\n // line being discarded. Single combined check keeps the hot path to one branch;\n // the actual handling lives out-of-line in `resumeAfterSkip`.\n if (skippingLine || skipNextLineFeed) {\n chunk = resumeAfterSkip(chunk);\n if (!chunk) {\n return;\n }\n }\n // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n // straight to `processLines`, exactly like the original implementation.\n // Zero new work in the common case (every chunk ends with `\\n\\n`).\n if (!pendingFragments.length) {\n const trailing = processLines(chunk);\n if (trailing !== '') {\n storeTrailing(trailing);\n }\n checkForBufferOverflow();\n return;\n }\n // We have a buffered prefix. If this chunk also has no terminator, append\n // to the buffer without concatenating — that's the O(N²) trap we're\n // avoiding (large single `data:` payload split across many tiny chunks).\n if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n if (pendingFragmentsLength < MAX_FIELD_PREFIX_LENGTH) {\n const head = pendingFragments.join('') +\n chunk.slice(0, MAX_FIELD_PREFIX_LENGTH - pendingFragmentsLength);\n if (!shouldBufferTrailing(head)) {\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n skippingLine = true;\n return;\n }\n }\n pendingFragments.push(chunk);\n pendingFragmentsLength += chunk.length;\n checkForBufferOverflow();\n return;\n }\n // Terminator arrived. Join the accumulated fragments + this chunk once,\n // process, and buffer any new trailing partial line.\n pendingFragments.push(chunk);\n const input = pendingFragments.join('');\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n storeTrailing(processLines(input));\n checkForBufferOverflow();\n }\n // Out-of-line handler for the rare post-boundary states. `skipNextLineFeed` means a\n // line (parsed or discarded) ended with a trailing `\\r` at the previous chunk boundary,\n // so a single leading `\\n` must be swallowed to consume a split `\\r\\n` as one terminator.\n // `skippingLine` means we are discarding an invalid line until its terminator arrives.\n // The two states are mutually exclusive. Returns the remaining chunk to parse ('' if\n // this chunk was fully consumed).\n function resumeAfterSkip(chunk) {\n if (chunk.length === 0) {\n return chunk;\n }\n if (skipNextLineFeed) {\n skipNextLineFeed = false;\n return chunk.charCodeAt(0) === LF ? chunk.slice(1) : chunk;\n }\n const crIndex = chunk.indexOf('\\r');\n const lfIndex = chunk.indexOf('\\n');\n const lineEnd = crIndex === -1 ? lfIndex : lfIndex === -1 ? crIndex : crIndex < lfIndex ? crIndex : lfIndex;\n if (lineEnd === -1) {\n return '';\n }\n // Trailing `\\r` at the very end of the chunk: defer the CRLF/CR decision to the\n // next chunk (see `skipNextLineFeed`) rather than greedily consuming just the `\\r`.\n if (lineEnd === chunk.length - 1 && chunk.charCodeAt(lineEnd) === CR) {\n skippingLine = false;\n skipNextLineFeed = true;\n return '';\n }\n skippingLine = false;\n return chunk.slice(lineEnd + (chunk.charCodeAt(lineEnd) === CR && chunk.charCodeAt(lineEnd + 1) === LF ? 2 : 1));\n }\n function storeTrailing(trailing) {\n if (!trailing)\n return;\n // A trailing that ends with `\\r` is not a partial line: the `\\r` terminates it,\n // and only the CRLF-vs-CR ambiguity remains (the matching `\\n` may start the next\n // chunk). Parse the completed line now — buffering it could grow unbounded through\n // the no-terminator append path, and discarding it would eat the terminator and\n // make skip mode swallow the next line.\n if (trailing.charCodeAt(trailing.length - 1) === CR) {\n parseLine(trailing, 0, trailing.length - 1);\n if (checkForBufferOverflow())\n return;\n skipNextLineFeed = true;\n return;\n }\n if (shouldBufferTrailing(trailing)) {\n pendingFragments.push(trailing);\n pendingFragmentsLength = trailing.length;\n return;\n }\n skippingLine = true;\n }\n function shouldBufferTrailing(trailing) {\n const firstCharCode = trailing.charCodeAt(0);\n return ((firstCharCode === 58 && !!onComment) ||\n (firstCharCode === 100 && isPotentialField(trailing, 'data')) ||\n (firstCharCode === 101 && isPotentialField(trailing, 'event')) ||\n (firstCharCode === 105 && isPotentialField(trailing, 'id')) ||\n (firstCharCode === 114 && isPotentialField(trailing, 'retry')));\n }\n // Returns true when parsing must stop for the current chunk (the parser was already\n // terminated or has just overflowed), and false when processing can continue.\n function checkForBufferOverflow() {\n if (terminated)\n return true;\n if (maxBufferSize === undefined)\n return false;\n if (pendingFragmentsLength + data.length <= maxBufferSize)\n return false;\n terminated = true;\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n skippingLine = false;\n skipNextLineFeed = false;\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: 'max-buffer-size-exceeded',\n }));\n return true;\n }\n /**\n * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n * Returns any trailing bytes that did not terminate with a line break, so the\n * caller can prepend them to the next chunk.\n *\n * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n * present in the chunk. The slow path is spec-correct but does more work per line.\n */\n function processLines(chunk) {\n let searchIndex = 0;\n // Fast path: LF-only chunk (the common case for typical SSE servers).\n // We can scan forward with a single `indexOf('\\n')` per line and inline\n // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n // the slow path needs.\n if (chunk.indexOf('\\r') === -1) {\n let lfIndex = chunk.indexOf('\\n', searchIndex);\n while (lfIndex !== -1) {\n // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n // and reset the buffered fields. This is hoisted out of `parseLine` because\n // it's the single most common line shape after `data:` lines.\n if (searchIndex === lfIndex) {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n if (dataLines > 0) {\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({ id, event: eventType, data });\n }\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n searchIndex = lfIndex + 1;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n // `data:` line — append the value to the event's data buffer.\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5;\n const value = chunk.slice(valueStart, lfIndex);\n // Fast path within a fast path: if this is the first data line AND the\n // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n // without ever writing to the `data` buffer. This is the shape of a\n // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n // hot enough to be worth the duplication.\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({ id, event: eventType, data: value });\n id = undefined;\n data = '';\n eventType = undefined;\n searchIndex = lfIndex + 2;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n continue;\n }\n // Multi-line data: concatenate with newline separator per spec.\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n }\n else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n // `event:` line — set the event type for the next dispatch. Per spec,\n // an empty value resets `event type` to its default (undefined here).\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || undefined;\n }\n else {\n // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n // fields, or malformed lines. These are rarer and go through the full\n // per-line parser, which handles the SSE field grammar in detail.\n parseLine(chunk, searchIndex, lfIndex);\n }\n if (checkForBufferOverflow())\n return '';\n searchIndex = lfIndex + 1;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n // the nearest `\\r` and `\\n` and picking whichever comes first.\n while (searchIndex < chunk.length) {\n const crIndex = chunk.indexOf('\\r', searchIndex);\n const lfIndex = chunk.indexOf('\\n', searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1) {\n lineEnd = crIndex < lfIndex ? crIndex : lfIndex;\n }\n else if (crIndex !== -1) {\n // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n // in the next chunk. Defer until we see more input.\n if (crIndex === chunk.length - 1) {\n lineEnd = -1;\n }\n else {\n lineEnd = crIndex;\n }\n }\n else if (lfIndex !== -1) {\n lineEnd = lfIndex;\n }\n if (lineEnd === -1) {\n break;\n }\n parseLine(chunk, searchIndex, lineEnd);\n if (checkForBufferOverflow())\n return '';\n searchIndex = lineEnd + 1;\n // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n // pair is treated as a single terminator rather than an empty line.\n if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n searchIndex++;\n }\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5;\n const value = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined;\n return;\n }\n // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n if (firstCharCode === 105 &&\n chunk.charCodeAt(start + 1) === 100 &&\n chunk.charCodeAt(start + 2) === 58) {\n // 'id:'.length === 3, 'id: '.length === 4\n const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0'))\n id = value;\n return;\n }\n // Comment line — ':' = 58\n if (firstCharCode === 58) {\n if (onComment) {\n const line = chunk.slice(start, end);\n // skip ':' (+1), or ': ' (+2) when a space follows\n onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end);\n const fieldSeparatorIndex = line.indexOf(':');\n if (fieldSeparatorIndex === -1) {\n processField(line, '', line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex);\n // skip ':' (+1), or ': ' (+2) when a space follows\n const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;\n const value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n // Field names must be compared literally, with no case folding performed.\n switch (field) {\n case 'event':\n // Set the `event type` buffer to field value\n eventType = value || undefined;\n break;\n case 'data':\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n break;\n case 'id':\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0'))\n id = value;\n break;\n case 'retry':\n // If the field value consists of only ASCII digits, then interpret the field value as an\n // integer in base ten, and set the event stream's reconnection time to that integer.\n // Otherwise, ignore the field.\n if (/^\\d+$/.test(value)) {\n onRetry === null || onRetry === void 0 ? void 0 : onRetry(parseInt(value, 10));\n }\n else {\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: 'invalid-retry',\n value,\n line,\n }));\n }\n break;\n default:\n // Otherwise, the field is ignored.\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`, { type: 'unknown-field', field, value, line }));\n break;\n }\n }\n function dispatchEvent() {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n if (dataLines > 0) {\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({\n id,\n event: eventType,\n data,\n });\n }\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join('');\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n bomPrefix = '';\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n terminated = false;\n skippingLine = false;\n skipNextLineFeed = false;\n }\n return { feed, reset };\n}\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return (firstCharCode === 100 &&\n chunk.charCodeAt(i + 1) === 97 &&\n chunk.charCodeAt(i + 2) === 116 &&\n chunk.charCodeAt(i + 3) === 97 &&\n chunk.charCodeAt(i + 4) === 58);\n}\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return (firstCharCode === 101 &&\n chunk.charCodeAt(i + 1) === 118 &&\n chunk.charCodeAt(i + 2) === 101 &&\n chunk.charCodeAt(i + 3) === 110 &&\n chunk.charCodeAt(i + 4) === 116 &&\n chunk.charCodeAt(i + 5) === 58);\n}\nfunction isPotentialField(line, field) {\n let i = 1;\n while (i < line.length && i < field.length) {\n if (line.charCodeAt(i) !== field.charCodeAt(i)) {\n return false;\n }\n i++;\n }\n return line.length <= field.length || line.charCodeAt(field.length) === 58;\n}\n//# sourceMappingURL=parse.js.map","/**\n * SSE subscriber that turns `GET {base_path}/events` into callbacks.\n *\n * One connection per (fetch, url), reference-counted and fanned out to every\n * subscriber. The caller passes an already authenticated `fetch`: this is\n * fetch streaming, not `EventSource`, because `EventSource` cannot send an\n * Authorization header. Frames carry no `event:` name: the first has\n * `id: 0` and `{\"subscriber_id\": ...}`; later ones are record events. A\n * reconnect passes `?{resume_param}=<subscriber_id>` explicitly (never\n * `Last-Event-ID`, which the server would read as a subscriber id) when the\n * stream replays, and always tells subscribers to reset, so the gap is\n * covered even without replay. A stream silent for three keep-alive\n * intervals is dead and is reconnected with exponential backoff and jitter.\n * Events invalidate; they never apply snapshots.\n *\n * A hub is shared by every subscriber of the same (fetch, url) and the first\n * subscriber's options win: the keep-alive, resume parameter, replay mode and\n * resource label of later subscribers are ignored. In development\n * (`process.env.NODE_ENV !== \"production\"`) a later subscriber whose options\n * differ gets a `console.warn` naming the URL and the fields.\n *\n * Every connection has an identity (an opaque {@link EventConnection}) that\n * the hub passes to `onReset` (for the connect reset) and to `onStatus(true)`.\n * A subscriber that joins an already connected hub, or during the handshake's\n * reset fan-out, gets no connect reset; it sees `onStatus(true)` with a\n * connection it was never reset for and resets itself (see `invalidateOnEvents`\n * and `bridgeEvents`).\n */\nimport { createParser } from \"eventsource-parser\";\nimport type { EventSourceMessage } from \"eventsource-parser\";\nimport { describeUrl } from \"./errors.ts\";\nimport type { CrudEvent, MaybePromise } from \"./interfaces.ts\";\n\n/** The manifest's `capabilities.events` object (I1), plain. */\nexport interface EventsConfig {\n /** The server's event label, not the manifest name. */\n readonly resource: string;\n readonly path?: string;\n readonly resume_param?: string;\n /** `persistent` resumes by subscriber id; anything else (`none`) does not. A plain string, as on the wire. */\n readonly replay?: string;\n readonly keepalive_seconds?: number;\n}\n\n/** Opaque identity of one connection of a hub; a new one per connect. */\nexport type EventConnection = object;\n\n/**\n * What a subscriber wants to hear. A handler that throws must not kill the\n * stream, so errors are swallowed; handlers run one after another, in order.\n */\nexport interface EventHandlers {\n onEvent(event: CrudEvent): MaybePromise<void>;\n /**\n * After every connect (the first included), and for an event with no usable\n * record id: clear the resource. `connection` is set for the connect reset\n * only, and is the same object `onStatus(true)` then receives.\n */\n onReset?(connection?: EventConnection): MaybePromise<void>;\n /**\n * `true` when the stream is connected, `false` on any loss, exit or\n * unsubscribe. `connection` identifies the connection when `connected`.\n * A subscriber that joined after the connect reset gets `true` without\n * having been sent `onReset` for that connection.\n */\n onStatus?(\n connected: boolean,\n connection?: EventConnection,\n ): MaybePromise<void>;\n}\n\n/** A shared event stream: `subscribe` returns the (idempotent) unsubscribe. */\nexport interface EventHub {\n subscribe(handlers: EventHandlers): () => void;\n}\n\nexport interface EventHubOptions {\n /** Authenticated; shared hubs are keyed by this function and `url`. */\n readonly fetch: typeof fetch;\n /** Absolute URL of the events endpoint. */\n readonly url: string;\n /**\n * Used only by the first subscriber of a hub (first wins): a later\n * subscriber's differing `resource`, `resume_param`, `replay` or\n * `keepalive_seconds` is ignored, with a development `console.warn`.\n */\n readonly events: EventsConfig;\n /** Jitter source in `[0, 1)`; defaults to `Math.random`. */\n readonly random?: () => number;\n}\n\nexport interface SubscribeEventsOptions extends EventHubOptions, EventHandlers {\n /** Aborting unsubscribes. */\n readonly signal?: AbortSignal;\n}\n\nconst BACKOFF_START_MS = 1000;\nconst BACKOFF_MAX_MS = 30_000;\nconst DEFAULT_KEEPALIVE_S = 15;\nconst DEAD_AFTER_KEEPALIVES = 3;\n/** Cap on the SSE parser's buffered characters (one unterminated line or event); past it the stream is dropped. */\nconst MAX_BUFFER_CHARS = 1024 * 1024;\n/** `setTimeout` clamps a longer delay to 1 ms, which would declare the stream dead at once. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\nconst ACTIONS: ReadonlySet<unknown> = new Set([\n \"create\",\n \"update\",\n \"delete\",\n \"restore\",\n]);\n\n/**\n * The keep-alive interval in seconds. Zero, negative and non-finite values\n * are invalid and treated as unset, so the default applies (as the WHATWG SSE\n * spec ignores an invalid `retry` value instead of acting on it); otherwise a\n * dead-stream deadline of 0 would reconnect forever.\n */\nfunction keepaliveSeconds(events: EventsConfig): number {\n const value = events.keepalive_seconds;\n return value !== undefined && Number.isFinite(value) && value > 0\n ? value\n : DEFAULT_KEEPALIVE_S;\n}\n\n/** The `events` fields that change what a hub does, with defaults applied. */\nfunction hubSettings(events: EventsConfig): Record<string, unknown> {\n return {\n resource: events.resource,\n resume_param: events.resume_param ?? \"subscriber_id\",\n replay: events.replay,\n keepalive_seconds: keepaliveSeconds(events),\n };\n}\n\n/** `process.env.NODE_ENV` is replaced by bundlers; without it (no `process`) assume development. */\nfunction inDevelopment(): boolean {\n try {\n return process.env.NODE_ENV !== \"production\";\n } catch {\n return true;\n }\n}\n\n/** Warns, in development, that a later subscriber's options differ from the hub's. */\nfunction warnOnDifferingOptions(\n hub: EventHubOptions,\n later: EventHubOptions,\n): void {\n if (!inDevelopment()) {\n return;\n }\n const first = hubSettings(hub.events);\n const next = hubSettings(later.events);\n const differing = Object.keys(first).filter(\n (key) => first[key] !== next[key],\n );\n if (differing.length > 0) {\n console.warn(\n `crud-sdk: the event hub for ${describeUrl(hub.url)} was opened with other events options; ` +\n `the first subscriber's win and these are ignored: ${differing.join(\", \")}`,\n );\n }\n}\n\nconst registry = new WeakMap<typeof fetch, Map<string, Hub>>();\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n const done = (): void => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nclass Hub {\n private readonly handlers = new Set<EventHandlers>();\n private readonly options: EventHubOptions;\n private readonly onEmpty: () => void;\n private controller: AbortController | undefined;\n private connected = false;\n private connection: EventConnection | undefined;\n private subscriberId: string | undefined;\n private attempt = 0;\n\n constructor(options: EventHubOptions, onEmpty: () => void) {\n this.options = options;\n this.onEmpty = onEmpty;\n }\n\n subscribe(handlers: EventHandlers, requested: EventHubOptions): () => void {\n if (this.handlers.size > 0) {\n warnOnDifferingOptions(this.options, requested);\n }\n // The same object may subscribe twice; give each subscription its own identity.\n const entry: EventHandlers = {\n onEvent: (event) => handlers.onEvent(event),\n onReset: (connection) => handlers.onReset?.(connection),\n onStatus: (connected, connection) =>\n handlers.onStatus?.(connected, connection),\n };\n this.handlers.add(entry);\n if (this.controller === undefined) {\n this.controller = new AbortController();\n void this.run(this.controller.signal);\n } else if (this.connected) {\n void this.guard(() => entry.onStatus?.(true, this.connection));\n }\n return () => {\n if (!this.handlers.delete(entry)) {\n return;\n }\n void this.guard(() => entry.onStatus?.(false));\n if (this.handlers.size === 0) {\n // Abort the live stream instead of waiting for the next frame.\n this.controller?.abort();\n this.controller = undefined;\n this.onEmpty();\n }\n };\n }\n\n private async guard(\n call: () => MaybePromise<void> | undefined,\n ): Promise<void> {\n try {\n await call();\n } catch {\n // A failing subscriber must not take the stream down.\n }\n }\n\n private async fan(\n call: (handlers: EventHandlers) => MaybePromise<void> | undefined,\n ): Promise<void> {\n // A snapshot, so a subscriber added during dispatch waits for the next\n // one; one removed meanwhile (its unsubscribe already ran) is skipped.\n for (const handlers of Array.from(this.handlers)) {\n if (this.handlers.has(handlers)) {\n await this.guard(() => call(handlers));\n }\n }\n }\n\n private async setConnected(\n connected: boolean,\n connection?: EventConnection,\n ): Promise<void> {\n if (this.connected === connected) {\n return;\n }\n this.connected = connected;\n this.connection = connected ? connection : undefined;\n await this.fan((handlers) => handlers.onStatus?.(connected, connection));\n }\n\n private backoff(): number {\n const base = Math.min(BACKOFF_START_MS * 2 ** this.attempt, BACKOFF_MAX_MS);\n this.attempt += 1;\n const jitter = (this.options.random ?? Math.random)();\n return Math.min(base * (1 + 0.5 * jitter), BACKOFF_MAX_MS);\n }\n\n /** Connect, read and reconnect until aborted. */\n private async run(signal: AbortSignal): Promise<void> {\n try {\n while (!signal.aborted) {\n try {\n await this.readOnce(signal);\n } catch {\n // Lost, refused or dead: reconnect below.\n }\n await this.setConnected(false);\n await sleep(this.backoff(), signal);\n }\n } finally {\n // On any exit, tell the subscribers so the freshness gate closes.\n await this.setConnected(false);\n }\n }\n\n private resumeUrl(): string {\n const { url, events } = this.options;\n if (events.replay !== \"persistent\" || this.subscriberId === undefined) {\n return url;\n }\n const param = events.resume_param ?? \"subscriber_id\";\n const separator = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${separator}${encodeURIComponent(param)}=${encodeURIComponent(this.subscriberId)}`;\n }\n\n private async readOnce(signal: AbortSignal): Promise<void> {\n const deadMs = Math.min(\n keepaliveSeconds(this.options.events) * DEAD_AFTER_KEEPALIVES * 1000,\n MAX_TIMER_MS,\n );\n const conn = new AbortController();\n const abortConn = (): void => {\n conn.abort();\n };\n signal.addEventListener(\"abort\", abortConn, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const arm = (): void => {\n clearTimeout(timer);\n timer = setTimeout(abortConn, deadMs);\n };\n try {\n arm();\n const response = await this.options.fetch(this.resumeUrl(), {\n headers: { accept: \"text/event-stream\" },\n signal: conn.signal,\n });\n if (!response.ok || response.body === null) {\n throw new Error(`event stream refused: HTTP ${response.status}`);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const pending: EventSourceMessage[] = [];\n let overflow = false;\n const parser = createParser({\n maxBufferSize: MAX_BUFFER_CHARS,\n onEvent: (message) => {\n pending.push(message);\n },\n onError: (error) => {\n overflow ||= error.type === \"max-buffer-size-exceeded\";\n },\n });\n // Rejects when the connection is aborted (dead-stream timer included),\n // so a handler that never settles cannot hold the reader loop.\n const closed = new Promise<never>((_resolve, reject) => {\n conn.signal.addEventListener(\n \"abort\",\n () => {\n reject(new Error(\"event stream closed\"));\n },\n { once: true },\n );\n });\n closed.catch(() => undefined);\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n // Any byte, keep-alive comments included, proves the stream is alive.\n // The timer keeps running while handlers do, and each message gets a\n // fresh `deadMs` for its handler: a hung handler ends the connection\n // like a silent stream (the hub reconnects, closing the freshness gate\n // meanwhile), while a batch of slow-but-finishing handlers does not.\n // Reconnects are paced by the backoff and by `deadMs` per attempt.\n arm();\n parser.feed(decoder.decode(value, { stream: true }));\n for (const message of pending.splice(0)) {\n arm();\n await Promise.race([this.handle(message), closed]);\n }\n if (overflow) {\n // Events parsed before the oversized one were handled above.\n throw new Error(\"event stream line or event too large\");\n }\n }\n } finally {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", abortConn);\n conn.abort(); // release the connection on every way out\n }\n }\n\n private async handle(message: EventSourceMessage): Promise<void> {\n let data: unknown;\n try {\n data = JSON.parse(message.data);\n } catch {\n return;\n }\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return;\n }\n const record = data as Record<string, unknown>;\n if (\"subscriber_id\" in record) {\n this.subscriberId = String(record[\"subscriber_id\"]);\n this.attempt = 0;\n // Every connect, the first included: entries stored before this stream\n // (an earlier page session, a persisted store) may predate server changes.\n // A subscriber that joins while this fans out is not in it; it gets\n // `onStatus(true)` with this connection and resets itself.\n const connection: EventConnection = {};\n const present = new Set(this.handlers);\n await this.fan((handlers) => handlers.onReset?.(connection));\n if (this.connected) {\n // A repeated handshake on a live stream: whoever joined during the\n // fan-out was told about the old connection only.\n this.connection = connection;\n for (const handlers of Array.from(this.handlers)) {\n if (!present.has(handlers)) {\n await this.guard(() => handlers.onStatus?.(true, connection));\n }\n }\n } else {\n await this.setConnected(true, connection);\n }\n return;\n }\n if (record[\"resource\"] !== this.options.events.resource) {\n return;\n }\n const action = record[\"action\"];\n const recordId = record[\"record_id\"];\n if (!ACTIONS.has(action) || !Number.isInteger(recordId)) {\n await this.fan((handlers) => handlers.onReset?.());\n return;\n }\n const snapshot = record[\"snapshot\"];\n const event: CrudEvent = {\n resource: String(record[\"resource\"]),\n recordId: recordId as number,\n action: action as CrudEvent[\"action\"],\n snapshot:\n typeof snapshot === \"object\" && snapshot !== null\n ? (snapshot as Record<string, unknown>)\n : {},\n timestamp: String(record[\"timestamp\"] ?? \"\"),\n };\n await this.fan((handlers) => handlers.onEvent(event));\n }\n}\n\n/**\n * The shared hub for `(fetch, url)`: the first subscriber opens the stream,\n * the last one aborts it. A later subscribe after that opens a fresh one.\n *\n * The first subscriber's `events` options win while the hub lives. A later\n * subscriber whose `resource`, `resume_param`, `replay` or `keepalive_seconds`\n * differ is served by the same stream with the first's values, and in\n * development (`process.env.NODE_ENV !== \"production\"`) gets a `console.warn`\n * naming the URL and the differing fields.\n */\nexport function getEventHub(options: EventHubOptions): EventHub {\n return {\n subscribe(handlers) {\n let hubs = registry.get(options.fetch);\n if (hubs === undefined) {\n hubs = new Map();\n registry.set(options.fetch, hubs);\n }\n const byUrl = hubs;\n let hub = byUrl.get(options.url);\n if (hub === undefined) {\n hub = new Hub(options, () => {\n byUrl.delete(options.url);\n });\n byUrl.set(options.url, hub);\n }\n return hub.subscribe(handlers, options);\n },\n };\n}\n\n/**\n * Subscribe to one resource's event stream. Returns the unsubscribe; the\n * last unsubscribe aborts the stream. `signal` aborting unsubscribes too.\n */\nexport function subscribeEvents(options: SubscribeEventsOptions): () => void {\n const { signal } = options;\n if (signal?.aborted === true) {\n return () => undefined;\n }\n const unsubscribe = getEventHub(options).subscribe(options);\n signal?.addEventListener(\"abort\", unsubscribe, { once: true });\n return () => {\n signal?.removeEventListener(\"abort\", unsubscribe);\n unsubscribe();\n };\n}\n"],"ignoreList":[2,3],"mappings":";;AA8BA,SAAS,QAAQ,OAAwB;CACvC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IACrD,KAAK,IAAI,OAAO,CAAC,IACjB;AACN;;AAGA,SAAgB,wBACd,UACA,YAAkC,CAAC,GACtB;CACb,MAAM,QAAQ,SAAS,SAAS,CAAC;CACjC,OAAO;EACL,SAAS,UAAU,WAAW;EAC9B,QAAQ,UAAU,UAAU,QAAQ,MAAM,OAAO;EACjD,UAAU,UAAU,YAAY,QAAQ,MAAM,SAAS;EACvD,sBACE,UAAU,wBAAwB,QAAQ,MAAM,sBAAsB;EACxE,MAAM,UAAU,QAAQ,MAAM,SAAS;EACvC,gBAAgB,UAAU,kBAAkB,MAAM,oBAAoB;CACxE;AACF;;;;;AAMA,SAAgB,oBACd,UACA,YAAkC,CAAC,GACtB;CACb,OAAO,wBAAwB,UAAU;EACvC,gBAAgB;EAChB,GAAG;CACL,CAAC;AACH;;;AC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