@mnmal-ai/substrate 1.0.0-alpha.8 → 1.0.0-beta.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.
Files changed (53) hide show
  1. package/README.md +32 -14
  2. package/dist/boot-store-BMQUbHKv.js +4086 -0
  3. package/dist/{runtime-metrics-DwpDJ8vz.d.ts → bridge-DnToJedN.d.ts} +2 -87
  4. package/dist/cli-DModIbnN.js +3390 -0
  5. package/dist/client.browser.js +2507 -0
  6. package/dist/client.d.ts +222 -171
  7. package/dist/client.js +6 -7
  8. package/dist/cluster-worker.js +0 -1
  9. package/dist/{content-type-C7T28xNb.js → content-type-wLljot5M.js} +0 -1
  10. package/dist/{env-utils-CGNazUNt.js → env-utils-s25Z1YSA.js} +0 -1
  11. package/dist/{errors-D4vKuwz8.d.ts → errors-Cmkp1qxf.d.ts} +44 -4
  12. package/dist/{fake-DUVtKVSE.js → fake-DdXtb-m8.js} +0 -1
  13. package/dist/{index-D7mSOFlM.d.ts → index-BI4KqFiR.d.ts} +7 -11
  14. package/dist/msgpackr-Dq18g6Ds.js +16 -0
  15. package/dist/node-version-BtK_Nq6z.js +32 -0
  16. package/dist/pack.d.ts +75 -11
  17. package/dist/pack.js +4 -4
  18. package/dist/{plugin-B3NxUCVn.js → plugin-CEOhrEme.js} +149 -6
  19. package/dist/proposals-bootstrap.js +6 -5
  20. package/dist/proposals.config.schema.json +5 -0
  21. package/dist/proposals.d.ts +17 -5
  22. package/dist/proposals.default-config.json +2 -1
  23. package/dist/proposals.js +2 -3
  24. package/dist/recall-bootstrap.js +5 -4
  25. package/dist/recall.config.schema.json +6 -0
  26. package/dist/recall.d.ts +27 -6
  27. package/dist/recall.js +2 -3
  28. package/dist/{repl-DeKzfvNV.js → repl-BvDZy-Ut.js} +52 -26
  29. package/dist/{row-ByLFE2Wx.d.ts → row-D0If4qif.d.ts} +92 -12
  30. package/dist/run-BT123RV1.js +2443 -0
  31. package/dist/{plugin-t2g2wX0b.d.ts → schema-aIkY8sR3.d.ts} +1293 -63
  32. package/dist/{script-C6DSa_Na.js → script-ByQ9pzhC.js} +54 -26
  33. package/dist/script-runner.js +78 -0
  34. package/dist/sdk.d.ts +236 -38
  35. package/dist/sdk.js +5 -110
  36. package/dist/semver-D_zdq0hi.js +17 -0
  37. package/dist/src-BMD2OE--.js +8289 -0
  38. package/dist/{src-BLgbLq2k.js → src-B_kHkbsr.js} +780 -330
  39. package/dist/{src-DjIuRjzF.js → src-CKSJ13p8.js} +10231 -4237
  40. package/dist/{src-CkZw6xVD.js → src-CW7eRDss.js} +188 -87
  41. package/dist/{row-DZ0Fnpc6.js → src-DmiUWOLp.js} +2 -1
  42. package/dist/{src-DCy7Iy2l.js → src-DmjwFMu8.js} +900 -77
  43. package/dist/{src-DiNTSaFk.js → src-FXO5JPyk.js} +686 -856
  44. package/dist/substrate-admin.js +17 -782
  45. package/dist/substrate.js +4 -5206
  46. package/dist/testing.d.ts +473 -96
  47. package/dist/testing.js +19 -165
  48. package/dist/{ws-C72iVS5T.d.ts → ws-DW8ng02H.d.ts} +4 -5
  49. package/package.json +26 -26
  50. package/dist/dataset-jZS_4ci4.js +0 -1535
  51. package/dist/pg-edges-store-KH_FQCxx.js +0 -381
  52. package/dist/schema-g4FQLr0V.d.ts +0 -433
  53. package/dist/src-BD27zeGF.js +0 -2339
