@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
@@ -1,68 +0,0 @@
1
- import { SchemaRegistry } from "../../registries/schema-registry/index.js";
2
- import { MetadataStorage } from "../../providers/storage/types.js";
3
- import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
4
- import { BundleManifest, FieldInput, HydratedBundle, Manifest, ManifestEntry, PublishRecord } from "./types.js";
5
- import { BaseManifest, BuildContext, ChunkDraft, ChunkRef, ManifestBuilder, ResolvedSchemaShape } from "./builders/types.js";
6
- import { RecordSetBuilder, RecordSetInput } from "./builders/record-set.js";
7
- import { BundleBuilder, BundleUploadInput } from "./builders/bundle.js";
8
- import { Address, Hex, WalletClient } from "viem";
9
-
10
- //#region src/roles/publisher/index.d.ts
11
-
12
- interface CommitResult {
13
- manifestUri: string;
14
- schemaId: Hex;
15
- owner: Address;
16
- entryCount: number;
17
- }
18
- declare class PublisherRole {
19
- private readonly dataSourceRegistry;
20
- private readonly schemaRegistry;
21
- private readonly storage;
22
- private readonly walletClient;
23
- private readonly schemaCache;
24
- constructor(dataSourceRegistry: DataSourceRegistry, schemaRegistry: SchemaRegistry, storage: MetadataStorage, walletClient: WalletClient);
25
- publish<TIn, TMan extends {
26
- kind: string;
27
- schemaId: Hex;
28
- root: Hex;
29
- tree: Hex[][];
30
- }>(params: {
31
- schemaName: string;
32
- builder: ManifestBuilder<TIn, TMan>;
33
- input: TIn;
34
- datasetName?: string;
35
- concurrency?: number;
36
- }): Promise<CommitResult>;
37
- publishRecords(params: {
38
- records: PublishRecord[] | AsyncIterable<PublishRecord>;
39
- schemaName: string;
40
- chunkSize?: number;
41
- concurrency?: number;
42
- datasetName?: string;
43
- }): Promise<CommitResult>;
44
- publishBundle(params: {
45
- bundleName: string;
46
- nodes: {
47
- id: string;
48
- type: string;
49
- fields: Record<string, FieldInput>;
50
- }[];
51
- edges?: {
52
- rel: string;
53
- from: string;
54
- to: string;
55
- }[];
56
- datasetName?: string;
57
- concurrency?: number;
58
- }): Promise<CommitResult>;
59
- readBundle(manifest: BundleManifest): Promise<HydratedBundle>;
60
- getManifest(schemaName: string, datasetName: string): Promise<Manifest | undefined>;
61
- getEntry(schemaName: string, datasetName: string, recordName: string): Promise<ManifestEntry>;
62
- getBundleManifestByCid(manifestCid: string): Promise<BundleManifest | undefined>;
63
- getBundleManifest(bundleName: string, datasetName: string): Promise<BundleManifest | undefined>;
64
- private resolveSchema;
65
- private requireAccount;
66
- }
67
- //#endregion
68
- export { type BaseManifest, type BuildContext, BundleBuilder, type BundleUploadInput, type ChunkDraft, type ChunkRef, CommitResult, type ManifestBuilder, PublisherRole, RecordSetBuilder, type RecordSetInput, type ResolvedSchemaShape };
@@ -1,179 +0,0 @@
1
- import { MerkleTree } from "../../registries/datasource-registry/index.js";
2
- import { RecordSetBuilder } from "./builders/record-set.js";
3
- import { BundleBuilder } from "./builders/bundle.js";
4
-
5
- //#region src/roles/publisher/index.ts
6
- var PublisherRole = class {
7
- schemaCache = /* @__PURE__ */ new Map();
8
- constructor(dataSourceRegistry, schemaRegistry, storage, walletClient) {
9
- this.dataSourceRegistry = dataSourceRegistry;
10
- this.schemaRegistry = schemaRegistry;
11
- this.storage = storage;
12
- this.walletClient = walletClient;
13
- }
14
- async publish(params) {
15
- const { schemaName, builder, input, datasetName, concurrency = 10 } = params;
16
- const { schema, schemaId } = await this.resolveSchema(schemaName);
17
- await builder.validate(schema, input);
18
- const chunks = [];
19
- const inFlight = /* @__PURE__ */ new Set();
20
- let firstErr;
21
- let idx = 0n;
22
- for await (const draft of builder.chunk(input, schema)) {
23
- if (firstErr) break;
24
- const myIdx = idx++;
25
- const task = (async () => {
26
- const cid = await this.storage.put(draft.data, { name: draft.name });
27
- chunks.push({
28
- index: myIdx,
29
- cid,
30
- name: draft.name,
31
- meta: draft.meta
32
- });
33
- })().catch((e) => {
34
- firstErr ??= e;
35
- });
36
- inFlight.add(task);
37
- task.finally(() => inFlight.delete(task));
38
- while (inFlight.size >= concurrency) await Promise.race(inFlight);
39
- }
40
- await Promise.all(inFlight);
41
- if (firstErr !== void 0) throw firstErr;
42
- if (chunks.length === 0) throw new Error("builder produced no chunks");
43
- chunks.sort((a, b) => builder.compareChunks(a, b));
44
- const leafInputs = chunks.map((c) => ({
45
- index: c.index,
46
- name: c.cid
47
- }));
48
- const leaves = leafInputs.map((l) => MerkleTree.rootToHex(MerkleTree.leafHash(l)));
49
- const { root, layers } = MerkleTree.buildTree(leafInputs);
50
- const context = {
51
- schemaId,
52
- chunks,
53
- leaves,
54
- root: MerkleTree.rootToHex(root),
55
- layers: layers.map((layer) => layer.map((r) => MerkleTree.rootToHex(r)))
56
- };
57
- const manifest = builder.assemble(context, input, schema);
58
- const owner = this.requireAccount();
59
- const manifestCid = await this.storage.put(manifest, { name: `manifest:${builder.kind}:${schemaId}:${Date.now().toString()}` });
60
- const ds = datasetName ?? `${schemaId}:${owner}`;
61
- await this.dataSourceRegistry.publish(manifestCid, context.root, schemaId, ds);
62
- return {
63
- manifestUri: manifestCid,
64
- schemaId,
65
- owner,
66
- entryCount: chunks.length
67
- };
68
- }
69
- async publishRecords(params) {
70
- return this.publish({
71
- schemaName: params.schemaName,
72
- builder: new RecordSetBuilder(),
73
- input: {
74
- records: params.records,
75
- chunkSize: params.chunkSize
76
- },
77
- datasetName: params.datasetName,
78
- concurrency: params.concurrency
79
- });
80
- }
81
- async publishBundle(params) {
82
- return this.publish({
83
- schemaName: params.bundleName,
84
- builder: new BundleBuilder(this.storage, this.schemaRegistry),
85
- input: {
86
- bundleName: params.bundleName,
87
- nodes: params.nodes,
88
- edges: params.edges
89
- },
90
- datasetName: params.datasetName,
91
- concurrency: params.concurrency
92
- });
93
- }
94
- async readBundle(manifest) {
95
- const nodeArrays = await Promise.all(manifest.nodeChunks.map((chunk) => this.storage.get(chunk.dataCid)));
96
- const edges = await this.storage.get(manifest.edgeChunk.dataCid);
97
- const nodesById = /* @__PURE__ */ new Map();
98
- for (const nodes of nodeArrays) for (const node of nodes) nodesById.set(node.id, node);
99
- return {
100
- nodesById,
101
- edges
102
- };
103
- }
104
- async getManifest(schemaName, datasetName) {
105
- const schemaId = (await this.resolveSchema(schemaName)).schemaId;
106
- const owner = this.requireAccount();
107
- try {
108
- const ds = await this.dataSourceRegistry.get(owner, schemaId, datasetName);
109
- if (!ds.manifestCid) return void 0;
110
- return await this.storage.get(ds.manifestCid);
111
- } catch {
112
- return;
113
- }
114
- }
115
- async getEntry(schemaName, datasetName, recordName) {
116
- const manifest = await this.getManifest(schemaName, datasetName);
117
- if (!manifest) throw new Error(`No manifest found for schema ${schemaName} under dataset ${datasetName}`);
118
- for (const chunkEntry of manifest.entries) {
119
- const dataCid = chunkEntry.fields.dataCid;
120
- if (typeof dataCid !== "string") continue;
121
- try {
122
- const found = (await this.storage.get(dataCid)).find((r) => r.name === recordName);
123
- if (found) return found;
124
- } catch {
125
- continue;
126
- }
127
- }
128
- throw new Error(`Entry "${recordName}" not found in dataset ${datasetName}`);
129
- }
130
- async getBundleManifestByCid(manifestCid) {
131
- try {
132
- const manifest = await this.storage.get(manifestCid);
133
- if (manifest.kind !== "bundle") return void 0;
134
- return manifest;
135
- } catch {
136
- return;
137
- }
138
- }
139
- async getBundleManifest(bundleName, datasetName) {
140
- const bundleSchemaId = await this.schemaRegistry.schemaId(bundleName);
141
- const owner = this.requireAccount();
142
- try {
143
- const ds = await this.dataSourceRegistry.get(owner, bundleSchemaId, datasetName);
144
- if (!ds.manifestCid) return void 0;
145
- return await this.getBundleManifestByCid(ds.manifestCid);
146
- } catch {
147
- return;
148
- }
149
- }
150
- resolveSchema(name) {
151
- if (!this.schemaCache.has(name)) {
152
- const p = Promise.all([this.schemaRegistry.getSchema(name), this.schemaRegistry.schemaId(name)]).then(async ([{ specCid }, schemaId]) => {
153
- const blob = await this.storage.get(specCid);
154
- const schema = blob.bundle ?? (blob.definition ? {
155
- fields: blob.definition,
156
- types: blob.types
157
- } : void 0);
158
- if (!schema) throw new Error(`schema "${name}" has neither definition nor bundle`);
159
- return {
160
- schema,
161
- schemaId
162
- };
163
- }).catch((err) => {
164
- this.schemaCache.delete(name);
165
- throw err;
166
- });
167
- this.schemaCache.set(name, p);
168
- }
169
- return this.schemaCache.get(name);
170
- }
171
- requireAccount() {
172
- const address = this.walletClient.account?.address;
173
- if (!address) throw new Error("No account connected");
174
- return address;
175
- }
176
- };
177
-
178
- //#endregion
179
- export { BundleBuilder, PublisherRole, RecordSetBuilder };
@@ -1,114 +0,0 @@
1
- import { Hex } from "viem";
2
-
3
- //#region src/roles/publisher/types.d.ts
4
- type FieldInput = null | string | number | boolean | Uint8Array | string[] | number[] | boolean[] | null[] | FieldInputObject | FieldInputObject[] | HandleFieldInput | HandleArray;
5
- interface FieldInputObject {
6
- [key: string]: FieldInput;
7
- }
8
- interface HandleArray {
9
- "@type": "array";
10
- items: HandleFieldInput[];
11
- }
12
- interface ResolvedHandleArray {
13
- "@type": "array";
14
- items: ResolvedHandleField[];
15
- }
16
- interface HandleFieldInput {
17
- "@type": "handle";
18
- uri: string;
19
- workerUrl: string;
20
- encryption?: {
21
- gadget: string;
22
- ciphertextHash: string;
23
- teePubkey?: string;
24
- };
25
- }
26
- /**
27
- * One schema-conformant record to publish.
28
- * `name` uniquely identifies this record within (owner, schemaId) —
29
- * it maps to the resourceId in the SettlementRegistry.
30
- */
31
- interface PublishRecord {
32
- name: string;
33
- fields: Record<string, FieldInput>;
34
- }
35
- /**
36
- * wait do I really even need this?
37
- * Resolved manifest fields
38
- */
39
- interface ResolvedHandleField {
40
- "@type": "handle";
41
- uri: string;
42
- workerUrl: string;
43
- encryption?: {
44
- gadget: string;
45
- ciphertextHash: string;
46
- teePubkey?: string;
47
- };
48
- }
49
- type ResolvedPlainField = null | string | number | boolean | Uint8Array | string[] | number[] | boolean[] | null[] | ResolvedObject | ResolvedObject[];
50
- interface ResolvedObject {
51
- [key: string]: ResolvedPlainField;
52
- }
53
- type ResolvedField = ResolvedPlainField | ResolvedHandleField | ResolvedHandleArray;
54
- interface ManifestLeaf {
55
- index: bigint;
56
- name: string;
57
- }
58
- interface ManifestEntry {
59
- name: string;
60
- fields: Record<string, unknown>;
61
- }
62
- /**
63
- * Dataset manifest
64
- */
65
- interface Manifest {
66
- kind: "record-set";
67
- schemaId: Hex;
68
- /**
69
- * Poseidon2 Merkle root
70
- */
71
- root: Hex;
72
- /**
73
- * Entire dataset
74
- */
75
- entries: ManifestEntry[];
76
- /**
77
- * Full Merkle tree layers
78
- *
79
- * layer[0] = leaves
80
- * layer[last][0] = root
81
- */
82
- tree: Hex[][];
83
- }
84
- interface BundleManifest {
85
- kind: "bundle";
86
- schemaId: Hex;
87
- root: Hex;
88
- nodeChunks: {
89
- type: string;
90
- dataCid: string;
91
- leaf: Hex;
92
- }[];
93
- edgeChunk: {
94
- dataCid: string;
95
- leaf: Hex;
96
- };
97
- tree: Hex[][];
98
- }
99
- interface BundleNode {
100
- id: string;
101
- type: string;
102
- fields: Record<string, ResolvedField>;
103
- }
104
- interface BundleEdge {
105
- rel: string;
106
- from: string;
107
- to: string;
108
- }
109
- interface HydratedBundle {
110
- nodesById: Map<string, BundleNode>;
111
- edges: BundleEdge[];
112
- }
113
- //#endregion
114
- export { BundleEdge, BundleManifest, BundleNode, FieldInput, FieldInputObject, HandleArray, HandleFieldInput, HydratedBundle, Manifest, ManifestEntry, ManifestLeaf, PublishRecord, ResolvedField, ResolvedHandleArray, ResolvedHandleField, ResolvedObject, ResolvedPlainField };
@@ -1 +0,0 @@
1
- export { };
@@ -1,44 +0,0 @@
1
- import { SchemaRegistry } from "../../registries/schema-registry/index.js";
2
- import { MetadataStorage } from "../../providers/storage/types.js";
3
- import { BundleInput, BundleSchemaBlob, BundleShape, Constraint, EdgeShape, EncryptedField, FieldDefinition, FieldType, HandleField, NullableType, PlainField, ResolvedBundle, ResolverSchemaBlob, ScalarType, SchemaBlob, SchemaDefinition, SchemaDoc, SchemaKind, SchemaRoleConfig, TypeDefinition } from "./types.js";
4
- import { Hex, WalletClient } from "viem";
5
-
6
- //#region src/roles/schema/index.d.ts
7
- type RegisterSchemaParams = {
8
- kind?: "resolver";
9
- name: string;
10
- definition: SchemaDefinition;
11
- types?: Record<string, TypeDefinition>;
12
- } | {
13
- kind: "bundle";
14
- name: string;
15
- bundle: BundleInput;
16
- };
17
- interface RegisteredSchemaBase {
18
- schemaId: Hex;
19
- schemaCid: string;
20
- name: string;
21
- owner: Hex;
22
- }
23
- type RegisteredSchema = (RegisteredSchemaBase & {
24
- kind: "resolver";
25
- definition: SchemaDefinition;
26
- types?: Record<string, TypeDefinition>;
27
- }) | (RegisteredSchemaBase & {
28
- kind: "bundle";
29
- bundle: ResolvedBundle;
30
- });
31
- declare class SchemaRole {
32
- private readonly schemaRegistry;
33
- private readonly storage;
34
- private readonly walletClient;
35
- constructor(schemaRegistry: SchemaRegistry, storage: MetadataStorage, walletClient: WalletClient);
36
- register(params: RegisterSchemaParams): Promise<RegisteredSchema>;
37
- get(nameOrId: string): Promise<RegisteredSchema | undefined>;
38
- /** Resolve node refs → registered resolver schemaIds and enforce edge closure. */
39
- private resolveBundle;
40
- validate(data: Record<string, unknown>, definition: SchemaDefinition | SchemaDoc): string[];
41
- private requireAccount;
42
- }
43
- //#endregion
44
- export { BundleInput, BundleSchemaBlob, BundleShape, Constraint, EdgeShape, EncryptedField, FieldDefinition, FieldType, HandleField, NullableType, PlainField, RegisterSchemaParams, RegisteredSchema, ResolvedBundle, ResolverSchemaBlob, ScalarType, SchemaBlob, SchemaDefinition, SchemaDoc, SchemaKind, SchemaRole, SchemaRoleConfig, TypeDefinition };
@@ -1,127 +0,0 @@
1
- import { validate } from "./validate.js";
2
-
3
- //#region src/roles/schema/index.ts
4
- var SchemaRole = class {
5
- constructor(schemaRegistry, storage, walletClient) {
6
- this.schemaRegistry = schemaRegistry;
7
- this.storage = storage;
8
- this.walletClient = walletClient;
9
- }
10
- async register(params) {
11
- const owner = this.requireAccount();
12
- const createdAt = (/* @__PURE__ */ new Date()).toISOString();
13
- let blob;
14
- if (params.kind === "bundle") {
15
- const bundle = await this.resolveBundle(params.bundle);
16
- blob = {
17
- kind: "bundle",
18
- name: params.name,
19
- owner,
20
- createdAt,
21
- bundle
22
- };
23
- } else blob = {
24
- kind: "resolver",
25
- name: params.name,
26
- owner,
27
- createdAt,
28
- definition: params.definition,
29
- types: params.types
30
- };
31
- const schemaCid = await this.storage.put(blob, { name: `schema:${params.name}` });
32
- let schemaId;
33
- try {
34
- ({schemaId} = await this.schemaRegistry.registerSchema(params.name, schemaCid));
35
- } catch (err) {
36
- if (!isSchemaAlreadyExists(err)) throw err;
37
- schemaId = await this.schemaRegistry.schemaId(params.name);
38
- }
39
- const base = {
40
- schemaId,
41
- schemaCid,
42
- name: params.name,
43
- owner
44
- };
45
- return blob.kind === "bundle" ? {
46
- kind: "bundle",
47
- ...base,
48
- bundle: blob.bundle
49
- } : {
50
- kind: "resolver",
51
- ...base,
52
- definition: blob.definition,
53
- types: blob.types
54
- };
55
- }
56
- async get(nameOrId) {
57
- try {
58
- const schemaId = await this.schemaRegistry.schemaId(nameOrId);
59
- const record = await this.schemaRegistry.getSchema(nameOrId);
60
- if (!record.specCid) return void 0;
61
- const blob = await this.storage.get(record.specCid);
62
- const base = {
63
- schemaId,
64
- schemaCid: record.specCid,
65
- name: blob.name,
66
- owner: blob.owner
67
- };
68
- if (blob.kind === "resolver") return {
69
- kind: "resolver",
70
- ...base,
71
- definition: blob.definition,
72
- types: blob.types
73
- };
74
- return {
75
- kind: "bundle",
76
- ...base,
77
- bundle: blob.bundle
78
- };
79
- } catch (e) {
80
- console.error(e);
81
- return;
82
- }
83
- }
84
- /** Resolve node refs → registered resolver schemaIds and enforce edge closure. */
85
- async resolveBundle(input) {
86
- const errors = [];
87
- if (Object.keys(input.nodes).length === 0) errors.push("bundle declares no node types");
88
- const nodes = {};
89
- await Promise.all(Object.entries(input.nodes).map(async ([typeName, ref]) => {
90
- const existing = await this.get(ref);
91
- if (!existing) errors.push(`node "${typeName}" → unknown schema "${ref}"`);
92
- else if (existing.kind !== "resolver") errors.push(`node "${typeName}" → "${ref}" is a bundle; nodes must be resolver schemas`);
93
- else nodes[typeName] = existing.schemaId;
94
- }));
95
- input.edges.forEach((e, i) => {
96
- if (!e.rel) errors.push(`edge[${i.toString()}] missing rel`);
97
- if (!(e.from in input.nodes)) errors.push(`edge[${i.toString()}] "${e.rel}" from undeclared type "${e.from}"`);
98
- if (!(e.to in input.nodes)) errors.push(`edge[${i.toString()}] "${e.rel}" to undeclared type "${e.to}"`);
99
- const min = e.min ?? 0;
100
- const max = e.max ?? null;
101
- if (min < 0) errors.push(`edge[${i.toString()}] "${e.rel}" min < 0`);
102
- if (max !== null && max < min) errors.push(`edge[${i.toString()}] "${e.rel}" max(${max.toString()}) < min(${min.toString()})`);
103
- });
104
- if (errors.length) throw new Error("Invalid bundle shape:\n" + errors.map((e) => ` - ${e}`).join("\n"));
105
- return {
106
- nodes,
107
- edges: input.edges
108
- };
109
- }
110
- validate(data, definition) {
111
- return validate(data, definition);
112
- }
113
- requireAccount() {
114
- const address = this.walletClient.account?.address;
115
- if (!address) throw new Error("No account connected to wallet client");
116
- return address;
117
- }
118
- };
119
- function isSchemaAlreadyExists(err) {
120
- if (!(err instanceof Error)) return false;
121
- const causeData = err.cause?.data;
122
- const errorData = err.data;
123
- return (causeData ?? errorData)?.errorName === "SchemaAlreadyExists";
124
- }
125
-
126
- //#endregion
127
- export { SchemaRole };
@@ -1,113 +0,0 @@
1
- import { Hex } from "viem";
2
-
3
- //#region src/roles/schema/types.d.ts
4
- type SchemaKind = "resolver" | "bundle";
5
- type SchemaDefinition = Record<string, FieldDefinition>;
6
- type ScalarType = "string" | "number" | "boolean" | "bytes";
7
- type NullableType = `${ScalarType} | null` | "array | null" | "object | null";
8
- type FieldType = ScalarType | "array" | "object" | NullableType;
9
- type PlainField = {
10
- "@type": ScalarType | NullableType;
11
- } | {
12
- "@type": "array" | "array | null";
13
- items: FieldDefinition;
14
- } | {
15
- "@type": "object" | "object | null";
16
- items: Record<string, FieldDefinition>;
17
- };
18
- interface EncryptedField {
19
- "@type": "encrypted";
20
- gadget: string;
21
- handle?: {
22
- cid: string;
23
- gateway: string;
24
- };
25
- }
26
- interface HandleField {
27
- "@type": "handle";
28
- }
29
- type Constraint = {
30
- kind: "regex";
31
- pattern: string;
32
- } | {
33
- kind: "enum";
34
- values: (string | number | boolean)[];
35
- } | {
36
- kind: "range";
37
- min?: number;
38
- max?: number;
39
- exclusive?: boolean;
40
- } | {
41
- kind: "length";
42
- min?: number;
43
- max?: number;
44
- } | {
45
- kind: "ref";
46
- type: string;
47
- };
48
- interface TypeDefinition {
49
- shape: Record<string, FieldDefinition>;
50
- constraints?: Constraint[];
51
- }
52
- interface FieldDefinition {
53
- "@type": string;
54
- "@description"?: string;
55
- constraints?: Constraint[];
56
- items?: FieldDefinition | Record<string, FieldDefinition>;
57
- }
58
- interface SchemaDoc {
59
- types?: Record<string, TypeDefinition>;
60
- fields: SchemaDefinition;
61
- }
62
- interface EdgeShape {
63
- rel: string;
64
- from: string;
65
- to: string;
66
- min?: number;
67
- max?: number | null;
68
- }
69
- /** Author-facing input: node refs are schema names OR ids. */
70
- interface BundleInput {
71
- nodes: Record<string, string>;
72
- edges: EdgeShape[];
73
- }
74
- /** Committed form: node refs resolved + pinned to schemaIds. */
75
- interface ResolvedBundle {
76
- nodes: Record<string, Hex>;
77
- edges: EdgeShape[];
78
- }
79
- /** The on-storage bundle shape (what specCid points to for a bundle). */
80
- interface BundleShape {
81
- "@kind": "bundle";
82
- bundle: ResolvedBundle;
83
- }
84
- interface SchemaBlobBase {
85
- name: string;
86
- owner: Hex;
87
- createdAt: string;
88
- }
89
- interface ResolverSchemaBlob extends SchemaBlobBase {
90
- kind: "resolver";
91
- definition: SchemaDefinition;
92
- types?: Record<string, TypeDefinition>;
93
- }
94
- interface BundleSchemaBlob extends SchemaBlobBase {
95
- kind: "bundle";
96
- bundle: ResolvedBundle;
97
- }
98
- type SchemaBlob = ResolverSchemaBlob | BundleSchemaBlob;
99
- interface SchemaRoleConfig {
100
- chainId: number;
101
- rpcUrl: string;
102
- privateKey: Hex;
103
- pinataJwt: string;
104
- /** Optional — override ERC-8004 registry addresses per chainId */
105
- registryOverrides?: Record<number, {
106
- IDENTITY: string;
107
- REPUTATION: string;
108
- }>;
109
- /** Optional — override subgraph URLs per chainId */
110
- subgraphOverrides?: Record<number, string>;
111
- }
112
- //#endregion
113
- export { BundleInput, BundleSchemaBlob, BundleShape, Constraint, EdgeShape, EncryptedField, FieldDefinition, FieldType, HandleField, NullableType, PlainField, ResolvedBundle, ResolverSchemaBlob, ScalarType, SchemaBlob, SchemaDefinition, SchemaDoc, SchemaKind, SchemaRoleConfig, TypeDefinition };
@@ -1 +0,0 @@
1
- export { };
@@ -1,9 +0,0 @@
1
- import { Constraint, SchemaDefinition, SchemaDoc } from "./types.js";
2
-
3
- //#region src/roles/schema/validate.d.ts
4
- /** Accept either the explicit document shape or a bare flat field map. */
5
- declare function normalize(schema: SchemaDoc | SchemaDefinition): SchemaDoc;
6
- declare function validate(data: Record<string, unknown>, schema: SchemaDoc | SchemaDefinition): string[];
7
- declare function applyConstraints(value: unknown, constraints: Constraint[], doc: SchemaDoc, path: string): string[];
8
- //#endregion
9
- export { applyConstraints, normalize, validate };