@fangorn-network/sdk 0.1.6 → 0.2.1
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 +1 -1
- package/lib/cli/cli.js +85 -46
- package/lib/cli/index.js +1 -1
- package/lib/cli/sell.d.ts +2 -2
- package/lib/cli/sell.js +14 -8
- package/lib/cli/stage.d.ts +21 -3
- package/lib/cli/stage.js +110 -24
- package/lib/config.d.ts +481 -155
- package/lib/config.js +14 -4
- package/lib/contracts/data-registry/abi.d.ts +41 -0
- package/lib/contracts/data-registry/abi.js +46 -0
- package/lib/contracts/data-registry/index.d.ts +45 -3
- package/lib/contracts/data-registry/index.js +69 -14
- package/lib/contracts/data-registry/mmr.d.ts +9 -2
- package/lib/contracts/data-registry/mmr.js +6 -2
- package/lib/contracts/index.d.ts +2 -2
- package/lib/contracts/index.js +2 -2
- package/lib/contracts/write.d.ts +17 -2
- package/lib/contracts/write.js +63 -7
- package/lib/crypto/encryption.js +3 -0
- package/lib/crypto/paid.d.ts +1 -1
- package/lib/crypto/paid.js +4 -1
- package/lib/engine/index.d.ts +9 -2
- package/lib/engine/index.js +33 -17
- package/lib/engine/records.d.ts +9 -1
- package/lib/engine/records.js +32 -6
- package/lib/erc8004.d.ts +1 -1
- package/lib/erc8004.js +12 -5
- package/lib/fangorn.d.ts +11 -1
- package/lib/fangorn.js +26 -16
- package/lib/feed.d.ts +23 -2
- package/lib/feed.js +43 -6
- package/lib/index.d.ts +3 -3
- package/lib/index.js +4 -4
- package/lib/providers/storage/index.js +1 -1
- package/lib/providers/storage/pinata.js +14 -6
- package/lib/providers/storage/signed-url.d.ts +1 -1
- package/lib/providers/storage/signed-url.js +23 -9
- package/lib/providers/storage/types.d.ts +9 -1
- package/lib/providers/storage/types.js +54 -1
- package/lib/providers/storage/utils.d.ts +3 -1
- package/lib/providers/storage/utils.js +3 -3
- package/lib/test/mem-registry.d.ts +3 -3
- package/lib/test/mem-registry.js +7 -5
- package/lib/test/testbed.d.ts +5230 -5230
- package/package.json +6 -3
package/README.md
CHANGED
|
@@ -62,7 +62,7 @@ The [Guide](docs/GUIDE.md) covers the full flow: commit vs push, epochs, history
|
|
|
62
62
|
|
|
63
63
|
## Network
|
|
64
64
|
|
|
65
|
-
Fangorn runs on **Base Sepolia** (the default) and **Arbitrum Sepolia**. Each has its own DataRegistry, SettlementRegistry, hosted upload worker and key server. Addresses are in [`src/config.ts`](src/config.ts) (`BaseSepoliaConfig`, `ArbitrumSepoliaConfig`). The CLI asks for the network in `fangorn init`, and `CHAIN_NAME
|
|
65
|
+
Fangorn runs on **Base Sepolia** (the default) and **Arbitrum Sepolia**. Each has its own DataRegistry, SettlementRegistry, hosted upload worker and key server. **Base** mainnet has a DataRegistry only: repos read and publish there, but there are no paid records, and no hosted upload worker yet, so publishing needs your own Pinata JWT. Addresses are in [`src/config.ts`](src/config.ts) (`BaseSepoliaConfig`, `ArbitrumSepoliaConfig`, `BaseConfig`). The CLI asks for the network in `fangorn init`, and `CHAIN_NAME` (`baseSepolia`, `arbitrumSepolia` or `base`) overrides it. To use a local anvil or a private deployment, pass your own `NetworkConfig` to `Fangorn.create`, or set the `FANGORN_*` overrides for the CLI (see the [Guide](docs/GUIDE.md#configure)). Contract sources are in [fangorn-network/contracts](https://github.com/fangorn-network/contracts).
|
|
66
66
|
|
|
67
67
|
## Development
|
|
68
68
|
|
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 {
|
|
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 {
|
|
14
|
-
import { dirname, join } from "path";
|
|
12
|
+
import { confirm, intro, log, 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, {
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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 (
|
|
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
|
|
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):",
|
|
@@ -187,6 +209,8 @@ program.command("init").description("Configure your Fangorn credentials").action
|
|
|
187
209
|
placeholder: "https://pinata-url-provider.your-subdomain.workers.dev"
|
|
188
210
|
});
|
|
189
211
|
handleCancel(signedUrlWorkerUrl);
|
|
212
|
+
const net = getNetwork(chainName);
|
|
213
|
+
if (!net.signedUrlWorker && !nonBlank(pinataJwt) && !nonBlank(signedUrlWorkerUrl)) log.warn(`No hosted upload worker exists for ${net.chain.name}. If publishing data, include your own Pinata JWT (rerun \`fangorn init\`, or set PINATA_JWT).`);
|
|
190
214
|
writeStoredConfig({
|
|
191
215
|
privateKey,
|
|
192
216
|
chainName,
|
|
@@ -195,6 +219,7 @@ program.command("init").description("Configure your Fangorn credentials").action
|
|
|
195
219
|
signedUrlWorkerUrl
|
|
196
220
|
});
|
|
197
221
|
outro(`Config saved to ${CONFIG_PATH}`);
|
|
222
|
+
process.exit(0);
|
|
198
223
|
});
|
|
199
224
|
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
225
|
try {
|
|
@@ -286,20 +311,9 @@ program.command("repo").description("Repository operations").command("init").des
|
|
|
286
311
|
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
312
|
try {
|
|
288
313
|
const repo = LocalRepo.open();
|
|
289
|
-
const staged = repo.staged();
|
|
290
|
-
|
|
291
|
-
for (const
|
|
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
|
-
}
|
|
314
|
+
const { staged, added, skipped, n } = addPaths(repo.root(), paths.map((p) => resolve(p)), options, repo.staged());
|
|
315
|
+
for (const rel of skipped) console.warn(`skipped (binary): ${rel}`);
|
|
316
|
+
for (const line of added) console.log(`added ${line}`);
|
|
303
317
|
repo.setStaged(staged);
|
|
304
318
|
console.log(`${n.toString()} change(s) staged. Run \`fangorn commit\`.`);
|
|
305
319
|
process.exit(0);
|
|
@@ -313,6 +327,7 @@ program.command("rm").description("Stage record deletes (and drop them from the
|
|
|
313
327
|
const repo = LocalRepo.open();
|
|
314
328
|
const staged = repo.staged();
|
|
315
329
|
staged.records = staged.records.filter((r) => !r.id || !ids.includes(r.id));
|
|
330
|
+
if (staged.sources) staged.sources = Object.fromEntries(Object.entries(staged.sources).filter(([id]) => !ids.includes(id)));
|
|
316
331
|
staged.deletes = [...new Set([...staged.deletes, ...ids])];
|
|
317
332
|
repo.setStaged(staged);
|
|
318
333
|
console.log(`${ids.length.toString()} delete(s) staged.`);
|
|
@@ -378,12 +393,26 @@ program.command("push").description("Settle the local tip commit as the on-chain
|
|
|
378
393
|
const head = repo.head();
|
|
379
394
|
if (!head) throw new Error("nothing to push — no commits yet");
|
|
380
395
|
const fangorn = getFangorn();
|
|
396
|
+
const tip = await fangorn.onChainTip(fangorn.getAddress(), repo.namespace());
|
|
397
|
+
const pending = [];
|
|
398
|
+
for await (const c of fangorn.log(head)) {
|
|
399
|
+
if (c.cid === tip) break;
|
|
400
|
+
pending.unshift(c.cid);
|
|
401
|
+
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`);
|
|
402
|
+
}
|
|
403
|
+
if (!pending.length) {
|
|
404
|
+
console.log("Everything up to date.");
|
|
405
|
+
process.exit(0);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
381
408
|
const s = spinner();
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
409
|
+
for (const [i, cid] of pending.entries()) {
|
|
410
|
+
s.start(`Pushing ${(i + 1).toString()}/${pending.length.toString()}...`);
|
|
411
|
+
const { txHash } = await fangorn.push(repo.namespace(), cid);
|
|
412
|
+
s.stop();
|
|
413
|
+
console.log(`Tx: ${txHash}`);
|
|
414
|
+
}
|
|
415
|
+
console.log(`Tip: ${head}`);
|
|
387
416
|
process.exit(0);
|
|
388
417
|
} catch (err) {
|
|
389
418
|
console.error("Failed:", err.message);
|
|
@@ -503,7 +532,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
|
|
|
503
532
|
owner = owner ?? fangorn.getAddress();
|
|
504
533
|
}
|
|
505
534
|
const repoDir = join(process.cwd(), ".fangorn");
|
|
506
|
-
const cursorPath = join(repoDir, `subscribe-${owner ?? "all"}-${namespace ?? "all"}.json`);
|
|
535
|
+
const cursorPath = join(repoDir, `subscribe-${owner ?? "all"}-${encodeURIComponent(namespace ?? "all")}.json`);
|
|
507
536
|
const readCursor = () => {
|
|
508
537
|
if (options.fromStart) return 0n;
|
|
509
538
|
if (options.fromBlock !== void 0) return options.fromBlock;
|
|
@@ -512,13 +541,13 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
|
|
|
512
541
|
return BigInt(numInput) + 1n;
|
|
513
542
|
}
|
|
514
543
|
};
|
|
515
|
-
const writeCursor = (block) => {
|
|
544
|
+
const writeCursor = (block$1) => {
|
|
516
545
|
if (!existsSync(repoDir)) mkdirSync(repoDir, { recursive: true });
|
|
517
|
-
|
|
546
|
+
writeAtomic(cursorPath, JSON.stringify({
|
|
518
547
|
owner,
|
|
519
548
|
namespace,
|
|
520
|
-
lastBlock: block.toString()
|
|
521
|
-
}, null, 2)
|
|
549
|
+
lastBlock: block$1.toString()
|
|
550
|
+
}, null, 2));
|
|
522
551
|
};
|
|
523
552
|
const bigintReplacer = (_k, v) => typeof v === "bigint" ? v.toString() : v;
|
|
524
553
|
const fromBlock = readCursor();
|
|
@@ -541,9 +570,13 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
|
|
|
541
570
|
fromBlock,
|
|
542
571
|
signal: controller.signal
|
|
543
572
|
});
|
|
573
|
+
let block;
|
|
544
574
|
for await (const change of stream) {
|
|
575
|
+
if (change.blockNumber !== block) {
|
|
576
|
+
writeCursor(change.blockNumber - 1n);
|
|
577
|
+
block = change.blockNumber;
|
|
578
|
+
}
|
|
545
579
|
process.stdout.write(JSON.stringify(change, bigintReplacer, options.pretty ? 2 : 0) + "\n");
|
|
546
|
-
writeCursor(change.blockNumber);
|
|
547
580
|
}
|
|
548
581
|
process.exit(0);
|
|
549
582
|
} catch (err) {
|
|
@@ -575,16 +608,22 @@ program.command("read").description("List every record committed under a namespa
|
|
|
575
608
|
}
|
|
576
609
|
});
|
|
577
610
|
program.command("reset").description("DANGER!: reset this namespace's on-chain head to zero (abandons all prior commits)").action(async () => {
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
611
|
+
try {
|
|
612
|
+
const namespace = LocalRepo.open().namespace();
|
|
613
|
+
const confirmFirst = await confirm({ message: `Are you sure? The on-chain head for "${namespace}" will reset to 0x0000...` });
|
|
614
|
+
handleCancel(confirmFirst);
|
|
615
|
+
if (!confirmFirst) {
|
|
616
|
+
console.log("Reset aborted.");
|
|
617
|
+
process.exit(0);
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
await getFangorn().reset(namespace);
|
|
621
|
+
console.log(`On-chain head for "${namespace}" reset to zero. \`repo init\` will now start fresh.`);
|
|
583
622
|
process.exit(0);
|
|
623
|
+
} catch (err) {
|
|
624
|
+
console.error("Failed:", err.message);
|
|
625
|
+
process.exit(1);
|
|
584
626
|
}
|
|
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
627
|
});
|
|
589
628
|
program.parse();
|
|
590
629
|
|
package/lib/cli/index.js
CHANGED
|
@@ -12,7 +12,7 @@ const selectChain = async () => {
|
|
|
12
12
|
message: "Pick your chain.",
|
|
13
13
|
options: Object.entries(SupportedNetworks).map(([value, c]) => ({
|
|
14
14
|
value,
|
|
15
|
-
label: c.chain.name
|
|
15
|
+
label: c.chain.testnet ? c.chain.name : `${c.chain.name} (mainnet)`
|
|
16
16
|
}))
|
|
17
17
|
});
|
|
18
18
|
handleCancel(choice);
|
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,
|
|
20
|
-
* `@deposit/<generation>` record
|
|
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,
|
|
10
|
-
* `@deposit/<generation>` record
|
|
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
|
|
@@ -34,12 +34,18 @@ async function sealRecords(fangorn, repo, records, o) {
|
|
|
34
34
|
const out = [];
|
|
35
35
|
let kRepo;
|
|
36
36
|
const existing = (await fangorn.engine.readRecord(publisher, repo, depositId))?.payload;
|
|
37
|
-
if (existing)
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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`);
|
package/lib/cli/stage.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
}
|
|
30
|
+
endRow();
|
|
31
|
+
} else {
|
|
32
|
+
field += c;
|
|
33
|
+
dirty = true;
|
|
34
|
+
}
|
|
27
35
|
}
|
|
28
|
-
if (
|
|
36
|
+
if (quoted) throw new Error("unterminated quoted field");
|
|
37
|
+
endRow();
|
|
29
38
|
const [header = [], ...body] = rows;
|
|
30
|
-
|
|
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
|
-
/**
|
|
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
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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))
|
|
68
|
-
records
|
|
69
|
-
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 };
|