@mnmal-ai/substrate 1.0.0-alpha.11 → 1.0.0-alpha.12

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 (38) hide show
  1. package/README.md +4 -2
  2. package/dist/{boot-store-C5vNZJ3i.js → boot-store-DHv9H1Gr.js} +165 -69
  3. package/dist/{bridge-COu0Tg_h.d.ts → bridge-DQyQ6Qhn.d.ts} +1 -1
  4. package/dist/{cli-BrwW4tjO.js → cli-_UNdneXr.js} +11 -9
  5. package/dist/client.d.ts +3 -3
  6. package/dist/client.js +3 -3
  7. package/dist/{errors-BOllGhVx.d.ts → errors-xP9Mo7Q1.d.ts} +25 -4
  8. package/dist/{index-Cp74OcmS.d.ts → index-baF5A5jU.d.ts} +1 -1
  9. package/dist/pack.d.ts +2 -2
  10. package/dist/pack.js +1 -1
  11. package/dist/{pg-edges-store-BLsbcXkk.js → pg-edges-store-B4FSN9yp.js} +72 -9
  12. package/dist/{plugin-DIYm2cZE.js → plugin-BLm5IRdX.js} +2 -2
  13. package/dist/proposals-bootstrap.js +2 -2
  14. package/dist/proposals.d.ts +2 -2
  15. package/dist/proposals.js +1 -1
  16. package/dist/recall-bootstrap.js +2 -2
  17. package/dist/recall.d.ts +10 -10
  18. package/dist/recall.js +2 -2
  19. package/dist/{repl-B8gy0YM7.js → repl-DUJGBwie.js} +25 -25
  20. package/dist/{row-DwaDU4b-.d.ts → row-Cu_iRhcR.d.ts} +2 -2
  21. package/dist/{run-B18qtGKc.js → run-BpsTNvdI.js} +520 -141
  22. package/dist/{schema-CijHRfuk.d.ts → schema-oXfQyo0s.d.ts} +272 -27
  23. package/dist/sdk.d.ts +93 -29
  24. package/dist/sdk.js +4 -4
  25. package/dist/{src-D041j6GS.js → src-Bew_JvTo.js} +32 -16
  26. package/dist/{src-DpPdw2oL.js → src-Bi3NhEsT.js} +1 -1
  27. package/dist/{src-DK7VEQT6.js → src-C4t1Gy-m.js} +2477 -830
  28. package/dist/{src-Br6aDUti.js → src-CHND7-Pm.js} +2 -2
  29. package/dist/src-CSe2tJDf.js +6940 -0
  30. package/dist/{src-DptNGNYQ.js → src-CzhKLsOV.js} +175 -91
  31. package/dist/{src-Dbvuel6w.js → src-DWqzrm3O.js} +18 -1
  32. package/dist/substrate-admin.js +1 -1
  33. package/dist/substrate.js +1 -1
  34. package/dist/testing.d.ts +233 -92
  35. package/dist/testing.js +6 -23
  36. package/dist/{ws-DC8OhMaV.d.ts → ws-Dx3A2B4U.d.ts} +2 -2
  37. package/package.json +19 -20
  38. package/dist/src-gz4I1F29.js +0 -5097
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
- import { A as expandFlat, D as isActiveAdminKeyRow, F as parseGrantEntries, I as decodeList, L as encodeList, M as grantEntryError, P as intersectGrants, S as and, T as SYSTEM_NAMESPACE, d as confersAnywhere, f as coversNamespace, g as checkUpdatable, h as checkRevocable, l as requireNamespace, m as grantedIn, o as denyVerbs, p as grantOf, s as requireCapability, t as applyRowFilters, u as allCapabilities, v as grantEntriesConfer, w as or } from "./src-DpPdw2oL.js";
3
- import { C as parseQualifiedKey, S as formatQualifiedKey, _ as encodeEnvelope, c as isPlainRequestData, o as decodeWsEnvelope, s as encodeWsFrame, t as WS_SUBPROTOCOL_SUBSTRATE_PACK, v as encodePositional, w as assertNever, x as naturalOrderOf } from "./src-Dbvuel6w.js";
2
+ import { A as expandFlat, D as isActiveAdminKeyRow, F as parseGrantEntries, I as decodeList, L as encodeList, M as grantEntryError, P as intersectGrants, S as and, T as SYSTEM_NAMESPACE, d as confersAnywhere, f as coversNamespace, g as checkUpdatable, h as checkRevocable, l as requireNamespace, m as grantedIn, o as denyVerbs, p as grantOf, s as requireCapability, t as applyRowFilters, u as allCapabilities, v as grantEntriesConfer, w as or } from "./src-Bi3NhEsT.js";
3
+ import { C as formatQualifiedKey, E as assertNever, S as naturalOrderOf, T as DEFAULT_FILTER_WRITE_LIMITS, _ as encodeEnvelope, c as isPlainRequestData, o as decodeWsEnvelope, s as encodeWsFrame, t as WS_SUBPROTOCOL_SUBSTRATE_PACK, v as encodePositional, w as parseQualifiedKey, x as isColumnField } from "./src-DWqzrm3O.js";
4
4
  import { n as acceptsPack, t as PACK_MIME } from "./content-type-C7T28xNb.js";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, createPublicKey, createVerify, hkdfSync, randomBytes, randomUUID, sign, timingSafeEqual, verify } from "node:crypto";
