@fangorn-network/sdk 2026.8.18-dev → 2026.10.1-9.0-dev

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 (91) hide show
  1. package/README.md +191 -195
  2. package/lib/cli/cli.d.ts +0 -0
  3. package/lib/cli/cli.js +198 -164
  4. package/lib/cli/index.d.ts +3 -91
  5. package/lib/cli/index.js +5 -2
  6. package/lib/config.d.ts +349 -433
  7. package/lib/config.js +41 -28
  8. package/lib/contracts/app-registry/abi.d.ts +1064 -265
  9. package/lib/contracts/app-registry/abi.js +1233 -308
  10. package/lib/contracts/app-registry/index.d.ts +123 -102
  11. package/lib/contracts/app-registry/index.js +200 -198
  12. package/lib/contracts/data-registry/abi.d.ts +166 -187
  13. package/lib/contracts/data-registry/abi.js +207 -237
  14. package/lib/contracts/data-registry/index.d.ts +4 -160
  15. package/lib/contracts/data-registry/index.js +5 -294
  16. package/lib/contracts/index.d.ts +6 -7
  17. package/lib/contracts/index.js +6 -8
  18. package/lib/contracts/logs.d.ts +21 -0
  19. package/lib/contracts/logs.js +32 -0
  20. package/lib/contracts/membership-registry/abi.d.ts +1145 -0
  21. package/lib/contracts/membership-registry/abi.js +1333 -0
  22. package/lib/contracts/membership-registry/index.d.ts +79 -0
  23. package/lib/contracts/membership-registry/index.js +104 -0
  24. package/lib/contracts/types.d.ts +3 -1
  25. package/lib/contracts/types.js +3 -1
  26. package/lib/contracts/write.d.ts +34 -2
  27. package/lib/contracts/write.js +48 -1
  28. package/lib/crypto/encryption.js +4 -4
  29. package/lib/engine/car.d.ts +2 -2
  30. package/lib/engine/car.js +10 -5
  31. package/lib/engine/index.d.ts +99 -143
  32. package/lib/engine/index.js +156 -295
  33. package/lib/engine/records.d.ts +110 -0
  34. package/lib/engine/records.js +165 -0
  35. package/lib/engine/test-helpers.d.ts +7 -14
  36. package/lib/engine/test-helpers.js +7 -18
  37. package/lib/fangorn.d.ts +163 -155
  38. package/lib/fangorn.js +284 -248
  39. package/lib/feed.d.ts +7 -4
  40. package/lib/feed.js +4 -1
  41. package/lib/index.d.ts +9 -9
  42. package/lib/index.js +9 -10
  43. package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
  44. package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
  45. package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
  46. package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
  47. package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
  48. package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
  49. package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
  50. package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
  51. package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
  52. package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
  53. package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
  54. package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
  55. package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
  56. package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
  57. package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
  58. package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
  59. package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
  60. package/lib/node_modules/chai/index.js +2874 -0
  61. package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
  62. package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
  63. package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
  64. package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
  65. package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
  66. package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
  67. package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
  68. package/lib/providers/storage/signed-url.d.ts +16 -6
  69. package/lib/providers/storage/signed-url.js +20 -8
  70. package/lib/registry.d.ts +116 -0
  71. package/lib/registry.js +182 -0
  72. package/lib/test/mem-registry.d.ts +51 -0
  73. package/lib/test/mem-registry.js +107 -0
  74. package/lib/test/sdk-suite.d.ts +13 -0
  75. package/lib/test/sdk-suite.js +226 -0
  76. package/lib/test/testbed.d.ts +16411 -61
  77. package/lib/test/testbed.js +190 -84
  78. package/lib/types/index.d.ts +13 -11
  79. package/package.json +89 -72
  80. package/lib/contracts/data-registry/test.d.ts +0 -1
  81. package/lib/contracts/data-registry/test.js +0 -1
  82. package/lib/contracts/settlement-registry/abi.d.ts +0 -466
  83. package/lib/contracts/settlement-registry/abi.js +0 -535
  84. package/lib/contracts/settlement-registry/index.d.ts +0 -163
  85. package/lib/contracts/settlement-registry/index.js +0 -264
  86. package/lib/contracts/subscription-registry/abi.d.ts +0 -179
  87. package/lib/contracts/subscription-registry/abi.js +0 -195
  88. package/lib/contracts/subscription-registry/index.d.ts +0 -59
  89. package/lib/contracts/subscription-registry/index.js +0 -116
  90. package/lib/engine/graph.d.ts +0 -70
  91. package/lib/engine/graph.js +0 -73
