@fangorn-network/sdk 2026.5.11 → 2026.7.1-2.0

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 (101) hide show
  1. package/README.md +219 -225
  2. package/lib/ crypto/constants.d.ts +4 -0
  3. package/lib/ crypto/constants.js +5 -0
  4. package/lib/ crypto/merkle.d.ts +10 -0
  5. package/lib/ crypto/merkle.js +34 -0
  6. package/lib/cli/cli.d.ts +0 -0
  7. package/lib/cli/cli.js +234 -235
  8. package/lib/cli/index.d.ts +13 -650
  9. package/lib/config.d.ts +45 -699
  10. package/lib/config.js +6 -22
  11. package/lib/contracts/data-registry/abi.d.ts +38 -0
  12. package/lib/contracts/data-registry/abi.js +237 -0
  13. package/lib/contracts/data-registry/index.d.ts +81 -0
  14. package/lib/contracts/data-registry/index.js +184 -0
  15. package/lib/contracts/data-registry/test.d.ts +1 -0
  16. package/lib/contracts/index.d.ts +3 -0
  17. package/lib/contracts/index.js +4 -0
  18. package/lib/crypto/aes.d.ts +26 -0
  19. package/lib/crypto/aes.js +58 -0
  20. package/lib/crypto/encryption.d.ts +53 -0
  21. package/lib/crypto/encryption.js +82 -0
  22. package/lib/crypto/rand.d.ts +5 -0
  23. package/lib/{modules/encryption → crypto}/rand.js +1 -1
  24. package/lib/{modules/encryption → crypto}/types.d.ts +1 -1
  25. package/lib/engine/blockstore.d.ts +24 -0
  26. package/lib/engine/blockstore.js +85 -0
  27. package/lib/engine/index.d.ts +180 -0
  28. package/lib/engine/index.js +367 -0
  29. package/lib/fangorn.d.ts +149 -16
  30. package/lib/fangorn.js +256 -37
  31. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +1 -0
  32. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  33. package/lib/harness/index.d.ts +57 -0
  34. package/lib/harness/index.js +67 -0
  35. package/lib/index.d.ts +2 -4
  36. package/lib/index.js +1 -3
  37. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js +218 -0
  38. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js +261 -0
  39. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js +156 -0
  40. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js +299 -0
  41. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js +532 -0
  42. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js +344 -0
  43. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js +137 -0
  44. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js +262 -0
  45. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/utils.js +150 -0
  46. package/lib/providers/storage/car.d.ts +36 -0
  47. package/lib/providers/storage/car.js +80 -0
  48. package/lib/providers/storage/pinata.d.ts +34 -2
  49. package/lib/providers/storage/pinata.js +141 -5
  50. package/lib/providers/storage/types.d.ts +31 -16
  51. package/lib/providers/storage/utils.js +2 -1
  52. package/lib/roles/repo/index.d.ts +56 -0
  53. package/lib/roles/repo/index.js +73 -0
  54. package/lib/test/car_smoke.d.ts +1 -0
  55. package/lib/test/car_smoke.js +81 -0
  56. package/lib/test/cleanup-embeddings-testdata.d.ts +1 -0
  57. package/lib/test/cleanup-embeddings-testdata.js +75 -0
  58. package/lib/test/setup-embeddings-testdata.d.ts +11 -0
  59. package/lib/test/setup-embeddings-testdata.js +155 -0
  60. package/lib/test/testbed.d.ts +39 -30
  61. package/lib/test/testbed.js +43 -129
  62. package/lib/types/index.d.ts +3 -19
  63. package/lib/utils/manifest.d.ts +23 -0
  64. package/lib/utils/manifest.js +77 -0
  65. package/package.json +99 -67
  66. package/lib/modules/encryption/actions.d.ts +0 -4
  67. package/lib/modules/encryption/actions.js +0 -18
  68. package/lib/modules/encryption/aes.d.ts +0 -10
  69. package/lib/modules/encryption/aes.js +0 -51
  70. package/lib/modules/encryption/rand.d.ts +0 -5
  71. package/lib/registries/datasource-registry/abi.d.ts +0 -156
  72. package/lib/registries/datasource-registry/abi.js +0 -194
  73. package/lib/registries/datasource-registry/index.d.ts +0 -30
  74. package/lib/registries/datasource-registry/index.js +0 -158
  75. package/lib/registries/index.d.ts +0 -3
  76. package/lib/registries/index.js +0 -4
  77. package/lib/registries/schema-registry/abi.d.ts +0 -218
  78. package/lib/registries/schema-registry/abi.js +0 -246
  79. package/lib/registries/schema-registry/index.d.ts +0 -34
  80. package/lib/registries/schema-registry/index.js +0 -179
  81. package/lib/registries/settlement-registry/abi.d.ts +0 -218
  82. package/lib/registries/settlement-registry/abi.js +0 -259
  83. package/lib/registries/settlement-registry/index.d.ts +0 -63
  84. package/lib/registries/settlement-registry/index.js +0 -325
  85. package/lib/registries/settlement-registry/types.d.ts +0 -54
  86. package/lib/roles/consumer/index.d.ts +0 -39
  87. package/lib/roles/consumer/index.js +0 -143
  88. package/lib/roles/consumer/types.d.ts +0 -47
  89. package/lib/roles/consumer/types.js +0 -1
  90. package/lib/roles/publisher/index.d.ts +0 -50
  91. package/lib/roles/publisher/index.js +0 -224
  92. package/lib/roles/publisher/types.d.ts +0 -99
  93. package/lib/roles/publisher/types.js +0 -1
  94. package/lib/roles/schema/index.d.ts +0 -18
  95. package/lib/roles/schema/index.js +0 -93
  96. package/lib/roles/schema/types.d.ts +0 -91
  97. package/lib/roles/schema/types.js +0 -1
  98. /package/lib/{modules/encryption/index.d.ts → crypto/utils.d.ts} +0 -0
  99. /package/lib/{modules/encryption/index.js → crypto/utils.js} +0 -0
  100. /package/lib/{modules/encryption/types.js → contracts/data-registry/test.js} +0 -0
  101. /package/lib/{registries/settlement-registry → crypto}/types.js +0 -0
