@fangorn-network/sdk 2026.6.16 → 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 (105) hide show
  1. package/README.md +210 -266
  2. package/lib/cli/cli.d.ts +0 -0
  3. package/lib/cli/cli.js +261 -167
  4. package/lib/cli/index.d.ts +13 -651
  5. package/lib/config.d.ts +137 -792
  6. package/lib/config.js +6 -22
  7. package/lib/contracts/data-registry/abi.d.ts +38 -0
  8. package/lib/contracts/data-registry/abi.js +237 -0
  9. package/lib/contracts/data-registry/index.d.ts +81 -0
  10. package/lib/contracts/data-registry/index.js +184 -0
  11. package/lib/contracts/index.d.ts +3 -0
  12. package/lib/contracts/index.js +4 -0
  13. package/lib/crypto/aes.d.ts +26 -0
  14. package/lib/crypto/aes.js +58 -0
  15. package/lib/crypto/encryption.d.ts +53 -0
  16. package/lib/crypto/encryption.js +82 -0
  17. package/lib/{modules/encryption → crypto}/rand.d.ts +1 -1
  18. package/lib/{modules/encryption → crypto}/rand.js +1 -1
  19. package/lib/{modules/encryption → crypto}/types.d.ts +1 -1
  20. package/lib/engine/blockstore.d.ts +24 -0
  21. package/lib/engine/blockstore.js +85 -0
  22. package/lib/engine/index.d.ts +180 -0
  23. package/lib/engine/index.js +367 -0
  24. package/lib/fangorn.d.ts +149 -16
  25. package/lib/fangorn.js +256 -37
  26. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  27. package/lib/harness/index.d.ts +57 -0
  28. package/lib/harness/index.js +67 -0
  29. package/lib/index.d.ts +2 -2
  30. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js +218 -0
  31. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js +261 -0
  32. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js +156 -0
  33. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js +299 -0
  34. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js +532 -0
  35. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js +344 -0
  36. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js +137 -0
  37. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js +262 -0
  38. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/utils.js +150 -0
  39. package/lib/providers/storage/car.d.ts +36 -0
  40. package/lib/providers/storage/car.js +80 -0
  41. package/lib/providers/storage/pinata.d.ts +29 -1
  42. package/lib/providers/storage/pinata.js +135 -20
  43. package/lib/providers/storage/types.d.ts +25 -18
  44. package/lib/roles/repo/index.d.ts +56 -0
  45. package/lib/roles/repo/index.js +73 -0
  46. package/lib/test/car_smoke.d.ts +1 -0
  47. package/lib/test/car_smoke.js +81 -0
  48. package/lib/test/cleanup-embeddings-testdata.js +9 -38
  49. package/lib/test/setup-embeddings-testdata.d.ts +4 -6
  50. package/lib/test/setup-embeddings-testdata.js +40 -94
  51. package/lib/test/testbed.d.ts +35 -32
  52. package/lib/test/testbed.js +48 -138
  53. package/lib/types/index.d.ts +3 -19
  54. package/lib/utils/manifest.d.ts +23 -0
  55. package/lib/utils/manifest.js +77 -0
  56. package/package.json +99 -81
  57. package/lib/modules/encryption/actions.d.ts +0 -4
  58. package/lib/modules/encryption/actions.js +0 -18
  59. package/lib/modules/encryption/aes.d.ts +0 -10
  60. package/lib/modules/encryption/aes.js +0 -51
  61. package/lib/registries/datasource-registry/abi.d.ts +0 -186
  62. package/lib/registries/datasource-registry/abi.js +0 -229
  63. package/lib/registries/datasource-registry/index.d.ts +0 -39
  64. package/lib/registries/datasource-registry/index.js +0 -158
  65. package/lib/registries/index.d.ts +0 -3
  66. package/lib/registries/index.js +0 -4
  67. package/lib/registries/schema-registry/abi.d.ts +0 -218
  68. package/lib/registries/schema-registry/abi.js +0 -246
  69. package/lib/registries/schema-registry/index.d.ts +0 -34
  70. package/lib/registries/schema-registry/index.js +0 -179
  71. package/lib/registries/settlement-registry/abi.d.ts +0 -218
  72. package/lib/registries/settlement-registry/abi.js +0 -259
  73. package/lib/registries/settlement-registry/index.d.ts +0 -63
  74. package/lib/registries/settlement-registry/index.js +0 -325
  75. package/lib/registries/settlement-registry/types.d.ts +0 -54
  76. package/lib/registries/settlement-registry/types.js +0 -1
  77. package/lib/roles/consumer/index.d.ts +0 -39
  78. package/lib/roles/consumer/index.js +0 -150
  79. package/lib/roles/consumer/types.d.ts +0 -47
  80. package/lib/roles/consumer/types.js +0 -1
  81. package/lib/roles/publisher/builders/bundle.d.ts +0 -32
  82. package/lib/roles/publisher/builders/bundle.js +0 -137
  83. package/lib/roles/publisher/builders/record-set.d.ts +0 -17
  84. package/lib/roles/publisher/builders/record-set.js +0 -55
  85. package/lib/roles/publisher/builders/types.d.ts +0 -38
  86. package/lib/roles/publisher/builders/types.js +0 -1
  87. package/lib/roles/publisher/builders/utils.d.ts +0 -9
  88. package/lib/roles/publisher/builders/utils.js +0 -29
  89. package/lib/roles/publisher/encryption.d.ts +0 -18
  90. package/lib/roles/publisher/encryption.js +0 -38
  91. package/lib/roles/publisher/index.d.ts +0 -68
  92. package/lib/roles/publisher/index.js +0 -179
  93. package/lib/roles/publisher/types.d.ts +0 -114
  94. package/lib/roles/publisher/types.js +0 -1
  95. package/lib/roles/schema/index.d.ts +0 -44
  96. package/lib/roles/schema/index.js +0 -127
  97. package/lib/roles/schema/types.d.ts +0 -113
  98. package/lib/roles/schema/types.js +0 -1
  99. package/lib/roles/schema/validate.d.ts +0 -9
  100. package/lib/roles/schema/validate.js +0 -128
  101. package/lib/test/publish_mb_bundle.js +0 -296
  102. /package/lib/{modules/encryption/index.d.ts → contracts/data-registry/test.d.ts} +0 -0
  103. /package/lib/{modules/encryption/index.js → contracts/data-registry/test.js} +0 -0
  104. /package/lib/{modules/encryption → crypto}/types.js +0 -0
  105. /package/lib/{test/publish_mb_bundle.d.ts → harness/examples/hackmd/build-markdown-graph.d.ts} +0 -0
