@mnmal-ai/substrate 1.0.0-alpha.18 → 1.0.0-alpha.19

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.
Files changed (40) hide show
  1. package/README.md +4 -4
  2. package/dist/{boot-store-C8KrACZ5.js → boot-store-DL2Wkzun.js} +191 -268
  3. package/dist/{bridge-5VHZiH9o.d.ts → bridge-BhiJKwfF.d.ts} +1 -1
  4. package/dist/{cli-zZ7nHhY5.js → cli-BYyPsfdY.js} +25 -28
  5. package/dist/client.browser.js +2478 -0
  6. package/dist/client.d.ts +176 -164
  7. package/dist/client.js +5 -5
  8. package/dist/{errors-DHgT7Fa8.d.ts → errors-CYOaWZ8l.d.ts} +1 -1
  9. package/dist/{index-DKJXQ031.d.ts → index-rW7fu2Af.d.ts} +3 -11
  10. package/dist/{node-version-CxqcqECU.js → node-version-BlYrbY2I.js} +8 -1
  11. package/dist/pack.d.ts +59 -11
  12. package/dist/pack.js +2 -2
  13. package/dist/{pg-edges-store-D7etFxNK.js → pg-edges-store-B0Krqoac.js} +1 -1
  14. package/dist/{plugin-DcoJGEMM.js → plugin-Dk9h__NU.js} +2 -2
  15. package/dist/proposals-bootstrap.js +2 -2
  16. package/dist/proposals.d.ts +2 -2
  17. package/dist/proposals.js +1 -1
  18. package/dist/recall-bootstrap.js +2 -2
  19. package/dist/recall.d.ts +1 -1
  20. package/dist/recall.js +2 -2
  21. package/dist/{repl-SY8cLOZl.js → repl-D6_CBsue.js} +1 -1
  22. package/dist/{row-DHxnCnhA.d.ts → row-CfsHSEfB.d.ts} +4 -4
  23. package/dist/{run-Cr-53N3F.js → run-BJMgCcCC.js} +18 -9
  24. package/dist/{schema-B5WBO8yh.d.ts → schema-laGLMvMC.d.ts} +15 -40
  25. package/dist/{script-B-32wZGY.js → script-DgXaJY1Y.js} +1 -1
  26. package/dist/sdk.d.ts +6 -6
  27. package/dist/sdk.js +3 -3
  28. package/dist/{src-CdbUzLhB.js → src-B6nsPVmD.js} +201 -25
  29. package/dist/{src-DV6PcXym.js → src-B_oTGi3X.js} +648 -845
  30. package/dist/{src-BcuotITf.js → src-BcigMQdR.js} +7 -4
  31. package/dist/{src-DR_hUj2p.js → src-D3ACIp1y.js} +1 -1
  32. package/dist/{src-B4dTiEWw.js → src-Dlmuq32R.js} +3 -3
  33. package/dist/{src-DZfgQ2gR.js → src-DreZjBk7.js} +3 -3
  34. package/dist/{src-D55T3ZcP.js → src-oO0DtS6y.js} +313 -887
  35. package/dist/substrate-admin.js +2 -2
  36. package/dist/substrate.js +2 -2
  37. package/dist/testing.d.ts +13 -47
  38. package/dist/testing.js +6 -167
  39. package/dist/{ws-BL9nSELO.d.ts → ws-BT8kL1IF.d.ts} +4 -4
  40. package/package.json +21 -23
@@ -1,10 +1,307 @@
1
1
  import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
2
  import { c as makeTokenProvider, i as DEFAULT_CAPABILITIES, n as trimTrailingSlashes } from "./env-utils-CGNazUNt.js";
3
- import { D as isActiveAdminKeyRow, O as capabilitiesFor, T as SYSTEM_NAMESPACE } from "./src-DR_hUj2p.js";
4
- import { D as parseQualifiedKey, a as buildDecodePlan, f as SchemaDriftError, i as applyDecodePlanInPlace, o as decodeWsEnvelope, p as decodeEnvelope, s as encodeWsFrame, t as WS_SUBPROTOCOL_SUBSTRATE_PACK } from "./src-CdbUzLhB.js";
3
+ import { D as isActiveAdminKeyRow, O as capabilitiesFor, T as SYSTEM_NAMESPACE } from "./src-D3ACIp1y.js";
4
+ import { C as SchemaDriftError, R as parseQualifiedKey, a as FRAMES_JSON_MIME, f as withIdleTimeout, h as decodeWsEnvelope, i as DEFAULT_STREAM_IDLE_MS, l as decodeStreamFrames, m as buildDecodePlan, o as FRAMES_PACK_MIME, p as applyDecodePlanInPlace, w as decodeEnvelope, x as mutationReturns } from "./src-B6nsPVmD.js";
5
+ import http2 from "node:http2";
5
6
  import { signal } from "@preact/signals-core";
6
- import { WebSocket } from "ws";
7
7
 