@@ -88,6 +88,8 @@ const ROW_METADATA_FIELDS = [
88
88
 
89
89
  //#endregion
90
90
  //#region ../../packages/substrate-types/src/errors.ts
91
+ /** A by-filter write matched more rows than `SUBSTRATE_FILTER_WRITE_MAX_MATCH`; nothing changed. */
92
+ const FILTER_TOO_BROAD = "filter_too_broad";
91
93
  /** Refusal codes for the typed-edge-walk grammar. */
92
94
  const WALKS_NEED_PARTITIONED = "walks_need_partitioned";
93
95
  const WALKS_IN_SUBSCRIPTION = "walks_in_subscription";
@@ -95,6 +97,8 @@ const WALKS_IN_MUTATION = "walks_in_mutation";
95
97
  const ROW_POLICY_BLOCKS_WALK = "row_policy_blocks_walk";
96
98
  const WALK_BUDGET_EXCEEDED = "walk_budget_exceeded";
97
99
  const WALKS_UNSUPPORTED_STORE = "walks_unsupported_store";
100
+ /** A read cancelled by the store's statement timeout; `details: { timeoutMs }`. */
101
+ const QUERY_TIMEOUT = "query_timeout";
98
102
  /**
99
103
  * A walk construct refused where it cannot be answered: inside a struct, over
100
104
  * a list or struct-nested crossRef, under a reused field name, on a virtual
@@ -134,6 +138,10 @@ var ResolverFrameError = class extends Error {
134
138
  if (details !== void 0) this.details = details;
135
139
  }
136
140
  };
141
+ /** `filter_too_broad`: a by-filter write on `<namespace>/<type>` matched more than `maxMatch` rows. */
142
+ function filterTooBroad(namespace, type, maxMatch) {
143
+ return new ResolverFrameError(FILTER_TOO_BROAD, `${namespace}/${type}: the filter matches more than ${maxMatch} rows; nothing changed. Narrow the where, or raise SUBSTRATE_FILTER_WRITE_MAX_MATCH`, { maxMatch });
144
+ }
137
145
  /**
138
146
  * Thrown by a write-path resolver when a crossRef declaring `onMissing: 'reject'`
139
147
  * references a target that does not exist (or has been tombstoned). Extends
@@ -194,12 +202,13 @@ var NamespaceMismatch = class extends Error {
194
202
  };
195
203
  /**
196
204
  * Thrown by `Dataset.updateField` when the caller targets a reserved
197
- * field name (e.g. `_deletedAt`). Spec §4.5.
205
+ * field name (e.g. `_deletedAt`), and by any other write path that refuses
206
+ * one; `how` names that path in the message. Spec §4.5.
198
207
  */
199
208
  var ReservedField = class extends Error {
200
209
  name = "ReservedField";
201
- constructor(field) {
202
- super(`field '${field}' is reserved and cannot be written via updateField`);
210
+ constructor(field, how = "via updateField") {
211
+ super(`field '${field}' is reserved and cannot be written ${how}`);
203
212
  }
204
213
  };
205
214
  /**
@@ -232,6 +241,27 @@ var BridgeUnreachableError = class extends Error {
232
241
  }
233
242
  };
234
243
  /**
244
+ * Thrown by a `BatchResolver` to refuse element `index` of its args list. The
245
+ * engine rolls back the whole array and reports `cause` as the per-element
246
+ * resolver would have: a `ResolverFrameError` or `RestrictViolation` keeps
247
+ * its code at `[key]`, and `batched_frame_rolled_back` names the element.
248
+ */
249
+ var BatchElementError = class extends Error {
250
+ index;
251
+ cause;
252
+ name = "BatchElementError";
253
+ constructor(index, cause) {
254
+ super(`batch element ${index} refused: ${cause instanceof Error ? cause.message : String(cause)}`);
255
+ this.index = index;
256
+ this.cause = cause;
257
+ }
258
+ };
259
+ /** Recognise a {@link BatchElementError} across module-realm boundaries. */
260
+ function isBatchElementError(err) {
261
+ if (err instanceof BatchElementError) return true;
262
+ return typeof err === "object" && err !== null && err.name === "BatchElementError" && typeof err.index === "number";
263
+ }
264
+ /**
235
265
  * Recognise a {@link ResolverFrameError} across module-realm boundaries.
236
266
  *
237
267
  * Plain `instanceof` is realm-fragile whenever this class exists twice in one
@@ -1810,302 +1840,6 @@ var ShapeRecorder = class {
1810
1840
  }
1811
1841
  };
1812
1842
 
1813
- //#endregion
1814
- //#region ../../packages/substrate-core/src/advisor/walk-service.ts
1815
- const isObj$4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1816
- const dirOf = (d) => d === "desc" ? "desc" : "asc";
1817
- function orderOf(orderBy) {
1818
- const out = [];
1819
- for (const clause of Array.isArray(orderBy) ? orderBy : []) {
1820
- if (!isObj$4(clause)) continue;
1821
- for (const [f, d] of Object.entries(clause)) out.push([f, dirOf(d)]);
1822
- }
1823
- return out;
1824
- }
1825
- /** Every walk site of a frame entry `{ params, fields }` seeded at `seed`, at any depth. */
1826
- function walkSites(entry, seed, resolve) {
1827
- const out = [];
1828
- const site = (node, from, path) => {
1829
- const s = {
1830
- path,
1831
- far: resolve(node, from, path),
1832
- wheres: []
1833
- };
1834
- if (typeof node.in === "string") s.crossRef = node.in.slice(node.in.indexOf(".") + 1);
1835
- out.push(s);
1836
- return s;
1837
- };
1838
- const addWhere = (s, where, path) => {
1839
- if (where === void 0) return;
1840
- s.wheres.push({
1841
- where,
1842
- path
1843
- });
1844
- inWhere(where, s.far, path);
1845
- };
1846
- const inWhere = (v, type, path) => {
1847
- if (Array.isArray(v)) {
1848
- v.forEach((c, i) => {
1849
- inWhere(c, type, [...path, String(i)]);
1850
- });
1851
- return;
1852
- }
1853
- if (!isObj$4(v)) return;
1854
- for (const [k, child] of Object.entries(v)) {
1855
- const at = [...path, k];
1856
- if (k === "_walk" && isObj$4(child)) {
1857
- const s = site(child, type, at);
1858
- const pick = isObj$4(child.pick) ? Object.entries(child.pick)[0] : void 0;
1859
- if (pick !== void 0) {
1860
- const [fn, field] = pick;
1861
- s.order = {
1862
- by: [[String(field), fn === "min" ? "asc" : "desc"]],
1863
- path: [...at, "pick"],
1864
- kind: "order"
1865
- };
1866
- }
1867
- addWhere(s, child.where, [...at, "where"]);
1868
- } else if (k === "_agg" && isObj$4(child)) agg(child, type, at);
1869
- else inWhere(child, type, at);
1870
- }
1871
- };
1872
- const agg = (node, from, path) => {
1873
- const s = site(node, from, path);
1874
- if (isObj$4(node.latest)) s.order = {
1875
- by: [[String(node.latest.by), "desc"]],
1876
- path: [...path, "latest"],
1877
- kind: "agg"
1878
- };
1879
- else if (typeof node.min === "string" || typeof node.max === "string") {
1880
- const fn = typeof node.min === "string" ? "min" : "max";
1881
- s.order = {
1882
- by: [[String(node[fn]), fn === "min" ? "asc" : "desc"]],
1883
- path: [...path, fn],
1884
- kind: "agg"
1885
- };
1886
- } else s.agg = [...path, [
1887
- "count",
1888
- "avg",
1889
- "sum"
1890
- ].find((k) => k in node) ?? "count"];
1891
- addWhere(s, node.where, [...path, "where"]);
1892
- };
1893
- const inFields = (fields, type, path) => {
1894
- if (!isObj$4(fields)) return;
1895
- for (const [name, sel] of Object.entries(fields)) {
1896
- const at = [...path, name];
1897
- if (name === "_agg" && isObj$4(sel)) {
1898
- for (const [n, a] of Object.entries(sel)) if (isObj$4(a)) agg(a, type, [...at, n]);
1899
- } else if (isObj$4(sel) && isObj$4(sel._walk)) {
1900
- const wp = [...at, "_walk"];
1901
- const s = site(sel._walk, type, wp);
1902
- const by = orderOf(sel.orderBy);
1903
- if (by.length > 0) s.order = {
1904
- by,
1905
- path: [...at, "orderBy"],
1906
- kind: "order",
1907
- exact: true
1908
- };
1909
- addWhere(s, sel._walk.where, [...wp, "where"]);
1910
- addWhere(s, sel.where, [...at, "where"]);
1911
- inFields(sel.fields, s.far, [...at, "fields"]);
1912
- }
1913
- }
1914
- };
1915
- inWhere((isObj$4(entry.params) ? entry.params : {}).where, seed, ["where"]);
1916
- inFields(entry.fields, seed, ["fields"]);
1917
- return out;
1918
- }
1919
- const COMBINATORS = /* @__PURE__ */ new Set([
1920
- "AND",
1921
- "OR",
1922
- "NOT"
1923
- ]);
1924
- const SKIP = /* @__PURE__ */ new Set([
1925
- "_walk",
1926
- "_agg",
1927
- "$ref"
1928
- ]);
1929
- /** The predicates of one type's `where`, not descending into walks. */
1930
- function predicates(where, fields, path) {
1931
- const out = [];
1932
- const visit = (w, defs, prefix, at, conjunct = true) => {
1933
- if (Array.isArray(w)) {
1934
- w.forEach((c, i) => {
1935
- visit(c, defs, prefix, [...at, String(i)], conjunct);
1936
- });
1937
- return;
1938
- }
1939
- if (!isObj$4(w) || Object.hasOwn(w, "_agg")) return;
1940
- for (const [k, v] of Object.entries(w)) {
1941
- if (SKIP.has(k)) continue;
1942
- if (COMBINATORS.has(k)) {
1943
- visit(v, defs, prefix, [...at, k], conjunct && k === "AND");
1944
- continue;
1945
- }
1946
- const def = defs !== void 0 && Object.hasOwn(defs, k) ? defs[k] : void 0;
1947
- if (def?.kind === "struct") visit(v, def.fields, `${prefix}${k}.`, [...at, k], conjunct);
1948
- else if (isObj$4(v)) {
1949
- const ref = Object.values(v).some((o) => isObj$4(o) && "$ref" in o);
1950
- const bounds = conjunct && Object.keys(v).some((op) => op !== "neq");
1951
- out.push({
1952
- field: `${prefix}${k}`,
1953
- path: [...at, k],
1954
- ref,
1955
- bounds
1956
- });
1957
- }
1958
- }
1959
- };
1960
- visit(where, fields, "", path);
1961
- return out;
1962
- }
1963
- /** What an `indexes` entry may key on: a declared scalar or crossRef, or a metadata column. */
1964
- const declarable$1 = (field, fields) => {
1965
- if (field === "createdAt" || field === "updatedAt") return true;
1966
- const def = fields !== void 0 && Object.hasOwn(fields, field) ? fields[field] : void 0;
1967
- return def?.kind === "crossRef" || def?.kind === "scalar" && def.type !== "json";
1968
- };
1969
- /**
1970
- * Whether some full index's keys begin with `lead` and then `next`, by field
1971
- * name, and when `next` gives a direction, in it: an index key is ascending
1972
- * or descending, nulls last either way, so one scanned forward is the order
1973
- * `<dir> NULLS LAST` that reads compile to, and one scanned backward is not.
1974
- */
1975
- const leads = (indexes, lead, next) => indexes.some((i) => i.only === void 0 && [...lead, ...next].every((k, n) => typeof k === "string" ? i.keys[n]?.[0] === k : i.keys[n]?.[0] === k[0] && i.keys[n]?.[1] === k[1]));
1976
- /** The fields that follow `lead` as the next key of a full index, i.e. what a walk through `lead` is served on. */
1977
- const nextKeys = (indexes, lead) => [...new Set(indexes.flatMap((i) => i.only === void 0 && i.keys[0]?.[0] === lead && i.keys[1] !== void 0 ? [i.keys[1][0]] : []))];
1978
- /**
1979
- * Each clause of a walk-grammar frame, served or not (spec §2):
1980
- * - a hop is served, inbound by the eager `(crossRef, natural order)` index
1981
- * (absent for a crossRef declared `indexed: false`) and outbound by the
1982
- * primary key;
1983
- * - a far filter, pick or latest/min/max is served when a full index on the
1984
- * far type leads with the hop's crossRef and that field next, and a nested
1985
- * list's order when its keys follow in its directions too (after an
1986
- * outbound hop the far row is one primary-key read, so all of it is served);
1987
- * - a `$ref` predicate is a residual on rows already narrowed: always served;
1988
- * - a seed filter, or a bucket's field, is served by an index leading with it;
1989
- * - a derived ordering is served only when a served seed filter bounds the
1990
- * result (AND-ed, not under OR or NOT, and not only `neq`); no index ever
1991
- * serves it, so it recommends none;
1992
- * - anything else is unserved, recommending the index that would serve it
1993
- * when its fields can be declared.
1994
- */
1995
- function classifyWalkService(input, indexesOf) {
1996
- const { entry, seed, fieldsOf } = input;
1997
- const out = [];
1998
- const params = isObj$4(entry.params) ? entry.params : {};
1999
- const clause = (path, kind, served, type, keys) => {
2000
- const c = {
2001
- path,
2002
- kind,
2003
- served
2004
- };
2005
- const names = keys.map((k) => typeof k === "string" ? k : k.field);
2006
- if (!served && names.every((f) => declarable$1(f, fieldsOf(type)))) c.recommend = { fields: keys };
2007
- out.push(c);
2008
- };
2009
- const seedIndexes = indexesOf(seed);
2010
- let bounded = false;
2011
- for (const p of predicates(params.where, fieldsOf(seed), ["where"])) {
2012
- if (p.ref) {
2013
- out.push({
2014
- path: p.path,
2015
- kind: "ref",
2016
- served: true
2017
- });
2018
- continue;
2019
- }
2020
- const served = leads(seedIndexes, [p.field], []);
2021
- bounded ||= served && p.bounds;
2022
- clause(p.path, "filter", served, seed, [p.field]);
2023
- }
2024
- for (const s of walkSites(entry, seed, input.resolve)) {
2025
- const farIndexes = indexesOf(s.far);
2026
- const cr = s.crossRef;
2027
- const hop = cr === void 0 || leads(farIndexes, [cr], []);
2028
- clause(s.path, "hop", hop, s.far, cr === void 0 ? [] : [cr]);
2029
- for (const w of s.wheres) for (const p of predicates(w.where, fieldsOf(s.far), w.path)) if (p.ref) out.push({
2030
- path: p.path,
2031
- kind: "ref",
2032
- served: true
2033
- });
2034
- else {
2035
- const served = cr === void 0 || leads(farIndexes, [cr], [p.field]);
2036
- clause(p.path, "filter", served, s.far, cr === void 0 ? [] : [cr, p.field]);
2037
- }
2038
- if (s.order !== void 0) {
2039
- const { by, path, kind, exact } = s.order;
2040
- const served = cr === void 0 || leads(farIndexes, [cr], by.map(([f, d]) => exact ? [f, d] : f));
2041
- const keys = cr === void 0 ? [] : [cr, ...by.map(([field, dir]) => ({
2042
- field,
2043
- dir
2044
- }))];
2045
- clause(path, kind, served, s.far, keys);
2046
- }
2047
- if (s.agg !== void 0) out.push({
2048
- path: s.agg,
2049
- kind: "agg",
2050
- served: true
2051
- });
2052
- }
2053
- if (isObj$4(params.bucket) && typeof params.bucket.field === "string") {
2054
- const field = params.bucket.field;
2055
- clause(["bucket"], "bucket", leads(seedIndexes, [field], []), seed, [field]);
2056
- }
2057
- orderOf(params.orderBy).forEach(([f], i) => {
2058
- if (f.startsWith("$")) out.push({
2059
- path: ["orderBy", String(i)],
2060
- kind: "derive",
2061
- served: bounded
2062
- });
2063
- });
2064
- return out;
2065
- }
2066
-
2067
- //#endregion
2068
- //#region ../../packages/substrate-core/src/engine/cursor-seal.ts
2069
- /**
2070
- * Seals a pagination cursor so its contents cannot be read.
2071
- *
2072
- * A dataset cursor names the last row of the page it read, before row-filter
2073
- * policies ran. Under a row policy that row may be one the caller cannot see,
2074
- * so the engine seals the cursor and opens it again on the way back in.
2075
- */
2076
- const PREFIX = "s1.";
2077
- let KEY = randomBytes(32);
2078
- /** Derives the seal key from a deployment secret, so every process sharing it opens the same cursors. */
2079
- function setCursorSealSecret(secret) {
2080
- KEY = Buffer.from(hkdfSync("sha256", secret, "", "substrate-cursor-seal", 32));
2081
- }
2082
- function sealCursor(cursor) {
2083
- const iv = randomBytes(12);
2084
- const cipher = createCipheriv("aes-256-gcm", KEY, iv);
2085
- const body = Buffer.concat([cipher.update(cursor, "utf8"), cipher.final()]);
2086
- return PREFIX + Buffer.concat([
2087
- iv,
2088
- cipher.getAuthTag(),
2089
- body
2090
- ]).toString("base64url");
2091
- }
2092
- function isSealedCursor(cursor) {
2093
- return cursor.startsWith(PREFIX);
2094
- }
2095
- /** The original cursor, the input itself when it was never sealed, or `null` when it does not open. */
2096
- function openCursor(cursor) {
2097
- if (!cursor.startsWith(PREFIX)) return cursor;
2098
- const raw = Buffer.from(cursor.slice(3), "base64url");
2099
- if (raw.length < 28) return null;
2100
- try {
2101
- const decipher = createDecipheriv("aes-256-gcm", KEY, raw.subarray(0, 12));
2102
- decipher.setAuthTag(raw.subarray(12, 28));
2103
- return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8");
2104
- } catch {
2105
- return null;
2106
- }
2107
- }
2108
-
2109
1843
  //#endregion
2110
1844
  //#region ../../packages/substrate-filter/src/apply-extension-meta.ts
2111
1845
  function fieldRequested(fields, name) {
@@ -2274,6 +2008,17 @@ function decodeCursor(cursor, expected) {
2274
2008
  order: issued
2275
2009
  };
2276
2010
  }
2011
+ /**
2012
+ * `orderBy` as `[field, dir]` pairs, with `['id', 'asc']` appended unless a
2013
+ * clause already orders by id (in either direction). Appended even when
2014
+ * `orderBy` is absent: the id tail is what a cursor resumes on.
2015
+ */
2016
+ function normalizeOrderBy(orderBy) {
2017
+ const out = [];
2018
+ for (const clause of orderBy ?? []) for (const [field, dir] of Object.entries(clause)) out.push([field, dir]);
2019
+ if (!out.some(([f]) => f === "id")) out.push(["id", "asc"]);
2020
+ return out;
2021
+ }
2277
2022
 
2278
2023
  //#endregion
2279
2024
  //#region ../../packages/substrate-filter/src/extension-operators.ts
@@ -2687,8 +2432,8 @@ function buildMeta(hits) {
2687
2432
  */
2688
2433
  /** Default per-read cap on walk work (far rows examined plus binding assignments tried). */
2689
2434
  const WALK_EVALUATION_BUDGET = 1e6;
2690
- const isObj$3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2691
- const isRefOperand = (v) => isObj$3(v) && typeof v.$ref === "string";
2435
+ const isObj$6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2436
+ const isRefOperand = (v) => isObj$6(v) && typeof v.$ref === "string";
2692
2437
  /**
2693
2438
  * One AND group, flattened: its `any` walks with `as` (the object's own
2694
2439
  * `_walk`, then, through AND, its conjuncts') and every other conjunct as a
@@ -2699,13 +2444,13 @@ function groupConjuncts(where, out = {
2699
2444
  binds: [],
2700
2445
  items: []
2701
2446
  }) {
2702
- if (!isObj$3(where)) return out;
2447
+ if (!isObj$6(where)) return out;
2703
2448
  if (Object.hasOwn(where, "_agg")) {
2704
2449
  out.items.push(where);
2705
2450
  return out;
2706
2451
  }
2707
2452
  const w = where._walk;
2708
- if (isObj$3(w) && typeof w.as === "string") out.binds.push(w);
2453
+ if (isObj$6(w) && typeof w.as === "string") out.binds.push(w);
2709
2454
  else if (Object.hasOwn(where, "_walk")) out.items.push({ _walk: w });
2710
2455
  if (Array.isArray(where.AND)) for (const sub of where.AND) groupConjuncts(sub, out);
2711
2456
  for (const [k, v] of Object.entries(where)) if (k !== "_walk" && k !== "AND") out.items.push({ [k]: v });
@@ -2718,7 +2463,7 @@ function bindingWalks(where) {
2718
2463
  /** Binding names a `$ref` anywhere below `where` reads. */
2719
2464
  function refNames(where, out = /* @__PURE__ */ new Set()) {
2720
2465
  if (Array.isArray(where)) for (const w of where) refNames(w, out);
2721
- else if (isObj$3(where)) {
2466
+ else if (isObj$6(where)) {
2722
2467
  if (typeof where.$ref === "string") out.add(where.$ref.split(".", 1)[0] ?? "");
2723
2468
  for (const v of Object.values(where)) refNames(v, out);
2724
2469
  }
@@ -3294,10 +3039,458 @@ function msToMicros(ms) {
3294
3039
  }
3295
3040
 
3296
3041
  //#endregion
3297
- //#region ../../packages/substrate-core/src/sweep.ts
3298
- const DEFAULT_BATCH_SIZE$1 = 100;
3299
- const SWEEP_ACTOR = {
3300
- kind: "system",
3042
+ //#region ../../packages/substrate-filter/src/walk-forms.ts
3043
+ /**
3044
+ * A page larger than this (the default max page) wants every seed rather than a page of them.
3045
+ * Fixed rather than the configured `maxLimit`, which the datasets never see. So under default
3046
+ * page limits the shared forms apply to counts and whole-result aggregates, and to pages only
3047
+ * for callers with a raised `maxLimit` or in-process reads with no limit.
3048
+ */
3049
+ const EVERY_SEED_LIMIT = 1e3;
3050
+ /** True when a read evaluates its walks for every matching seed: a count, a whole-result aggregate, or a page with no limit or one over {@link EVERY_SEED_LIMIT}. */
3051
+ function readsEverySeed(params) {
3052
+ return params.count === true || params.aggregate !== void 0 || params.limit === void 0 || params.limit > 1e3;
3053
+ }
3054
+ const isObj$5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3055
+ /** The `_walk` nodes among a where's top-level AND conjuncts, without `as`. */
3056
+ const conjunctWalks = (where) => groupConjuncts(where).items.flatMap((i) => {
3057
+ const w = i._walk;
3058
+ return isObj$5(w) ? [w] : [];
3059
+ });
3060
+ const isAny$1 = (w) => w.pick === void 0 && (w.quantifier ?? "any") === "any";
3061
+ /**
3062
+ * The `per-hub` rule. A pick P is shared, mapped to its hub walk O, when the
3063
+ * read wants every seed and is a count or a page (not a whole-result
3064
+ * aggregate), O is a top-level AND conjunct `{ _walk: { out, where } }`
3065
+ * of the seed's where (an `any` walk, no `as`) that reads no top-level `as`
3066
+ * binding, P is an inbound pick among O's where's AND conjuncts, and P's
3067
+ * where reads no binding but `$` (or a frame `_agg`). Picking depends only on
3068
+ * the hub, and `$` is read after the pick, so P's where is still tested per
3069
+ * seed. O reading a top-level binding would compile inside that binding's
3070
+ * EXISTS, where the shared CTE could not be hashed.
3071
+ */
3072
+ function sharedPicks(params) {
3073
+ const out = /* @__PURE__ */ new Map();
3074
+ if (!readsEverySeed(params) || params.aggregate !== void 0) return out;
3075
+ const bound = new Set(groupConjuncts(params.where).binds.map((b) => b.as));
3076
+ for (const o of conjunctWalks(params.where)) {
3077
+ if (typeof o.out !== "string" || !isAny$1(o)) continue;
3078
+ if ([...refNames(o.where)].some((n) => bound.has(n))) continue;
3079
+ for (const p of conjunctWalks(o.where)) {
3080
+ if (typeof p.in !== "string" || p.pick === void 0) continue;
3081
+ if ([...refNames(p.where)].every((n) => n === "$" || n === "_agg")) out.set(p, o);
3082
+ }
3083
+ }
3084
+ return out;
3085
+ }
3086
+ const RANGE_OPS = /* @__PURE__ */ new Set([
3087
+ "gt",
3088
+ "gte",
3089
+ "lt",
3090
+ "lte",
3091
+ "between"
3092
+ ]);
3093
+ /** True when `where` holds no walk grammar (`_walk`, `_agg`, `$ref`): it reads only the far row. */
3094
+ const farOnly = (where) => Array.isArray(where) ? where.every(farOnly) : !isObj$5(where) || Object.entries(where).every(([k, v]) => k !== "_walk" && k !== "_agg" && k !== "$ref" && farOnly(v));
3095
+ /** An `_agg` is a pick (a top-1, per seed): a latest, or a date min/max. */
3096
+ const isPickAgg = (spec, fieldDef) => "latest" in spec || ["min", "max"].some((op) => {
3097
+ const f = spec[op];
3098
+ return typeof f === "string" && isDateField(f, fieldDef);
3099
+ });
3100
+ /**
3101
+ * The `group-by` rule, for one frame-level `_agg` entry. It is aggregated in
3102
+ * one pass over its window when:
3103
+ * - the read is a page (a count or aggregate projects no `_agg`) that wants
3104
+ * every seed (see {@link readsEverySeed});
3105
+ * - its hop is inbound and it is a count, avg, sum or number min/max (a
3106
+ * latest or date min/max is a top-1 probe per seed, already cheap);
3107
+ * - its `where` reads only the far row (no `_walk`, `_agg` or `$ref`) and
3108
+ * holds, AND-ed at the top, a range on a field `indexed` on the far type
3109
+ * (an index leads with it), so the window is one index range;
3110
+ * - the seed's where has, AND-ed at the top, an `any` walk over the same hop
3111
+ * and the very same `where` (compared as JSON; a mismatch only misses the
3112
+ * form): every seed is then one of the window's keys, so the window is
3113
+ * read anyway. The seeds may be fewer than the keys; the pg compiler
3114
+ * semi-joins the keys to the seeds' other conjuncts, so the pass covers
3115
+ * only the keys that can match.
3116
+ */
3117
+ function windowGroupBy(spec, params, fieldDef, indexed) {
3118
+ if (params.count === true || params.aggregate !== void 0 || !readsEverySeed(params)) return false;
3119
+ if (typeof spec.in !== "string" || spec.where === void 0) return false;
3120
+ if (isPickAgg(spec, fieldDef) || !farOnly(spec.where)) return false;
3121
+ if (!groupConjuncts(spec.where).items.some((i) => Object.entries(i).some(([f, ops]) => isObj$5(ops) && Object.keys(ops).some((op) => RANGE_OPS.has(op)) && indexed(f)))) return false;
3122
+ const key = JSON.stringify(spec.where);
3123
+ return conjunctWalks(params.where).some((w) => isAny$1(w) && w.in === spec.in && JSON.stringify(w.where) === key);
3124
+ }
3125
+
3126
+ //#endregion
3127
+ //#region ../../packages/substrate-filter/src/walk-hops.ts
3128
+ const isObj$4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3129
+ /**
3130
+ * Visits every hop of a frame entry `{ params: { where }, fields }` seeded at
3131
+ * `seed`, at any depth, each before the hops beneath it. `visit` gets the hop
3132
+ * and its near type and returns the far type; the hops in the far rows'
3133
+ * wheres (the node's `where`, then a nested selection's own `where`) and a
3134
+ * nested selection's `fields` are visited next. Returning `undefined` stops the
3135
+ * descent below that hop. A where is searched generically, under AND/OR/NOT
3136
+ * and anywhere else, as the walk gate does.
3137
+ */
3138
+ function forEachWalkHop(entry, seed, visit) {
3139
+ const inWhere = (v, type, path) => {
3140
+ if (Array.isArray(v)) {
3141
+ v.forEach((c, i) => {
3142
+ inWhere(c, type, [...path, String(i)]);
3143
+ });
3144
+ return;
3145
+ }
3146
+ if (!isObj$4(v)) return;
3147
+ for (const [k, child] of Object.entries(v)) {
3148
+ const at = [...path, k];
3149
+ if ((k === "_walk" || k === "_agg") && isObj$4(child)) {
3150
+ const far = visit({
3151
+ kind: k === "_walk" ? "walk" : "agg",
3152
+ node: child,
3153
+ path: at
3154
+ }, type);
3155
+ if (far !== void 0) inWhere(child.where, far, [...at, "where"]);
3156
+ } else inWhere(child, type, at);
3157
+ }
3158
+ };
3159
+ const inFields = (fields, type, path) => {
3160
+ if (!isObj$4(fields)) return;
3161
+ for (const [name, sel] of Object.entries(fields)) {
3162
+ const at = [...path, name];
3163
+ if (name === "_agg" && isObj$4(sel)) for (const [n, agg] of Object.entries(sel)) {
3164
+ if (!isObj$4(agg)) continue;
3165
+ const far = visit({
3166
+ kind: "agg",
3167
+ node: agg,
3168
+ path: [...at, n]
3169
+ }, type);
3170
+ if (far !== void 0) inWhere(agg.where, far, [
3171
+ ...at,
3172
+ n,
3173
+ "where"
3174
+ ]);
3175
+ }
3176
+ else if (isObj$4(sel) && isObj$4(sel._walk)) {
3177
+ const walk = sel._walk;
3178
+ const wp = [...at, "_walk"];
3179
+ const far = visit({
3180
+ kind: "nested",
3181
+ node: walk,
3182
+ path: wp,
3183
+ selection: {
3184
+ sel,
3185
+ path: at
3186
+ }
3187
+ }, type);
3188
+ if (far === void 0) continue;
3189
+ inWhere(walk.where, far, [...wp, "where"]);
3190
+ inWhere(sel.where, far, [...at, "where"]);
3191
+ inFields(sel.fields, far, [...at, "fields"]);
3192
+ }
3193
+ }
3194
+ };
3195
+ inWhere((isObj$4(entry.params) ? entry.params : {}).where, seed, ["where"]);
3196
+ inFields(entry.fields, seed, ["fields"]);
3197
+ }
3198
+
3199
+ //#endregion
3200
+ //#region ../../packages/substrate-core/src/advisor/walk-service.ts
3201
+ /**
3202
+ * Index service of a walk-grammar read (spec 2026-10-24-typed-edge-walks
3203
+ * goal 7, §2): each clause is marked served or unserved for `plan`, and each
3204
+ * walk is a site the shape recorder turns into a far-type read shape. Nothing
3205
+ * here refuses anything; it only describes.
3206
+ */
3207
+ const isObj$3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3208
+ const dirOf = (d) => d === "desc" ? "desc" : "asc";
3209
+ function orderOf(orderBy) {
3210
+ const out = [];
3211
+ for (const clause of Array.isArray(orderBy) ? orderBy : []) {
3212
+ if (!isObj$3(clause)) continue;
3213
+ for (const [f, d] of Object.entries(clause)) out.push([f, dirOf(d)]);
3214
+ }
3215
+ return out;
3216
+ }
3217
+ /**
3218
+ * Every walk site of a frame entry `{ params, fields }` seeded at `seed`, at
3219
+ * any depth. `naturalOrder` gives a nested list without `orderBy` its far
3220
+ * type's natural order, as the engine reads it (#1821).
3221
+ */
3222
+ function walkSites(entry, seed, resolve, naturalOrder) {
3223
+ const out = [];
3224
+ forEachWalkHop(entry, seed, ({ kind, node, path, selection }, from) => {
3225
+ const far = resolve(node, from, path);
3226
+ const s = {
3227
+ path,
3228
+ node,
3229
+ far,
3230
+ wheres: []
3231
+ };
3232
+ if (typeof node.in === "string") s.crossRef = node.in.slice(node.in.indexOf(".") + 1);
3233
+ out.push(s);
3234
+ const addWhere = (where, at) => {
3235
+ if (where !== void 0) s.wheres.push({
3236
+ where,
3237
+ path: at
3238
+ });
3239
+ };
3240
+ if (kind === "walk") {
3241
+ const pick = isObj$3(node.pick) ? Object.entries(node.pick)[0] : void 0;
3242
+ if (pick !== void 0) {
3243
+ const [fn, field] = pick;
3244
+ s.order = {
3245
+ by: [[String(field), fn === "min" ? "asc" : "desc"]],
3246
+ path: [...path, "pick"],
3247
+ kind: "order"
3248
+ };
3249
+ }
3250
+ addWhere(node.where, [...path, "where"]);
3251
+ } else if (kind === "agg") {
3252
+ if (isObj$3(node.latest)) s.order = {
3253
+ by: [[String(node.latest.by), "desc"]],
3254
+ path: [...path, "latest"],
3255
+ kind: "agg"
3256
+ };
3257
+ else if (typeof node.min === "string" || typeof node.max === "string") {
3258
+ const fn = typeof node.min === "string" ? "min" : "max";
3259
+ s.order = {
3260
+ by: [[String(node[fn]), fn === "min" ? "asc" : "desc"]],
3261
+ path: [...path, fn],
3262
+ kind: "agg"
3263
+ };
3264
+ } else s.agg = [...path, [
3265
+ "count",
3266
+ "avg",
3267
+ "sum"
3268
+ ].find((k) => k in node) ?? "count"];
3269
+ addWhere(node.where, [...path, "where"]);
3270
+ } else if (selection !== void 0) {
3271
+ const { sel, path: at } = selection;
3272
+ let by = orderOf(sel.orderBy);
3273
+ if (by.length === 0 && naturalOrder !== void 0) by = orderOf([naturalOrder(far)]);
3274
+ if (by.length > 0) s.order = {
3275
+ by,
3276
+ path: [...at, "orderBy"],
3277
+ kind: "order",
3278
+ exact: true
3279
+ };
3280
+ addWhere(node.where, [...path, "where"]);
3281
+ addWhere(sel.where, [...at, "where"]);
3282
+ }
3283
+ return far;
3284
+ });
3285
+ return out;
3286
+ }
3287
+ const COMBINATORS = /* @__PURE__ */ new Set([
3288
+ "AND",
3289
+ "OR",
3290
+ "NOT"
3291
+ ]);
3292
+ const SKIP = /* @__PURE__ */ new Set([
3293
+ "_walk",
3294
+ "_agg",
3295
+ "$ref"
3296
+ ]);
3297
+ /** The predicates of one type's `where`, not descending into walks. */
3298
+ function predicates(where, fields, path) {
3299
+ const out = [];
3300
+ const visit = (w, defs, prefix, at, conjunct = true) => {
3301
+ if (Array.isArray(w)) {
3302
+ w.forEach((c, i) => {
3303
+ visit(c, defs, prefix, [...at, String(i)], conjunct);
3304
+ });
3305
+ return;
3306
+ }
3307
+ if (!isObj$3(w) || Object.hasOwn(w, "_agg")) return;
3308
+ for (const [k, v] of Object.entries(w)) {
3309
+ if (SKIP.has(k)) continue;
3310
+ if (COMBINATORS.has(k)) {
3311
+ visit(v, defs, prefix, [...at, k], conjunct && k === "AND");
3312
+ continue;
3313
+ }
3314
+ const def = defs !== void 0 && Object.hasOwn(defs, k) ? defs[k] : void 0;
3315
+ if (def?.kind === "struct") visit(v, def.fields, `${prefix}${k}.`, [...at, k], conjunct);
3316
+ else if (isObj$3(v)) {
3317
+ const ref = Object.values(v).some((o) => isObj$3(o) && "$ref" in o);
3318
+ const bounds = conjunct && Object.keys(v).some((op) => op !== "neq");
3319
+ out.push({
3320
+ field: `${prefix}${k}`,
3321
+ path: [...at, k],
3322
+ ref,
3323
+ bounds
3324
+ });
3325
+ }
3326
+ }
3327
+ };
3328
+ visit(where, fields, "", path);
3329
+ return out;
3330
+ }
3331
+ /** What an `indexes` entry may key on: a declared scalar or crossRef, or a metadata column. */
3332
+ const declarable$1 = (field, fields) => {
3333
+ if (field === "createdAt" || field === "updatedAt") return true;
3334
+ const def = fields !== void 0 && Object.hasOwn(fields, field) ? fields[field] : void 0;
3335
+ return def?.kind === "crossRef" || def?.kind === "scalar" && def.type !== "json";
3336
+ };
3337
+ /**
3338
+ * Whether some full index's keys begin with `lead` and then `next`, by field
3339
+ * name, and when `next` gives a direction, in it: an index key is ascending
3340
+ * or descending, nulls last either way, so one scanned forward is the order
3341
+ * `<dir> NULLS LAST` that reads compile to, and one scanned backward is not.
3342
+ */
3343
+ const leads = (indexes, lead, next) => indexes.some((i) => i.only === void 0 && [...lead, ...next].every((k, n) => typeof k === "string" ? i.keys[n]?.[0] === k : i.keys[n]?.[0] === k[0] && i.keys[n]?.[1] === k[1]));
3344
+ /** The fields that follow `lead` as the next key of a full index, i.e. what a walk through `lead` is served on. */
3345
+ const nextKeys = (indexes, lead) => [...new Set(indexes.flatMap((i) => i.only === void 0 && i.keys[0]?.[0] === lead && i.keys[1] !== void 0 ? [i.keys[1][0]] : []))];
3346
+ /**
3347
+ * Each clause of a walk-grammar frame, served or not (spec §2):
3348
+ * - a hop is served, inbound by the eager `(crossRef, natural order)` index
3349
+ * (absent for a crossRef declared `indexed: false`) and outbound by the
3350
+ * primary key;
3351
+ * - a far filter, pick or latest/min/max is served when a full index on the
3352
+ * far type leads with the hop's crossRef and that field next, and a nested
3353
+ * list's order when its keys follow in its directions too (after an
3354
+ * outbound hop the far row is one primary-key read, so all of it is served);
3355
+ * - a `$ref` predicate is a residual on rows already narrowed: always served;
3356
+ * - a seed filter, or a bucket's field, is served by an index leading with it;
3357
+ * - a derived ordering is served only when a served seed filter bounds the
3358
+ * result (AND-ed, not under OR or NOT, and not only `neq`); no index ever
3359
+ * serves it, so it recommends none;
3360
+ * - anything else is unserved, recommending the index that would serve it
3361
+ * when its fields can be declared.
3362
+ */
3363
+ function classifyWalkService(input, indexesOf) {
3364
+ const { entry, seed, fieldsOf } = input;
3365
+ const out = [];
3366
+ const params = isObj$3(entry.params) ? entry.params : {};
3367
+ const clause = (path, kind, served, type, keys) => {
3368
+ const c = {
3369
+ path,
3370
+ kind,
3371
+ served
3372
+ };
3373
+ const names = keys.map((k) => typeof k === "string" ? k : k.field);
3374
+ if (!served && names.every((f) => declarable$1(f, fieldsOf(type)))) c.recommend = { fields: keys };
3375
+ out.push(c);
3376
+ };
3377
+ const seedIndexes = indexesOf(seed);
3378
+ let bounded = false;
3379
+ for (const p of predicates(params.where, fieldsOf(seed), ["where"])) {
3380
+ if (p.ref) {
3381
+ out.push({
3382
+ path: p.path,
3383
+ kind: "ref",
3384
+ served: true
3385
+ });
3386
+ continue;
3387
+ }
3388
+ const served = leads(seedIndexes, [p.field], []);
3389
+ bounded ||= served && p.bounds;
3390
+ clause(p.path, "filter", served, seed, [p.field]);
3391
+ }
3392
+ const shared = sharedPicks(params);
3393
+ /** #1815: how a pick or a frame `_agg` is evaluated, by the rules pg compiles to. */
3394
+ const formOf = (s, indexes) => {
3395
+ const top = s.path.length === 3 && s.path[0] === "fields" && s.path[1] === "_agg";
3396
+ if (s.node.pick !== void 0) return shared.has(s.node) ? "per-hub" : "per-seed";
3397
+ if (!top) return void 0;
3398
+ const fields = fieldsOf(s.far);
3399
+ const def = (f) => fields !== void 0 && Object.hasOwn(fields, f) ? fields[f] : void 0;
3400
+ return windowGroupBy(s.node, params, def, (f) => leads(indexes, [f], [])) ? "group-by" : "per-seed";
3401
+ };
3402
+ for (const s of walkSites(entry, seed, input.resolve, input.naturalOrder)) {
3403
+ const farIndexes = indexesOf(s.far);
3404
+ const cr = s.crossRef;
3405
+ const hop = cr === void 0 || leads(farIndexes, [cr], []);
3406
+ clause(s.path, "hop", hop, s.far, cr === void 0 ? [] : [cr]);
3407
+ const form = formOf(s, farIndexes);
3408
+ if (form !== void 0) out[out.length - 1].form = form;
3409
+ for (const w of s.wheres) for (const p of predicates(w.where, fieldsOf(s.far), w.path)) if (p.ref) out.push({
3410
+ path: p.path,
3411
+ kind: "ref",
3412
+ served: true
3413
+ });
3414
+ else {
3415
+ const served = cr === void 0 || leads(farIndexes, [cr], [p.field]);
3416
+ clause(p.path, "filter", served, s.far, cr === void 0 ? [] : [cr, p.field]);
3417
+ }
3418
+ if (s.order !== void 0) {
3419
+ const { by, path, kind, exact } = s.order;
3420
+ const served = cr === void 0 || leads(farIndexes, [cr], by.map(([f, d]) => exact ? [f, d] : f));
3421
+ const keys = cr === void 0 ? [] : [cr, ...by.map(([field, dir]) => ({
3422
+ field,
3423
+ dir
3424
+ }))];
3425
+ clause(path, kind, served, s.far, keys);
3426
+ }
3427
+ if (s.agg !== void 0) out.push({
3428
+ path: s.agg,
3429
+ kind: "agg",
3430
+ served: true
3431
+ });
3432
+ }
3433
+ if (isObj$3(params.bucket) && typeof params.bucket.field === "string") {
3434
+ const field = params.bucket.field;
3435
+ clause(["bucket"], "bucket", leads(seedIndexes, [field], []), seed, [field]);
3436
+ }
3437
+ orderOf(params.orderBy).forEach(([f], i) => {
3438
+ if (f.startsWith("$")) out.push({
3439
+ path: ["orderBy", String(i)],
3440
+ kind: "derive",
3441
+ served: bounded
3442
+ });
3443
+ });
3444
+ return out;
3445
+ }
3446
+
3447
+ //#endregion
3448
+ //#region ../../packages/substrate-core/src/engine/cursor-seal.ts
3449
+ /**
3450
+ * Seals a pagination cursor so its contents cannot be read.
3451
+ *
3452
+ * A dataset cursor names the last row of the page it read, before row-filter
3453
+ * policies ran. Under a row policy that row may be one the caller cannot see,
3454
+ * so the engine seals the cursor and opens it again on the way back in.
3455
+ */
3456
+ const PREFIX = "s1.";
3457
+ let KEY = randomBytes(32);
3458
+ /** Derives the seal key from a deployment secret, so every process sharing it opens the same cursors. */
3459
+ function setCursorSealSecret(secret) {
3460
+ KEY = Buffer.from(hkdfSync("sha256", secret, "", "substrate-cursor-seal", 32));
3461
+ }
3462
+ function sealCursor(cursor) {
3463
+ const iv = randomBytes(12);
3464
+ const cipher = createCipheriv("aes-256-gcm", KEY, iv);
3465
+ const body = Buffer.concat([cipher.update(cursor, "utf8"), cipher.final()]);
3466
+ return PREFIX + Buffer.concat([
3467
+ iv,
3468
+ cipher.getAuthTag(),
3469
+ body
3470
+ ]).toString("base64url");
3471
+ }
3472
+ function isSealedCursor(cursor) {
3473
+ return cursor.startsWith(PREFIX);
3474
+ }
3475
+ /** The original cursor, the input itself when it was never sealed, or `null` when it does not open. */
3476
+ function openCursor(cursor) {
3477
+ if (!cursor.startsWith(PREFIX)) return cursor;
3478
+ const raw = Buffer.from(cursor.slice(3), "base64url");
3479
+ if (raw.length < 28) return null;
3480
+ try {
3481
+ const decipher = createDecipheriv("aes-256-gcm", KEY, raw.subarray(0, 12));
3482
+ decipher.setAuthTag(raw.subarray(12, 28));
3483
+ return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8");
3484
+ } catch {
3485
+ return null;
3486
+ }
3487
+ }
3488
+
3489
+ //#endregion
3490
+ //#region ../../packages/substrate-core/src/sweep.ts
3491
+ const DEFAULT_BATCH_SIZE$1 = 100;
3492
+ const SWEEP_ACTOR = {
3493
+ kind: "system",
3301
3494
  id: "sweep"
3302
3495
  };
3303
3496
  /** `UNKNOWN`: the bridge could not answer (down, or refused), so nothing may be applied. */
@@ -3499,6 +3692,94 @@ async function applyLostNamespace(lostNs, deps, opts = {}) {
3499
3692
  return { affectedEdges };
3500
3693
  }
3501
3694
 
3695
+ //#endregion
3696
+ //#region ../../packages/substrate-core/src/engine/committed-writes.ts
3697
+ /**
3698
+ * The row-attribution actor of a request identity, or null when it names none.
3699
+ * Mirrors the sdk's `resolveIdentity` (core cannot import the sdk) but returns
3700
+ * null instead of throwing: a hook is told who wrote, it does not gate the write.
3701
+ */
3702
+ function actorOf(identity) {
3703
+ if (identity === null) return null;
3704
+ const { agentKeyId, tokenId } = identity;
3705
+ if (typeof agentKeyId === "string" && agentKeyId.length > 0) return {
3706
+ kind: "agent",
3707
+ id: agentKeyId
3708
+ };
3709
+ if (typeof tokenId === "string" && tokenId.length > 0) return {
3710
+ kind: "user",
3711
+ id: tokenId
3712
+ };
3713
+ if (identity.kind === "system" && identity.id.length > 0) return {
3714
+ kind: "system",
3715
+ id: identity.id
3716
+ };
3717
+ return null;
3718
+ }
3719
+ var CommittedWritesQueue = class {
3720
+ #hooks;
3721
+ #metric;
3722
+ #chains = /* @__PURE__ */ new Map();
3723
+ #warnings = /* @__PURE__ */ new Map();
3724
+ constructor(hooks, metric) {
3725
+ this.#hooks = hooks;
3726
+ this.#metric = metric;
3727
+ }
3728
+ /** Callers check this first, so a deployment with no hooks does no grouping at all. */
3729
+ get active() {
3730
+ return this.#hooks.length > 0;
3731
+ }
3732
+ /** Queue one committed transaction's events (or an announced set): one call per group per hook. */
3733
+ queue(events, actor) {
3734
+ if (this.#hooks.length === 0 || events.length === 0) return;
3735
+ const groups = /* @__PURE__ */ new Map();
3736
+ for (const e of events) {
3737
+ const key = JSON.stringify([
3738
+ e.ns,
3739
+ e.type,
3740
+ e.operation
3741
+ ]);
3742
+ const group = groups.get(key);
3743
+ if (group === void 0) groups.set(key, {
3744
+ namespace: e.ns,
3745
+ type: e.type,
3746
+ operation: e.operation,
3747
+ actor,
3748
+ ids: [e.id]
3749
+ });
3750
+ else group.ids.push(e.id);
3751
+ }
3752
+ for (const group of groups.values()) Object.freeze(group.ids);
3753
+ for (const { plugin, hook } of this.#hooks) for (const batch of groups.values()) this.#enqueue(plugin, hook, batch);
3754
+ }
3755
+ /**
3756
+ * Resolves once every call queued so far has finished. A hook that itself
3757
+ * mutates queues calls this does not wait for.
3758
+ */
3759
+ async settled() {
3760
+ await Promise.all(this.#chains.values());
3761
+ }
3762
+ warnings() {
3763
+ return [...this.#warnings.values()];
3764
+ }
3765
+ #enqueue(plugin, hook, batch) {
3766
+ const next = (this.#chains.get(plugin) ?? Promise.resolve()).then(async () => {
3767
+ await hook(batch);
3768
+ this.#warnings.delete(plugin);
3769
+ }).catch((err) => {
3770
+ const message = err instanceof Error ? err.message : String(err);
3771
+ this.#warnings.set(plugin, `post-write hook ${plugin} failed at ${(/* @__PURE__ */ new Date()).toISOString()}`);
3772
+ try {
3773
+ this.#metric("engine_post_write_hook_error", {
3774
+ plugin,
3775
+ error: message
3776
+ });
3777
+ } catch {}
3778
+ });
3779
+ this.#chains.set(plugin, next);
3780
+ }
3781
+ };
3782
+
3502
3783
  //#endregion
3503
3784
  //#region ../../packages/substrate-core/src/policy-evaluator.ts
3504
3785
  /**
@@ -3582,6 +3863,8 @@ var Registry = class extends RegistryBase {
3582
3863
  if (input.indexes !== void 0) entry.indexes = input.indexes;
3583
3864
  if (input.expectedSize !== void 0) entry.expectedSize = input.expectedSize;
3584
3865
  if (input.verb !== void 0) entry.verb = input.verb;
3866
+ if (input.batch !== void 0) entry.batch = input.batch;
3867
+ if (input.filterTarget !== void 0) entry.filterTarget = input.filterTarget;
3585
3868
  this.entries.set(name, entry);
3586
3869
  }
3587
3870
  /**
@@ -3605,6 +3888,8 @@ var Registry = class extends RegistryBase {
3605
3888
  if (input.indexes !== void 0) entry.indexes = input.indexes;
3606
3889
  if (input.expectedSize !== void 0) entry.expectedSize = input.expectedSize;
3607
3890
  if (input.verb !== void 0) entry.verb = input.verb;
3891
+ if (input.batch !== void 0) entry.batch = input.batch;
3892
+ if (input.filterTarget !== void 0) entry.filterTarget = input.filterTarget;
3608
3893
  this.entries.set(name, entry);
3609
3894
  }
3610
3895
  performUnregister(key) {
@@ -3838,6 +4123,7 @@ function validatePrimitiveKind(fieldKind, value, path, op) {
3838
4123
  if (!(value instanceof Date) && typeof value !== "string") throw new FilterValidationError("type_mismatch", `operator '${op}' expected Date or ISO string, got ${typeof value}`, path);
3839
4124
  const field = path.slice(path[0] === "where" ? 1 : 0, -1).join(".");
3840
4125
  if (value instanceof Date && Number.isNaN(value.getTime()) || typeof value === "string" && isImpossibleIsoTimestamp(value)) throw new FilterValidationError("type_mismatch", `operator '${op}' on '${field}': ${String(value)} is not a real date`, path);
4126
+ if (typeof value === "string" && !isIsoTimestamp(value)) throw new FilterValidationError("type_mismatch", `operator '${op}' on '${field}': ${JSON.stringify(value)} is not an ISO 8601 date or date-time`, path);
3841
4127
  return;
3842
4128
  }
3843
4129
  case "crossRef":
@@ -4526,6 +4812,12 @@ function deriveOperand(o, path, scope, h) {
4526
4812
 
4527
4813
  //#endregion
4528
4814
  //#region ../../packages/substrate-core/src/walk-types.ts
4815
+ /**
4816
+ * Every type a walk-grammar frame reads besides its seed (spec 2026-10-24-typed-edge-walks §2, §3):
4817
+ * each `_walk`, `_agg` and nested `{ _walk }` selection at any depth, with the
4818
+ * walk's own `where`. The engine evaluates each one's read policy before the
4819
+ * frame runs, so a walk can never read rows a top-level read could not.
4820
+ */
4529
4821
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4530
4822
  /** A `HopResolver` over one namespace's schema, sharing the validator's edge resolution. */
4531
4823
  function hopResolver(namespace, schemaOf) {
@@ -4557,55 +4849,18 @@ function walkedTypes(entry, seed, resolve) {
4557
4849
  unfiltered
4558
4850
  ]);
4559
4851
  if (!out.has(k)) out.set(k, {
4560
- type,
4561
- path,
4562
- ...where !== void 0 ? { where } : {},
4563
- ...unfiltered ? { unfiltered: true } : {}
4564
- });
4565
- return type;
4566
- };
4567
- const inWhere = (v, type, path) => {
4568
- if (Array.isArray(v)) {
4569
- v.forEach((c, i) => {
4570
- inWhere(c, type, [...path, String(i)]);
4571
- });
4572
- return;
4573
- }
4574
- if (!isObj(v)) return;
4575
- for (const [k, child] of Object.entries(v)) {
4576
- const at = [...path, k];
4577
- if ((k === "_walk" || k === "_agg") && isObj(child)) {
4578
- const far = hop(child, type, at);
4579
- inWhere(child.where, far, [...at, "where"]);
4580
- } else inWhere(child, type, at);
4581
- }
4582
- };
4583
- const inFields = (fields, type, path) => {
4584
- if (!isObj(fields)) return;
4585
- for (const [name, sel] of Object.entries(fields)) {
4586
- const at = [...path, name];
4587
- if (name === "_agg" && isObj(sel)) for (const [n, agg] of Object.entries(sel)) {
4588
- if (!isObj(agg)) continue;
4589
- const far = hop(agg, type, [...at, n]);
4590
- inWhere(agg.where, far, [
4591
- ...at,
4592
- n,
4593
- "where"
4594
- ]);
4595
- }
4596
- else if (isObj(sel) && isObj(sel._walk)) {
4597
- const walk = sel._walk;
4598
- const wp = [...at, "_walk"];
4599
- const where = walk.where !== void 0 && sel.where !== void 0 ? { AND: [walk.where, sel.where] } : walk.where ?? sel.where;
4600
- const far = hop(walk, type, wp, where);
4601
- inWhere(walk.where, far, [...wp, "where"]);
4602
- inWhere(sel.where, far, [...at, "where"]);
4603
- inFields(sel.fields, far, [...at, "fields"]);
4604
- }
4605
- }
4852
+ type,
4853
+ path,
4854
+ ...where !== void 0 ? { where } : {},
4855
+ ...unfiltered ? { unfiltered: true } : {}
4856
+ });
4857
+ return type;
4606
4858
  };
4607
- inWhere((isObj(entry.params) ? entry.params : {}).where, seed, ["where"]);
4608
- inFields(entry.fields, seed, ["fields"]);
4859
+ forEachWalkHop(entry, seed, ({ node, path, selection }, from) => {
4860
+ const sel = selection?.sel;
4861
+ const where = sel === void 0 ? node.where : node.where !== void 0 && sel.where !== void 0 ? { AND: [node.where, sel.where] } : node.where ?? sel.where;
4862
+ return hop(node, from, path, where);
4863
+ });
4609
4864
  return [...out.values()];
4610
4865
  }
4611
4866
 
@@ -4724,6 +4979,32 @@ function withNaturalOrder(params, entry, dataset) {
4724
4979
  };
4725
4980
  }
4726
4981
  /**
4982
+ * `fields` with each nested `{ _walk }` selection that names no `orderBy`
4983
+ * given its far type's natural order, at any depth: a nested list reads as a
4984
+ * top-level read of its type does, served by the eager `(crossRef, natural
4985
+ * order, id)` index; the datasets append `id` as the tie-break. Returns
4986
+ * `fields` itself when nothing is added.
4987
+ */
4988
+ function withNestedNaturalOrder(fields, from, resolve, orderOf) {
4989
+ if (typeof fields !== "object" || fields === null || Array.isArray(fields)) return fields;
4990
+ let changed = false;
4991
+ const out = Object.entries(fields).map(([name, sel]) => {
4992
+ const s = sel;
4993
+ if (name === "_agg" || typeof sel !== "object" || sel === null || !Object.hasOwn(s, "_walk")) return [name, sel];
4994
+ const far = resolve(s._walk, from, [name]);
4995
+ const sub = withNestedNaturalOrder(s.fields, far, resolve, orderOf);
4996
+ const ordered = Array.isArray(s.orderBy) && s.orderBy.length > 0;
4997
+ if (ordered && sub === s.fields) return [name, sel];
4998
+ changed = true;
4999
+ return [name, {
5000
+ ...s,
5001
+ fields: sub,
5002
+ ...ordered ? {} : { orderBy: [{ ...orderOf(far) }] }
5003
+ }];
5004
+ });
5005
+ return changed ? Object.fromEntries(out) : fields;
5006
+ }
5007
+ /**
4727
5008
  * The frame with its `where` / `orderBy` metadata spellings rewritten onto the
4728
5009
  * canonical columns (`createdBy` -> `createdById`, …). Given `hop`, every walk
4729
5010
  * subtree is rewritten against its far type too: a `_walk` / `_agg` where, a
@@ -4748,7 +5029,7 @@ function canonicalParams(params, fields, hop) {
4748
5029
  ...params.orderBy !== void 0 ? { orderBy: normaliseMetadataOrderBy(params.orderBy, fields) } : {}
4749
5030
  };
4750
5031
  }
4751
- const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
5032
+ const isPlainObject$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4752
5033
  /** A field selection with its `_agg` wheres and nested `{ _walk }` selections rewritten. */
4753
5034
  function canonicalFields(selection, hop) {
4754
5035
  if (selection === void 0) return selection;
@@ -4757,14 +5038,14 @@ function canonicalFields(selection, hop) {
4757
5038
  out ??= { ...selection };
4758
5039
  out[name] = v;
4759
5040
  };
4760
- for (const [name, sel] of Object.entries(selection)) if (name === "_agg" && isPlainObject(sel)) set(name, Object.fromEntries(Object.entries(sel).map(([n, a]) => [n, normaliseWalkNode(a, hop)])));
4761
- else if (isPlainObject(sel) && isPlainObject(sel._walk)) {
5041
+ for (const [name, sel] of Object.entries(selection)) if (name === "_agg" && isPlainObject$1(sel)) set(name, Object.fromEntries(Object.entries(sel).map(([n, a]) => [n, normaliseWalkNode(a, hop)])));
5042
+ else if (isPlainObject$1(sel) && isPlainObject$1(sel._walk)) {
4762
5043
  const far = hop(sel._walk);
4763
5044
  if (far === void 0) continue;
4764
5045
  set(name, {
4765
5046
  ...canonicalParams(sel, far.fields, far.hop),
4766
5047
  _walk: normaliseWalkNode(sel._walk, hop),
4767
- ...isPlainObject(sel.fields) ? { fields: canonicalFields(sel.fields, far.hop) } : {}
5048
+ ...isPlainObject$1(sel.fields) ? { fields: canonicalFields(sel.fields, far.hop) } : {}
4768
5049
  });
4769
5050
  }
4770
5051
  return out ?? selection;
@@ -5089,8 +5370,10 @@ var BridgeSubsystem = class {
5089
5370
  /**
5090
5371
  * Pre-dispatch filter validation (§5.2) for non-virtual `type` entries on a
5091
5372
  * query: validates where/orderBy and projected fields against the type's
5092
- * schema and dataset capabilities before the resolver runs. Mutations and
5093
- * virtual entries are exempt; their params are resolver-interpreted.
5373
+ * schema and dataset capabilities before the resolver runs. A by-filter
5374
+ * mutation (`filterTarget`) has its `where` validated as a query's on that
5375
+ * type. Other mutations and virtual entries are exempt; their params are
5376
+ * resolver-interpreted.
5094
5377
  *
5095
5378
  * Returns `true` when dispatch may proceed, `false` when an error was recorded
5096
5379
  * into the envelope. Errors other than `FilterValidationError` propagate.
@@ -5103,6 +5386,11 @@ var BridgeSubsystem = class {
5103
5386
  const PROJECTION_VIRTUAL_KEYS = /* @__PURE__ */ new Set(["_metadata", ...Object.keys(METADATA_FILTER_FIELDS)]);
5104
5387
  function runFilterGuard(deps, input) {
5105
5388
  const { envelope, key, entry, ns, name, operation, entryKind, isVirtual, dataset } = input;
5389
+ if (operation === "mutate" && input.filterTarget !== void 0 && dataset) {
5390
+ const where = entry.params?.where;
5391
+ if (where === void 0) return true;
5392
+ return validateAgainst(deps, envelope, key, ns, input.filterTarget, dataset, { where });
5393
+ }
5106
5394
  if (!(operation === "query" && entryKind === "type" && !isVirtual && dataset)) return true;
5107
5395
  const params = entry.params;
5108
5396
  const where = params?.where;
@@ -5135,11 +5423,24 @@ function runFilterGuard(deps, input) {
5135
5423
  }
5136
5424
  }
5137
5425
  const walks = usesWalkGrammar(entry);
5138
- if (where !== void 0 || orderBy !== void 0 || walks) try {
5139
- let typeSchema = deps.schemaFor(ns).types[name];
5426
+ if (where === void 0 && orderBy === void 0 && !walks) return true;
5427
+ return validateAgainst(deps, envelope, key, ns, name, dataset, {
5428
+ ...where !== void 0 ? { where } : {},
5429
+ ...orderBy !== void 0 ? { orderBy } : {},
5430
+ ...walks ? walkInput(entry) : {}
5431
+ });
5432
+ }
5433
+ /**
5434
+ * Validates `filter` against `typeName`'s published schema. Records the
5435
+ * refusal and returns false on a `FilterValidationError`; a type registered
5436
+ * but absent from the schema is let through with a diagnostic.
5437
+ */
5438
+ function validateAgainst(deps, envelope, key, ns, typeName, dataset, filter) {
5439
+ try {
5440
+ let typeSchema = deps.schemaFor(ns).types[typeName];
5140
5441
  if (typeSchema === void 0) {
5141
5442
  deps.invalidateSchemaCaches(ns);
5142
- typeSchema = deps.schemaFor(ns).types[name];
5443
+ typeSchema = deps.schemaFor(ns).types[typeName];
5143
5444
  }
5144
5445
  if (typeSchema === void 0) {
5145
5446
  deps.metric("engine_filter_validation_skipped", {
@@ -5149,19 +5450,17 @@ function runFilterGuard(deps, input) {
5149
5450
  envelope._diagnostics ??= {};
5150
5451
  envelope._diagnostics[key] = {
5151
5452
  ...envelope._diagnostics[key] ?? {},
5152
- filterValidationSkipped: `type '${name}' is registered but absent from the '${ns}' schema`
5453
+ filterValidationSkipped: `type '${typeName}' is registered but absent from the '${ns}' schema`
5153
5454
  };
5154
5455
  } else {
5155
5456
  const types = deps.schemaFor(ns).types;
5156
5457
  validateFilter({
5157
- ...where !== void 0 ? { where } : {},
5158
- ...orderBy !== void 0 ? { orderBy } : {},
5159
- ...walks ? walkInput(entry) : {},
5458
+ ...filter,
5160
5459
  typeSchema,
5161
5460
  capabilities: dataset.capabilities,
5162
5461
  schemaOf: (type) => Object.hasOwn(types, type) ? types[type] : void 0,
5163
5462
  namespace: ns,
5164
- typeName: name
5463
+ typeName
5165
5464
  });
5166
5465
  }
5167
5466
  } catch (err) {
@@ -5355,7 +5654,11 @@ function partitionMutateByTxScope(singleFrameKeys, parsedByKey, datasets) {
5355
5654
  */
5356
5655
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5357
5656
  function shapeResult(input) {
5358
- const { envelope, key, entry, ctx, decision, result, metric } = input;
5657
+ const { envelope, key, entry, ctx, result, metric } = input;
5658
+ const decision = input.resolverFiltered === true ? {
5659
+ ...input.decision,
5660
+ obligations: []
5661
+ } : input.decision;
5359
5662
  if (isAsyncIterable(result)) {
5360
5663
  addError(envelope, [key], `resolver for '${key}' returned an async iterable; use engine.stream instead`, "streamable_on_oneshot");
5361
5664
  metric("engine_streamable_on_oneshot", { key });
@@ -5954,7 +6257,7 @@ var StreamSubsystem = class {
5954
6257
  //#region ../../packages/substrate-core/src/engine/subscribe.ts
5955
6258
  /**
5956
6259
  * SubscribeSubsystem — owns the live subscription bus and WriteEvent fanout
5957
- * (§5.4, §5.13). Mutate feeds it through `dispatchWrite(event)`.
6260
+ * (§5.4, §5.13). Mutate feeds it through `dispatchWrites(events)`.
5958
6261
  */
5959
6262
  /**
5960
6263
  * Documented top-level params keys for a subscribe frame. Anything else is
@@ -6183,6 +6486,15 @@ var SubscribeSubsystem = class {
6183
6486
  this.#emitToSubscription(entry, event);
6184
6487
  }
6185
6488
  }
6489
+ /**
6490
+ * `dispatchWrite` for every event of one committed mutate, in emit order.
6491
+ * Not grouped by type: one subscription can span several types under one
6492
+ * id and `onFrame`, and an idle entry's first frame is delivered
6493
+ * synchronously, so grouping would reorder that subscription's wire.
6494
+ */
6495
+ dispatchWrites(events) {
6496
+ for (const event of events) this.dispatchWrite(event);
6497
+ }
6186
6498
  #buildSubscribeContext(caller) {
6187
6499
  const base = {
6188
6500
  identity: caller.identity ?? null,
@@ -6790,6 +7102,42 @@ var BatchedFrameRefusal = class extends Error {
6790
7102
  }
6791
7103
  };
6792
7104
  /**
7105
+ * A batch resolver refused with a frame error that names no element (on pg, a
7106
+ * `unique_violation` from its set-wise write). `#runArrayEntry` rolls the
7107
+ * attempt back and re-runs the array per element to find the element and the
7108
+ * envelope sequential dispatch gives.
7109
+ */
7110
+ var BatchRefusalWithoutIndex = class extends Error {
7111
+ cause;
7112
+ name = "BatchRefusalWithoutIndex";
7113
+ constructor(cause) {
7114
+ super(cause.message);
7115
+ this.cause = cause;
7116
+ }
7117
+ };
7118
+ function slotResultOf(scratch, key) {
7119
+ const entry = {};
7120
+ if (key in scratch.data) entry.data = scratch.data[key];
7121
+ const shape = scratch.shapes[key];
7122
+ if (shape === "single" || shape === "list") entry.shape = shape;
7123
+ if (scratch.errors !== void 0 && scratch.errors.length > 0) entry.errors = scratch.errors;
7124
+ return entry;
7125
+ }
7126
+ function cachedSlotResult(slot) {
7127
+ return {
7128
+ ...slot.data !== void 0 ? { data: slot.data } : {},
7129
+ ...slot.shape !== void 0 ? { shape: slot.shape } : {},
7130
+ ...slot.errors !== void 0 ? { errors: slot.errors } : {}
7131
+ };
7132
+ }
7133
+ /** Hand `o` to the resolve hook; a metrics sink must never change what the caller gets. */
7134
+ function observe(hook, o) {
7135
+ try {
7136
+ const ret = hook(o);
7137
+ if (typeof ret?.then === "function") Promise.resolve(ret).catch(() => {});
7138
+ } catch {}
7139
+ }
7140
+ /**
6793
7141
  * Refusal prose. A missing namespace and a namespace narrowed to the wrong
6794
7142
  * capability are different operator problems, so they get different messages.
6795
7143
  */
@@ -6814,6 +7162,14 @@ var Engine = class {
6814
7162
  #edges;
6815
7163
  #metric;
6816
7164
  #onResolve;
7165
+ /** Built once rather than per entry: every frame entry reaches the filter guard. */
7166
+ #guardDeps = {
7167
+ schemaFor: (ns) => this.schemaFor(ns),
7168
+ invalidateSchemaCaches: (ns) => this.invalidateSchemaCaches(ns),
7169
+ metric: (name, payload) => this.#metric(name, payload)
7170
+ };
7171
+ #committed;
7172
+ #filterWriteLimits;
6817
7173
  #shapeRecorder;
6818
7174
  #idempotency;
6819
7175
  /**
@@ -6836,7 +7192,7 @@ var Engine = class {
6836
7192
  /**
6837
7193
  * Live subscription subsystem (§5.4, §5.13). Owns the subscription bus, the
6838
7194
  * back-pressure queue, and the WriteEvent fanout. The mutate path calls
6839
- * `this.#subscribe.dispatchWrite(event)` after each write event; everything
7195
+ * `this.#subscribe.dispatchWrites(events)` after the write events; everything
6840
7196
  * else lives behind the subsystem's surface.
6841
7197
  */
6842
7198
  #subscribe;
@@ -6850,7 +7206,9 @@ var Engine = class {
6850
7206
  this.#edges = opts.edges;
6851
7207
  this.#metric = opts.metric ?? (() => {});
6852
7208
  this.#onResolve = opts.onResolve;
7209
+ this.#committed = new CommittedWritesQueue(opts.committedWritesHooks ?? [], this.#metric);
6853
7210
  this.#shapeRecorder = opts.shapeRecorder;
7211
+ this.#filterWriteLimits = opts.filterWriteLimits ?? DEFAULT_FILTER_WRITE_LIMITS;
6854
7212
  this.#idempotency = opts.idempotency !== void 0 ? {
6855
7213
  store: opts.idempotency.store,
6856
7214
  defaultTtlMs: opts.idempotency.defaultTtlMs ?? 864e5
@@ -7285,13 +7643,23 @@ var Engine = class {
7285
7643
  const onWrite = (event) => {
7286
7644
  writeBatch.push(event);
7287
7645
  };
7646
+ const hooked = this.#committed.active;
7647
+ const actor = hooked ? actorOf(identity) : null;
7648
+ let announced = 0;
7649
+ const commit = () => {
7650
+ const events = writeBatch.slice(announced);
7651
+ this.#subscribe.dispatchWrites(events);
7652
+ if (hooked) this.#committed.queue(events, actor);
7653
+ announced = writeBatch.length;
7654
+ };
7288
7655
  await this.#dispatchSingleFrameLocal(envelope, input.frame, singleFrameKeys, parsedByKey, partition, ctx, onWrite, signal);
7656
+ commit();
7289
7657
  for (const key of nonEmptyArrayKeys) {
7290
7658
  const frames = input.frame[key];
7291
7659
  await this.#runArrayEntry(envelope, key, parsedByKey.get(key) ?? null, frames, ctx, onWrite, signal);
7660
+ commit();
7292
7661
  }
7293
7662
  await Promise.all(bridgePromises);
7294
- for (const event of writeBatch) this.#subscribe.dispatchWrite(event);
7295
7663
  return this.#finaliseMutateEnvelope(envelope, keys, idempotencyResolution, callerKey);
7296
7664
  }
7297
7665
  /**
@@ -7527,18 +7895,13 @@ var Engine = class {
7527
7895
  const caller = callerId !== void 0 ? { caller: callerId } : {};
7528
7896
  const before = envelope.errors?.length ?? 0;
7529
7897
  const t0 = performance.now();
7530
- const emit = (o) => {
7531
- try {
7532
- const ret = hook({
7533
- key: obsKey,
7534
- kind,
7535
- durationMs: performance.now() - t0,
7536
- ...caller,
7537
- ...o
7538
- });
7539
- if (typeof ret?.then === "function") Promise.resolve(ret).catch(() => {});
7540
- } catch {}
7541
- };
7898
+ const emit = (o) => observe(hook, {
7899
+ key: obsKey,
7900
+ kind,
7901
+ durationMs: performance.now() - t0,
7902
+ ...caller,
7903
+ ...o
7904
+ });
7542
7905
  let refused;
7543
7906
  try {
7544
7907
  refused = await this.#runEntryInner(envelope, key, ...rest);
@@ -7578,17 +7941,24 @@ var Engine = class {
7578
7941
  };
7579
7942
  return hopFrom(from);
7580
7943
  }
7944
+ /** Hop resolution, field declarations and natural order over namespace `ns`'s schema. */
7945
+ #walkTools(ns) {
7946
+ const types = this.schemaFor(ns).types;
7947
+ const schemaOf = (t) => Object.hasOwn(types, t) ? types[t] : void 0;
7948
+ return {
7949
+ resolve: hopResolver(ns, schemaOf),
7950
+ fieldsOf: (t) => schemaOf(t)?.fields,
7951
+ naturalOrder: (t) => naturalOrderOf(schemaOf(t) ?? {})
7952
+ };
7953
+ }
7581
7954
  /** The walk sites of a walk-grammar query frame, or undefined for an ordinary one. */
7582
7955
  #walkSitesOf(frame, ns, seed) {
7583
7956
  if (!usesWalkGrammar(frame)) return void 0;
7584
- const types = this.schemaFor(ns).types;
7585
- const schemaOf = (t) => Object.hasOwn(types, t) ? types[t] : void 0;
7586
- const resolve = hopResolver(ns, schemaOf);
7957
+ const tools = this.#walkTools(ns);
7587
7958
  try {
7588
7959
  return {
7589
- sites: walkSites(frame, seed, resolve),
7590
- resolve,
7591
- fieldsOf: (t) => schemaOf(t)?.fields
7960
+ sites: walkSites(frame, seed, tools.resolve, tools.naturalOrder),
7961
+ ...tools
7592
7962
  };
7593
7963
  } catch {
7594
7964
  return;
@@ -7618,7 +7988,8 @@ var Engine = class {
7618
7988
  entry: frame,
7619
7989
  seed,
7620
7990
  resolve: scan.resolve,
7621
- fieldsOf: scan.fieldsOf
7991
+ fieldsOf: scan.fieldsOf,
7992
+ naturalOrder: scan.naturalOrder
7622
7993
  }, (t) => byType.get(t) ?? []);
7623
7994
  }
7624
7995
  /**
@@ -7657,34 +8028,39 @@ var Engine = class {
7657
8028
  }
7658
8029
  return false;
7659
8030
  }
7660
- async #runEntryInner(envelope, key, entry, ctxBase, operation, tx, txEdges, parsed, onWrite, signal, afterTx, txEntries) {
8031
+ /**
8032
+ * Everything a frame entry does before its resolver runs: the grant, the
8033
+ * lookups, policy, the walk refusals, the filter guard, the cursor and the
8034
+ * resolver args. Synchronous. Returns null once it has recorded a refusal.
8035
+ */
8036
+ #prepareEntry(envelope, key, entry, ctxBase, operation, tx, txEdges, parsed, onWrite, signal, afterTx, txEntries) {
7661
8037
  if (!parsed) {
7662
8038
  addError(envelope, [key], `unqualified frame key '${key}' — expected '<ns>/<name>'`, "unqualified_key");
7663
8039
  this.#metric("engine_unqualified_key", key);
7664
- return false;
8040
+ return null;
7665
8041
  }
7666
8042
  const { ns, name } = parsed;
7667
- if (this.#refuseUngranted(envelope, key, ns, ctxBase.identity, operation)) return false;
8043
+ if (this.#refuseUngranted(envelope, key, ns, ctxBase.identity, operation)) return null;
7668
8044
  if (this.#tombstoned.has(ns)) {
7669
8045
  addError(envelope, [key], `namespace '${ns}' was deleted`, "namespace_tombstoned");
7670
8046
  this.#metric("engine_namespace_tombstoned_reject", {
7671
8047
  key,
7672
8048
  ns
7673
8049
  });
7674
- return false;
8050
+ return null;
7675
8051
  }
7676
8052
  const nsCfg = this.#namespaces.get(ns);
7677
8053
  if (!nsCfg) {
7678
8054
  addError(envelope, [key], `unknown namespace '${ns}'`, "unknown_namespace");
7679
8055
  this.#metric("engine_unknown_namespace", ns);
7680
- return false;
8056
+ return null;
7681
8057
  }
7682
8058
  const isVirtual = nsCfg.virtual === true;
7683
8059
  const dataset = isVirtual ? void 0 : tx ?? this.#datasets.get(ns);
7684
8060
  if (!isVirtual && !dataset) {
7685
8061
  addError(envelope, [key], `unknown namespace '${ns}'`, "unknown_namespace");
7686
8062
  this.#metric("engine_unknown_namespace", ns);
7687
- return false;
8063
+ return null;
7688
8064
  }
7689
8065
  const registryEntry = nsCfg.registry.get(name);
7690
8066
  if (!registryEntry) {
@@ -7693,9 +8069,10 @@ var Engine = class {
7693
8069
  ns,
7694
8070
  name
7695
8071
  });
7696
- return false;
8072
+ return null;
7697
8073
  }
7698
- const frame = operation === "query" && registryEntry.kind === "type" ? withCanonicalMetadataFilters(entry, registryEntry.fields, usesWalkGrammar(entry) ? this.#metadataHop(ns, name) : void 0) : entry;
8074
+ const filterTarget = operation === "mutate" ? registryEntry.filterTarget : void 0;
8075
+ const frame = operation === "query" && registryEntry.kind === "type" ? withCanonicalMetadataFilters(entry, registryEntry.fields, usesWalkGrammar(entry) ? this.#metadataHop(ns, name) : void 0) : filterTarget !== void 0 ? withCanonicalMetadataFilters(entry, nsCfg.registry.get(filterTarget)?.fields ?? {}) : entry;
7699
8076
  const ctx = {
7700
8077
  ...ctxBase,
7701
8078
  namespace: ns,
@@ -7711,34 +8088,34 @@ var Engine = class {
7711
8088
  key,
7712
8089
  reason: decision.reason
7713
8090
  });
7714
- return false;
8091
+ return null;
7715
8092
  }
7716
8093
  if ((decision.obligations?.length ?? 0) > 0) delete args.fields;
8094
+ if (filterTarget !== void 0) args.filterWriteLimits = this.#filterWriteLimits;
7717
8095
  if (operation === "mutate") {
7718
- const walkPath = walkGrammarPath({ fields: frame.fields });
8096
+ const walkPath = walkGrammarPath({
8097
+ fields: frame.fields,
8098
+ ...filterTarget !== void 0 ? { params: { where: frame.params?.where } } : {}
8099
+ });
7719
8100
  if (walkPath) {
7720
8101
  addError(envelope, [key, ...walkPath], "walks are not available in a mutation", WALKS_IN_MUTATION);
7721
- return false;
8102
+ return null;
7722
8103
  }
7723
8104
  } else if (isVirtual) {
7724
8105
  const walkPath = walkGrammarPath(frame);
7725
8106
  if (walkPath) {
7726
8107
  addError(envelope, [key, ...walkPath], "walks are not available on virtual types", WALK_UNSUPPORTED_REF);
7727
- return false;
8108
+ return null;
7728
8109
  }
7729
8110
  }
7730
8111
  if (operation === "query" && registryEntry.kind === "type" && !isVirtual && dataset?.capabilities.walks !== true) {
7731
8112
  const walkPath = walkGrammarPath(frame);
7732
8113
  if (walkPath) {
7733
8114
  addError(envelope, [key, ...walkPath], `the '${ns}' store does not answer walks`, WALKS_UNSUPPORTED_STORE);
7734
- return false;
8115
+ return null;
7735
8116
  }
7736
8117
  }
7737
- if (!runFilterGuard({
7738
- schemaFor: (ns) => this.schemaFor(ns),
7739
- invalidateSchemaCaches: (ns) => this.invalidateSchemaCaches(ns),
7740
- metric: (name, payload) => this.#metric(name, payload)
7741
- }, {
8118
+ if (!runFilterGuard(this.#guardDeps, {
7742
8119
  envelope,
7743
8120
  key,
7744
8121
  entry: frame,
@@ -7747,9 +8124,10 @@ var Engine = class {
7747
8124
  operation,
7748
8125
  entryKind: registryEntry.kind,
7749
8126
  isVirtual,
7750
- dataset
7751
- })) return false;
7752
- if (operation === "query" && registryEntry.kind === "type" && this.#refuseWalkPolicy(envelope, key, frame, ns, name, ctx, decision)) return false;
8127
+ dataset,
8128
+ ...filterTarget !== void 0 ? { filterTarget } : {}
8129
+ })) return null;
8130
+ if (operation === "query" && registryEntry.kind === "type" && this.#refuseWalkPolicy(envelope, key, frame, ns, name, ctx, decision)) return null;
7753
8131
  if (operation === "query" && !isVirtual) {
7754
8132
  const params = withNaturalOrder(args.params, registryEntry, dataset);
7755
8133
  if (params !== void 0) args.params = params;
@@ -7759,7 +8137,7 @@ var Engine = class {
7759
8137
  const opened = (decision.obligations?.length ?? 0) > 0 && !isSealedCursor(cursor) ? null : openCursor(cursor);
7760
8138
  if (opened === null) {
7761
8139
  addError(envelope, [key], "cursor is not one this server issued", "invalid_cursor");
7762
- return false;
8140
+ return null;
7763
8141
  }
7764
8142
  args.params = {
7765
8143
  ...args.params,
@@ -7767,6 +8145,27 @@ var Engine = class {
7767
8145
  };
7768
8146
  }
7769
8147
  const walkScan = operation === "query" && registryEntry.kind === "type" && !isVirtual ? this.#walkSitesOf(frame, ns, name) : void 0;
8148
+ if (operation === "query" && registryEntry.kind === "type" && !isVirtual && args.fields !== void 0 && usesWalkGrammar(frame)) {
8149
+ const tools = walkScan ?? this.#walkTools(ns);
8150
+ args.fields = withNestedNaturalOrder(args.fields, name, tools.resolve, tools.naturalOrder);
8151
+ }
8152
+ return {
8153
+ registryEntry,
8154
+ frame,
8155
+ ctx,
8156
+ args,
8157
+ decision,
8158
+ ns,
8159
+ name,
8160
+ isVirtual,
8161
+ dataset,
8162
+ walkScan
8163
+ };
8164
+ }
8165
+ async #runEntryInner(envelope, key, entry, ctxBase, operation, tx, txEdges, parsed, onWrite, signal, afterTx, txEntries) {
8166
+ const prepared = this.#prepareEntry(envelope, key, entry, ctxBase, operation, tx, txEdges, parsed, onWrite, signal, afterTx, txEntries);
8167
+ if (prepared === null) return false;
8168
+ const { registryEntry, frame, ctx, args, decision, ns, name, isVirtual, dataset, walkScan } = prepared;
7770
8169
  let result;
7771
8170
  const t0 = performance.now();
7772
8171
  try {
@@ -7813,7 +8212,8 @@ var Engine = class {
7813
8212
  ctx,
7814
8213
  decision,
7815
8214
  result,
7816
- metric: (name, payload) => this.#metric(name, payload)
8215
+ metric: this.#metric,
8216
+ resolverFiltered: registryEntry.filterTarget !== void 0
7817
8217
  });
7818
8218
  return false;
7819
8219
  }
@@ -7939,52 +8339,66 @@ var Engine = class {
7939
8339
  };
7940
8340
  else slots[i] = { cached: false };
7941
8341
  }
7942
- const arrayWriteBatch = [];
8342
+ let arrayWriteBatch = [];
7943
8343
  const arrayOnWrite = (event) => {
7944
8344
  arrayWriteBatch.push(event);
7945
8345
  };
7946
- const scratchResults = new Array(frames.length);
7947
- let frameError;
7948
- let failedIndex;
7949
- const settled = [];
7950
- try {
7951
- await this.#withRowsAndEdgesTx(dataset, ns, async (txDs, txEdges) => {
7952
- for (let i = 0; i < frames.length; i++) {
7953
- const slot = slots[i];
7954
- if (slot.cached) {
7955
- scratchResults[i] = {
7956
- ...slot.data !== void 0 ? { data: slot.data } : {},
7957
- ...slot.shape !== void 0 ? { shape: slot.shape } : {},
7958
- ...slot.errors !== void 0 ? { errors: slot.errors } : {}
7959
- };
7960
- continue;
8346
+ let scratchResults = new Array(frames.length);
8347
+ const batch = nsCfg.registry.get(parsed.name)?.batch;
8348
+ /** One attempt in its own transaction: `batch` once, or the per-element loop. */
8349
+ const attempt = async (useBatch) => {
8350
+ let failedIndex;
8351
+ let frameError;
8352
+ const settled = [];
8353
+ try {
8354
+ await this.#withRowsAndEdgesTx(dataset, ns, async (txDs, txEdges) => {
8355
+ if (useBatch && batch !== void 0) {
8356
+ await this.#runBatch(batch, key, parsed, frames, slots, scratchResults, ctxBase, txDs, txEdges, arrayOnWrite, signal, (fn) => settled.push(fn), envelope.schemaVersion);
8357
+ return;
7961
8358
  }
7962
- const frame = frames[i];
7963
- const scratch = {
7964
- schemaVersion: envelope.schemaVersion,
7965
- data: {},
7966
- shapes: {}
7967
- };
7968
- failedIndex = i;
7969
- await this.#runEntry(scratch, key, frame, ctxBase, "mutate", txDs, txEdges, parsed, arrayOnWrite, signal, (fn) => settled.push(fn), frames.length);
7970
- failedIndex = void 0;
7971
- const entry = {};
7972
- if (key in scratch.data) entry.data = scratch.data[key];
7973
- const shape = scratch.shapes[key];
7974
- if (shape === "single" || shape === "list") entry.shape = shape;
7975
- if (scratch.errors !== void 0 && scratch.errors.length > 0) {
7976
- entry.errors = scratch.errors;
7977
- scratchResults[i] = entry;
8359
+ for (let i = 0; i < frames.length; i++) {
8360
+ const slot = slots[i];
8361
+ if (slot.cached) {
8362
+ scratchResults[i] = cachedSlotResult(slot);
8363
+ continue;
8364
+ }
8365
+ const frame = frames[i];
8366
+ const scratch = {
8367
+ schemaVersion: envelope.schemaVersion,
8368
+ data: {},
8369
+ shapes: {}
8370
+ };
7978
8371
  failedIndex = i;
7979
- throw new BatchedFrameRefusal(scratch.errors);
8372
+ await this.#runEntry(scratch, key, frame, ctxBase, "mutate", txDs, txEdges, parsed, arrayOnWrite, signal, (fn) => settled.push(fn), frames.length);
8373
+ failedIndex = void 0;
8374
+ const entry = slotResultOf(scratch, key);
8375
+ scratchResults[i] = entry;
8376
+ if (entry.errors !== void 0) {
8377
+ failedIndex = i;
8378
+ throw new BatchedFrameRefusal(entry.errors);
8379
+ }
7980
8380
  }
7981
- scratchResults[i] = entry;
8381
+ });
8382
+ } catch (err) {
8383
+ let thrown = err;
8384
+ if (useBatch && isBatchElementError(err)) {
8385
+ failedIndex = err.index;
8386
+ thrown = err.cause;
7982
8387
  }
7983
- });
7984
- } catch (err) {
7985
- frameError = err instanceof Error ? err : new Error(String(err));
8388
+ frameError = thrown instanceof Error ? thrown : new Error(String(thrown));
8389
+ }
8390
+ await this.#runSettled(settled, frameError === void 0);
8391
+ return {
8392
+ frameError,
8393
+ failedIndex
8394
+ };
8395
+ };
8396
+ let { frameError, failedIndex } = await attempt(batch !== void 0);
8397
+ if (frameError instanceof BatchRefusalWithoutIndex) {
8398
+ arrayWriteBatch = [];
8399
+ scratchResults = new Array(frames.length);
8400
+ ({frameError, failedIndex} = await attempt(false));
7986
8401
  }
7987
- await this.#runSettled(settled, frameError === void 0);
7988
8402
  if (frameError !== void 0) {
7989
8403
  const atSuffix = failedIndex !== void 0 ? ` at frame[${failedIndex}]` : "";
7990
8404
  if (frameError instanceof BatchedFrameRefusal) for (const e of frameError.frameErrors) addError(envelope, e.path ?? [key], e.message, e.code);
@@ -8044,6 +8458,169 @@ var Engine = class {
8044
8458
  for (const event of arrayWriteBatch) onWrite(event);
8045
8459
  }
8046
8460
  /**
8461
+ * The batch branch of `#runArrayEntry`, inside its transaction. Prepares
8462
+ * every uncached element as `#runEntryInner` would, calls `batch` once with
8463
+ * their args in slot order, then shapes each result under its own frame and
8464
+ * decision. A refusal at slot `i` throws `BatchElementError(i, …)` with a
8465
+ * `BatchedFrameRefusal` carrying the element's own errors, or the raw cause
8466
+ * when it is not a frame refusal; `#runArrayEntry` unwraps it into today's
8467
+ * rollback envelope. Cached slots are filled and skipped; when every slot is
8468
+ * cached, `batch` is not called.
8469
+ */
8470
+ async #runBatch(batch, key, parsed, frames, slots, results, ctxBase, txDs, txEdges, onWrite, signal, afterTx, schemaVersion) {
8471
+ const hook = this.#onResolve;
8472
+ const callerId = ctxBase.identity?.id;
8473
+ const t0 = performance.now();
8474
+ let batchSize = 0;
8475
+ const report = (ok, durationMs, batchIndex, err) => {
8476
+ if (hook === void 0) return;
8477
+ observe(hook, {
8478
+ key,
8479
+ kind: "mutate",
8480
+ durationMs,
8481
+ ok,
8482
+ ...batchIndex !== void 0 ? {
8483
+ batchSize,
8484
+ batchIndex
8485
+ } : {},
8486
+ ...callerId !== void 0 ? { caller: callerId } : {},
8487
+ ...err?.code !== void 0 ? { code: err.code } : {},
8488
+ ...err !== void 0 ? { message: err.message } : {}
8489
+ });
8490
+ };
8491
+ const at = [];
8492
+ const prepared = [];
8493
+ for (let i = 0; i < frames.length; i++) {
8494
+ const slot = slots[i];
8495
+ if (slot.cached) {
8496
+ results[i] = cachedSlotResult(slot);
8497
+ continue;
8498
+ }
8499
+ const scratch = {
8500
+ schemaVersion,
8501
+ data: {},
8502
+ shapes: {}
8503
+ };
8504
+ let p;
8505
+ try {
8506
+ p = this.#prepareEntry(scratch, key, frames[i], ctxBase, "mutate", txDs, txEdges, parsed, onWrite, signal, afterTx, frames.length);
8507
+ } catch (err) {
8508
+ report(false, performance.now() - t0, void 0, {
8509
+ code: "exception",
8510
+ message: err instanceof Error ? err.message : String(err)
8511
+ });
8512
+ throw new BatchElementError(i, err);
8513
+ }
8514
+ if (p === null) {
8515
+ const refused = slotResultOf(scratch, key);
8516
+ results[i] = refused;
8517
+ const errors = refused.errors ?? [];
8518
+ report(false, performance.now() - t0, void 0, errors[0]);
8519
+ throw new BatchElementError(i, new BatchedFrameRefusal(errors));
8520
+ }
8521
+ at.push(i);
8522
+ prepared.push(p);
8523
+ }
8524
+ if (prepared.length === 0) return;
8525
+ const n = prepared.length;
8526
+ batchSize = n;
8527
+ const tb = performance.now();
8528
+ let rows;
8529
+ try {
8530
+ rows = await batch(prepared[0].ctx, prepared.map((p) => p.args));
8531
+ } catch (err) {
8532
+ const ms = performance.now() - tb;
8533
+ const slot = isBatchElementError(err) ? at[err.index] : void 0;
8534
+ if (!isBatchElementError(err) && (isResolverFrameError(err) || isRestrictViolation(err))) {
8535
+ report(false, ms, 0, {
8536
+ code: isRestrictViolation(err) ? "restrict_violation" : err.code,
8537
+ message: err.message
8538
+ });
8539
+ throw new BatchRefusalWithoutIndex(err);
8540
+ }
8541
+ if (!isBatchElementError(err) || slot === void 0) {
8542
+ const cause = isBatchElementError(err) ? /* @__PURE__ */ new Error(`batch resolver for '${key}' refused element ${err.index} of ${n}`) : err;
8543
+ report(false, ms, 0, {
8544
+ code: "exception",
8545
+ message: cause instanceof Error ? cause.message : String(cause)
8546
+ });
8547
+ throw cause;
8548
+ }
8549
+ const cause = err.cause;
8550
+ const refusal = this.#batchFrameRefusal(key, cause);
8551
+ for (let j = 0; j < err.index; j++) report(true, ms, j);
8552
+ report(false, ms, err.index, {
8553
+ code: refusal?.frameErrors[0]?.code ?? "exception",
8554
+ message: cause instanceof Error ? cause.message : String(cause)
8555
+ });
8556
+ throw new BatchElementError(slot, refusal ?? cause);
8557
+ }
8558
+ const ms = performance.now() - tb;
8559
+ if (!Array.isArray(rows) || rows.length !== n) {
8560
+ const wrong = /* @__PURE__ */ new Error(`batch resolver for '${key}' returned ${Array.isArray(rows) ? rows.length : typeof rows} results for ${n} elements`);
8561
+ report(false, ms, 0, {
8562
+ code: "exception",
8563
+ message: wrong.message
8564
+ });
8565
+ throw wrong;
8566
+ }
8567
+ for (let j = 0; j < n; j++) {
8568
+ const p = prepared[j];
8569
+ const i = at[j];
8570
+ const scratch = {
8571
+ schemaVersion,
8572
+ data: {},
8573
+ shapes: {}
8574
+ };
8575
+ shapeResult({
8576
+ envelope: scratch,
8577
+ key,
8578
+ entry: p.frame,
8579
+ ctx: p.ctx,
8580
+ decision: p.decision,
8581
+ result: rows[j] ?? null,
8582
+ metric: this.#metric,
8583
+ resolverFiltered: p.registryEntry.filterTarget !== void 0
8584
+ });
8585
+ const shaped = slotResultOf(scratch, key);
8586
+ results[i] = shaped;
8587
+ if (shaped.errors !== void 0) {
8588
+ report(false, ms, j, shaped.errors[0]);
8589
+ throw new BatchElementError(i, new BatchedFrameRefusal(shaped.errors));
8590
+ }
8591
+ report(true, ms, j);
8592
+ }
8593
+ }
8594
+ /**
8595
+ * A batch's `ResolverFrameError` or `RestrictViolation` as the per-element
8596
+ * resolver catch records it: its own code at `[key]`, with the same metric.
8597
+ * Undefined for any other error.
8598
+ */
8599
+ #batchFrameRefusal(key, cause) {
8600
+ if (isRestrictViolation(cause)) {
8601
+ this.#metric("engine_restrict_violation", {
8602
+ key,
8603
+ blockedBy: cause.blockedBy.length
8604
+ });
8605
+ return new BatchedFrameRefusal([{
8606
+ message: cause.message,
8607
+ path: [key],
8608
+ code: "restrict_violation"
8609
+ }]);
8610
+ }
8611
+ if (isResolverFrameError(cause)) {
8612
+ this.#metric("engine_resolver_frame_error", {
8613
+ key,
8614
+ code: cause.code
8615
+ });
8616
+ return new BatchedFrameRefusal([{
8617
+ message: cause.message,
8618
+ path: [key],
8619
+ code: cause.code
8620
+ }]);
8621
+ }
8622
+ }
8623
+ /**
8047
8624
  * Register a subscription (§5.4) by delegating to the SubscribeSubsystem.
8048
8625
  * The subsystem owns the bus, the back-pressure queue, and the WriteEvent
8049
8626
  * fanout — see subscribe.ts for the full contract.
@@ -8052,6 +8629,25 @@ var Engine = class {
8052
8629
  return this.#subscribe.subscribe(input);
8053
8630
  }
8054
8631
  /**
8632
+ * Announce writes committed outside `mutate` (a server-internal writer): they
8633
+ * reach subscribers, then the coordinators' `onCommittedWrites` hooks, as a
8634
+ * commit through `mutate` would. This is not a transaction and checks
8635
+ * nothing: the caller guarantees `events` are already committed.
8636
+ */
8637
+ announceWrites(events, actor) {
8638
+ this.#subscribe.dispatchWrites(events);
8639
+ this.#committed.queue(events, actor);
8640
+ return Promise.resolve();
8641
+ }
8642
+ /** Resolves once every post-write hook call queued so far has finished. */
8643
+ hooksSettled() {
8644
+ return this.#committed.settled();
8645
+ }
8646
+ /** The last failure per plugin whose post-write hook has not succeeded since. */
8647
+ postWriteWarnings() {
8648
+ return this.#committed.warnings();
8649
+ }
8650
+ /**
8055
8651
  * Live count of active subscription entries. Delegates to the
8056
8652
  * SubscribeSubsystem, which owns the authoritative map.
8057
8653
  */
@@ -8360,6 +8956,15 @@ var MemoryEdgesStore = class {
8360
8956
  this.#indexAdd(edge);
8361
8957
  return this.#copy(edge);
8362
8958
  }
8959
+ async writeMany(inputs) {
8960
+ const out = [];
8961
+ for (const input of inputs) out.push(await this.write(input));
8962
+ return out;
8963
+ }
8964
+ async tombstoneMany(ids, at) {
8965
+ const stamp = at ?? this.now();
8966
+ for (const id of ids) await this.tombstone(id, stamp);
8967
+ }
8363
8968
  async tombstone(id, at) {
8364
8969
  const existing = this.edges.get(id);
8365
8970
  if (!existing) return;
@@ -8387,11 +8992,14 @@ var MemoryEdgesStore = class {
8387
8992
  return this.#liveByIndex(this.#toIndex, refKey(ref));
8388
8993
  }
8389
8994
  async findEdgesToMany(refs) {
8390
- if (refs.length === 0) return [];
8995
+ return this.#liveByManyIndex(this.#toIndex, refs);
8996
+ }
8997
+ /** Live edges whose indexed ref matches ANY of `refs`, each edge once. */
8998
+ #liveByManyIndex(index, refs) {
8391
8999
  const seen = /* @__PURE__ */ new Set();
8392
9000
  const out = [];
8393
9001
  for (const ref of refs) {
8394
- const ids = this.#toIndex.get(refKey(ref));
9002
+ const ids = index.get(refKey(ref));
8395
9003
  if (ids === void 0) continue;
8396
9004
  for (const id of ids) {
8397
9005
  if (seen.has(id)) continue;
@@ -8407,6 +9015,9 @@ var MemoryEdgesStore = class {
8407
9015
  async findEdgesFrom(ref) {
8408
9016
  return this.#liveByIndex(this.#fromIndex, refKey(ref));
8409
9017
  }
9018
+ async findEdgesFromMany(refs) {
9019
+ return this.#liveByManyIndex(this.#fromIndex, refs);
9020
+ }
8410
9021
  async canDelete(ref) {
8411
9022
  const blockedBy = [];
8412
9023
  for (const e of this.#liveByIndex(this.#toIndex, refKey(ref))) if (e.policy === "restrict") blockedBy.push(e);
@@ -8545,7 +9156,7 @@ var ResolverTable = class {
8545
9156
  } else this.#rows.delete(o.key);
8546
9157
  row.calls++;
8547
9158
  if (!o.ok) row.errors++;
8548
- row.hist.observe(o.durationMs);
9159
+ if ((o.batchIndex ?? 0) === 0) row.hist.observe(o.durationMs);
8549
9160
  row.lastAt = this.#now();
8550
9161
  this.#rows.set(o.key, row);
8551
9162
  }
@@ -8612,17 +9223,19 @@ function createRuntimeStats(deps) {
8612
9223
  };
8613
9224
  resolvers.observe(o);
8614
9225
  const at = now().toISOString();
8615
- const eligible = seen < 100 || o.durationMs >= allHist.percentileLowerBound(.99);
8616
- allHist.observe(o.durationMs);
8617
- if (++seen % 1e4 === 0) allHist = new LogHistogram();
8618
- if (eligible && o.key !== UNKNOWN) {
8619
- slowest.unshift({
8620
- key: o.key,
8621
- kind: o.kind,
8622
- durationMs: round(o.durationMs),
8623
- at
8624
- });
8625
- slowest.length = Math.min(slowest.length, 10);
9226
+ if ((o.batchIndex ?? 0) === 0) {
9227
+ const eligible = seen < 100 || o.durationMs >= allHist.percentileLowerBound(.99);
9228
+ allHist.observe(o.durationMs);
9229
+ if (++seen % 1e4 === 0) allHist = new LogHistogram();
9230
+ if (eligible && o.key !== UNKNOWN) {
9231
+ slowest.unshift({
9232
+ key: o.key,
9233
+ kind: o.kind,
9234
+ durationMs: round(o.durationMs),
9235
+ at
9236
+ });
9237
+ slowest.length = Math.min(slowest.length, 10);
9238
+ }
8626
9239
  }
8627
9240
  if (!o.ok) {
8628
9241
  const code = scrub(o.code ?? "error");
@@ -8810,6 +9423,51 @@ async function resolveEntityRow(dataset, type, input) {
8810
9423
  })).rows[0] ?? null;
8811
9424
  }
8812
9425
  /**
9426
+ * `resolveEntityRow` for many inputs, in input order, with the same answer per
9427
+ * input: one raw-id read, then ONE `resolveShortIds` for the raw misses that
9428
+ * parse as a short id, then one read of the rows those name. `resolveShortIds`
9429
+ * answers live rows only, which is what the single form's follow-up live read
9430
+ * gives. An `undefined` input answers null.
9431
+ */
9432
+ async function resolveEntityRows(dataset, type, inputs) {
9433
+ const given = [...new Set(inputs.filter((i) => i !== void 0))];
9434
+ if (given.length === 0) return inputs.map(() => null);
9435
+ const byId = /* @__PURE__ */ new Map();
9436
+ for (const r of (await dataset.read(type, {
9437
+ ids: given,
9438
+ includeDeleted: false
9439
+ })).rows) byId.set(String(r.id), r);
9440
+ const shortOf = /* @__PURE__ */ new Map();
9441
+ for (const input of given) {
9442
+ if (byId.has(String(input))) continue;
9443
+ const shortId = parseShortForm(input);
9444
+ if (shortId !== null) shortOf.set(String(input), shortId);
9445
+ }
9446
+ const viaShort = /* @__PURE__ */ new Map();
9447
+ if (shortOf.size > 0) {
9448
+ const bound = await dataset.resolveShortIds(type, [...shortOf.values()]);
9449
+ const ids = [...new Set(bound.values())];
9450
+ if (ids.length > 0) {
9451
+ const { rows } = await dataset.read(type, {
9452
+ ids,
9453
+ includeDeleted: false
9454
+ });
9455
+ const fetched = new Map(rows.map((r) => [String(r.id), r]));
9456
+ for (const [shortId, id] of bound) {
9457
+ const r = fetched.get(id);
9458
+ if (r !== void 0) viaShort.set(shortId, r);
9459
+ }
9460
+ }
9461
+ }
9462
+ return inputs.map((input) => {
9463
+ if (input === void 0) return null;
9464
+ const raw = byId.get(String(input));
9465
+ if (raw !== void 0) return raw;
9466
+ const shortId = shortOf.get(String(input));
9467
+ return shortId === void 0 ? null : viaShort.get(shortId) ?? null;
9468
+ });
9469
+ }
9470
+ /**
8813
9471
  * Short-form gate shared by both resolvers: numeric-string inputs only.
8814
9472
  * PostgreSQL bigint holds up to 2^63, but JS Number precision ends at
8815
9473
  * Number.MAX_SAFE_INTEGER (2^53 - 1). Values beyond that silently truncate
@@ -9139,153 +9797,29 @@ function assertVocabImplications(typeName, fieldDefs) {
9139
9797
  if (sibDef.kind === "scalar" && sibDef.enum !== void 0 && sibDef.strict !== false) {
9140
9798
  const canonical = canonicalVocabValue(sibDef, value);
9141
9799
  if (typeof canonical !== "string" || !sibDef.enum.includes(canonical)) throw new Error(`${typeName}.${name}: '${key}' implies ${sibling} '${String(value)}', which ${sibling} does not accept`);
9142
- }
9143
- }
9144
- }
9145
- }
9146
- /**
9147
- * Reject a type whose autoCRUD create could never fill a field: a non-nullable,
9148
- * non-defaulted, non-readonly scalar date with `serverSet` of `'create'` or
9149
- * `'both'`. Clients may not supply it on create and autoCRUD does not stamp
9150
- * serverSet fields, so every create would write a row without it.
9151
- *
9152
- * Throws a plain `Error` naming the type and every offending field.
9153
- */
9154
- function assertServerSetFieldsFillable(typeName, fieldDefs) {
9155
- const unfillable = [];
9156
- for (const [name, def] of Object.entries(fieldDefs)) {
9157
- if (def.kind !== "scalar" || def.type !== "date") continue;
9158
- if (def.serverSet !== "create" && def.serverSet !== "both") continue;
9159
- if (def.nullable === true || def.default !== void 0 || def.readonly === true) continue;
9160
- unfillable.push(name);
9161
- }
9162
- if (unfillable.length === 0) return;
9163
- const names = unfillable.map((n) => `'${n}'`).join(", ");
9164
- throw new Error(`type '${typeName}': serverSet field(s) ${names} are non-nullable with no default, but clients may not supply them on create and autoCRUD does not stamp serverSet fields, so autoCRUD create could never fill them. Declare them \`nullable: true\` and stamp them from server-side code, or give them a \`default\`.`);
9165
- }
9166
-
9167
- //#endregion
9168
- //#region ../../packages/substrate-sdk/src/autocrud/autocrud-create.ts
9169
- function createResolver(typeName, dataset, options = {}) {
9170
- return async (ctx, args) => {
9171
- const ds = args.dataset ?? dataset;
9172
- const params = dropUndefinedParams(args.params ?? {});
9173
- if (options.fields) assertNoClientServerFields(params, options.fields, "create");
9174
- if (options.fields) {
9175
- for (const [fieldName, def] of Object.entries(options.fields)) if (def.kind === "scalar" && def.readonly === true && fieldName in params) throw new ResolverFrameError("readonly_field", `Cannot set read-only field '${fieldName}' (engine-allocated)`, { field: fieldName });
9176
- }
9177
- if (options.fields) {
9178
- Object.assign(params, normaliseVocabValues(params, options.fields));
9179
- assertEnumValues(params, options.fields);
9180
- }
9181
- if (options.fields) assertNoUnknownFields(params, options.fields, "create");
9182
- if (options.fields) {
9183
- assertNoNullOnNonNullable(params, options.fields, "create");
9184
- assertScalarTypes(params, options.fields, "create");
9185
- applyScalarDefaults(params, options.fields);
9186
- assertRequiredFields(params, options.fields);
9187
- }
9188
- const { id: rawId, ...body } = params;
9189
- const id = coerceId(rawId);
9190
- const at = ctx.now.toISOString();
9191
- const actor = resolveIdentity(ctx);
9192
- const _metadata = {
9193
- createdAt: at,
9194
- updatedAt: at,
9195
- createdBy: actor,
9196
- updatedBy: actor
9197
- };
9198
- const row = id === void 0 ? {
9199
- ...body,
9200
- _metadata
9201
- } : {
9202
- ...body,
9203
- id,
9204
- _metadata
9205
- };
9206
- const { rows: writtenRows } = await ds.write(typeName, [row], { insertOnly: true });
9207
- const storedRow = writtenRows[0];
9208
- if (storedRow === void 0) throw new ResolverFrameError("id_exists", `create${typeName}: a row with id '${id}' exists`, { field: "id" });
9209
- let finalRow = storedRow;
9210
- const shortIdDef = options.fields?.shortId;
9211
- if (shortIdDef?.kind === "scalar" && shortIdDef.readonly === true) {
9212
- const shortId = await ds.allocateShortId(typeName);
9213
- await ds.bindShortId(typeName, shortId, String(storedRow.id));
9214
- finalRow = {
9215
- ...storedRow,
9216
- shortId
9217
- };
9218
- }
9219
- args.onWrite?.({
9220
- ns: ds.namespace,
9221
- type: typeName,
9222
- id: finalRow.id,
9223
- operation: "create",
9224
- row: finalRow
9225
- });
9226
- return finalRow;
9227
- };
9228
- }
9229
-
9230
- //#endregion
9231
- //#region ../../packages/substrate-sdk/src/delete.ts
9232
- async function deleteRow(args) {
9233
- const gate = await args.edges.canDelete(args.ref);
9234
- if (!gate.ok) throw new RestrictViolation(args.ref, gate.blockedBy);
9235
- await args.dataset.tombstone(args.ref.type, [args.ref.id]);
9236
- return {
9237
- ok: true,
9238
- tombstonedAt: args.now()
9239
- };
9240
- }
9241
-
9242
- //#endregion
9243
- //#region ../../packages/substrate-sdk/src/autocrud/autocrud-delete.ts
9244
- const KNOWN_DELETE_PARAMS = /* @__PURE__ */ new Set(["id"]);
9245
- function deleteResolver(typeName, dataset, edges) {
9246
- return async (_ctx, args) => {
9247
- rejectUnknownParams("delete", typeName, args.params, KNOWN_DELETE_PARAMS);
9248
- const ds = args.dataset ?? dataset;
9249
- const edgeStore = args.edges ?? edges;
9250
- const id = coerceId(args.params?.id);
9251
- if (id === void 0) throw new ResolverFrameError("missing_id", `deleteResolver('${typeName}'): params.id is required`, { field: "id" });
9252
- const rowId = await resolveEntityId(ds, typeName, id);
9253
- if (rowId === null) return {
9254
- id,
9255
- deleted: false
9256
- };
9257
- const ref = {
9258
- ns: ds.namespace,
9259
- type: typeName,
9260
- id: rowId
9261
- };
9262
- const { rows: existing } = await ds.read(typeName, { id: rowId });
9263
- if (existing.length === 0) return {
9264
- id,
9265
- deleted: false
9266
- };
9267
- await deleteRow({
9268
- dataset: ds,
9269
- edges: edgeStore,
9270
- ref,
9271
- now: () => /* @__PURE__ */ new Date()
9272
- });
9273
- const preRow = existing[0];
9274
- if (args.onWrite !== void 0) {
9275
- const event = {
9276
- ns: ds.namespace,
9277
- type: typeName,
9278
- id: rowId,
9279
- operation: "delete",
9280
- ...preRow !== void 0 ? { row: preRow } : {}
9281
- };
9282
- args.onWrite(event);
9283
- }
9284
- return {
9285
- id: rowId,
9286
- deleted: true
9287
- };
9288
- };
9800
+ }
9801
+ }
9802
+ }
9803
+ }
9804
+ /**
9805
+ * Reject a type whose autoCRUD create could never fill a field: a non-nullable,
9806
+ * non-defaulted, non-readonly scalar date with `serverSet` of `'create'` or
9807
+ * `'both'`. Clients may not supply it on create and autoCRUD does not stamp
9808
+ * serverSet fields, so every create would write a row without it.
9809
+ *
9810
+ * Throws a plain `Error` naming the type and every offending field.
9811
+ */
9812
+ function assertServerSetFieldsFillable(typeName, fieldDefs) {
9813
+ const unfillable = [];
9814
+ for (const [name, def] of Object.entries(fieldDefs)) {
9815
+ if (def.kind !== "scalar" || def.type !== "date") continue;
9816
+ if (def.serverSet !== "create" && def.serverSet !== "both") continue;
9817
+ if (def.nullable === true || def.default !== void 0 || def.readonly === true) continue;
9818
+ unfillable.push(name);
9819
+ }
9820
+ if (unfillable.length === 0) return;
9821
+ const names = unfillable.map((n) => `'${n}'`).join(", ");
9822
+ throw new Error(`type '${typeName}': serverSet field(s) ${names} are non-nullable with no default, but clients may not supply them on create and autoCRUD does not stamp serverSet fields, so autoCRUD create could never fill them. Declare them \`nullable: true\` and stamp them from server-side code, or give them a \`default\`.`);
9289
9823
  }
9290
9824
 
9291
9825
  //#endregion
@@ -9419,29 +9953,203 @@ function purgeResolver(typeName, dataset) {
9419
9953
  };
9420
9954
  }
9421
9955
 
9956
+ //#endregion
9957
+ //#region ../../packages/substrate-sdk/src/delete.ts
9958
+ async function deleteRow(args) {
9959
+ const gate = await args.edges.canDelete(args.ref);
9960
+ if (!gate.ok) throw new RestrictViolation(args.ref, gate.blockedBy);
9961
+ await args.dataset.tombstone(args.ref.type, [args.ref.id]);
9962
+ return {
9963
+ ok: true,
9964
+ tombstonedAt: args.now()
9965
+ };
9966
+ }
9967
+ /**
9968
+ * `deleteRow` for many rows of one type in the dataset's namespace: one
9969
+ * `findEdgesToMany` gates them all (one `canDelete` for a single row), then
9970
+ * one `tombstone` call. Throws
9971
+ * `RestrictViolation` for the first id, in `ids` order, that a live `restrict`
9972
+ * edge blocks, before tombstoning anything. Returns the ids tombstoned.
9973
+ */
9974
+ async function deleteRows(args) {
9975
+ if (args.ids.length === 0) return [];
9976
+ await assertNoRestrictEdges(args.edges, {
9977
+ ns: args.dataset.namespace,
9978
+ type: args.type
9979
+ }, args.ids);
9980
+ const { ids } = await args.dataset.tombstone(args.type, args.ids);
9981
+ return ids;
9982
+ }
9983
+ /**
9984
+ * The restrict gate of `deleteRows`: one `findEdgesToMany` (one `canDelete`
9985
+ * for a single row). Throws `RestrictViolation` for the first id, in `ids`
9986
+ * order, that a live `restrict` edge points at. Sends nothing for no ids.
9987
+ */
9988
+ async function assertNoRestrictEdges(edges, target, ids) {
9989
+ if (ids.length === 0) return;
9990
+ const refs = ids.map((id) => ({
9991
+ ...target,
9992
+ id
9993
+ }));
9994
+ const blocked = /* @__PURE__ */ new Map();
9995
+ const only = refs.length === 1 ? refs[0] : void 0;
9996
+ if (only !== void 0) {
9997
+ const gate = await edges.canDelete(only);
9998
+ if (!gate.ok) blocked.set(String(only.id), gate.blockedBy);
9999
+ } else for (const e of await edges.findEdgesToMany(refs)) {
10000
+ if (e.policy !== "restrict" || e.deletedAt != null) continue;
10001
+ const key = String(e.to.id);
10002
+ const by = blocked.get(key);
10003
+ if (by === void 0) blocked.set(key, [e]);
10004
+ else by.push(e);
10005
+ }
10006
+ for (const ref of refs) {
10007
+ const by = blocked.get(String(ref.id));
10008
+ if (by !== void 0) throw new RestrictViolation(ref, by);
10009
+ }
10010
+ }
10011
+
10012
+ //#endregion
10013
+ //#region ../../packages/substrate-sdk/src/autocrud/autocrud-create.ts
10014
+ /**
10015
+ * One create element's validation, run in JS before any write: returns the
10016
+ * row to insert, without `_metadata`, and with no `id` when the dataset is to
10017
+ * assign one. Throws the element's refusal. The single and batch create
10018
+ * resolvers both call it, so the checks exist once.
10019
+ */
10020
+ function prepareCreateRow(rawParams, fields) {
10021
+ const params = dropUndefinedParams(rawParams ?? {});
10022
+ if (fields) {
10023
+ assertNoClientServerFields(params, fields, "create");
10024
+ for (const [fieldName, def] of Object.entries(fields)) if (def.kind === "scalar" && def.readonly === true && fieldName in params) throw new ResolverFrameError("readonly_field", `Cannot set read-only field '${fieldName}' (engine-allocated)`, { field: fieldName });
10025
+ Object.assign(params, normaliseVocabValues(params, fields));
10026
+ assertEnumValues(params, fields);
10027
+ assertNoUnknownFields(params, fields, "create");
10028
+ assertNoNullOnNonNullable(params, fields, "create");
10029
+ assertScalarTypes(params, fields, "create");
10030
+ applyScalarDefaults(params, fields);
10031
+ assertRequiredFields(params, fields);
10032
+ }
10033
+ const { id: rawId, ...body } = params;
10034
+ const id = coerceId(rawId);
10035
+ return id === void 0 ? body : {
10036
+ ...body,
10037
+ id
10038
+ };
10039
+ }
10040
+
10041
+ //#endregion
10042
+ //#region ../../packages/substrate-sdk/src/autocrud/autocrud-delete.ts
10043
+ const KNOWN_DELETE_PARAMS = /* @__PURE__ */ new Set(["id"]);
10044
+ /**
10045
+ * One delete element's validation: returns the requested id or throws the
10046
+ * element's refusal. The single and batch delete resolvers both call it.
10047
+ */
10048
+ function prepareDelete(typeName, params) {
10049
+ rejectUnknownParams("delete", typeName, params, KNOWN_DELETE_PARAMS);
10050
+ const id = coerceId(params?.id);
10051
+ if (id === void 0) throw new ResolverFrameError("missing_id", `deleteResolver('${typeName}'): params.id is required`, { field: "id" });
10052
+ return id;
10053
+ }
10054
+
10055
+ //#endregion
10056
+ //#region ../../packages/substrate-sdk/src/autocrud/autocrud-update.ts
10057
+ /**
10058
+ * The trusted write-tail of an id-based update: applies the whole patch to
10059
+ * the live row in one round-trip, stamping updatedAt/updatedBy, and emits
10060
+ * the §5.4 onWrite event when a row actually landed. Returns null when the
10061
+ * row is missing or tombstoned.
10062
+ *
10063
+ * `updateResolver` delegates here after its guards; custom system-stamped
10064
+ * resolvers (e.g. a status transition such as `approveRequest`) call it
10065
+ * directly with an already-resolved row id. It deliberately runs NO
10066
+ * client-field guards — that is what lets a system writer stamp serverSet
10067
+ * fields like `approvedAt`. Callers own validation and permission
10068
+ * checks; this owns the metadata idiom so it stays single-sourced.
10069
+ */
10070
+ async function applyUpdatePatch(ds, typeName, rowId, patchFields, ctx, onWrite) {
10071
+ const { row: merged } = await ds.conditionalUpdate(typeName, rowId, {}, patchFields, resolveIdentity(ctx), ctx.now);
10072
+ if (merged === null) return null;
10073
+ onWrite?.({
10074
+ ns: ds.namespace,
10075
+ type: typeName,
10076
+ id: merged.id,
10077
+ operation: "update",
10078
+ row: merged
10079
+ });
10080
+ return merged;
10081
+ }
10082
+ /**
10083
+ * One update element's validation, run in JS before any write: returns the
10084
+ * requested id and the normalised params (the patch plus `id`). Throws the
10085
+ * element's refusal. The single and batch update resolvers both call it, so
10086
+ * the checks exist once.
10087
+ */
10088
+ function prepareUpdate(typeName, rawParams, fields) {
10089
+ const id = coerceId(rawParams?.id);
10090
+ if (id === void 0) throw new ResolverFrameError("missing_id", `updateResolver('${typeName}'): params.id is required`, { field: "id" });
10091
+ return {
10092
+ id,
10093
+ params: preparePatch(rawParams, fields)
10094
+ };
10095
+ }
10096
+ /**
10097
+ * An update's checks on everything but the id, run in JS before any write:
10098
+ * returns the normalised params. `update<T>` runs it on `{ id, ...patch }`,
10099
+ * `updateMany<T>` on its `set`, so both refuse the same patches.
10100
+ */
10101
+ function preparePatch(rawParams, fields) {
10102
+ if (fields) assertNoClientServerFields(rawParams ?? {}, fields, "update");
10103
+ const sent = dropUndefinedParams(rawParams ?? {});
10104
+ const params = fields !== void 0 ? normaliseVocabValues(sent, fields) : sent;
10105
+ if ("_deletedAt" in params) throw new ReservedField("_deletedAt");
10106
+ if (fields) {
10107
+ assertEnumValues(params, fields);
10108
+ assertNoUnknownFields(params, fields, "update");
10109
+ assertNoNullOnNonNullable(params, fields, "update");
10110
+ assertScalarTypes(params, fields, "update");
10111
+ }
10112
+ return params;
10113
+ }
10114
+ /**
10115
+ * The reported miss of an update: a null result beside empty `errors` reads
10116
+ * exactly like a write that landed. `get` still returns null — asking about a
10117
+ * missing row has a true answer; asserting a write against one does not.
10118
+ */
10119
+ function updateNotFound(typeName, id) {
10120
+ return new ResolverFrameError("not_found", `updateResolver('${typeName}'): no row with id '${String(id)}'`, { field: "id" });
10121
+ }
10122
+
9422
10123
  //#endregion
9423
10124
  //#region ../../packages/substrate-sdk/src/autocrud/crossref-edge-sync.ts
9424
10125
  /**
9425
10126
  * Reconcile first-class edges against an update patch. For every crossRef
9426
10127
  * field that is a KEY in `patchParams` (a field simply absent from the patch
9427
10128
  * is left untouched — partial updates must not churn edges for fields the
9428
- * caller never mentioned), this tombstones the field's current live edge(s)
9429
- * and writes a fresh edge at the new target when the target actually changed.
10129
+ * caller never mentioned), the field's current live edge(s) are tombstoned
10130
+ * and a fresh edge written at the new target when the target actually changed.
9430
10131
  * A no-op repoint (same target, or clearing an already-null field) is
9431
10132
  * detected and skipped so a no-change update doesn't churn edge history.
9432
- */
9433
- async function reconcileCrossRefEdgesOnUpdate(edges, fromRef, crossRefs, patchParams) {
9434
- const touched = crossRefs.filter(({ fieldName }) => Object.hasOwn(patchParams, fieldName));
9435
- if (touched.length === 0) return;
9436
- const currentEdgesFromOwner = await edges.findEdgesFrom(fromRef);
9437
- await Promise.all(touched.map(async ({ fieldName, def }) => {
10133
+ *
10134
+ * Returns the edge changes one update patch needs, given the owner's live outbound
10135
+ * edges: the stale edge ids to tombstone and the fresh edges to write. Pure,
10136
+ * so a batch plans every element from one `findEdgesFromMany` and applies them
10137
+ * with one `tombstoneMany` and one `writeMany`.
10138
+ */
10139
+ function planCrossRefEdges(currentEdgesFromOwner, fromRef, crossRefs, patchParams) {
10140
+ const plan = {
10141
+ tombstone: [],
10142
+ write: []
10143
+ };
10144
+ for (const { fieldName, def } of crossRefs) {
10145
+ if (!Object.hasOwn(patchParams, fieldName)) continue;
9438
10146
  const rawValue = patchParams[fieldName];
9439
10147
  const newId = typeof rawValue === "string" || typeof rawValue === "number" ? rawValue : null;
9440
10148
  const currentEdges = currentEdgesFromOwner.filter((e) => e.fieldName === fieldName);
9441
10149
  const currentId = currentEdges[0]?.to.id ?? null;
9442
- if (currentEdges.length <= 1 && (currentId === null ? newId === null : newId !== null && String(currentId) === String(newId))) return;
9443
- for (const edge of currentEdges) await edges.tombstone(edge.id);
9444
- if (newId !== null) await edges.write({
10150
+ if (currentEdges.length <= 1 && (currentId === null ? newId === null : newId !== null && String(currentId) === String(newId))) continue;
10151
+ for (const edge of currentEdges) plan.tombstone.push(edge.id);
10152
+ if (newId !== null) plan.write.push({
9445
10153
  from: fromRef,
9446
10154
  to: {
9447
10155
  ns: def.ns,
@@ -9451,7 +10159,40 @@ async function reconcileCrossRefEdgesOnUpdate(edges, fromRef, crossRefs, patchPa
9451
10159
  fieldName,
9452
10160
  policy: def.onDelete
9453
10161
  });
10162
+ }
10163
+ return plan;
10164
+ }
10165
+ /**
10166
+ * Applies `planCrossRefEdges` to every updated row whose patch names a
10167
+ * crossRef: one `findEdgesFromMany`, one `tombstoneMany`, one `writeMany`.
10168
+ * A repointed crossRef must not leave the old edge live, or the sweep's
10169
+ * applyPolicy fires onDelete against the stale target. Sends nothing when no
10170
+ * patch names a crossRef.
10171
+ */
10172
+ async function syncCrossRefEdges(edgeStore, owner, crossRefs, updated) {
10173
+ const touched = updated.filter((u) => crossRefs.some(({ fieldName }) => Object.hasOwn(u.params, fieldName)));
10174
+ if (touched.length === 0) return;
10175
+ const refs = touched.map((u) => ({
10176
+ ...owner,
10177
+ id: u.id
9454
10178
  }));
10179
+ const byOwner = /* @__PURE__ */ new Map();
10180
+ for (const e of await edgeStore.findEdgesFromMany(refs)) {
10181
+ const key = String(e.from.id);
10182
+ const owned = byOwner.get(key);
10183
+ if (owned === void 0) byOwner.set(key, [e]);
10184
+ else owned.push(e);
10185
+ }
10186
+ const tombstone = [];
10187
+ const write = [];
10188
+ for (const [k, u] of touched.entries()) {
10189
+ const ref = refs[k];
10190
+ const plan = planCrossRefEdges(byOwner.get(String(ref.id)) ?? [], ref, crossRefs, u.params);
10191
+ tombstone.push(...plan.tombstone);
10192
+ write.push(...plan.write);
10193
+ }
10194
+ await edgeStore.tombstoneMany(tombstone);
10195
+ await edgeStore.writeMany(write);
9455
10196
  }
9456
10197
 
9457
10198
  //#endregion
@@ -9467,10 +10208,15 @@ function collectCrossRefFields(fields) {
9467
10208
  return out;
9468
10209
  }
9469
10210
  /**
9470
- * Verify each crossRef's target row exists (live, non-tombstoned). Same-ns
10211
+ * Refuse a crossRef to a missing target, for a batch: element `i`'s values are
10212
+ * `values[i]`. For each target type it reads the distinct values once, then
10213
+ * resolves the misses that parse as a short id with one `resolveShortIds`.
10214
+ * A value that `pending` names counts as existing for element `i` only when
10215
+ * the element creating it comes before `i`, as sequential dispatch has it
10216
+ * written by then. Throws `BatchElementError(i, MissingReferentError)` for
10217
+ * the lowest refused element, fields checked in declared order. Same-ns
9471
10218
  * targets read the tx-scoped `args.dataset`; cross-ns targets read the
9472
- * committed `args.resolveDataset(ns)` view. Throws MissingReferentError on the
9473
- * first missing target.
10219
+ * committed `args.resolveDataset(ns)` view.
9474
10220
  *
9475
10221
  * Enforcement is ON by default: a crossRef is a PK<->FK relationship. Three
9476
10222
  * states:
@@ -9485,95 +10231,665 @@ function collectCrossRefFields(fields) {
9485
10231
  * 'allow' never enforce. The deliberate opt-out, for a genuinely soft
9486
10232
  * reference.
9487
10233
  */
9488
- async function assertCrossRefTargetsExist(args, crossRefs, values, fromNs) {
9489
- for (const { fieldName, def } of crossRefs) {
9490
- if (def.onMissing === "allow") continue;
9491
- const value = values[fieldName];
9492
- if (value === null || value === void 0) continue;
9493
- if (typeof value !== "string" && typeof value !== "number") continue;
9494
- const targetDs = def.ns === fromNs ? args.dataset : args.resolveDataset?.(def.ns);
9495
- if (targetDs === void 0) {
9496
- if (def.onMissing === "reject") throw new MissingReferentError(fieldName, {
9497
- ns: def.ns,
10234
+ async function assertCrossRefTargetsExistMany(args, crossRefs, values, fromNs, pending) {
10235
+ const enforced = crossRefs.filter(({ def }) => def.onMissing !== "allow");
10236
+ if (enforced.length === 0) return;
10237
+ const refOf = (i, fieldName) => {
10238
+ const v = values[i]?.[fieldName];
10239
+ return typeof v === "string" || typeof v === "number" ? v : void 0;
10240
+ };
10241
+ const targetOf = (def) => def.ns === fromNs ? args.dataset : args.resolveDataset?.(def.ns);
10242
+ const groups = /* @__PURE__ */ new Map();
10243
+ for (const { fieldName, def } of enforced) {
10244
+ const ds = targetOf(def);
10245
+ if (ds === void 0) continue;
10246
+ const key = `${def.ns}\u0000${def.type}`;
10247
+ let group = groups.get(key);
10248
+ if (group === void 0) {
10249
+ group = {
10250
+ ds,
9498
10251
  type: def.type,
9499
- id: value
9500
- });
9501
- continue;
10252
+ ids: /* @__PURE__ */ new Set()
10253
+ };
10254
+ groups.set(key, group);
9502
10255
  }
9503
- if (await resolveEntityId(targetDs, def.type, value) === null) throw new MissingReferentError(fieldName, {
10256
+ for (let i = 0; i < values.length; i++) {
10257
+ const v = refOf(i, fieldName);
10258
+ if (v !== void 0) group.ids.add(v);
10259
+ }
10260
+ }
10261
+ const existing = /* @__PURE__ */ new Map();
10262
+ for (const [key, { ds, type, ids }] of groups) existing.set(key, await existingIds(ds, type, [...ids]));
10263
+ for (let i = 0; i < values.length; i++) for (const { fieldName, def } of enforced) {
10264
+ const value = refOf(i, fieldName);
10265
+ if (value === void 0) continue;
10266
+ const missing = new MissingReferentError(fieldName, {
9504
10267
  ns: def.ns,
9505
10268
  type: def.type,
9506
10269
  id: value
9507
10270
  });
10271
+ const found = existing.get(`${def.ns}\u0000${def.type}`);
10272
+ if (found === void 0) {
10273
+ if (def.onMissing === "reject") throw new BatchElementError(i, missing);
10274
+ continue;
10275
+ }
10276
+ if (found.has(String(value))) continue;
10277
+ const earlier = def.ns === fromNs && pending?.type === def.type ? pending.ids.get(String(value)) : void 0;
10278
+ if (earlier !== void 0 && earlier < i) continue;
10279
+ throw new BatchElementError(i, missing);
10280
+ }
10281
+ }
10282
+ /** The inputs naming a live row: by raw id, else as a short id. */
10283
+ async function existingIds(ds, type, inputs) {
10284
+ const found = /* @__PURE__ */ new Set();
10285
+ if (inputs.length === 0) return found;
10286
+ for (const r of (await ds.read(type, {
10287
+ ids: inputs,
10288
+ includeDeleted: false
10289
+ })).rows) found.add(String(r.id));
10290
+ const shortOf = /* @__PURE__ */ new Map();
10291
+ for (const input of inputs) {
10292
+ if (found.has(String(input))) continue;
10293
+ const shortId = parseShortForm(input);
10294
+ if (shortId === null) continue;
10295
+ const same = shortOf.get(shortId);
10296
+ if (same === void 0) shortOf.set(shortId, [String(input)]);
10297
+ else same.push(String(input));
10298
+ }
10299
+ if (shortOf.size === 0) return found;
10300
+ const bound = await ds.resolveShortIds(type, [...shortOf.keys()]);
10301
+ for (const shortId of bound.keys()) for (const input of shortOf.get(shortId) ?? []) found.add(input);
10302
+ return found;
10303
+ }
10304
+
10305
+ //#endregion
10306
+ //#region ../../packages/substrate-sdk/src/autocrud/batch.ts
10307
+ /**
10308
+ * autoCRUD batch resolvers for `create<T>`, `update<T>` and `delete<T>` (#1814).
10309
+ *
10310
+ * A mutate array of one generated mutation calls its batch resolver once with
10311
+ * every element. The resolver does per-batch work, not per-row: validation in
10312
+ * JS, one resolution of the ids named, one existence read per crossRef target
10313
+ * type, then one statement per kind of write. The single-frame resolver is the
10314
+ * same batch resolver called with one element, so the per-element checks exist
10315
+ * once.
10316
+ *
10317
+ * Every slot answers as sequential dispatch would. Each element runs its checks
10318
+ * in the order the single resolver runs them, and a later check runs only on
10319
+ * the elements before the lowest refusal so far, so the refusal reported is the
10320
+ * one sequential dispatch meets first. It is thrown as
10321
+ * `BatchElementError(i, cause)`; the engine replays the cause's code at `[key]`
10322
+ * and reports `batched_frame_rolled_back` at `[key, i]`.
10323
+ *
10324
+ * An update or delete array that names one row twice runs each element alone,
10325
+ * in order, in the same transaction: the elements then depend on each other.
10326
+ */
10327
+ /** The single-frame resolver: `batch` with one element, its refusal unwrapped. */
10328
+ function singleFrame(batch) {
10329
+ return async (ctx, args) => {
10330
+ try {
10331
+ return (await batch(ctx, [args]))[0];
10332
+ } catch (err) {
10333
+ throw isBatchElementError(err) ? err.cause : err;
10334
+ }
10335
+ };
10336
+ }
10337
+ /**
10338
+ * The lowest refused element so far. Each phase runs only on the elements
10339
+ * before it, so a refusal found later at a lower index replaces it.
10340
+ */
10341
+ var FirstRefusal = class {
10342
+ size;
10343
+ index;
10344
+ #cause;
10345
+ constructor(size) {
10346
+ this.size = size;
10347
+ this.index = size;
10348
+ }
10349
+ live(i) {
10350
+ return i < this.index;
10351
+ }
10352
+ refuse(i, cause) {
10353
+ if (i >= this.index) return;
10354
+ this.index = i;
10355
+ this.#cause = cause;
10356
+ }
10357
+ /** Element `i`'s own check: whatever it throws refuses `i`. */
10358
+ check(i, fn) {
10359
+ try {
10360
+ fn();
10361
+ } catch (err) {
10362
+ this.refuse(i, err);
10363
+ }
10364
+ }
10365
+ /** A set-wise check names its element with `BatchElementError`; anything else fails the batch. */
10366
+ async capture(work) {
10367
+ try {
10368
+ await work;
10369
+ } catch (err) {
10370
+ if (!isBatchElementError(err)) throw err;
10371
+ this.refuse(err.index, err.cause);
10372
+ }
10373
+ }
10374
+ throwIfRefused() {
10375
+ if (this.index < this.size) throw new BatchElementError(this.index, this.#cause);
10376
+ }
10377
+ };
10378
+ /** Each element alone, in order: the sequential answer, for elements that depend on each other. */
10379
+ async function eachAlone(batch, ctx, list) {
10380
+ const out = [];
10381
+ for (const [i, args] of list.entries()) try {
10382
+ out.push((await batch(ctx, [args]))[0] ?? null);
10383
+ } catch (err) {
10384
+ throw new BatchElementError(i, isBatchElementError(err) ? err.cause : err);
10385
+ }
10386
+ return out;
10387
+ }
10388
+ function namesARowTwice(rows) {
10389
+ const seen = /* @__PURE__ */ new Set();
10390
+ for (const r of rows) {
10391
+ if (r === null) continue;
10392
+ const key = String(r.id);
10393
+ if (seen.has(key)) return true;
10394
+ seen.add(key);
10395
+ }
10396
+ return false;
10397
+ }
10398
+ /**
10399
+ * A row policy filters what a read returns, so on its own it would let an
10400
+ * update or delete reach a row the caller cannot read. Runs the policy's row
10401
+ * filters against each element's stored row (`stored[i]`, already read) and
10402
+ * returns which elements must answer as for a missing row.
10403
+ */
10404
+ function guardRowWrites(ctx, policy, list, stored) {
10405
+ return list.map((args, i) => {
10406
+ if (policy === void 0 || coerceId(args.params?.id) === void 0) return false;
10407
+ const decision = policy(ctx, args);
10408
+ if (decision.obligations === void 0 || decision.obligations.length === 0) return false;
10409
+ const row = stored[i] ?? null;
10410
+ return row !== null && applyRowFilters(decision, [row], ctx).length === 0;
10411
+ });
10412
+ }
10413
+ /**
10414
+ * Runs `postWrite` once the engine transaction commits, on the row as
10415
+ * committed, so its side effects (embeddings, indexes) never describe a
10416
+ * rolled-back write or hold a connection across the transaction. A rolled-back
10417
+ * write skips it. Outside a transaction (no `afterTx`) it runs at once.
10418
+ */
10419
+ async function runPostWrite(postWrite, typeName, dataset, row, ctx, args) {
10420
+ if (args.afterTx === void 0) {
10421
+ await postWrite(row, ctx);
10422
+ return;
9508
10423
  }
10424
+ args.afterTx(async (outcome) => {
10425
+ if (!outcome.committed) return;
10426
+ const { rows } = await dataset.read(typeName, { id: row.id });
10427
+ const committed = rows[0];
10428
+ if (committed !== void 0) await postWrite(committed, ctx);
10429
+ });
10430
+ }
10431
+ /**
10432
+ * `create<T>` for many rows. Per element, as the single resolver: crossRef
10433
+ * targets exist (on the params as sent), validation, then the insert. Per
10434
+ * batch: one existence read per target type, one insert-only `write`, one
10435
+ * `allocateShortIds` + `bindShortIds`, one edges `writeMany`.
10436
+ *
10437
+ * `edges: null` writes rows only: no crossRef check and no edges.
10438
+ */
10439
+ function createBatchResolver(typeName, dataset, edges, opts = {}) {
10440
+ const { fields, postWrite } = opts;
10441
+ const crossRefs = edges === null ? [] : collectCrossRefFields(fields);
10442
+ const shortIdDef = fields?.shortId;
10443
+ const allocatesShortId = shortIdDef?.kind === "scalar" && shortIdDef.readonly === true;
10444
+ return async (ctx, list) => {
10445
+ const n = list.length;
10446
+ if (n === 0) return [];
10447
+ const first = list[0];
10448
+ const ds = first.dataset ?? dataset;
10449
+ const refusal = new FirstRefusal(n);
10450
+ if (crossRefs.length > 0) {
10451
+ const pending = /* @__PURE__ */ new Map();
10452
+ for (const [i, args] of list.entries()) {
10453
+ const id = coerceId(args.params?.id);
10454
+ if (id !== void 0 && !pending.has(String(id))) pending.set(String(id), i);
10455
+ }
10456
+ await refusal.capture(assertCrossRefTargetsExistMany(first, crossRefs, list.map((args) => args.params ?? {}), ds.namespace, {
10457
+ type: typeName,
10458
+ ids: pending
10459
+ }));
10460
+ }
10461
+ const bodies = [];
10462
+ for (let i = 0; refusal.live(i); i++) refusal.check(i, () => {
10463
+ bodies[i] = prepareCreateRow(list[i]?.params, fields);
10464
+ });
10465
+ const stored = [];
10466
+ const count = refusal.index;
10467
+ if (count > 0) {
10468
+ let actor;
10469
+ try {
10470
+ actor = resolveIdentity(ctx);
10471
+ } catch (err) {
10472
+ refusal.refuse(0, err);
10473
+ }
10474
+ if (actor !== void 0) {
10475
+ const at = ctx.now.toISOString();
10476
+ const meta = {
10477
+ createdAt: at,
10478
+ updatedAt: at,
10479
+ createdBy: actor,
10480
+ updatedBy: actor
10481
+ };
10482
+ const input = bodies.slice(0, count).map((b) => ({
10483
+ ...b,
10484
+ _metadata: { ...meta }
10485
+ }));
10486
+ const written = await ds.write(typeName, input, { insertOnly: true });
10487
+ let p = 0;
10488
+ for (const [i, row] of input.entries()) {
10489
+ const landed = written.rows[p];
10490
+ if (landed !== void 0 && (row.id === void 0 || String(written.ids[p]) === String(row.id))) {
10491
+ stored.push(landed);
10492
+ p++;
10493
+ continue;
10494
+ }
10495
+ refusal.refuse(i, new ResolverFrameError("id_exists", `create${typeName}: a row with id '${String(row.id)}' exists`, { field: "id" }));
10496
+ break;
10497
+ }
10498
+ }
10499
+ }
10500
+ refusal.throwIfRefused();
10501
+ let rows = stored;
10502
+ if (allocatesShortId) {
10503
+ const shortIds = await ds.allocateShortIds(typeName, n);
10504
+ rows = stored.map((r, i) => ({
10505
+ ...r,
10506
+ shortId: shortIds[i]
10507
+ }));
10508
+ await ds.bindShortIds(typeName, rows.map((r) => ({
10509
+ shortId: r.shortId,
10510
+ rowId: String(r.id)
10511
+ })));
10512
+ }
10513
+ const edgeStore = first.edges ?? edges;
10514
+ if (crossRefs.length > 0 && edgeStore !== null) {
10515
+ const inputs = [];
10516
+ for (const r of rows) for (const { fieldName, def } of crossRefs) {
10517
+ const value = r[fieldName];
10518
+ if (typeof value !== "string" && typeof value !== "number") continue;
10519
+ inputs.push({
10520
+ from: {
10521
+ ns: ds.namespace,
10522
+ type: typeName,
10523
+ id: r.id
10524
+ },
10525
+ to: {
10526
+ ns: def.ns,
10527
+ type: def.type,
10528
+ id: value
10529
+ },
10530
+ fieldName,
10531
+ policy: def.onDelete
10532
+ });
10533
+ }
10534
+ await edgeStore.writeMany(inputs);
10535
+ }
10536
+ for (const [i, row] of rows.entries()) {
10537
+ const args = list[i];
10538
+ args.onWrite?.({
10539
+ ns: ds.namespace,
10540
+ type: typeName,
10541
+ id: row.id,
10542
+ operation: "create",
10543
+ row
10544
+ });
10545
+ if (postWrite !== void 0) await runPostWrite(postWrite, typeName, dataset, row, ctx, args);
10546
+ }
10547
+ return rows;
10548
+ };
10549
+ }
10550
+ /**
10551
+ * `update<T>` for many rows. Per element, as the single resolver: the row
10552
+ * guard, validation, `not_found`, crossRef targets exist, then the patch. Per
10553
+ * batch: one resolution of the ids (shared with the guard), one existence read
10554
+ * per target type, one live-only `patchRows` (an update never revives or
10555
+ * re-creates a row), one `findEdgesFromMany`, `tombstoneMany` and `writeMany`.
10556
+ */
10557
+ function updateBatchResolver(typeName, dataset, edges, opts = {}) {
10558
+ const { fields, policy, postWrite } = opts;
10559
+ const crossRefs = collectCrossRefFields(fields);
10560
+ const batch = async (ctx, list) => {
10561
+ const n = list.length;
10562
+ if (n === 0) return [];
10563
+ const first = list[0];
10564
+ const ds = first.dataset ?? dataset;
10565
+ const targets = await resolveEntityRows(ds, typeName, list.map((args) => coerceId(args.params?.id)));
10566
+ if (n > 1 && namesARowTwice(targets)) return eachAlone(batch, ctx, list);
10567
+ const hidden = guardRowWrites(ctx, policy, list, targets);
10568
+ const refusal = new FirstRefusal(n);
10569
+ const patches = [];
10570
+ for (let i = 0; refusal.live(i); i++) {
10571
+ if (hidden[i]) continue;
10572
+ refusal.check(i, () => {
10573
+ const { id, params } = prepareUpdate(typeName, list[i]?.params, fields);
10574
+ const target = targets[i] ?? null;
10575
+ if (target === null) throw updateNotFound(typeName, id);
10576
+ patches[i] = {
10577
+ i,
10578
+ id,
10579
+ params,
10580
+ target
10581
+ };
10582
+ });
10583
+ }
10584
+ if (crossRefs.length > 0) await refusal.capture(assertCrossRefTargetsExistMany(first, crossRefs, list.map((_, i) => (refusal.live(i) ? patches[i]?.params : void 0) ?? {}), ds.namespace));
10585
+ const writers = patches.filter((p) => p !== void 0 && refusal.live(p.i));
10586
+ const merged = list.map(() => null);
10587
+ const firstWriter = writers[0];
10588
+ if (firstWriter !== void 0) {
10589
+ let actor;
10590
+ try {
10591
+ actor = resolveIdentity(ctx);
10592
+ } catch (err) {
10593
+ refusal.refuse(firstWriter.i, err);
10594
+ }
10595
+ if (actor !== void 0) {
10596
+ const out = await ds.patchRows(typeName, writers.map((w) => ({
10597
+ id: w.target.id,
10598
+ patch: withoutId(w.params)
10599
+ })), actor, ctx.now);
10600
+ for (const [k, w] of writers.entries()) {
10601
+ const row = out[k] ?? null;
10602
+ if (row === null) refusal.refuse(w.i, updateNotFound(typeName, w.id));
10603
+ merged[w.i] = row;
10604
+ }
10605
+ }
10606
+ }
10607
+ refusal.throwIfRefused();
10608
+ await syncCrossRefEdges(first.edges ?? edges, {
10609
+ ns: ds.namespace,
10610
+ type: typeName
10611
+ }, crossRefs, writers.map((w) => ({
10612
+ id: w.target.id,
10613
+ params: w.params
10614
+ })));
10615
+ for (const [i, row] of merged.entries()) {
10616
+ if (row === null) continue;
10617
+ const args = list[i];
10618
+ args.onWrite?.({
10619
+ ns: ds.namespace,
10620
+ type: typeName,
10621
+ id: row.id,
10622
+ operation: "update",
10623
+ row
10624
+ });
10625
+ if (postWrite !== void 0) await runPostWrite(postWrite, typeName, dataset, row, ctx, args);
10626
+ }
10627
+ return merged;
10628
+ };
10629
+ return batch;
10630
+ }
10631
+ function withoutId(params) {
10632
+ const patch = {};
10633
+ for (const [field, value] of Object.entries(params)) if (field !== "id") patch[field] = value;
10634
+ return patch;
10635
+ }
10636
+ /**
10637
+ * `delete<T>` for many rows. Per element, as the single resolver: the row
10638
+ * guard, validation, then the restrict gate and the tombstone. A row that is
10639
+ * missing, tombstoned or hidden answers `{ id, deleted: false }`. Per batch:
10640
+ * one resolution of the ids (shared with the guard) and one `deleteRows`
10641
+ * (one `findEdgesToMany`, one `tombstone`).
10642
+ */
10643
+ function deleteBatchResolver(typeName, dataset, edges, opts = {}) {
10644
+ const { policy } = opts;
10645
+ const batch = async (ctx, list) => {
10646
+ const n = list.length;
10647
+ if (n === 0) return [];
10648
+ const first = list[0];
10649
+ const ds = first.dataset ?? dataset;
10650
+ const edgeStore = first.edges ?? edges;
10651
+ const requested = list.map((args) => coerceId(args.params?.id));
10652
+ const targets = await resolveEntityRows(ds, typeName, requested);
10653
+ if (n > 1 && namesARowTwice(targets)) return eachAlone(batch, ctx, list);
10654
+ const hidden = guardRowWrites(ctx, policy, list, targets);
10655
+ const refusal = new FirstRefusal(n);
10656
+ for (let i = 0; refusal.live(i); i++) if (!hidden[i]) refusal.check(i, () => prepareDelete(typeName, list[i]?.params));
10657
+ const doomed = [];
10658
+ for (let i = 0; refusal.live(i); i++) if (!hidden[i] && (targets[i] ?? null) !== null) doomed.push(i);
10659
+ try {
10660
+ await deleteRows({
10661
+ dataset: ds,
10662
+ edges: edgeStore,
10663
+ type: typeName,
10664
+ ids: doomed.map((i) => targets[i].id)
10665
+ });
10666
+ } catch (err) {
10667
+ if (!isRestrictViolation(err)) throw err;
10668
+ const blocked = err.blockedBy[0]?.to.id;
10669
+ const at = doomed.find((i) => String(targets[i]?.id) === String(blocked));
10670
+ if (at === void 0) throw err;
10671
+ refusal.refuse(at, err);
10672
+ }
10673
+ refusal.throwIfRefused();
10674
+ const out = [];
10675
+ for (const [i, args] of list.entries()) {
10676
+ const target = targets[i] ?? null;
10677
+ if (hidden[i] || target === null) {
10678
+ out.push({
10679
+ id: requested[i],
10680
+ deleted: false
10681
+ });
10682
+ continue;
10683
+ }
10684
+ args.onWrite?.({
10685
+ ns: ds.namespace,
10686
+ type: typeName,
10687
+ id: target.id,
10688
+ operation: "delete",
10689
+ row: target
10690
+ });
10691
+ out.push({
10692
+ id: target.id,
10693
+ deleted: true
10694
+ });
10695
+ }
10696
+ return out;
10697
+ };
10698
+ return batch;
10699
+ }
10700
+ /** `create<T>` without crossRef edges: the batch resolver with `edges: null`, one element. */
10701
+ function createResolver(typeName, dataset, options = {}) {
10702
+ return singleFrame(createBatchResolver(typeName, dataset, null, options));
10703
+ }
10704
+ /** `update<T>`: the batch resolver with one element. */
10705
+ function updateResolver(typeName, dataset, edges, options = {}) {
10706
+ return singleFrame(updateBatchResolver(typeName, dataset, edges, options));
10707
+ }
10708
+ /** `delete<T>`: the batch resolver with one element. */
10709
+ function deleteResolver(typeName, dataset, edges) {
10710
+ return singleFrame(deleteBatchResolver(typeName, dataset, edges));
9509
10711
  }
9510
10712
 
9511
10713
  //#endregion
9512
- //#region ../../packages/substrate-sdk/src/autocrud/autocrud-update.ts
10714
+ //#region ../../packages/substrate-sdk/src/autocrud/filter-writes.ts
9513
10715
  /**
9514
- * The trusted write-tail of an id-based update: applies the whole patch to
9515
- * the live row in one round-trip, stamping updatedAt/updatedBy, and emits
9516
- * the §5.4 onWrite event when a row actually landed. Returns null when the
9517
- * row is missing or tombstoned.
10716
+ * autoCRUD `updateMany<T>` (`{ where, set }`) and `deleteMany<T>` (`{ where }`).
9518
10717
  *
9519
- * `updateResolver` delegates here after its guards; custom system-stamped
9520
- * resolvers (e.g. a status transition such as `approveRequest`) call it
9521
- * directly with an already-resolved row id. It deliberately runs NO
9522
- * client-field guards — that is what lets a system writer stamp serverSet
9523
- * fields like `approvedAt`. Callers own validation and permission
9524
- * checks; this owns the metadata idiom so it stays single-sourced.
10718
+ * The engine validates `where` as a query's on the target type before the
10719
+ * resolver runs (the entry's `filterTarget`). The resolver runs `update<T>`'s
10720
+ * checks on `set`, then writes:
10721
+ *
10722
+ * - With no policy on the type: one `updateWhere` / `deleteWhere` statement
10723
+ * with the caller's `where`.
10724
+ * - With a policy: the matches are read first (refused past `maxMatch`), the
10725
+ * policy runs once per matched row with `{ id, ...set }` (`{ id }` for a
10726
+ * delete), as `update<T>` / `delete<T>` would run it. Any deny refuses the
10727
+ * frame; a row filter drops the rows the caller cannot see. The write is
10728
+ * then by those ids: one `patchRows` (constant text, locks in id order), or
10729
+ * `deleteRows` (restrict gate, then one `tombstone`).
10730
+ *
10731
+ * Neither is served while a plugin has replaced its single-row counterpart
10732
+ * (`update<T>` / `delete<T>`): the custom logic there would be bypassed.
10733
+ *
10734
+ * Every changed row is announced with `onWrite`, so subscribers and post-write
10735
+ * hooks see each id. The result is `{ count, ids, idsTruncated }`, `ids` cut
10736
+ * at `idsCap`.
9525
10737
  */
9526
- async function applyUpdatePatch(ds, typeName, rowId, patchFields, ctx, onWrite) {
9527
- const { row: merged } = await ds.conditionalUpdate(typeName, rowId, {}, patchFields, resolveIdentity(ctx), ctx.now);
9528
- if (merged === null) return null;
9529
- onWrite?.({
9530
- ns: ds.namespace,
9531
- type: typeName,
9532
- id: merged.id,
9533
- operation: "update",
9534
- row: merged
9535
- });
9536
- return merged;
9537
- }
9538
- function updateResolver(typeName, dataset, edges, options = {}) {
9539
- const crossRefs = collectCrossRefFields(options.fields);
10738
+ /** `updateMany<T>`: `set` merged into every live row `where` matches. */
10739
+ function updateManyResolver(typeName, dataset, edges, opts = {}) {
10740
+ const { fields, policy, postWrite } = opts;
10741
+ const crossRefs = collectCrossRefFields(fields);
10742
+ const op = `updateMany${typeName}`;
9540
10743
  return async (ctx, args) => {
9541
10744
  const ds = args.dataset ?? dataset;
9542
- const id = coerceId(args.params?.id);
9543
- if (id === void 0) throw new ResolverFrameError("missing_id", `updateResolver('${typeName}'): params.id is required`, { field: "id" });
9544
- if (options.fields) assertNoClientServerFields(args.params ?? {}, options.fields, "update");
9545
- const sent = dropUndefinedParams(args.params ?? {});
9546
- const inParams = options.fields !== void 0 ? normaliseVocabValues(sent, options.fields) : sent;
9547
- if ("_deletedAt" in inParams) throw new ReservedField("_deletedAt");
9548
- if (options.fields) assertEnumValues(inParams, options.fields);
9549
- if (options.fields) {
9550
- assertNoUnknownFields(inParams, options.fields, "update");
9551
- assertNoNullOnNonNullable(inParams, options.fields, "update");
9552
- assertScalarTypes(inParams, options.fields, "update");
10745
+ if (opts.ownsSingleRowWrite?.() === false) throw replaced(op, `update${typeName}`);
10746
+ const where = whereOf(op, args.params);
10747
+ const raw = args.params?.set;
10748
+ if (!isPlainObject(raw) || Object.keys(raw).length === 0) throw new ResolverFrameError("invalid_params", `${op}: params.set must name a field`, { param: "set" });
10749
+ if (Object.hasOwn(raw, "id")) throw new ResolverFrameError("invalid_params", `${op}: set cannot change id`, { field: "id" });
10750
+ const set = preparePatch(raw, fields);
10751
+ if (crossRefs.length > 0) try {
10752
+ await assertCrossRefTargetsExistMany(args, crossRefs, [set], ds.namespace);
10753
+ } catch (err) {
10754
+ throw isBatchElementError(err) ? err.cause : err;
9553
10755
  }
9554
- const rowId = await resolveEntityId(ds, typeName, id);
9555
- if (rowId === null) throw new ResolverFrameError("not_found", `updateResolver('${typeName}'): no row with id '${String(id)}'`, { field: "id" });
9556
- const params = inParams;
9557
- await assertCrossRefTargetsExist(args, crossRefs, params, ds.namespace);
9558
- const patchFields = {};
9559
- for (const [field, value] of Object.entries(params)) {
9560
- if (field === "id") continue;
9561
- patchFields[field] = value;
9562
- }
9563
- const merged = await applyUpdatePatch(ds, typeName, rowId, patchFields, ctx, args.onWrite);
9564
- if (merged === null) throw new ResolverFrameError("not_found", `updateResolver('${typeName}'): no row with id '${String(id)}'`, { field: "id" });
9565
- if (crossRefs.length > 0) {
9566
- const edgeStore = args.edges ?? edges;
9567
- const fromRef = {
10756
+ const actor = resolveIdentity(ctx);
10757
+ const { maxMatch, idsCap } = args.filterWriteLimits ?? DEFAULT_FILTER_WRITE_LIMITS;
10758
+ let rows;
10759
+ if (policy === void 0) {
10760
+ const updateWhere = ds.updateWhere?.bind(ds);
10761
+ if (updateWhere === void 0) throw unsupported(op, ds);
10762
+ ({rows} = await updateWhere(typeName, where, set, {
10763
+ maxMatch,
10764
+ actor,
10765
+ now: ctx.now
10766
+ }));
10767
+ } else {
10768
+ const kept = await policyKept(ctx, args, ds, typeName, where, policy, maxMatch, set);
10769
+ rows = (await ds.patchRows(typeName, kept.map((r) => ({
10770
+ id: r.id,
10771
+ patch: set
10772
+ })), actor, ctx.now)).filter((r) => r !== null);
10773
+ }
10774
+ await syncCrossRefEdges(args.edges ?? edges, {
10775
+ ns: ds.namespace,
10776
+ type: typeName
10777
+ }, crossRefs, rows.map((r) => ({
10778
+ id: r.id,
10779
+ params: set
10780
+ })));
10781
+ for (const row of rows) {
10782
+ args.onWrite?.({
10783
+ ns: ds.namespace,
10784
+ type: typeName,
10785
+ id: row.id,
10786
+ operation: "update",
10787
+ row
10788
+ });
10789
+ if (postWrite !== void 0) await runPostWrite(postWrite, typeName, dataset, row, ctx, args);
10790
+ }
10791
+ return resultOf(rows, idsCap);
10792
+ };
10793
+ }
10794
+ /** `deleteMany<T>`: tombstones every live row `where` matches, behind the restrict gate. */
10795
+ function deleteManyResolver(typeName, dataset, edges, opts = {}) {
10796
+ const { policy } = opts;
10797
+ const op = `deleteMany${typeName}`;
10798
+ return async (ctx, args) => {
10799
+ const ds = args.dataset ?? dataset;
10800
+ if (opts.ownsSingleRowWrite?.() === false) throw replaced(op, `delete${typeName}`);
10801
+ const edgeStore = args.edges ?? edges;
10802
+ const where = whereOf(op, args.params);
10803
+ const { maxMatch, idsCap } = args.filterWriteLimits ?? DEFAULT_FILTER_WRITE_LIMITS;
10804
+ let rows;
10805
+ if (policy === void 0) {
10806
+ const deleteWhere = ds.deleteWhere?.bind(ds);
10807
+ if (deleteWhere === void 0) throw unsupported(op, ds);
10808
+ ({rows} = await deleteWhere(typeName, where, { maxMatch }));
10809
+ await assertNoRestrictEdges(edgeStore, {
9568
10810
  ns: ds.namespace,
10811
+ type: typeName
10812
+ }, rows.map((r) => r.id));
10813
+ } else {
10814
+ const kept = await policyKept(ctx, args, ds, typeName, where, policy, maxMatch, {});
10815
+ const done = new Set((await deleteRows({
10816
+ dataset: ds,
10817
+ edges: edgeStore,
9569
10818
  type: typeName,
9570
- id: rowId
10819
+ ids: kept.map((r) => r.id)
10820
+ })).map(String));
10821
+ rows = kept.filter((r) => done.has(String(r.id)));
10822
+ }
10823
+ for (const row of rows) args.onWrite?.({
10824
+ ns: ds.namespace,
10825
+ type: typeName,
10826
+ id: row.id,
10827
+ operation: "delete",
10828
+ row
10829
+ });
10830
+ return resultOf(rows, idsCap);
10831
+ };
10832
+ }
10833
+ /**
10834
+ * The matched rows a policy lets the caller write: the matches are read
10835
+ * (refused past `maxMatch`), the policy runs per row with `{ id, ...set }`,
10836
+ * a deny on any row refuses the frame, and a row filter drops the rows the
10837
+ * caller cannot see.
10838
+ */
10839
+ async function policyKept(ctx, args, ds, typeName, where, policy, maxMatch, set) {
10840
+ const { rows } = await ds.read(typeName, {
10841
+ where,
10842
+ limit: maxMatch + 1
10843
+ });
10844
+ if (rows.length > maxMatch) throw filterTooBroad(ds.namespace, typeName, maxMatch);
10845
+ const kept = [];
10846
+ for (const row of rows) {
10847
+ let decision;
10848
+ try {
10849
+ decision = policy(ctx, {
10850
+ ...args,
10851
+ params: {
10852
+ id: row.id,
10853
+ ...set
10854
+ }
10855
+ });
10856
+ } catch {
10857
+ decision = {
10858
+ allow: false,
10859
+ reason: "policy error"
9571
10860
  };
9572
- await reconcileCrossRefEdgesOnUpdate(edgeStore, fromRef, crossRefs, params);
9573
10861
  }
9574
- return merged;
10862
+ if (!decision.allow) throw new ResolverFrameError("policy_denied", decision.reason ?? "policy denied");
10863
+ if (applyRowFilters(decision, [row], ctx).length > 0) kept.push(row);
10864
+ }
10865
+ return kept;
10866
+ }
10867
+ function replaced(op, single) {
10868
+ return new ResolverFrameError("capability_unsupported", `${op}: ${single} has custom logic that a write by filter would bypass; write by id`);
10869
+ }
10870
+ function whereOf(op, params) {
10871
+ const where = params?.where;
10872
+ if (!isPlainObject(where)) throw new ResolverFrameError("invalid_params", `${op}: params.where is required`, { param: "where" });
10873
+ return where;
10874
+ }
10875
+ function resultOf(rows, idsCap) {
10876
+ const ids = rows.map((r) => r.id).sort((a, b) => {
10877
+ const x = String(a);
10878
+ const y = String(b);
10879
+ return x < y ? -1 : x > y ? 1 : 0;
10880
+ });
10881
+ return {
10882
+ count: rows.length,
10883
+ ids: ids.slice(0, idsCap),
10884
+ idsTruncated: rows.length > idsCap
9575
10885
  };
9576
10886
  }
10887
+ function unsupported(op, ds) {
10888
+ return new ResolverFrameError("capability_unsupported", `${op}: the '${ds.namespace}' store does not write by filter`);
10889
+ }
10890
+ function isPlainObject(v) {
10891
+ return typeof v === "object" && v !== null && !Array.isArray(v);
10892
+ }
9577
10893
 
9578
10894
  //#endregion
9579
10895
  //#region ../../packages/substrate-sdk/src/autocrud/index.ts
@@ -9589,41 +10905,29 @@ function updateResolver(typeName, dataset, edges, options = {}) {
9589
10905
  * - mutation: `updateTodo` (id-based multi-field update, one `write()`
9590
10906
  * inside the engine's G1 transaction)
9591
10907
  * - mutation: `deleteTodo` (two-phase delete, §6.2)
9592
- *
9593
- * Filter-based update — `updateTodo({ where }, { ...newFields })` — is spec
9594
- * §5.2.1 and not implemented.
10908
+ * - mutation: `updateManyTodo` (`{ where, set }`) and `deleteManyTodo`
10909
+ * (`{ where }`), by filter (`./filter-writes.ts`)
9595
10910
  *
9596
10911
  * `registry` is typed structurally via `AutoCrudRegistry` so this package takes
9597
10912
  * no runtime dependency on `@mnmal-ai/substrate-core`; the core `Registry`
9598
10913
  * satisfies the interface shape.
9599
10914
  */
9600
10915
  /**
9601
- * The narrow surface `installAutoCrud` needs from a registry. The core
9602
- * `Registry` class satisfies this structurally.
9603
- *
9604
- * Resolver signature matches the core `Resolver` type exactly — typed against
9605
- * `(ctx, args) => Promise<Row | Row[] | null>` so autocrud's `get` can surface
9606
- * null without sentinel gymnastics.
9607
- */
9608
- /**
9609
- * A row policy filters what a read returns, so on its own it would let an
9610
- * update or delete reach a row the caller cannot read. Run the policy's row
9611
- * filters against the stored row first and answer as for a missing row.
10916
+ * A namespace declares both `X` and `ManyX`: `X`'s `updateManyX` /
10917
+ * `deleteManyX` are `ManyX`'s `update<T>` / `delete<T>` keys.
9612
10918
  */
9613
- function guardRowWrite(typeName, dataset, policy, hidden, resolver) {
9614
- if (policy === void 0) return resolver;
9615
- return async (ctx, args) => {
9616
- const id = coerceId(args.params?.id);
9617
- if (id === void 0) return resolver(ctx, args);
9618
- const decision = policy(ctx, args);
9619
- if (decision.obligations === void 0 || decision.obligations.length === 0) return resolver(ctx, args);
9620
- const ds = args.dataset ?? dataset;
9621
- const rowId = await resolveEntityId(ds, typeName, id);
9622
- const stored = rowId === null ? void 0 : (await ds.read(typeName, { id: rowId })).rows[0];
9623
- if (stored !== void 0 && applyRowFilters(decision, [stored], ctx).length === 0) return hidden(id);
9624
- return resolver(ctx, args);
9625
- };
9626
- }
10919
+ var AutoCrudNameCollisionError = class extends Error {
10920
+ namespace;
10921
+ type;
10922
+ other;
10923
+ name = "AutoCrudNameCollisionError";
10924
+ constructor(namespace, type, other) {
10925
+ super(`namespace '${namespace}' declares both '${type}' and '${other}': their generated updateMany/deleteMany and update/delete mutation keys collide. Rename one of the types.`);
10926
+ this.namespace = namespace;
10927
+ this.type = type;
10928
+ this.other = other;
10929
+ }
10930
+ };
9627
10931
  /**
9628
10932
  * Wrap the base create resolver so every crossRef field with a non-null value
9629
10933
  * emits a corresponding edge post-insert — the crossRef set derives from the
@@ -9639,56 +10943,7 @@ function guardRowWrite(typeName, dataset, policy, hidden, resolver) {
9639
10943
  * caller — the SDK does not swallow.
9640
10944
  */
9641
10945
  function createResolverWithEdges(typeName, dataset, edges, options = {}) {
9642
- const { fields, postWrite } = options;
9643
- const crossRefs = collectCrossRefFields(fields);
9644
- const base = createResolver(typeName, dataset, fields !== void 0 ? { fields } : {});
9645
- return async (ctx, args) => {
9646
- const ds = args.dataset ?? dataset;
9647
- await assertCrossRefTargetsExist(args, crossRefs, args.params ?? {}, ds.namespace);
9648
- const createdRow = await base(ctx, args);
9649
- const edgeStore = args.edges ?? edges;
9650
- const edgeWrites = [];
9651
- for (const { fieldName, def } of crossRefs) {
9652
- const value = createdRow[fieldName];
9653
- if (value == null) continue;
9654
- if (typeof value !== "string" && typeof value !== "number") continue;
9655
- edgeWrites.push(edgeStore.write({
9656
- from: {
9657
- ns: ds.namespace,
9658
- type: typeName,
9659
- id: createdRow.id
9660
- },
9661
- to: {
9662
- ns: def.ns,
9663
- type: def.type,
9664
- id: value
9665
- },
9666
- fieldName,
9667
- policy: def.onDelete
9668
- }));
9669
- }
9670
- if (edgeWrites.length > 0) await Promise.all(edgeWrites);
9671
- if (postWrite !== void 0) await runPostWrite(postWrite, typeName, dataset, createdRow, ctx, args);
9672
- return createdRow;
9673
- };
9674
- }
9675
- /**
9676
- * Runs `postWrite` once the engine transaction commits, on the row as
9677
- * committed, so its side effects (embeddings, indexes) never describe a
9678
- * rolled-back write or hold a connection across the transaction. A rolled-back
9679
- * write skips it. Outside a transaction (no `afterTx`) it runs at once.
9680
- */
9681
- async function runPostWrite(postWrite, typeName, dataset, row, ctx, args) {
9682
- if (args.afterTx === void 0) {
9683
- await postWrite(row, ctx);
9684
- return;
9685
- }
9686
- args.afterTx(async (outcome) => {
9687
- if (!outcome.committed) return;
9688
- const { rows } = await dataset.read(typeName, { id: row.id });
9689
- const committed = rows[0];
9690
- if (committed !== void 0) await postWrite(committed, ctx);
9691
- });
10946
+ return singleFrame(createBatchResolver(typeName, dataset, edges, options));
9692
10947
  }
9693
10948
  /**
9694
10949
  * `id` is coerced to string at the wire per the pg convention. Every autoCRUD
@@ -9725,6 +10980,31 @@ function deleteReturnFieldDef() {
9725
10980
  }
9726
10981
  };
9727
10982
  }
10983
+ /** `updateMany<T>` / `deleteMany<T>` return shape: `{ count, ids, idsTruncated }`. */
10984
+ function filterWriteReturnFieldDef() {
10985
+ return {
10986
+ kind: "struct",
10987
+ fields: {
10988
+ count: {
10989
+ kind: "scalar",
10990
+ type: "number"
10991
+ },
10992
+ ids: {
10993
+ kind: "list",
10994
+ of: ID_FIELD
10995
+ },
10996
+ idsTruncated: {
10997
+ kind: "scalar",
10998
+ type: "boolean"
10999
+ }
11000
+ }
11001
+ };
11002
+ }
11003
+ /** `updateMany<T>`'s params: a filter and a patch. Both opaque here; the engine and resolver check them. */
11004
+ const FILTER_WHERE = {
11005
+ kind: "scalar",
11006
+ type: "json"
11007
+ };
9728
11008
  /** `purge<T>` return shape: `{ id, purged }`. */
9729
11009
  function purgeReturnFieldDef() {
9730
11010
  return {
@@ -9747,7 +11027,31 @@ const installedOptions = /* @__PURE__ */ new WeakMap();
9747
11027
  function autoCrudOptionsOf(typeResolver) {
9748
11028
  return installedOptions.get(typeResolver);
9749
11029
  }
11030
+ /** `X`'s first letter upper-cased: the suffix of its generated mutation keys. */
11031
+ function capOf(typeName) {
11032
+ return typeName.charAt(0).toUpperCase() + typeName.slice(1);
11033
+ }
11034
+ /**
11035
+ * Throws when another autoCRUD type in `registry` would register the same
11036
+ * mutation keys: `X` against `ManyX`, in either install order. A registry
11037
+ * without `get` (a reinstall's replace writer) is not checked.
11038
+ */
11039
+ function assertNoManyCollision(registry, dataset, typeName) {
11040
+ const get = registry.get?.bind(registry);
11041
+ if (get === void 0) return;
11042
+ const cap = capOf(typeName);
11043
+ const others = [`Many${cap}`, `many${cap}`];
11044
+ if (cap.startsWith("Many") && cap.length > 4) {
11045
+ const base = cap.slice(4);
11046
+ others.push(base, base.charAt(0).toLowerCase() + base.slice(1));
11047
+ }
11048
+ for (const other of others) {
11049
+ const entry = other === typeName ? void 0 : get(other);
11050
+ if (entry?.kind === "type" && autoCrudOptionsOf(entry.resolver) !== void 0) throw new AutoCrudNameCollisionError(dataset.namespace, typeName, other);
11051
+ }
11052
+ }
9750
11053
  function installAutoCrud(registry, typeName, dataset, edges, options = {}) {
11054
+ assertNoManyCollision(registry, dataset, typeName);
9751
11055
  const policy = options.policy;
9752
11056
  const fields = options.fields;
9753
11057
  const postWrite = options.postWrite;
@@ -9759,21 +11063,31 @@ function installAutoCrud(registry, typeName, dataset, edges, options = {}) {
9759
11063
  const list = listResolver(typeName, dataset, fields !== void 0 ? { fields } : {});
9760
11064
  installedOptions.set(list, options);
9761
11065
  const get = getResolver(typeName, dataset);
9762
- const create = createResolverWithEdges(typeName, dataset, edges, {
11066
+ const hooks = {
9763
11067
  ...fields !== void 0 ? { fields } : {},
11068
+ ...policy !== void 0 ? { policy } : {},
9764
11069
  ...postWrite !== void 0 ? { postWrite } : {}
9765
- });
9766
- const baseUpdate = updateResolver(typeName, dataset, edges, fields !== void 0 ? { fields } : {});
9767
- const update = guardRowWrite(typeName, dataset, policy, () => null, postWrite !== void 0 ? async (ctx, args) => {
9768
- const result = await baseUpdate(ctx, args);
9769
- if (result !== null) await runPostWrite(postWrite, typeName, dataset, result, ctx, args);
9770
- return result;
9771
- } : baseUpdate);
9772
- const del = guardRowWrite(typeName, dataset, policy, (id) => ({
9773
- id,
9774
- deleted: false
9775
- }), deleteResolver(typeName, dataset, edges));
11070
+ };
11071
+ const createBatch = createBatchResolver(typeName, dataset, edges, hooks);
11072
+ const updateBatch = updateBatchResolver(typeName, dataset, edges, hooks);
11073
+ const deleteBatch = deleteBatchResolver(typeName, dataset, edges, hooks);
11074
+ const create = singleFrame(createBatch);
11075
+ const update = singleFrame(updateBatch);
11076
+ const del = singleFrame(deleteBatch);
9776
11077
  const purge = purgeResolver(typeName, dataset);
11078
+ const cap = capOf(typeName);
11079
+ const stillOwn = (key, own) => () => {
11080
+ const get = registry.get?.bind(registry);
11081
+ return get !== void 0 && get(key)?.resolver === own;
11082
+ };
11083
+ const updateMany = updateManyResolver(typeName, dataset, edges, {
11084
+ ...hooks,
11085
+ ownsSingleRowWrite: stillOwn(`update${cap}`, update)
11086
+ });
11087
+ const deleteMany = deleteManyResolver(typeName, dataset, edges, {
11088
+ ...hooks,
11089
+ ownsSingleRowWrite: stillOwn(`delete${cap}`, del)
11090
+ });
9777
11091
  const typeFields = fields ?? {};
9778
11092
  registry.register(typeName, {
9779
11093
  resolver: list,
@@ -9784,7 +11098,6 @@ function installAutoCrud(registry, typeName, dataset, edges, options = {}) {
9784
11098
  ...options.indexes !== void 0 ? { indexes: options.indexes } : {},
9785
11099
  ...options.expectedSize !== void 0 ? { expectedSize: options.expectedSize } : {}
9786
11100
  });
9787
- const cap = typeName.charAt(0).toUpperCase() + typeName.slice(1);
9788
11101
  registry.register(`get${cap}`, {
9789
11102
  resolver: get,
9790
11103
  kind: "mutation",
@@ -9796,6 +11109,7 @@ function installAutoCrud(registry, typeName, dataset, edges, options = {}) {
9796
11109
  });
9797
11110
  registry.register(`create${cap}`, {
9798
11111
  resolver: create,
11112
+ batch: createBatch,
9799
11113
  kind: "mutation",
9800
11114
  verb: "create",
9801
11115
  params: typeFields,
@@ -9805,6 +11119,7 @@ function installAutoCrud(registry, typeName, dataset, edges, options = {}) {
9805
11119
  });
9806
11120
  registry.register(`update${cap}`, {
9807
11121
  resolver: update,
11122
+ batch: updateBatch,
9808
11123
  kind: "mutation",
9809
11124
  verb: "update",
9810
11125
  params: {
@@ -9817,12 +11132,34 @@ function installAutoCrud(registry, typeName, dataset, edges, options = {}) {
9817
11132
  });
9818
11133
  registry.register(`delete${cap}`, {
9819
11134
  resolver: del,
11135
+ batch: deleteBatch,
9820
11136
  kind: "mutation",
9821
11137
  verb: "delete",
9822
11138
  params: { id: ID_FIELD },
9823
11139
  returns: deleteReturnFieldDef(),
9824
11140
  ...policy !== void 0 ? { policy } : {}
9825
11141
  });
11142
+ registry.register(`updateMany${cap}`, {
11143
+ resolver: updateMany,
11144
+ kind: "mutation",
11145
+ verb: "update",
11146
+ filterTarget: typeName,
11147
+ params: {
11148
+ where: FILTER_WHERE,
11149
+ set: typeStructFieldDef(typeFields)
11150
+ },
11151
+ returns: filterWriteReturnFieldDef(),
11152
+ ...policy !== void 0 ? { policy } : {}
11153
+ });
11154
+ registry.register(`deleteMany${cap}`, {
11155
+ resolver: deleteMany,
11156
+ kind: "mutation",
11157
+ verb: "delete",
11158
+ filterTarget: typeName,
11159
+ params: { where: FILTER_WHERE },
11160
+ returns: filterWriteReturnFieldDef(),
11161
+ ...policy !== void 0 ? { policy } : {}
11162
+ });
9826
11163
  if (options.purgeable === true) {
9827
11164
  const capabilityName = options.adminCapability ?? "admin";
9828
11165
  const adminGate = requireCapability(capabilityName);
@@ -10278,6 +11615,17 @@ const KEY_FIELDS = {
10278
11615
  capabilities: field.string({ indexed: false }),
10279
11616
  revokedAt: field.date({ nullable: true })
10280
11617
  };
11618
+ /**
11619
+ * One live key per kid: two would make verification ambiguous. Revoked and
11620
+ * tombstoned keys may share it. The name is the one the old layouts' baseline
11621
+ * gave the same index on `rows`.
11622
+ */
11623
+ const KEY_INDEXES = [{
11624
+ name: "substrate_key_live_kid_uniq",
11625
+ fields: ["kid"],
11626
+ unique: true,
11627
+ where: { revokedAt: null }
11628
+ }];
10281
11629
  const INVITE_FIELDS = {
10282
11630
  namespaces: field.string({ indexed: false }),
10283
11631
  capabilities: field.string({ indexed: false }),
@@ -10311,6 +11659,13 @@ const INVITE_FIELDS = {
10311
11659
  * - `destructive_op_refused` : kill switch refused a hard-destructive operation
10312
11660
  * - `index_proposed` : `propose_index` added, removed or reordered an index, or
10313
11661
  * dismissed a recommendation; `details` names the action
11662
+ * - `field_pending` : a field added at runtime (propose_field) is held in jsonb
11663
+ * until the promotion sweep gives it a column
11664
+ * - `field_promoted` : the promotion sweep gave a field its column and moved its values
11665
+ * - `field_promotion_failed` : a field's promotion failed, or its table's lock stayed busy
11666
+ * three sweeps in a row; `details.error` says why
11667
+ * The three `field_*` kinds carry `details` `{ namespace, type, field, attempts, error? }`
11668
+ * and actorKid `'system'`.
10314
11669
  *
10315
11670
  * `details` is an opaque JSON body — `field.json()` round-trips the value
10316
11671
  * unchanged through encoder/decoder, no JSON.stringify boundary needed.
@@ -10504,8 +11859,9 @@ function createKeyRegistry(opts) {
10504
11859
  * old revoked one — and the read is unordered, so liveness, via the same
10505
11860
  * `isLive` predicate `lookup` and `refresh` use, picks the winner.
10506
11861
  *
10507
- * Not expressible as `where: { revokedAt: { eq: null } }`: a FUTURE
10508
- * `revokedAt` is a scheduled revocation that must still resolve.
11862
+ * Not expressible as `where: { revokedAt: { eq: null } }`: a row written
11863
+ * before future `revokedAt` values were refused may still hold one, and
11864
+ * `isLive` reads it as live until then.
10509
11865
  */
10510
11866
  async function loadAll() {
10511
11867
  const { rows } = await dataset.read("Key", {});
@@ -10818,6 +12174,20 @@ async function backfillBootstrapAuditIfNeeded(dataset) {
10818
12174
  });
10819
12175
  }
10820
12176
  /**
12177
+ * Refuses a future `revokedAt`. The registry reads such a key as live until
12178
+ * then, but the live-kid unique index (partial on `revokedAt IS NULL`) reads
12179
+ * it as revoked, so a second live key for the kid would slip past the index.
12180
+ * Checked against the clock, not `ctx.now`, which predates a route's own stamp.
12181
+ */
12182
+ function assertRevokedAtNotFuture(params) {
12183
+ const value = params?.revokedAt;
12184
+ if (value === void 0 || value === null || value === "") return;
12185
+ if (new Date(value).getTime() > Date.now()) throw new ResolverFrameError("invalid_params", "Key: revokedAt may not be in the future; revoke at the moment it should take effect", {
12186
+ field: "revokedAt",
12187
+ supplied: value
12188
+ });
12189
+ }
12190
+ /**
10821
12191
  * Throws a `ResolverFrameError` with
10822
12192
  * `code: 'hmac_not_allowed'` on HS256 / missing algorithm / unknown algorithm
10823
12193
  * so the engine surfaces a structured envelope error instead of persisting an
@@ -10865,6 +12235,7 @@ async function installSystemNamespace(opts) {
10865
12235
  createKey: (base) => lockedKeyWrite(async (ctx, args) => {
10866
12236
  assertAllowedAlgorithm(args.params);
10867
12237
  assertGrantParses(args.params ?? {});
12238
+ assertRevokedAtNotFuture(args.params);
10868
12239
  const newKid = args.params?.kid;
10869
12240
  if (isLive(args.params) && (await keysFor(args)).some((r) => r.kid === newKid && isLive(r))) throw new ResolverFrameError("kid_already_live", `kid '${String(newKid)}' is already registered and live — rotate or revoke it before re-registering`);
10870
12241
  const result = await base(ctx, args);
@@ -10890,6 +12261,7 @@ async function installSystemNamespace(opts) {
10890
12261
  updateKey: (base) => lockedKeyWrite(async (ctx, args) => {
10891
12262
  if (args.params?.kid !== void 0) throw new Error("Key.kid is immutable; rotate or re-register instead of changing kid");
10892
12263
  if (args.params?.algorithm !== void 0) assertAllowedAlgorithm(args.params);
12264
+ assertRevokedAtNotFuture(args.params);
10893
12265
  const params = args.params ?? {};
10894
12266
  const rows = await keysFor(args);
10895
12267
  const target = rows.find((r) => r.id === params.id);
@@ -10956,7 +12328,8 @@ async function installSystemNamespace(opts) {
10956
12328
  })
10957
12329
  });
10958
12330
  installAutoCrud(wrappedForSubstrateKey, "Key", opts.dataset, opts.edges, {
10959
- fields: mergeIdField(KEY_FIELDS),
12331
+ fields: KEY_DEF.fields,
12332
+ indexes: KEY_DEF.indexes,
10960
12333
  policy: adminGate,
10961
12334
  purgeable: true,
10962
12335
  adminCapability
@@ -10995,7 +12368,7 @@ async function installSystemNamespace(opts) {
10995
12368
  }
10996
12369
  });
10997
12370
  installAutoCrud(wrappedForSubstrateInvite, INVITE_TYPE, opts.dataset, opts.edges, {
10998
- fields: mergeIdField(INVITE_FIELDS),
12371
+ fields: INVITE_DEF.fields,
10999
12372
  policy: adminGate,
11000
12373
  purgeable: true,
11001
12374
  adminCapability
@@ -11012,31 +12385,31 @@ async function installSystemNamespace(opts) {
11012
12385
  }
11013
12386
  } });
11014
12387
  installAutoCrud(wrappedForSubstrateAuditEvent, AUDIT_EVENT_TYPE, opts.dataset, opts.edges, {
11015
- fields: mergeIdField(AUDIT_EVENT_FIELDS),
12388
+ fields: AUDIT_EVENT_DEF.fields,
11016
12389
  policy: adminGate,
11017
12390
  purgeable: true,
11018
12391
  adminCapability
11019
12392
  });
11020
12393
  installAutoCrud(opts.registry, ENUM_VERDICT_TYPE, opts.dataset, opts.edges, {
11021
- fields: mergeIdField(ENUM_VERDICT_FIELDS),
12394
+ fields: ENUM_VERDICT_DEF.fields,
11022
12395
  policy: adminGate,
11023
12396
  purgeable: true,
11024
12397
  adminCapability
11025
12398
  });
11026
12399
  const indexGate = or(adminGate, and(requireCapability(INDEX_CAPABILITY), requireNamespace(SYSTEM_NAMESPACE)));
11027
12400
  installAutoCrud(opts.registry, STORE_PROFILE_TYPE, opts.dataset, opts.edges, {
11028
- fields: mergeIdField(STORE_PROFILE_FIELDS),
12401
+ fields: STORE_PROFILE_DEF.fields,
11029
12402
  policy: indexGate,
11030
12403
  adminCapability
11031
12404
  });
11032
12405
  installAutoCrud(opts.registry, INDEX_RECOMMENDATION_TYPE, opts.dataset, opts.edges, {
11033
- fields: mergeIdField(INDEX_RECOMMENDATION_FIELDS),
12406
+ fields: INDEX_RECOMMENDATION_DEF.fields,
11034
12407
  policy: indexGate,
11035
12408
  purgeable: true,
11036
12409
  adminCapability
11037
12410
  });
11038
12411
  installAutoCrud(opts.registry, ADVISOR_STATE_TYPE, opts.dataset, opts.edges, {
11039
- fields: mergeIdField(ADVISOR_STATE_FIELDS),
12412
+ fields: ADVISOR_STATE_DEF.fields,
11040
12413
  policy: and(adminGate, denyVerbs([
11041
12414
  "create",
11042
12415
  "update",
@@ -11073,6 +12446,33 @@ function mergeIdField(fields) {
11073
12446
  ...fields
11074
12447
  };
11075
12448
  }
12449
+ /** Each `_system` type's def, which `installAutoCrud` registers and `SYSTEM_TYPE_DEFS` lists. */
12450
+ const KEY_DEF = {
12451
+ fields: mergeIdField(KEY_FIELDS),
12452
+ indexes: KEY_INDEXES
12453
+ };
12454
+ const INVITE_DEF = { fields: mergeIdField(INVITE_FIELDS) };
12455
+ const AUDIT_EVENT_DEF = { fields: mergeIdField(AUDIT_EVENT_FIELDS) };
12456
+ const ENUM_VERDICT_DEF = { fields: mergeIdField(ENUM_VERDICT_FIELDS) };
12457
+ const STORE_PROFILE_DEF = { fields: mergeIdField(STORE_PROFILE_FIELDS) };
12458
+ const INDEX_RECOMMENDATION_DEF = { fields: mergeIdField(INDEX_RECOMMENDATION_FIELDS) };
12459
+ const ADVISOR_STATE_DEF = { fields: mergeIdField(ADVISOR_STATE_FIELDS) };
12460
+ /**
12461
+ * Each `_system` type's fields and declared indexes, as `installSystemNamespace`
12462
+ * registers them. A dataset that writes `_system` outside the engine (the admin
12463
+ * CLI) takes its type defs from here, so it creates each type's table as a boot
12464
+ * would: typed columns, and `Key`'s live-kid unique index. A test pins it to
12465
+ * the registry's entries both ways.
12466
+ */
12467
+ const SYSTEM_TYPE_DEFS = {
12468
+ ["Key"]: KEY_DEF,
12469
+ [INVITE_TYPE]: INVITE_DEF,
12470
+ [AUDIT_EVENT_TYPE]: AUDIT_EVENT_DEF,
12471
+ [ENUM_VERDICT_TYPE]: ENUM_VERDICT_DEF,
12472
+ [STORE_PROFILE_TYPE]: STORE_PROFILE_DEF,
12473
+ [INDEX_RECOMMENDATION_TYPE]: INDEX_RECOMMENDATION_DEF,
12474
+ [ADVISOR_STATE_TYPE]: ADVISOR_STATE_DEF
12475
+ };
11076
12476
 
11077
12477
  //#endregion
11078
12478
  //#region ../../packages/substrate-compose/src/_system/backfill-field.ts
@@ -11544,6 +12944,117 @@ function normaliseVocabRoute(deps) {
11544
12944
  };
11545
12945
  }
11546
12946
 
12947
+ //#endregion
12948
+ //#region ../../packages/substrate-compose/src/_system/promote-fields.ts
12949
+ /** The longest a sweep's ADD COLUMN queues writers behind its table lock. */
12950
+ const PROMOTE_LOCK_TIMEOUT_MS = 2e3;
12951
+ /** Rows a backfill statement moves at once. */
12952
+ const PROMOTE_BATCH_ROWS = 1e3;
12953
+ const SYSTEM_ACTOR = {
12954
+ kind: "system",
12955
+ id: "system"
12956
+ };
12957
+ /**
12958
+ * Writes each event as an `_system/AuditEvent`, then announces the rows.
12959
+ * Nothing when there are none, or when the engine has no `_system` dataset.
12960
+ */
12961
+ async function emitFieldEvents(engine, events, now = /* @__PURE__ */ new Date()) {
12962
+ const system = events.length === 0 ? void 0 : engine.datasetFor(SYSTEM_NAMESPACE);
12963
+ if (system === void 0) return;
12964
+ const rows = events.map(({ kind, ...details }) => buildAuditRow({
12965
+ actorKid: "system",
12966
+ kind,
12967
+ details,
12968
+ now
12969
+ }));
12970
+ const written = await system.write(AUDIT_EVENT_TYPE, rows, {
12971
+ identity: SYSTEM_ACTOR,
12972
+ now
12973
+ });
12974
+ await engine.announceWrites(written.ids.map((id, i) => ({
12975
+ ns: SYSTEM_NAMESPACE,
12976
+ type: AUDIT_EVENT_TYPE,
12977
+ id,
12978
+ operation: "create",
12979
+ row: written.rows?.[i] ?? {
12980
+ ...rows[i],
12981
+ id
12982
+ }
12983
+ })), SYSTEM_ACTOR);
12984
+ }
12985
+ /** The audit event for a sweep's event; none for `busy`. */
12986
+ function auditOf(e) {
12987
+ if (e.kind === "busy") return [];
12988
+ const { kind, ...rest } = e;
12989
+ return [{
12990
+ kind: kind === "promoted" ? "field_promoted" : "field_promotion_failed",
12991
+ ...rest
12992
+ }];
12993
+ }
12994
+ /**
12995
+ * The sweep, one at a time, with a timer every `intervalMs` (0: none; the
12996
+ * route still runs it). A dataset without `promotePendingFields` sweeps nothing.
12997
+ */
12998
+ function createPromoteFieldsRunner(deps) {
12999
+ const abort = new AbortController();
13000
+ const pass = async (retryConflicts) => {
13001
+ if (deps.dataset.promotePendingFields === void 0 || abort.signal.aborted) return [];
13002
+ const events = await deps.dataset.promotePendingFields({
13003
+ lockTimeoutMs: PROMOTE_LOCK_TIMEOUT_MS,
13004
+ batchRows: PROMOTE_BATCH_ROWS,
13005
+ signal: abort.signal,
13006
+ ...retryConflicts ? { retryConflicts } : {}
13007
+ });
13008
+ for (const e of events) {
13009
+ const outcome = e.kind === "busy" && e.error !== void 0 ? `busy (${e.error})` : `${e.kind} (attempt ${e.attempts})${e.error !== void 0 ? `: ${e.error}` : ""}`;
13010
+ process.stdout.write(`[substrate] field ${e.namespace}/${e.type}.${e.field}: ${outcome}\n`);
13011
+ }
13012
+ await emitFieldEvents(deps.engine, events.flatMap(auditOf));
13013
+ return events;
13014
+ };
13015
+ let tail = Promise.resolve();
13016
+ const run = (opts = {}) => {
13017
+ const next = tail.then(() => pass(opts.retryConflicts === true));
13018
+ tail = next.catch(() => void 0);
13019
+ return next;
13020
+ };
13021
+ let timer;
13022
+ if (deps.intervalMs > 0 && deps.dataset.promotePendingFields !== void 0) {
13023
+ let running = false;
13024
+ timer = setInterval(() => {
13025
+ if (running) return;
13026
+ running = true;
13027
+ run().catch((err) => {
13028
+ process.stderr.write(`[substrate] promotion sweep failed and will run again: ${err instanceof Error ? err.message : String(err)}\n`);
13029
+ }).finally(() => {
13030
+ running = false;
13031
+ });
13032
+ }, deps.intervalMs);
13033
+ timer.unref?.();
13034
+ }
13035
+ return {
13036
+ run,
13037
+ stop: async () => {
13038
+ clearInterval(timer);
13039
+ abort.abort();
13040
+ await tail;
13041
+ }
13042
+ };
13043
+ }
13044
+ /** `POST /substrate/v1/_system/promote-fields`: runs one sweep and answers its events. Admin-gated by the caller. */
13045
+ function promoteFieldsRoute(run) {
13046
+ return async () => {
13047
+ try {
13048
+ return jsonResponse(200, { events: await run({ retryConflicts: true }) });
13049
+ } catch (err) {
13050
+ return jsonResponse(500, {
13051
+ code: "promotion_failed",
13052
+ message: err instanceof Error ? err.message : String(err)
13053
+ });
13054
+ }
13055
+ };
13056
+ }
13057
+
11547
13058
  //#endregion
11548
13059
  //#region ../../packages/substrate-compose/src/_system/rate-limit.ts
11549
13060
  function createRateLimiter(opts) {
@@ -12737,6 +14248,14 @@ var MemoryShortIdStore = class {
12737
14248
  const b = this.bucket(ns, type);
12738
14249
  return b.next++;
12739
14250
  }
14251
+ /** `count` consecutive `allocateUnbound` ids, ascending. */
14252
+ async allocateUnboundMany(ns, type, count) {
14253
+ if (!Number.isSafeInteger(count) || count < 0) throw new Error(`MemoryShortIdStore: count must be a non-negative integer, got ${count}`);
14254
+ const b = this.bucket(ns, type);
14255
+ const first = b.next;
14256
+ b.next += count;
14257
+ return Array.from({ length: count }, (_, i) => first + i);
14258
+ }
12740
14259
  /**
12741
14260
  * Record the (shortId → rowId) pairing. Safe to call without a prior
12742
14261
  * `allocateUnbound` (the mapping is stored unconditionally).
@@ -13064,10 +14583,11 @@ var MemoryDataset = class MemoryDataset {
13064
14583
  rows: slice,
13065
14584
  hasMore
13066
14585
  };
14586
+ const columns = this.columnFieldNames(type);
13067
14587
  const page = (rows) => {
13068
14588
  const base = original.size === 0 ? rows : rows.map((r) => original.get(r) ?? r);
13069
- if (params.agg === void 0 && params.nested === void 0) return base;
13070
- return base.map((r) => ({
14589
+ if (params.agg === void 0 && params.nested === void 0) return base.map((r) => withoutNullColumns(columns, r));
14590
+ return base.map((r) => withoutNullColumns(columns, {
13071
14591
  ...r,
13072
14592
  ...walkProjection(r, params.agg, params.nested ?? {}, ctxFor(r), true)
13073
14593
  }));
@@ -13124,7 +14644,9 @@ var MemoryDataset = class MemoryDataset {
13124
14644
  const merged = [];
13125
14645
  const fallbackNow = (options?.now ?? /* @__PURE__ */ new Date()).toISOString();
13126
14646
  const fallbackActor = options?.identity ?? null;
13127
- const visible = this.typeDefLookup?.(type, this.namespace)?.ordering === "visible";
14647
+ const def = this.typeDefLookup?.(type, this.namespace);
14648
+ const visible = def?.ordering === "visible";
14649
+ const columns = columnFieldNames(def?.fields);
13128
14650
  for (const input of rows) {
13129
14651
  const row = {
13130
14652
  ...input,
@@ -13179,7 +14701,7 @@ var MemoryDataset = class MemoryDataset {
13179
14701
  b.set(rowToWrite.id, landed);
13180
14702
  }
13181
14703
  ids.push(row.id);
13182
- merged.push({ ...landed });
14704
+ merged.push(withoutNullColumns(columns, { ...landed }));
13183
14705
  }
13184
14706
  return {
13185
14707
  written: ids.length,
@@ -13187,6 +14709,10 @@ var MemoryDataset = class MemoryDataset {
13187
14709
  rows: merged
13188
14710
  };
13189
14711
  }
14712
+ /** The type's column fields, looked up once per call rather than per row. */
14713
+ columnFieldNames(type) {
14714
+ return columnFieldNames(this.typeDefLookup?.(type, this.namespace)?.fields);
14715
+ }
13190
14716
  async tombstone(type, ids) {
13191
14717
  const b = this.store.get(type);
13192
14718
  if (!b) return {
@@ -13291,7 +14817,7 @@ var MemoryDataset = class MemoryDataset {
13291
14817
  };
13292
14818
  return {
13293
14819
  matched: true,
13294
- row: { ...row }
14820
+ row: withoutNullColumns(this.columnFieldNames(type), { ...row })
13295
14821
  };
13296
14822
  }
13297
14823
  async updateField(ref, fieldName, value) {
@@ -13378,6 +14904,64 @@ var MemoryDataset = class MemoryDataset {
13378
14904
  async resolveShortId(type, shortId) {
13379
14905
  return this.shortIds.resolveShortId(this.namespace, type, shortId);
13380
14906
  }
14907
+ async allocateShortIds(type, count) {
14908
+ return this.shortIds.allocateUnboundMany(this.namespace, type, count);
14909
+ }
14910
+ async bindShortIds(type, pairs) {
14911
+ for (const p of pairs) await this.bindShortId(type, p.shortId, p.rowId);
14912
+ }
14913
+ async resolveShortIds(type, shortIds) {
14914
+ const out = /* @__PURE__ */ new Map();
14915
+ const b = this.store.get(type);
14916
+ for (const shortId of new Set(shortIds)) {
14917
+ const rowId = await this.shortIds.resolveShortId(this.namespace, type, shortId);
14918
+ if (rowId !== null && b?.get(rowId) !== void 0 && b.get(rowId)?._deletedAt == null) out.set(shortId, rowId);
14919
+ }
14920
+ return out;
14921
+ }
14922
+ async patchRows(type, patches, actor, now) {
14923
+ const folded = /* @__PURE__ */ new Map();
14924
+ for (const p of patches) folded.set(p.id, {
14925
+ ...folded.get(p.id),
14926
+ ...p.patch
14927
+ });
14928
+ const done = /* @__PURE__ */ new Map();
14929
+ for (const [id, patch] of folded) {
14930
+ const r = await this.conditionalUpdate(type, id, {}, patch, actor ?? void 0, now);
14931
+ done.set(id, r.matched ? r.row : null);
14932
+ }
14933
+ return patches.map((p) => done.get(p.id) ?? null);
14934
+ }
14935
+ async updateWhere(type, where, set, opts) {
14936
+ const matched = await this.#matchForWrite(type, where, opts.maxMatch);
14937
+ const rows = (await this.patchRows(type, matched.map((r) => ({
14938
+ id: r.id,
14939
+ patch: set
14940
+ })), opts.actor ?? null, opts.now ?? /* @__PURE__ */ new Date())).filter((r) => r !== null);
14941
+ return {
14942
+ count: rows.length,
14943
+ ids: rows.map((r) => r.id),
14944
+ rows
14945
+ };
14946
+ }
14947
+ async deleteWhere(type, where, opts) {
14948
+ const rows = (await this.#matchForWrite(type, where, opts.maxMatch)).map((r) => ({ ...r }));
14949
+ await this.tombstone(type, rows.map((r) => r.id));
14950
+ return {
14951
+ count: rows.length,
14952
+ ids: rows.map((r) => r.id),
14953
+ rows
14954
+ };
14955
+ }
14956
+ /** The live rows `where` matches, refused past `maxMatch` before anything changes. */
14957
+ async #matchForWrite(type, where, maxMatch) {
14958
+ const { rows } = await this.read(type, {
14959
+ where,
14960
+ limit: maxMatch + 1
14961
+ });
14962
+ if (rows.length > maxMatch) throw filterTooBroad(this.namespace, type, maxMatch);
14963
+ return rows;
14964
+ }
13381
14965
  async getShortIdForRow(type, rowId) {
13382
14966
  return this.shortIds.getShortIdForRow(this.namespace, type, rowId);
13383
14967
  }
@@ -13391,6 +14975,23 @@ var MemoryDataset = class MemoryDataset {
13391
14975
  });
13392
14976
  }
13393
14977
  };
14978
+ /** The names of the declared fields that read back absent when null (`isColumnField`). */
14979
+ function columnFieldNames(fields) {
14980
+ return Object.entries(fields ?? {}).flatMap(([k, def]) => isColumnField(def) ? [k] : []);
14981
+ }
14982
+ /**
14983
+ * The row as it reads back: a column field holding `null` is absent, as on pg.
14984
+ * The stored row keeps its null; the same row comes back when it has none.
14985
+ */
14986
+ function withoutNullColumns(columns, row) {
14987
+ let out = row;
14988
+ for (const k of columns) {
14989
+ if (row[k] !== null) continue;
14990
+ if (out === row) out = { ...row };
14991
+ delete out[k];
14992
+ }
14993
+ return out;
14994
+ }
13394
14995
  /**
13395
14996
  * Equality predicate used by `conditionalUpdate`. Handles the three shapes
13396
14997
  * the `_system` invite consumption check touches: scalar `===`, `null` ↔ `null`
@@ -13478,19 +15079,6 @@ function walkProjection(row, aggs, nested, ctx, top = false) {
13478
15079
  if (truncated.length > 0) out.push(["_truncated", Object.fromEntries(truncated)]);
13479
15080
  return Object.fromEntries(out);
13480
15081
  }
13481
- function normalizeOrderBy(orderBy) {
13482
- const out = [];
13483
- let hasIdTail = false;
13484
- for (const clause of orderBy ?? []) {
13485
- const entries = Object.entries(clause);
13486
- for (const [field, dir] of entries) {
13487
- out.push([field, dir]);
13488
- if (field === "id") hasIdTail = true;
13489
- }
13490
- }
13491
- if (!hasIdTail) out.push(["id", "asc"]);
13492
- return out;
13493
- }
13494
15082
  function compareByClauses(a, b, orderBy, fieldDefOf) {
13495
15083
  for (const [field, dir] of orderBy) {
13496
15084
  const av = asSortValue(field, getFieldValue(a, field), fieldDefOf);
@@ -14373,6 +15961,7 @@ async function readVerdicts(engine, req, trustedProxies, authEnabled) {
14373
15961
  function healthRoute(deps) {
14374
15962
  return async () => jsonResponse(200, {
14375
15963
  status: "ok",
15964
+ warnings: await deps.warnings(),
14376
15965
  version: deps.version,
14377
15966
  walks: true,
14378
15967
  uptimeSeconds: Math.floor((Date.now() - deps.startedAt) / 1e3)
@@ -14900,14 +16489,18 @@ function schemaForTypeRoute(engine) {
14900
16489
  });
14901
16490
  const mutations = {};
14902
16491
  for (const [name, def] of Object.entries(schema.mutations)) if (mutationTargetsType(name, def, type, typeSchema.fields)) mutations[name] = def;
16492
+ const storage = await engine.datasetFor(ns)?.describeStorage?.(type).catch(() => void 0);
16493
+ const pending = new Set(storage?.pending ?? []);
14903
16494
  const base = {
14904
16495
  schemaVersion: schema.schemaVersion,
14905
16496
  namespace: ns,
14906
16497
  type,
14907
- fields: typeSchema.fields,
16498
+ fields: pending.size === 0 ? typeSchema.fields : Object.fromEntries(Object.entries(typeSchema.fields).map(([f, def]) => [f, pending.has(f) ? {
16499
+ ...def,
16500
+ storage: "pending"
16501
+ } : def])),
14908
16502
  ...operatorContract(engine, ns)
14909
16503
  };
14910
- const storage = await engine.datasetFor(ns)?.describeStorage?.(type).catch(() => void 0);
14911
16504
  const withStorage = storage === void 0 ? base : {
14912
16505
  ...base,
14913
16506
  storage
@@ -14928,13 +16521,14 @@ function schemaForTypeRoute(engine) {
14928
16521
  };
14929
16522
  }
14930
16523
  /**
14931
- * A mutation targets a type when its name is a lowercase verb followed by
14932
- * exactly the type name (`createTodo`, `purgeTodo`), or when it returns the
16524
+ * A mutation targets a type when its name is a lowercase verb, optionally
16525
+ * followed by `Many`, then exactly the type name (`createTodo`, `purgeTodo`,
16526
+ * `updateManyTodo`), or when it returns the
14933
16527
  * type's row — a struct, or a list of structs, carrying exactly the type's
14934
16528
  * fields (`markAgentMessageRead`).
14935
16529
  */
14936
16530
  function mutationTargetsType(name, def, type, fields) {
14937
- if (name.endsWith(type) && /^[a-z]+$/.test(name.slice(0, -type.length))) return true;
16531
+ if (name.endsWith(type) && /^[a-z]+(Many)?$/.test(name.slice(0, -type.length))) return true;
14938
16532
  const row = def.returns.kind === "list" ? def.returns.of : def.returns;
14939
16533
  return row.kind === "struct" && isDeepStrictEqual(row.fields, fields);
14940
16534
  }
@@ -15881,10 +17475,11 @@ function registerWsRoute(server, engine, trustedProxies, metric, auth, systemIde
15881
17475
  //#endregion
15882
17476
  //#region ../../packages/substrate-compose/src/compose/routes.ts
15883
17477
  async function registerCoreRoutes(args) {
15884
- const { server, engine, gate, trustedProxies, auth, streamTicketSecret, version, stats, routeEventMetric, substrateDataset, substrateKeyRegistry, datasets, edges, namespaces, coordinatorPlugins, systemIdentity, routeMetric, bridges, registerRateLimiter, identityDirectory, adminCapability, configReport, storageReport } = args;
17478
+ const { server, engine, gate, trustedProxies, auth, streamTicketSecret, version, stats, routeEventMetric, substrateDataset, substrateKeyRegistry, datasets, edges, namespaces, coordinatorPlugins, systemIdentity, routeMetric, bridges, registerRateLimiter, identityDirectory, adminCapability, configReport, storageReport, promoteFields, fieldWarnings } = args;
15885
17479
  server.route("GET", "/health", healthRoute({
15886
17480
  version: version ?? "0.0.0",
15887
- startedAt: Date.now()
17481
+ startedAt: Date.now(),
17482
+ warnings: async () => [...engine.postWriteWarnings(), ...await fieldWarnings?.().catch(() => []) ?? []]
15888
17483
  }));
15889
17484
  server.route("GET", "/substrate/v1/schema", gate(schemaRoute(engine, "default"), "read"));
15890
17485
  server.route("GET", "/substrate/v1/schema/:namespace", gate(schemaForNamespaceRoute(engine), "read"));
@@ -15955,6 +17550,18 @@ async function registerCoreRoutes(args) {
15955
17550
  }), "utf8")
15956
17551
  };
15957
17552
  };
17553
+ const adminStoreWide = (handler) => async (req) => {
17554
+ if (auth === void 0) return handler(req);
17555
+ if (grantedIn(grantOf(req.identity ?? null), "*").includes(adminCap)) return handler(req);
17556
+ return {
17557
+ status: 403,
17558
+ headers: { "content-type": "application/json" },
17559
+ body: Buffer.from(JSON.stringify({
17560
+ code: "forbidden",
17561
+ required: `*:${adminCap}`
17562
+ }), "utf8")
17563
+ };
17564
+ };
15958
17565
  const dropGrants = auth === void 0 ? {} : {
15959
17566
  holds: (req, ns, cap) => grantedIn(grantOf(req.identity ?? null), ns).includes(cap),
15960
17567
  adminCapability: adminCap
@@ -15999,6 +17606,7 @@ async function registerCoreRoutes(args) {
15999
17606
  now: () => /* @__PURE__ */ new Date(),
16000
17607
  trustedProxies
16001
17608
  })), "admin"));
17609
+ server.route("POST", "/substrate/v1/_system/promote-fields", gate(adminStoreWide(promoteFieldsRoute(promoteFields)), "admin"));
16002
17610
  server.route("POST", "/substrate/v1/_system/register", registerRoute(substrateDataset, substrateKeyRegistry, rateLimiter, { trustedProxies }));
16003
17611
  server.route("GET", "/substrate/v1/whoami", whoamiRoute(auth));
16004
17612
  registerWsRoute(server, engine, trustedProxies, routeEventMetric, auth, systemIdentity, connections, sessionCap);
@@ -16281,6 +17889,11 @@ async function composeInner(opts, cleanup) {
16281
17889
  const advisorIntervalMs = opts.advisor?.intervalMs ?? 0;
16282
17890
  const shapeRecorder = advisorIntervalMs > 0 ? new ShapeRecorder() : void 0;
16283
17891
  if (shapeRecorder !== void 0) engineOpts.shapeRecorder = shapeRecorder;
17892
+ if (opts.filterWriteLimits !== void 0) engineOpts.filterWriteLimits = opts.filterWriteLimits;
17893
+ engineOpts.committedWritesHooks = coordinatorPlugins.flatMap((p) => p.onCommittedWrites !== void 0 ? [{
17894
+ plugin: p.name,
17895
+ hook: p.onCommittedWrites
17896
+ }] : []);
16284
17897
  const engine = new Engine(engineOpts);
16285
17898
  engineForStats = engine;
16286
17899
  let auth;
@@ -16296,6 +17909,11 @@ async function composeInner(opts, cleanup) {
16296
17909
  };
16297
17910
  const gate = (handler, required) => auth === void 0 ? withSystemActor(handler, systemIdentity) : withAuth(handler, auth, required, anonymousReadSink);
16298
17911
  const trustedProxies = opts.trustedProxies ?? /* @__PURE__ */ new Set();
17912
+ const promoteRunner = createPromoteFieldsRunner({
17913
+ dataset: opts.dataset,
17914
+ engine,
17915
+ intervalMs: opts.promoteFields?.intervalMs ?? 0
17916
+ });
16299
17917
  const { rateLimiter, ownsRateLimiter } = await registerCoreRoutes({
16300
17918
  server: opts.server,
16301
17919
  engine,
@@ -16320,7 +17938,9 @@ async function composeInner(opts, cleanup) {
16320
17938
  ...opts.auth?.identityDirectory !== void 0 ? { identityDirectory: opts.auth.identityDirectory } : {},
16321
17939
  ...opts.auth?.adminCapability !== void 0 ? { adminCapability: opts.auth.adminCapability } : {},
16322
17940
  ...opts.configReport !== void 0 ? { configReport: opts.configReport } : {},
16323
- ...opts.storageReport !== void 0 ? { storageReport: opts.storageReport } : {}
17941
+ ...opts.storageReport !== void 0 ? { storageReport: opts.storageReport } : {},
17942
+ promoteFields: promoteRunner.run,
17943
+ ...opts.dataset.fieldWarnings !== void 0 ? { fieldWarnings: opts.dataset.fieldWarnings.bind(opts.dataset) } : {}
16324
17944
  });
16325
17945
  let scheduler = null;
16326
17946
  if (scheduleEntries.length > 0) {
@@ -16365,12 +17985,14 @@ async function composeInner(opts, cleanup) {
16365
17985
  sweepDeps,
16366
17986
  runSweepNow: () => runSweep(sweepDeps, { lastSweptCursor: null }),
16367
17987
  runAdvisorNow,
17988
+ runPromoteFieldsNow: promoteRunner.run,
16368
17989
  scheduler,
16369
17990
  stats,
16370
17991
  stop: async (stopOpts) => {
16371
17992
  sampler.stop();
16372
17993
  clearInterval(advisorTimer);
16373
17994
  await advisorPass;
17995
+ await promoteRunner.stop();
16374
17996
  if (scheduler !== null) await scheduler.stop();
16375
17997
  if (runCoordinatorOnStop !== null) await runCoordinatorOnStop(engine);
16376
17998
  if (ownsRateLimiter) rateLimiter.dispose();
@@ -16516,6 +18138,26 @@ function mountKernelRoute(server, claim, auth, trustedProxies = /* @__PURE__ */
16516
18138
  const handler = claim.capability !== "public" && auth !== null ? withAuth(claim.handler, auth, claim.capability) : claim.handler;
16517
18139
  server.route(claim.method, `/substrate/v1/${claim.path}`, withRequestContext(handler, trustedProxies, auth !== null));
16518
18140
  }
18141
+ /**
18142
+ * A kernel migration ran DDL on `rows`, which a store on per-type tables does
18143
+ * not have (pg 42P01). The plugin predates the `tables` layout and must be
18144
+ * upgraded before this store boots with it.
18145
+ */
18146
+ var KernelMigrationLayoutError = class extends Error {
18147
+ plugin;
18148
+ id;
18149
+ name = "KernelMigrationLayoutError";
18150
+ constructor(plugin, id, options) {
18151
+ super(`kernel plugin ${plugin}: migration ${id} needs the \`rows\` table, which a store on per-type tables does not have. Upgrade ${plugin} to a release whose migrations support the tables layout, then boot.`, options);
18152
+ this.plugin = plugin;
18153
+ this.id = id;
18154
+ }
18155
+ };
18156
+ /** pg's undefined_table on `rows`, schema-qualified or not, as postgres.js reports it. */
18157
+ const isRowsMissing = (err) => {
18158
+ const e = err;
18159
+ return e?.code === "42P01" && typeof e.message === "string" && /"(?:[^".]+\.)?rows"/.test(e.message);
18160
+ };
16519
18161
  async function composeKernelPlugins(plugins, ctx) {
16520
18162
  for (const plugin of plugins) {
16521
18163
  if (plugin.migrations !== void 0) {
@@ -16528,11 +18170,16 @@ async function composeKernelPlugins(plugins, ctx) {
16528
18170
  });
16529
18171
  continue;
16530
18172
  }
16531
- await migration.apply({
16532
- sql: ctx.sql,
16533
- layout: ctx.layout,
16534
- metric: ctx.metric
16535
- });
18173
+ try {
18174
+ await migration.apply({
18175
+ sql: ctx.sql,
18176
+ layout: ctx.layout,
18177
+ metric: ctx.metric
18178
+ });
18179
+ } catch (err) {
18180
+ if (isRowsMissing(err)) throw new KernelMigrationLayoutError(plugin.name, migration.id, { cause: err });
18181
+ throw err;
18182
+ }
16536
18183
  await ctx.applyMigration(plugin.name, migration.id);
16537
18184
  }
16538
18185
  }
@@ -16580,4 +18227,4 @@ function kernelMigrationTracking(sql) {
16580
18227
  }
16581
18228
 
16582
18229
  //#endregion
16583
- export { bindingWalks as $, WALKS_IN_SUBSCRIPTION as $t, createResolverWithEdges as A, storedVocabSpellings as At, UnattributedWriteError as B, isIsoTimestamp as Bt, queryOne as C, signHs256 as Ct, isReservedAutoCrudField as D, canonicalVocabValue as Dt, RESERVED_AUTOCRUD_FIELD_NAMES as E, WS_REASON_SUBSCRIPTION_OVERLOADED as Et, listResolver as F, normaliseMetadataOrderBy as Ft, loadPlugins as G, MissingReferentError as Gt, resolveEntityId as H, assertHardDeleteAllowed as Ht, getResolver as I, normaliseMetadataWhere as It, applyObligations as J, ReservedField as Jt, publishSchema as K, NamespaceMismatch as Kt, deleteResolver as L, normaliseWalkNode as Lt, applyUpdatePatch as M, RegistryBase as Mt, updateResolver as N, METADATA_AUTHOR_FIELDS as Nt, field as O, normaliseVocabValues as Ot, purgeResolver as P, METADATA_FILTER_FIELDS as Pt, isDateField as Q, WALKS_IN_MUTATION as Qt, deleteRow as R, createKeyedMutex as Rt, queryAll as S, parseAuthConfig as St, RESERVED_AUTOCRUD_FIELDS as T, WS_REASON_SERVER_RESTART as Tt, resolveEntityRow as U, validateHardDeleteEnv as Ut, resolveIdentity as V, normalizeIsoTimestamp as Vt, MemoryEdgesStore as W, BridgeUnreachableError as Wt, runSweep as X, RestrictViolation as Xt, loadSweepState as Y, ResolverFrameError as Yt, saveSweepState as Z, UnsupportedFilterError as Zt, assertIndexDecl as _, JSON_HEADERS as _t, composeFromManifests as a, isResolverFrameError as an, isJsonPathPredicate as at, EngineQueryError as b, jsonResponse as bt, MemoryDataset as c, ROW_METADATA_FIELDS as cn, registerExtensionOperator as ct, uuidFromName as d, BootstrapConfigError as dn, decodeCursor as dt, WALKS_NEED_PARTITIONED as en, groupConjuncts as et, migrateFieldValues as f, defineBootstrap as fn, encodeCursor as ft, INVITE_TYPE as g, HttpBridgeClient as gt, AUDIT_EVENT_TYPE as h, fieldRequested as ht, PluginLoadError as i, isAuthCause as in, assertJsonPathPredicate as it, installAutoCrud as j, vocabImplication as jt, autoCrudOptionsOf as k, normaliseVocabWhere as kt, planServesShape as l, assertNoRepeatedIds as ln, unregisterExtensionOperator as lt, buildAuditRow as m, applyExtensionResultMeta as mt, kernelMigrationTracking as n, WALK_BUDGET_EXCEEDED as nn, refNames as nt, DEFAULT_NAMESPACE as o, isRestrictViolation as on, getExtensionOperator as ot, runInviteSweep as p, fullBuiltinOperators as pt, effectiveFilterOperators as q, ROW_POLICY_BLOCKS_WALK as qt, mountKernelRoute as r, WALK_UNSUPPORTED_REF as rn, preResolveExtensionOperatorsDetailed as rt, compose as s, CLIENT_SUPPLIED_SERVER_FIELD as sn, listExtensionOperators as st, composeKernelPlugins as t, WALKS_UNSUPPORTED_STORE as tn, isRefOperand as tt, isStoreProfileName as u, canonicalize as un, CursorDecodeError as ut, assertOrderedBy as v, buildContext as vt, selectAll as w, WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME as wt, makeCtx as x, parseJsonBody as xt, defineNamespace as y, error400 as yt, createResolver as z, isImpossibleIsoTimestamp as zt };
18230
+ export { applyObligations as $, BatchElementError as $t, field as A, parseJsonBody as At, applyUpdatePatch as B, vocabImplication as Bt, makeCtx as C, assertNoRepeatedIds as Cn, applyExtensionResultMeta as Ct, RESERVED_AUTOCRUD_FIELDS as D, buildContext as Dt, selectAll as E, defineBootstrap as En, JSON_HEADERS as Et, deleteManyResolver as F, WS_REASON_SUBSCRIPTION_OVERLOADED as Ft, UnattributedWriteError as G, normaliseMetadataWhere as Gt, purgeResolver as H, METADATA_AUTHOR_FIELDS as Ht, updateManyResolver as I, canonicalVocabValue as It, resolveEntityRow as J, isImpossibleIsoTimestamp as Jt, resolveIdentity as K, normaliseWalkNode as Kt, createResolver as L, normaliseVocabValues as Lt, autoCrudOptionsOf as M, signHs256 as Mt, createResolverWithEdges as N, WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME as Nt, RESERVED_AUTOCRUD_FIELD_NAMES as O, error400 as Ot, installAutoCrud as P, WS_REASON_SERVER_RESTART as Pt, effectiveFilterOperators as Q, validateHardDeleteEnv as Qt, deleteResolver as R, normaliseVocabWhere as Rt, EngineQueryError as S, ROW_METADATA_FIELDS as Sn, fullBuiltinOperators as St, queryOne as T, BootstrapConfigError as Tn, HttpBridgeClient as Tt, listResolver as U, METADATA_FILTER_FIELDS as Ut, deleteRow as V, RegistryBase as Vt, getResolver as W, normaliseMetadataOrderBy as Wt, loadPlugins as X, normalizeIsoTimestamp as Xt, MemoryEdgesStore as Y, isIsoTimestamp as Yt, publishSchema as Z, assertHardDeleteAllowed as Zt, AUDIT_EVENT_TYPE as _, isAuthCause as _n, unregisterExtensionOperator as _t, composeFromManifests as a, ROW_POLICY_BLOCKS_WALK as an, windowGroupBy as at, assertOrderedBy as b, isRestrictViolation as bn, encodeCursor as bt, MemoryDataset as c, RestrictViolation as cn, groupConjuncts as ct, uuidFromName as d, WALKS_IN_SUBSCRIPTION as dn, preResolveExtensionOperatorsDetailed as dt, BridgeUnreachableError as en, loadSweepState as et, emitFieldEvents as f, WALKS_NEED_PARTITIONED as fn, assertJsonPathPredicate as ft, buildAuditRow as g, filterTooBroad as gn, registerExtensionOperator as gt, SYSTEM_TYPE_DEFS as h, WALK_UNSUPPORTED_REF as hn, listExtensionOperators as ht, PluginLoadError as i, QUERY_TIMEOUT as in, sharedPicks as it, AutoCrudNameCollisionError as j, parseAuthConfig as jt, isReservedAutoCrudField as k, jsonResponse as kt, planServesShape as l, UnsupportedFilterError as ln, isRefOperand as lt, runInviteSweep as m, WALK_BUDGET_EXCEEDED as mn, getExtensionOperator as mt, kernelMigrationTracking as n, MissingReferentError as nn, saveSweepState as nt, DEFAULT_NAMESPACE as o, ReservedField as on, isDateField as ot, migrateFieldValues as p, WALKS_UNSUPPORTED_STORE as pn, isJsonPathPredicate as pt, resolveEntityId as q, createKeyedMutex as qt, mountKernelRoute as r, NamespaceMismatch as rn, forEachWalkHop as rt, compose as s, ResolverFrameError as sn, bindingWalks as st, composeKernelPlugins as t, FILTER_TOO_BROAD as tn, runSweep as tt, isStoreProfileName as u, WALKS_IN_MUTATION as un, refNames as ut, INVITE_TYPE as v, isBatchElementError as vn, CursorDecodeError as vt, queryAll as w, canonicalize as wn, fieldRequested as wt, defineNamespace as x, CLIENT_SUPPLIED_SERVER_FIELD as xn, normalizeOrderBy as xt, assertIndexDecl as y, isResolverFrameError as yn, decodeCursor as yt, updateResolver as z, storedVocabSpellings as zt };