@fangorn-network/sdk 2026.7.1-2.1 → 2026.7.13

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.
package/README.md CHANGED
@@ -1,16 +1,14 @@
1
1
  # Fangorn SDK
2
2
 
3
- commit → push → discover → fetch
4
-
5
3
  Intent-bound data for the agentic web.
6
4
 
7
5
  Fangorn lets you publish content-addressed graph data, organized into namespaces, so that agents can discover and verify it across any number of publishers. Content is stored in your own storage backend (IPFS via Pinata today); the on-chain **DataRegistry** holds only a single cryptographic pointer per publisher. The protocol coordinates commitment and discovery without ever touching your content directly.
8
6
 
9
- Each publisher owns exactly **one on-chain state root** — the root of a content-addressed Pail tree (`@web3-storage/pail`), wrapped in a commit. Everything you publish lives as key-prefixed **namespaces** inside that one tree. Advancing the root is a compare-and-swap: it *is* a git ref update.
7
+ Each publisher owns exactly **one on-chain state root** — the digest of a commit block wrapping a native IPLD DAG. Everything you publish lives as **namespaces** inside that one root map. Advancing the root is a compare-and-swap: it _is_ a git ref update.
10
8
 
11
- Data is a **metagraph** — **vertices** (a JSON payload tagged by a free-form schema id) and **edges** (a labeled relation between two vertex CIDs) — committed under a namespace.
9
+ Data is a **metagraph** — **vertices** (a JSON payload tagged by a free-form schema id) and **edges** (a labeled relation between two vertices, as native IPLD links) — committed under a namespace.
12
10
 
13
- Datasets are versioned like git: each update is a **commit** that points at its parent, the registry stores only the pointer to the latest commit, and full history lives in IPFS — reconstructible from the on-chain tip alone, no indexer required. `commit` builds locally (permissionless); `push` moves the on-chain pointer (the single permissioned step, fast-forward checked).
11
+ Datasets are versioned like git, down to the storage model: each update is a **commit** that points at its parent and at a single **CAR file** (a packfile) holding only the blocks that commit introduced. The registry stores only the pointer to the latest commit; full history lives in IPFS — reconstructible from the on-chain tip alone, no indexer required. `commit` builds the graph in memory and persists it as **exactly two uploads** (one CAR + one small commit block), regardless of graph size; `push` moves the on-chain pointer (the single permissioned step, fast-forward checked). Unchanged data re-derives identical CIDs and is never re-uploaded.
14
12
 
15
13
  > **Note:** access-controlled (encrypted) fields and the purchase → claim → fetch settlement flow are being built on top of this registry and are **not available in the current release**. Registration, namespaces, and the git-native commit / push / log / clone rail are live.
16
14
 
@@ -38,6 +36,7 @@ fangorn init
38
36
  ```
39
37
 
40
38
  `fangorn init` prompts for:
39
+
41
40
  - Wallet private key
42
41
  - Pinata JWT + gateway URL (content + commit-object storage)
43
42
  - Fangorn access worker URL (reserved for the upcoming access-control flow)
@@ -64,7 +63,7 @@ fangorn register
64
63
 
65
64
  ### Track a namespace (git-native repo)
66
65
 
67
- A **namespace** is a key prefix inside your on-chain tree. `repo init` allocates it and starts tracking it in a local `.fangorn/` pointer file (just a HEAD ref — there is no local object store; commit objects live in IPFS).
66
+ A **namespace** is an entry in your on-chain root map. `repo init` allocates it and starts tracking it in a local `.fangorn/` pointer file (just a HEAD ref — there is no local object store; commit objects and their CARs live in IPFS).
68
67
 
69
68
  ```sh
70
69
  # Allocate a namespace on-chain (no-op if it already exists) and track it here
@@ -73,7 +72,7 @@ fangorn repo init rusty-anchor
73
72
 
74
73
  ### Commit → push
75
74
 
76
- `commit` snapshots a namespace's vertices/edges into a new commit **locally** (pins the blocks to IPFS, advances your local HEAD) — it does **not** touch the chain. `push` fast-forwards the on-chain state root to your local tip: the single permissioned step.
75
+ `commit` snapshots a namespace's vertices/edges into a new commit (one CAR upload to IPFS, advances your local HEAD) — it does **not** touch the chain. `push` fast-forwards the on-chain state root to your local tip: the single permissioned step.
77
76
 