8
+ //#region ../../packages/substrate-client/src/transport/default-fetch.ts
9
+ let current = (input, init) => globalThis.fetch(input, init);
10
+ const substrateFetch = (input, init) => current(input, init);
11
+ /** Replace what `substrateFetch` calls. The Node entry and test setups use it. */
12
+ function setSubstrateFetch(fetch) {
13
+ current = fetch;
14
+ }
15
+
16
+ //#endregion
17
+ //#region ../../packages/substrate-client/src/transport/h2-fetch.ts
18
+ /**
19
+ * A fetch-shaped function over `node:http2`: the transport seam's HTTP/2
20
+ * adapter for Node and Bun (Todo #1850, Decision #625).
21
+ *
22
+ * One `ClientHttp2Session` per origin, opened on first use and shared by every
23
+ * request to it; concurrent first calls share the pending connect. A session is
24
+ * dropped on GOAWAY, close or error, and the next request opens a new one. An
25
+ * idle session is unref'd, so a short-lived process exits without `close()`.
26
+ * `http:` origins use HTTP/2 with prior knowledge (h2c); `https:` origins verify
27
+ * the server against `ca`, or the process's default trust (which includes
28
+ * NODE_EXTRA_CA_CERTS). Certificate checks are never turned off.
29
+ *
30
+ * Imports node builtins only.
31
+ */
32
+ const DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
33
+ /** Request headers HTTP/2 forbids (RFC 9113 §8.2.2); fetch callers may still set them. */
34
+ const CONNECTION_HEADERS = /* @__PURE__ */ new Set([
35
+ "connection",
36
+ "keep-alive",
37
+ "transfer-encoding",
38
+ "upgrade",
39
+ "proxy-connection",
40
+ "host"
41
+ ]);
42
+ function abortError(signal) {
43
+ const reason = signal.reason;
44
+ if (reason instanceof Error && reason.name === "AbortError") return reason;
45
+ return new DOMException("This operation was aborted", "AbortError");
46
+ }
47
+ function toHeaderRecord(init) {
48
+ const out = {};
49
+ new Headers(init).forEach((value, name) => {
50
+ if (!CONNECTION_HEADERS.has(name)) out[name] = value;
51
+ });
52
+ return out;
53
+ }
54
+ function toBodyBytes(body) {
55
+ if (body === void 0 || body === null) return void 0;
56
+ if (typeof body === "string" || body instanceof Uint8Array) return body;
57
+ if (body instanceof ArrayBuffer) return new Uint8Array(body);
58
+ if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
59
+ throw new TypeError("createH2Fetch: only string, ArrayBuffer and typed-array bodies are supported");
60
+ }
61
+ function createH2Fetch(opts = {}) {
62
+ const connectTimeoutMs = opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
63
+ const pool = /* @__PURE__ */ new Map();
64
+ /** Every session opened, connected or not, so close() can end them all. */
65
+ const sessions = /* @__PURE__ */ new Set();
66
+ function connect(origin) {
67
+ const existing = pool.get(origin);
68
+ if (existing !== void 0) return existing;
69
+ const pending = new Promise((resolve, reject) => {
70
+ const session = http2.connect(origin, origin.startsWith("https:") && opts.ca !== void 0 ? { ca: opts.ca } : {});
71
+ sessions.add(session);
72
+ session.once("close", () => sessions.delete(session));
73
+ const pooled = {
74
+ session,
75
+ holds: 0
76
+ };
77
+ let connected = false;
78
+ const drop = () => {
79
+ if (pool.get(origin) === pending) pool.delete(origin);
80
+ };
81
+ const fail = (err) => {
82
+ clearTimeout(timer);
83
+ drop();
84
+ if (!connected) reject(err);
85
+ };
86
+ const timer = setTimeout(() => {
87
+ session.destroy();
88
+ fail(/* @__PURE__ */ new Error(`connect to ${origin} timed out after ${connectTimeoutMs} ms`));
89
+ }, connectTimeoutMs);
90
+ timer.unref();
91
+ session.once("connect", () => {
92
+ clearTimeout(timer);
93
+ connected = true;
94
+ session.unref();
95
+ resolve(pooled);
96
+ });
97
+ session.on("error", fail);
98
+ session.on("goaway", drop);
99
+ session.on("close", () => fail(/* @__PURE__ */ new Error(`connection to ${origin} closed before it opened`)));
100
+ });
101
+ pending.catch(() => {});
102
+ pool.set(origin, pending);
103
+ return pending;
104
+ }
105
+ /** Forget `pooled` if it is still the origin's session, so the next request opens a new one. */
106
+ function forget(origin, pooled) {
107
+ const current = pool.get(origin);
108
+ if (current === void 0) return;
109
+ current.then((p) => {
110
+ if (p === pooled && pool.get(origin) === current) pool.delete(origin);
111
+ }, () => {});
112
+ }
113
+ const fetchH2 = async (input, init = {}) => {
114
+ const signal = init.signal ?? void 0;
115
+ if (signal?.aborted) throw abortError(signal);
116
+ const url = new URL(input);
117
+ const body = toBodyBytes(init.body);
118
+ const headers = {
119
+ ...toHeaderRecord(init.headers),
120
+ ":method": (init.method ?? "GET").toUpperCase(),
121
+ ":path": `${url.pathname}${url.search}`
122
+ };
123
+ for (let attempt = 0;; attempt++) {
124
+ const pooled = await untilAborted(connect(url.origin), signal);
125
+ const outcome = await send(pooled, headers, body, init, signal);
126
+ if (outcome.kind === "response") return outcome.response;
127
+ forget(url.origin, pooled);
128
+ if (outcome.kind === "retry" && attempt === 0) continue;
129
+ throw outcome.error;
130
+ }
131
+ };
132
+ return Object.assign(fetchH2, { async close() {
133
+ pool.clear();
134
+ await Promise.all([...sessions].map((session) => {
135
+ if (session.connecting) {
136
+ session.destroy();
137
+ return;
138
+ }
139
+ return session.closed ? void 0 : new Promise((r) => session.close(() => r()));
140
+ }));
141
+ } });
142
+ }
143
+ /** Keep the session ref'd while anyone waits on it; an idle or unread one lets the process exit. */
144
+ function hold(p) {
145
+ if (p.holds++ === 0) p.session.ref();
146
+ }
147
+ function release(p) {
148
+ if (--p.holds === 0 && !p.session.destroyed) p.session.unref();
149
+ }
150
+ function untilAborted(p, signal) {
151
+ if (signal === void 0) return p;
152
+ return new Promise((resolve, reject) => {
153
+ const onAbort = () => reject(abortError(signal));
154
+ signal.addEventListener("abort", onAbort, { once: true });
155
+ p.then((v) => {
156
+ signal.removeEventListener("abort", onAbort);
157
+ resolve(v);
158
+ }, (e) => {
159
+ signal.removeEventListener("abort", onAbort);
160
+ reject(e);
161
+ });
162
+ });
163
+ }
164
+ const RETRYABLE_CODES = /* @__PURE__ */ new Set(["ERR_HTTP2_GOAWAY_SESSION", "ERR_HTTP2_INVALID_SESSION"]);
165
+ function send(pooled, headers, body, init, signal) {
166
+ return new Promise((resolve) => {
167
+ let stream;
168
+ try {
169
+ stream = pooled.session.request(headers, { endStream: body === void 0 });
170
+ } catch (err) {
171
+ const code = err.code;
172
+ resolve({
173
+ kind: code !== void 0 && RETRYABLE_CODES.has(code) ? "retry" : "error",
174
+ error: err
175
+ });
176
+ return;
177
+ }
178
+ hold(pooled);
179
+ let settled = false;
180
+ const settle = (o) => {
181
+ if (settled) return;
182
+ settled = true;
183
+ release(pooled);
184
+ resolve(o);
185
+ };
186
+ const onAbort = () => {
187
+ stream.close(http2.constants.NGHTTP2_CANCEL);
188
+ settle({
189
+ kind: "error",
190
+ error: abortError(signal)
191
+ });
192
+ };
193
+ signal?.addEventListener("abort", onAbort, { once: true });
194
+ stream.once("close", () => {
195
+ signal?.removeEventListener("abort", onAbort);
196
+ const refused = stream.rstCode === http2.constants.NGHTTP2_REFUSED_STREAM;
197
+ settle({
198
+ kind: refused ? "retry" : "error",
199
+ error: /* @__PURE__ */ new Error(`stream closed before a response (code ${stream.rstCode})`)
200
+ });
201
+ });
202
+ stream.once("error", (err) => settle({
203
+ kind: "error",
204
+ error: err
205
+ }));
206
+ stream.once("response", (h) => {
207
+ const status = Number(h[":status"]);
208
+ const responseHeaders = new Headers();
209
+ for (const [name, value] of Object.entries(h)) {
210
+ if (name.startsWith(":") || value === void 0) continue;
211
+ for (const v of Array.isArray(value) ? value : [String(value)]) responseHeaders.append(name, v);
212
+ }
213
+ if (status >= 300 && status < 400 && responseHeaders.has("location") && init.redirect !== "manual") {
214
+ stream.close(http2.constants.NGHTTP2_CANCEL);
215
+ settle({
216
+ kind: "error",
217
+ error: /* @__PURE__ */ new TypeError(`redirect refused: ${status} to ${responseHeaders.get("location")}`)
218
+ });
219
+ return;
220
+ }
221
+ const nullBody = status === 204 || status === 205 || status === 304 || headers[":method"] === "HEAD";
222
+ let response;
223
+ try {
224
+ response = new Response(nullBody ? null : webBody(stream, pooled, signal), {
225
+ status,
226
+ headers: responseHeaders
227
+ });
228
+ } catch (err) {
229
+ stream.close(http2.constants.NGHTTP2_CANCEL);
230
+ settle({
231
+ kind: "error",
232
+ error: err
233
+ });
234
+ return;
235
+ }
236
+ if (nullBody) stream.resume();
237
+ settle({
238
+ kind: "response",
239
+ response
240
+ });
241
+ });
242
+ if (body !== void 0) stream.end(body);
243
+ });
244
+ }
245
+ /**
246
+ * The response body as a web stream with backpressure. The session stays ref'd
247
+ * only while the reader is waiting for data, so a body nobody reads lets the
248
+ * process exit. An unread body still holds its HTTP/2 stream open until the
249
+ * server finishes it: read or cancel every body. Cancelling resets the stream.
250
+ * Built by hand rather than with `Readable.toWeb`, which aborts h2 bodies early under Bun.
251
+ */
252
+ function webBody(stream, pooled, signal) {
253
+ let done = false;
254
+ let holding = false;
255
+ const setHold = (on) => {
256
+ if (on === holding) return;
257
+ holding = on;
258
+ if (on) hold(pooled);
259
+ else release(pooled);
260
+ };
261
+ const finish = () => {
262
+ done = true;
263
+ setHold(false);
264
+ };
265
+ return new ReadableStream({
266
+ start(controller) {
267
+ stream.on("data", (chunk) => {
268
+ if (done) return;
269
+ controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
270
+ if ((controller.desiredSize ?? 1) <= 0) {
271
+ stream.pause();
272
+ setHold(false);
273
+ }
274
+ });
275
+ stream.once("end", () => {
276
+ if (done) return;
277
+ finish();
278
+ if (signal?.aborted) controller.error(abortError(signal));
279
+ else controller.close();
280
+ });
281
+ stream.once("error", (err) => {
282
+ if (done) return;
283
+ finish();
284
+ controller.error(signal?.aborted ? abortError(signal) : err);
285
+ });
286
+ stream.once("close", () => {
287
+ if (done) return;
288
+ finish();
289
+ controller.error(signal?.aborted ? abortError(signal) : /* @__PURE__ */ new Error(`stream closed before its end (code ${stream.rstCode})`));
290
+ });
291
+ },
292
+ pull() {
293
+ if (done) return;
294
+ setHold(true);
295
+ stream.resume();
296
+ },
297
+ cancel() {
298
+ finish();
299
+ stream.close(http2.constants.NGHTTP2_CANCEL);
300
+ }
301
+ });
302
+ }
303
+
304
+ //#endregion
8
305
  //#region ../../packages/substrate-client/src/admin/diagnose.ts
9
306
  /**
10
307
  * The library behind `substrate-admin doctor` and substrate-tui's `/doctor` — diagnoses
@@ -293,7 +590,7 @@ const DIAGNOSE_CHECKS = [
293
590
  */