@@ -0,0 +1,2507 @@
1
+ import * as msgpackr from "msgpackr";
2
+ import { signal } from "@preact/signals-core";
3
+
4
+ //#region ../../packages/substrate-client/src/admin/onboard.ts
5
+ const SECOND_ADMIN = "second-admin";
6
+ const FIRST_AGENT = "first-agent";
7
+ const ONBOARD_STEPS = [
8
+ "reachable",
9
+ "auth-enabled",
10
+ "credential",
11
+ "identity",
12
+ "admin-capability",
13
+ "admin-floor",
14
+ SECOND_ADMIN,
15
+ "namespaces",
16
+ "key-directory",
17
+ FIRST_AGENT
18
+ ];
19
+ const SKIPPABLE_STEPS = /* @__PURE__ */ new Set([SECOND_ADMIN, FIRST_AGENT]);
20
+ /** The checklist marks every surface draws, so the CLI and the TUI cannot drift. */
21
+ const STEP_MARKS = {
22
+ done: "✓",
23
+ todo: "·",
24
+ blocked: "⊘",
25
+ skipped: "↷"
26
+ };
27
+ /** Marks the step the operator is on: the first `todo`. */
28
+ const CURRENT_MARK = "▶";
29
+ const NO_BOOTSTRAP_FIX = "No admin credential resolves, and `bootstrap` needs SUBSTRATE_DATABASE_URL (a postgres:// URL) — run onboard where the database is reachable, or set SUBSTRATE_ADMIN_TOKEN / SUBSTRATE_ADMIN_KEY_PATH + SUBSTRATE_ADMIN_KEY_ID for an existing admin.";
30
+ function fromCheck(name, check) {
31
+ const base = {
32
+ name,
33
+ optional: false,
34
+ skippable: false
35
+ };
36
+ if (check === void 0) return {
37
+ ...base,
38
+ status: "blocked",
39
+ detail: "not reported — an earlier step stopped the run"
40
+ };
41
+ if (check.status === "ok") return {
42
+ ...base,
43
+ status: "done",
44
+ detail: check.detail
45
+ };
46
+ if (check.status === "skip") return {
47
+ ...base,
48
+ status: "blocked",
49
+ detail: check.detail
50
+ };
51
+ return {
52
+ ...base,
53
+ status: "todo",
54
+ detail: check.detail,
55
+ ...check.fix !== void 0 ? { fix: check.fix } : {}
56
+ };
57
+ }
58
+ function fromGoal(goal, skipped) {
59
+ const base = {
60
+ name: goal.name,
61
+ optional: goal.optional,
62
+ skippable: true
63
+ };
64
+ if (!goal.measured) return {
65
+ ...base,
66
+ status: "blocked",
67
+ detail: goal.detail.blocked
68
+ };
69
+ if (goal.met) return {
70
+ ...base,
71
+ status: "done",
72
+ detail: goal.detail.met
73
+ };
74
+ if (skipped.has(goal.name)) return {
75
+ ...base,
76
+ status: "skipped",
77
+ detail: goal.detail.unmet
78
+ };
79
+ return {
80
+ ...base,
81
+ status: "todo",
82
+ detail: goal.detail.unmet,
83
+ fix: goal.fix,
84
+ action: goal.action
85
+ };
86
+ }
87
+ function planOnboarding(result, opts) {
88
+ const byName = new Map(result.checks.map((c) => [c.name, c]));
89
+ const { facts } = result;
90
+ const steps = [];
91
+ for (const name of ONBOARD_STEPS) {
92
+ if (name === SECOND_ADMIN) {
93
+ const admins = facts.adminKids;
94
+ steps.push(fromGoal({
95
+ name,
96
+ optional: false,
97
+ measured: byName.get("admin-floor")?.status === "ok" && admins !== void 0,
98
+ met: (admins?.length ?? 0) >= 2,
99
+ detail: {
100
+ met: `${admins?.length ?? 0} admin keys — succession is possible`,
101
+ unmet: "one admin key. Losing it locks this deployment out of its own admin surface, and the floor will refuse to revoke it.",
102
+ blocked: "not measured — admin-floor did not pass"
103
+ },
104
+ fix: "Register a second admin key, held somewhere other than the first.",
105
+ action: { kind: "register-admin" }
106
+ }, opts.skipped));
107
+ continue;
108
+ }
109
+ if (name === FIRST_AGENT) {
110
+ const agents = facts.agentKids;
111
+ steps.push(fromGoal({
112
+ name,
113
+ optional: true,
114
+ measured: agents !== void 0,
115
+ met: (agents?.length ?? 0) > 0,
116
+ detail: {
117
+ met: `${agents?.length ?? 0} agent identities with a live key`,
118
+ unmet: "no agent identity yet — register one to exercise the route and directory",
119
+ blocked: "not measured — the directory could not be read"
120
+ },
121
+ fix: "Register a first agent identity.",
122
+ action: { kind: "register-agent" }
123
+ }, opts.skipped));
124
+ continue;
125
+ }
126
+ const step = fromCheck(name, byName.get(name));
127
+ if (step.status !== "todo") {
128
+ steps.push(step);
129
+ continue;
130
+ }
131
+ if (name === "credential") {
132
+ steps.push(opts.canBootstrap ? {
133
+ ...step,
134
+ action: { kind: "bootstrap" }
135
+ } : opts.explainNoBootstrap === false ? step : {
136
+ ...step,
137
+ fix: NO_BOOTSTRAP_FIX
138
+ });
139
+ continue;
140
+ }
141
+ const retired = facts.retiredWithLiveKey ?? [];
142
+ if (name === "key-directory" && retired.length > 0) {
143
+ steps.push({
144
+ ...step,
145
+ action: {
146
+ kind: "revoke",
147
+ kids: retired
148
+ }
149
+ });
150
+ continue;
151
+ }
152
+ steps.push(step);
153
+ }
154
+ return steps;
155
+ }
156
+ /** The step the operator is on: the first one still to do. */
157
+ function currentStep(steps) {
158
+ return steps.find((s) => s.status === "todo");
159
+ }
160
+ /** True while any required step is still to do — the `--check` verdict. */
161
+ function requiredOutstanding(steps) {
162
+ return steps.some((s) => s.status === "todo" && !s.optional);
163
+ }
164
+
165
+ //#endregion
166
+ //#region ../../packages/substrate-client/src/admin/surgery.ts
167
+ /** Mirrors BACKFILL_MAX_ROWS in substrate-compose; the server enforces it. */
168
+ const BACKFILL_CHUNK = 5e3;
169
+ /**
170
+ * A chunk was refused. `chunksDone` chunks were already sent (and, on apply, WRITTEN); `partial` sums them.
171
+ *
172
+ * `cause` is the real failure and may be an `AuthError` (a rejected admin key) or a
173
+ * `NetworkError` (including one wrapping an `AbortError`). Callers must unwrap `cause`
174
+ * before applying an auth-lock rule or abort handling.
175
+ *
176
+ * `partial.applied` true means at least one chunk was accepted and written; `chunksDone` says how
177
+ * many. `false` does NOT prove nothing was written: a first chunk refused with anything but a 4xx
178
+ * may have partly written (below). A refusal with a 4xx status guarantees the failing chunk wrote nothing;
179
+ * anything else (a 5xx such as `verify_failed`, a dropped connection, an abort) may have
180
+ * partly written the failing chunk, since the route writes in non-transactional 200-row batches.
181
+ */
182
+ var AdminBackfillError = class extends Error {
183
+ cause;
184
+ chunksDone;
185
+ chunks;
186
+ partial;
187
+ name = "AdminBackfillError";
188
+ constructor(cause, chunksDone, chunks, partial) {
189
+ super(`backfill stopped at chunk ${chunksDone + 1} of ${chunks}: ${cause instanceof Error ? cause.message : String(cause)}`);
190
+ this.cause = cause;
191
+ this.chunksDone = chunksDone;
192
+ this.chunks = chunks;
193
+ this.partial = partial;
194
+ }
195
+ };
196
+ const sig$1 = (o) => o.signal !== void 0 ? { signal: o.signal } : {};
197
+ function createSurgeryApi(t) {
198
+ const post = async (path, body, o) => await (await t.raw(path, {
199
+ method: "POST",
200
+ body,
201
+ ...sig$1(o)
202
+ })).json();
203
+ return {
204
+ async backfill(input, o = {}) {
205
+ const entries = Object.entries(input.values);
206
+ const chunks = Math.ceil(entries.length / BACKFILL_CHUNK);
207
+ const apply = input.apply === true;
208
+ let write = 0;
209
+ let kept = 0;
210
+ let unchanged = 0;
211
+ const missing = [];
212
+ const counts = {};
213
+ const summary = (applied = apply) => ({
214
+ requested: entries.length,
215
+ write,
216
+ kept,
217
+ unchanged,
218
+ missing: [...missing],
219
+ counts: { ...counts },
220
+ applied,
221
+ chunks
222
+ });
223
+ for (let index = 0; index < chunks; index++) {
224
+ const slice = entries.slice(index * BACKFILL_CHUNK, (index + 1) * BACKFILL_CHUNK);
225
+ let body;
226
+ try {
227
+ body = await post("/substrate/v1/_system/backfill-field", {
228
+ namespace: input.namespace,
229
+ type: input.type,
230
+ field: input.field,
231
+ apply,
232
+ overwrite: input.overwrite === true,
233
+ values: Object.fromEntries(slice)
234
+ }, o);
235
+ } catch (err) {
236
+ throw new AdminBackfillError(err, index, chunks, summary(apply && index > 0));
237
+ }
238
+ write += Number(body.write ?? 0);
239
+ kept += Number(body.kept ?? 0);
240
+ unchanged += Number(body.unchanged ?? 0);
241
+ if (Array.isArray(body.missing)) missing.push(...body.missing);
242
+ for (const [k, n] of Object.entries(body.counts ?? {})) counts[k] = (counts[k] ?? 0) + n;
243
+ o.onChunk?.({
244
+ index,
245
+ chunks,
246
+ body
247
+ });
248
+ }
249
+ return summary();
250
+ },
251
+ reindexPage(input, o = {}) {
252
+ const body = {
253
+ namespace: input.namespace,
254
+ type: input.type
255
+ };
256
+ if (input.cursor !== void 0) body.cursor = input.cursor;
257
+ if (input.limit !== void 0) body.limit = input.limit;
258
+ return post("/substrate/v1/embed/reindex", body, o);
259
+ },
260
+ async embedStats(o = {}) {
261
+ return await (await t.raw("/substrate/v1/embed-stats", {
262
+ method: "GET",
263
+ ...sig$1(o)
264
+ })).json();
265
+ },
266
+ dropNamespace(input, o = {}) {
267
+ const body = {
268
+ namespace: input.namespace,
269
+ confirm: input.confirm
270
+ };
271
+ if (input.cascade !== void 0) body.cascade = input.cascade;
272
+ if (input.dryRun !== void 0) body.dryRun = input.dryRun;
273
+ return post("/substrate/v1/_system/drop-namespace", body, o);
274
+ },
275
+ dropType(input, o = {}) {
276
+ const body = {
277
+ namespace: input.namespace,
278
+ type: input.type,
279
+ confirm: input.confirm
280
+ };
281
+ if (input.cascade !== void 0) body.cascade = input.cascade;
282
+ if (input.dryRun !== void 0) body.dryRun = input.dryRun;
283
+ return post("/substrate/v1/_system/drop-type", body, o);
284
+ },
285
+ normalise(input, o = {}) {
286
+ const body = {
287
+ namespace: input.namespace,
288
+ type: input.type,
289
+ field: input.field
290
+ };
291
+ if (input.reject !== void 0) body.reject = [...input.reject];
292
+ if (input.apply === true) body.apply = true;
293
+ return post("/substrate/v1/_system/normalise-vocab", body, o);
294
+ }
295
+ };
296
+ }
297
+
298
+ //#endregion
299
+ //#region ../../packages/substrate-types/src/assert-never.ts
300
+ /**
301
+ * Exhaustiveness guard for the `default:` arm of a `switch` over a
302
+ * discriminated union. An unhandled variant makes the call fail to
303
+ * type-check; at runtime it throws rather than returning `undefined`.
304
+ */
305
+ function assertNever(x) {
306
+ throw new Error(`unhandled variant: ${JSON.stringify(x)}`);
307
+ }
308
+
309
+ //#endregion
310
+ //#region ../../packages/substrate-types/src/env-utils.ts
311
+ /**
312
+ * `url` with its trailing slashes removed, for joining a configured base URL
313
+ * to a path. A loop rather than `/\/+$/`, which backtracks quadratically on a
314
+ * long run of slashes that does not end the string.
315
+ */
316
+ function trimTrailingSlashes(url) {
317
+ let end = url.length;
318
+ while (end > 0 && url.charCodeAt(end - 1) === 47) end--;
319
+ return url.slice(0, end);
320
+ }
321
+
322
+ //#endregion
323
+ //#region ../../packages/substrate-types/src/expression.ts
324
+ const sig = (name, args, returns, description) => ({
325
+ name,
326
+ args,
327
+ returns,
328
+ description
329
+ });
330
+ const CMP = "both sides the same type; int64 and number compare as number.";
331
+ const EXPR_FUNCTIONS = [
332
+ sig("add", ["number", "number"], "any", "Sum; int64 when both are int64 (or a safe-integer literal), else number. Errors on overflow."),
333
+ sig("sub", ["number", "number"], "any", "Difference; int64 when both are int64, else number. Errors on overflow."),
334
+ sig("mul", ["number", "number"], "any", "Product; int64 when both are int64, else number. Errors on overflow, and on a nonzero product that underflows to zero."),
335
+ sig("div", ["number", "number"], "number", "Quotient as a number; null when the divisor is zero. Errors on overflow, and on a nonzero quotient that underflows to zero."),
336
+ sig("mod", ["int64", "int64"], "int64", "Remainder of int64 arguments (a safe-integer literal counts); null when the divisor is zero."),
337
+ sig("neg", ["number"], "any", "Arithmetic negation; keeps int64."),
338
+ sig("eq", ["any", "any"], "boolean", `Equal; ${CMP}`),
339
+ sig("neq", ["any", "any"], "boolean", `Not equal; ${CMP}`),
340
+ sig("gt", ["any", "any"], "boolean", `Greater than; ${CMP}`),
341
+ sig("gte", ["any", "any"], "boolean", `Greater than or equal; ${CMP}`),
342
+ sig("lt", ["any", "any"], "boolean", `Less than; ${CMP}`),
343
+ sig("lte", ["any", "any"], "boolean", `Less than or equal; ${CMP}`),
344
+ sig("and", "variadic", "boolean", "True when every boolean argument (one or more) is true."),
345
+ sig("or", "variadic", "boolean", "True when any boolean argument (one or more) is true."),
346
+ sig("not", ["boolean"], "boolean", "Boolean negation."),
347
+ sig("isNull", ["any"], "boolean", "True when its one argument is null; any type."),
348
+ sig("in", "variadic", "boolean", "True when the first argument equals any later one (two or more arguments share a type)."),
349
+ sig("length", ["string"], "number", "Length in characters."),
350
+ sig("lower", ["string"], "string", "Lower-cased text; ASCII letters only, every other character is unchanged."),
351
+ sig("upper", ["string"], "string", "Upper-cased text; ASCII letters only, every other character is unchanged."),
352
+ sig("substring", [
353
+ "string",
354
+ "number",
355
+ "number"
356
+ ], "string", "Substring from a 1-based start for a length."),
357
+ sig("concat", "variadic", "string", "Concatenation of one or more string arguments."),
358
+ sig("like", ["string", "likePattern"], "boolean", "SQL LIKE, case-sensitive: % and _ wildcards, backslash escape. The pattern is a lit that does not end in an unescaped backslash."),
359
+ sig("notLike", ["string", "likePattern"], "boolean", "Negated SQL LIKE, case-sensitive."),
360
+ sig("regexpMatch", ["string", "pattern"], "boolean", "True when the portable-subset regex (a lit) matches anywhere."),
361
+ sig("regexpReplace", [
362
+ "string",
363
+ "pattern",
364
+ "string"
365
+ ], "string", "Replace the leftmost-longest regex (a lit) match; the replacement may use \\1 to \\9. The pattern may use capturing groups or |, not both."),
366
+ sig("dateTrunc", ["unit", "date"], "date", "Truncate a date (UTC) to a unit given as a lit."),
367
+ sig("extract", ["unit", "date"], "number", "A date part (UTC) as a number; the unit is a lit."),
368
+ sig("case", "variadic", "any", "Pairs [cond, then] then a final else; branches share a type."),
369
+ sig("coalesce", "variadic", "any", "First non-null of one or more arguments sharing a type.")
370
+ ];
371
+
372
+ //#endregion
373
+ //#region ../../packages/substrate-types/src/qualified-key.ts
374
+ function parseQualifiedKey(key) {
375
+ const slash = key.indexOf("/");
376
+ if (slash <= 0 || slash === key.length - 1) return null;
377
+ return {
378
+ ns: key.slice(0, slash),
379
+ name: key.slice(slash + 1)
380
+ };
381
+ }
382
+
383
+ //#endregion
384
+ //#region ../../packages/substrate-pack/src/_plan-cache.ts
385
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
386
+ /** The slot for one selection entry, or undefined for a plain field. */
387
+ function walkSlot(name, sel, fieldMap) {
388
+ if (!isObj(sel)) return void 0;
389
+ if (name === "_agg") return {
390
+ kind: "agg",
391
+ names: Object.keys(sel)
392
+ };
393
+ const walk = sel._walk;
394
+ if (!isObj(walk)) return void 0;
395
+ let type;
396
+ if (typeof walk.in === "string") type = /^[^/]+\/([^./]+)\./.exec(walk.in)?.[1];
397
+ else if (typeof walk.out === "string") {
398
+ const def = Object.hasOwn(fieldMap, walk.out) ? fieldMap[walk.out] : void 0;
399
+ if (def?.kind === "crossRef") type = def.type;
400
+ }
401
+ if (type === void 0) return void 0;
402
+ const fields = isObj(sel.fields) ? sel.fields : {};
403
+ return {
404
+ kind: "nested",
405
+ type,
406
+ fields: {
407
+ id: true,
408
+ ...fields
409
+ }
410
+ };
411
+ }
412
+ /**
413
+ * Lookup-or-build the per-(fields, fieldMap) plan. O(1) on hit; O(F) on miss
414
+ * for F selected fields.
415
+ */
416
+ function getRowPlan$1(cache, fields, fieldMap) {
417
+ let perFieldMap = cache.get(fields);
418
+ if (perFieldMap === void 0) {
419
+ perFieldMap = /* @__PURE__ */ new WeakMap();
420
+ cache.set(fields, perFieldMap);
421
+ }
422
+ const cached = perFieldMap.get(fieldMap);
423
+ if (cached !== void 0) return cached;
424
+ const entries = Object.entries(fields);
425
+ const plan = new Array(entries.length);
426
+ let nested = false;
427
+ for (let i = 0; i < entries.length; i++) {
428
+ const pair = entries[i];
429
+ const def = Object.hasOwn(fieldMap, pair[0]) ? fieldMap[pair[0]] : void 0;
430
+ const slot = def === void 0 ? walkSlot(pair[0], pair[1], fieldMap) : void 0;
431
+ if (slot?.kind === "nested") nested = true;
432
+ plan[i] = slot === void 0 ? [
433
+ pair[0],
434
+ pair[1],
435
+ def
436
+ ] : [
437
+ pair[0],
438
+ pair[1],
439
+ def,
440
+ slot
441
+ ];
442
+ }
443
+ if (nested) plan.push([
444
+ "_truncated",
445
+ true,
446
+ void 0,
447
+ { kind: "truncated" }
448
+ ]);
449
+ perFieldMap.set(fieldMap, plan);
450
+ return plan;
451
+ }
452
+ /**
453
+ * Lookup-or-build the per-fields FieldDefPlan. O(1) on hit; O(F) on miss.
454
+ */
455
+ function getFieldDefPlan$1(cache, fields) {
456
+ const cached = cache.get(fields);
457
+ if (cached !== void 0) return cached;
458
+ const entries = Object.entries(fields);
459
+ const plan = new Array(entries.length);
460
+ for (let i = 0; i < entries.length; i++) {
461
+ const pair = entries[i];
462
+ plan[i] = [pair[0], pair[1]];
463
+ }
464
+ cache.set(fields, plan);
465
+ return plan;
466
+ }
467
+ /**
468
+ * Schema lookup for a type name. Tries the regular type registry first; falls
469
+ * back to mutations whose `returns` is a struct (the natural lookup for
470
+ * nested selection through a mutation-typed frame key). Returns `undefined`
471
+ * when the type is unknown — callers throw their own typed error with the
472
+ * appropriate path context.
473
+ *
474
+ * Non-struct mutation returns (e.g. delete's `{id, deleted}`) intentionally
475
+ * surface as an empty field map rather than undefined — the lookup
476
+ * succeeded; the type has no nested selection. Both codecs treat the empty
477
+ * map as "no fields to project".
478
+ */
479
+ function lookupFieldMap(schema, typeName) {
480
+ const typeEntry = Object.hasOwn(schema.types, typeName) ? schema.types[typeName] : void 0;
481
+ if (typeEntry !== void 0) return typeEntry.fields;
482
+ const mutationEntry = Object.hasOwn(schema.mutations, typeName) ? schema.mutations[typeName] : void 0;
483
+ if (mutationEntry !== void 0) {
484
+ const ret = mutationEntry.returns;
485
+ if (ret.kind === "struct") return ret.fields;
486
+ return {};
487
+ }
488
+ }
489
+ /**
490
+ * Resolve a type's field map, or throw the error `makeError` builds when the
491
+ * type is unknown.
492
+ */
493
+ function resolveFieldMap$1(schema, typeName, path, makeError) {
494
+ const fieldMap = lookupFieldMap(schema, typeName);
495
+ if (fieldMap === void 0) throw makeError(`unknown type '${typeName}' in schema`, path);
496
+ return fieldMap;
497
+ }
498
+
499
+ //#endregion
500
+ //#region ../../packages/substrate-pack/src/msgpackr.ts
501
+ /**
502
+ * The one module that imports msgpackr. The published bundle gives it a chunk
503
+ * of its own, so a consumer that never packs or unpacks drops msgpackr, which
504
+ * does not declare itself free of load-time side effects. These are wrappers,
505
+ * not re-exports: a bundler resolves a re-export straight to msgpackr, which
506
+ * would leave every importer of this module importing msgpackr itself.
507
+ */
508
+ const unpack = (...args) => msgpackr.unpack(...args);
509
+ const createUnpackr = (options) => new msgpackr.Unpackr(options);
510
+
511
+ //#endregion
512
+ //#region ../../packages/substrate-pack/src/encoder.ts
513
+ /**
514
+ * @internal — error thrown by the positional encoder on malformed input.
515
+ * Exported, but treat as package-private.
516
+ */
517
+ var PackEncodeError = class extends Error {
518
+ name = "PackEncodeError";
519
+ path;
520
+ constructor(message, path) {
521
+ super(`${message} at ${path.length === 0 ? "<root>" : path.join(".")}`);
522
+ this.path = path.slice();
523
+ }
524
+ };
525
+ /** A shape whose value is a `{ count }` or `{ groups }` map, not rows. */
526
+ function isAggShape(shape) {
527
+ return shape === "count" || shape === "groups";
528
+ }
529
+ /** Frame `idx`'s return shape: its own entry for a batched key, else the key's one shape. */
530
+ function frameDef(def, idx) {
531
+ if (!Array.isArray(def)) return def;
532
+ const one = def[idx];
533
+ if (one === void 0) throw new PackEncodeError(`no return shape for frame ${idx}`, []);
534
+ return one;
535
+ }
536
+
537
+ //#endregion
538
+ //#region ../../packages/substrate-pack/src/decoder.ts
539
+ /**
540
+ * Positional decoder. Spec: §7.0, §7.2.
541
+ *
542
+ * Mirror of `encoder.ts`. Rebuilds named objects from positional tuples using
543
+ * the same `FieldInput` the client originally sent plus the schema cached at
544
+ * init. Single-vs-list dispatch is driven by `PackEnvelope.shapes[key]`
545
+ * (§7.2) — no inference from the tuple shape.
546
+ *
547
+ * Schema drift (§7.1) is detected here when the caller passes
548
+ * `expectedSchemaVersion`: the decoder throws `SchemaDriftError` before
549
+ * decoding any data value, so drift fails loudly instead of corrupting row
550
+ * shapes. Refetch-and-retry is the caller's job. Without
551
+ * `expectedSchemaVersion` no check is made.
552
+ */
553
+ /**
554
+ * @internal — error thrown by the positional decoder on malformed input.
555
+ * Exported, but treat as package-private; signature may change without a
556
+ * major bump.
557
+ */
558
+ var PackDecodeError = class extends Error {
559
+ name = "PackDecodeError";
560
+ path;
561
+ constructor(message, path) {
562
+ super(`${message} at ${path.length === 0 ? "<root>" : path.join(".")}`);
563
+ this.path = path.slice();
564
+ }
565
+ };
566
+ /**
567
+ * §7.1 loud-failure. Thrown by `decodeEnvelope` when the caller supplied an
568
+ * `expectedSchemaVersion` that disagrees with the envelope's declared version.
569
+ * Carries both sides of the mismatch so the caller can decide whether to
570
+ * refetch the federated schema and retry or surface the error.
571
+ */
572
+ var SchemaDriftError = class extends Error {
573
+ envelopeSchemaVersion;
574
+ expectedSchemaVersion;
575
+ name = "SchemaDriftError";
576
+ constructor(envelopeSchemaVersion, expectedSchemaVersion) {
577
+ super(`schema drift: envelope schemaVersion '${envelopeSchemaVersion}' does not match expected '${expectedSchemaVersion}'`);
578
+ this.envelopeSchemaVersion = envelopeSchemaVersion;
579
+ this.expectedSchemaVersion = expectedSchemaVersion;
580
+ }
581
+ };
582
+ function decodePositional(encoded, fields, schema, typeName, ctx) {
583
+ if (encoded === null || encoded === void 0) return null;
584
+ return decodeValueByArity(encoded, fields, resolveFieldMap(schema, typeName, [typeName]), schema, [typeName], ctx);
585
+ }
586
+ /**
587
+ * Decode a mutation response against its declared `FieldDef`. Symmetric to
588
+ * `encodePositionalFromFieldDef`.
589
+ *
590
+ * @internal — used by `decodeEnvelope` for mutation returns. Treat as
591
+ * package-private.
592
+ */
593
+ function decodePositionalFromFieldDef(encoded, def, schema, ctx, path = []) {
594
+ if (encoded === null || encoded === void 0) return null;
595
+ return decodeFieldDef(encoded, def, schema, path, ctx);
596
+ }
597
+ function decodeEnvelope(bytes, ctx) {
598
+ const raw = unpack(bytes);
599
+ if (ctx.expectedSchemaVersion !== void 0 && raw.schemaVersion !== ctx.expectedSchemaVersion) throw new SchemaDriftError(raw.schemaVersion, ctx.expectedSchemaVersion);
600
+ const rewritten = {};
601
+ for (const [key, value] of Object.entries(raw.data)) {
602
+ if (isAggShape(raw.shapes[key])) {
603
+ rewritten[key] = value;
604
+ continue;
605
+ }
606
+ const returns = ctx.returnsByKey?.[key];
607
+ if (returns !== void 0) {
608
+ const currentNs = ctx.currentNsByKey[key];
609
+ const schema = currentNs !== void 0 ? ctx.schemas[currentNs] : void 0;
610
+ if (currentNs === void 0 || schema === void 0) {
611
+ rewritten[key] = value;
612
+ continue;
613
+ }
614
+ rewritten[key] = decodeByShapeFromDef(value, returns, schema, raw.shapes[key], {
615
+ schemas: ctx.schemas,
616
+ currentNs
617
+ });
618
+ continue;
619
+ }
620
+ const fields = ctx.fieldsByKey[key];
621
+ const typeName = ctx.typeByKey[key];
622
+ const currentNs = ctx.currentNsByKey[key];
623
+ if (fields === void 0 || typeName === void 0 || currentNs === void 0) {
624
+ rewritten[key] = value;
625
+ continue;
626
+ }
627
+ const schema = ctx.schemas[currentNs];
628
+ if (schema === void 0) {
629
+ rewritten[key] = value;
630
+ continue;
631
+ }
632
+ const rawShape = raw.shapes[key];
633
+ rewritten[key] = decodeByShape(value, fields, schema, typeName, Array.isArray(rawShape) || isAggShape(rawShape) ? void 0 : rawShape, {
634
+ schemas: ctx.schemas,
635
+ currentNs
636
+ });
637
+ }
638
+ const out = {
639
+ schemaVersion: raw.schemaVersion,
640
+ data: rewritten,
641
+ shapes: raw.shapes
642
+ };
643
+ if (raw._meta !== void 0) out._meta = raw._meta;
644
+ if (raw._pagination !== void 0) out._pagination = raw._pagination;
645
+ if (raw._completeness !== void 0) out._completeness = raw._completeness;
646
+ if (raw._diagnostics !== void 0) out._diagnostics = raw._diagnostics;
647
+ if (raw.errors !== void 0) out.errors = raw.errors;
648
+ return out;
649
+ }
650
+ function decodeByShape(value, fields, schema, typeName, shape, ctx) {
651
+ if (value === null || value === void 0) return null;
652
+ const plan = getRowPlan(fields, resolveFieldMap(schema, typeName, [typeName]));
653
+ if (shape === "list") {
654
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list shape", [typeName]);
655
+ return value.map((elem) => decodeRowWithPlan(elem, plan, schema, [typeName], ctx));
656
+ }
657
+ return decodeRowWithPlan(value, plan, schema, [typeName], ctx);
658
+ }
659
+ function decodeByShapeFromDef(value, def, schema, shape, ctx) {
660
+ if (value === null || value === void 0) return null;
661
+ if (Array.isArray(shape)) {
662
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for batched shape", []);
663
+ return value.map((elem, idx) => decodeByShapeFromDef(elem, frameDef(def, idx), schema, shape[idx], ctx));
664
+ }
665
+ const one = frameDef(def, 0);
666
+ if (shape === "list" && one.kind !== "list") {
667
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list shape", []);
668
+ return value.map((elem, idx) => decodePositionalFromFieldDef(elem, one, schema, ctx, [`[${idx}]`]));
669
+ }
670
+ return decodePositionalFromFieldDef(value, one, schema, ctx);
671
+ }
672
+ function resolveFieldMap(schema, typeName, path) {
673
+ return resolveFieldMap$1(schema, typeName, path, (message, p) => new PackDecodeError(message, p));
674
+ }
675
+ /**
676
+ * Decide whether `value` is a single tuple or a list of tuples based on its
677
+ * shape plus the FieldInput — used only by the top-level `decodePositional`
678
+ * helper (the envelope decoder uses `shapes[key]` directly). Heuristic:
679
+ * - null → null
680
+ * - Array where the first element is itself an array → list of rows
681
+ * - Array otherwise → single row (tuple)
682
+ *
683
+ * This heuristic is the ambiguity §7.2 calls out, so callers SHOULD go through
684
+ * `decodeEnvelope` to use explicit shape metadata.
685
+ */
686
+ function decodeValueByArity(value, fields, fieldMap, schema, path, ctx) {
687
+ if (value === null || value === void 0) return null;
688
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array (tuple) for positional row", path);
689
+ const plan = getRowPlan(fields, fieldMap);
690
+ if (value.length > 0 && Array.isArray(value[0])) return value.map((elem) => decodeRowWithPlan(elem, plan, schema, path, ctx));
691
+ return decodeRowWithPlan(value, plan, schema, path, ctx);
692
+ }
693
+ const DECODE_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
694
+ function getRowPlan(fields, fieldMap) {
695
+ return getRowPlan$1(DECODE_PLAN_CACHE, fields, fieldMap);
696
+ }
697
+ function decodeRowWithPlan(tuple, plan, schema, path, ctx) {
698
+ if (tuple === null || tuple === void 0) return null;
699
+ if (!Array.isArray(tuple)) throw new PackDecodeError("expected array (tuple) for row", path);
700
+ const out = {};
701
+ const len = plan.length;
702
+ for (let i = 0; i < len; i++) {
703
+ const entry = plan[i];
704
+ const field = entry[0];
705
+ const selection = entry[1];
706
+ const def = entry[2];
707
+ const cell = tuple[i] ?? null;
708
+ const slot = entry[3];
709
+ if (slot?.kind === "truncated" && cell === null) continue;
710
+ path.push(field);
711
+ out[field] = slot === void 0 ? decodeField(cell, selection, def, schema, path, ctx) : decodeWalkSlot(cell, slot, schema, path, ctx);
712
+ path.pop();
713
+ }
714
+ return out;
715
+ }
716
+ function decodeWalkSlot(cell, slot, schema, path, ctx) {
717
+ if (cell === null || cell === void 0) return null;
718
+ switch (slot.kind) {
719
+ case "truncated": return cell;
720
+ case "agg":
721
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for _agg", path);
722
+ return Object.fromEntries(slot.names.map((n, i) => [n, cell[i] ?? null]));
723
+ case "nested": {
724
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for nested selection", path);
725
+ const plan = getRowPlan(slot.fields, resolveFieldMap(schema, slot.type, path));
726
+ return cell.map((tuple, idx) => {
727
+ path.push(`[${idx}]`);
728
+ const out = decodeRowWithPlan(tuple, plan, schema, path, ctx);
729
+ path.pop();
730
+ return out;
731
+ });
732
+ }
733
+ default: return assertNever(slot);
734
+ }
735
+ }
736
+ function decodeField(cell, selection, def, schema, path, ctx) {
737
+ if (cell === null || cell === void 0) return null;
738
+ if (def === void 0) return cell;
739
+ if (selection === true) return decodeLeaf(cell, def, path);
740
+ switch (def.kind) {
741
+ case "scalar": throw new PackDecodeError(`field is a scalar (${def.type}); cannot select sub-fields`, path);
742
+ case "struct": return decodeStruct(cell, selection, def, schema, path, ctx);
743
+ case "list": return decodeList(cell, selection, def, schema, path, ctx);
744
+ case "crossRef": return decodeCrossRef(cell, selection, def, schema, path, ctx);
745
+ default: return assertNever(def);
746
+ }
747
+ }
748
+ function decodeLeaf(cell, def, path) {
749
+ switch (def.kind) {
750
+ case "scalar": return cell;
751
+ case "list":
752
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list leaf", path);
753
+ return cell;
754
+ case "struct":
755
+ case "crossRef": return cell;
756
+ default: return assertNever(def);
757
+ }
758
+ }
759
+ function decodeStruct(cell, selection, def, schema, path, ctx) {
760
+ return decodeRowWithPlan(cell, getRowPlan(selection, def.fields), schema, path, ctx);
761
+ }
762
+ function decodeList(cell, selection, def, schema, path, ctx) {
763
+ if (!Array.isArray(cell)) throw new PackDecodeError("expected array for list field", path);
764
+ const inner = def.of;
765
+ const innerPlan = inner.kind === "struct" ? getRowPlan(selection, inner.fields) : void 0;
766
+ const out = [];
767
+ for (let idx = 0; idx < cell.length; idx++) {
768
+ const elem = cell[idx];
769
+ if (elem === null || elem === void 0) {
770
+ out.push(null);
771
+ continue;
772
+ }
773
+ path.push(`[${idx}]`);
774
+ out.push(decodeListElement(elem, selection, inner, schema, path, ctx, innerPlan));
775
+ path.pop();
776
+ }
777
+ return out;
778
+ }
779
+ function decodeListElement(elem, selection, inner, schema, elemPath, ctx, structPlan) {
780
+ switch (inner.kind) {
781
+ case "scalar": throw new PackDecodeError(`list element is scalar (${inner.type}); cannot select sub-fields`, elemPath);
782
+ case "struct": return decodeRowWithPlan(elem, structPlan ?? getRowPlan(selection, inner.fields), schema, elemPath, ctx);
783
+ case "list": return decodeList(elem, selection, inner, schema, elemPath, ctx);
784
+ case "crossRef": return decodeCrossRef(elem, selection, inner, schema, elemPath, ctx);
785
+ default: return assertNever(inner);
786
+ }
787
+ }
788
+ function decodeCrossRef(cell, selection, def, schema, path, ctx) {
789
+ if (def.ns === ctx.currentNs) return decodeRowWithPlan(cell, getRowPlan(selection, resolveFieldMap(schema, def.type, path)), schema, path, ctx);
790
+ const schemas = ctx.schemas;
791
+ if (schemas === void 0) throw new PackDecodeError(`cross-namespace crossRef '${def.ns}/${def.type}' requires ctx.schemas`, path);
792
+ const targetSchema = schemas[def.ns];
793
+ if (targetSchema === void 0) throw new PackDecodeError(`cross-namespace crossRef target namespace '${def.ns}' not in ctx.schemas`, path);
794
+ return decodeRowWithPlan(cell, getRowPlan(selection, resolveFieldMap(targetSchema, def.type, path)), targetSchema, path, {
795
+ ...ctx,
796
+ currentNs: def.ns
797
+ });
798
+ }
799
+ function decodeFieldDef(value, def, schema, path, ctx) {
800
+ if (value === null || value === void 0) return null;
801
+ switch (def.kind) {
802
+ case "scalar": return value;
803
+ case "struct": return decodeStructFromDef(value, def, schema, path, ctx);
804
+ case "list": return decodeListFromDef(value, def, schema, path, ctx);
805
+ case "crossRef": return value;
806
+ default: return assertNever(def);
807
+ }
808
+ }
809
+ const DECODE_FIELDDEF_PLAN_CACHE = /* @__PURE__ */ new WeakMap();
810
+ function getFieldDefPlan(fields) {
811
+ return getFieldDefPlan$1(DECODE_FIELDDEF_PLAN_CACHE, fields);
812
+ }
813
+ function decodeStructFromDef(value, def, schema, path, ctx) {
814
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array (tuple) for struct", path);
815
+ const out = {};
816
+ const plan = getFieldDefPlan(def.fields);
817
+ const len = plan.length;
818
+ for (let i = 0; i < len; i++) {
819
+ const entry = plan[i];
820
+ const fieldName = entry[0];
821
+ const sub = entry[1];
822
+ const cell = value[i] ?? null;
823
+ path.push(fieldName);
824
+ out[fieldName] = decodeFieldDef(cell, sub, schema, path, ctx);
825
+ path.pop();
826
+ }
827
+ return out;
828
+ }
829
+ function decodeListFromDef(value, def, schema, path, ctx) {
830
+ if (!Array.isArray(value)) throw new PackDecodeError("expected array for list field", path);
831
+ const out = [];
832
+ for (let idx = 0; idx < value.length; idx++) {
833
+ const elem = value[idx];
834
+ if (elem === null || elem === void 0) {
835
+ out.push(null);
836
+ continue;
837
+ }
838
+ path.push(`[${idx}]`);
839
+ out.push(decodeFieldDef(elem, def.of, schema, path, ctx));
840
+ path.pop();
841
+ }
842
+ return out;
843
+ }
844
+
845
+ //#endregion
846
+ //#region ../../packages/substrate-pack/src/mutation-returns.ts
847
+ /** What a row-writing mutation answers when the frame names no `fields`. */
848
+ const MUTATION_ACK_FIELDS = {
849
+ id: true,
850
+ shortId: true
851
+ };
852
+ /** The `returns` a mutation's result is positioned by, given the frame's `fields` (`true` selects everything). */
853
+ function mutationReturns(mutation, fields) {
854
+ if (fields === true) return mutation.returns;
855
+ const selection = fields ?? (mutation.writesRows === true ? MUTATION_ACK_FIELDS : void 0);
856
+ return selection === void 0 ? mutation.returns : narrow(mutation.returns, selection);
857
+ }
858
+ /**
859
+ * `def` narrowed to the selection, in declared order: a list narrows its
860
+ * element, and a nested selection narrows a nested struct, as the JSON
861
+ * projection recurses. A selected field the struct does not declare is
862
+ * dropped, as the JSON projection drops a field the row does not carry.
863
+ */
864
+ function narrow(def, selection) {
865
+ if (def.kind === "list") return {
866
+ ...def,
867
+ of: narrow(def.of, selection)
868
+ };
869
+ if (def.kind !== "struct") return def;
870
+ const fields = {};
871
+ for (const [name, field] of Object.entries(def.fields)) {
872
+ const sub = selection[name];
873
+ if (sub === void 0) continue;
874
+ fields[name] = typeof sub === "object" && sub !== null ? narrow(field, sub) : field;
875
+ }
876
+ return {
877
+ ...def,
878
+ fields
879
+ };
880
+ }
881
+
882
+ //#endregion
883
+ //#region ../../packages/substrate-pack/src/wire.ts
884
+ /**
885
+ * Frame wire codec. Spec §8.5.
886
+ *
887
+ * Centralizes JSON-vs-pack envelope handling for frame streams plus the
888
+ * precomputed decode plan that turns positional `data` tuples back into named
889
+ * objects. The plan is built once per subscription, so per-frame work is
890
+ * O(plan entries). Shared by substrate-client and the perf harness so both
891
+ * measure the same codepath.
892
+ */
893
+ /**
894
+ * Decode an inbound frame envelope (the outer `{ id, kind, data?, ... }`
895
+ * shape — positional `data` reconstruction is a separate concern handled by
896
+ * `applyDecodePlanInPlace`).
897
+ *
898
+ * The `mode` discriminant determines how `raw` is interpreted: pack-mode
899
+ * messages arrive as `ArrayBuffer | Uint8Array | Buffer` and are msgpack-
900
+ * decoded; JSON-mode messages arrive as `string` (or, when node-ws hands the
901
+ * payload across as binary, as bytes that we coerce back to text before
902
+ * `JSON.parse`).
903
+ *
904
+ * The runtime narrowing is centralized here so callers don't reach for
905
+ * `raw as string` casts at every call site.
906
+ */
907
+ function decodeWsEnvelope(raw, mode) {
908
+ if (mode === "pack") {
909
+ inbound ??= createUnpackr({
910
+ structuredClone: false,
911
+ mapsAsObjects: true
912
+ });
913
+ return inbound.unpack(toBytes(raw));
914
+ }
915
+ if (typeof raw === "string") return JSON.parse(raw);
916
+ return JSON.parse(new TextDecoder().decode(toBytes(raw)));
917
+ }
918
+ /**
919
+ * Inbound frames come from untrusted peers: structured-clone references (and
920
+ * so cyclic values) are refused. `mapsAsObjects` keeps the default `unpack`'s
921
+ * plain-object maps. msgpackr's other built-in extensions are process-global
922
+ * and still decode, so a server checks a request with `isPlainRequestData`.
923
+ */
924
+ let inbound;
925
+ function toBytes(raw) {
926
+ if (raw instanceof Uint8Array) return raw;
927
+ if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
928
+ return new Uint8Array(raw);
929
+ }
930
+ /**
931
+ * Build the decode plan from a frame spec map + federated schemas. Called
932
+ * once per subscription, before the first frame arrives. Keys that are
933
+ * unqualified, have no matching schema, or have no field selection are
934
+ * skipped.
935
+ */
936
+ function buildDecodePlan(frameSpec, schemas) {
937
+ const plan = [];
938
+ for (const qkey of Object.keys(frameSpec)) {
939
+ const parsed = parseQualifiedKey(qkey);
940
+ if (parsed === null) continue;
941
+ const { ns, name } = parsed;
942
+ const schema = schemas[ns];
943
+ if (schema === void 0) continue;
944
+ const spec = frameSpec[qkey];
945
+ if (spec === void 0) continue;
946
+ const fields = spec.fields;
947
+ if (fields === void 0) continue;
948
+ plan.push({
949
+ qkey,
950
+ name,
951
+ schema,
952
+ fields,
953
+ opts: {
954
+ schemas,
955
+ currentNs: ns
956
+ }
957
+ });
958
+ }
959
+ return plan;
960
+ }
961
+ /**
962
+ * Apply a precomputed decode plan to an envelope's `data` map in place.
963
+ * Mutates `envelope.data[qkey]` from positional tuple to named object/list
964
+ * for each plan entry whose qkey is present.
965
+ *
966
+ * Accepts `unknown` so both `WsResponseFrame` and the data-bearing
967
+ * `SubscribeEvent` variants flow through without a parameter-type cast at the
968
+ * call site; remove/end/error frames lack a `data` property and short-circuit
969
+ * here.
970
+ */
971
+ function applyDecodePlanInPlace(envelope, plan) {
972
+ if (envelope === null || typeof envelope !== "object") return;
973
+ const data = envelope.data;
974
+ if (data === null || data === void 0 || typeof data !== "object") return;
975
+ const map = data;
976
+ for (const entry of plan) {
977
+ const value = map[entry.qkey];
978
+ if (value === void 0) continue;
979
+ map[entry.qkey] = decodePositional(value, entry.fields, entry.schema, entry.name, entry.opts);
980
+ }
981
+ }
982
+
983
+ //#endregion
984
+ //#region ../../packages/substrate-pack/src/stream-frames.ts
985
+ const FRAMES_JSON_MIME = "application/vnd.substrate.frames+json";
986
+ const FRAMES_PACK_MIME = "application/vnd.substrate.frames+pack";
987
+ /** Largest payload a decoder accepts unless told otherwise. */
988
+ const DEFAULT_MAX_FRAME_BYTES = 16777216;
989
+ var FrameStreamError = class extends Error {
990
+ code;
991
+ constructor(code, message) {
992
+ super(message);
993
+ this.name = "FrameStreamError";
994
+ this.code = code;
995
+ }
996
+ };
997
+ /** A little over three of the server's 20 s heartbeats. */
998
+ const DEFAULT_STREAM_IDLE_MS = 65e3;
999
+ /**
1000
+ * `body`, failing with `stream_idle` when a read waits `ms` for bytes,
1001
+ * heartbeats included. It times only reads the consumer is waiting on, so a
1002
+ * slow consumer never trips it; a connection that died without closing does.
1003
+ * The underlying reader is cancelled on timeout, which settles its pending read.
1004
+ */
1005
+ function withIdleTimeout(body, ms) {
1006
+ const reader = body.getReader();
1007
+ return new ReadableStream({
1008
+ async pull(controller) {
1009
+ let timer;
1010
+ const idle = new Promise((_, reject) => {
1011
+ timer = setTimeout(() => reject(new FrameStreamError("stream_idle", `the stream sent nothing for ${ms} ms`)), ms);
1012
+ });
1013
+ try {
1014
+ const r = await Promise.race([reader.read(), idle]);
1015
+ if (r.done) controller.close();
1016
+ else controller.enqueue(r.value);
1017
+ } catch (err) {
1018
+ reader.cancel().catch(() => {});
1019
+ controller.error(err);
1020
+ } finally {
1021
+ clearTimeout(timer);
1022
+ }
1023
+ },
1024
+ cancel(reason) {
1025
+ return reader.cancel(reason);
1026
+ }
1027
+ }, { highWaterMark: 0 });
1028
+ }
1029
+ const utf8 = new TextEncoder();
1030
+ /**
1031
+ * The payloads of a frame stream, in order, heartbeats skipped. A length above
1032
+ * `maxFrameBytes` throws `frame_too_large` before any of that payload is read
1033
+ * or allocated; a body that ends inside a frame throws `truncated_frame`.
1034
+ */
1035
+ async function* decodeStreamFrames(body, opts = {}) {
1036
+ const max = opts.maxFrameBytes ?? 16777216;
1037
+ if (!Number.isInteger(max) || max < 0) throw new RangeError(`maxFrameBytes must be a non-negative integer, got ${max}`);
1038
+ let buf = /* @__PURE__ */ new Uint8Array(4096);
1039
+ let start = 0;
1040
+ let end = 0;
1041
+ const append = (chunk) => {
1042
+ if (end + chunk.length > buf.length) {
1043
+ const live = end - start;
1044
+ if (live + chunk.length > buf.length) {
1045
+ const grown = new Uint8Array(Math.max(buf.length * 2, live + chunk.length));
1046
+ grown.set(buf.subarray(start, end), 0);
1047
+ buf = grown;
1048
+ } else buf.copyWithin(0, start, end);
1049
+ start = 0;
1050
+ end = live;
1051
+ }
1052
+ buf.set(chunk, end);
1053
+ end += chunk.length;
1054
+ };
1055
+ const source = typeof body[Symbol.asyncIterator] === "function" ? body : readableToIterable(body);
1056
+ for await (const chunk of source) {
1057
+ append(chunk);
1058
+ while (end - start >= 4) {
1059
+ const len = new DataView(buf.buffer, buf.byteOffset + start, 4).getUint32(0, false);
1060
+ if (len > max) throw new FrameStreamError("frame_too_large", `frame of ${len} bytes exceeds the ${max}-byte limit`);
1061
+ if (end - start < 4 + len) break;
1062
+ if (len > 0) yield buf.slice(start + 4, start + 4 + len);
1063
+ start += 4 + len;
1064
+ }
1065
+ }
1066
+ if (end - start > 0) throw new FrameStreamError("truncated_frame", `stream ended inside a frame (${end - start} bytes left over)`);
1067
+ }
1068
+ /** A ReadableStream without async iteration (Safari), cancelled when the consumer stops early. */
1069
+ async function* readableToIterable(stream) {
1070
+ const reader = stream.getReader();
1071
+ let finished = false;
1072
+ try {
1073
+ for (;;) {
1074
+ const { done, value } = await reader.read();
1075
+ if (done) {
1076
+ finished = true;
1077
+ return;
1078
+ }
1079
+ yield value;
1080
+ }
1081
+ } finally {
1082
+ if (!finished) await reader.cancel().catch(() => {});
1083
+ reader.releaseLock();
1084
+ }
1085
+ }
1086
+
1087
+ //#endregion
1088
+ //#region ../../packages/substrate-client/src/admin/api.ts
1089
+ function createAdminApi(t) {
1090
+ return {
1091
+ ...createSurgeryApi(t),
1092
+ async keys(opts = {}) {
1093
+ const out = [];
1094
+ let cursor;
1095
+ for (;;) {
1096
+ const q = new URLSearchParams();
1097
+ if (opts.filter === "all") q.set("filter", "all");
1098
+ if (cursor !== void 0) q.set("cursor", cursor);
1099
+ const qs = q.toString() === "" ? "" : `?${q.toString()}`;
1100
+ const page = await (await t.raw(`/substrate/v1/_system/keys${qs}`, {
1101
+ method: "GET",
1102
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1103
+ })).json();
1104
+ out.push(...page.keys);
1105
+ if (page.hasMore !== true) return out;
1106
+ if (typeof page.nextCursor !== "string") throw new Error("server reported hasMore with no nextCursor — refusing to report a partial key table as complete");
1107
+ cursor = page.nextCursor;
1108
+ }
1109
+ },
1110
+ async update(change, opts = {}) {
1111
+ const body = {
1112
+ kid: change.kid,
1113
+ namespaces: [...change.namespaces],
1114
+ capabilities: [...change.capabilities]
1115
+ };
1116
+ if (change.widen === true) body.widen = true;
1117
+ if (change.allowAdmin === true) body.allowAdmin = true;
1118
+ if (change.allowUnknownNs === true) body.allowUnknownNs = true;
1119
+ return await (await t.raw("/substrate/v1/_system/keys", {
1120
+ method: "PATCH",
1121
+ body,
1122
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1123
+ })).json();
1124
+ },
1125
+ async revoke(kid, opts = {}) {
1126
+ return await (await t.raw("/substrate/v1/_system/keys", {
1127
+ method: "PATCH",
1128
+ body: {
1129
+ kid,
1130
+ revoke: true
1131
+ },
1132
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1133
+ })).json();
1134
+ },
1135
+ async register(input, opts = {}) {
1136
+ const body = {
1137
+ kid: input.kid,
1138
+ publicKey: input.publicKey,
1139
+ algorithm: input.algorithm,
1140
+ namespaces: [...input.namespaces],
1141
+ capabilities: [...input.capabilities]
1142
+ };
1143
+ if (input.name !== void 0) body.name = input.name;
1144
+ if (input.directory !== void 0) body.directory = { create: input.directory };
1145
+ if (input.allowAdmin === true) body.allowAdmin = true;
1146
+ if (input.allowUnknownNs === true) body.allowUnknownNs = true;
1147
+ return await (await t.raw("/substrate/v1/_system/keys", {
1148
+ method: "POST",
1149
+ body,
1150
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1151
+ })).json();
1152
+ },
1153
+ async invite(input, opts = {}) {
1154
+ const body = {
1155
+ namespaces: [...input.namespaces],
1156
+ capabilities: [...input.capabilities]
1157
+ };
1158
+ if (input.ttlMs !== void 0) body.ttlMs = input.ttlMs;
1159
+ return await (await t.raw("/substrate/v1/_system/invites", {
1160
+ method: "POST",
1161
+ body,
1162
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1163
+ })).json();
1164
+ }
1165
+ };
1166
+ }
1167
+
1168
+ //#endregion
1169
+ //#region ../../packages/substrate-client/src/errors.ts
1170
+ var NetworkError = class extends Error {
1171
+ cause;
1172
+ name = "NetworkError";
1173
+ /** HTTP status of the response, when the failure was one. */
1174
+ status;
1175
+ /** The server's JSON error `code`, when its body carried one. */
1176
+ code;
1177
+ /** The server's JSON `error` text, when its body carried one. */
1178
+ serverMessage;
1179
+ /** The refusal's parsed JSON object, verbatim. */
1180
+ body;
1181
+ constructor(message, cause, info = {}) {
1182
+ super(message);
1183
+ this.cause = cause;
1184
+ if (info.status !== void 0) this.status = info.status;
1185
+ if (info.code !== void 0) this.code = info.code;
1186
+ if (info.serverMessage !== void 0) this.serverMessage = info.serverMessage;
1187
+ if (info.body !== void 0) this.body = info.body;
1188
+ }
1189
+ };
1190
+ /**
1191
+ * Thrown on Substrate auth failures — 401 (unauthenticated) or 403 (authenticated but
1192
+ * not authorised). Proxy-level failures (407, 511) fall through to NetworkError.
1193
+ */
1194
+ var AuthError = class extends Error {
1195
+ status;
1196
+ name = "AuthError";
1197
+ /** The server's JSON error `code`, when its body carried one: the auth gate says `forbidden`. */
1198
+ code;
1199
+ /** The server's JSON `error` or `message` text, when its body carried one. */
1200
+ serverMessage;
1201
+ /** The refusal's parsed JSON object, verbatim. */
1202
+ body;
1203
+ constructor(message, status, info = {}) {
1204
+ super(message);
1205
+ this.status = status;
1206
+ if (info.code !== void 0) this.code = info.code;
1207
+ if (info.serverMessage !== void 0) this.serverMessage = info.serverMessage;
1208
+ if (info.body !== void 0) this.body = info.body;
1209
+ }
1210
+ };
1211
+ var SubscribeError = class extends Error {
1212
+ code;
1213
+ name = "SubscribeError";
1214
+ constructor(message, code) {
1215
+ super(message);
1216
+ this.code = code;
1217
+ }
1218
+ };
1219
+
1220
+ //#endregion
1221
+ //#region ../../packages/substrate-client/src/subscribe-rows.ts
1222
+ /**
1223
+ * Pure subscribe-event → typed-row-set fold, shared by `SubstrateClient.watch` and
1224
+ * the cache store.
1225
+ *
1226
+ * The `data` envelope shape per event kind:
1227
+ * - snapshot : data = { '<ns>/<Type>': Row[] } — the full current set
1228
+ * - add : data = { '<ns>/<Type>': Row } — one newly-matching row
1229
+ * - update : data = { '<ns>/<Type>': Row } — one changed row (by id)
1230
+ * - remove : { removedId: string } — no data envelope
1231
+ * - end / error / chunk : no row change (terminal / streaming kinds)
1232
+ *
1233
+ * Rows are correlated by their `id` field (string-coerced), so any frame fed to
1234
+ * the fold must select `id` — `SubstrateClient.watch` injects it via
1235
+ * `augmentFramesWithId`. `add` appends (no de-dup) and ignores the query's
1236
+ * `orderBy`.
1237
+ */
1238
+ function rowSlot(data, qualifiedKey) {
1239
+ if (data === null || typeof data !== "object") return void 0;
1240
+ return data[qualifiedKey];
1241
+ }
1242
+ function rowId(row) {
1243
+ return String(row.id);
1244
+ }
1245
+ /**
1246
+ * Fold one subscribe event into `current`, returning the next row list. Pure:
1247
+ * the caller owns terminal-kind delivery and the "select id" contract.
1248
+ *
1249
+ * Returns the SAME array reference when the event does not change the set (an
1250
+ * `update` whose row carries no `id`, or a non-row kind), so callers can cheaply
1251
+ * skip redundant writes / yields by identity.
1252
+ */
1253
+ function reduceSubscribeRows(current, qualifiedKey, event) {
1254
+ switch (event.kind) {
1255
+ case "snapshot": {
1256
+ const slot = rowSlot(event.data, qualifiedKey);
1257
+ if (Array.isArray(slot)) return [...slot];
1258
+ return slot === void 0 || slot === null ? [] : [slot];
1259
+ }
1260
+ case "add": return [...current, rowSlot(event.data, qualifiedKey)];
1261
+ case "update": {
1262
+ const row = rowSlot(event.data, qualifiedKey);
1263
+ if (row === void 0 || row.id === void 0) return current;
1264
+ const targetId = String(row.id);
1265
+ return current.map((r) => rowId(r) === targetId ? row : r);
1266
+ }
1267
+ case "remove": return current.filter((r) => rowId(r) !== String(event.removedId));
1268
+ default: return current;
1269
+ }
1270
+ }
1271
+ /** End reasons after which the transport resubscribes rather than finishing. */
1272
+ const SURVIVABLE_END_REASONS = /* @__PURE__ */ new Set([
1273
+ "server_restart",
1274
+ "credential_expired",
1275
+ "credential_changed"
1276
+ ]);
1277
+ /**
1278
+ * Fold a single-key subscription's event stream into a live row-set: yields the
1279
+ * current `T[]` after every snapshot / add / update / remove. Completes on `end`
1280
+ * (or when the source iterator completes); throws `SubscribeError` on an `error`
1281
+ * event — matching the raw `subscribe` contract, where the transport throws on
1282
+ * error frames.
1283
+ *
1284
+ * A delta that does not change the set (e.g. an `update` whose row has no id) is
1285
+ * not re-yielded. Cancellation: breaking the consuming `for await` (or calling
1286
+ * `.return()`) propagates to the source iterable's `return()` through the inner
1287
+ * `for await`, cancelling the underlying subscription.
1288
+ */
1289
+ async function* watchRows(events, qualifiedKey) {
1290
+ let rows = [];
1291
+ for await (const event of events) {
1292
+ if (event.kind === "end" && !SURVIVABLE_END_REASONS.has(event.reason ?? "")) return;
1293
+ if (event.kind === "end") continue;
1294
+ if (event.kind === "error") {
1295
+ const first = event.errors[0];
1296
+ throw new SubscribeError(first?.message ?? "subscribe error", first?.code ?? "unknown");
1297
+ }
1298
+ const next = reduceSubscribeRows(rows, qualifiedKey, event);
1299
+ if (next === rows) continue;
1300
+ rows = next;
1301
+ yield rows;
1302
+ }
1303
+ }
1304
+
1305
+ //#endregion
1306
+ //#region ../../packages/substrate-client/src/cache/store.ts
1307
+ /**
1308
+ * Signals-backed reactive cache. Keyed by canonicalised frame key (same shape
1309
+ * as `canonicaliseFrameKey`). Each entry holds signals for `data`, `loading`,
1310
+ * `error`, plus refCount + invalidatedAt for lifecycle and drift management.
1311
+ *
1312
+ * Lifecycle:
1313
+ * - subscribe(key) → increment refCount, return an unsubscribe that decrements.
1314
+ * - When refCount → 0, schedule GC after `idleGcMs`; cancel if a new subscribe
1315
+ * arrives in that window.
1316
+ * - invalidate(keyPrefix): if any entry under that prefix has refCount > 0,
1317
+ * stamp `invalidatedAt` (callers observe and re-fetch). Entries with
1318
+ * refCount === 0 are dropped.
1319
+ */
1320
+ var CacheStore = class {
1321
+ #entries = /* @__PURE__ */ new Map();
1322
+ #idleGcMs;
1323
+ constructor(opts) {
1324
+ this.#idleGcMs = opts.idleGcMs;
1325
+ }
1326
+ get(key) {
1327
+ const existing = this.#entries.get(key);
1328
+ if (existing !== void 0) return existing;
1329
+ const entry = {
1330
+ data: signal(void 0),
1331
+ loading: signal(false),
1332
+ error: signal(null),
1333
+ diagnostics: signal([]),
1334
+ invalidatedSignal: signal(0),
1335
+ refCount: 0,
1336
+ invalidatedAt: null,
1337
+ lastFetched: 0,
1338
+ gcTimer: null
1339
+ };
1340
+ this.#entries.set(key, entry);
1341
+ return entry;
1342
+ }
1343
+ peek(key) {
1344
+ return this.#entries.get(key);
1345
+ }
1346
+ subscribe(key) {
1347
+ const entry = this.get(key);
1348
+ entry.refCount += 1;
1349
+ if (entry.gcTimer !== null) {
1350
+ clearTimeout(entry.gcTimer);
1351
+ entry.gcTimer = null;
1352
+ }
1353
+ let unsubscribed = false;
1354
+ return () => {
1355
+ if (unsubscribed) return;
1356
+ unsubscribed = true;
1357
+ entry.refCount -= 1;
1358
+ if (entry.refCount === 0) this.#scheduleGc(key, entry);
1359
+ };
1360
+ }
1361
+ set(key, data, diagnostics = []) {
1362
+ const entry = this.get(key);
1363
+ entry.data.value = data;
1364
+ entry.loading.value = false;
1365
+ entry.error.value = null;
1366
+ if (diagnostics.length > 0 || entry.diagnostics.value.length > 0) entry.diagnostics.value = diagnostics;
1367
+ entry.invalidatedAt = null;
1368
+ entry.invalidatedSignal.value = 0;
1369
+ entry.lastFetched = Date.now();
1370
+ }
1371
+ setLoading(key, loading) {
1372
+ const entry = this.get(key);
1373
+ entry.loading.value = loading;
1374
+ }
1375
+ setError(key, err) {
1376
+ const entry = this.get(key);
1377
+ entry.error.value = err;
1378
+ entry.loading.value = false;
1379
+ }
1380
+ invalidate(keyPrefix) {
1381
+ const now = Date.now();
1382
+ for (const [key, entry] of this.#entries) {
1383
+ if (!key.startsWith(keyPrefix)) continue;
1384
+ if (entry.refCount > 0) {
1385
+ entry.invalidatedAt = now;
1386
+ entry.invalidatedSignal.value = now;
1387
+ } else {
1388
+ if (entry.gcTimer !== null) clearTimeout(entry.gcTimer);
1389
+ this.#entries.delete(key);
1390
+ }
1391
+ }
1392
+ }
1393
+ /**
1394
+ * Apply a subscribe event to the entry at `cacheKey`, patching the row slot
1395
+ * under `qualifiedKey` in the entry's `data` envelope.
1396
+ *
1397
+ * - snapshot → replace the entire envelope via `set()`
1398
+ * - add → append the single row to the list at data[qualifiedKey]
1399
+ * - update → replace row by id in the list at data[qualifiedKey]
1400
+ * - remove → drop row by removedId from the list at data[qualifiedKey]
1401
+ * - end / error / chunk → no cache change (the hook surfaces these)
1402
+ *
1403
+ * `update` / `remove` on an entry without data are no-ops — the server always
1404
+ * emits `snapshot` first.
1405
+ */
1406
+ applySubscribeEvent(cacheKey, qualifiedKey, event) {
1407
+ if (event.kind === "snapshot") {
1408
+ this.set(cacheKey, event.data);
1409
+ return;
1410
+ }
1411
+ if (event.kind !== "add" && event.kind !== "update" && event.kind !== "remove") return;
1412
+ const entry = this.get(cacheKey);
1413
+ const current = entry.data.value;
1414
+ if (event.kind !== "add" && (current === void 0 || !Array.isArray(current[qualifiedKey]))) return;
1415
+ const list = Array.isArray(current?.[qualifiedKey]) ? current[qualifiedKey] : [];
1416
+ const next = reduceSubscribeRows(list, qualifiedKey, event);
1417
+ if (next === list) return;
1418
+ entry.data.value = {
1419
+ ...current ?? {},
1420
+ [qualifiedKey]: next
1421
+ };
1422
+ }
1423
+ #scheduleGc(key, entry) {
1424
+ if (entry.gcTimer !== null) clearTimeout(entry.gcTimer);
1425
+ entry.gcTimer = setTimeout(() => {
1426
+ entry.gcTimer = null;
1427
+ if (entry.refCount === 0) this.#entries.delete(key);
1428
+ }, this.#idleGcMs);
1429
+ }
1430
+ };
1431
+
1432
+ //#endregion
1433
+ //#region ../../packages/substrate-client/src/diagnostics.ts
1434
+ const HANDLED = /* @__PURE__ */ new Set([
1435
+ "unknownProjectionFields",
1436
+ "filterValidationSkipped",
1437
+ "plan"
1438
+ ]);
1439
+ /**
1440
+ * Reduce one envelope entry to a diagnostic, or `undefined` when it holds
1441
+ * nothing worth reporting — an entry present but empty, or one whose only
1442
+ * unknown-field list is empty. Without that, the default sink emits a warning
1443
+ * naming no observation at all.
1444
+ */
1445
+ function describeEntry(opKey, entry) {
1446
+ const unknownProjectionFields = [...entry.unknownProjectionFields ?? []];
1447
+ const { filterValidationSkipped } = entry;
1448
+ const unrecognizedKeys = Object.keys(entry).filter((k) => !HANDLED.has(k) && entry[k] !== void 0).sort();
1449
+ if (unknownProjectionFields.length === 0 && filterValidationSkipped === void 0 && unrecognizedKeys.length === 0) return;
1450
+ const diagnostic = {
1451
+ opKey,
1452
+ unknownProjectionFields
1453
+ };
1454
+ if (filterValidationSkipped !== void 0) diagnostic.filterValidationSkipped = filterValidationSkipped;
1455
+ if (unrecognizedKeys.length > 0) diagnostic.unrecognizedKeys = unrecognizedKeys;
1456
+ return diagnostic;
1457
+ }
1458
+ /**
1459
+ * Extract diagnostics from a decoded envelope and hand each one to `sink`.
1460
+ * Returns the flattened list so callers can also attach it to a mapped result.
1461
+ *
1462
+ * An envelope with no `_diagnostics` returns `[]` without the sink firing.
1463
+ */
1464
+ function collectDiagnostics(envDiagnostics, sink) {
1465
+ if (envDiagnostics === void 0) return [];
1466
+ const out = [];
1467
+ for (const [opKey, entry] of Object.entries(envDiagnostics)) {
1468
+ if (entry === null || entry === void 0) continue;
1469
+ const diagnostic = describeEntry(opKey, entry);
1470
+ if (diagnostic === void 0) continue;
1471
+ out.push(diagnostic);
1472
+ sink?.(diagnostic);
1473
+ }
1474
+ return out;
1475
+ }
1476
+ /**
1477
+ * Default sink: one `console.warn` per distinct observation set, naming the
1478
+ * frame key and everything observed about it, plus the reason the reader should
1479
+ * care in each case.
1480
+ *
1481
+ * ONE warning per diagnostic rather than one per observation. An entry carrying
1482
+ * both an unknown projection and a skipped filter validation describes a single
1483
+ * read, and splitting it reads as two independent defects.
1484
+ *
1485
+ * Deduping state is per-sink, so per-client: `new SubstrateClient(...)` starts
1486
+ * fresh.
1487
+ */
1488
+ function createDefaultDiagnosticsSink() {
1489
+ const seen = /* @__PURE__ */ new Set();
1490
+ return (diagnostic) => {
1491
+ const { opKey, filterValidationSkipped } = diagnostic;
1492
+ const fields = [...diagnostic.unknownProjectionFields].sort();
1493
+ const unrecognized = [...diagnostic.unrecognizedKeys ?? []].sort();
1494
+ const dedupeKey = [
1495
+ opKey,
1496
+ fields.join(","),
1497
+ filterValidationSkipped ?? "",
1498
+ unrecognized.join(",")
1499
+ ].join("\0");
1500
+ if (seen.has(dedupeKey)) return;
1501
+ seen.add(dedupeKey);
1502
+ const parts = [];
1503
+ if (fields.length > 0) parts.push(`projected field(s) the type does not declare: ${fields.join(", ")}. The read succeeded — these are null on EVERY row, which is indistinguishable from a declared field that is always null. Check for a typo, or a substrate that has not restarted with your schema yet.`);
1504
+ if (filterValidationSkipped !== void 0) parts.push(`the where-clause was not schema-validated (${filterValidationSkipped}), so its operators and operands were never checked against the field kinds. Results are still correct — the substrate refuses a predicate it cannot honour — but a malformed filter fails later and less clearly.`);
1505
+ if (unrecognized.length > 0) parts.push(`the substrate reported diagnostic(s) this client cannot read: ${unrecognized.join(", ")}. Upgrade @mnmal-ai/substrate-client to surface them.`);
1506
+ console.warn(`[substrate-client] ${opKey}: ${parts.join(" Also, ")} (Pass \`onDiagnostics\` to SubstrateClient to route this elsewhere.)`);
1507
+ };
1508
+ }
1509
+
1510
+ //#endregion
1511
+ //#region ../../packages/substrate-client/src/reconnect.ts
1512
+ var ReconnectScheduler = class {
1513
+ #base;
1514
+ #max;
1515
+ #jitter;
1516
+ #attempt = 0;
1517
+ constructor(opts) {
1518
+ this.#base = opts.baseDelayMs;
1519
+ this.#max = opts.maxDelayMs;
1520
+ this.#jitter = opts.jitter;
1521
+ }
1522
+ nextDelay() {
1523
+ const raw = Math.min(this.#base * 2 ** this.#attempt, this.#max);
1524
+ this.#attempt += 1;
1525
+ if (this.#jitter === 0) return raw;
1526
+ const spread = raw * this.#jitter;
1527
+ return raw + (Math.random() * 2 - 1) * spread;
1528
+ }
1529
+ reset() {
1530
+ this.#attempt = 0;
1531
+ }
1532
+ /**
1533
+ * Resolve after `nextDelay()` ms. Callers must use this serially — the
1534
+ * `#attempt` counter is shared across calls, so overlapping `schedule()`
1535
+ * invocations will produce incorrect delays. The stream reconnect loop awaits
1536
+ * each `schedule()` before firing the next attempt.
1537
+ */
1538
+ async schedule() {
1539
+ const d = this.nextDelay();
1540
+ await new Promise((resolve) => setTimeout(resolve, d));
1541
+ }
1542
+ };
1543
+
1544
+ //#endregion
1545
+ //#region ../../packages/substrate-client/src/transport/frame-event.ts
1546
+ /** Server response frames as the subscribe and stream iterables yield them. */
1547
+ const DEFAULT_RECONNECT = {
1548
+ baseDelayMs: 1e3,
1549
+ maxDelayMs: 3e4,
1550
+ jitter: .1
1551
+ };
1552
+ const DEFAULT_OVERLOAD_RESUBSCRIBE = {
1553
+ enabled: true,
1554
+ maxAttempts: 3,
1555
+ baseDelayMs: 1e3,
1556
+ maxDelayMs: 3e4,
1557
+ jitter: .1,
1558
+ healthyResetMs: 6e4
1559
+ };
1560
+ /** Convert a server frame to a SubscribeEvent, or null if unrecognised. */
1561
+ function msgToEvent(msg) {
1562
+ switch (msg.kind) {
1563
+ case "snapshot":
1564
+ case "add":
1565
+ case "update": return {
1566
+ kind: msg.kind,
1567
+ data: msg.data,
1568
+ ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {}
1569
+ };
1570
+ case "chunk": return {
1571
+ kind: "chunk",
1572
+ data: msg.data,
1573
+ ...msg.shapes !== void 0 ? { shapes: msg.shapes } : {},
1574
+ ...msg.sequence !== void 0 ? { sequence: msg.sequence } : {}
1575
+ };
1576
+ case "remove": return {
1577
+ kind: "remove",
1578
+ removedId: msg.removedId ?? ""
1579
+ };
1580
+ case "end": return {
1581
+ kind: "end",
1582
+ ...msg.final !== void 0 ? { final: msg.final } : {},
1583
+ ...msg.reason !== void 0 ? { reason: msg.reason } : {}
1584
+ };
1585
+ case "error": {
1586
+ const first = (msg.errors ?? [{
1587
+ message: "unknown error",
1588
+ code: "unknown"
1589
+ }])[0] ?? {
1590
+ message: "unknown error",
1591
+ code: "unknown"
1592
+ };
1593
+ throw new SubscribeError(first.message, first.code ?? "unknown");
1594
+ }
1595
+ default: return null;
1596
+ }
1597
+ }
1598
+
1599
+ //#endregion
1600
+ //#region ../../packages/substrate-client/src/transport/frames.ts
1601
+ /**
1602
+ * Subscribe and stream over length-prefixed frame streams: one POST per
1603
+ * subscription, its response body a sequence of frames (substrate-pack's
1604
+ * stream-frames codec). Each subscription owns its request, so cancelling one
1605
+ * aborts only that request.
1606
+ *
1607
+ * A subscription survives the following, re-subscribing for a fresh
1608
+ * snapshot: a dropped connection (after backoff), `end { server_restart }`
1609
+ * (at once), `subscription_overloaded` (after the overload delay, within its
1610
+ * budget) and a lapsed credential when `getToken` can mint a new one. A 401 or
1611
+ * 403 is terminal. A stream is never re-sent, since that would replay its chunks.
1612
+ */
1613
+ /** `NetworkError.code` when the server does not answer with frame streams. */
1614
+ const FRAMES_UNSUPPORTED = "frames_unsupported";
1615
+ /** `NetworkError.code` when a stream was cut short by a server restart. */
1616
+ const STREAM_INTERRUPTED = "stream_interrupted";
1617
+ const OVERLOADED = "subscription_overloaded";
1618
+ const SERVER_RESTART = "server_restart";
1619
+ const LAPSES = /* @__PURE__ */ new Set(["credential_expired", "credential_changed"]);
1620
+ function openFrameStream(http, path, frame, opts) {
1621
+ return { [Symbol.asyncIterator]: () => {
1622
+ const ctrl = new AbortController();
1623
+ const gen = run(http, path, frame, opts, opts.signal === void 0 ? ctrl.signal : anySignal([ctrl.signal, opts.signal]));
1624
+ return {
1625
+ next: () => gen.next(),
1626
+ return: async () => {
1627
+ ctrl.abort();
1628
+ await gen.return(void 0);
1629
+ return {
1630
+ value: void 0,
1631
+ done: true
1632
+ };
1633
+ }
1634
+ };
1635
+ } };
1636
+ }
1637
+ async function* run(http, path, frame, opts, signal) {
1638
+ const subscribe = path === "/substrate/v1/subscribe";
1639
+ const reconnect = {
1640
+ ...DEFAULT_RECONNECT,
1641
+ ...opts.reconnect
1642
+ };
1643
+ const backoff = new ReconnectScheduler(reconnect);
1644
+ const overload = {
1645
+ ...DEFAULT_OVERLOAD_RESUBSCRIBE,
1646
+ ...opts.overload
1647
+ };
1648
+ let overloadAttempts = 0;
1649
+ let lastOverloadAt = null;
1650
+ let opened = false;
1651
+ let busyRetries = 0;
1652
+ const accept = opts.wire === "pack" ? FRAMES_PACK_MIME : FRAMES_JSON_MIME;
1653
+ for (;;) {
1654
+ let body;
1655
+ try {
1656
+ const res = await http.raw(path, {
1657
+ method: "POST",
1658
+ body: frame,
1659
+ accept,
1660
+ signal
1661
+ });
1662
+ const type = res.headers.get("content-type") ?? "";
1663
+ if (!type.startsWith(accept)) {
1664
+ await res.body?.cancel();
1665
+ throw new NetworkError(`POST ${path} answered '${type}', not ${accept}: the server predates frame streams`, null, {
1666
+ status: res.status,
1667
+ code: FRAMES_UNSUPPORTED
1668
+ });
1669
+ }
1670
+ if (res.body === null) throw new NetworkError(`POST ${path}: response has no body`, null);
1671
+ body = res.body;
1672
+ } catch (err) {
1673
+ if (signal.aborted) return;
1674
+ if (!opened && isBusy(err) && busyRetries < BUSY_RETRIES) {
1675
+ busyRetries++;
1676
+ if (!await sleep(backoff.nextDelay(), signal)) return;
1677
+ continue;
1678
+ }
1679
+ if (err instanceof AuthError || !opened || !subscribe || refused(err)) throw err;
1680
+ if (!await sleep(backoff.nextDelay(), signal)) return;
1681
+ continue;
1682
+ }
1683
+ opened = true;
1684
+ const openedAt = Date.now();
1685
+ let next;
1686
+ try {
1687
+ const idleMs = opts.idleMs ?? 65e3;
1688
+ for await (const payload of decodeStreamFrames(idleMs > 0 ? withIdleTimeout(body, idleMs) : body)) {
1689
+ const msg = decodeFrame(payload, opts.wire);
1690
+ if (Date.now() - openedAt >= reconnect.maxDelayMs) backoff.reset();
1691
+ if (subscribe && msg.kind === "error" && msg.errors?.[0]?.code === OVERLOADED && overload.enabled) {
1692
+ const now = Date.now();
1693
+ if (lastOverloadAt !== null && now - lastOverloadAt > overload.healthyResetMs) overloadAttempts = 0;
1694
+ lastOverloadAt = now;
1695
+ if (overloadAttempts < overload.maxAttempts) {
1696
+ overloadAttempts += 1;
1697
+ next = { delayMs: jittered(overload, overloadAttempts) };
1698
+ break;
1699
+ }
1700
+ }
1701
+ if (!subscribe && msg.kind === "end" && msg.reason === SERVER_RESTART) throw new NetworkError(`POST ${path}: the server restarted mid-stream`, null, { code: STREAM_INTERRUPTED });
1702
+ const event = msgToEvent(msg);
1703
+ if (event === null) continue;
1704
+ yield event;
1705
+ if (msg.kind === "end") {
1706
+ next = subscribe && (msg.reason === SERVER_RESTART || msg.reason !== void 0 && LAPSES.has(msg.reason) && opts.canRefreshToken) ? { delayMs: 0 } : "stop";
1707
+ break;
1708
+ }
1709
+ }
1710
+ } catch (err) {
1711
+ if (signal.aborted) return;
1712
+ if (err instanceof SubscribeError || err instanceof NetworkError && err.code === "stream_interrupted") throw err;
1713
+ if (!subscribe) throw err instanceof NetworkError ? err : new NetworkError(`POST ${path}: the stream broke before its end frame`, err);
1714
+ }
1715
+ if (next === "stop") return;
1716
+ if (next === void 0) {
1717
+ if (signal.aborted) return;
1718
+ if (!subscribe) throw new NetworkError(`POST ${path}: stream ended without an end frame`, null);
1719
+ next = { delayMs: backoff.nextDelay() };
1720
+ }
1721
+ if (!await sleep(next.delayMs, signal)) return;
1722
+ }
1723
+ }
1724
+ /** Retries of a 429 before the first response, after which it surfaces. */
1725
+ const BUSY_RETRIES = 3;
1726
+ function isBusy(err) {
1727
+ return err instanceof NetworkError && err.status === 429;
1728
+ }
1729
+ /**
1730
+ * A refusal that retrying will not change: a server without frame streams, or a
1731
+ * 4xx other than 408 and 429 (the frame no longer validates, say).
1732
+ */
1733
+ function refused(err) {
1734
+ if (!(err instanceof NetworkError)) return false;
1735
+ if (err.code === "frames_unsupported") return true;
1736
+ const status = err.status;
1737
+ return status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
1738
+ }
1739
+ /**
1740
+ * Aborts when any of `signals` does. `AbortSignal.any` holds no listener on its
1741
+ * sources, so finished subscriptions leave nothing behind on a shared signal; the
1742
+ * fallback, for browsers before 2024, does.
1743
+ */
1744
+ function anySignal(signals) {
1745
+ if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
1746
+ const ctrl = new AbortController();
1747
+ for (const s of signals) {
1748
+ if (s.aborted) {
1749
+ ctrl.abort(s.reason);
1750
+ break;
1751
+ }
1752
+ s.addEventListener("abort", () => ctrl.abort(s.reason), { once: true });
1753
+ }
1754
+ return ctrl.signal;
1755
+ }
1756
+ function decodeFrame(payload, wire) {
1757
+ const value = wire === "pack" ? decodeWsEnvelope(payload, "pack") : JSON.parse(new TextDecoder().decode(payload));
1758
+ if (value === null || typeof value !== "object" || typeof value.kind !== "string") throw new NetworkError("malformed frame in subscription stream", null);
1759
+ return value;
1760
+ }
1761
+ function jittered(cfg, attempt) {
1762
+ const raw = Math.min(cfg.baseDelayMs * 2 ** (attempt - 1), cfg.maxDelayMs);
1763
+ return cfg.jitter === 0 ? raw : raw + (Math.random() * 2 - 1) * raw * cfg.jitter;
1764
+ }
1765
+ /** Resolves true after `ms`, or false as soon as `signal` aborts. */
1766
+ function sleep(ms, signal) {
1767
+ if (signal.aborted) return Promise.resolve(false);
1768
+ return new Promise((resolve) => {
1769
+ const timer = setTimeout(() => {
1770
+ signal.removeEventListener("abort", onAbort);
1771
+ resolve(true);
1772
+ }, ms);
1773
+ const onAbort = () => {
1774
+ clearTimeout(timer);
1775
+ resolve(false);
1776
+ };
1777
+ signal.addEventListener("abort", onAbort, { once: true });
1778
+ });
1779
+ }
1780
+
1781
+ //#endregion
1782
+ //#region ../../packages/substrate-client/src/nl.ts
1783
+ function createNlApi(t) {
1784
+ const packs = /* @__PURE__ */ new Map();
1785
+ return {
1786
+ async *ask(req, opts = {}) {
1787
+ const res = await t.raw("/substrate/v1/nl", {
1788
+ method: "POST",
1789
+ body: req,
1790
+ accept: FRAMES_JSON_MIME,
1791
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1792
+ });
1793
+ const type = res.headers.get("content-type") ?? "";
1794
+ if (!type.startsWith("application/vnd.substrate.frames+json") || res.body === null) {
1795
+ await res.body?.cancel();
1796
+ throw new NetworkError(`POST /substrate/v1/nl answered '${type}', not ${FRAMES_JSON_MIME}: the server predates frame streams`, null, {
1797
+ status: res.status,
1798
+ code: FRAMES_UNSUPPORTED
1799
+ });
1800
+ }
1801
+ const utf8 = new TextDecoder();
1802
+ for await (const payload of decodeStreamFrames(res.body)) {
1803
+ let ev;
1804
+ try {
1805
+ ev = JSON.parse(utf8.decode(payload));
1806
+ } catch (err) {
1807
+ throw new NetworkError("malformed frame in the NL stream", err);
1808
+ }
1809
+ if (ev.event === "error") {
1810
+ const e = ev.data;
1811
+ throw new NetworkError(`${e.code ?? "error"}: ${e.message ?? ""}`, ev.data);
1812
+ }
1813
+ yield ev;
1814
+ }
1815
+ },
1816
+ async askJson(req, opts = {}) {
1817
+ return await (await t.raw("/substrate/v1/nl", {
1818
+ method: "POST",
1819
+ body: req,
1820
+ accept: "application/json",
1821
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1822
+ })).json();
1823
+ },
1824
+ async pack(namespace, opts = {}) {
1825
+ const prior = packs.get(namespace);
1826
+ const url = `/substrate/v1/nl/pack/${encodeURIComponent(namespace)}`;
1827
+ const res = await t.raw(url, {
1828
+ method: "GET",
1829
+ allow304: true,
1830
+ ...prior !== void 0 ? { headers: { "if-none-match": prior.etag } } : {},
1831
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1832
+ });
1833
+ if (res.status === 304) {
1834
+ if (prior !== void 0) return structuredClone(prior.body);
1835
+ throw new NetworkError(`GET ${url} returned 304 with no cached pack to reuse`, null);
1836
+ }
1837
+ const body = await res.json();
1838
+ const etag = res.headers.get("etag");
1839
+ if (etag !== null) packs.set(namespace, {
1840
+ etag,
1841
+ body: structuredClone(body)
1842
+ });
1843
+ return structuredClone(body);
1844
+ }
1845
+ };
1846
+ }
1847
+
1848
+ //#endregion
1849
+ //#region ../../packages/substrate-client/src/subscribe-util.ts
1850
+ /**
1851
+ * Produce a copy of `frame` where every qualified key's `fields` selection has
1852
+ * `id: true` injected. `update` and `remove` subscribe events are correlated by
1853
+ * row id, so without an `id` in the selection a live consumer would have nothing
1854
+ * to patch against.
1855
+ *
1856
+ * The input frame is never mutated. Callers still use the original frame for
1857
+ * cache-key canonicalisation so query + subscribe on the same frame resolve to
1858
+ * the same cache entry.
1859
+ */
1860
+ function augmentFramesWithId(frame) {
1861
+ const out = {};
1862
+ for (const [key, entry] of Object.entries(frame)) if (Array.isArray(entry)) out[key] = entry.map((e) => ({
1863
+ params: e.params ?? {},
1864
+ fields: {
1865
+ id: true,
1866
+ ...e.fields ?? {}
1867
+ }
1868
+ }));
1869
+ else if (entry !== void 0) out[key] = {
1870
+ params: entry.params ?? {},
1871
+ fields: {
1872
+ id: true,
1873
+ ...entry.fields ?? {}
1874
+ }
1875
+ };
1876
+ return out;
1877
+ }
1878
+ /**
1879
+ * Validate that `frame` has exactly one qualified key and return it. Throws with
1880
+ * a descriptive error for zero- or multi-key frames.
1881
+ */
1882
+ function assertSingleKey(frame) {
1883
+ const keys = Object.keys(frame);
1884
+ if (keys.length !== 1) {
1885
+ if (keys.length === 0) throw new Error("Live subscribe surfaces require exactly one key in the frame.");
1886
+ throw new Error(`Live subscribe surfaces require a single qualified key. Got: ${keys.join(", ")}`);
1887
+ }
1888
+ return keys[0];
1889
+ }
1890
+
1891
+ //#endregion
1892
+ //#region ../../packages/substrate-client/src/transport/platform-fetch.browser.ts
1893
+ const platformFetch = (input, init) => globalThis.fetch(input, init);
1894
+
1895
+ //#endregion
1896
+ //#region ../../packages/substrate-client/src/transport/default-fetch.ts
1897
+ let current = platformFetch;
1898
+ const substrateFetch = (input, init) => current(input, init);
1899
+
1900
+ //#endregion
1901
+ //#region ../../packages/substrate-client/src/transport/http.ts
1902
+ var HttpTransport = class {
1903
+ #endpoint;
1904
+ #fetch;
1905
+ #token;
1906
+ #getToken;
1907
+ constructor(opts) {
1908
+ if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("HttpTransport: provide `token` OR `getToken`, not both");
1909
+ this.#endpoint = trimTrailingSlashes(opts.endpoint);
1910
+ this.#fetch = (opts.fetch ?? substrateFetch).bind(globalThis);
1911
+ this.#token = opts.token;
1912
+ this.#getToken = opts.getToken;
1913
+ }
1914
+ async query(frame, opts) {
1915
+ return this.#postEnvelope(`${this.#endpoint}/substrate/v1/query`, frame, opts);
1916
+ }
1917
+ async mutate(frame, opts) {
1918
+ return this.#postEnvelope(`${this.#endpoint}/substrate/v1/mutate`, frame, opts);
1919
+ }
1920
+ async federatedSchema(opts = {}) {
1921
+ const url = `${this.#endpoint}/substrate/v1/federated-schema`;
1922
+ const headers = await this.#headers("json", opts.headers);
1923
+ let res;
1924
+ try {
1925
+ res = await this.#fetch(url, {
1926
+ method: "GET",
1927
+ headers,
1928
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1929
+ });
1930
+ } catch (err) {
1931
+ throw new NetworkError(`GET ${url} failed`, err);
1932
+ }
1933
+ await this.#assertOk(res, url);
1934
+ return await res.json();
1935
+ }
1936
+ /** A request to an arbitrary /substrate path with the client's auth; asserts ok (a 304 passes only with allow304). */
1937
+ async raw(path, init) {
1938
+ const url = `${this.#endpoint}${path}`;
1939
+ const extra = init.accept !== void 0 ? { accept: init.accept } : {};
1940
+ for (const [k, v] of Object.entries(init.headers ?? {})) extra[k.toLowerCase()] = v;
1941
+ const headers = await this.#headers("json", extra);
1942
+ if (init.body === void 0) delete headers["content-type"];
1943
+ let res;
1944
+ try {
1945
+ res = await this.#fetch(url, {
1946
+ method: init.method,
1947
+ headers,
1948
+ ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
1949
+ ...init.signal !== void 0 ? { signal: init.signal } : {}
1950
+ });
1951
+ } catch (err) {
1952
+ throw new NetworkError(`${init.method} ${url} failed`, err);
1953
+ }
1954
+ if (!(init.allow304 === true && res.status === 304)) await this.#assertOk(res, url);
1955
+ return res;
1956
+ }
1957
+ async #postEnvelope(url, body, opts) {
1958
+ const wire = opts.wire ?? "json";
1959
+ const headers = await this.#headers(wire, opts.headers);
1960
+ let res;
1961
+ try {
1962
+ res = await this.#fetch(url, {
1963
+ method: "POST",
1964
+ headers,
1965
+ body: JSON.stringify(body),
1966
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
1967
+ });
1968
+ } catch (err) {
1969
+ throw new NetworkError(`POST ${url} failed`, err);
1970
+ }
1971
+ await this.#assertOk(res, url);
1972
+ if (wire === "pack") {
1973
+ const buf = await res.arrayBuffer();
1974
+ return { __packBytes: new Uint8Array(buf) };
1975
+ }
1976
+ return await res.json();
1977
+ }
1978
+ async #headers(wire, extra) {
1979
+ const headers = {
1980
+ "content-type": "application/json",
1981
+ accept: wire === "pack" ? "application/vnd.substrate.pack" : "application/json"
1982
+ };
1983
+ const tok = this.#token ?? (this.#getToken ? await this.#getToken() : void 0);
1984
+ if (tok !== void 0) headers.authorization = `Bearer ${tok}`;
1985
+ return {
1986
+ ...headers,
1987
+ ...extra
1988
+ };
1989
+ }
1990
+ async #assertOk(res, url) {
1991
+ if (res.ok) return;
1992
+ if (res.status === 401 || res.status === 403) {
1993
+ const { code, serverMessage, body } = await errorInfo(res);
1994
+ const info = {
1995
+ ...code !== void 0 ? { code } : {},
1996
+ ...serverMessage !== void 0 ? { serverMessage } : {},
1997
+ ...body !== void 0 ? { body } : {}
1998
+ };
1999
+ throw new AuthError(`${res.status === 401 ? "Unauthorised" : "Forbidden"}: ${url}`, res.status, info);
2000
+ }
2001
+ throw new NetworkError(`${res.status} from ${url}`, null, await errorInfo(res));
2002
+ }
2003
+ };
2004
+ /** The status plus whatever a JSON body says: the whole object as `body`, the first string of `error.message` (the recall plugin's nested shape), `error`, `message` as the message, and the first string of `error.code`, `code` as the code. Non-JSON bodies leave the status alone. */
2005
+ async function errorInfo(res) {
2006
+ const info = { status: res.status };
2007
+ try {
2008
+ const body = JSON.parse(await res.text());
2009
+ if (body !== null && typeof body === "object" && !Array.isArray(body)) {
2010
+ const b = body;
2011
+ info.body = b;
2012
+ const nested = b.error !== null && typeof b.error === "object" ? b.error : void 0;
2013
+ const message = [
2014
+ nested?.message,
2015
+ b.error,
2016
+ b.message
2017
+ ].find((v) => typeof v === "string");
2018
+ const code = [nested?.code, b.code].find((v) => typeof v === "string");
2019
+ if (typeof message === "string") info.serverMessage = message;
2020
+ if (typeof code === "string") info.code = code;
2021
+ }
2022
+ } catch {}
2023
+ return info;
2024
+ }
2025
+
2026
+ //#endregion
2027
+ //#region ../../packages/substrate-client/src/wire/pack.ts
2028
+ function isPackMarker(v) {
2029
+ return typeof v === "object" && v !== null && "__packBytes" in v;
2030
+ }
2031
+
2032
+ //#endregion
2033
+ //#region ../../packages/substrate-client/src/wire/json.ts
2034
+ function decodeJsonEnvelope(env) {
2035
+ if (typeof env.schemaVersion !== "string") throw new Error("Malformed envelope: missing schemaVersion");
2036
+ return env;
2037
+ }
2038
+
2039
+ //#endregion
2040
+ //#region ../../packages/substrate-client/src/client.ts
2041
+ /**
2042
+ * SubstrateClient — the public facade over the HTTP and frame-stream transports, wire
2043
+ * decoding and schema-drift handling.
2044
+ *
2045
+ * Routing is protocol-mandated: query and mutate are plain HTTP requests;
2046
+ * subscribe and stream are frame streams (one POST each, response held open).
2047
+ *
2048
+ * Drift detection is lazy-seeded: the client cannot replicate the server's
2049
+ * federated schema-version hash, so the first envelope's `schemaVersion` seeds
2050
+ * the cache and any later mismatch refetches the schema and accepts the new
2051
+ * version as authoritative.
2052
+ */
2053
+ var SubstrateClient = class {
2054
+ #http;
2055
+ #nl;
2056
+ #admin;
2057
+ #streamWire;
2058
+ #canRefreshToken;
2059
+ /** Aborted by close(), ending every open subscription and stream. */
2060
+ #closing = new AbortController();
2061
+ #reconnectOpts;
2062
+ #streamIdleMs;
2063
+ #overloadResubscribeOpts;
2064
+ #schemaCache = null;
2065
+ #schemaFetch = null;
2066
+ #driftCachedVersion = null;
2067
+ #closed = false;
2068
+ #cache;
2069
+ #onDiagnostics;
2070
+ constructor(opts) {
2071
+ if (opts.token !== void 0 && opts.getToken !== void 0) throw new Error("SubstrateClient: provide `token` OR `getToken`, not both");
2072
+ this.#http = new HttpTransport({
2073
+ endpoint: opts.endpoint,
2074
+ ...opts.token !== void 0 ? { token: opts.token } : {},
2075
+ ...opts.getToken !== void 0 ? { getToken: opts.getToken } : {},
2076
+ ...opts.fetch !== void 0 ? { fetch: opts.fetch } : {}
2077
+ });
2078
+ this.#streamWire = opts.streamWire ?? "json";
2079
+ this.#canRefreshToken = opts.token === void 0 && opts.getToken !== void 0;
2080
+ this.#reconnectOpts = opts.reconnect;
2081
+ this.#streamIdleMs = opts.streamIdleMs;
2082
+ this.#overloadResubscribeOpts = opts.overloadResubscribe;
2083
+ this.#onDiagnostics = opts.onDiagnostics ?? createDefaultDiagnosticsSink();
2084
+ this.#cache = new CacheStore({ idleGcMs: 5e3 });
2085
+ }
2086
+ /** Natural-language ask (frame stream or JSON) and the served namespace pack. Requires the substrate-nl plugin. */
2087
+ get nl() {
2088
+ this.#nl ??= createNlApi(this.#http);
2089
+ return this.#nl;
2090
+ }
2091
+ /** The admin-gated routes. Needs an identity whose grant confers `admin`. */
2092
+ get admin() {
2093
+ this.#admin ??= createAdminApi(this.#http);
2094
+ return this.#admin;
2095
+ }
2096
+ #ensureOpen() {
2097
+ if (this.#closed) throw new Error("SubstrateClient: already closed");
2098
+ }
2099
+ async federatedSchema() {
2100
+ this.#ensureOpen();
2101
+ if (this.#schemaCache !== null) return this.#schemaCache;
2102
+ if (this.#schemaFetch === null) this.#schemaFetch = this.#http.federatedSchema().then((schema) => {
2103
+ this.#schemaCache = schema;
2104
+ this.#schemaFetch = null;
2105
+ return schema;
2106
+ }, (err) => {
2107
+ this.#schemaFetch = null;
2108
+ throw err;
2109
+ });
2110
+ return this.#schemaFetch;
2111
+ }
2112
+ async query(frame, opts = {}) {
2113
+ this.#ensureOpen();
2114
+ await this.federatedSchema();
2115
+ const wire = opts.wire ?? "json";
2116
+ const raw = await this.#http.query(frame, {
2117
+ wire,
2118
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {},
2119
+ ...opts.headers !== void 0 ? { headers: opts.headers } : {}
2120
+ });
2121
+ return this.#decode(raw, frame, wire);
2122
+ }
2123
+ async mutate(frame, opts = {}) {
2124
+ this.#ensureOpen();
2125
+ await this.federatedSchema();
2126
+ const wire = opts.wire ?? "json";
2127
+ const raw = await this.#http.mutate(frame, {
2128
+ wire,
2129
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {},
2130
+ ...opts.headers !== void 0 ? { headers: opts.headers } : {}
2131
+ });
2132
+ return this.#decode(raw, frame, wire);
2133
+ }
2134
+ /** A live query: a snapshot, then deltas. `opts.wire` and `opts.signal` apply. */
2135
+ subscribe(frame, opts = {}) {
2136
+ return this.#frameStream("/substrate/v1/subscribe", frame, opts);
2137
+ }
2138
+ /** A one-shot streamed resolver: chunks, then `end`. `opts.wire` and `opts.signal` apply. */
2139
+ stream(frame, opts = {}) {
2140
+ return this.#frameStream("/substrate/v1/stream", frame, opts);
2141
+ }
2142
+ #frameStream(path, frame, opts) {
2143
+ this.#ensureOpen();
2144
+ const body = flatFrame(frame);
2145
+ const wire = opts.wire ?? this.#streamWire;
2146
+ const signal = opts.signal === void 0 ? this.#closing.signal : anySignal([this.#closing.signal, opts.signal]);
2147
+ const inner = openFrameStream(this.#http, path, body, {
2148
+ wire,
2149
+ canRefreshToken: this.#canRefreshToken,
2150
+ signal,
2151
+ ...this.#reconnectOpts !== void 0 ? { reconnect: this.#reconnectOpts } : {},
2152
+ ...this.#streamIdleMs !== void 0 ? { idleMs: this.#streamIdleMs } : {},
2153
+ ...this.#overloadResubscribeOpts !== void 0 ? { overload: this.#overloadResubscribeOpts } : {}
2154
+ });
2155
+ return wire === "pack" ? this.#wrapPackDecode(inner, body) : inner;
2156
+ }
2157
+ /**
2158
+ * Live typed-row view over a single-key subscription. Subscribes under the
2159
+ * hood, folds snapshot/add/update/remove into the current row-set, and yields
2160
+ * the maintained `T[]` after each delta — hiding the raw `SubscribeEvent`
2161
+ * protocol. `id` is force-selected (via `augmentFramesWithId`) so
2162
+ * update/remove can correlate rows by id.
2163
+ *
2164
+ * Completes when the subscription ends; throws on an error frame — the same
2165
+ * contract as `subscribe`. Breaking the consuming `for await` cancels the
2166
+ * underlying subscription. Reconnect / overload-resubscribe are handled by
2167
+ * `subscribe`; each fresh snapshot atomically replaces the row-set.
2168
+ *
2169
+ * Single-qualified-key only: multi-key frames throw; use `subscribe` for
2170
+ * those or for raw events.
2171
+ */
2172
+ watch(frame) {
2173
+ this.#ensureOpen();
2174
+ const qualifiedKey = assertSingleKey(frame);
2175
+ return watchRows(this.subscribe(augmentFramesWithId(frame)), qualifiedKey);
2176
+ }
2177
+ /**
2178
+ * @internal — not part of the stable public surface.
2179
+ */
2180
+ get cache() {
2181
+ return this.#cache;
2182
+ }
2183
+ invalidate(keyPrefix) {
2184
+ this.#ensureOpen();
2185
+ this.#cache.invalidate(keyPrefix);
2186
+ }
2187
+ /** Runtime metrics: op totals, per-key latency, process health, slowest requests. Needs `read`. */
2188
+ async metrics(opts = {}) {
2189
+ this.#ensureOpen();
2190
+ return await (await this.#http.raw("/substrate/v1/metrics", {
2191
+ method: "GET",
2192
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
2193
+ })).json();
2194
+ }
2195
+ /** The recent error log. Needs `admin`. */
2196
+ async errors(opts = {}) {
2197
+ this.#ensureOpen();
2198
+ return await (await this.#http.raw("/substrate/v1/errors", {
2199
+ method: "GET",
2200
+ ...opts.signal !== void 0 ? { signal: opts.signal } : {}
2201
+ })).json();
2202
+ }
2203
+ async close() {
2204
+ if (this.#closed) return;
2205
+ this.#closed = true;
2206
+ this.#closing.abort();
2207
+ }
2208
+ async #refetchSchema() {
2209
+ const schema = await this.#http.federatedSchema();
2210
+ this.#schemaCache = schema;
2211
+ }
2212
+ async #decode(raw, frame, wire) {
2213
+ let env;
2214
+ if (wire === "pack" && isPackMarker(raw)) {
2215
+ const bytes = raw.__packBytes;
2216
+ const decode = (expectedSchemaVersion) => decodeEnvelope(bytes, {
2217
+ ...this.#buildDecodeCtx(frame, this.#schemaCache ?? {}),
2218
+ ...expectedSchemaVersion !== void 0 ? { expectedSchemaVersion } : {}
2219
+ });
2220
+ try {
2221
+ env = decode(this.#driftCachedVersion ?? void 0);
2222
+ } catch (err) {
2223
+ if (!(err instanceof SchemaDriftError)) throw err;
2224
+ await this.#refetchSchema();
2225
+ this.#driftCachedVersion = err.envelopeSchemaVersion;
2226
+ env = decode();
2227
+ }
2228
+ } else env = decodeJsonEnvelope(raw);
2229
+ if (this.#driftCachedVersion === null) this.#driftCachedVersion = env.schemaVersion;
2230
+ else if (this.#driftCachedVersion !== env.schemaVersion) {
2231
+ await this.#refetchSchema();
2232
+ this.#driftCachedVersion = env.schemaVersion;
2233
+ }
2234
+ collectDiagnostics(env._diagnostics, this.#onDiagnostics);
2235
+ return env;
2236
+ }
2237
+ /**
2238
+ * Wrap a frame event stream so each `data`-bearing frame (snapshot/add/update/
2239
+ * chunk) gets its positional tuple values reconstructed into named-object
2240
+ * rows using the cached federated schema. Errors from the inner stream
2241
+ * (transport drop, server error frame) propagate untouched.
2242
+ *
2243
+ * The decode plan is built once, after the schema resolves, and reused for
2244
+ * every frame of the subscription.
2245
+ *
2246
+ * Hand-rolled iterator, NOT a native async generator: the generator form
2247
+ * queues return() behind an in-flight next(), which on a quiet connection
2248
+ * never resolves, so close() would hang. return() here forwards immediately.
2249
+ */
2250
+ #wrapPackDecode(inner, frameSpec) {
2251
+ const buildPlan = async () => {
2252
+ const schemas = await this.federatedSchema();
2253
+ return buildDecodePlan(frameSpec, schemas);
2254
+ };
2255
+ return { [Symbol.asyncIterator]: () => {
2256
+ const innerIt = inner[Symbol.asyncIterator]();
2257
+ let planPromise = null;
2258
+ return {
2259
+ async next() {
2260
+ planPromise ??= buildPlan();
2261
+ const plan = await planPromise;
2262
+ const result = await innerIt.next();
2263
+ if (!result.done) applyDecodePlanInPlace(result.value, plan);
2264
+ return result;
2265
+ },
2266
+ async return() {
2267
+ await innerIt.return?.();
2268
+ return {
2269
+ value: void 0,
2270
+ done: true
2271
+ };
2272
+ }
2273
+ };
2274
+ } };
2275
+ }
2276
+ #buildDecodeCtx(frame, schemas) {
2277
+ const fieldsByKey = {};
2278
+ const returnsByKey = {};
2279
+ const typeByKey = {};
2280
+ const currentNsByKey = {};
2281
+ for (const key of Object.keys(frame)) {
2282
+ const frameEntry = frame[key];
2283
+ const entry = Array.isArray(frameEntry) ? frameEntry[0] : frameEntry;
2284
+ const parsed = parseQualifiedKey(key);
2285
+ if (parsed === null) continue;
2286
+ const { ns, name } = parsed;
2287
+ currentNsByKey[key] = ns;
2288
+ typeByKey[key] = name;
2289
+ const mutation = schemas[ns]?.mutations[name];
2290
+ if (mutation !== void 0) {
2291
+ const shapeOf = (fields) => mutationReturns(mutation, fields);
2292
+ returnsByKey[key] = Array.isArray(frameEntry) ? frameEntry.map((f) => shapeOf(f.fields)) : shapeOf(entry?.fields);
2293
+ } else fieldsByKey[key] = entry?.fields ?? {};
2294
+ }
2295
+ return {
2296
+ fieldsByKey,
2297
+ returnsByKey,
2298
+ typeByKey,
2299
+ schemas,
2300
+ currentNsByKey
2301
+ };
2302
+ }
2303
+ };
2304
+ function flatFrame(frame) {
2305
+ const flat = {};
2306
+ for (const [key, entry] of Object.entries(frame)) {
2307
+ const single = Array.isArray(entry) ? entry[0] : entry;
2308
+ flat[key] = {
2309
+ params: single?.params ?? {},
2310
+ fields: single?.fields ?? {}
2311
+ };
2312
+ }
2313
+ return flat;
2314
+ }
2315
+
2316
+ //#endregion
2317
+ //#region ../../packages/substrate-client/src/script.ts
2318
+ const DEFAULT_MAX_WRITES = 50;
2319
+ const DEFAULT_MAX_PAGES = 200;
2320
+ /** Counts the frames in a mutate payload: an array under an op-key is one frame per element. */
2321
+ function frameCount(frame) {
2322
+ return Object.values(frame).reduce((n, v) => n + (Array.isArray(v) ? v.length : 1), 0);
2323
+ }
2324
+ function assertKeys(frame, env, verb) {
2325
+ const missing = Object.keys(frame).filter((k) => !(k in env.data));
2326
+ if (missing.length > 0 || verb === "mutate" && (env.errors?.length ?? 0) > 0) {
2327
+ const errs = (env.errors ?? []).map((e) => `${e.code ?? "error"}: ${e.message}`).join("; ");
2328
+ throw new Error(`${verb} refused${missing.length > 0 ? ` for ${missing.join(", ")}` : ""}${errs !== "" ? ` (${errs})` : ""}`);
2329
+ }
2330
+ }
2331
+ /**
2332
+ * Runs `script` against a guarded context and reports everything it did,
2333
+ * including the mutations applied before any failure.
2334
+ */
2335
+ async function runScript(script, opts) {
2336
+ const { client, kid, mode = "read", args = {}, maxWrites = 50, maxPages = DEFAULT_MAX_PAGES } = opts;
2337
+ const log = opts.log ?? ((line) => console.error(line));
2338
+ const mutations = [];
2339
+ const warnings = [];
2340
+ const stats = {
2341
+ queries: 0,
2342
+ writes: 0,
2343
+ ms: 0
2344
+ };
2345
+ const started = Date.now();
2346
+ const query = async (frame) => {
2347
+ stats.queries++;
2348
+ const env = await client.query(frame);
2349
+ assertKeys(frame, env, "query");
2350
+ for (const [key, page] of Object.entries(env._pagination ?? {})) if (page.hasMore) warnings.push(`${key}: result truncated (hasMore); use queryAll for a complete read`);
2351
+ return env;
2352
+ };
2353
+ async function queryAll(key, frame) {
2354
+ const rows = [];
2355
+ let cursor;
2356
+ for (let page = 0; page < maxPages; page++) {
2357
+ const params = {
2358
+ ...frame.params,
2359
+ ...cursor !== void 0 ? { cursor } : {}
2360
+ };
2361
+ stats.queries++;
2362
+ const env = await client.query({ [key]: {
2363
+ ...frame,
2364
+ params
2365
+ } });
2366
+ assertKeys({ [key]: frame }, env, "query");
2367
+ const data = env.data[key];
2368
+ rows.push(...Array.isArray(data) ? data : [data]);
2369
+ const p = env._pagination?.[key];
2370
+ if (p?.hasMore !== true) return rows;
2371
+ if (p.nextCursor === void 0) throw new Error(`${key}: hasMore with no nextCursor`);
2372
+ cursor = p.nextCursor;
2373
+ }
2374
+ throw new Error(`${key}: still hasMore after ${maxPages} pages`);
2375
+ }
2376
+ async function byShortId(key, n, fields) {
2377
+ const wanted = Array.isArray(n) ? n : [n];
2378
+ if (wanted.length === 0) return [];
2379
+ const unique = [...new Set(wanted)];
2380
+ const rows = await queryAll(key, {
2381
+ params: { where: { shortId: unique.length === 1 ? { eq: unique[0] } : { in: unique } } },
2382
+ ...fields !== void 0 ? { fields: {
2383
+ ...fields,
2384
+ shortId: true
2385
+ } } : {}
2386
+ });
2387
+ const byId = new Map(rows.map((r) => [Number(r.shortId), r]));
2388
+ const missing = unique.filter((id) => !byId.has(id));
2389
+ if (missing.length > 0) throw new Error(`${key}: no row with shortId ${missing.join(", ")}`);
2390
+ const found = wanted.map((id) => byId.get(id));
2391
+ return Array.isArray(n) ? found : found[0];
2392
+ }
2393
+ const ctx = {
2394
+ kid,
2395
+ mode,
2396
+ args: Object.freeze({ ...args }),
2397
+ query,
2398
+ queryAll,
2399
+ byShortId,
2400
+ async recall({ query: to, row, ...params }) {
2401
+ const fields = row === void 0 ? {} : { fields: {
2402
+ id: true,
2403
+ namespace: true,
2404
+ type: true,
2405
+ score: true,
2406
+ kind: true,
2407
+ expandedFrom: true,
2408
+ row
2409
+ } };
2410
+ return (await query({ "recall/Hit": {
2411
+ params: {
2412
+ to,
2413
+ ...params
2414
+ },
2415
+ ...fields
2416
+ } })).data["recall/Hit"];
2417
+ },
2418
+ async schema(namespace, type) {
2419
+ const all = await client.federatedSchema();
2420
+ if (namespace === void 0) return all;
2421
+ const ns = all[namespace];
2422
+ if (ns === void 0) throw new Error(`schema: unknown namespace '${namespace}'`);
2423
+ if (type === void 0) return ns;
2424
+ const t = ns.types[type];
2425
+ if (t === void 0) throw new Error(`schema: unknown type '${namespace}/${type}'`);
2426
+ return t;
2427
+ },
2428
+ async mutate(frame) {
2429
+ if (mode === "read") throw new Error("mutate refused: read mode (run in dry-run or write mode)");
2430
+ if (mode === "dry-run") {
2431
+ mutations.push({
2432
+ frame,
2433
+ applied: false
2434
+ });
2435
+ return null;
2436
+ }
2437
+ const n = frameCount(frame);
2438
+ if (stats.writes + n > maxWrites) throw new Error(`mutate refused: ${stats.writes + n} frames would exceed --max-writes ${maxWrites}`);
2439
+ const env = await client.mutate(frame);
2440
+ const applied = Object.keys(frame).some((k) => k in env.data);
2441
+ if (applied) stats.writes += n;
2442
+ mutations.push({
2443
+ frame,
2444
+ applied,
2445
+ ...env.errors !== void 0 ? { errors: env.errors } : {}
2446
+ });
2447
+ assertKeys(frame, env, "mutate");
2448
+ return env;
2449
+ },
2450
+ log: (...args) => log(args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" "))
2451
+ };
2452
+ const report = (extra) => {
2453
+ stats.ms = Date.now() - started;
2454
+ return {
2455
+ ...extra,
2456
+ kid,
2457
+ mode,
2458
+ args,
2459
+ mutations,
2460
+ warnings,
2461
+ stats
2462
+ };
2463
+ };
2464
+ try {
2465
+ return report({
2466
+ ok: true,
2467
+ result: await script(ctx)
2468
+ });
2469
+ } catch (err) {
2470
+ return report({
2471
+ ok: false,
2472
+ error: err instanceof Error ? err.message : String(err)
2473
+ });
2474
+ }
2475
+ }
2476
+
2477
+ //#endregion
2478
+ //#region ../../packages/substrate-client/src/token-target.ts
2479
+ /**
2480
+ * Where a freshly minted credential may be sent: an https origin, or plain
2481
+ * http only to a loopback host, where nothing on the network can read it.
2482
+ */
2483
+ const LOOPBACK = /^(localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/;
2484
+ /**
2485
+ * @returns the origin of `baseUrl`, which a token for it names as its `aud`.
2486
+ * @throws Error when `baseUrl` is not a URL, or is plain http to a non-loopback host.
2487
+ */
2488
+ function tokenAudience(baseUrl) {
2489
+ let url;
2490
+ try {
2491
+ url = new URL(baseUrl);
2492
+ } catch {
2493
+ throw new Error(`'${baseUrl}' is not a URL`);
2494
+ }
2495
+ if (url.protocol === "https:" || url.protocol === "http:" && LOOPBACK.test(url.hostname)) return url.origin;
2496
+ throw new Error(`refusing to send a credential to ${url.origin}: use https, or plain http only to a loopback host`);
2497
+ }
2498
+ /** `fetchImpl` with redirects refused: a redirect would carry the credential to wherever it points. */
2499
+ function noRedirectFetch(fetchImpl = substrateFetch) {
2500
+ return (input, init) => fetchImpl(input, {
2501
+ ...init,
2502
+ redirect: "error"
2503
+ });
2504
+ }
2505
+
2506
+ //#endregion
2507
+ export { AdminBackfillError, AuthError, BACKFILL_CHUNK, CURRENT_MARK, DEFAULT_MAX_WRITES, NetworkError, ONBOARD_STEPS, SKIPPABLE_STEPS, STEP_MARKS, SchemaDriftError, SubscribeError, SubstrateClient, collectDiagnostics, createDefaultDiagnosticsSink, currentStep, noRedirectFetch, planOnboarding, reduceSubscribeRows, requiredOutstanding, runScript, substrateFetch, tokenAudience, watchRows };