@fangorn-network/sdk 0.1.5 → 0.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 (46) hide show
  1. package/lib/cli/cli.js +83 -46
  2. package/lib/cli/sell.d.ts +2 -2
  3. package/lib/cli/sell.js +15 -9
  4. package/lib/cli/stage.d.ts +21 -3
  5. package/lib/cli/stage.js +110 -24
  6. package/lib/config.d.ts +327 -1
  7. package/lib/config.js +11 -2
  8. package/lib/contracts/data-registry/abi.d.ts +42 -1
  9. package/lib/contracts/data-registry/abi.js +47 -1
  10. package/lib/contracts/data-registry/index.d.ts +45 -3
  11. package/lib/contracts/data-registry/index.js +69 -14
  12. package/lib/contracts/data-registry/mmr.d.ts +9 -2
  13. package/lib/contracts/data-registry/mmr.js +6 -2
  14. package/lib/contracts/index.d.ts +2 -2
  15. package/lib/contracts/index.js +2 -2
  16. package/lib/contracts/settlement-registry/abi.d.ts +1 -1
  17. package/lib/contracts/settlement-registry/abi.js +1 -1
  18. package/lib/contracts/write.d.ts +29 -5
  19. package/lib/contracts/write.js +78 -12
  20. package/lib/crypto/encryption.js +3 -0
  21. package/lib/crypto/paid.d.ts +1 -1
  22. package/lib/crypto/paid.js +4 -1
  23. package/lib/engine/index.d.ts +23 -4
  24. package/lib/engine/index.js +49 -21
  25. package/lib/engine/records.d.ts +9 -1
  26. package/lib/engine/records.js +32 -6
  27. package/lib/erc8004.d.ts +1 -1
  28. package/lib/erc8004.js +12 -4
  29. package/lib/fangorn.d.ts +12 -2
  30. package/lib/fangorn.js +38 -17
  31. package/lib/feed.d.ts +23 -2
  32. package/lib/feed.js +43 -6
  33. package/lib/index.d.ts +3 -3
  34. package/lib/index.js +4 -4
  35. package/lib/providers/storage/index.js +1 -1
  36. package/lib/providers/storage/pinata.js +14 -6
  37. package/lib/providers/storage/signed-url.js +21 -8
  38. package/lib/providers/storage/types.d.ts +9 -1
  39. package/lib/providers/storage/types.js +54 -1
  40. package/lib/providers/storage/utils.d.ts +3 -1
  41. package/lib/providers/storage/utils.js +3 -3
  42. package/lib/test/mem-registry.d.ts +3 -3
  43. package/lib/test/mem-registry.js +7 -5
  44. package/lib/test/testbed.d.ts +5190 -5190
  45. package/lib/test/testbed.js +1 -1
  46. package/package.json +6 -3
package/lib/cli/cli.js CHANGED
@@ -3,15 +3,15 @@ import getNetwork, { nonBlank } from "../config.js";
3
3
  import { agentCardUrl, parseAgentId } from "../erc8004.js";
4
4
  import { Fangorn } from "../fangorn.js";
5
5
  import { sealRecords } from "./sell.js";
6
- import { fileToRecords, walk } from "./stage.js";
6
+ import { addPaths } from "./stage.js";
7
7
  import { handleCancel, selectChain } from "./index.js";
8
8
  import { createRequire } from "node:module";
9
9
  import { createPublicClient, formatEther, http, isAddress, parseUnits } from "viem";
10
10
  import { privateKeyToAccount } from "viem/accounts";
11
11
  import { Command } from "commander";
12
- import { confirm, intro, outro, spinner, text } from "@clack/prompts";
13
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
14
- import { dirname, join } from "path";
12
+ import { confirm, intro, outro, password, spinner, text } from "@clack/prompts";
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
14
+ import { dirname, join, resolve } from "path";
15
15
  import { homedir } from "os";
16
16
  import "dotenv/config";
17
17
 
@@ -24,10 +24,21 @@ let _fangorn = null;
24
24
  function readStoredConfig() {
25
25
  return JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
26
26
  }