294
591
  async function diagnose(opts) {
295
592
  const checks = new Checks();
296
- const fetchImpl = opts.fetch ?? fetch;
593
+ const fetchImpl = opts.fetch ?? substrateFetch;
297
594
  const adminCapability = opts.adminCapability ?? "admin";
298
595
  const baseUrl = trimTrailingSlashes(opts.baseUrl);
299
596
  let identityId = null;
@@ -923,7 +1220,7 @@ const SURVIVABLE_END_REASONS = /* @__PURE__ */ new Set([
923
1220
  * A delta that does not change the set (e.g. an `update` whose row has no id) is
924
1221
  * not re-yielded. Cancellation: breaking the consuming `for await` (or calling
925
1222
  * `.return()`) propagates to the source iterable's `return()` through the inner
926
- * `for await`, cancelling the underlying WS subscription.
1223
+ * `for await`, cancelling the underlying subscription.
927
1224
  */
928
1225
  async function* watchRows(events, qualifiedKey) {
929
1226
  let rows = [];
@@ -1147,62 +1444,275 @@ function createDefaultDiagnosticsSink() {
1147
1444
  }
1148
1445
 
1149
1446
  //#endregion
1150
- //#region ../../packages/substrate-client/src/transport/sse.ts
1151
- /** Parse one SSE block; null when it carries no data (comment-only or empty). Throws on an in-band `error` event. */
1152
- function parseBlock(block) {
1153
- let event = "message";
1154
- const data = [];
1155
- for (const line of block.split("\n")) {
1156
- if (line.startsWith(":")) continue;
1157
- if (line.startsWith("event:")) event = line.slice(6).trim();
1158
- else if (line.startsWith("data:")) data.push(line.slice(5).startsWith(" ") ? line.slice(6) : line.slice(5));
1159
- }
1160
- if (data.length === 0) return null;
1161
- const raw = data.join("\n");
1162
- let parsed;
1163
- try {
1164
- parsed = JSON.parse(raw);
1165
- } catch (err) {
1166
- throw new NetworkError(`malformed SSE data for event '${event}': ${raw.slice(0, 100)}`, err);
1447
+ //#region ../../packages/substrate-client/src/reconnect.ts
1448
+ var ReconnectScheduler = class {
1449
+ #base;
1450
+ #max;
1451
+ #jitter;
1452
+ #attempt = 0;
1453
+ constructor(opts) {
1454
+ this.#base = opts.baseDelayMs;
1455
+ this.#max = opts.maxDelayMs;
1456
+ this.#jitter = opts.jitter;
1457
+ }
1458
+ nextDelay() {
1459
+ const raw = Math.min(this.#base * 2 ** this.#attempt, this.#max);
1460
+ this.#attempt += 1;
1461
+ if (this.#jitter === 0) return raw;
1462
+ const spread = raw * this.#jitter;
1463
+ return raw + (Math.random() * 2 - 1) * spread;
1167
1464
  }
1168
- if (event === "error") {
1169
- const e = parsed;
1170
- throw new NetworkError(`${e.code ?? "error"}: ${e.message ?? ""}`, parsed);
1465
+ reset() {
1466
+ this.#attempt = 0;
1467
+ }
1468
+ /**
1469
+ * Resolve after `nextDelay()` ms. Callers must use this serially — the
1470
+ * `#attempt` counter is shared across calls, so overlapping `schedule()`
1471
+ * invocations will produce incorrect delays. The stream reconnect loop awaits
1472
+ * each `schedule()` before firing the next attempt.
1473
+ */
1474
+ async schedule() {
1475
+ const d = this.nextDelay();
1476
+ await new Promise((resolve) => setTimeout(resolve, d));
1477
+ }
1478
+ };
1479
+
1480
+ //#endregion
1481
+ //#region ../../packages/substrate-client/src/transport/frame-event.ts
1482
+ /** Server response frames as the subscribe and stream iterables yield them. */
1483
+ const DEFAULT_RECONNECT = {
1484
+ baseDelayMs: 1e3,
1485
+ maxDelayMs: 3e4,
1486
+ jitter: .1
1487
+ };
1488
+ const DEFAULT_OVERLOAD_RESUBSCRIBE = {
1489
+ enabled: true,
1490
+ maxAttempts: 3,
1491
+ baseDelayMs: 1e3,
1492
+ maxDelayMs: 3e4,
1493
+ jitter: .1,
1494
+ healthyResetMs: 6e4
1495
+ };
1496
+ /** Convert a server frame to a SubscribeEvent, or null if unrecognised. */
1497
+ function msgToEvent(msg) {
1498
+ switch (msg.kind) {
1499
+ case "snapshot":
1500
+ case "add":
1501
+ case "update": return {
1502
+ kind: msg.kind,
1503
+ data: msg.data,
1504
+ ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {}
1505
+ };
1506
+ case "chunk": return {
1507
+ kind: "chunk",
1508
+ data: msg.data,
1509
+ ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {},
1510
+ ...msg.sequence !== void 0 ? { sequence: msg.sequence } : {}
1511
+ };
1512
+ case "remove": return {
1513
+ kind: "remove",
1514
+ removedId: msg.removedId ?? ""
1515
+ };
1516
+ case "end": return {
1517
+ kind: "end",
1518
+ ...msg.final !== void 0 ? { final: msg.final } : {},
1519
+ ...msg.reason !== void 0 ? { reason: msg.reason } : {}
1520
+ };
1521
+ case "error": {
1522
+ const first = (msg.errors ?? [{
1523
+ message: "unknown error",
1524
+ code: "unknown"
1525
+ }])[0] ?? {
1526
+ message: "unknown error",
1527
+ code: "unknown"
1528
+ };
1529
+ throw new SubscribeError(first.message, first.code ?? "unknown");
1530
+ }
1531
+ default: return null;
1171
1532
  }
1172
- return {
1173
- event,
1174
- data: parsed
1175
- };
1176
1533
  }
1177
- async function* readSse(body) {
1178
- const reader = body.getReader();
1179
- const decoder = new TextDecoder();
1180
- let buf = "";
1181
- try {
1182
- for (;;) {
1183
- const { value, done } = await reader.read();
1184
- if (done) break;
1185
- buf = (buf + decoder.decode(value, { stream: true })).replace(/\r\n/g, "\n");
1186
- let sep = buf.indexOf("\n\n");
1187
- while (sep >= 0) {
1188
- const block = buf.slice(0, sep);
1189
- buf = buf.slice(sep + 2);
1190
- sep = buf.indexOf("\n\n");
1191
- const evt = parseBlock(block);
1192
- if (evt !== null) yield evt;
1534
+
1535
+ //#endregion
1536
+ //#region ../../packages/substrate-client/src/transport/frames.ts
1537
+ /**
1538
+ * Subscribe and stream over length-prefixed frame streams: one POST per
1539
+ * subscription, its response body a sequence of frames (substrate-pack's
1540
+ * stream-frames codec). Each subscription owns its request, so cancelling one
1541
+ * aborts only that request.
1542
+ *
1543
+ * A subscription survives the following, re-subscribing for a fresh
1544
+ * snapshot: a dropped connection (after backoff), `end { server_restart }`
1545
+ * (at once), `subscription_overloaded` (after the overload delay, within its
1546
+ * budget) and a lapsed credential when `getToken` can mint a new one. A 401 or
1547
+ * 403 is terminal. A stream is never re-sent, since that would replay its chunks.
1548
+ */
1549
+ /** `NetworkError.code` when the server does not answer with frame streams. */
1550
+ const FRAMES_UNSUPPORTED = "frames_unsupported";
1551
+ /** `NetworkError.code` when a stream was cut short by a server restart. */
1552
+ const STREAM_INTERRUPTED = "stream_interrupted";
1553
+ const OVERLOADED = "subscription_overloaded";
1554
+ const SERVER_RESTART = "server_restart";
1555
+ const LAPSES = /* @__PURE__ */ new Set(["credential_expired", "credential_changed"]);
1556
+ function openFrameStream(http, path, frame, opts) {
1557
+ return { [Symbol.asyncIterator]: () => {
1558
+ const ctrl = new AbortController();
1559
+ const gen = run(http, path, frame, opts, opts.signal === void 0 ? ctrl.signal : anySignal([ctrl.signal, opts.signal]));
1560
+ return {
1561
+ next: () => gen.next(),
1562
+ return: async () => {
1563
+ ctrl.abort();
1564
+ await gen.return(void 0);
1565
+ return {
1566
+ value: void 0,
1567
+ done: true
1568
+ };
1569
+ }
1570
+ };
1571
+ } };
1572
+ }
1573
+ async function* run(http, path, frame, opts, signal) {
1574
+ const subscribe = path === "/substrate/v1/subscribe";
1575
+ const reconnect = {
1576
+ ...DEFAULT_RECONNECT,
1577
+ ...opts.reconnect
1578
+ };
1579
+ const backoff = new ReconnectScheduler(reconnect);
1580
+ const overload = {
1581
+ ...DEFAULT_OVERLOAD_RESUBSCRIBE,
1582
+ ...opts.overload
1583
+ };
1584
+ let overloadAttempts = 0;
1585
+ let lastOverloadAt = null;
1586
+ let opened = false;
1587
+ let busyRetries = 0;
1588
+ const accept = opts.wire === "pack" ? FRAMES_PACK_MIME : FRAMES_JSON_MIME;
1589
+ for (;;) {
1590
+ let body;
1591
+ try {
1592
+ const res = await http.raw(path, {
1593
+ method: "POST",
1594
+ body: frame,
1595
+ accept,
1596
+ signal
1597
+ });
1598
+ const type = res.headers.get("content-type") ?? "";
1599
+ if (!type.startsWith(accept)) {
1600
+ await res.body?.cancel();
1601
+ throw new NetworkError(`POST ${path} answered '${type}', not ${accept}: the server predates frame streams`, null, {
1602
+ status: res.status,
1603
+ code: FRAMES_UNSUPPORTED
1604
+ });
1193
1605
  }
1606
+ if (res.body === null) throw new NetworkError(`POST ${path}: response has no body`, null);
1607
+ body = res.body;
1608
+ } catch (err) {
1609
+ if (signal.aborted) return;
1610
+ if (!opened && isBusy(err) && busyRetries < BUSY_RETRIES) {
1611
+ busyRetries++;
1612
+ if (!await sleep(backoff.nextDelay(), signal)) return;
1613
+ continue;
1614
+ }
1615
+ if (err instanceof AuthError || !opened || !subscribe || refused(err)) throw err;
1616
+ if (!await sleep(backoff.nextDelay(), signal)) return;
1617
+ continue;
1194
1618
  }
1195
- buf += decoder.decode();
1196
- const tail = buf.replace(/\r\n?/g, "\n").trim();
1197
- if (tail !== "") {
1198
- const evt = parseBlock(tail);
1199
- if (evt !== null) yield evt;
1619
+ opened = true;
1620
+ const openedAt = Date.now();
1621
+ let next;
1622
+ try {
1623
+ const idleMs = opts.idleMs ?? 65e3;
1624
+ for await (const payload of decodeStreamFrames(idleMs > 0 ? withIdleTimeout(body, idleMs) : body)) {
1625
+ const msg = decodeFrame(payload, opts.wire);
1626
+ if (Date.now() - openedAt >= reconnect.maxDelayMs) backoff.reset();
1627
+ if (subscribe && msg.kind === "error" && msg.errors?.[0]?.code === OVERLOADED && overload.enabled) {
1628
+ const now = Date.now();
1629
+ if (lastOverloadAt !== null && now - lastOverloadAt > overload.healthyResetMs) overloadAttempts = 0;
1630
+ lastOverloadAt = now;
1631
+ if (overloadAttempts < overload.maxAttempts) {
1632
+ overloadAttempts += 1;
1633
+ next = { delayMs: jittered(overload, overloadAttempts) };
1634
+ break;
1635
+ }
1636
+ }
1637
+ if (!subscribe && msg.kind === "end" && msg.reason === SERVER_RESTART) throw new NetworkError(`POST ${path}: the server restarted mid-stream`, null, { code: STREAM_INTERRUPTED });
1638
+ const event = msgToEvent(msg);
1639
+ if (event === null) continue;
1640
+ yield event;
1641
+ if (msg.kind === "end") {
1642
+ next = subscribe && (msg.reason === SERVER_RESTART || msg.reason !== void 0 && LAPSES.has(msg.reason) && opts.canRefreshToken) ? { delayMs: 0 } : "stop";
1643
+ break;
1644
+ }
1645
+ }
1646
+ } catch (err) {
1647
+ if (signal.aborted) return;
1648
+ if (err instanceof SubscribeError || err instanceof NetworkError && err.code === "stream_interrupted") throw err;
1649
+ if (!subscribe) throw err instanceof NetworkError ? err : new NetworkError(`POST ${path}: the stream broke before its end frame`, err);
1200
1650
  }
1201
- } finally {
1202
- await reader.cancel().catch(() => {});
1203
- reader.releaseLock();
1651
+ if (next === "stop") return;
1652
+ if (next === void 0) {
1653
+ if (signal.aborted) return;
1654
+ if (!subscribe) throw new NetworkError(`POST ${path}: stream ended without an end frame`, null);
1655
+ next = { delayMs: backoff.nextDelay() };
1656
+ }
1657
+ if (!await sleep(next.delayMs, signal)) return;
1204
1658
  }
1205
1659
  }
1660
+ /** Retries of a 429 before the first response, after which it surfaces. */
1661
+ const BUSY_RETRIES = 3;
1662
+ function isBusy(err) {
1663
+ return err instanceof NetworkError && err.status === 429;
1664
+ }
1665
+ /**
1666
+ * A refusal that retrying will not change: a server without frame streams, or a
1667
+ * 4xx other than 408 and 429 (the frame no longer validates, say).
1668
+ */
1669
+ function refused(err) {
1670
+ if (!(err instanceof NetworkError)) return false;
1671
+ if (err.code === "frames_unsupported") return true;
1672
+ const status = err.status;
1673
+ return status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
1674
+ }
1675
+ /**
1676
+ * Aborts when any of `signals` does. `AbortSignal.any` holds no listener on its
1677
+ * sources, so finished subscriptions leave nothing behind on a shared signal; the
1678
+ * fallback, for browsers before 2024, does.
1679
+ */
1680
+ function anySignal(signals) {
1681
+ if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
1682
+ const ctrl = new AbortController();
1683
+ for (const s of signals) {
1684
+ if (s.aborted) {
1685
+ ctrl.abort(s.reason);
1686
+ break;
1687
+ }
1688
+ s.addEventListener("abort", () => ctrl.abort(s.reason), { once: true });
1689
+ }
1690
+ return ctrl.signal;
1691
+ }
1692
+ function decodeFrame(payload, wire) {
1693
+ const value = wire === "pack" ? decodeWsEnvelope(payload, "pack") : JSON.parse(new TextDecoder().decode(payload));
1694
+ if (value === null || typeof value !== "object" || typeof value.kind !== "string") throw new NetworkError("malformed frame in subscription stream", null);
1695
+ return value;
1696
+ }
1697
+ function jittered(cfg, attempt) {
1698
+ const raw = Math.min(cfg.baseDelayMs * 2 ** (attempt - 1), cfg.maxDelayMs);
1699
+ return cfg.jitter === 0 ? raw : raw + (Math.random() * 2 - 1) * raw * cfg.jitter;
1700
+ }
1701
+ /** Resolves true after `ms`, or false as soon as `signal` aborts. */
1702
+ function sleep(ms, signal) {
1703
+ if (signal.aborted) return Promise.resolve(false);
1704
+ return new Promise((resolve) => {
1705
+ const timer = setTimeout(() => {
1706
+ signal.removeEventListener("abort", onAbort);
1707
+ resolve(true);
1708
+ }, ms);
1709
+ const onAbort = () => {
1710
+ clearTimeout(timer);
1711
+ resolve(false);
1712
+ };
1713
+ signal.addEventListener("abort", onAbort, { once: true });
1714
+ });
1715
+ }
1206
1716
 
1207
1717
  //#endregion
1208
1718
  //#region ../../packages/substrate-client/src/nl.ts
@@ -1213,11 +1723,31 @@ function createNlApi(t) {
1213
1723
  const res = await t.raw("/substrate/v1/nl", {
1214
1724
  method: "POST",
1215
1725
  body: req,
1216
- accept: "text/event-stream",
1726
+ accept: FRAMES_JSON_MIME,
1217
1727
  ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1218
1728
  });
1219
- if (res.body === null) throw new NetworkError("empty SSE body", null);
1220
- yield* readSse(res.body);
1729
+ const type = res.headers.get("content-type") ?? "";
1730
+ if (!type.startsWith("application/vnd.substrate.frames+json") || res.body === null) {
1731
+ await res.body?.cancel();
1732
+ throw new NetworkError(`POST /substrate/v1/nl answered '${type}', not ${FRAMES_JSON_MIME}: the server predates frame streams`, null, {
1733
+ status: res.status,
1734
+ code: FRAMES_UNSUPPORTED
1735
+ });
1736
+ }
1737
+ const utf8 = new TextDecoder();
1738
+ for await (const payload of decodeStreamFrames(res.body)) {
1739
+ let ev;
1740
+ try {
1741
+ ev = JSON.parse(utf8.decode(payload));
1742
+ } catch (err) {
1743
+ throw new NetworkError("malformed frame in the NL stream", err);
1744
+ }
1745
+ if (ev.event === "error") {
1746
+ const e = ev.data;
1747
+ throw new NetworkError(`${e.code ?? "error"}: ${e.message ?? ""}`, ev.data);
1748
+ }
1749
+ yield ev;
1750
+ }
1221
1751
  },
1222
1752
  async askJson(req, opts = {}) {
1223
1753
  return await (await t.raw("/substrate/v1/nl", {
@@ -1304,7 +1834,7 @@ var HttpTransport = class {
1304
1834
  constructor(opts) {
1305
1835
  if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("HttpTransport: provide `token` OR `getToken`, not both");
1306
1836
  this.#endpoint = trimTrailingSlashes(opts.endpoint);
1307
- this.#fetch = (opts.fetch ?? globalThis.fetch).bind(globalThis);
1837
+ this.#fetch = (opts.fetch ?? substrateFetch).bind(globalThis);
1308
1838
  this.#token = opts.token;
1309
1839
  this.#getToken = opts.getToken;
1310
1840
  }
@@ -1420,722 +1950,6 @@ async function errorInfo(res) {
1420
1950
  return info;
1421
1951
  }
1422
1952
 
1423
- //#endregion
1424
- //#region ../../packages/substrate-client/src/reconnect.ts
1425
- var ReconnectScheduler = class {
1426
- #base;
1427
- #max;
1428
- #jitter;
1429
- #attempt = 0;
1430
- constructor(opts) {
1431
- this.#base = opts.baseDelayMs;
1432
- this.#max = opts.maxDelayMs;
1433
- this.#jitter = opts.jitter;
1434
- }
1435
- nextDelay() {
1436
- const raw = Math.min(this.#base * 2 ** this.#attempt, this.#max);
1437
- this.#attempt += 1;
1438
- if (this.#jitter === 0) return raw;
1439
- const spread = raw * this.#jitter;
1440
- return raw + (Math.random() * 2 - 1) * spread;
1441
- }
1442
- reset() {
1443
- this.#attempt = 0;
1444
- }
1445
- /**
1446
- * Resolve after `nextDelay()` ms. Callers must use this serially — the
1447
- * `#attempt` counter is shared across calls, so overlapping `schedule()`
1448
- * invocations will produce incorrect delays. The WS reconnect loop awaits
1449
- * each `schedule()` before firing the next attempt.
1450
- */
1451
- async schedule() {
1452
- const d = this.nextDelay();
1453
- await new Promise((resolve) => setTimeout(resolve, d));
1454
- }
1455
- };
1456
-
1457
- //#endregion
1458
- //#region ../../packages/substrate-client/src/transport/multiplex.ts
1459
- /**
1460
- * MultiplexedSocket — low-level WS multiplexer.
1461
- *
1462
- * One raw WebSocket; outbound frames get a client-generated `id`; inbound
1463
- * frames with a matching `id` route to the right pending handler.
1464
- *
1465
- * Subscribe/stream ops stay pending across multiple messages (they receive
1466
- * snapshot/add/update/remove/chunk/end/error frames). Query/mutate are not
1467
- * handled here — those go via HTTP.
1468
- *
1469
- * Encoding: JSON-over-WS by default. Pass `usePack: true` to send/receive
1470
- * msgpack-encoded frames matching the `substrate-pack` subprotocol negotiated
1471
- * one level up by `WsTransport`. Under pack, `data` values arrive as
1472
- * positional tuples — the higher layer (`SubstrateClient`) is responsible for
1473
- * the schema-driven positional → named decode; the multiplexer only
1474
- * handles wire-format framing.
1475
- *
1476
- * Works with both node-ws WebSocket and browser native WebSocket via the
1477
- * shared `addEventListener` interface (node-ws v8+ supports it).
1478
- */
1479
- /** Terminal response kinds — once received the pending entry is cleared. */
1480
- const TERMINAL_KINDS = /* @__PURE__ */ new Set(["end", "error"]);
1481
- var MultiplexedSocket = class {
1482
- #ws;
1483
- #mode;
1484
- #pending = /* @__PURE__ */ new Map();
1485
- #seq = 0;
1486
- #closing = false;
1487
- /**
1488
- * Accept either a node `ws` WebSocket or a browser WebSocket — both expose
1489
- * `addEventListener`. The constructor wires up message and close handling.
1490
- *
1491
- * `usePack` is set by `WsTransport` after the `substrate-pack` subprotocol
1492
- * has been negotiated at handshake; once true the socket exclusively
1493
- * speaks msgpack frames.
1494
- */
1495
- constructor(ws, opts = {}) {
1496
- this.#ws = ws;
1497
- this.#mode = opts.usePack === true ? "pack" : "json";
1498
- ws.addEventListener("message", (ev) => this.#onMessage(ev));
1499
- ws.addEventListener("close", (ev) => this.#onClose(ev));
1500
- }
1501
- nextId() {
1502
- this.#seq += 1;
1503
- return `c${this.#seq}`;
1504
- }
1505
- /**
1506
- * Serialise + send `frame` (which must already include an `id` field) and
1507
- * register `pending` as the handler for responses bearing that id.
1508
- * Returns the frame id for caller bookkeeping.
1509
- */
1510
- send(frame, pending) {
1511
- const id = frame.id ?? this.nextId();
1512
- const frameWithId = id === frame.id ? frame : {
1513
- ...frame,
1514
- id
1515
- };
1516
- this.#pending.set(id, pending);
1517
- try {
1518
- this.#sendWire(encodeWsFrame(frameWithId, this.#mode));
1519
- } catch (_err) {
1520
- this.#pending.delete(id);
1521
- pending.onClose("send failed");
1522
- }
1523
- return id;
1524
- }
1525
- /**
1526
- * Send a cancel frame for a given subscription id and remove the pending
1527
- * handler. The server will emit a terminal `end` frame; since we delete the
1528
- * pending entry here, that frame is silently dropped.
1529
- */
1530
- cancel(id) {
1531
- this.#pending.delete(id);
1532
- try {
1533
- this.#sendWire(encodeWsFrame({
1534
- id,
1535
- op: "cancel"
1536
- }, this.#mode));
1537
- } catch {}
1538
- }
1539
- /**
1540
- * Push wire bytes to the socket. The branch exists because `WebSocket.send`'s
1541
- * overloads don't accept the union. Binary frames are copied into a fresh
1542
- * `Uint8Array` so the backing buffer is an `ArrayBuffer`, not the
1543
- * `ArrayBufferLike` msgpackr's `Buffer` is typed with — avoiding a cast.
1544
- */
1545
- #sendWire(wire) {
1546
- if (typeof wire === "string") this.#ws.send(wire);
1547
- else this.#ws.send(new Uint8Array(wire));
1548
- }
1549
- close() {
1550
- if (this.#closing) return;
1551
- this.#closing = true;
1552
- try {
1553
- this.#ws.close();
1554
- } catch {}
1555
- }
1556
- #onMessage(ev) {
1557
- let msg;
1558
- try {
1559
- msg = decodeWsEnvelope(ev.data, this.#mode);
1560
- } catch {
1561
- return;
1562
- }
1563
- const pending = this.#pending.get(msg.id);
1564
- if (!pending) return;
1565
- if (TERMINAL_KINDS.has(msg.kind)) this.#pending.delete(msg.id);
1566
- pending.onMessage(msg);
1567
- }
1568
- #onClose(ev) {
1569
- const reason = this.#closing ? "transport_closed" : ev.code === 1012 ? "server_restart" : `ws closed (code ${ev.code})`;
1570
- const snapshot = [...this.#pending.entries()];
1571
- this.#pending.clear();
1572
- for (const [, pending] of snapshot) pending.onClose(reason);
1573
- }
1574
- };
1575
-
1576
- //#endregion
1577
- //#region ../../packages/substrate-client/src/transport/ws.ts
1578
- /**
1579
- * WsTransport — high-level WebSocket transport for Substrate subscriptions.
1580
- *
1581
- * Manages one raw socket per `(endpoint, auth)` pair via MultiplexedSocket.
1582
- * Exposes `subscribe` and `stream` as AsyncIterables; `cancel` is handled
1583
- * transparently via the iterator's `return()` method.
1584
- *
1585
- * Protocol:
1586
- * - No hello/handshake: send subscribe/stream frames immediately on open.
1587
- * - WS handles: subscribe, stream, cancel only. Query/mutate use HTTP.
1588
- * - Auth: Bearer token in Authorization header on the HTTP upgrade request.
1589
- * Node-ws supports custom headers; the WHATWG/browser WebSocket does not,
1590
- * so under Node node-ws is always preferred even when a global WebSocket
1591
- * exists. True browsers cannot authenticate the WS without a
1592
- * header-capable `webSocket` implementation.
1593
- * - Response kinds: snapshot / add / update / remove / chunk / end / error.
1594
- * - Terminal kinds for cleanup: 'end' and 'error'.
1595
- *
1596
- * Reconnect: when the socket closes unexpectedly, ReconnectScheduler backs
1597
- * off and re-opens. Active subscriptions are resubscribed on the new socket —
1598
- * the consumer's AsyncIterable keeps flowing (snapshot arrives again from the
1599
- * server's perspective; the consumer sees it as a new event). A transport that
1600
- * has never connected does not retry: its first failure rejects `next()`.
1601
- */
1602
- /**
1603
- * Terminal-cause tokens from the WS teardown contract
1604
- * (docs/ws-subscription-contract.md). Local literals, not substrate-types
1605
- * imports: they are stable wire contract, like the 1012 close code.
1606
- */
1607
- const REASON_SUBSCRIPTION_OVERLOADED = "subscription_overloaded";
1608
- const REASON_SERVER_RESTART = "server_restart";
1609
- /**
1610
- * Pick the WebSocket implementation for a connection.
1611
- *
1612
- * Priority: injected > node-ws under Node > global (browser). Node ≥22 ships
1613
- * a global WebSocket that cannot carry headers, so preferring it would
1614
- * silently drop the bearer.
1615
- *
1616
- * Throws when a token is configured but the only available implementation
1617
- * cannot carry headers (a true browser): connecting anonymously to an
1618
- * auth-gated server would loop on 4001 instead.
1619
- */
1620
- function selectWebSocketImpl(opts) {
1621
- if (opts.injected !== void 0) return {
1622
- impl: opts.injected,
1623
- supportsHeaders: true
1624
- };
1625
- if (opts.isNode) return {
1626
- impl: opts.nodeWs,
1627
- supportsHeaders: true
1628
- };
1629
- if (opts.globalWs !== void 0) {
1630
- if (opts.hasToken) throw new NetworkError("WsTransport: a bearer token is configured but the only available WebSocket implementation (the WHATWG/browser global) cannot carry the Authorization header. Supply a header-capable implementation via the `webSocket` option.", null);
1631
- return {
1632
- impl: opts.globalWs,
1633
- supportsHeaders: false
1634
- };
1635
- }
1636
- throw new NetworkError("WsTransport: no WebSocket implementation available", null);
1637
- }
1638
- const DEFAULT_RECONNECT = {
1639
- baseDelayMs: 1e3,
1640
- maxDelayMs: 3e4,
1641
- jitter: .1
1642
- };
1643
- const DEFAULT_OVERLOAD_RESUBSCRIBE = {
1644
- enabled: true,
1645
- maxAttempts: 3,
1646
- baseDelayMs: 1e3,
1647
- maxDelayMs: 3e4,
1648
- jitter: .1,
1649
- healthyResetMs: 6e4
1650
- };
1651
- var WsTransport = class {
1652
- #endpoint;
1653
- #token;
1654
- #getToken;
1655
- #webSocket;
1656
- #reconnectOpts;
1657
- #encoding;
1658
- #overloadResubscribe;
1659
- /** Current multiplexed socket, or null if not yet opened / closed. */
1660
- #mux = null;
1661
- /** Promise that resolves when the socket is open and ready. */
1662
- #openPromise = null;
1663
- /** Set when close() is called — no more reconnects. */
1664
- #destroyed = false;
1665
- /** Active subscriptions keyed by their logical frame id. */
1666
- #activeSubs = /* @__PURE__ */ new Map();
1667
- /** Guard: prevents multiple concurrent #reconnectActiveSubs invocations. */
1668
- #reconnecting = false;
1669
- /**
1670
- * Close code captured from the most recent unintentional socket close.
1671
- * Read once by the next `#openLoop` and cleared. When it equals 1012
1672
- * (W3C "Service Restart") the loop skips its first scheduled backoff —
1673
- * the server is intentionally bouncing and we'd rather pay one wasted
1674
- * connect attempt than 1+s of jittered delay.
1675
- */
1676
- #lastCloseCode = null;
1677
- /**
1678
- * Backoff for closes that come AFTER an accepted upgrade (1013 overload,
1679
- * 4001 on a lapsed credential). It lives on the transport, not the open
1680
- * loop, so repeated churn grows the delay; a socket that delivers a frame
1681
- * and outlives `maxDelayMs` proves healthy and resets it.
1682
- */
1683
- #churn;
1684
- /**
1685
- * Retry forever only once a socket has opened. Before that, a failure is
1686
- * most likely a wrong endpoint or a broken token, so it surfaces instead.
1687
- */
1688
- #hasOpened = false;
1689
- constructor(opts) {
1690
- if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("WsTransport: provide `token` OR `getToken`, not both");
1691
- this.#endpoint = opts.endpoint;
1692
- this.#token = opts.token;
1693
- this.#getToken = opts.getToken;
1694
- this.#webSocket = opts.webSocket;
1695
- this.#reconnectOpts = {
1696
- ...DEFAULT_RECONNECT,
1697
- ...opts.reconnect
1698
- };
1699
- this.#churn = new ReconnectScheduler(this.#reconnectOpts);
1700
- this.#encoding = opts.encoding ?? "json";
1701
- this.#overloadResubscribe = {
1702
- ...DEFAULT_OVERLOAD_RESUBSCRIBE,
1703
- ...opts.overloadResubscribe
1704
- };
1705
- }
1706
- /**
1707
- * Subscribe to a live query. Returns an AsyncIterable of SubscribeEvents.
1708
- * Calling `break` or `return()` on the iterator sends a cancel frame.
1709
- */
1710
- subscribe(req) {
1711
- return this.#makeIterable({
1712
- ...req,
1713
- op: "subscribe"
1714
- });
1715
- }
1716
- /** Stream a one-shot resolver. Returns chunk events followed by an end event. */
1717
- stream(req) {
1718
- return this.#makeIterable({
1719
- ...req,
1720
- op: "stream"
1721
- });
1722
- }
1723
- /** Gracefully shut down. Cancels all active subscriptions and closes the socket. */
1724
- async close() {
1725
- this.#destroyed = true;
1726
- for (const [, sub] of this.#activeSubs) {
1727
- sub.done = true;
1728
- if (sub.retryTimer !== null) {
1729
- clearTimeout(sub.retryTimer);
1730
- sub.retryTimer = null;
1731
- }
1732
- if (sub.waiter) {
1733
- sub.waiter(null);
1734
- sub.waiter = null;
1735
- }
1736
- }
1737
- this.#activeSubs.clear();
1738
- if (this.#mux) {
1739
- this.#mux.close();
1740
- this.#mux = null;
1741
- }
1742
- this.#openPromise = null;
1743
- }
1744
- /** Ensure a connected MultiplexedSocket is available. */
1745
- async #ensureOpen() {
1746
- if (this.#mux !== null) return this.#mux;
1747
- if (this.#openPromise !== null) return this.#openPromise;
1748
- this.#openPromise = this.#openLoop();
1749
- return this.#openPromise;
1750
- }
1751
- /**
1752
- * Open loop: try to open a socket; on failure, backoff and retry.
1753
- * Runs until connected or #destroyed.
1754
- */
1755
- async #openLoop() {
1756
- const scheduler = new ReconnectScheduler(this.#reconnectOpts);
1757
- const wasGracefulRestart = this.#lastCloseCode === 1012;
1758
- const churned = this.#lastCloseCode === 1013 || this.#lastCloseCode === 4001;
1759
- this.#lastCloseCode = null;
1760
- if (churned) {
1761
- await this.#churn.schedule();
1762
- if (this.#destroyed) throw new NetworkError("WsTransport destroyed", null);
1763
- }
1764
- let firstFailure = true;
1765
- while (true) {
1766
- if (this.#destroyed) throw new NetworkError("WsTransport destroyed", null);
1767
- try {
1768
- const mux = await this.#openOnce();
1769
- if (this.#destroyed) {
1770
- mux.close();
1771
- throw new NetworkError("WsTransport destroyed", null);
1772
- }
1773
- scheduler.reset();
1774
- this.#hasOpened = true;
1775
- this.#mux = mux;
1776
- this.#openPromise = null;
1777
- return mux;
1778
- } catch (err) {
1779
- if (this.#destroyed) throw new NetworkError("WsTransport destroyed", err);
1780
- if (!this.#hasOpened) {
1781
- this.#openPromise = null;
1782
- throw err;
1783
- }
1784
- if (wasGracefulRestart && firstFailure) {
1785
- firstFailure = false;
1786
- await new Promise((resolve) => setTimeout(resolve, 0));
1787
- } else {
1788
- firstFailure = false;
1789
- await scheduler.schedule();
1790
- }
1791
- if (this.#destroyed) throw new NetworkError("WsTransport destroyed", null);
1792
- }
1793
- }
1794
- }
1795
- /** Open one WebSocket connection and resolve when it's ready. */
1796
- async #openOnce() {
1797
- const token = this.#token ?? (this.#getToken ? await this.#getToken() : void 0);
1798
- const subprotocols = this.#encoding === "pack" ? [WS_SUBPROTOCOL_SUBSTRATE_PACK] : void 0;
1799
- const ws = await new Promise((resolve, reject) => {
1800
- let rawWs;
1801
- const { impl, supportsHeaders } = selectWebSocketImpl({
1802
- injected: this.#webSocket,
1803
- isNode: typeof process !== "undefined" && process.versions?.node !== void 0,
1804
- globalWs: globalThis.WebSocket,
1805
- nodeWs: WebSocket,
1806
- hasToken: token !== void 0
1807
- });
1808
- if (supportsHeaders) {
1809
- const headers = {};
1810
- if (token !== void 0) headers.authorization = `Bearer ${token}`;
1811
- rawWs = new impl(this.#endpoint, subprotocols, { headers });
1812
- } else rawWs = subprotocols !== void 0 ? new impl(this.#endpoint, subprotocols) : new impl(this.#endpoint);
1813
- if (this.#encoding === "pack") try {
1814
- rawWs.binaryType = "arraybuffer";
1815
- } catch {}
1816
- const onOpen = () => {
1817
- rawWs.removeEventListener("error", onError);
1818
- resolve(rawWs);
1819
- };
1820
- const onError = (ev) => {
1821
- rawWs.removeEventListener("open", onOpen);
1822
- reject(new NetworkError(`WS connect failed: ${this.#endpoint}`, ev));
1823
- };
1824
- rawWs.addEventListener("open", onOpen);
1825
- rawWs.addEventListener("error", onError);
1826
- });
1827
- const mux = new MultiplexedSocket(ws, { usePack: this.#encoding === "pack" });
1828
- const openedAt = Date.now();
1829
- let delivered = false;
1830
- ws.addEventListener("message", () => {
1831
- delivered = true;
1832
- }, { once: true });
1833
- ws.addEventListener("close", (ev) => {
1834
- if (this.#destroyed) return;
1835
- const healthy = delivered && Date.now() - openedAt >= this.#reconnectOpts.maxDelayMs;
1836
- if (healthy) this.#churn.reset();
1837
- if (ev.code === 4001 && !(healthy && this.#canRefreshToken())) {
1838
- if (this.#mux === mux) this.#mux = null;
1839
- this.#failActiveSubs(new NetworkError(`WS closed 4001 unauthorized by ${this.#endpoint} — bearer rejected (wrong/expired token, or none configured against an auth-gated server)`, ev));
1840
- return;
1841
- }
1842
- if (this.#mux === mux) {
1843
- this.#mux = null;
1844
- this.#lastCloseCode = ev.code;
1845
- }
1846
- this.#reconnectActiveSubs().catch(() => {});
1847
- });
1848
- return mux;
1849
- }
1850
- /** Only a provider can mint a fresh token; a fixed `token` would be refused again. */
1851
- #canRefreshToken() {
1852
- return this.#token === void 0 && this.#getToken !== void 0;
1853
- }
1854
- /** Terminate every active sub with `err` — delivered so next() throws. */
1855
- #failActiveSubs(err) {
1856
- for (const [, sub] of this.#activeSubs) {
1857
- if (sub.done) continue;
1858
- sub.done = true;
1859
- if (sub.retryTimer !== null) {
1860
- clearTimeout(sub.retryTimer);
1861
- sub.retryTimer = null;
1862
- }
1863
- const payload = {
1864
- ok: false,
1865
- err
1866
- };
1867
- if (sub.waiter) {
1868
- const w = sub.waiter;
1869
- sub.waiter = null;
1870
- w(payload);
1871
- } else sub.queue.push(payload);
1872
- }
1873
- this.#activeSubs.clear();
1874
- }
1875
- /** Re-subscribe all active subs after a reconnect. */
1876
- async #reconnectActiveSubs() {
1877
- if (this.#reconnecting) return;
1878
- if (this.#destroyed) return;
1879
- this.#reconnecting = true;
1880
- try {
1881
- if (this.#activeSubs.size === 0) return;
1882
- let mux;
1883
- try {
1884
- mux = await this.#ensureOpen();
1885
- } catch {
1886
- for (const [, sub] of this.#activeSubs) {
1887
- sub.done = true;
1888
- if (sub.retryTimer !== null) {
1889
- clearTimeout(sub.retryTimer);
1890
- sub.retryTimer = null;
1891
- }
1892
- if (sub.waiter) {
1893
- sub.waiter(null);
1894
- sub.waiter = null;
1895
- }
1896
- }
1897
- this.#activeSubs.clear();
1898
- return;
1899
- }
1900
- for (const [, sub] of this.#activeSubs) {
1901
- if (sub.done) continue;
1902
- if (sub.retryTimer !== null) {
1903
- clearTimeout(sub.retryTimer);
1904
- sub.retryTimer = null;
1905
- }
1906
- this.#doSubscribe(mux, sub);
1907
- }
1908
- } finally {
1909
- this.#reconnecting = false;
1910
- }
1911
- }
1912
- /** Send a subscribe/stream frame on the mux and wire up the Pending handler. */
1913
- #doSubscribe(mux, sub) {
1914
- const pending = {
1915
- onMessage: (msg) => {
1916
- if (sub.done) return;
1917
- const action = this.#classifyTerminal(msg, sub);
1918
- if (action === "suppress") return;
1919
- let payload;
1920
- try {
1921
- if (msgToEvent(msg) === null) return;
1922
- payload = {
1923
- ok: true,
1924
- msg
1925
- };
1926
- } catch (err) {
1927
- payload = {
1928
- ok: false,
1929
- err: err instanceof Error ? err : new Error(String(err))
1930
- };
1931
- sub.done = true;
1932
- }
1933
- if (action === "terminal" && (msg.kind === "end" || msg.kind === "error")) sub.done = true;
1934
- if (sub.waiter) {
1935
- const w = sub.waiter;
1936
- sub.waiter = null;
1937
- w(payload);
1938
- } else sub.queue.push(payload);
1939
- },
1940
- onClose: (_reason) => {
1941
- if (sub.done) return;
1942
- if (this.#destroyed) {
1943
- sub.done = true;
1944
- if (sub.waiter) {
1945
- sub.waiter(null);
1946
- sub.waiter = null;
1947
- }
1948
- }
1949
- }
1950
- };
1951
- const outFrame = {
1952
- id: sub.socketId,
1953
- op: sub.frame.op,
1954
- frame: sub.frame.frame
1955
- };
1956
- mux.send(outFrame, pending);
1957
- }
1958
- /**
1959
- * Classify a frame per the teardown contract (substrate repo
1960
- * docs/ws-subscription-contract.md) BEFORE msgToEvent, which throws on
1961
- * error frames.
1962
- *
1963
- * - 'suppress': consumed by the retry machinery; never reaches the consumer.
1964
- * Overload error frames with budget left schedule a resubscribe here; the
1965
- * trailing `end { reason: 'subscription_overloaded' }` of a suppressed
1966
- * teardown is swallowed too.
1967
- * - 'survive': delivered to the consumer but NOT terminal — server_restart
1968
- * end frames; the sub stays live so the socket-close reconnect path
1969
- * resubscribes it.
1970
- * - 'terminal': mark done on delivery.
1971
- * - 'data': everything else.
1972
- */
1973
- #classifyTerminal(msg, sub) {
1974
- const cfg = this.#overloadResubscribe;
1975
- if (msg.kind === "error") {
1976
- if (msg.errors?.[0]?.code !== REASON_SUBSCRIPTION_OVERLOADED || !cfg.enabled) return "terminal";
1977
- const now = Date.now();
1978
- if (sub.lastOverloadAt !== null && now - sub.lastOverloadAt > cfg.healthyResetMs) sub.overloadAttempts = 0;
1979
- sub.lastOverloadAt = now;
1980
- if (sub.overloadAttempts >= cfg.maxAttempts) return "terminal";
1981
- sub.overloadAttempts += 1;
1982
- this.#scheduleOverloadRetry(sub);
1983
- return "suppress";
1984
- }
1985
- if (msg.kind === "end") {
1986
- if (msg.reason === REASON_SUBSCRIPTION_OVERLOADED && cfg.enabled && sub.retryTimer !== null) return "suppress";
1987
- if (msg.reason === REASON_SERVER_RESTART) return "survive";
1988
- if ((msg.reason === "credential_expired" || msg.reason === "credential_changed") && this.#canRefreshToken()) return "survive";
1989
- return "terminal";
1990
- }
1991
- return "data";
1992
- }
1993
- /** Backoff then re-send the subscribe frame for `sub` on the live socket. */
1994
- #scheduleOverloadRetry(sub) {
1995
- const cfg = this.#overloadResubscribe;
1996
- const raw = Math.min(cfg.baseDelayMs * 2 ** (sub.overloadAttempts - 1), cfg.maxDelayMs);
1997
- const delay = cfg.jitter === 0 ? raw : raw + (Math.random() * 2 - 1) * raw * cfg.jitter;
1998
- sub.retryTimer = setTimeout(() => {
1999
- sub.retryTimer = null;
2000
- if (sub.done || this.#destroyed) return;
2001
- this.#ensureOpen().then((mux) => {
2002
- if (!sub.done) this.#doSubscribe(mux, sub);
2003
- }).catch(() => {});
2004
- }, delay);
2005
- }
2006
- #makeIterable(frame) {
2007
- const logicalId = frame.id;
2008
- const transport = this;
2009
- return { [Symbol.asyncIterator]() {
2010
- const sub = {
2011
- frame,
2012
- socketId: logicalId,
2013
- queue: [],
2014
- waiter: null,
2015
- done: false,
2016
- overloadAttempts: 0,
2017
- lastOverloadAt: null,
2018
- retryTimer: null
2019
- };
2020
- transport.#activeSubs.set(logicalId, sub);
2021
- transport.#ensureOpen().then((mux) => {
2022
- if (!sub.done) transport.#doSubscribe(mux, sub);
2023
- }).catch((err) => {
2024
- if (sub.done) return;
2025
- sub.done = true;
2026
- transport.#activeSubs.delete(logicalId);
2027
- const payload = {
2028
- ok: false,
2029
- err: err instanceof Error ? err : new NetworkError(String(err), err)
2030
- };
2031
- if (sub.waiter) {
2032
- const w = sub.waiter;
2033
- sub.waiter = null;
2034
- w(payload);
2035
- } else sub.queue.push(payload);
2036
- });
2037
- return {
2038
- async next() {
2039
- while (true) {
2040
- if (sub.queue.length > 0) {
2041
- const payload = sub.queue.shift();
2042
- if (!payload.ok) {
2043
- sub.done = true;
2044
- transport.#activeSubs.delete(logicalId);
2045
- throw payload.err;
2046
- }
2047
- const ev = msgToEvent(payload.msg);
2048
- if (ev === null) continue;
2049
- return {
2050
- value: ev,
2051
- done: false
2052
- };
2053
- }
2054
- if (sub.done) return {
2055
- value: void 0,
2056
- done: true
2057
- };
2058
- const payload = await new Promise((resolve) => {
2059
- sub.waiter = resolve;
2060
- });
2061
- if (payload === null) return {
2062
- value: void 0,
2063
- done: true
2064
- };
2065
- if (!payload.ok) {
2066
- sub.done = true;
2067
- transport.#activeSubs.delete(logicalId);
2068
- throw payload.err;
2069
- }
2070
- const ev = msgToEvent(payload.msg);
2071
- if (ev !== null) return {
2072
- value: ev,
2073
- done: false
2074
- };
2075
- }
2076
- },
2077
- async return() {
2078
- if (!sub.done) {
2079
- sub.done = true;
2080
- if (sub.retryTimer !== null) {
2081
- clearTimeout(sub.retryTimer);
2082
- sub.retryTimer = null;
2083
- }
2084
- transport.#activeSubs.delete(logicalId);
2085
- if (transport.#mux) transport.#mux.cancel(sub.socketId);
2086
- if (sub.waiter) {
2087
- sub.waiter(null);
2088
- sub.waiter = null;
2089
- }
2090
- }
2091
- return {
2092
- value: void 0,
2093
- done: true
2094
- };
2095
- }
2096
- };
2097
- } };
2098
- }
2099
- };
2100
- /** Convert an InboundMessage to a SubscribeEvent, or null if unrecognised. */
2101
- function msgToEvent(msg) {
2102
- switch (msg.kind) {
2103
- case "snapshot":
2104
- case "add":
2105
- case "update": return {
2106
- kind: msg.kind,
2107
- data: msg.data,
2108
- ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {}
2109
- };
2110
- case "chunk": return {
2111
- kind: "chunk",
2112
- data: msg.data,
2113
- ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {},
2114
- ...msg.sequence !== void 0 ? { sequence: msg.sequence } : {}
2115
- };
2116
- case "remove": return {
2117
- kind: "remove",
2118
- removedId: msg.removedId ?? ""
2119
- };
2120
- case "end": return {
2121
- kind: "end",
2122
- ...msg.final !== void 0 ? { final: msg.final } : {},
2123
- ...msg.reason !== void 0 ? { reason: msg.reason } : {}
2124
- };
2125
- case "error": {
2126
- const first = (msg.errors ?? [{
2127
- message: "unknown error",
2128
- code: "unknown"
2129
- }])[0] ?? {
2130
- message: "unknown error",
2131
- code: "unknown"
2132
- };
2133
- throw new SubscribeError(first.message, first.code ?? "unknown");
2134
- }
2135
- default: return null;
2136
- }
2137
- }
2138
-
2139
1953
  //#endregion
2140
1954
  //#region ../../packages/substrate-client/src/wire/pack.ts
2141
1955
  function isPackMarker(v) {
@@ -2152,11 +1966,11 @@ function decodeJsonEnvelope(env) {
2152
1966
  //#endregion
2153
1967
  //#region ../../packages/substrate-client/src/client.ts
2154
1968
  /**
2155
- * SubstrateClient — the public facade over the HTTP and WS transports, wire
1969
+ * SubstrateClient — the public facade over the HTTP and frame-stream transports, wire
2156
1970
  * decoding and schema-drift handling.
2157
1971
  *
2158
- * Routing is protocol-mandated: query and mutate go over HTTP only (WS does
2159
- * not accept them); subscribe and stream go over WS only.
1972
+ * Routing is protocol-mandated: query and mutate are plain HTTP requests;
1973
+ * subscribe and stream are frame streams (one POST each, response held open).
2160
1974
  *
2161
1975
  * Drift detection is lazy-seeded: the client cannot replicate the server's
2162
1976
  * federated schema-version hash, so the first envelope's `schemaVersion` seeds
@@ -2165,21 +1979,19 @@ function decodeJsonEnvelope(env) {
2165
1979
  */
2166
1980
  var SubstrateClient = class {
2167
1981
  #http;
2168
- #ws = null;
2169
1982
  #nl;
2170
1983
  #admin;
2171
- #wsEndpoint;
2172
- #wsToken;
2173
- #wsGetToken;
2174
- #wsEncoding;
1984
+ #streamWire;
1985
+ #canRefreshToken;
1986
+ /** Aborted by close(), ending every open subscription and stream. */
1987
+ #closing = new AbortController();
2175
1988
  #reconnectOpts;
1989
+ #streamIdleMs;
2176
1990
  #overloadResubscribeOpts;
2177
- #webSocketImpl;
2178
1991
  #schemaCache = null;
2179
1992
  #schemaFetch = null;
2180
1993
  #driftCachedVersion = null;
2181
1994
  #closed = false;
2182
- #wsReqSeq = 0;
2183
1995
  #cache;
2184
1996
  #onDiagnostics;
2185
1997
  constructor(opts) {
@@ -2190,17 +2002,15 @@ var SubstrateClient = class {
2190
2002
  ...opts.getToken !== void 0 ? { getToken: opts.getToken } : {},
2191
2003
  ...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
2192
2004
  });
2193
- this.#wsEndpoint = `${trimTrailingSlashes(opts.endpoint.replace(/^http/, "ws"))}/substrate/v1/ws`;
2194
- this.#wsToken = opts.token;
2195
- this.#wsGetToken = opts.getToken;
2196
- this.#wsEncoding = opts.wsEncoding ?? "json";
2005
+ this.#streamWire = opts.streamWire ?? "json";
2006
+ this.#canRefreshToken = opts.token === void 0 && opts.getToken !== void 0;
2197
2007
  this.#reconnectOpts = opts.reconnect;
2008
+ this.#streamIdleMs = opts.streamIdleMs;
2198
2009
  this.#overloadResubscribeOpts = opts.overloadResubscribe;
2199
- this.#webSocketImpl = opts.webSocket;
2200
2010
  this.#onDiagnostics = opts.onDiagnostics ?? createDefaultDiagnosticsSink();
2201
2011
  this.#cache = new CacheStore({ idleGcMs: 5e3 });
2202
2012
  }
2203
- /** Natural-language ask (SSE or JSON) and the served namespace pack. Requires the substrate-nl plugin. */
2013
+ /** Natural-language ask (frame stream or JSON) and the served namespace pack. Requires the substrate-nl plugin. */
2204
2014
  get nl() {
2205
2015
  this.#nl ??= createNlApi(this.#http);
2206
2016
  return this.#nl;
@@ -2248,17 +2058,28 @@ var SubstrateClient = class {
2248
2058
  });
2249
2059
  return this.#decode(raw, frame, wire);
2250
2060
  }
2251
- subscribe(frame, _opts = {}) {
2252
- this.#ensureOpen();
2253
- const req = this.#frameToWsRequest(frame);
2254
- const inner = this.#getWs().subscribe(req);
2255
- return this.#wsEncoding === "pack" ? this.#wrapPackDecode(inner, req.frame) : inner;
2061
+ /** A live query: a snapshot, then deltas. `opts.wire` and `opts.signal` apply. */
2062
+ subscribe(frame, opts = {}) {
2063
+ return this.#frameStream("/substrate/v1/subscribe", frame, opts);
2256
2064
  }
2257
- stream(frame, _opts = {}) {
2065
+ /** A one-shot streamed resolver: chunks, then `end`. `opts.wire` and `opts.signal` apply. */
2066
+ stream(frame, opts = {}) {
2067
+ return this.#frameStream("/substrate/v1/stream", frame, opts);
2068
+ }
2069
+ #frameStream(path, frame, opts) {
2258
2070
  this.#ensureOpen();
2259
- const req = this.#frameToWsRequest(frame);
2260
- const inner = this.#getWs().stream(req);
2261
- return this.#wsEncoding === "pack" ? this.#wrapPackDecode(inner, req.frame) : inner;
2071
+ const body = flatFrame(frame);
2072
+ const wire = opts.wire ?? this.#streamWire;
2073
+ const signal = opts.signal === void 0 ? this.#closing.signal : anySignal([this.#closing.signal, opts.signal]);
2074
+ const inner = openFrameStream(this.#http, path, body, {
2075
+ wire,
2076
+ canRefreshToken: this.#canRefreshToken,
2077
+ signal,
2078
+ ...this.#reconnectOpts !== void 0 ? { reconnect: this.#reconnectOpts } : {},
2079
+ ...this.#streamIdleMs !== void 0 ? { idleMs: this.#streamIdleMs } : {},
2080
+ ...this.#overloadResubscribeOpts !== void 0 ? { overload: this.#overloadResubscribeOpts } : {}
2081
+ });
2082
+ return wire === "pack" ? this.#wrapPackDecode(inner, body) : inner;
2262
2083
  }
2263
2084
  /**
2264
2085
  * Live typed-row view over a single-key subscription. Subscribes under the
@@ -2269,7 +2090,7 @@ var SubstrateClient = class {
2269
2090
  *
2270
2091
  * Completes when the subscription ends; throws on an error frame — the same
2271
2092
  * contract as `subscribe`. Breaking the consuming `for await` cancels the
2272
- * underlying WS subscription. Reconnect / overload-resubscribe are handled by
2093
+ * underlying subscription. Reconnect / overload-resubscribe are handled by
2273
2094
  * `subscribe`; each fresh snapshot atomically replaces the row-set.
2274
2095
  *
2275
2096
  * Single-qualified-key only: multi-key frames throw; use `subscribe` for
@@ -2309,22 +2130,7 @@ var SubstrateClient = class {
2309
2130
  async close() {
2310
2131
  if (this.#closed) return;
2311
2132
  this.#closed = true;
2312
- if (this.#ws !== null) {
2313
- await this.#ws.close();
2314
- this.#ws = null;
2315
- }
2316
- }
2317
- #getWs() {
2318
- if (this.#ws === null) this.#ws = new WsTransport({
2319
- endpoint: this.#wsEndpoint,
2320
- encoding: this.#wsEncoding,
2321
- ...this.#wsToken !== void 0 ? { token: this.#wsToken } : {},
2322
- ...this.#wsGetToken !== void 0 ? { getToken: this.#wsGetToken } : {},
2323
- ...this.#reconnectOpts !== void 0 ? { reconnect: this.#reconnectOpts } : {},
2324
- ...this.#overloadResubscribeOpts !== void 0 ? { overloadResubscribe: this.#overloadResubscribeOpts } : {},
2325
- ...this.#webSocketImpl !== void 0 ? { webSocket: this.#webSocketImpl } : {}
2326
- });
2327
- return this.#ws;
2133
+ this.#closing.abort();
2328
2134
  }
2329
2135
  async #refetchSchema() {
2330
2136
  const schema = await this.#http.federatedSchema();
@@ -2356,31 +2162,7 @@ var SubstrateClient = class {
2356
2162
  return env;
2357
2163
  }
2358
2164
  /**
2359
- * Convert a `QualifiedFrame` into a `WsFrameRequest` for the WsTransport.
2360
- *
2361
- * The id MUST be unique per call: a key-derived id lets a re-subscribe race
2362
- * the old sub's terminal frame and silently kill the new one. The type-key
2363
- * prefix is only for readable logs. WsTransport reuses the id verbatim on
2364
- * reconnect, so it is stable for the subscription's lifetime.
2365
- */
2366
- #frameToWsRequest(frame) {
2367
- this.#wsReqSeq += 1;
2368
- const id = `${Object.keys(frame).sort().join("|")}#${this.#wsReqSeq}`;
2369
- const wsFrame = {};
2370
- for (const [key, entry] of Object.entries(frame)) {
2371
- const single = Array.isArray(entry) ? entry[0] : entry;
2372
- wsFrame[key] = {
2373
- params: single?.params ?? {},
2374
- fields: single?.fields ?? {}
2375
- };
2376
- }
2377
- return {
2378
- id,
2379
- frame: wsFrame
2380
- };
2381
- }
2382
- /**
2383
- * Wrap a WS event stream so each `data`-bearing frame (snapshot/add/update/
2165
+ * Wrap a frame event stream so each `data`-bearing frame (snapshot/add/update/
2384
2166
  * chunk) gets its positional tuple values reconstructed into named-object
2385
2167
  * rows using the cached federated schema. Errors from the inner stream
2386
2168
  * (transport drop, server error frame) propagate untouched.
@@ -2431,9 +2213,11 @@ var SubstrateClient = class {
2431
2213
  const { ns, name } = parsed;
2432
2214
  currentNsByKey[key] = ns;
2433
2215
  typeByKey[key] = name;
2434
- const nsSchema = schemas[ns];
2435
- if (nsSchema !== void 0 && nsSchema.mutations[name] !== void 0) returnsByKey[key] = nsSchema.mutations[name].returns;
2436
- else fieldsByKey[key] = entry?.fields ?? {};
2216
+ const mutation = schemas[ns]?.mutations[name];
2217
+ if (mutation !== void 0) {
2218
+ const shapeOf = (fields) => mutationReturns(mutation, fields);
2219
+ returnsByKey[key] = Array.isArray(frameEntry) ? frameEntry.map((f) => shapeOf(f.fields)) : shapeOf(entry?.fields);
2220
+ } else fieldsByKey[key] = entry?.fields ?? {};
2437
2221
  }
2438
2222
  return {
2439
2223
  fieldsByKey,
@@ -2444,6 +2228,17 @@ var SubstrateClient = class {
2444
2228
  };
2445
2229
  }
2446
2230
  };
2231
+ function flatFrame(frame) {
2232
+ const flat = {};
2233
+ for (const [key, entry] of Object.entries(frame)) {
2234
+ const single = Array.isArray(entry) ? entry[0] : entry;
2235
+ flat[key] = {
2236
+ params: single?.params ?? {},
2237
+ fields: single?.fields ?? {}
2238
+ };
2239
+ }
2240
+ return flat;
2241
+ }
2447
2242
 
2448
2243
  //#endregion
2449
2244
  //#region ../../packages/substrate-client/src/token-target.ts
@@ -2467,7 +2262,7 @@ function tokenAudience(baseUrl) {
2467
2262
  throw new Error(`refusing to send a credential to ${url.origin}: use https, or plain http only to a loopback host`);
2468
2263
  }
2469
2264
  /** `fetchImpl` with redirects refused: a redirect would carry the credential to wherever it points. */
2470
- function noRedirectFetch(fetchImpl = fetch) {
2265
+ function noRedirectFetch(fetchImpl = substrateFetch) {
2471
2266
  return (input, init) => fetchImpl(input, {
2472
2267
  ...init,
2473
2268
  redirect: "error"
@@ -2538,4 +2333,12 @@ function createClientFromEnv(opts = {}) {
2538
2333
  }
2539
2334
 
2540
2335
  //#endregion
2541
- export { diagnose as C, DIAGNOSE_CHECKS as S, SKIPPABLE_STEPS as _, SubstrateClient as a, planOnboarding as b, reduceSubscribeRows as c, NetworkError as d, SubscribeError as f, ONBOARD_STEPS as g, CURRENT_MARK as h, tokenAudience as i, watchRows as l, BACKFILL_CHUNK as m, resolveAgentCapabilities as n, collectDiagnostics as o, AdminBackfillError as p, noRedirectFetch as r, createDefaultDiagnosticsSink as s, createClientFromEnv as t, AuthError as u, STEP_MARKS as v, reconcileIdentities as w, requiredOutstanding as x, currentStep as y };
2336
+ //#region ../../packages/substrate-client/src/index.ts
2337
+ /**
2338
+ * The Node and Bun client: the browser surface, plus env-driven signing,
2339
+ * `diagnose`, and the `node:http2` fetch that `substrateFetch` uses from here on.
2340
+ */
2341
+ setSubstrateFetch(createH2Fetch());
2342
+
2343
+ //#endregion
2344
+ export { diagnose as C, substrateFetch as E, DIAGNOSE_CHECKS as S, createH2Fetch as T, SKIPPABLE_STEPS as _, SubstrateClient as a, planOnboarding as b, reduceSubscribeRows as c, NetworkError as d, SubscribeError as f, ONBOARD_STEPS as g, CURRENT_MARK as h, tokenAudience as i, watchRows as l, BACKFILL_CHUNK as m, resolveAgentCapabilities as n, collectDiagnostics as o, AdminBackfillError as p, noRedirectFetch as r, createDefaultDiagnosticsSink as s, createClientFromEnv as t, AuthError as u, STEP_MARKS as v, reconcileIdentities as w, requiredOutstanding as x, currentStep as y };