@@ -1,59 +1,48 @@
1
+ import { assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, encodeBlock, lookupMst, readMst } from "./records.js";
1
2
  import { packCar, readCar } from "./car.js";
2
- import { buildPages, decodeBlock, encodeBlock, readPages } from "./graph.js";
3
+ import { ZERO_HEAD } from "../registry.js";
3
4
  import { CID } from "multiformats/cid";
5
+ import { randomUUID } from "crypto";
4
6
  import { sha256 } from "multiformats/hashes/sha2";
5
7
  import * as Digest from "multiformats/hashes/digest";
6
8
 
7
9
  //#region src/engine/index.ts
8
10
  /**
9
- * The Metagraph registry is a class for building and validating knowledge graphs
10
- *
11
- * The vertices each represent a unique piece of data, while the edges
12
- * represent the relationships that connect them into a graph.
13
- *
11
+ * Per-repo record schemas. Types without a registered schema are
12
+ * accepted as-is (permissive by default); register one to require fields.
14
13
  */
15
- var MetagraphRegistry = class {
16
- vertexSchemas = /* @__PURE__ */ new Map();
17
- edgeSchemas = /* @__PURE__ */ new Set();
18
- registerVertex(namespace, schema) {
19
- this.vertexSchemas.set(`${namespace}|${schema.id}`, schema);
14
+ var SchemaRegistry = class {
15
+ schemas = /* @__PURE__ */ new Map();
16
+ register(repo, schema) {
17
+ this.schemas.set(`${repo}|${schema.type}`, schema);
20
18
  }
21
- hasVertexSchema(namespace, schemaId) {
22
- return this.vertexSchemas.has(`${namespace}|${schemaId}`);
23
- }
24
- registerEdge(namespace, rule) {
25
- this.edgeSchemas.add(`${namespace}|${rule.sourceSchema}|${rule.relation}|${rule.targetSchema}`);
26
- }
27
- hasEdgeSchema(namespace, sourceSchema, relation, targetSchema) {
28
- return this.edgeSchemas.has(`${namespace}|${sourceSchema}|${relation}|${targetSchema}`);
29
- }
30
- validateVertex(namespace, schemaId, payload) {
31
- const schema = this.vertexSchemas.get(`${namespace}|${schemaId}`);
32
- if (!schema) return false;
33
- return schema.requiredFields.every((field) => field in payload);
34
- }
35
- validateEdge(namespace, sourceSchema, relation, targetSchema) {
36
- return this.edgeSchemas.has(`${namespace}|${sourceSchema}|${relation}|${targetSchema}`);
19
+ validate(repo, type, payload) {
20
+ const schema = this.schemas.get(`${repo}|${type}`);
21
+ return !schema || schema.requiredFields.every((field) => field in payload);
37
22
  }
38
23
  };
39
- const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
24
+ const ZERO_BYTES32 = ZERO_HEAD;
40
25
  /**
41
- * Upper bound on a namespace name's length. Namespaces are keys of the root
42
- * map block, so this is just a sanity bound keeping that block small and
26
+ * Upper bound on a repo name's length. The name is stored in every commit
27
+ * block, so this is just a sanity bound keeping that block small and
43
28
  * rejecting garbage input early.
44
29
  */
45
- const MAX_NAMESPACE_LENGTH = 256;
30
+ const MAX_REPO_NAME_LENGTH = 256;
46
31
  /**
47
32
  * The root of the graph, committed to IPFS, as hex
48
33
  */
49
34
  function rootHexFromCid(commitCid) {
50
35
  return `0x${Buffer.from(commitCid.multihash.digest).toString("hex")}`;
51
36
  }
52
- /** Namespaces must be non-empty strings whose length does not exceed MAX_NAMESPACE_LENGTH */
53
- function assertValidNamespace(namespace) {
54
- if (typeof namespace !== "string" || namespace.length === 0) throw new Error("namespace must be a non-empty string");
55
- if (namespace.length > MAX_NAMESPACE_LENGTH) throw new Error(`namespace exceeds the maximum length of ${MAX_NAMESPACE_LENGTH.toString()} characters (got ${namespace.length.toString()}).`);
37
+ /** Repos must be non-empty strings whose length does not exceed MAX_REPO_NAME_LENGTH */
38
+ function assertValidRepoName(repo) {
39
+ if (typeof repo !== "string" || repo.length === 0) throw new Error("repo must be a non-empty string");
40
+ if (repo.length > MAX_REPO_NAME_LENGTH) throw new Error(`repo exceeds the maximum length of ${MAX_REPO_NAME_LENGTH.toString()} characters (got ${repo.length.toString()}).`);
56
41
  }
42
+ const EMPTY_STATE = {
43
+ state: /* @__PURE__ */ new Map(),
44
+ nodeCids: /* @__PURE__ */ new Set()
45
+ };
57
46
  var FangornEngine = class {
58
47
  /**
59
48
  * Local block cache. Written blocks land here immediately; remote blocks
@@ -63,10 +52,10 @@ var FangornEngine = class {
63
52
  cache = /* @__PURE__ */ new Map();
64
53
  /** Commits whose CAR has already been loaded into the cache. */
65
54
  loadedCars = /* @__PURE__ */ new Set();
66
- constructor(storage, metagraph, registryClient) {
55
+ constructor(storage, schemas, registry) {
67
56
  this.storage = storage;
68
- this.metagraph = metagraph;
69
- this.registryClient = registryClient;
57
+ this.schemas = schemas;
58
+ this.registry = registry;
70
59
  }
71
60
  /**
72
61
  * Reconstructs the CID a commit's raw digest hex refers to. The contract only
@@ -86,14 +75,16 @@ var FangornEngine = class {
86
75
  let bytes = this.cache.get(key);
87
76
  if (!bytes) {
88
77
  bytes = await this.storage.getRawBlock(key);
78
+ assertBlockMatches(commitCid, bytes);
89
79
  this.cache.set(key, bytes);
90
80
  }
91
81
  const decoded = decodeBlock(bytes);
92
- if (decoded.pailRoot !== void 0) throw new Error(`commit ${key} predates the v2 data layer (pail-era). Reset the on-chain head (\`fangorn reset\`) and re-publish.`);
82
+ if (typeof decoded.epoch !== "number" || typeof decoded.repo !== "string") throw new Error(`commit ${key} predates the (e, parent, root) commit format. Reset the on-chain head (\`fangorn reset\`) and re-publish.`);
93
83
  return {
84
+ epoch: decoded.epoch,
85
+ parent: decoded.parent ? CID.parse(String(decoded.parent)) : null,
94
86
  root: CID.parse(String(decoded.root)),
95
- parents: (decoded.parents ?? []).map((p) => CID.parse(String(p))),
96
- timestamp: decoded.timestamp ?? 0,
87
+ repo: decoded.repo,
97
88
  message: decoded.message ?? "",
98
89
  car: decoded.car ?? ""
99
90
  };
@@ -120,7 +111,7 @@ var FangornEngine = class {
120
111
  const found = this.cache.get(key);
121
112
  if (found) return found;
122
113
  }
123
- cursor = commit.parents.length ? commit.parents[0] : null;
114
+ cursor = commit.parent;
124
115
  }
125
116
  throw new Error(`Block payload missing for key: ${key}`);
126
117
  }
@@ -128,155 +119,72 @@ var FangornEngine = class {
128
119
  this.cache.set(block.cid.toString(), block.bytes);
129
120
  }
130
121
  /**
131
- * Reconstruct the current on-chain head of one publisher's namespace as a
132
- * commit CID, or null if none. Each namespace is its own on-chain timeline,
133
- * so this is per-(publisher, namespace) rather than per-publisher.
122
+ * Reconstruct the current on-chain head of one publisher's repo as a
123
+ * commit CID, or null if none. Each repo is its own on-chain timeline,
124
+ * so this is per-(publisher, repo) rather than per-publisher.
134
125
  */
135
- async resolveHeadCommit(publisher, namespace) {
136
- const currentHead = await this.registryClient.getNamespaceHead(publisher, namespace);
126
+ async resolveHeadCommit(publisher, repo) {
127
+ const currentHead = await this.registry.head({
128
+ publisher,
129
+ repo
130
+ });
137
131
  if (currentHead === ZERO_BYTES32) return null;
138
132
  return this.hexToRootCid(currentHead);
139
133
  }
140
- /** Decode the root map behind a commit. */
141
- async rootMapAt(commitCid) {
142
- const commit = await this.getCommit(commitCid);
143
- const raw = decodeBlock(await this.getBlock(commit.root, commitCid));
144
- const rootMap = {};
145
- for (const [ns, link] of Object.entries(raw)) rootMap[ns] = CID.parse(String(link));
146
- return rootMap;
147
- }
148
134
  /**
149
- * Which namespace a commit belongs to, read from its root map.
150
- *
151
- * Each namespace is its own on-chain timeline, so a commit's root map carries
152
- * exactly one entry — which is how an app-wide subscriber recovers the
153
- * namespace *name* from a stream that only carries `keccak256(name)`. A commit
154
- * with several entries predates per-namespace timelines and can't be
155
- * attributed to one.
135
+ * Which repo a commit belongs to. Events carry only `keccak256(name)`, so
136
+ * this is how an app-wide subscriber recovers the name.
156
137
  */
157
- async namespaceOf(rootHex) {
158
- const names = Object.keys(await this.rootMapAt(this.hexToRootCid(rootHex)));
159
- if (names.length !== 1) throw new Error(`commit ${rootHex} spans ${names.length.toString()} namespaces; expected exactly one`);
160
- return names[0];
138
+ async repoOf(rootHex) {
139
+ return (await this.getCommit(this.hexToRootCid(rootHex))).repo;
161
140
  }
162
- /** The full vertex/edge link sets one commit records for `namespace`. */
163
- async treeLinksAt(commitCid, namespace) {
164
- const rootMap = await this.rootMapAt(commitCid);
165
- if (!(namespace in rootMap)) return {
166
- vertexLinks: [],
167
- edgeLinks: [],
168
- structureCids: /* @__PURE__ */ new Set()
169
- };
170
- const treeLink = rootMap[namespace];
171
- const tree = decodeBlock(await this.getBlock(treeLink, commitCid));
172
- const get = (cid) => this.getBlock(cid, commitCid);
173
- return {
174
- vertexLinks: (await readPages(tree.vertices.map((c) => CID.parse(String(c))), get)).map((c) => CID.parse(String(c))),
175
- edgeLinks: (await readPages(tree.edges.map((c) => CID.parse(String(c))), get)).map((c) => CID.parse(String(c))),
176
- structureCids: new Set([
177
- treeLink.toString(),
178
- ...tree.vertices.map(String),
179
- ...tree.edges.map(String)
180
- ])
181
- };
141
+ /** The record state a commit holds. */
142
+ async stateAt(commitCid) {
143
+ return readMst((await this.getCommit(commitCid)).root, (cid) => this.getBlock(cid, commitCid));
182
144
  }
183
145
  /**
184
- * TODO: revisit the storage model
185
- * Q: what if CAR is not supported?
186
- *
187
146
  * Build a new commit on top of `base` — entirely in memory, then persisted
188
147
  * as exactly TWO uploads: one CAR file holding every block this commit
189
148
  * introduced (git's packfile), and the small commit block itself (stored
190
149
  * individually so the on-chain digest resolves without any index).
191
150
  *
192
- * The new namespace state is the parent state plus the staged graph;
193
- * unchanged blocks are shared byte-for-byte with ancestors and are NOT
151
+ * Unchanged records and MST nodes re-derive their old CIDs and are NOT
194
152
  * re-uploaded. Does not touch the chain — `pushCommit` settles it.
195
153
  */
196
154
  async createCommit(opts) {
197
- assertValidNamespace(opts.namespace);
198
- const { namespace, base } = opts;
199
- const rootMap = base ? await this.rootMapAt(base) : {};
200
- const old = base ? await this.treeLinksAt(base, namespace) : {
201
- vertexLinks: [],
202
- edgeLinks: [],
203
- structureCids: /* @__PURE__ */ new Set()
204
- };
205
- const oldVertexSet = new Set(old.vertexLinks.map(String));
206
- const oldEdgeSet = new Set(old.edgeLinks.map(String));
155
+ assertValidRepoName(opts.repo);
156
+ const { repo, base } = opts;
157
+ if (base && (await this.getCommit(base)).repo !== repo) throw new Error(`commit ${base.toString()} belongs to another repo than ${repo}`);
158
+ const old = base ? await this.stateAt(base) : EMPTY_STATE;
159
+ const oldRecordCids = new Set([...old.state.values()].map(String));
160
+ const state = opts.replace ? /* @__PURE__ */ new Map() : new Map(old.state);
161
+ for (const id of opts.deletes ?? []) state.delete(id);
207
162
  const carBlocks = [];
208
- const vertexCids = {};
209
- const idInfo = /* @__PURE__ */ new Map();
210
- const vertexLinks = opts.replace ? [] : [...old.vertexLinks];
211
- const newVertexSet = new Set(vertexLinks.map(String));
212
- for (const v of opts.vertices) {
213
- if (!this.metagraph.validateVertex(namespace, v.schemaId, v.payload)) throw new Error(`Schema violation for vertex type [${v.schemaId}] in namespace [${namespace}]`);
214
- const block = await encodeBlock({
215
- schemaId: v.schemaId,
216
- payload: v.payload
217
- });
218
- idInfo.set(v.id, {
219
- cid: block.cid,
220
- tag: v.schemaId
221
- });
222
- vertexCids[v.id] = block.cid.toString();
223
- const key = block.cid.toString();
224
- if (!newVertexSet.has(key)) {
225
- newVertexSet.add(key);
226
- vertexLinks.push(block.cid);
227
- if (!oldVertexSet.has(key)) carBlocks.push(block);
228
- }
229
- }
230
- const resolveEndpoint = (ref) => {
231
- const info = idInfo.get(ref);
232
- if (info) return info;
233
- try {
234
- return {
235
- cid: CID.parse(ref),
236
- tag: null
237
- };
238
- } catch {
239
- throw new Error(`edge references unknown local id (or invalid CID): ${ref}`);
240
- }
241
- };
242
- const edgeLinks = opts.replace ? [] : [...old.edgeLinks];
243
- const newEdgeSet = new Set(edgeLinks.map(String));
244
- for (const e of opts.edges) {
245
- const source = resolveEndpoint(e.from);
246
- const target = resolveEndpoint(e.to);
247
- if (source.tag && target.tag && !this.metagraph.validateEdge(namespace, source.tag, e.relation, target.tag)) throw new Error(`Invalid structural link relation [${e.relation}] in namespace [${namespace}]`);
163
+ const recordCids = {};
164
+ for (const r of opts.records) {
165
+ const id = r.id ?? randomUUID();
166
+ assertValidRecordId(id);
167
+ if (id in recordCids) throw new Error(`record id ${id} staged twice`);
168
+ if (!this.schemas.validate(repo, r.type, r.payload)) throw new Error(`Schema violation for record type [${r.type}] in repo [${repo}]`);
248
169
  const block = await encodeBlock({
249
- source: source.cid,
250
- relation: e.relation,
251
- target: target.cid
170
+ id,
171
+ type: r.type,
172
+ payload: r.payload
252
173
  });
253
- const key = block.cid.toString();
254
- if (!newEdgeSet.has(key)) {
255
- newEdgeSet.add(key);
256
- edgeLinks.push(block.cid);
257
- if (!oldEdgeSet.has(key)) carBlocks.push(block);
258
- }
174
+ state.set(id, block.cid);
175
+ recordCids[id] = block.cid.toString();
176
+ if (!oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
259
177
  }
260
- const { pages: vertexPages, pageLinks: vertexPageLinks } = await buildPages(vertexLinks);
261
- const { pages: edgePages, pageLinks: edgePageLinks } = await buildPages(edgeLinks);
262
- for (const page of [...vertexPages, ...edgePages]) if (!old.structureCids.has(page.cid.toString())) carBlocks.push(page);
263
- const treeBlock = await encodeBlock({
264
- vertices: vertexPageLinks,
265
- edges: edgePageLinks
266
- });
267
- if (!old.structureCids.has(treeBlock.cid.toString())) carBlocks.push(treeBlock);
268
- const rootBlock = await encodeBlock({
269
- ...rootMap,
270
- [namespace]: treeBlock.cid
271
- });
272
- carBlocks.push(rootBlock);
178
+ const mst = await buildMst(state);
179
+ for (const node of mst.nodes) if (!old.nodeCids.has(node.cid.toString())) carBlocks.push(node);
273
180
  for (const block of carBlocks) this.putLocal(block);
274
- const carBytes = await packCar(rootBlock.cid, carBlocks);
275
- const carUri = await this.storage.putFile(carBytes, `${rootBlock.cid.toString()}.car`);
181
+ const carBytes = await packCar(mst.root, carBlocks);
182
+ const carUri = await this.storage.putFile(carBytes, `${mst.root.toString()}.car`);
276
183
  const commitBlock = await encodeBlock({
277
- root: rootBlock.cid,
278
- parents: base ? [base] : [],
279
- timestamp: Date.now(),
184
+ epoch: await this.registry.epoch(),
185
+ parent: base,
186
+ root: mst.root,
187
+ repo,
280
188
  message: opts.message,
281
189
  car: carUri
282
190
  });
@@ -285,30 +193,35 @@ var FangornEngine = class {
285
193
  this.loadedCars.add(commitBlock.cid.toString());
286
194
  return {
287
195
  commitCid: commitBlock.cid,
288
- root: rootBlock.cid,
289
- vertexCids
196
+ root: mst.root,
197
+ recordCids
290
198
  };
291
199
  }
292
200
  /**
293
- * Settle a local commit as the on-chain head of one namespace — the
294
- * permissioned, git `push` step. The commit and its CAR are already durable
295
- * in storage (createCommit uploads them), so this is just the compare-and-swap
296
- * against the current head. Unless `force`, the on-chain head must be an
297
- * ancestor of `commitCid` (fast-forward only).
201
+ * Settle a local commit as the on-chain head of one repo — the `update` of
202
+ * WHITEPAPER_1 §3.2. The commit and its CAR are already durable in storage
203
+ * (createCommit uploads them), so this is just the compare-and-swap.
204
+ *
205
+ * The commit's parent must BE the current head, not merely an ancestor of
206
+ * it: then the parent chain and the registry's log are one history
207
+ * (Theorem 3). Today's contract only checks the old root, so the parent is
208
+ * checked here.
298
209
  */
299
- async pushCommit(publisher, namespace, commitCid, opts) {
300
- const onChainHex = await this.registryClient.getNamespaceHead(publisher, namespace);
301
- const onChainCommit = onChainHex === ZERO_BYTES32 ? null : this.hexToRootCid(onChainHex);
302
- if (!opts?.force && onChainCommit && onChainCommit.toString() !== commitCid.toString()) {
303
- if (!await this.isAncestor(onChainCommit, commitCid)) throw new Error("non-fast-forward: the on-chain tip is not an ancestor of this commit — clone/rebuild onto the current tip, or push with force.");
304
- }
305
- const newRootHex = rootHexFromCid(commitCid);
210
+ async pushCommit(publisher, repo, commitCid) {
211
+ const head = await this.registry.head({
212
+ publisher,
213
+ repo
214
+ });
215
+ const commit = await this.getCommit(commitCid);
216
+ const parentHex = commit.parent ? rootHexFromCid(commit.parent) : ZERO_BYTES32;
217
+ if (commit.repo !== repo) throw new Error(`commit ${commitCid.toString()} is a commit of ${commit.repo}, not ${repo}`);
218
+ if (parentHex !== head) throw new Error("stale parent: this commit's parent is not the on-chain head — rebuild it onto the current head.");
306
219
  return {
307
- txHash: await this.registryClient.commitStateRoot(namespace, onChainHex, newRootHex),
220
+ txHash: await this.registry.update(repo, head, rootHexFromCid(commitCid)),
308
221
  onChainTip: commitCid
309
222
  };
310
223
  }
311
- /** Walk the first-parent chain from `tip` toward the root, newest first. */
224
+ /** Walk the parent chain from `tip` toward the root, newest first. */
312
225
  async *walkParents(tip, max) {
313
226
  let cursor = tip;
314
227
  for (let n = 0; cursor && (max === void 0 || n < max); n++) {
@@ -317,15 +230,9 @@ var FangornEngine = class {
317
230
  cid: cursor,
318
231
  commit
319
232
  };
320
- cursor = commit.parents.length ? commit.parents[0] : null;
233
+ cursor = commit.parent;
321
234
  }
322
235
  }
323
- /** True if `ancestor` appears on the first-parent chain of `tip`. */
324
- async isAncestor(ancestor, tip) {
325
- const target = ancestor.toString();
326
- for await (const { cid } of this.walkParents(tip)) if (cid.toString() === target) return true;
327
- return false;
328
- }
329
236
  /** The commit CID string a raw on-chain root hex points at. */
330
237
  commitCidFromRootHex(hex) {
331
238
  return this.hexToRootCid(hex).toString();
@@ -334,142 +241,96 @@ var FangornEngine = class {
334
241
  rootHexFromCommitCid(commitCid) {
335
242
  return rootHexFromCid(CID.parse(commitCid));
336
243
  }
337
- /** Decode a vertex block into the public read shape. */
338
- async decodeVertex(link, hint) {
339
- const decoded = decodeBlock(await this.getBlock(link, hint));
244
+ /** Decode a record block, checking it is filed under its own id. */
245
+ async decodeRecord(id, link, hint) {
246
+ const r = decodeBlock(await this.getBlock(link, hint));
247
+ if (r.id !== id) throw new Error(`record ${link.toString()} has id ${r.id}, filed under ${id}`);
340
248
  return {
249
+ id,
341
250
  cid: link.toString(),
342
- schemaId: decoded.schemaId,
343
- payload: decoded.payload
344
- };
345
- }
346
- /** Decode an edge block into the public read shape. */
347
- async decodeEdge(link, hint) {
348
- const decoded = decodeBlock(await this.getBlock(link, hint));
349
- return {
350
- sourceCid: String(decoded.source),
351
- relation: decoded.relation,
352
- targetCid: String(decoded.target)
251
+ type: r.type,
252
+ payload: r.payload
353
253
  };
354
254
  }
355
255
  /**
356
- * Net change to a single namespace between two on-chain roots — the core of
357
- * the subscription light-client. Namespace trees are explicit link sets, so
358
- * the diff is a plain set difference; only blocks that actually changed are
359
- * decoded (each side resolves through its own commit's CAR chain).
256
+ * Net change to a single repo between two on-chain roots — the core of
257
+ * the subscription light-client. A plain comparison of the two id → CID
258
+ * maps; only records that actually changed are decoded.
360
259
  *
361
260
  * Diffing root-to-root (rather than walking commits) is deliberately robust:
362
261
  * it yields the correct net delta even across a force-push / non-fast-forward
363
- * reorg — exactly what an index builder needs (which vertices to (re)embed,
364
- * which to evict).
262
+ * reorg — exactly what an index builder needs (what to (re)embed, what to evict).
263
+ * ponytail: reads both whole trees; skip subtrees with equal CIDs if diffs
264
+ * of large repos get slow.
365
265
  */
366
- async namespaceDiff(oldRootHex, newRootHex, namespace) {
266
+ async repoDiff(oldRootHex, newRootHex) {
367
267
  const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
368
268
  const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
369
- const after = newCommit ? await this.treeLinksAt(newCommit, namespace) : {
370
- vertexLinks: [],
371
- edgeLinks: []
372
- };
373
- const before = oldCommit ? await this.treeLinksAt(oldCommit, namespace) : {
374
- vertexLinks: [],
375
- edgeLinks: []
376
- };
377
- const beforeV = new Set(before.vertexLinks.map(String));
378
- const beforeE = new Set(before.edgeLinks.map(String));
379
- const afterV = new Set(after.vertexLinks.map(String));
380
- const afterE = new Set(after.edgeLinks.map(String));
381
- const addedVertices = [];
382
- const addedEdges = [];
383
- if (after.vertexLinks.length > 0 || after.edgeLinks.length > 0) {
384
- if (!newCommit) throw new Error("Missing commit context required to decode graph changes");
385
- for (const link of after.vertexLinks) if (!beforeV.has(link.toString())) addedVertices.push(await this.decodeVertex(link, newCommit));
386
- for (const link of after.edgeLinks) if (!beforeE.has(link.toString())) addedEdges.push(await this.decodeEdge(link, newCommit));
387
- }
388
- const removedVertexCids = before.vertexLinks.map(String).filter((c) => !afterV.has(c));
389
- const removedEdges = [];
390
- if (oldCommit) {
391
- for (const link of before.edgeLinks) if (!afterE.has(link.toString())) removedEdges.push(await this.decodeEdge(link, oldCommit));
269
+ const after = newCommit ? (await this.stateAt(newCommit)).state : /* @__PURE__ */ new Map();
270
+ const before = oldCommit ? (await this.stateAt(oldCommit)).state : /* @__PURE__ */ new Map();
271
+ const puts = [];
272
+ if (newCommit) {
273
+ for (const [id, cid] of after) if (before.get(id)?.toString() !== cid.toString()) puts.push(await this.decodeRecord(id, cid, newCommit));
392
274
  }
393
275
  return {
394
- addedVertices,
395
- addedEdges,
396
- removedVertexCids,
397
- removedEdges
276
+ puts,
277
+ deletes: [...before.keys()].filter((id) => !after.has(id))
398
278
  };
399
279
  }
400
- /** Diff a commit against its first parent, across every namespace. */
280
+ /** Diff a commit against its parent. */
401
281
  async diffCommit(commitCid) {
402
282
  const commit = await this.getCommit(commitCid);
403
- const parent = commit.parents.length ? commit.parents[0] : null;
404
- const childRoot = await this.rootMapAt(commitCid);
405
- const parentRoot = parent ? await this.rootMapAt(parent) : {};
283
+ const ns = commit.repo;
284
+ const child = (await this.stateAt(commitCid)).state;
285
+ const par = commit.parent ? (await this.stateAt(commit.parent)).state : /* @__PURE__ */ new Map();
406
286
  const added = [];
287
+ const updated = [];
407
288
  const removed = [];
408
- const namespaces = new Set([...Object.keys(childRoot), ...Object.keys(parentRoot)]);
409
- for (const ns of namespaces) {
410
- const inParent = ns in parentRoot;
411
- const inChild = ns in childRoot;
412
- if (inParent && inChild && String(parentRoot[ns]) === String(childRoot[ns])) continue;
413
- const child = inChild ? await this.treeLinksAt(commitCid, ns) : {
414
- vertexLinks: [],
415
- edgeLinks: []
416
- };
417
- const par = parent && inParent ? await this.treeLinksAt(parent, ns) : {
418
- vertexLinks: [],
419
- edgeLinks: []
420
- };
421
- const parV = new Set(par.vertexLinks.map(String));
422
- const parE = new Set(par.edgeLinks.map(String));
423
- const childV = new Set(child.vertexLinks.map(String));
424
- const childE = new Set(child.edgeLinks.map(String));
425
- for (const c of childV) if (!parV.has(c)) added.push(`${ns}/v/${c}`);
426
- for (const c of childE) if (!parE.has(c)) added.push(`${ns}/e/${c}`);
427
- for (const c of parV) if (!childV.has(c)) removed.push(`${ns}/v/${c}`);
428
- for (const c of parE) if (!childE.has(c)) removed.push(`${ns}/e/${c}`);
289
+ for (const [id, cid] of child) {
290
+ const prev = par.get(id);
291
+ if (!prev) added.push(`${ns}/${id}`);
292
+ else if (prev.toString() !== cid.toString()) updated.push(`${ns}/${id}`);
429
293
  }
294
+ for (const id of par.keys()) if (!child.has(id)) removed.push(`${ns}/${id}`);
430
295
  return {
431
296
  message: commit.message,
432
- parents: commit.parents.map((c) => c.toString()),
433
- timestamp: commit.timestamp,
297
+ parent: commit.parent?.toString() ?? null,
298
+ epoch: commit.epoch,
299
+ repo: ns,
434
300
  root: commit.root.toString(),
435
301
  added: added.sort(),
302
+ updated: updated.sort(),
436
303
  removed: removed.sort()
437
304
  };
438
305
  }
439
- /** check if the namespace already exists (head resolves) */
440
- async namespaceExists(namespace, publisher) {
441
- const head = await this.resolveHeadCommit(publisher, namespace);
442
- if (!head) return false;
443
- return namespace in await this.rootMapAt(head);
306
+ /** check if the repo already exists (head resolves) */
307
+ async repoExists(publisher, repo) {
308
+ return await this.resolveHeadCommit(publisher, repo) !== null;
444
309
  }
445
- /** Lists every vertex and edge currently committed under a namespace, resolved from the on-chain root. */
446
- async listNamespace(namespace, publisher) {
447
- const head = await this.resolveHeadCommit(publisher, namespace);
448
- if (!head) return {
449
- vertices: [],
450
- edges: []
451
- };
452
- const { vertexLinks, edgeLinks } = await this.treeLinksAt(head, namespace);
453
- const vertices = [];
454
- for (const link of vertexLinks) vertices.push(await this.decodeVertex(link, head));
455
- const edges = [];
456
- for (const link of edgeLinks) edges.push(await this.decodeEdge(link, head));
457
- return {
458
- vertices,
459
- edges
460
- };
310
+ /** Lists every record currently committed under a repo, resolved from the on-chain root. */
311
+ async listRepo(publisher, repo) {
312
+ return this.listAt(await this.resolveHeadCommit(publisher, repo));
313
+ }
314
+ /** Every record in the state a commit holds; none for no commit. */
315
+ async listAt(head) {
316
+ if (!head) return { records: [] };
317
+ const { state } = await this.stateAt(head);
318
+ const records = [];
319
+ for (const [id, cid] of state) records.push(await this.decodeRecord(id, cid, head));
320
+ return { records };
461
321
  }
462
322
  /**
463
- * Fetch a single vertex by CID, resolving through the publisher's commit
464
- * CAR chain (vertex blocks are not individually pinned — they live inside
465
- * commit CARs).
323
+ * Fetch the current version of one record by id — one MST path from the
324
+ * on-chain root, then the record block. Null if the repo has no such id.
466
325
  */
467
- async readVertex(cid, publisher, namespace) {
468
- const head = await this.resolveHeadCommit(publisher, namespace);
469
- if (!head) throw new Error(`publisher ${publisher} has no on-chain commits in namespace ${namespace}`);
470
- return this.decodeVertex(CID.parse(cid), head);
326
+ async readRecord(publisher, repo, id) {
327
+ const head = await this.resolveHeadCommit(publisher, repo);
328
+ if (!head) throw new Error(`publisher ${publisher} has no on-chain commits in repo ${repo}`);
329
+ const get = (cid$1) => this.getBlock(cid$1, head);
330
+ const cid = await lookupMst((await this.getCommit(head)).root, id, get);
331
+ return cid ? this.decodeRecord(id, cid, head) : null;
471
332
  }
472
333
  };
473
334
 
474
335
  //#endregion
475
- export { FangornEngine, MAX_NAMESPACE_LENGTH, MetagraphRegistry, assertValidNamespace, rootHexFromCid };
336
+ export { FangornEngine, MAX_REPO_NAME_LENGTH, SchemaRegistry, assertValidRepoName, rootHexFromCid };