@fangorn-network/sdk 0.1.0-dev → 0.1.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 (96) hide show
  1. package/lib/cli/cli.js +328 -128
  2. package/lib/cli/index.d.ts +4 -1
  3. package/lib/cli/index.js +20 -2
  4. package/lib/config.d.ts +111 -48
  5. package/lib/config.js +39 -11
  6. package/lib/contracts/app-registry/abi.d.ts +1265 -0
  7. package/lib/contracts/app-registry/abi.js +1454 -0
  8. package/lib/contracts/app-registry/index.d.ts +161 -0
  9. package/lib/contracts/app-registry/index.js +274 -0
  10. package/lib/contracts/data-registry/abi.d.ts +19 -195
  11. package/lib/contracts/data-registry/abi.js +206 -409
  12. package/lib/contracts/data-registry/index.d.ts +2 -126
  13. package/lib/contracts/data-registry/index.js +1 -174
  14. package/lib/contracts/index.d.ts +7 -4
  15. package/lib/contracts/index.js +7 -4
  16. package/lib/contracts/logs.d.ts +1 -1
  17. package/lib/contracts/logs.js +1 -1
  18. package/lib/contracts/{settlement-registry → membership-registry}/abi.d.ts +636 -301
  19. package/lib/contracts/membership-registry/abi.js +1333 -0
  20. package/lib/contracts/membership-registry/index.d.ts +79 -0
  21. package/lib/contracts/membership-registry/index.js +104 -0
  22. package/lib/contracts/types.d.ts +10 -0
  23. package/lib/contracts/types.js +12 -0
  24. package/lib/crypto/aes.d.ts +2 -2
  25. package/lib/crypto/aes.js +4 -4
  26. package/lib/crypto/encryption.d.ts +109 -8
  27. package/lib/crypto/encryption.js +114 -16
  28. package/lib/engine/car.d.ts +1 -5
  29. package/lib/engine/car.js +2 -2
  30. package/lib/engine/index.d.ts +14 -33
  31. package/lib/engine/index.js +41 -98
  32. package/lib/engine/records.d.ts +8 -19
  33. package/lib/engine/records.js +7 -81
  34. package/lib/engine/test-helpers.d.ts +3 -2
  35. package/lib/engine/test-helpers.js +5 -7
  36. package/lib/erc8004.js +10 -7
  37. package/lib/fangorn.d.ts +86 -65
  38. package/lib/fangorn.js +153 -115
  39. package/lib/feed.d.ts +8 -7
  40. package/lib/feed.js +8 -7
  41. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +1 -0
  42. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  43. package/lib/harness/index.d.ts +58 -0
  44. package/lib/harness/index.js +73 -0
  45. package/lib/index.d.ts +13 -10
  46. package/lib/index.js +13 -10
  47. package/lib/node_modules/{@jridgewell → .pnpm/@jridgewell_sourcemap-codec@1.5.5/node_modules/@jridgewell}/sourcemap-codec/dist/sourcemap-codec.js +1 -1
  48. package/lib/node_modules/{@vitest → .pnpm/@vitest_expect@4.0.18/node_modules/@vitest}/expect/dist/index.js +8 -8
  49. package/lib/node_modules/{@vitest → .pnpm/@vitest_pretty-format@4.0.18/node_modules/@vitest}/pretty-format/dist/index.js +2 -2
  50. package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/chunk-tasks.js +2 -2
  51. package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/index.js +4 -4
  52. package/lib/node_modules/{@vitest → .pnpm/@vitest_snapshot@4.0.18/node_modules/@vitest}/snapshot/dist/index.js +4 -4
  53. package/lib/node_modules/{@vitest → .pnpm/@vitest_spy@4.0.18/node_modules/@vitest}/spy/dist/index.js +1 -1
  54. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/chunk-_commonjsHelpers.js +1 -1
  55. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/chunk-pathe.M-eThtNZ.js +1 -1
  56. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/diff.js +3 -3
  57. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/display.js +2 -2
  58. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/error.js +2 -2
  59. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/helpers.js +1 -1
  60. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/serialize.js +1 -1
  61. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/source-map.js +1 -1
  62. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/timers.js +1 -1
  63. package/lib/node_modules/{chai → .pnpm/chai@6.2.2/node_modules/chai}/index.js +1 -1
  64. package/lib/node_modules/{magic-string → .pnpm/magic-string@0.30.21/node_modules/magic-string}/dist/magic-string.es.js +2 -2
  65. package/lib/node_modules/{pathe → .pnpm/pathe@2.0.3/node_modules/pathe}/dist/shared/pathe.M-eThtNZ.js +1 -1
  66. package/lib/node_modules/{tinyrainbow → .pnpm/tinyrainbow@3.0.3/node_modules/tinyrainbow}/dist/index.js +1 -1
  67. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/_commonjsHelpers.D26ty3Ew.js +1 -1
  68. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/date.Bq6ZW5rf.js +1 -1
  69. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/utils.DvEY5TfP.js +2 -2
  70. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/vi.2VT5v0um.js +11 -11
  71. package/lib/providers/storage/signed-url.d.ts +10 -2
  72. package/lib/providers/storage/signed-url.js +15 -5
  73. package/lib/providers/storage/types.d.ts +1 -1
  74. package/lib/providers/storage/utils.js +3 -5
  75. package/lib/registry.d.ts +118 -0
  76. package/lib/registry.js +184 -0
  77. package/lib/test/mem-registry.d.ts +19 -14
  78. package/lib/test/mem-registry.js +37 -44
  79. package/lib/test/sdk-suite.d.ts +4 -1
  80. package/lib/test/sdk-suite.js +89 -18
  81. package/lib/test/testbed.d.ts +5227 -5218
  82. package/lib/test/testbed.js +56 -29
  83. package/lib/types/index.d.ts +11 -6
  84. package/package.json +1 -1
  85. package/lib/cli/sell.d.ts +0 -28
  86. package/lib/cli/sell.js +0 -95
  87. package/lib/cli/stage.d.ts +0 -19
  88. package/lib/cli/stage.js +0 -94
  89. package/lib/contracts/settlement-registry/abi.js +0 -962
  90. package/lib/contracts/settlement-registry/index.d.ts +0 -143
  91. package/lib/contracts/settlement-registry/index.js +0 -213
  92. package/lib/crypto/paid.d.ts +0 -104
  93. package/lib/crypto/paid.js +0 -147
  94. package/lib/test/key-server.d.ts +0 -12
  95. package/lib/test/key-server.js +0 -30
  96. /package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/utils.js +0 -0