27
+ /** Write through a temp file and a rename, so a crash never leaves a torn file. */
28
+ function writeAtomic(path, data, mode = 420) {
29
+ const tmp = `${path}.${process.pid.toString()}.tmp`;
30
+ writeFileSync(tmp, data, {
31
+ encoding: "utf-8",
32
+ mode
33
+ });
34
+ renameSync(tmp, path);
35
+ }
27
36
  function writeStoredConfig(stored) {
28
- if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
29
- writeFileSync(CONFIG_PATH, JSON.stringify(stored, null, 2), "utf-8");
30
- chmodSync(CONFIG_PATH, 384);
37
+ if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, {
38
+ recursive: true,
39
+ mode: 448
40
+ });
41
+ writeAtomic(CONFIG_PATH, JSON.stringify(stored, null, 2), 384);
31
42
  }
32
43
  function loadConfig() {
33
44
  if (_config) return _config;
@@ -131,7 +142,7 @@ var LocalRepo = class LocalRepo {
131
142
  throw new Error("not a fangorn repo (no .fangorn/repo.json here or above). Run `fangorn repo init <namespace>` or `fangorn clone`.");
132
143
  }
133
144
  save() {
134
- writeFileSync(LocalRepo.path(this.dir), JSON.stringify(this.state, null, 2), "utf-8");
145
+ writeAtomic(LocalRepo.path(this.dir), JSON.stringify(this.state, null, 2));
135
146
  }
136
147
  namespace() {
137
148
  return this.state.namespace;
@@ -158,24 +169,35 @@ var LocalRepo = class LocalRepo {
158
169
  };
159
170
  }
160
171
  setStaged(s) {
161
- writeFileSync(join(this.dir, ".fangorn", "index.json"), JSON.stringify(s, null, 2), "utf-8");
172
+ writeAtomic(join(this.dir, ".fangorn", "index.json"), JSON.stringify(s, null, 2));
162
173
  }
163
174
  };
164
175
  const program = new Command();
165
176
  program.name("fangorn").description("Fangorn Network CLI").version(createRequire(import.meta.url)("../../package.json").version);