package/lib/fangorn.js CHANGED
@@ -1,15 +1,14 @@
1
1
  import { FangornConfig } from "./config.js";
2
- import { SchemaRole } from "./roles/schema/index.js";
3
- import { PublisherRole } from "./roles/publisher/index.js";
4
- import { DataSourceRegistry } from "./registries/datasource-registry/index.js";
5
2
  import { PinataBackend } from "./providers/storage/pinata.js";
6
- import { ConsumerRole } from "./roles/consumer/index.js";
7
- import { SchemaRegistry } from "./registries/schema-registry/index.js";
8
- import { SettlementRegistry } from "./registries/settlement-registry/index.js";
3
+ import { FangornEngine, MetagraphRegistry } from "./engine/index.js";
4
+ import { StorageBlockstoreAdapter } from "./engine/blockstore.js";
5
+ import { DataRegistryClient } from "./contracts/data-registry/index.js";
9
6
  import { createPublicClient, createWalletClient, http } from "viem";
10
7
  import { privateKeyToAccount } from "viem/accounts";
8
+ import { CID } from "multiformats/cid";
11
9
 
12
10
  //#region src/fangorn.ts
11
+ const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
13
12
  function isPinataConfig(s) {
14
13
  return "pinata" in s;
15
14
  }
@@ -20,26 +19,27 @@ function resolveStorage(storage) {
20
19
  }