78
77
  ```sh
79
78
  # Snapshot graph data into a new local commit — does NOT push
@@ -88,18 +87,19 @@ fangorn push --force # push even if it doesn't fast-forward the on-chain
88
87
 
89
88
  ```json
90
89
  {
91
- "vertices": [
92
- { "id": "t1", "tag": "track", "payload": { "title": "Locura", "artist": "Alice" } },
93
- { "id": "a1", "tag": "artist", "payload": { "name": "Alice" } }
94
- ],
95
- "edges": [
96
- { "rel": "performed_by", "from": "t1", "to": "a1" }
97
- ]
90
+ "vertices": [
91
+ {
92
+ "id": "t1",
93
+ "tag": "track",
94
+ "payload": { "title": "Locura", "artist": "Alice" }
95
+ },
96
+ { "id": "a1", "tag": "artist", "payload": { "name": "Alice" } }
97
+ ],
98
+ "edges": [{ "rel": "performed_by", "from": "t1", "to": "a1" }]
98
99
  }
99
100
  ```
100
101
 
101
- Each commit records its parent, so history is real and walkable. Deleting a vertex is just a later commit that omits it — earlier history is retained. Blocks are content-addressed, so unchanged data is reused byte-for-byte across commits.
102
-
102
+ Each commit records its parent, so history is real and walkable. By default a commit is **additive** (the staged graph joins the namespace's existing contents); pass `--replace` for snapshot semantics, where the file _is_ the namespace's new state and anything omitted is removed — earlier history is retained either way. Blocks are content-addressed, so unchanged data is reused byte-for-byte across commits and never re-uploaded.
103
103
 
104
104
  ### Graph Builders
105
105
 
@@ -111,7 +111,7 @@ A graph builders are delegated to the application layer. Developers are responsi
111
111
  fangorn status # local tip vs on-chain tip
112
112
  fangorn log # walk commit history from the tip (newest first)
113
113
  fangorn log -n 5 # limit
114
- fangorn show # the tip commit + which keys it changed vs its parent
114
+ fangorn show # the tip commit + what it changed vs its parent
115
115
  fangorn show <commitCid> # a specific commit
116
116
 
117
117
  # List every vertex and edge committed under a namespace, as JSON
@@ -133,9 +133,9 @@ fangorn clone <owner> rusty-anchor --dir ./somewhere
133
133
  Watch a namespace for on-chain updates and stream the diffs — **no subgraph, no
134
134
  indexer**. A publisher owns exactly one on-chain root, so this watches that
135
135
  publisher's `StateCommitted` event (read straight from the RPC node) and, for
136
- each new root, diffs the tree against the previous one restricted to your
137
- namespace's key prefix. Only pushes that actually changed the namespace are
138
- emitted. Diffs are resolved from IPFS on demand.
136
+ each new root, diffs your namespace's link sets against the previous root.
137
+ Only pushes that actually changed the namespace are emitted. Each push's
138
+ blocks arrive as one CAR download, resolved from IPFS on demand.
139
139
 
140
140
  ```sh
141
141
  # Watch the current repo's namespace; each change is one JSON line on stdout.
@@ -152,14 +152,18 @@ Each emitted line is a namespace change:
152
152
 
153
153
  ```jsonc
154
154
  {
155
- "namespace": "rusty-anchor",
156
- "owner": "0x...",
157
- "commitCid": "bafy...", // the new on-chain tip
158
- "blockNumber": "12345678", // persist this to resume
159
- "addedVertices": [{ "cid": "bafy...", "schemaId": "track", "payload": { "title": "Locura" } }],
160
- "addedEdges": [{ "sourceCid": "bafy...", "relation": "by", "targetCid": "bafy..." }],
161
- "removedVertexCids": ["bafy..."],
162
- "removedEdges": []
155
+ "namespace": "rusty-anchor",
156
+ "owner": "0x...",
157
+ "commitCid": "bafy...", // the new on-chain tip
158
+ "blockNumber": "12345678", // persist this to resume
159
+ "addedVertices": [
160
+ { "cid": "bafy...", "schemaId": "track", "payload": { "title": "Locura" } },
161
+ ],
162
+ "addedEdges": [
163
+ { "sourceCid": "bafy...", "relation": "by", "targetCid": "bafy..." },
164
+ ],
165
+ "removedVertexCids": ["bafy..."],
166
+ "removedEdges": [],
163
167
  }
164
168
  ```