@@ -1,19 +1,21 @@
1
1
  import { FangornConfig } from "../config.js";
2
2
  import { PinataBackend } from "../providers/storage/pinata.js";
3
+ import { APP_REGISTRY_ABI } from "../contracts/app-registry/abi.js";
3
4
  import { DATA_REGISTRY_ABI } from "../contracts/data-registry/abi.js";
4
- import { SETTLEMENT_REGISTRY_ABI } from "../contracts/settlement-registry/abi.js";
5
5
  import "../contracts/index.js";
6
6
  import { Fangorn } from "../fangorn.js";
7
7
  import { MemLedger, MemRegistry } from "./mem-registry.js";
8
8
  import { MemStorage } from "../engine/test-helpers.js";
9
- import { foundry } from "viem/chains";
10
9
  import { createTestClient, encodeFunctionData, getAddress, http, parseEther, publicActions, walletActions } from "viem";
10
+ import { foundry } from "viem/chains";
11
11
  import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
12
12
  import { spawn, spawnSync } from "node:child_process";
13
13
  import { existsSync, readFileSync } from "node:fs";
14
14
  import { resolve } from "node:path";
15
15
 
16
16
  //#region src/test/testbed.ts
17
+ /** The app every client is accepted into unless told otherwise. */
18
+ const TEST_APP = "test-app";
17
19
  function memoryNetwork(Registry = MemRegistry) {
18
20
  const ledger = new MemLedger();
19
21
  const storage = new MemStorage();
@@ -21,16 +23,20 @@ function memoryNetwork(Registry = MemRegistry) {
21
23
  name: "memory",
22
24
  ledger,
23
25
  storage,
24
- client(sk = generatePrivateKey(), R = Registry) {
25
- return Promise.resolve(Fangorn.create({
26
+ client(app = TEST_APP, sk = generatePrivateKey(), R = Registry) {
27
+ const f = Fangorn.create({
26
28
  privateKey: sk,
29
+ appId: app ?? void 0,
27
30
  config: {
28
31
  ...FangornConfig,
29
- fromBlock: 0n
32
+ appRegistryFromBlock: 0n
30
33
  },
31
34
  storage: { backend: storage },
32
35
  registry: new R(privateKeyToAccount(sk).address, ledger)
33
- }));
36
+ });
37
+ const id = f.getAppId();
38
+ if (id) ledger.members.add(`${id}/${f.getAddress().toLowerCase()}`);
39
+ return Promise.resolve(f);
34
40
  },
35
41
  clock: () => Promise.resolve(ledger.t),
36
42
  stop: () => void 0
@@ -46,6 +52,8 @@ const has = (cmd) => spawnSync(cmd, ["--version"]).status === 0;
46
52
  const skipChain = !(has("anvil") && has("forge") && existsSync(CONTRACTS)) && !process.env.CI;
47
53
  /** anvil's first prefunded account: the deployer, and the protocol admin. */
48
54
  const ADMIN_KEY = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
55
+ /** No contract: fees are zero, so the token is never called. */
56
+ const NO_TOKEN = "0x000000000000000000000000000000000000dEaD";
49
57
  async function startAnvil(chainId) {
50
58
  const anvil = spawn("anvil", [
51
59
  "--port",
@@ -73,9 +81,8 @@ async function startAnvil(chainId) {
73
81
  anvil
74
82
  };
75
83
  }
76
- /** `file`: the .sol it is in, when that isn't `name`.sol. */
77
- function artifact(name, file = name) {
78
- const json = JSON.parse(readFileSync(`${CONTRACTS}/out/${file}.sol/${name}.json`, "utf-8"));
84
+ function artifact(name) {
85
+ const json = JSON.parse(readFileSync(`${CONTRACTS}/out/${name}.sol/${name}.json`, "utf-8"));
79
86
  return {
80
87
  abi: json.abi,
81
88
  bytecode: json.bytecode.object
@@ -90,7 +97,7 @@ function e2eStorage() {
90
97
  }
91
98
  /**
92
99
  * A fresh anvil with the contracts deployed from source, each behind its
93
- * ERC-1967 proxy as Deploy.s.sol does, and wired to each other.
100
+ * ERC-1967 proxy as Deploy.s.sol does, and wired to each other. Fees are zero.
94
101
  * Call `stop` from `afterAll`.
95
102
  */
96
103
  async function chainNetwork() {
@@ -108,8 +115,8 @@ async function chainNetwork() {
108
115
  transport: http(rpcUrl)
109
116
  }).extend(publicActions).extend(walletActions);
110
117
  const admin = privateKeyToAccount(ADMIN_KEY);
111
- const deploy = async (name, args, file) => {
112
- const { abi, bytecode } = artifact(name, file);
118
+ const deploy = async (name, args) => {
119
+ const { abi, bytecode } = artifact(name);
113
120
  const hash = await chain.deployContract({
114
121
  account: admin,
115
122
  abi,
@@ -121,27 +128,34 @@ async function chainNetwork() {
121
128
  return getAddress(contractAddress);
122
129
  };
123
130
  const proxied = async (name, init) => deploy("ERC1967Proxy", [await deploy(name, []), init]);
124
- const data = await proxied("DataRegistry", encodeFunctionData({
125
- abi: DATA_REGISTRY_ABI,
126
- functionName: "initialize",
127
- args: [admin.address]
128
- }));
129
- const usdc = await deploy("MockUSDC", [], "Mocks");
130
- const settlement = await proxied("SettlementRegistry", encodeFunctionData({
131
- abi: SETTLEMENT_REGISTRY_ABI,
131
+ const apps = await proxied("AppRegistry", encodeFunctionData({
132
+ abi: APP_REGISTRY_ABI,
132
133
  functionName: "initialize",
133
134
  args: [
134
135
  admin.address,
135
- usdc,
136
- await deploy("MockSemaphore", [], "Mocks")
136
+ NO_TOKEN,
137
+ 0n,
138
+ 30n * 24n * 3600n
137
139
  ]
138
140
  }));
141
+ const data = await proxied("DataRegistry", encodeFunctionData({
142
+ abi: DATA_REGISTRY_ABI,
143
+ functionName: "initialize",
144
+ args: [admin.address, apps]
145
+ }));
146
+ await chain.waitForTransactionReceipt({ hash: await chain.writeContract({
147
+ account: admin,
148
+ address: apps,
149
+ abi: APP_REGISTRY_ABI,
150
+ functionName: "setDataRegistry",
151
+ args: [data]
152
+ }) });
139
153
  const config = {
140
154
  ...FangornConfig,
141
155
  rpcUrl,
156
+ appRegistryContractAddress: apps,
142
157
  dataRegistryContractAddress: data,
143
- settlementRegistryContractAddress: settlement,
144
- fromBlock: 0n
158
+ appRegistryFromBlock: 0n
145
159
  };
146
160
  const storage = e2eStorage();
147
161
  /** A wallet with gas: `sk`, or a new one. */
@@ -152,24 +166,37 @@ async function chainNetwork() {
152
166
  });
153
167
  return sk;
154
168
  };
155
- /** A client with gas. */
156
- const client = async (sk) => Fangorn.create({
169
+ /** A client and nothing more: no app claimed or accepted into. */
170
+ const raw = async (app, sk) => Fangorn.create({
157
171
  privateKey: await wallet(sk),
158
172
  config,
173
+ appId: app,
159
174
  storage: { backend: storage }
160
175
  });
176
+ const owners = /* @__PURE__ */ new Map();
161
177
  return {
162
178
  name: "chain",
163
179
  storage,
164
180
  config,
165
181
  chain,
166
- usdc,
182
+ adminKey: ADMIN_KEY,
167
183
  wallet,
168
- client,
184
+ raw,
185
+ owner: (app = TEST_APP) => owners.get(app),
186
+ async client(app = TEST_APP, sk) {
187
+ const f = await raw(app ?? void 0, sk);
188
+ if (app === null) return f;
189
+ const owner = owners.get(app);
190
+ if (!owner) {
191
+ await f.getAppRegistry().registerApp();
192
+ owners.set(app, f);
193
+ } else await owner.getAppRegistry().acceptPublisher(f.getAddress());
194
+ return f;
195
+ },
169
196
  clock: () => chain.getBlockNumber({ cacheTime: 0 }),
170
197
  stop: () => anvil.kill()
171
198
  };
172
199
  }
173
200
 
174
201
  //#endregion
175
- export { MemLedger, MemRegistry, chainNetwork, memoryNetwork, skipChain };
202
+ export { MemLedger, MemRegistry, TEST_APP, chainNetwork, memoryNetwork, skipChain };
@@ -1,17 +1,21 @@
1
- import { Registry } from "../contracts/data-registry/index.js";
2
- import "../contracts/index.js";
1
+ import { AppConfig } from "../config.js";
2
+ import { Registry } from "../registry.js";
3
3
  import { MetadataStorage } from "../providers/storage/types.js";
4
- import { NetworkConfig } from "../config.js";
5
4
  import { Hex, PublicClient, WalletClient } from "viem";
6
5
 
7
6
  //#region src/types/index.d.ts
8
7
  interface FangornContext {
9
- config: NetworkConfig;
8
+ config: AppConfig;
10
9
  walletClient: WalletClient;
11
10
  publicClient: PublicClient;
12
11
  metadataStorage: MetadataStorage | undefined;
13
- /** Heads and the update log (WHITEPAPER_1 §3.2). */
12
+ /** Heads, membership, exclusions and logs (WHITEPAPER_1 §3.2). */
14
13
  registry: Registry;
14
+ /**
15
+ * The app this client reads and publishes under (the paper's context). Unset,
16
+ * reads are each publisher's latest head, and hosted uploads are refused.
17
+ */
18
+ appId: Hex | undefined;
15
19
  }
16
20
  type StorageConfig = {
17
21
  pinata: {
@@ -28,7 +32,8 @@ type StorageConfig = {
28
32
  };
29
33
  interface FangornCreateOptions {
30
34
  storage?: StorageConfig;
31
- config?: NetworkConfig;
35
+ config?: AppConfig;
36
+ appId?: string;
32
37
  privateKey?: Hex;
33
38
  walletClient?: WalletClient;
34
39
  registry?: Registry;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fangorn-network/sdk",
3
- "version": "0.1.0-dev",
3
+ "version": "0.1.0",
4
4
  "description": "decentralized, verifiable and platformless content management framework",
5
5
  "repository": {
6
6
  "type": "git",
package/lib/cli/sell.d.ts DELETED
@@ -1,28 +0,0 @@
1
- import { RecordInput } from "../engine/index.js";
2
- import { Fangorn } from "../fangorn.js";
3
-
4
- //#region src/cli/sell.d.ts
5
- interface SellOptions {
6
- /** Payload fields to seal. A record with none of them is left as it is. */
7
- fields: string[];
8
- /** USDC base units (6 decimals). */
9
- price: bigint;
10
- /** The referrer's share, 0..10000. Through Barliman the referrer is Fangorn's treasury. */
11
- shareBps: number;
12
- /** Unix seconds after which the terms can't be bought. */
13
- deadline: bigint;
14
- /** Key server for a new deposit; the deposit names it for good. An existing deposit keeps its own. */
15
- keyServer?: string;
16
- }
17
- /**
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.
21
- *
22
- * The deposit is read from the repo's on-chain head. Commit and push this before sealing more:
23
- * a second call before the push makes a second deposit, and the first commit's fields would
24
- * only open under the deposit it replaced.
25
- */
26
- declare function sealRecords(fangorn: Fangorn, repo: string, records: RecordInput[], o: SellOptions): Promise<RecordInput[]>;
27
- //#endregion
28
- export { SellOptions, sealRecords };
package/lib/cli/sell.js DELETED
@@ -1,95 +0,0 @@
1
- import { repoId } from "../contracts/data-registry/index.js";
2
- import { WHOLE_REPO, recordKey, termsToJson } from "../contracts/settlement-registry/index.js";
3
- import { makeDeposit, newRepoKey, requestKey, sealField } from "../crypto/paid.js";
4
- import { hexToBytes } from "viem";
5
-
6
- //#region src/cli/sell.ts
7
- /**
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.
11
- *
12
- * The deposit is read from the repo's on-chain head. Commit and push this before sealing more:
13
- * a second call before the push makes a second deposit, and the first commit's fields would
14
- * only open under the deposit it replaced.
15
- */
16
- async function sealRecords(fangorn, repo, records, o) {
17
- const settlement = fangorn.getSettlementRegistry();
18
- const publisher = fangorn.getAddress();
19
- const rid = repoId(repo);
20
- const generation = await settlement.generationOf(publisher, rid);
21
- const scope = {
22
- chainId: fangorn.getConfig().chain.id,
23
- registry: settlement.getAddress(),
24
- publisher,
25
- repo: rid,
26
- generation
27
- };
28
- const depositId = `@deposit/${generation.toString()}`;
29
- const wallet = fangorn.getWalletClient();
30
- const signer = { signMessage: (m) => wallet.signMessage({
31
- account: wallet.account ?? publisher,
32
- ...m
33
- }) };
34
- const out = [];
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 {
43
- if (!o.keyServer) throw new Error("no key server: pass keyServer (CLI: --key-server)");
44
- const res = await fetch(`${o.keyServer}/pubkey`);
45
- if (!res.ok) throw new Error(`key server ${o.keyServer}/pubkey: HTTP ${res.status.toString()}`);
46
- const { pubkey } = await res.json();
47
- kRepo = newRepoKey();
48
- const deposit = makeDeposit({
49
- kRepo,
50
- keyServerPubkey: hexToBytes(pubkey),
51
- keyServer: o.keyServer,
52
- scope
53
- });
54
- out.push({
55
- id: depositId,
56
- type: "deposit",
57
- payload: deposit
58
- });
59
- }
60
- const enc = new TextEncoder();
61
- for (const r of records) {
62
- const payload = { ...r.payload };
63
- const paid = o.fields.filter((f) => f in payload);
64
- if (!paid.length) {
65
- out.push(r);
66
- continue;
67
- }
68
- if (!r.id) throw new Error(`a record with paid fields needs an id (type ${r.type})`);
69
- const key = recordKey(r.id);
70
- for (const field of paid) payload[field] = await sealField({
71
- plaintext: enc.encode(JSON.stringify(payload[field])),
72
- kRepo,
73
- scope,
74
- key,
75
- field,
76
- storage: fangorn.getStorage()
77
- });
78
- payload["@terms"] = termsToJson(await settlement.signTerms({
79
- repo: rid,
80
- key,
81
- price: o.price,
82
- shareBps: o.shareBps,
83
- deadline: o.deadline,
84
- generation
85
- }));
86
- out.push({
87
- ...r,
88
- payload
89
- });
90
- }
91
- return out;
92
- }
93
-
94
- //#endregion
95
- export { sealRecords };
@@ -1,19 +0,0 @@
1
- import { RecordInput } from "../engine/index.js";
2
-
3
- //#region src/cli/stage.d.ts
4
- interface Staged {
5
- records: RecordInput[];
6
- deletes: string[];
7
- }
8
- interface StageOpts {
9
- type?: string;
10
- idColumn?: string;
11
- }
12
- /** RFC 4180 CSV → one object per row, keyed by the header. */
13
- declare function parseCsv(text: string): Record<string, string>[];
14
- /** Files under `path` (file or dir) as root-relative posix paths; dot entries skipped. */
15
- declare function walk(root: string, path: string): string[];
16
- /** One file → records. null for binary files (no text to stage). */
17
- declare function fileToRecords(root: string, rel: string, opts: StageOpts): Staged | null;
18
- //#endregion
19
- export { StageOpts, Staged, fileToRecords, parseCsv, walk };
package/lib/cli/stage.js DELETED
@@ -1,94 +0,0 @@
1
- import { readFileSync, readdirSync, statSync } from "fs";
2
- import { basename, extname, join, relative, sep } from "path";
3
-
4
- //#region src/cli/stage.ts
5
- /** RFC 4180 CSV → one object per row, keyed by the header. */
6
- function parseCsv(text) {
7
- const rows = [];
8
- let row = [];
9
- let field = "";
10
- let quoted = false;
11
- for (let i = 0; i < text.length; i++) {
12
- const c = text[i];
13
- if (quoted) if (c === "\"" && text[i + 1] === "\"") field += text[++i];
14
- else if (c === "\"") quoted = false;
15
- else field += c;
16
- else if (c === "\"") quoted = true;
17
- else if (c === ",") {
18
- row.push(field);
19
- field = "";
20
- } else if (c === "\n" || c === "\r") {
21
- if (c === "\r" && text[i + 1] === "\n") i++;
22
- row.push(field);
23
- rows.push(row);
24
- row = [];
25
- field = "";
26
- } else field += c;
27
- }
28
- if (field || row.length) rows.push([...row, field]);
29
- const [header = [], ...body] = rows;
30
- return body.map((r) => Object.fromEntries(header.map((h, i) => [h, r[i] ?? ""])));
31
- }
32
- const safeId = (s) => s.replace(/[^\x21-\x7e]/g, "_");
33
- /** Files under `path` (file or dir) as root-relative posix paths; dot entries skipped. */
34
- 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(".")));
41
- }
42
- /** One file → records. null for binary files (no text to stage). */
43
- function fileToRecords(root, rel, opts) {
44
- const bytes = readFileSync(join(root, rel));
45
- if (bytes.subarray(0, 8192).includes(0)) return null;
46
- const text = bytes.toString("utf-8");
47
- const ext = extname(rel).toLowerCase();
48
- const type = opts.type ?? basename(rel, extname(rel));
49
- const idCol = opts.idColumn ?? "id";
50
- const many = (rows) => ({
51
- records: rows.map((payload, i) => {
52
- const id = payload[idCol];
53
- return {
54
- id: safeId((typeof id === "string" || typeof id === "number") && id !== "" ? String(id) : `${rel}#${(i + 1).toString()}`),
55
- type,
56
- payload
57
- };
58
- }),
59
- deletes: []
60
- });
61
- if (ext === ".csv") return many(parseCsv(text));
62
- if (ext === ".jsonl" || ext === ".ndjson") return many(text.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l)));
63
- if (ext === ".json") {
64
- const data = JSON.parse(text);
65
- if (Array.isArray(data)) return many(data);
66
- const obj = data;
67
- if (Array.isArray(obj.records) || Array.isArray(obj.deletes)) return {
68
- records: obj.records ?? [],
69
- deletes: obj.deletes ?? []
70
- };
71
- return {
72
- records: [{
73
- id: safeId(rel),
74
- type,
75
- payload: data
76
- }],
77
- deletes: []
78
- };
79
- }
80
- return {
81
- records: [{
82
- id: safeId(rel),
83
- type: opts.type ?? "file",
84
- payload: {
85
- path: rel,
86
- text
87
- }
88
- }],
89
- deletes: []
90
- };
91
- }
92
-
93
- //#endregion
94
- export { fileToRecords, parseCsv, walk };