21
20
  var Fangorn = class Fangorn {
22
21
  ctx;
23
- _schema = null;
24
- _publisher = null;
25
- _consumer = null;
22
+ _engine = null;
23
+ _metagraph = null;
26
24
  constructor(ctx) {
27
25
  this.ctx = ctx;
28
26
  }
29
- get schema() {
30
- if (!this.ctx.metadataStorage) throw new Error("fangorn.schema requires storage. Pass { pinata: { ... } } to Fangorn.create()");
31
- return this._schema ??= new SchemaRole(this.ctx.schemaRegistry, this.ctx.metadataStorage, this.ctx.walletClient);
27
+ get engine() {
28
+ if (!this.ctx.metadataStorage) throw new Error("fangorn.engine requires storage configurations. Pass { pinata: { ... } } to Fangorn.create()");
29
+ if (!this._engine) {
30
+ const blockstoreAdapter = new StorageBlockstoreAdapter(this.ctx.metadataStorage);
31
+ this._metagraph = new MetagraphRegistry();
32
+ this._engine = new FangornEngine(blockstoreAdapter, this._metagraph, this.ctx.dataRegistry);
33
+ }
34
+ return this._engine;
32
35
  }
33
- get publisher() {
34
- if (!this.ctx.metadataStorage) throw new Error("fangorn.publisher requires storage. Pass { pinata: { ... } } to Fangorn.create()");
35
- return this._publisher ??= new PublisherRole(this.ctx.dataSourceRegistry, this.ctx.schemaRegistry, this.ctx.metadataStorage, this.ctx.walletClient, this.ctx.config);
36
- }
37
- get consumer() {
38
- return this._consumer ??= new ConsumerRole(this.ctx.dataSourceRegistry, this.ctx.settlementRegistry);
36
+ get metagraph() {
37
+ this.engine;
38
+ return this._metagraph;
39
39
  }
40
40
  static create(options) {
41
41
  if (!options.privateKey && !options.walletClient) throw new Error("Either privateKey or walletClient must be provided");
42
- const resolvedConfig = options.config ?? FangornConfig.ArbitrumSepolia;
42
+ const resolvedConfig = options.config ?? FangornConfig;
43
43
  const walletClient = options.walletClient ?? createWalletClient({
44
44
  account: privateKeyToAccount(options.privateKey ?? "0x0"),
45
45
  chain: resolvedConfig.chain,
@@ -52,31 +52,250 @@ var Fangorn = class Fangorn {
52
52
  walletClient,
53
53
  metadataStorage,
54
54
  domain,
55
- schemaRegistry: new SchemaRegistry(resolvedConfig.schemaRegistryContractAddress, publicClient, walletClient),
56
- dataSourceRegistry: new DataSourceRegistry(resolvedConfig.dataSourceRegistryContractAddress, publicClient, walletClient),
57
- settlementRegistry: new SettlementRegistry(resolvedConfig.settlementRegistryContractAddress, publicClient, walletClient),
58
- schemaRoleConfig: options.agentConfig ? {
59
- chainId: resolvedConfig.chain.id,
60
- rpcUrl: resolvedConfig.rpcUrl,
61
- privateKey: options.agentConfig.privateKey,
62
- pinataJwt: options.agentConfig.pinataJwt,
63
- registryOverrides: options.agentConfig.registryOverrides,
64
- subgraphOverrides: options.agentConfig.subgraphOverrides
65
- } : void 0,
55
+ dataRegistry: new DataRegistryClient(resolvedConfig.dataRegistryContractAddress, publicClient, walletClient),
66
56
  config: resolvedConfig
67
57
  });
68
58
  }
59
+ async reset() {
60
+ const registry = this.getDataRegistry();
61
+ const currentRoot = await registry.getNamespaceHead(this.getAddress());
62
+ await registry.commitStateRoot(currentRoot, ZERO_BYTES32);
63
+ }
64
+ /**
65
+ * Allocates a namespace key directly within the transactional Pail index tree.
66
+ * A no-op (no on-chain tx) if the namespace is already initialized, so callers
67
+ * can call this unconditionally before every publish.
68
+ */
69
+ async initRepo(repoName) {
70
+ const publisher = this.getAddress();
71
+ if (await this.engine.namespaceExists(repoName, publisher)) return {
72
+ cid: void 0,
73
+ commitCid: void 0,
74
+ txHash: void 0,
75
+ alreadyInitialized: true
76
+ };
77
+ const { batch, baseCommitCid } = await this.engine.createBatch(publisher);
78
+ await batch.put(`${repoName}/sys/init`, "initialized");
79
+ const { commitCid } = await this.engine.sealBatch(batch, baseCommitCid ? [baseCommitCid] : [], `Initialize repository workspace: ${repoName}`);
80
+ const { txHash } = await this.engine.pushCommit(publisher, commitCid);
81
+ return {
82
+ cid: commitCid.toString(),
83
+ commitCid: commitCid.toString(),
84
+ txHash,
85
+ alreadyInitialized: false
86
+ };
87
+ }
88
+ /**
89
+ * Stages a node payload against structural metadata rules inside the Pail collection context.
90
+ */
91
+ async upload(repoName, payload, schemaId) {
92
+ const publisher = this.getAddress();
93
+ const { batch, contractHeadHex, baseCommitCid } = await this.engine.createBatch(publisher);
94
+ if (contractHeadHex === ZERO_BYTES32) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
95
+ if (!this.metagraph.hasVertexSchema(repoName, schemaId)) this.metagraph.registerVertex(repoName, {
96
+ id: schemaId,
97
+ requiredFields: []
98
+ });
99
+ const vertexCidString = await this.engine.stageVertex(batch, repoName, schemaId, payload);
100
+ const { commitCid } = await this.engine.sealBatch(batch, baseCommitCid ? [baseCommitCid] : [], `Upload to namespace ${repoName} under schema ${schemaId}`);
101
+ const { txHash } = await this.engine.pushCommit(publisher, commitCid);
102
+ return {
103
+ payloadCid: vertexCidString,
104
+ commitCid: commitCid.toString(),
105
+ txHash
106
+ };
107
+ }
108
+ /**
109
+ * Stages vertices (and edges resolved by local id) into a namespace against an
110
+ * already-open batch. Shared by the immediate `uploadBatch` path and the git
111
+ * `commit` path. Returns the local-id → staged-CID map.
112
+ */
113
+ async stageGraph(batch, repoName, vertices, edges) {
114
+ const idToCid = /* @__PURE__ */ new Map();
115
+ const idToTag = /* @__PURE__ */ new Map();
116
+ for (const v of vertices) {
117
+ if (!this.metagraph.hasVertexSchema(repoName, v.tag)) this.metagraph.registerVertex(repoName, {
118
+ id: v.tag,
119
+ requiredFields: []
120
+ });
121
+ const cid = await this.engine.stageVertex(batch, repoName, v.tag, v.payload);
122
+ idToCid.set(v.id, cid);
123
+ idToTag.set(v.id, v.tag);
124
+ }
125
+ for (const e of edges) {
126
+ const sourceCid = idToCid.get(e.from);
127
+ const targetCid = idToCid.get(e.to);
128
+ const sourceTag = idToTag.get(e.from);
129
+ const targetTag = idToTag.get(e.to);
130
+ if (!sourceCid || !targetCid || !sourceTag || !targetTag) throw new Error(`edge references unknown local id (from=${e.from}, to=${e.to})`);
131
+ if (!this.metagraph.hasEdgeSchema(repoName, sourceTag, e.rel, targetTag)) this.metagraph.registerEdge(repoName, {
132
+ sourceSchema: sourceTag,
133
+ relation: e.rel,
134
+ targetSchema: targetTag
135
+ });
136
+ await this.engine.stageEdge(batch, repoName, {
137
+ sourceCid,
138
+ relation: e.rel,
139
+ targetCid
140
+ }, sourceTag, targetTag);
141
+ }
142
+ return idToCid;
143
+ }
144
+ /**
145
+ * Stages many vertices (and optionally edges between them) in a single
146
+ * on-chain commit, instead of one tx per vertex. Edges reference vertices by
147
+ * the caller-supplied local `id`, resolved to their staged CID before staging.
148
+ */
149
+ async uploadBatch(repoName, vertices, edges = []) {
150
+ const publisher = this.getAddress();
151
+ const { batch, contractHeadHex, baseCommitCid } = await this.engine.createBatch(publisher);
152
+ if (contractHeadHex === ZERO_BYTES32) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
153
+ const idToCid = await this.stageGraph(batch, repoName, vertices, edges);
154
+ const { commitCid } = await this.engine.sealBatch(batch, baseCommitCid ? [baseCommitCid] : [], `Batch upload to namespace ${repoName}: ${vertices.length.toString()} vertices, ${edges.length.toString()} edges`);
155
+ const { txHash } = await this.engine.pushCommit(publisher, commitCid);
156
+ return {
157
+ commitCid: commitCid.toString(),
158
+ txHash,
159
+ vertexCids: Object.fromEntries(idToCid)
160
+ };
161
+ }
162
+ /**
163
+ * Build a new commit locally (no on-chain tx) that stages vertices/edges into
164
+ * `namespace` on top of `parent` (a commit CID string, or undefined for a root
165
+ * commit). Blocks are flushed to storage so a later `push` — even in a separate
166
+ * process — can settle it.
167
+ */
168
+ async commit(opts) {
169
+ const parentCid = opts.parent ? CID.parse(opts.parent) : null;
170
+ const basePailRoot = parentCid ? (await this.engine.getCommit(parentCid)).pailRoot : null;
171
+ const batch = await this.engine.openBatch(basePailRoot);
172
+ if (!parentCid) await batch.put(`${opts.namespace}/sys/init`, "initialized");
173
+ const idToCid = await this.stageGraph(batch, opts.namespace, opts.vertices ?? [], opts.edges ?? []);
174
+ const { commitCid, pailRoot } = await this.engine.sealBatch(batch, parentCid ? [parentCid] : [], opts.message);
175
+ await this.engine.flush();
176
+ return {
177
+ commitCid: commitCid.toString(),
178
+ parents: parentCid ? [parentCid.toString()] : [],
179
+ pailRoot: pailRoot.toString(),
180
+ vertexCids: Object.fromEntries(idToCid)
181
+ };
182
+ }
183
+ /** Settle a local commit as the on-chain head (fast-forward unless `force`). */
184
+ async push(commitCid, opts) {
185
+ const { txHash, onChainTip } = await this.engine.pushCommit(this.getAddress(), CID.parse(commitCid), opts);
186
+ return {
187
+ txHash,
188
+ onChainTip: onChainTip.toString()
189
+ };
190
+ }
191
+ /** The owner's current on-chain tip commit CID, or null if they have no commits. */
192
+ async onChainTip(owner) {
193
+ const cid = await this.engine.resolveHeadCommit(owner);
194
+ return cid ? cid.toString() : null;
195
+ }
196
+ /** Walk commit history from `head` (newest first). */
197
+ async *log(head, max) {
198
+ for await (const { cid, commit } of this.engine.walkParents(CID.parse(head), max)) yield {
199
+ cid: cid.toString(),
200
+ parents: commit.parents.map((c) => c.toString()),
201
+ timestamp: commit.timestamp,
202
+ message: commit.message,
203
+ pailRoot: commit.pailRoot.toString()
204
+ };
205
+ }
206
+ /** Show a commit and what it changed vs. its first parent. */
207
+ async show(commitCid) {
208
+ return this.engine.diffCommit(CID.parse(commitCid));
209
+ }
210
+ /**
211
+ * Lists every vertex and edge currently committed under a namespace, resolved
212
+ * from the publisher's on-chain root — useful for verifying what actually
213
+ * made it into the repository, as opposed to what a given call staged.
214
+ */
215
+ async inspectNamespace(repoName) {
216
+ return this.engine.listNamespace(repoName, this.getAddress());
217
+ }
218
+ /**
219
+ * Stream namespace-scoped changes as the on-chain root advances. Optionally
220
+ * replays from `fromBlock` first (resume cursor), then watches live until the
221
+ * `signal` aborts. Each yielded change carries `blockNumber` — persist it to
222
+ * resume exactly where you left off.
223
+ */
224
+ async *subscribe(opts) {
225
+ const owner = opts.owner ?? this.getAddress();
226
+ const ns = opts.namespace;
227
+ const registry = this.getDataRegistry();
228
+ const seen = /* @__PURE__ */ new Set();
229
+ const buffer = [];
230
+ let wake = null;
231
+ let failure = null;
232
+ let stopped = false;
233
+ const signal = () => {
234
+ const w = wake;
235
+ wake = null;
236
+ w?.();
237
+ };
238
+ const unwatch = registry.watchStateCommitted(owner, (log) => {
239
+ buffer.push(log);
240
+ signal();
241
+ }, (err) => {
242
+ failure = err;
243
+ signal();
244
+ }, opts.pollingInterval);
245
+ const onAbort = () => {
246
+ stopped = true;
247
+ signal();
248
+ };
249
+ opts.signal?.addEventListener("abort", onAbort);
250
+ try {
251
+ if (opts.fromBlock !== void 0) for (const log of await registry.getStateCommittedLogs(owner, opts.fromBlock)) {
252
+ if (seen.has(log.logId)) continue;
253
+ seen.add(log.logId);
254
+ const change = await this.toNamespaceChange(log, ns, owner);
255
+ if (change) yield change;
256
+ }
257
+ while (!stopped) {
258
+ if (failure) throw failure;
259
+ if (buffer.length === 0) {
260
+ await new Promise((res) => {
261
+ wake = res;
262
+ });
263
+ continue;
264
+ }
265
+ const log = buffer.shift();
266
+ if (seen.has(log.logId)) continue;
267
+ seen.add(log.logId);
268
+ const change = await this.toNamespaceChange(log, ns, owner);
269
+ if (change) yield change;
270
+ }
271
+ } finally {
272
+ unwatch();
273
+ opts.signal?.removeEventListener("abort", onAbort);
274
+ }
275
+ }
276
+ /** Resolve a raw `StateCommitted` log into a namespace change, or null if the namespace slice was untouched. */
277
+ async toNamespaceChange(log, namespace, owner) {
278
+ const diff = await this.engine.namespaceDiff(log.oldRoot === ZERO_BYTES32 ? null : log.oldRoot, log.newRoot, namespace);
279
+ if (!(diff.addedVertices.length || diff.removedVertexCids.length || diff.addedEdges.length || diff.removedEdges.length)) return null;
280
+ return {
281
+ namespace,
282
+ owner,
283
+ commitCid: this.engine.commitCidFromRootHex(log.newRoot),
284
+ oldRoot: log.oldRoot,
285
+ newRoot: log.newRoot,
286
+ blockNumber: log.blockNumber,
287
+ ...diff
288
+ };
289
+ }
69
290
  getConfig() {
70
291
  return this.ctx.config;
71
292
  }
72
- getSchemaRegistry() {
73
- return this.ctx.schemaRegistry;
74
- }
75
- getDatasourceRegistry() {
76
- return this.ctx.dataSourceRegistry;
293
+ getDataRegistry() {
294
+ return this.ctx.dataRegistry;
77
295
  }
78
- getSettlementRegistry() {
79
- return this.ctx.settlementRegistry;
296
+ getStorage() {
297
+ if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } to Fangorn.create()");
298
+ return this.ctx.metadataStorage;
80
299
  }
81
300
  getWalletClient() {
82
301
  return this.ctx.walletClient;
@@ -0,0 +1,17 @@
1
+ import { buildAssetGraph, extractMarkdownLinks } from "../../index.js";
2
+
3
+ //#region src/harness/examples/hackmd/build-markdown-graph.ts
4
+ const buildMarkdownGraph = (dir) => {
5
+ return buildAssetGraph(dir, { processors: { ".md": (file) => ({
6
+ tag: "doc",
7
+ payload: { content: file.readText() },
8
+ links: extractMarkdownLinks(file.readText())
9
+ }) } });
10
+ };
11
+ if (import.meta.url === `file://${process.argv[1]}`) {
12
+ const dir = process.argv[2] ?? ".";
13
+ process.stdout.write(JSON.stringify(buildMarkdownGraph(dir), null, 2) + "\n");
14
+ }
15
+
16
+ //#endregion
17
+ export { };
@@ -0,0 +1,57 @@
1
+ import { Stats } from "fs";
2
+
3
+ //#region src/harness/index.d.ts
4
+ interface FileFacade {
5
+ /** The full filename including extension (e.g., "notes.md") */
6
+ name: string;
7
+ /** The filename without extension, used as the default ID (e.g., "notes") */
8
+ nameNoExt: string;
9
+ /** The file extension in lowercase, including the dot (e.g., ".md") */
10
+ ext: string;
11
+ /** The absolute or relative path to the file */
12
+ path: string;
13
+ /** Reads the file and returns its content as a UTF-8 string */
14
+ readText: () => string;
15
+ /** Reads the file and returns its raw Buffer data */
16
+ readBuffer: () => Buffer;
17
+ /** Retrieves file system metadata stats for the file */
18
+ stat: () => Stats;
19
+ }
20
+ interface ProcessorResult {
21
+ /** The entity type/tag for the graph vertex (defaults to "asset") */
22
+ tag?: string;
23
+ /** Custom metadata object attached to the vertex */
24
+ payload?: Record<string, any>;
25
+ /** An array of target vertex IDs that this file links to */
26
+ links?: string[];
27
+ }
28
+ type AssetProcessor = (file: FileFacade) => ProcessorResult;
29
+ interface BuildAssetGraphOptions {
30
+ /** A dictionary mapping lowercase file extensions (e.g., ".md") to processor functions */
31
+ processors?: Record<string, AssetProcessor>;
32
+ }
33
+ interface Vertex {
34
+ id: string;
35
+ tag: string;
36
+ payload: Record<string, any>;
37
+ }
38
+ interface Edge {
39
+ rel: string;
40
+ from: string;
41
+ to: string;
42
+ }
43
+ interface CommitFileGraph {
44
+ vertices: Vertex[];
45
+ edges: Edge[];
46
+ }
47
+ /**
48
+ * Traverses a directory, parses files based on their extensions,
49
+ * and generates a strictly validated Fangorn-compliant commit graph.
50
+ */
51
+ declare function buildAssetGraph(dir: string, options?: BuildAssetGraphOptions): CommitFileGraph;
52
+ /**
53
+ * Utility helper to scan markdown strings for standard markdown links or wikilinks.
54
+ */
55
+ declare function extractMarkdownLinks(content: string): string[];
56
+ //#endregion
57
+ export { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, extractMarkdownLinks };
@@ -0,0 +1,67 @@
1
+ import { readFileSync, readdirSync, statSync } from "fs";
2
+ import { basename, extname, join } from "path";
3
+
4
+ //#region src/harness/index.ts
5
+ /**
6
+ * Traverses a directory, parses files based on their extensions,
7
+ * and generates a strictly validated Fangorn-compliant commit graph.
8
+ */
9
+ function buildAssetGraph(dir, options = {}) {
10
+ const { processors = {} } = options;
11
+ const rawFiles = readdirSync(dir);
12
+ const getId = (f) => basename(f, extname(f));
13
+ const validIds = new Set(rawFiles.map(getId));
14
+ const vertices = [];
15
+ const edges = /* @__PURE__ */ new Set();
16
+ for (const f of rawFiles) {
17
+ const ext = extname(f).toLowerCase();
18
+ const processor = processors[ext];
19
+ if (!processor) continue;
20
+ const fromId = getId(f);
21
+ const fullPath = join(dir, f);
22
+ const fileFacade = {
23
+ name: f,
24
+ nameNoExt: fromId,
25
+ ext,
26
+ path: fullPath,
27
+ readText: () => readFileSync(fullPath, "utf-8"),
28
+ readBuffer: () => readFileSync(fullPath),
29
+ stat: () => statSync(fullPath)
30
+ };
31
+ try {
32
+ const { tag = "asset", payload = {}, links = [] } = processor(fileFacade);
33
+ vertices.push({
34
+ id: fromId,
35
+ tag,
36
+ payload
37
+ });
38
+ for (const toId of links) if (toId && fromId !== toId && validIds.has(toId)) edges.add(JSON.stringify({
39
+ rel: "links",
40
+ from: fromId,
41
+ to: toId
42
+ }));
43
+ } catch (err) {
44
+ console.error(`Fangorn Error processing file ${f}:`, err);
45
+ }
46
+ }
47
+ return {
48
+ vertices,
49
+ edges: Array.from(edges).map((e) => JSON.parse(e))
50
+ };
51
+ }
52
+ /**
53
+ * Utility helper to scan markdown strings for standard markdown links or wikilinks.
54
+ */
55
+ function extractMarkdownLinks(content) {
56
+ const LINK_REGEX = /\]\(([^)\s]+?\.md)(?:#[^)]*)?\)|\[\[([^\]|#]+?)(?:[|#][^\]]*)?\]\]/g;
57
+ const links = [];
58
+ const convertToId = (str) => basename(str, extname(str));
59
+ for (const match of content.matchAll(LINK_REGEX)) {
60
+ const rawTarget = match[1] ?? match[2];
61
+ if (rawTarget) links.push(convertToId(rawTarget));
62
+ }
63
+ return links;
64
+ }
65
+
66
+ //#endregion
67
+ export { buildAssetGraph, extractMarkdownLinks };
package/lib/index.d.ts CHANGED
@@ -1,8 +1,6 @@
1
1
  import { AppConfig, FangornConfig, SupportedNetworks } from "./config.js";
2
- import { Fangorn } from "./fangorn.js";
3
2
  import { PinataBackend } from "./providers/storage/pinata.js";
4
3
  import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
5
- import { SETTLEMENT_REGISTRY_ABI } from "./registries/settlement-registry/abi.js";
6
- import { DS_REGISTRY_ABI } from "./registries/datasource-registry/abi.js";
4
+ import { Fangorn, NamespaceChange, SubscribeOptions } from "./fangorn.js";
7
5
  import { addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
8
- export { AppConfig, DS_REGISTRY_ABI, Fangorn, FangornConfig, PinataBackend, SETTLEMENT_REGISTRY_ABI, SupportedNetworks, addressToBytes32Array, computeSchemaId, deserialize, fieldToHex, hexToBytes32Array, hexToField, retrieveByCid, serialize, stringToBytes32Array };
6
+ export { AppConfig, Fangorn, FangornConfig, NamespaceChange, PinataBackend, SubscribeOptions, SupportedNetworks, addressToBytes32Array, computeSchemaId, deserialize, fieldToHex, hexToBytes32Array, hexToField, retrieveByCid, serialize, stringToBytes32Array };
package/lib/index.js CHANGED
@@ -1,9 +1,7 @@
1
1
  import { FangornConfig, SupportedNetworks } from "./config.js";
2
- import { DS_REGISTRY_ABI } from "./registries/datasource-registry/abi.js";
3
2
  import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
4
3
  import { PinataBackend } from "./providers/storage/pinata.js";
5
- import { SETTLEMENT_REGISTRY_ABI } from "./registries/settlement-registry/abi.js";
6
4
  import { Fangorn } from "./fangorn.js";
7
5
  import { addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
8
6
 
9
- export { DS_REGISTRY_ABI, Fangorn, FangornConfig, PinataBackend, SETTLEMENT_REGISTRY_ABI, SupportedNetworks, addressToBytes32Array, computeSchemaId, deserialize, fieldToHex, hexToBytes32Array, hexToField, retrieveByCid, serialize, stringToBytes32Array };
7
+ export { Fangorn, FangornConfig, PinataBackend, SupportedNetworks, addressToBytes32Array, computeSchemaId, deserialize, fieldToHex, hexToBytes32Array, hexToField, retrieveByCid, serialize, stringToBytes32Array };