165
169
 
@@ -188,16 +192,21 @@ your initial index from `fangorn read` first, then subscribe for the deltas.
188
192
  import { Fangorn, FangornConfig } from "@fangorn-network/sdk";
189
193
 
190
194
  const fangorn = Fangorn.create({
191
- privateKey: "0x...",
192
- storage: { pinata: { jwt: process.env.PINATA_JWT!, gateway: process.env.PINATA_GATEWAY! } },
193
- config: FangornConfig, // defaults to Arbitrum Sepolia
194
- domain: "localhost",
195
+ privateKey: "0x...",
196
+ storage: {
197
+ pinata: {
198
+ jwt: process.env.PINATA_JWT!,
199
+ gateway: process.env.PINATA_GATEWAY!,
200
+ },
201
+ },
202
+ config: FangornConfig, // defaults to Arbitrum Sepolia
203
+ domain: "localhost",
195
204
  });
196
205
 
197
206
  // Register once before committing.
198
207
  const registry = fangorn.getDataRegistry();
199
208
  if (!(await registry.isRegistered(fangorn.getAddress()))) {
200
- await registry.register();
209
+ await registry.register();
201
210
  }
202
211
  ```
203
212
 
@@ -213,13 +222,13 @@ await fangorn.initRepo("rusty-anchor");
213
222
 
214
223
  // First commit — no parent
215
224
  const c1 = await fangorn.commit({
216
- namespace: "rusty-anchor",
217
- message: "initial import",
218
- vertices: [
219
- { id: "t1", tag: "track", payload: { title: "Locura", artist: "Alice" } },
220
- { id: "a1", tag: "artist", payload: { name: "Alice" } },
221
- ],
222
- edges: [{ rel: "performed_by", from: "t1", to: "a1" }],
225
+ namespace: "rusty-anchor",
226
+ message: "initial import",
227
+ vertices: [
228
+ { id: "t1", tag: "track", payload: { title: "Locura", artist: "Alice" } },
229
+ { id: "a1", tag: "artist", payload: { name: "Alice" } },
230
+ ],
231
+ edges: [{ rel: "performed_by", from: "t1", to: "a1" }],
223
232
  });
224
233
 
225
234
  // Settle it on-chain (fast-forward from "no tip yet")
@@ -227,10 +236,12 @@ await fangorn.push(c1.commitCid);
227
236
 
228
237
  // A follow-up commit builds on the previous one
229
238
  const c2 = await fangorn.commit({
230
- namespace: "rusty-anchor",
231
- parent: c1.commitCid,
232
- message: "add another track",
233
- vertices: [{ id: "t2", tag: "track", payload: { title: "Otra", artist: "Alice" } }],
239
+ namespace: "rusty-anchor",
240
+ parent: c1.commitCid,
241
+ message: "add another track",
242
+ vertices: [
243
+ { id: "t2", tag: "track", payload: { title: "Otra", artist: "Alice" } },
244
+ ],
234
245
  });
235
246
  await fangorn.push(c2.commitCid); // refuses unless it fast-forwards the on-chain tip (pass { force: true } to override)
236
247
  ```
@@ -244,10 +255,10 @@ const tip = await fangorn.onChainTip(fangorn.getAddress());
244
255
 
245
256
  // Walk commits, newest first
246
257
  for await (const c of fangorn.log(tip!)) {
247
- console.log(c.cid, c.message);
258
+ console.log(c.cid, c.message);
248
259
  }
249
260
 
250
- // What a commit changed vs. its first parent (namespaced pail keys added/removed)
261
+ // What a commit changed vs. its first parent (namespaced vertex/edge entries added/removed)
251
262
  const diff = await fangorn.show(tip!);
252
263
 
253
264
  // Every vertex and edge currently committed under a namespace