package/lib/cli/cli.js CHANGED
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { FangornConfig, SupportedNetworks } from "../config.js";
2
+ import { FangornConfig } from "../config.js";
3
3
  import { Fangorn } from "../fangorn.js";
4
- import { handleCancel, selectChain } from "./index.js";
4
+ import { handleCancel } from "./index.js";
5
5
  import { privateKeyToAccount } from "viem/accounts";
6
6
  import { Command } from "commander";
7
- import { confirm, intro, log, note, outro, select, spinner, text } from "@clack/prompts";
8
- import { chmodSync, closeSync, createReadStream, existsSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync } from "fs";
9
- import streamArray from "stream-json/streamers/stream-array.js";
10
- import { extname, join } from "path";
7
+ import { confirm, intro, outro, spinner, text } from "@clack/prompts";
8
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
9
+ import { join } from "path";
11
10
  import { homedir } from "os";
12
11
  import "dotenv/config";
13
12
 
@@ -17,45 +16,39 @@ const CONFIG_PATH = join(CONFIG_DIR, "config.json");
17
16
  let _config = null;
18
17
  let _account = null;
19
18
  let _fangorn = null;
20
- function resolveAppConfig(chainName) {
21
- if (chainName === SupportedNetworks.ArbitrumSepolia.name) return FangornConfig.ArbitrumSepolia;
22
- return FangornConfig.BaseSepolia;
23
- }
24
19
  function loadConfig() {
25
20
  if (_config) return _config;
26
- const privateKey = process.env.DELEGATOR_ETH_PRIVATE_KEY;
21
+ const privateKey = process.env.ETH_PRIVATE_KEY;
27
22
  const pinataJwt = process.env.PINATA_JWT;
28
23
  const pinataGateway = process.env.PINATA_GATEWAY;
29
- const chainName = process.env.CHAIN_NAME;
30
24
  const workerUrl = process.env.WORKER_URL;
31
- if (privateKey || pinataJwt || pinataGateway || chainName) {
25
+ if (existsSync(CONFIG_PATH)) {
26
+ const stored = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
27
+ _config = {
28
+ privateKey: stored.privateKey,
29
+ cfg: FangornConfig,
30
+ pinataJwt: stored.pinataJwt,
31
+ pinataGateway: stored.pinataGateway,
32
+ workerUrl: stored.workerUrl
33
+ };
34
+ return _config;
35
+ }
36
+ {
32
37
  const missing = [];
33
- if (!privateKey) missing.push("DELEGATOR_ETH_PRIVATE_KEY");
38
+ if (!privateKey) missing.push("ETH_PRIVATE_KEY");
34
39
  if (!pinataJwt) missing.push("PINATA_JWT");
35
40
  if (!pinataGateway) missing.push("PINATA_GATEWAY");
36
- if (!chainName) missing.push("CHAIN_NAME");
37
41
  if (missing.length > 0) throw new Error(`Incomplete environment configuration. Missing: ${missing.join(", ")}\nSet all required env vars or run \`fangorn init\` to use a config file.`);
38
42
  _config = {
39
43
  privateKey,
40
- cfg: resolveAppConfig(chainName ?? ""),
44
+ cfg: FangornConfig,
41
45
  pinataJwt: pinataJwt ?? "",
42
46
  pinataGateway: pinataGateway ?? "",
43
47
  workerUrl: workerUrl ?? ""
44
48
  };
45
49
  return _config;
46
50
  }
47
- if (existsSync(CONFIG_PATH)) {
48
- const stored = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
49
- _config = {
50
- privateKey: stored.privateKey,
51
- cfg: resolveAppConfig(stored.chainName),
52
- pinataJwt: stored.pinataJwt,
53
- pinataGateway: stored.pinataGateway,
54
- workerUrl: stored.workerUrl
55
- };
56
- return _config;
57
- }
58
- throw new Error("No configuration found. Run `fangorn init` or set the required env vars:\n DELEGATOR_ETH_PRIVATE_KEY, PINATA_JWT, PINATA_GATEWAY, CHAIN_NAME");
51
+ throw new Error("No configuration found. Run `fangorn init` or set the required env vars:\n ETH_PRIVATE_KEY, PINATA_JWT, PINATA_GATEWAY, CHAIN_NAME");
59
52
  }
60
53
  function getAccount() {
61
54
  if (_account) return _account;
@@ -65,11 +58,6 @@ function getAccount() {
65
58
  function getFangorn() {
66
59
  if (_fangorn) return _fangorn;
67
60
  const cfg = loadConfig();
68
- console.log(JSON.stringify(cfg));
69
- const agentConfig = {
70
- privateKey: cfg.privateKey,
71
- pinataJwt: cfg.pinataJwt
72
- };
73
61
  _fangorn = Fangorn.create({
74
62
  privateKey: cfg.privateKey,
75
63
  storage: { pinata: {
@@ -77,21 +65,58 @@ function getFangorn() {
77
65
  gateway: cfg.pinataGateway
78
66
  } },
79
67
  domain: "localhost",
80
- config: cfg.cfg,
81
- agentConfig
68
+ config: cfg.cfg
82
69
  });
83
70
  return _fangorn;
84
71
  }
85
- async function resolveSchemaId(fangorn, schemaNameOrId) {
86
- try {
87
- return await fangorn.getSchemaRegistry().schemaId(/^0x[0-9a-fA-F]{64}$/.test(schemaNameOrId) ? schemaNameOrId : schemaNameOrId);
88
- } catch {
89
- throw new Error(`Schema "${schemaNameOrId}" not found on-chain. Register it with \`fangorn schema register\`.`);
72
+ var LocalRepo = class LocalRepo {
73
+ constructor(dir, state) {
74
+ this.dir = dir;
75
+ this.state = state;
90
76
  }
91
- }
92
- const program$1 = new Command();
93
- program$1.name("fangorn").description("Fangorn Network CLI").version("0.2.1");
94
- program$1.command("init").description("Configure your Fangorn credentials").action(async () => {
77
+ static path(dir) {
78
+ return join(dir, ".fangorn", "repo.json");
79
+ }
80
+ /** Create (or overwrite) a repo pointer in `dir`. */
81
+ static init(state, dir = process.cwd()) {
82
+ const repoDir = join(dir, ".fangorn");
83
+ if (!existsSync(repoDir)) mkdirSync(repoDir, { recursive: true });
84
+ const repo = new LocalRepo(dir, state);
85
+ repo.save();
86
+ return repo;
87
+ }
88
+ /** Open the repo containing `dir` (searches upward like git). Throws if none. */
89
+ static open(dir = process.cwd()) {
90
+ let cur = dir;
91
+ while (true) {
92
+ const p = LocalRepo.path(cur);
93
+ if (existsSync(p)) return new LocalRepo(cur, JSON.parse(readFileSync(p, "utf-8")));
94
+ const parent = join(cur, "..");
95
+ if (parent === cur) break;
96
+ cur = parent;
97
+ }
98
+ throw new Error("not a fangorn repo (no .fangorn/repo.json here or above). Run `fangorn repo init <namespace>` or `fangorn clone`.");
99
+ }
100
+ save() {
101
+ writeFileSync(LocalRepo.path(this.dir), JSON.stringify(this.state, null, 2), "utf-8");
102
+ }
103
+ namespace() {
104
+ return this.state.namespace;
105
+ }
106
+ owner() {
107
+ return this.state.owner;
108
+ }
109
+ head() {
110
+ return this.state.head;
111
+ }
112
+ setHead(cid) {
113
+ this.state.head = cid;
114
+ this.save();
115
+ }
116
+ };
117
+ const program = new Command();
118
+ program.name("fangorn").description("Fangorn Network CLI").version("0.4.0");
119
+ program.command("init").description("Configure your Fangorn credentials").action(async () => {
95
120
  intro("Fangorn Setup");
96
121
  const privateKey = await text({
97
122
  message: "Wallet private key (stored locally, never transmitted):",
@@ -102,17 +127,6 @@ program$1.command("init").description("Configure your Fangorn credentials").acti
102
127
  }
103
128
  });
104
129
  handleCancel(privateKey);
105
- const chainName = await select({
106
- message: "Default chain:",
107
- options: [{
108
- value: SupportedNetworks.ArbitrumSepolia.name,
109
- label: "Arbitrum Sepolia"
110
- }, {
111
- value: SupportedNetworks.BaseSepolia.name,
112
- label: "Base Sepolia"
113
- }]
114
- });
115
- handleCancel(chainName);
116
130
  const pinataJwt = await text({
117
131
  message: "Pinata JWT:",
118
132
  validate: (v) => {
@@ -138,7 +152,7 @@ program$1.command("init").description("Configure your Fangorn credentials").acti
138
152
  handleCancel(workerUrl);
139
153
  const stored = {
140
154
  privateKey,
141
- chainName,
155
+ chainName: "Arbitrum Sepolia",
142
156
  pinataJwt,
143
157
  pinataGateway,
144
158
  workerUrl
@@ -148,185 +162,265 @@ program$1.command("init").description("Configure your Fangorn credentials").acti
148
162
  chmodSync(CONFIG_PATH, 384);
149
163
  outro(`Config saved to ${CONFIG_PATH}`);
150
164
  });
151
- const schemaCmd = program$1.command("schema").description("Schema registry operations");
152
- schemaCmd.command("register").description("Register a schema on-chain").argument("<name>", "Schema name").action(async (name) => {
165
+ program.command("register").description("Register your wallet as a data publisher on-chain").action(async () => {
153
166
  try {
154
- intro("Chain selection");
155
- outro(`Selected chain: ${(await selectChain()).name}`);
156
- const fangorn = getFangorn();
157
- intro("Schema Registration");
158
- const schemaFilePath = await text({
159
- message: "Path to your JSON schema file:",
160
- placeholder: "./schema.json",
161
- validate: (v) => {
162
- if (!v) return "Required";
163
- if (!existsSync(v)) return `File not found: ${v}`;
164
- if (extname(v).toLowerCase() !== ".json") return "Must be a .json file";
165
- }
166
- });
167
- handleCancel(schemaFilePath);
168
- let definition;
169
- try {
170
- definition = JSON.parse(readFileSync(schemaFilePath, "utf-8"));
171
- } catch {
172
- throw new Error(`Failed to parse ${schemaFilePath} as JSON`);
173
- }
174
- note(JSON.stringify(definition, null, 2), "Schema definition:");
175
- const ok = await confirm({ message: "Register this schema?" });
176
- handleCancel(ok);
177
- if (!ok) {
178
- outro("Cancelled.");
167
+ const self = getAccount().address;
168
+ const registry = getFangorn().getDataRegistry();
169
+ const s = spinner();
170
+ if (await registry.isRegistered(self)) {
171
+ console.log(`Already registered: ${self}`);
179
172
  process.exit(0);
180
173
  }
181
- const s = spinner();
182
- s.start("Registering schema...");
183
- const { schemaId, schemaCid } = await fangorn.schema.register({
184
- name,
185
- definition
186
- });
174
+ s.start("Registering publisher...");
175
+ const txHash = await registry.register();
187
176
  s.stop();
188
- note(`Schema ID: ${schemaId}\nCID: ${schemaCid}`, "Schema registered");
177
+ console.log(`Publisher: ${self}`);
178
+ console.log(`Tx: ${txHash}`);
189
179
  process.exit(0);
190
180
  } catch (err) {
191
181
  console.error("Failed:", err.message);
192
182
  process.exit(1);
193
183
  }
194
184
  });
195
- schemaCmd.command("get").description("Fetch a registered schema by name").argument("<name>", "Schema name").action(async (name) => {
185
+ program.command("repo").description("Repository operations").command("init").description("Start tracking a namespace here (allocates it on-chain if new)").argument("<namespace>", "Namespace name").action(async (namespace) => {
196
186
  try {
197
187
  const fangorn = getFangorn();
188
+ const owner = fangorn.getAddress();
198
189
  const s = spinner();
199
- s.start(`Fetching schema "${name}"...`);
200
- const schema = await fangorn.schema.get(name);
190
+ s.start(`Initializing namespace "${namespace}"...`);
191
+ const result = await fangorn.initRepo(namespace);
192
+ const head = result.alreadyInitialized ? await fangorn.onChainTip(owner) : result.commitCid ?? null;
193
+ const repo = LocalRepo.init({
194
+ namespace,
195
+ owner,
196
+ head
197
+ });
201
198
  s.stop();
202
- if (!schema) {
203
- log.error(`Schema "${name}" not found.`);
204
- process.exit(1);
199
+ if (result.alreadyInitialized) console.log(`Namespace "${namespace}" already exists for ${owner}. Tracking it here.`);
200
+ else {
201
+ console.log(`Namespace: ${namespace}`);
202
+ console.log(`Owner: ${owner}`);
203
+ console.log(`Tx: ${result.txHash}`);
205
204
  }
206
- note(JSON.stringify(schema, null, 2), `Schema: ${name}`);
205
+ console.log(`HEAD: ${repo.head() ?? "(none)"}`);
207
206
  process.exit(0);
208
207
  } catch (err) {
209
208
  console.error("Failed:", err.message);
210
209
  process.exit(1);
211
210
  }
212
211
  });
213
- /**
214
- * Cheaply read the first non-whitespace byte of a file without loading it.
215
- * Used to decide between streaming an array ("[") and reading a single object.
216
- */
217
- function peekFirstNonWsByte(filepath) {
218
- const fd = openSync(filepath, "r");
219
- try {
220
- const buf = Buffer.alloc(64);
221
- let offset = 0;
222
- for (;;) {
223
- const bytesRead = readSync(fd, buf, 0, buf.length, offset);
224
- if (bytesRead === 0) return void 0;
225
- for (let i = 0; i < bytesRead; i++) {
226
- const b = buf[i];
227
- if (b !== 32 && b !== 9 && b !== 10 && b !== 13) return b;
228
- }
229
- offset += bytesRead;
230
- }
231
- } finally {
232
- closeSync(fd);
233
- }
234
- }
235
- const publishCmd = program$1.command("publish").description("Publisher operations");
236
- publishCmd.command("upload").description("Publish file handle(s) under a schema").argument("<files...>", "JSON file(s) containing PublishRecord(s)").requiredOption("-s, --schema <schemaName>", "Schema name or bytes32 ID").requiredOption("-d, --dataset <datasetName>", "Dataset name (groups entries under a manifest)").option("--chunk-size <n>", "Records per chunk (default 1000)", (v) => parseInt(v, 10)).option("--concurrency <n>", "Parallel chunk uploads (default 10)", (v) => parseInt(v, 10)).action(async (files, 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").action(async (file, options) => {
237
213
  try {
214
+ if (!existsSync(file)) throw new Error(`file not found: ${file}`);
215
+ const data = JSON.parse(readFileSync(file, "utf-8"));
216
+ if (!Array.isArray(data.vertices) || data.vertices.length === 0) throw new Error(`${file} must contain a non-empty "vertices" array`);
217
+ const repo = LocalRepo.open();
238
218
  const fangorn = getFangorn();
219
+ const parent = repo.head() ?? void 0;
239
220
  const s = spinner();
240
- let published = 0;
241
- async function* streamRecords() {
242
- for (const filepath of files) if (peekFirstNonWsByte(filepath) === 91) {
243
- const pipeline = createReadStream(filepath).pipe(streamArray.withParserAsStream());
244
- for await (const { value } of pipeline) {
245
- yield value;
246
- if (++published % 1e4 === 0) s.message(`Publishing... ${published.toLocaleString()} records read`);
247
- }
248
- } else {
249
- yield JSON.parse(readFileSync(filepath, "utf-8"));
250
- published++;
251
- }
252
- }
253
- s.start("Publishing...");
254
- const result = await fangorn.publisher.publishRecords({
255
- records: streamRecords(),
256
- schemaName: options.schema,
257
- datasetName: options.dataset,
258
- chunkSize: options.chunkSize,
259
- concurrency: options.concurrency
221
+ s.start(parent ? "Committing (building on local HEAD)..." : "Committing (initial)...");
222
+ const result = await fangorn.commit({
223
+ namespace: repo.namespace(),
224
+ vertices: data.vertices,
225
+ edges: data.edges ?? [],
226
+ parent,
227
+ message: options.message
260
228
  });
261
229
  s.stop();
262
- note(`Manifest URI: ${result.manifestUri}\nEntries: ${result.entryCount.toString()}\nSchema: ${result.schemaId}`, "Upload complete");
230
+ repo.setHead(result.commitCid);
231
+ console.log(`Commit: ${result.commitCid}`);
232
+ console.log(`Parent: ${result.parents[0] ?? "(root)"}`);
233
+ console.log(`Tree: ${result.pailRoot}`);
234
+ console.log(`Staged: ${data.vertices.length.toString()} vertice(s) / ${(data.edges ?? []).length.toString()} edge(s)`);
235
+ console.log(`Message: ${options.message}`);
236
+ console.log(`\nCommitted locally. Run \`fangorn push\` to settle it on-chain.`);
263
237
  process.exit(0);
264
238
  } catch (err) {
265
239
  console.error("Failed:", err.message);
266
240
  process.exit(1);
267
241
  }
268
242
  });
269
- publishCmd.command("entry").description("Show details for one of your manifest entries").argument("<tag>", "Entry tag / name").requiredOption("-s, --schema <schemaName>", "Schema name").requiredOption("-d, --dataset <datasetName>", "Dataset name").action(async (tag, options) => {
243
+ program.command("push").description("Settle the local tip commit as the on-chain state root (the permissioned step)").option("--force", "Push even if it does not fast-forward the on-chain tip").action(async (options) => {
270
244
  try {
245
+ const head = LocalRepo.open().head();
246
+ if (!head) throw new Error("nothing to push — no commits yet");
271
247
  const fangorn = getFangorn();
272
248
  const s = spinner();
273
- s.start(`Fetching entry "${tag}"...`);
274
- const entry = await fangorn.publisher.getEntry(options.schema, options.dataset, tag);
249
+ s.start("Pushing...");
250
+ const { txHash, onChainTip } = await fangorn.push(head, { force: options.force });
275
251
  s.stop();
276
- note(JSON.stringify(entry, null, 2), `Entry: ${tag}`);
252
+ console.log(`Tx: ${txHash}`);
253
+ console.log(`Tip: ${onChainTip}`);
277
254
  process.exit(0);
278
255
  } catch (err) {
279
256
  console.error("Failed:", err.message);
280
257
  process.exit(1);
281
258
  }
282
259
  });
283
- const consumeCmd = program$1.command("consume").description("Consumer operations");
284
- consumeCmd.command("list").description("List a publisher's manifest entries").requiredOption("-s, --schema <schemaName>", "Schema name or bytes32 ID").requiredOption("--owner <address>", "Publisher address").action(async (options) => {
260
+ program.command("status").description("Compare the local tip with the on-chain tip").action(async () => {
285
261
  try {
262
+ const repo = LocalRepo.open();
286
263
  const fangorn = getFangorn();
287
- const schemaId = await resolveSchemaId(fangorn, options.schema);
288
- if (!await fangorn.consumer.getEntry(options.owner, schemaId, options.schema)) {
289
- log.warn("No manifest found.");
264
+ const localHead = repo.head();
265
+ const onChainTip = await fangorn.onChainTip(repo.owner());
266
+ const state = localHead === onChainTip ? "up to date" : localHead && !onChainTip ? "local commits not yet pushed" : localHead !== onChainTip ? "local tip differs from on-chain tip (push to fast-forward)" : "no local commits";
267
+ console.log(`Namespace: ${repo.namespace()}`);
268
+ console.log(`Owner: ${repo.owner()}`);
269
+ console.log(`Local HEAD: ${localHead ?? "(none)"}`);
270
+ console.log(`On-chain tip: ${onChainTip ?? "(none)"}`);
271
+ console.log(`Status: ${state}`);
272
+ process.exit(0);
273
+ } catch (err) {
274
+ console.error("Failed:", err.message);
275
+ process.exit(1);
276
+ }
277
+ });
278
+ program.command("log").description("Walk commit history from the local tip").option("-n, --max <n>", "Limit number of commits", (v) => parseInt(v, 10)).action(async (options) => {
279
+ try {
280
+ const head = LocalRepo.open().head();
281
+ if (!head) {
282
+ console.log("(no commits yet)");
290
283
  process.exit(0);
291
284
  }
292
- console.log(`Owner: ${options.owner}`);
293
- console.log(`Schema: ${options.schema}`);
285
+ const fangorn = getFangorn();
286
+ for await (const c of fangorn.log(head, options.max)) {
287
+ console.log(`commit ${c.cid}`);
288
+ console.log(`Date: ${new Date(c.timestamp).toISOString()}`);
289
+ console.log(`Tree: ${c.pailRoot}`);
290
+ console.log(`\n ${c.message}\n`);
291
+ }
294
292
  process.exit(0);
295
293
  } catch (err) {
296
294
  console.error("Failed:", err.message);
297
295
  process.exit(1);
298
296
  }
299
297
  });
300
- consumeCmd.command("entry").description("Show a publisher's manifest entry").argument("<tag>", "Entry tag / name").requiredOption("-s, --schema <schemaName>", "Schema name or bytes32 ID").requiredOption("--owner <address>", "Publisher address").action(async (tag, options) => {
298
+ program.command("show").description("Show a commit and what it changed vs. its parent").argument("[commit]", "Commit CID (default: local HEAD)").action(async (commitArg) => {
299
+ try {
300
+ const repo = LocalRepo.open();
301
+ const target = commitArg ?? repo.head();
302
+ if (!target) throw new Error("no commit to show — no commits yet");
303
+ const diff = await getFangorn().show(target);
304
+ console.log(`commit ${target}`);
305
+ console.log(`Date: ${new Date(diff.timestamp).toISOString()}`);
306
+ console.log(`Parents: ${diff.parents.length ? diff.parents.join(", ") : "(root)"}`);
307
+ console.log(`Tree: ${diff.pailRoot}`);
308
+ console.log(`\n ${diff.message}\n`);
309
+ console.log(`Changes vs. parent: +${diff.added.length.toString()} / -${diff.removed.length.toString()} key(s)`);
310
+ for (const k of diff.added) console.log(` + ${k}`);
311
+ for (const k of diff.removed) console.log(` - ${k}`);
312
+ process.exit(0);
313
+ } catch (err) {
314
+ console.error("Failed:", err.message);
315
+ process.exit(1);
316
+ }
317
+ });
318
+ program.command("clone").description("Track an existing on-chain namespace by reconstructing its tip locally").argument("<owner>", "Owner (publisher) address").argument("<namespace>", "Namespace name").option("--dir <path>", "Directory to create the repo in (default: current dir)").action(async (owner, namespace, options) => {
301
319
  try {
302
320
  const fangorn = getFangorn();
303
- const schemaId = await resolveSchemaId(fangorn, options.schema);
304
- const entry = await fangorn.consumer.getEntry(options.owner, schemaId, tag);
305
- note(JSON.stringify(entry, null, 2), `Entry: ${tag}`);
321
+ const s = spinner();
322
+ s.start(`Resolving on-chain tip for ${owner}...`);
323
+ const tip = await fangorn.onChainTip(owner);
324
+ const repo = LocalRepo.init({
325
+ namespace,
326
+ owner,
327
+ head: tip
328
+ }, options.dir ?? process.cwd());
329
+ s.stop();
330
+ console.log(`Namespace: ${namespace}`);
331
+ console.log(`Owner: ${owner}`);
332
+ console.log(`HEAD: ${repo.head() ?? "(none — publisher has no commits yet)"}`);
306
333
  process.exit(0);
307
334
  } catch (err) {
308
335
  console.error("Failed:", err.message);
309
336
  process.exit(1);
310
337
  }
311
338
  });
312
- program$1.command("datasource").description("Data source registry queries").command("info").description("Show on-chain manifest info for an owner + schema").requiredOption("-s, --schema <schemaName>", "Schema name or bytes32 ID").option("--owner <address>", "Owner address (defaults to your wallet)").action(async (options) => {
339
+ program.command("subscribe").description("Watch on-chain pushes to a namespace and stream JSON diffs (light client — no indexer)").argument("[namespace]", "Namespace name (default: current repo)").option("--owner <address>", "Owner (publisher) address (default: current repo owner, else self)").option("--from-block <n>", "Replay from this block (overrides the saved cursor)", (v) => BigInt(v)).option("--from-start", "Replay this namespace's full history (ignore the saved cursor)").option("--pretty", "Pretty-print each change").action(async (namespaceArg, options) => {
340
+ try {
341
+ const fangorn = getFangorn();
342
+ let namespace = namespaceArg;
343
+ let owner = options.owner;
344
+ if (!namespace || !owner) try {
345
+ const repo = LocalRepo.open();
346
+ namespace = namespace ?? repo.namespace();
347
+ owner = owner ?? repo.owner();
348
+ } catch {}
349
+ if (!namespace) throw new Error("namespace required (pass it as an argument or run inside a repo)");
350
+ owner = owner ?? fangorn.getAddress();
351
+ const repoDir = join(process.cwd(), ".fangorn");
352
+ const cursorPath = join(repoDir, `subscribe-${owner}-${namespace}.json`);
353
+ const readCursor = () => {
354
+ if (options.fromStart) return void 0;
355
+ if (options.fromBlock !== void 0) return options.fromBlock;
356
+ if (existsSync(cursorPath)) return BigInt(JSON.parse(readFileSync(cursorPath, "utf-8")).lastBlock) + 1n;
357
+ };
358
+ const writeCursor = (block) => {
359
+ if (!existsSync(repoDir)) mkdirSync(repoDir, { recursive: true });
360
+ writeFileSync(cursorPath, JSON.stringify({
361
+ owner,
362
+ namespace,
363
+ lastBlock: block.toString()
364
+ }, null, 2), "utf-8");
365
+ };
366
+ const bigintReplacer = (_k, v) => typeof v === "bigint" ? v.toString() : v;
367
+ const fromBlock = readCursor();
368
+ console.error(`Subscribing to "${namespace}" @ ${owner} ` + (fromBlock !== void 0 ? `from block ${fromBlock}` : "(live from current tip)") + ` — Ctrl-C to stop.`);
369
+ const controller = new AbortController();
370
+ process.on("SIGINT", () => controller.abort());
371
+ process.on("SIGTERM", () => controller.abort());
372
+ for await (const change of fangorn.subscribe({
373
+ namespace,
374
+ owner,
375
+ fromBlock,
376
+ signal: controller.signal
377
+ })) {
378
+ process.stdout.write(JSON.stringify(change, bigintReplacer, options.pretty ? 2 : 0) + "\n");
379
+ writeCursor(change.blockNumber);
380
+ }
381
+ process.exit(0);
382
+ } catch (err) {
383
+ console.error("Failed:", err.message);
384
+ process.exit(1);
385
+ }
386
+ });
387
+ program.command("read").description("List every vertex and edge committed under a namespace, as JSON").argument("[namespace]", "Namespace name (default: current repo)").option("--owner <address>", "Owner (publisher) address (default: current repo owner)").option("--pretty", "Pretty-print the JSON output").action(async (namespaceArg, options) => {
313
388
  try {
314
- const self = getAccount().address;
315
- const owner = options.owner ?? self;
316
389
  const fangorn = getFangorn();
317
- const schemaId = await resolveSchemaId(fangorn, options.schema);
318
- const ds = await fangorn.getDatasourceRegistry().get(owner, schemaId, options.schema);
319
- console.log(`Owner: ${owner}`);
320
- console.log(`Schema ID: ${schemaId}`);
321
- console.log(`Version: ${String(ds.version)}`);
322
- console.log(`Manifest CID: ${ds.manifestCid || "(none yet)"}`);
390
+ let namespace = namespaceArg;
391
+ let owner = options.owner;
392
+ if (!namespace || !owner) {
393
+ const repo = LocalRepo.open();
394
+ namespace = namespace ?? repo.namespace();
395
+ owner = owner ?? repo.owner();
396
+ }
397
+ const [head, contents] = await Promise.all([fangorn.onChainTip(owner), fangorn.engine.listNamespace(namespace, owner)]);
398
+ const out = {
399
+ owner,
400
+ namespace,
401
+ head,
402
+ vertices: contents.vertices,
403
+ edges: contents.edges
404
+ };
405
+ process.stdout.write(JSON.stringify(out, null, options.pretty ? 2 : 0) + "\n");
323
406
  process.exit(0);
324
407
  } catch (err) {
325
408
  console.error("Failed:", err.message);
326
409
  process.exit(1);
327
410
  }
328
411
  });
329
- program$1.parse();
412
+ program.command("reset").description("DANGER!: reset your on-chain head to zero (abandons all prior commits)").action(async () => {
413
+ const confirmFirst = await confirm({ message: "Are you sure? Your onchain head will reset to 0x0000..." });
414
+ handleCancel(confirmFirst);
415
+ if (!confirmFirst) {
416
+ console.log("Reset aborted.");
417
+ process.exit(0);
418
+ }
419
+ await getFangorn().reset();
420
+ console.log("On-chain head reset to zero. `repo init` will now start fresh.");
421
+ process.exit(0);
422
+ });
423
+ program.parse();
330
424
 
331
425
  //#endregion
332
426
  export { };