166
177
  program.command("init").description("Configure your Fangorn credentials").action(async () => {
167
178
  intro("Fangorn Setup");
179
+ if (existsSync(CONFIG_PATH)) {
180
+ const overwrite = await confirm({
181
+ message: `${CONFIG_PATH} exists. Replace it? Its private key is gone for good unless you have it elsewhere.`,
182
+ initialValue: false
183
+ });
184
+ handleCancel(overwrite);
185
+ if (!overwrite) {
186
+ outro("Kept the existing config.");
187
+ process.exit(0);
188
+ return;
189
+ }
190
+ }
168
191
  const chainName = await selectChain();
169
- const privateKey = await text({
192
+ const privateKey = await password({
170
193
  message: "Wallet private key (stored locally, never transmitted):",
171
- placeholder: "0x...",
172
194
  validate: (v) => {
173
195
  if (!v) return "Required";
174
- if (!v.startsWith("0x") || v.length !== 66) return "Must be a valid 0x-prefixed 32-byte hex key";
196
+ if (!/^0x[0-9a-fA-F]{64}$/.test(v)) return "Must be a valid 0x-prefixed 32-byte hex key";
175
197
  }
176
198
  });
177
199
  handleCancel(privateKey);
178
- const pinataJwt = await text({ message: "Pinata JWT — leave blank to use Fangorn's shared Pinata account (testnet convenience; files may be unpinned without notice):" });
200
+ const pinataJwt = await password({ message: "Pinata JWT — leave blank to use Fangorn's shared Pinata account (testnet convenience; files may be unpinned without notice):" });
179
201
  handleCancel(pinataJwt);
180
202
  const pinataGateway = await text({
181
203
  message: "Pinata Gateway URL (optional; blank uses the network's gateway):",
@@ -195,6 +217,7 @@ program.command("init").description("Configure your Fangorn credentials").action
195
217
  signedUrlWorkerUrl
196
218
  });
197
219
  outro(`Config saved to ${CONFIG_PATH}`);
220
+ process.exit(0);
198
221
  });
199
222
  program.command("card").description("Point a repo at its agent card, and register the card as an ERC-8004 agent").argument("[cardUrl]", "The agent card URL; or pass --access-worker to use its /.well-known/agent-card.json").option("--repo <name>", "The repo the card speaks for (default: the repo tracked here)").option("--access-worker <url>", "The access worker serving the agent card").option("--mcp <url>", "An MCP endpoint to index alongside the card").option("--skip-register", "Only commit the @card record, for a card already registered with ERC-8004").option("--update <agentId>", "Update an agent already registered (e.g. 84532:10323) from the card as it is now: a new registration file, pointed to by setAgentURI; mints nothing").action(async (cardUrl, opts) => {
200
223
  try {
@@ -286,20 +309,9 @@ program.command("repo").description("Repository operations").command("init").des
286
309
  program.command("add").description("Stage files as records: csv/jsonl/json arrays → a record per row, other text → one record per file").argument("<paths...>", "Files or directories (dot entries skipped)").option("--type <type>", "Record type (default: file name, or \"file\" for text)").option("--id-column <col>", "Column/field holding the record id", "id").action((paths, options) => {
287
310
  try {
288
311
  const repo = LocalRepo.open();
289
- const staged = repo.staged();
290
- let n = 0;
291
- for (const p of paths) for (const rel of walk(repo.root(), join(process.cwd(), p))) {
292
- const got = fileToRecords(repo.root(), rel, options);
293
- if (!got) {
294
- console.warn(`skipped (binary): ${rel}`);
295
- continue;
296
- }
297
- const ids = new Set(got.records.map((r) => r.id));
298
- staged.records = staged.records.filter((r) => !r.id || !ids.has(r.id)).concat(got.records);
299
- staged.deletes = staged.deletes.filter((d) => !ids.has(d)).concat(got.deletes);
300
- n += got.records.length + got.deletes.length;
301
- console.log(`added ${rel} (${got.records.length.toString()} record(s))`);
302
- }
312
+ const { staged, added, skipped, n } = addPaths(repo.root(), paths.map((p) => resolve(p)), options, repo.staged());
313
+ for (const rel of skipped) console.warn(`skipped (binary): ${rel}`);
314
+ for (const line of added) console.log(`added ${line}`);
303
315
  repo.setStaged(staged);
304
316
  console.log(`${n.toString()} change(s) staged. Run \`fangorn commit\`.`);
305
317
  process.exit(0);
@@ -313,6 +325,7 @@ program.command("rm").description("Stage record deletes (and drop them from the
313
325
  const repo = LocalRepo.open();
314
326
  const staged = repo.staged();
315
327
  staged.records = staged.records.filter((r) => !r.id || !ids.includes(r.id));
328
+ if (staged.sources) staged.sources = Object.fromEntries(Object.entries(staged.sources).filter(([id]) => !ids.includes(id)));
316
329
  staged.deletes = [...new Set([...staged.deletes, ...ids])];
317
330
  repo.setStaged(staged);
318
331
  console.log(`${ids.length.toString()} delete(s) staged.`);
@@ -378,12 +391,26 @@ program.command("push").description("Settle the local tip commit as the on-chain
378
391
  const head = repo.head();
379
392
  if (!head) throw new Error("nothing to push — no commits yet");
380
393
  const fangorn = getFangorn();
394
+ const tip = await fangorn.onChainTip(fangorn.getAddress(), repo.namespace());
395
+ const pending = [];
396
+ for await (const c of fangorn.log(head)) {
397
+ if (c.cid === tip) break;
398
+ pending.unshift(c.cid);
399
+ if (!c.parent && tip) throw new Error(`the on-chain tip ${tip} is not in local history (pushed from elsewhere?): \`fangorn clone\` it, or \`fangorn reset\` to abandon it`);
400
+ }
401
+ if (!pending.length) {
402
+ console.log("Everything up to date.");
403
+ process.exit(0);
404
+ return;
405
+ }
381
406
  const s = spinner();
382
- s.start("Pushing...");
383
- const { txHash, onChainTip } = await fangorn.push(repo.namespace(), head);
384
- s.stop();
385
- console.log(`Tx: ${txHash}`);
386
- console.log(`Tip: ${onChainTip}`);
407
+ for (const [i, cid] of pending.entries()) {
408
+ s.start(`Pushing ${(i + 1).toString()}/${pending.length.toString()}...`);
409
+ const { txHash } = await fangorn.push(repo.namespace(), cid);
410
+ s.stop();
411
+ console.log(`Tx: ${txHash}`);
412
+ }
413
+ console.log(`Tip: ${head}`);
387
414
  process.exit(0);
388
415
  } catch (err) {
389
416
  console.error("Failed:", err.message);
@@ -503,7 +530,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
503
530
  owner = owner ?? fangorn.getAddress();
504
531
  }
505
532
  const repoDir = join(process.cwd(), ".fangorn");
506
- const cursorPath = join(repoDir, `subscribe-${owner ?? "all"}-${namespace ?? "all"}.json`);
533
+ const cursorPath = join(repoDir, `subscribe-${owner ?? "all"}-${encodeURIComponent(namespace ?? "all")}.json`);
507
534
  const readCursor = () => {
508
535
  if (options.fromStart) return 0n;
509
536
  if (options.fromBlock !== void 0) return options.fromBlock;
@@ -512,13 +539,13 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
512
539
  return BigInt(numInput) + 1n;
513
540
  }
514
541
  };
515
- const writeCursor = (block) => {
542
+ const writeCursor = (block$1) => {
516
543
  if (!existsSync(repoDir)) mkdirSync(repoDir, { recursive: true });
517
- writeFileSync(cursorPath, JSON.stringify({
544
+ writeAtomic(cursorPath, JSON.stringify({
518
545
  owner,
519
546
  namespace,
520
- lastBlock: block.toString()
521
- }, null, 2), "utf-8");
547
+ lastBlock: block$1.toString()
548
+ }, null, 2));
522
549
  };
523
550
  const bigintReplacer = (_k, v) => typeof v === "bigint" ? v.toString() : v;
524
551
  const fromBlock = readCursor();
@@ -541,9 +568,13 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
541
568
  fromBlock,
542
569
  signal: controller.signal
543
570
  });
571
+ let block;
544
572
  for await (const change of stream) {
573
+ if (change.blockNumber !== block) {
574
+ writeCursor(change.blockNumber - 1n);
575
+ block = change.blockNumber;
576
+ }
545
577
  process.stdout.write(JSON.stringify(change, bigintReplacer, options.pretty ? 2 : 0) + "\n");
546
- writeCursor(change.blockNumber);
547
578
  }
548
579
  process.exit(0);
549
580
  } catch (err) {
@@ -575,16 +606,22 @@ program.command("read").description("List every record committed under a namespa
575
606
  }
576
607
  });
577
608
  program.command("reset").description("DANGER!: reset this namespace's on-chain head to zero (abandons all prior commits)").action(async () => {
578
- const namespace = LocalRepo.open().namespace();
579
- const confirmFirst = await confirm({ message: `Are you sure? The on-chain head for "${namespace}" will reset to 0x0000...` });
580
- handleCancel(confirmFirst);
581
- if (!confirmFirst) {
582
- console.log("Reset aborted.");
609
+ try {
610
+ const namespace = LocalRepo.open().namespace();
611
+ const confirmFirst = await confirm({ message: `Are you sure? The on-chain head for "${namespace}" will reset to 0x0000...` });
612
+ handleCancel(confirmFirst);
613
+ if (!confirmFirst) {
614
+ console.log("Reset aborted.");
615
+ process.exit(0);
616
+ return;
617
+ }
618
+ await getFangorn().reset(namespace);
619
+ console.log(`On-chain head for "${namespace}" reset to zero. \`repo init\` will now start fresh.`);
583
620
  process.exit(0);
621
+ } catch (err) {
622
+ console.error("Failed:", err.message);
623
+ process.exit(1);
584
624
  }
585
- await getFangorn().reset(namespace);
586
- console.log(`On-chain head for "${namespace}" reset to zero. \`repo init\` will now start fresh.`);
587
- process.exit(0);
588
625
  });
589
626
  program.parse();
590
627
 
package/lib/cli/sell.d.ts CHANGED
@@ -16,8 +16,8 @@ interface SellOptions {
16
16
  }
17
17
  /**
18
18
  * Make records sellable: seal `fields` of each record (as JSON, under `field-v1`), and add the
19
- * publisher's signed terms under "@terms". Returns the records to commit, plus the repo's
20
- * `@deposit/<generation>` record if the repo had none for this generation.
19
+ * publisher's signed terms under "@terms". Returns the records to commit, led by the repo's
20
+ * `@deposit/<generation>` record (new, or the existing one re-emitted).
21
21
  *
22
22
  * The deposit is read from the repo's on-chain head. Commit and push this before sealing more:
23
23
  * a second call before the push makes a second deposit, and the first commit's fields would
package/lib/cli/sell.js CHANGED
@@ -6,8 +6,8 @@ import { hexToBytes } from "viem";
6
6
  //#region src/cli/sell.ts
7
7
  /**
8
8
  * Make records sellable: seal `fields` of each record (as JSON, under `field-v1`), and add the
9
- * publisher's signed terms under "@terms". Returns the records to commit, plus the repo's
10
- * `@deposit/<generation>` record if the repo had none for this generation.
9
+ * publisher's signed terms under "@terms". Returns the records to commit, led by the repo's
10
+ * `@deposit/<generation>` record (new, or the existing one re-emitted).
11
11
  *
12
12
  * The deposit is read from the repo's on-chain head. Commit and push this before sealing more:
13
13
  * a second call before the push makes a second deposit, and the first commit's fields would
@@ -33,13 +33,19 @@ async function sealRecords(fangorn, repo, records, o) {
33
33
  }) };
34
34
  const out = [];
35
35
  let kRepo;
36
- const existing = (await fangorn.engine.readRecord(publisher, repo, depositId).catch(() => null))?.payload;
37
- if (existing) kRepo = await requestKey({
38
- deposit: existing,
39
- key: WHOLE_REPO,
40
- signer
41
- });
42
- else {
36
+ const existing = (await fangorn.engine.readRecord(publisher, repo, depositId))?.payload;
37
+ if (existing) {
38
+ kRepo = await requestKey({
39
+ deposit: existing,
40
+ key: WHOLE_REPO,
41
+ signer
42
+ });
43
+ out.push({
44
+ id: depositId,
45
+ type: "deposit",
46
+ payload: existing
47
+ });
48
+ } else {
43
49
  const keyServer = o.keyServer ?? fangorn.getConfig().keyServer;
44
50
  if (!keyServer) throw new Error("no key server: pass keyServer (CLI: --key-server)");
45
51
  const res = await fetch(`${keyServer}/pubkey`);
@@ -4,16 +4,34 @@ import { RecordInput } from "../engine/index.js";
4
4
  interface Staged {
5
5
  records: RecordInput[];
6
6
  deletes: string[];
7
+ /** Staging-only provenance. Older indexes have no source information. */
8
+ sources?: Record<string, string>;
7
9
  }
8
10
  interface StageOpts {
9
11
  type?: string;
10
12
  idColumn?: string;
11
13
  }
12
- /** RFC 4180 CSV → one object per row, keyed by the header. */
14
+ /** RFC 4180 CSV → one object per row, keyed by the header. Blank lines are skipped. */
13
15
  declare function parseCsv(text: string): Record<string, string>[];
14
- /** Files under `path` (file or dir) as root-relative posix paths; dot entries skipped. */
16
+ /**
17
+ * Files under `path` (file or dir) as sorted root-relative posix paths. Dot entries are
18
+ * skipped, and symlinks inside a directory are not followed (no escaping the repo, no cycles).
19
+ * Throws for a path outside `root`, judged by real paths: a named symlink, or a symlinked
20
+ * ancestor, that leads out of the repo is outside it.
21
+ */
15
22
  declare function walk(root: string, path: string): string[];
16
23
  /** One file → records. null for binary files (no text to stage). */
17
24
  declare function fileToRecords(root: string, rel: string, opts: StageOpts): Staged | null;
25
+ /**
26
+ * `fangorn add`: stage the files under `paths` (absolute) on top of `staged`. Re-adding
27
+ * replaces staged records with the same ids. Throws, naming the file, if one fails to
28
+ * parse or two sources map to one record id; nothing is staged then.
29
+ */
30
+ declare function addPaths(root: string, paths: string[], opts: StageOpts, staged: Staged): {
31
+ staged: Staged;
32
+ added: string[];
33
+ skipped: string[];
34
+ n: number;
35
+ };
18
36
  //#endregion
19
- export { StageOpts, Staged, fileToRecords, parseCsv, walk };
37
+ export { StageOpts, Staged, addPaths, fileToRecords, parseCsv, walk };
package/lib/cli/stage.js CHANGED
@@ -1,54 +1,85 @@
1
- import { readFileSync, readdirSync, statSync } from "fs";
2
- import { basename, extname, join, relative, sep } from "path";
1
+ import { readFileSync, readdirSync, realpathSync, statSync } from "fs";
2
+ import { basename, extname, isAbsolute, join, relative, sep } from "path";
3
3
 
4
4
  //#region src/cli/stage.ts
5
- /** RFC 4180 CSV → one object per row, keyed by the header. */
5
+ /** RFC 4180 CSV → one object per row, keyed by the header. Blank lines are skipped. */
6
6
  function parseCsv(text) {
7
7
  const rows = [];
8
8
  let row = [];
9
9
  let field = "";
10
10
  let quoted = false;
11
+ let dirty = false;
12
+ const endRow = () => {
13
+ if (dirty) rows.push([...row, field]);
14
+ row = [];
15
+ field = "";
16
+ dirty = false;
17
+ };
11
18
  for (let i = 0; i < text.length; i++) {
12
19
  const c = text[i];
13
20
  if (quoted) if (c === "\"" && text[i + 1] === "\"") field += text[++i];
14
21
  else if (c === "\"") quoted = false;
15
22
  else field += c;
16
- else if (c === "\"") quoted = true;
23
+ else if (c === "\"") quoted = dirty = true;
17
24
  else if (c === ",") {
18
25
  row.push(field);
19
26
  field = "";
27
+ dirty = true;
20
28
  } else if (c === "\n" || c === "\r") {
21
29
  if (c === "\r" && text[i + 1] === "\n") i++;
22
- row.push(field);
23
- rows.push(row);
24
- row = [];
25
- field = "";
26
- } else field += c;
30
+ endRow();
31
+ } else {
32
+ field += c;
33
+ dirty = true;
34
+ }
27
35
  }
28
- if (field || row.length) rows.push([...row, field]);
36
+ if (quoted) throw new Error("unterminated quoted field");
37
+ endRow();
29
38
  const [header = [], ...body] = rows;
30
- return body.map((r) => Object.fromEntries(header.map((h, i) => [h, r[i] ?? ""])));
39
+ const dup = header.find((h, i) => header.indexOf(h) !== i);
40
+ if (dup !== void 0) throw new Error(`duplicate column ${JSON.stringify(dup)}`);
41
+ return body.map((r, n) => {
42
+ if (r.slice(header.length).some(Boolean)) throw new Error(`row ${(n + 1).toString()} has more fields than the header`);
43
+ return Object.fromEntries(header.map((h, i) => [h, r[i] ?? ""]));
44
+ });
31
45
  }
32
46
  const safeId = (s) => s.replace(/[^\x21-\x7e]/g, "_");
33
- /** Files under `path` (file or dir) as root-relative posix paths; dot entries skipped. */
47
+ /**
48
+ * Files under `path` (file or dir) as sorted root-relative posix paths. Dot entries are
49
+ * skipped, and symlinks inside a directory are not followed (no escaping the repo, no cycles).
50
+ * Throws for a path outside `root`, judged by real paths: a named symlink, or a symlinked
51
+ * ancestor, that leads out of the repo is outside it.
52
+ */
34
53
  function walk(root, path) {
35
- const rel = (p) => relative(root, p).split(sep).join("/");
36
- if (!statSync(path).isDirectory()) return [rel(path)];
37
- return readdirSync(path, {
38
- recursive: true,
39
- withFileTypes: true
40
- }).filter((e) => e.isFile()).map((e) => rel(join(e.parentPath, e.name))).filter((p) => !p.split("/").some((s) => s.startsWith(".")));
54
+ const realRoot = realpathSync(root);
55
+ const real = realpathSync(path);
56
+ const rel = (p) => relative(realRoot, p).split(sep).join("/");
57
+ const top = rel(real);
58
+ if (top === ".." || top.startsWith("../") || isAbsolute(top)) throw new Error(`${path} is outside the repo at ${root}`);
59
+ const out = [];
60
+ const visit = (dir) => {
61
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
62
+ const p = join(dir, e.name);
63
+ if (e.isDirectory()) visit(p);
64
+ else if (e.isFile()) out.push(rel(p));
65
+ }
66
+ };
67
+ if (statSync(real).isDirectory()) visit(real);
68
+ else out.push(top);
69
+ return out.filter((p) => !p.split("/").some((s) => s.startsWith("."))).sort();
41
70
  }
42
71
  /** One file → records. null for binary files (no text to stage). */
43
72
  function fileToRecords(root, rel, opts) {
44
73
  const bytes = readFileSync(join(root, rel));
45
74
  if (bytes.subarray(0, 8192).includes(0)) return null;
46
- const text = bytes.toString("utf-8");
75
+ const text = bytes.toString("utf-8").replace(/^\uFEFF/, "");
47
76
  const ext = extname(rel).toLowerCase();
48
77
  const type = opts.type ?? basename(rel, extname(rel));
49
78
  const idCol = opts.idColumn ?? "id";
50
79
  const many = (rows) => ({
51
80
  records: rows.map((payload, i) => {
81
+ const raw = payload;
82
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(`row ${(i + 1).toString()} is not an object`);
52
83
  const id = payload[idCol];
53
84
  return {
54
85
  id: safeId((typeof id === "string" || typeof id === "number") && id !== "" ? String(id) : `${rel}#${(i + 1).toString()}`),
@@ -64,10 +95,15 @@ function fileToRecords(root, rel, opts) {
64
95
  const data = JSON.parse(text);
65
96
  if (Array.isArray(data)) return many(data);
66
97
  const obj = data;
67
- if (Array.isArray(obj.records) || Array.isArray(obj.deletes)) return {
68
- records: obj.records ?? [],
69
- deletes: obj.deletes ?? []
70
- };
98
+ if (Array.isArray(obj.records) || Array.isArray(obj.deletes)) {
99
+ const records = obj.records ?? [];
100
+ const deletes = obj.deletes ?? [];
101
+ if (!records.every((r) => typeof r?.type === "string" && typeof r.payload === "object" && (r.id === void 0 || typeof r.id === "string")) || !deletes.every((d) => typeof d === "string")) throw new Error("has \"records\"/\"deletes\" but is not a commit file ({\"records\":[{\"id\",\"type\",\"payload\"}],\"deletes\":[\"id\"]})");
102
+ return {
103
+ records,
104
+ deletes
105
+ };
106
+ }
71
107
  return {
72
108
  records: [{
73
109
  id: safeId(rel),
@@ -89,6 +125,56 @@ function fileToRecords(root, rel, opts) {
89
125
  deletes: []
90
126
  };
91
127
  }
128
+ /**
129
+ * `fangorn add`: stage the files under `paths` (absolute) on top of `staged`. Re-adding
130
+ * replaces staged records with the same ids. Throws, naming the file, if one fails to
131
+ * parse or two sources map to one record id; nothing is staged then.
132
+ */
133
+ function addPaths(root, paths, opts, staged) {
134
+ const added = [];
135
+ const skipped = [];
136
+ const sources = new Map(Object.entries(staged.sources ?? {}));
137
+ const stagedIds = new Set(staged.records.map((r) => r.id));
138
+ let n = 0;
139
+ for (const rel of [...new Set(paths.flatMap((p) => walk(root, p)))]) {
140
+ let got;
141
+ try {
142
+ got = fileToRecords(root, rel, opts);
143
+ } catch (e) {
144
+ throw new Error(`${rel}: ${e.message}`);
145
+ }
146
+ if (!got) {
147
+ skipped.push(rel);
148
+ continue;
149
+ }
150
+ const seen = /* @__PURE__ */ new Set();
151
+ for (const { id } of got.records) {
152
+ if (id === void 0) continue;
153
+ const other = sources.get(id);
154
+ if (other === void 0 && stagedIds.has(id)) throw new Error(`staged record ${JSON.stringify(id)} has an unknown source; commit it or unstage it with fangorn rm before replacing it`);
155
+ if (seen.has(id)) throw new Error(`record id ${JSON.stringify(id)} comes from two rows of ${rel}; give each record its own id`);
156
+ if (other !== void 0 && other !== rel) throw new Error(`record id ${JSON.stringify(id)} comes from both ${other} and ${rel}; give each record its own id or rename the file`);
157
+ seen.add(id);
158
+ sources.set(id, rel);
159
+ }
160
+ const ids = new Set(got.records.map((r) => r.id));
161
+ staged = {
162
+ records: staged.records.filter((r) => !r.id || !ids.has(r.id)).concat(got.records),
163
+ deletes: staged.deletes.filter((d) => !ids.has(d)).concat(got.deletes)
164
+ };
165
+ n += got.records.length + got.deletes.length;
166
+ added.push(`${rel} (${got.records.length.toString()} record(s))`);
167
+ }
168
+ return {
169
+ staged: {
170
+ ...staged,
171
+ sources: Object.fromEntries(sources)
172
+ },
173
+ added,
174
+ skipped,
175
+ n
176
+ };
177
+ }
92
178
 
93
179
  //#endregion
94
- export { fileToRecords, parseCsv, walk };
180
+ export { addPaths, fileToRecords, parseCsv, walk };