@@ -267,9 +278,11 @@ For the common "stage and settle in one shot" case, `upload` (one vertex) and `u
267
278
  await fangorn.upload("rusty-anchor", { title: "Locura" }, "track");
268
279
 
269
280
  await fangorn.uploadBatch(
270
- "rusty-anchor",
271
- [{ id: "t1", tag: "track", payload: { title: "Locura" } }],
272
- [/* edges */],
281
+ "rusty-anchor",
282
+ [{ id: "t1", tag: "track", payload: { title: "Locura" } }],
283
+ [
284
+ /* edges */
285
+ ],
273
286
  );
274
287
  ```
275
288
 
@@ -283,14 +296,14 @@ replays from a block cursor (`fromBlock`) and then watches live until the
283
296
  const controller = new AbortController();
284
297
 
285
298
  for await (const change of fangorn.subscribe({
286
- namespace: "rusty-anchor",
287
- owner: "0x...", // defaults to your own address
288
- fromBlock: savedCursor, // omit to start live from the current tip
289
- signal: controller.signal,
299
+ namespace: "rusty-anchor",
300
+ owner: "0x...", // defaults to your own address
301
+ fromBlock: savedCursor, // omit to start live from the current tip
302
+ signal: controller.signal,
290
303
  })) {
291
- for (const v of change.addedVertices) index.upsert(v.cid, v.payload);
292
- for (const cid of change.removedVertexCids) index.remove(cid);
293
- persistCursor(change.blockNumber);
304
+ for (const v of change.addedVertices) index.upsert(v.cid, v.payload);
305
+ for (const cid of change.removedVertexCids) index.remove(cid);
306
+ persistCursor(change.blockNumber);
294
307
  }
295
308
  ```
296
309
 
@@ -300,9 +313,10 @@ two arbitrary roots without watching.
300
313
 
301
314
  ### Storage
302
315
 
303
- Fangorn operates on a 'Bring Your Own Storage' basis. Content-addressed blocks
304
- (vertices, edges, pail shards, commit objects) are pinned to IPFS via Pinata; the chain
305
- holds only the 32-byte commit pointer. Additional backends can be added behind the
316
+ Fangorn operates on a 'Bring Your Own Storage' basis. Each commit is persisted as
317
+ one CAR file (an opaque packfile of the commit's new blocks) plus one small commit
318
+ block, pinned to IPFS via Pinata; the chain holds only the 32-byte commit pointer.
319
+ The backend never needs to understand IPLD — any blob store can implement the
306
320
  `MetadataStorage` interface.
307
321
 
308
322
  ---
@@ -311,9 +325,9 @@ holds only the 32-byte commit pointer. Additional backends can be added behind t
311
325
 
312
326
  ### Arbitrum Sepolia
313
327
 
314
- | Contract | Address |
315
- | ------------- | -------------------------------------------- |
316
- | DataRegistry | `0x9a3811b365a4aeea1626eaad185b273424ae5e48` |
328
+ | Contract | Address |
329
+ | ------------ | -------------------------------------------- |
330
+ | DataRegistry | `0x9a3811b365a4aeea1626eaad185b273424ae5e48` |
317
331
 
318
332
  This is the address in `FangornConfig`; the SDK uses it by default.
319
333
 
@@ -338,11 +352,11 @@ pnpm test:e2e
338
352
 
339
353
  Required variables:
340
354
 
341
- | Variable | Description |
342
- | ----------------------- | ----------------------------------------- |
343
- | `ETH_PRIVATE_KEY` | Publisher private key (needs testnet ETH) |
344
- | `PINATA_JWT` | Pinata API JWT |
345
- | `PINATA_GATEWAY` | Pinata gateway URL |
355
+ | Variable | Description |
356
+ | ----------------- | ----------------------------------------- |
357
+ | `ETH_PRIVATE_KEY` | Publisher private key (needs testnet ETH) |
358
+ | `PINATA_JWT` | Pinata API JWT |
359
+ | `PINATA_GATEWAY` | Pinata gateway URL |
346
360
 
347
361
  The publisher must be registered (`fangorn register`, or `registry.register()`) on the target key.
348
362
 
package/lib/cli/cli.js CHANGED
@@ -209,7 +209,7 @@ program.command("repo").description("Repository operations").command("init").des
209
209
  process.exit(1);
210
210
  }
211
211
  });
212
- program.command("commit").description("Snapshot a namespace's vertices/edges into a new local commit (does not push)").argument("<file>", "JSON file: {\"vertices\":[{\"id\",\"tag\",\"payload\"}],\"edges\":[{\"rel\",\"from\",\"to\"}]}").requiredOption("-m, --message <msg>", "Commit message").action(async (file, options) => {
212
+ program.command("commit").description("Snapshot a namespace's vertices/edges into a new local commit (does not push)").argument("<file>", "JSON file: {\"vertices\":[{\"id\",\"tag\",\"payload\"}],\"edges\":[{\"rel\",\"from\",\"to\"}]}").requiredOption("-m, --message <msg>", "Commit message").option("--replace", "Snapshot semantics: the file replaces the namespace's previous contents (omitted entries are removed)").action(async (file, options) => {
213
213
  try {
214
214
  if (!existsSync(file)) throw new Error(`file not found: ${file}`);
215
215
  const data = JSON.parse(readFileSync(file, "utf-8"));
@@ -224,13 +224,14 @@ program.command("commit").description("Snapshot a namespace's vertices/edges int
224
224
  vertices: data.vertices,
225
225
  edges: data.edges ?? [],
226
226
  parent,
227
- message: options.message
227
+ message: options.message,
228
+ replace: options.replace
228
229
  });
229
230
  s.stop();
230
231
  repo.setHead(result.commitCid);
231
232
  console.log(`Commit: ${result.commitCid}`);
232
233
  console.log(`Parent: ${result.parents[0] ?? "(root)"}`);
233
- console.log(`Tree: ${result.pailRoot}`);
234
+ console.log(`Tree: ${result.root}`);
234
235
  console.log(`Staged: ${data.vertices.length.toString()} vertice(s) / ${(data.edges ?? []).length.toString()} edge(s)`);
235
236
  console.log(`Message: ${options.message}`);
236
237
  console.log(`\nCommitted locally. Run \`fangorn push\` to settle it on-chain.`);
@@ -286,7 +287,7 @@ program.command("log").description("Walk commit history from the local tip").opt
286
287
  for await (const c of fangorn.log(head, options.max)) {
287
288
  console.log(`commit ${c.cid}`);
288
289
  console.log(`Date: ${new Date(c.timestamp).toISOString()}`);
289
- console.log(`Tree: ${c.pailRoot}`);
290
+ console.log(`Tree: ${c.root}`);
290
291
  console.log(`\n ${c.message}\n`);
291
292
  }
292
293
  process.exit(0);
@@ -304,7 +305,7 @@ program.command("show").description("Show a commit and what it changed vs. its p
304
305
  console.log(`commit ${target}`);
305
306
  console.log(`Date: ${new Date(diff.timestamp).toISOString()}`);
306
307
  console.log(`Parents: ${diff.parents.length ? diff.parents.join(", ") : "(root)"}`);
307
- console.log(`Tree: ${diff.pailRoot}`);
308
+ console.log(`Tree: ${diff.root}`);
308
309
  console.log(`\n ${diff.message}\n`);
309
310
  console.log(`Changes vs. parent: +${diff.added.length.toString()} / -${diff.removed.length.toString()} key(s)`);
310
311
  for (const k of diff.added) console.log(` + ${k}`);
@@ -402,8 +403,7 @@ program.command("read").description("List every vertex and edge committed under
402
403
  vertices: contents.vertices,
403
404
  edges: contents.edges
404
405
  };
405
- process.stdout.write(JSON.stringify(out, null, options.pretty ? 2 : 0) + "\n");
406
- process.exit(0);
406
+ process.stdout.write(JSON.stringify(out, null, options.pretty ? 2 : 0) + "\n", () => process.exit(0));
407
407
  } catch (err) {
408
408
  console.error("Failed:", err.message);
409
409
  process.exit(1);
@@ -0,0 +1,10 @@
1
+ import { Block } from "./graph.js";
2
+ import { CID } from "multiformats/cid";
3
+
4
+ //#region src/engine/car.d.ts
5
+ /** Serialize blocks into CAR v1 bytes under a single root. */
6
+ declare function packCar(root: CID, blocks: Iterable<Block>): Promise<Uint8Array>;
7
+ /** Decode CAR bytes back into blocks. */
8
+ declare function readCar(bytes: Uint8Array): Promise<Block[]>;
9
+ //#endregion
10
+ export { packCar, readCar };
@@ -0,0 +1,37 @@
1
+ import { CID } from "multiformats/cid";
2
+ import { CarReader, CarWriter } from "@ipld/car";
3
+
4
+ //#region src/engine/car.ts
5
+ /** Serialize blocks into CAR v1 bytes under a single root. */
6
+ async function packCar(root, blocks) {
7
+ const { writer, out } = CarWriter.create([root]);
8
+ const collected = [];
9
+ const sink = (async () => {
10
+ for await (const part of out) collected.push(part);
11
+ })();
12
+ for (const block of blocks) await writer.put(block);
13
+ await writer.close();
14
+ await sink;
15
+ let total = 0;
16
+ for (const p of collected) total += p.length;
17
+ const buf = new Uint8Array(total);
18
+ let off = 0;
19
+ for (const p of collected) {
20
+ buf.set(p, off);
21
+ off += p.length;
22
+ }
23
+ return buf;
24
+ }
25
+ /** Decode CAR bytes back into blocks. */
26
+ async function readCar(bytes) {
27
+ const reader = await CarReader.fromBytes(bytes);
28
+ const blocks = [];
29
+ for await (const { cid, bytes: blockBytes } of reader.blocks()) blocks.push({
30
+ cid: CID.parse(cid.toString()),
31
+ bytes: blockBytes
32
+ });
33
+ return blocks;
34
+ }
35
+
36
+ //#endregion
37
+ export { packCar, readCar };
@@ -0,0 +1,70 @@
1
+ import { CID } from "multiformats/cid";
2
+
3
+ //#region src/engine/graph.d.ts
4
+ /** A content-addressed IPLD block. */
5
+ interface Block {
6
+ cid: CID;
7
+ bytes: Uint8Array;
8
+ }
9
+ /** Encode any value as canonical dag-cbor and derive its CIDv1 (sha256). */
10
+ declare function encodeBlock(obj: unknown): Promise<Block>;
11
+ declare function decodeBlock<T>(bytes: Uint8Array): T;
12
+ /** Vertex block: a JSON payload tagged by a free-form schema id. */
13
+ interface VertexBlock {
14
+ schemaId: string;
15
+ payload: Record<string, unknown>;
16
+ }
17
+ /** Edge block: a labeled relation between two vertex blocks, as native links. */
18
+ interface EdgeBlock {
19
+ source: CID;
20
+ relation: string;
21
+ target: CID;
22
+ }
23
+ /**
24
+ * Namespace tree: the complete current contents of one namespace, as pages of
25
+ * sorted vertex/edge links. Paged so a namespace of any size never produces a
26
+ * single oversized block; sorted so the same set of links always builds the
27
+ * same pages (deterministic CIDs → structural sharing across commits).
28
+ */
29
+ interface NamespaceTree {
30
+ vertices: CID[];
31
+ edges: CID[];
32
+ }
33
+ /**
34
+ * Average links per page. Boundaries are content-defined (a link closes its
35
+ * page when its digest satisfies a 1-in-TARGET_PAGE_SIZE condition), so an
36
+ * insertion into the sorted link set only rewrites the page it lands in —
37
+ * NOT every page after it, as fixed-size chunking would. That keeps the CAR
38
+ * delta of an incremental commit proportional to the delta, not to the
39
+ * accumulated namespace size. Kept small (256 links ≈ 10KB) so the unit of
40
+ * rewrite is cheap; a large staged delta touches many pages, but never costs
41
+ * more than the namespace's total page bytes.
42
+ */
43
+ declare const TARGET_PAGE_SIZE = 256;
44
+ /** Hard cap so a pathological digest run can't produce an oversized page block. */
45
+ declare const MAX_PAGE_SIZE: number;
46
+ /** Root map: every namespace this publisher has, each pointing at its tree. */
47
+ type RootMap = Record<string, CID>;
48
+ /**
49
+ * Commit block: the git-like history object the on-chain digest points at.
50
+ * `car` is the opaque storage URI of the CAR file holding every block this
51
+ * commit introduced — the commit block itself is stored OUTSIDE that CAR
52
+ * (individually addressable), so a reader goes digest → commit → CAR with no
53
+ * index lookups.
54
+ */
55
+ interface CommitBlock {
56
+ root: CID;
57
+ parents: CID[];
58
+ timestamp: number;
59
+ message: string;
60
+ car: string;
61
+ }
62
+ /** Build the page blocks for a set of links; returns the page links in tree order. */
63
+ declare function buildPages(links: Iterable<CID>): Promise<{
64
+ pages: Block[];
65
+ pageLinks: CID[];
66
+ }>;
67
+ /** Read every link out of a tree's pages via `getBlock`. */
68
+ declare function readPages(pageLinks: CID[], getBlock: (cid: CID) => Promise<Uint8Array>): Promise<CID[]>;
69
+ //#endregion
70
+ export { Block, CommitBlock, EdgeBlock, MAX_PAGE_SIZE, NamespaceTree, RootMap, TARGET_PAGE_SIZE, VertexBlock, buildPages, decodeBlock, encodeBlock, readPages };
@@ -0,0 +1,73 @@
1
+ import { CID } from "multiformats/cid";
2
+ import * as dagCbor from "@ipld/dag-cbor";
3
+ import { sha256 } from "multiformats/hashes/sha2";
4
+
5
+ //#region src/engine/graph.ts
6
+ /** Encode any value as canonical dag-cbor and derive its CIDv1 (sha256). */
7
+ async function encodeBlock(obj) {
8
+ const bytes = dagCbor.encode(obj);
9
+ const hash = await sha256.digest(bytes);
10
+ return {
11
+ cid: CID.createV1(dagCbor.code, hash),
12
+ bytes
13
+ };
14
+ }
15
+ function decodeBlock(bytes) {
16
+ return dagCbor.decode(bytes);
17
+ }
18
+ /**
19
+ * Average links per page. Boundaries are content-defined (a link closes its
20
+ * page when its digest satisfies a 1-in-TARGET_PAGE_SIZE condition), so an
21
+ * insertion into the sorted link set only rewrites the page it lands in —
22
+ * NOT every page after it, as fixed-size chunking would. That keeps the CAR
23
+ * delta of an incremental commit proportional to the delta, not to the
24
+ * accumulated namespace size. Kept small (256 links ≈ 10KB) so the unit of
25
+ * rewrite is cheap; a large staged delta touches many pages, but never costs
26
+ * more than the namespace's total page bytes.
27
+ */
28
+ const TARGET_PAGE_SIZE = 256;
29
+ /** Hard cap so a pathological digest run can't produce an oversized page block. */
30
+ const MAX_PAGE_SIZE = 4 * TARGET_PAGE_SIZE;
31
+ /** Content-defined boundary: last two digest bytes mod the target size. */
32
+ function isPageBoundary(link) {
33
+ const d = link.multihash.digest;
34
+ return (d[d.length - 2] << 8 | d[d.length - 1]) % TARGET_PAGE_SIZE === 0;
35
+ }
36
+ /** Sort link strings the way pages are ordered (plain lexicographic CID text). */
37
+ function sortedUnique(links) {
38
+ const byStr = /* @__PURE__ */ new Map();
39
+ for (const l of links) byStr.set(l.toString(), l);
40
+ return [...byStr.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, c]) => c);
41
+ }
42
+ /** Build the page blocks for a set of links; returns the page links in tree order. */
43
+ async function buildPages(links) {
44
+ const sorted = sortedUnique(links);
45
+ const pages = [];
46
+ const pageLinks = [];
47
+ let current = [];
48
+ const close = async () => {
49
+ if (current.length === 0) return;
50
+ const page = await encodeBlock(current);
51
+ pages.push(page);
52
+ pageLinks.push(page.cid);
53
+ current = [];
54
+ };
55
+ for (const link of sorted) {
56
+ current.push(link);
57
+ if (isPageBoundary(link) || current.length >= MAX_PAGE_SIZE) await close();
58
+ }
59
+ await close();
60
+ return {
61
+ pages,
62
+ pageLinks
63
+ };
64
+ }
65
+ /** Read every link out of a tree's pages via `getBlock`. */
66
+ async function readPages(pageLinks, getBlock) {
67
+ const out = [];
68
+ for (const link of pageLinks) out.push(...decodeBlock(await getBlock(link)));
69
+ return out;
70
+ }
71
+
72
+ //#endregion
73
+ export { MAX_PAGE_SIZE, TARGET_PAGE_SIZE, buildPages, decodeBlock, encodeBlock, readPages };