sapixdb-js 0.3.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.
package/README.md ADDED
@@ -0,0 +1,295 @@
1
+ # SapixDB JavaScript / TypeScript SDK
2
+
3
+ Official SDK for [SapixDB](https://sapixdb.com) — the agent-native living database.
4
+
5
+ Zero dependencies. Works in Node.js 18+, Bun, Deno, and modern browsers.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install sapixdb
11
+ # or
12
+ bun add sapixdb
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { SapixClient } from "sapixdb";
19
+
20
+ const db = new SapixClient({
21
+ url: "http://localhost:7475",
22
+ agent: "my-app",
23
+ });
24
+
25
+ // Write a record
26
+ const record = await db.collection("products").write({
27
+ name: "T-Shirt",
28
+ price: 29.99,
29
+ stock: 100,
30
+ });
31
+ console.log(record.id); // "nuc_abc123"
32
+ console.log(record.hash); // "sha3:e7f2a1..."
33
+
34
+ // Read latest records
35
+ const products = await db.collection("products").latest();
36
+
37
+ // Filter
38
+ const shirts = await db.collection("products").find({ category: "apparel" });
39
+
40
+ // Time travel — what did the DB look like yesterday?
41
+ const yesterday = await db
42
+ .collection("orders")
43
+ .asOf("2026-05-11T00:00:00Z")
44
+ .latest();
45
+ ```
46
+
47
+ ## API Reference
48
+
49
+ ### `new SapixClient(config)`
50
+
51
+ | Option | Type | Default | Description |
52
+ |--------|------|---------|-------------|
53
+ | `url` | `string` | — | SapixDB agent URL |
54
+ | `agent` | `string` | — | Agent ID (matches `SAPIX_AGENT_ID`) |
55
+ | `headers` | `Record<string,string>` | `{}` | Extra HTTP headers |
56
+ | `timeout` | `number` | `10000` | Request timeout (ms) |
57
+
58
+ ---
59
+
60
+ ### `db.collection(name)`
61
+
62
+ Returns a `CollectionClient` for the given collection name.
63
+
64
+ #### `.write(data)` → `WriteResult`
65
+
66
+ Append a new record. Nothing is ever overwritten.
67
+
68
+ ```typescript
69
+ const result = await db.collection("orders").write({
70
+ customer_id: "cust_001",
71
+ total: 149.99,
72
+ status: "placed",
73
+ });
74
+ // result.id — nucleotide ID
75
+ // result.hash — cryptographic fingerprint
76
+ // result.timestamp — ISO 8601 timestamp
77
+ ```
78
+
79
+ #### `.writeBatch(records[])` → `WriteResult[]`
80
+
81
+ Write multiple records in parallel.
82
+
83
+ ```typescript
84
+ await db.collection("products").writeBatch([
85
+ { name: "T-Shirt", price: 29.99 },
86
+ { name: "Sneakers", price: 89.99 },
87
+ ]);
88
+ ```
89
+
90
+ #### `.get(id)` → `NucleotideRecord`
91
+
92
+ Fetch a single record by its nucleotide ID.
93
+
94
+ ```typescript
95
+ const record = await db.collection("orders").get("nuc_abc123");
96
+ console.log(record.data.status); // "placed"
97
+ ```
98
+
99
+ #### `.latest(options?)` → `NucleotideRecord[]`
100
+
101
+ Fetch the latest version of every record in the collection.
102
+
103
+ #### `.history(options?)` → `NucleotideRecord[]`
104
+
105
+ Fetch ALL versions — the full append-only history.
106
+
107
+ #### `.find(filter, options?)` → `NucleotideRecord[]`
108
+
109
+ Find records matching a filter (latest version only).
110
+
111
+ ```typescript
112
+ const pending = await db.collection("orders").find({ status: "pending" });
113
+ ```
114
+
115
+ #### `.findOne(filter)` → `NucleotideRecord | null`
116
+
117
+ Find the first matching record, or `null`.
118
+
119
+ #### `.asOf(timestamp)` → `CollectionQuery`
120
+
121
+ Scope all subsequent reads to a specific point in time.
122
+
123
+ ```typescript
124
+ // What did Alice's record look like 2 hours ago?
125
+ const snapshot = await db
126
+ .collection("users")
127
+ .asOf("2026-05-12T08:00:00Z")
128
+ .find({ name: "Alice" });
129
+ ```
130
+
131
+ ---
132
+
133
+ ### `db.graph`
134
+
135
+ #### `.relate(src, dst, type, weight?)` → `void`
136
+
137
+ Create a typed directed edge between two records.
138
+
139
+ ```typescript
140
+ await db.graph.relate(orderId, customerId, "placed_by");
141
+ await db.graph.relate(productId, categoryId, "belongs_to");
142
+ await db.graph.relate(managerId, reportId, "manages", 1.0);
143
+ ```
144
+
145
+ #### `.addEdge(edge)` → `void`
146
+
147
+ Full edge creation with all options.
148
+
149
+ ```typescript
150
+ await db.graph.addEdge({
151
+ src: "nuc_abc123",
152
+ dst: "nuc_def456",
153
+ edge_type: "manages",
154
+ weight: 1.0,
155
+ });
156
+ ```
157
+
158
+ #### `.traverse(fromId, options?)` → `TraverseResult`
159
+
160
+ Walk the graph from a starting node.
161
+
162
+ ```typescript
163
+ const { nodes, edges } = await db.graph.traverse("nuc_abc123", {
164
+ depth: 3,
165
+ direction: "outbound", // "outbound" | "inbound" | "both"
166
+ });
167
+ ```
168
+
169
+ #### `.neighbors(id, direction?)` → `NucleotideRecord[]`
170
+
171
+ Get direct neighbours of a node.
172
+
173
+ ---
174
+
175
+ ### `db.ingest(collection, data)` → `WriteResult`
176
+
177
+ Write via the ingest endpoint — designed for AI agents, webhooks, and automated pipelines.
178
+
179
+ ```typescript
180
+ await db.ingest("ai_decisions", {
181
+ model: "gpt-4o",
182
+ action: "approve_loan",
183
+ confidence: 0.94,
184
+ reasoning: "Credit score 780, DTI 28%",
185
+ });
186
+ ```
187
+
188
+ ---
189
+
190
+ ### `db.health()` / `db.ping()`
191
+
192
+ ```typescript
193
+ const { status, agent } = await db.health(); // throws on failure
194
+ const alive = await db.ping(); // returns true/false, never throws
195
+ ```
196
+
197
+ ---
198
+
199
+ ## TypeScript Generics
200
+
201
+ Pass your type as a generic to get full autocomplete and type checking:
202
+
203
+ ```typescript
204
+ interface Product {
205
+ name: string;
206
+ price: number;
207
+ stock: number;
208
+ category?: string;
209
+ }
210
+
211
+ const products = db.collection<Product>("products");
212
+
213
+ const result = await products.write({ name: "T-Shirt", price: 29.99, stock: 100 });
214
+ const items = await products.latest();
215
+ // items[0].data.price is typed as number ✓
216
+ ```
217
+
218
+ ---
219
+
220
+ ## Error Handling
221
+
222
+ ```typescript
223
+ import { SapixError, SapixNetworkError, SapixNotFoundError } from "sapixdb";
224
+
225
+ try {
226
+ const record = await db.collection("orders").get("nuc_missing");
227
+ } catch (err) {
228
+ if (err instanceof SapixNotFoundError) {
229
+ console.log("Record does not exist");
230
+ } else if (err instanceof SapixNetworkError) {
231
+ console.log("Cannot reach SapixDB — is it running?");
232
+ } else if (err instanceof SapixError) {
233
+ console.log(`SapixDB error ${err.status}: ${err.message}`);
234
+ }
235
+ }
236
+ ```
237
+
238
+ ---
239
+
240
+ ## Full Example: Online Store
241
+
242
+ ```typescript
243
+ import { SapixClient } from "sapixdb";
244
+
245
+ const db = new SapixClient({ url: "http://localhost:7475", agent: "store" });
246
+
247
+ // ── 1. Add products ───────────────────────────────────────────────
248
+ const shirt = await db.collection("products").write({
249
+ sku: "SHIRT-001", name: "Classic T-Shirt", price: 29.99, stock: 200,
250
+ });
251
+ const shoes = await db.collection("products").write({
252
+ sku: "SHOE-042", name: "Running Sneakers", price: 89.99, stock: 50,
253
+ });
254
+
255
+ // ── 2. Register a customer ────────────────────────────────────────
256
+ const customer = await db.collection("customers").write({
257
+ name: "Alice Johnson", email: "alice@example.com", tier: "standard",
258
+ });
259
+
260
+ // ── 3. Place an order ─────────────────────────────────────────────
261
+ const order = await db.collection("orders").write({
262
+ customer_id: customer.id,
263
+ items: [
264
+ { product_id: shirt.id, qty: 2, unit_price: 29.99 },
265
+ { product_id: shoes.id, qty: 1, unit_price: 89.99 },
266
+ ],
267
+ total: 149.97,
268
+ status: "placed",
269
+ });
270
+
271
+ // Link order → customer in the graph
272
+ await db.graph.relate(order.id, customer.id, "placed_by");
273
+
274
+ // ── 4. Ship the order (append, never overwrite) ───────────────────
275
+ await db.collection("orders").write({
276
+ ...order, // same logical entity
277
+ status: "shipped",
278
+ tracking: "UPS-1Z999AA10123456784",
279
+ shipped_at: new Date().toISOString(),
280
+ });
281
+
282
+ // ── 5. Audit: what was the order status 10 minutes ago? ───────────
283
+ const tenMinutesAgo = new Date(Date.now() - 10 * 60_000).toISOString();
284
+ const snapshot = await db
285
+ .collection("orders")
286
+ .asOf(tenMinutesAgo)
287
+ .find({ customer_id: customer.id });
288
+ // → returns the "placed" version, before it was shipped
289
+
290
+ // ── 6. Graph: find everything this customer is connected to ───────
291
+ const { nodes } = await db.graph.traverse(customer.id, {
292
+ depth: 2, direction: "inbound",
293
+ });
294
+ // → returns the order records linked to this customer
295
+ ```
@@ -0,0 +1,115 @@
1
+ import { CollectionClient } from "./collection.js";
2
+ import { GraphClient } from "./graph.js";
3
+ import type { StreamEvent, SubscribeOptions } from "./stream.js";
4
+ import type { SapixClientConfig, HealthResponse, WriteResponse, SaqlQueryResult, SemanticQueryResult, ChainHeadResponse, CreateAgentResponse, AgentListResponse, CheckpointResponse } from "./types.js";
5
+ export declare class SapixClient {
6
+ private readonly config;
7
+ /** Graph traversal and edge management. */
8
+ readonly graph: GraphClient;
9
+ constructor(config: SapixClientConfig);
10
+ /**
11
+ * Access a named agent as a collection.
12
+ * In SapixDB, every collection IS an agent — the agent-as-table paradigm.
13
+ * The named agent must exist (create it with createAgent or SAPIX_AGENTS env var).
14
+ *
15
+ * @example
16
+ * const products = db.collection("products-agt");
17
+ * await products.write({ name: "T-Shirt", price: 29.99 });
18
+ * const { records } = await products.latest(10);
19
+ */
20
+ collection<T = Record<string, unknown>>(name: string): CollectionClient<T>;
21
+ /**
22
+ * Alias for collection() — prefer this to match SapixDB terminology.
23
+ */
24
+ agent<T = Record<string, unknown>>(id: string): CollectionClient<T>;
25
+ /**
26
+ * Write a JSON record to the primary agent's strand.
27
+ * Use collection() / agent() to write to a named agent.
28
+ */
29
+ write(data: Record<string, unknown>): Promise<WriteResponse>;
30
+ /**
31
+ * Execute a structured SaQL query against the primary agent (POST /v1/query).
32
+ *
33
+ * @example
34
+ * await db.query({ type: "latest", limit: 10 });
35
+ * await db.query({ type: "hash", content_hash: "e7f2a1b3..." });
36
+ * await db.query({ type: "time_range", from_ts: 0, to_ts: 18446744073709551615 });
37
+ */
38
+ query(body: Record<string, unknown>): Promise<SaqlQueryResult>;
39
+ /**
40
+ * Send a natural-language query to POST /v1/query/semantic.
41
+ */
42
+ querySemantic(nl: string): Promise<SemanticQueryResult>;
43
+ /** Get the primary agent's current chain head and record count. */
44
+ head(): Promise<ChainHeadResponse>;
45
+ /** Check that the SapixDB agent is reachable and running. */
46
+ health(): Promise<HealthResponse>;
47
+ /**
48
+ * Ping the agent. Returns true if healthy, false if unreachable.
49
+ * Does not throw.
50
+ */
51
+ ping(): Promise<boolean>;
52
+ /**
53
+ * Create a new named agent with a genesis block (POST /v1/agents).
54
+ * seedHex must be 64 hex characters (32 bytes). zone defaults to "governed".
55
+ *
56
+ * @example
57
+ * await db.createAgent("orders-agt", "abcd...64hexchars", "governed");
58
+ */
59
+ createAgent(agentId: string, seedHex: string, zone?: string): Promise<CreateAgentResponse>;
60
+ /**
61
+ * List all agents running on this node (GET /v1/agents).
62
+ */
63
+ listAgents(): Promise<AgentListResponse>;
64
+ /**
65
+ * Ingest a record into a named agent's strand.
66
+ * Designed for AI agents, webhooks, and automated pipelines.
67
+ * If agentId is omitted or empty, writes to the primary agent.
68
+ *
69
+ * @example
70
+ * await db.ingest("ai-decisions-agt", {
71
+ * model: "claude-opus-4-7",
72
+ * action: "approve_loan",
73
+ * confidence: 0.94,
74
+ * });
75
+ */
76
+ ingest(agentId: string, data: Record<string, unknown>): Promise<WriteResponse>;
77
+ /**
78
+ * Subscribe to realtime writes on a named agent via SSE.
79
+ * Returns an EventSource — call `.close()` to unsubscribe.
80
+ *
81
+ * @example
82
+ * const es = db.subscribeAgent("orders", (event) => {
83
+ * console.log("new record:", event.record_id, event.payload);
84
+ * });
85
+ * // Later:
86
+ * es.close();
87
+ *
88
+ * // With backfill from an HLC timestamp:
89
+ * const es = db.subscribeAgent("orders", handler, { since: lastSeenHlc });
90
+ */
91
+ subscribeAgent(agentId: string, onEvent: (event: StreamEvent) => void, opts?: SubscribeOptions): EventSource;
92
+ /**
93
+ * Subscribe to realtime writes on all agents via SSE.
94
+ * Returns an EventSource — call `.close()` to unsubscribe.
95
+ *
96
+ * @example
97
+ * const es = db.subscribeGlobal((event) => {
98
+ * console.log(event.agent_id, event.record_id);
99
+ * }, { agents: ["orders", "payments"] });
100
+ */
101
+ subscribeGlobal(onEvent: (event: StreamEvent) => void, opts?: SubscribeOptions & {
102
+ agents?: string[];
103
+ }): EventSource;
104
+ /**
105
+ * Seal and delete all agent WAL files so no plaintext remains on disk.
106
+ * Requires root key or a key with `admin:*` scope.
107
+ * Returns the number of agents checkpointed.
108
+ *
109
+ * @example
110
+ * const result = await db.checkpoint();
111
+ * console.log(`Sealed ${result.agents_checkpointed} agents`);
112
+ */
113
+ checkpoint(): Promise<CheckpointResponse>;
114
+ }
115
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,KAAK,EACV,iBAAiB,EACjB,cAAc,EACd,aAAa,EACb,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,EACnB,MAAM,YAAY,CAAC;AAEpB,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoB;IAE3C,2CAA2C;IAC3C,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;gBAEhB,MAAM,EAAE,iBAAiB;IASrC;;;;;;;;;OASG;IACH,UAAU,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,gBAAgB,CAAC,CAAC,CAAC;IAI1E;;OAEG;IACH,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAAE,EAAE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,OAAO,CAAC,kBAAkB,CAAC;CAG1C"}
package/dist/client.js ADDED
@@ -0,0 +1,156 @@
1
+ import { request } from "./http.js";
2
+ import { CollectionClient } from "./collection.js";
3
+ import { GraphClient } from "./graph.js";
4
+ import { subscribeAgent, subscribeGlobal } from "./stream.js";
5
+ export class SapixClient {
6
+ constructor(config) {
7
+ this.config = {
8
+ timeout: 10000,
9
+ ...config,
10
+ url: config.url.replace(/\/$/, ""),
11
+ };
12
+ this.graph = new GraphClient(this.config);
13
+ }
14
+ /**
15
+ * Access a named agent as a collection.
16
+ * In SapixDB, every collection IS an agent — the agent-as-table paradigm.
17
+ * The named agent must exist (create it with createAgent or SAPIX_AGENTS env var).
18
+ *
19
+ * @example
20
+ * const products = db.collection("products-agt");
21
+ * await products.write({ name: "T-Shirt", price: 29.99 });
22
+ * const { records } = await products.latest(10);
23
+ */
24
+ collection(name) {
25
+ return new CollectionClient(this.config, name);
26
+ }
27
+ /**
28
+ * Alias for collection() — prefer this to match SapixDB terminology.
29
+ */
30
+ agent(id) {
31
+ return new CollectionClient(this.config, id);
32
+ }
33
+ /**
34
+ * Write a JSON record to the primary agent's strand.
35
+ * Use collection() / agent() to write to a named agent.
36
+ */
37
+ write(data) {
38
+ return request(this.config, "POST", "/v1/records/json", { data });
39
+ }
40
+ /**
41
+ * Execute a structured SaQL query against the primary agent (POST /v1/query).
42
+ *
43
+ * @example
44
+ * await db.query({ type: "latest", limit: 10 });
45
+ * await db.query({ type: "hash", content_hash: "e7f2a1b3..." });
46
+ * await db.query({ type: "time_range", from_ts: 0, to_ts: 18446744073709551615 });
47
+ */
48
+ query(body) {
49
+ return request(this.config, "POST", "/v1/query", body);
50
+ }
51
+ /**
52
+ * Send a natural-language query to POST /v1/query/semantic.
53
+ */
54
+ querySemantic(nl) {
55
+ return request(this.config, "POST", "/v1/query/semantic", { query: nl });
56
+ }
57
+ /** Get the primary agent's current chain head and record count. */
58
+ head() {
59
+ return request(this.config, "GET", "/v1/strand/head");
60
+ }
61
+ /** Check that the SapixDB agent is reachable and running. */
62
+ health() {
63
+ return request(this.config, "GET", "/v1/health");
64
+ }
65
+ /**
66
+ * Ping the agent. Returns true if healthy, false if unreachable.
67
+ * Does not throw.
68
+ */
69
+ async ping() {
70
+ try {
71
+ const res = await this.health();
72
+ return res.status === "ok";
73
+ }
74
+ catch {
75
+ return false;
76
+ }
77
+ }
78
+ /**
79
+ * Create a new named agent with a genesis block (POST /v1/agents).
80
+ * seedHex must be 64 hex characters (32 bytes). zone defaults to "governed".
81
+ *
82
+ * @example
83
+ * await db.createAgent("orders-agt", "abcd...64hexchars", "governed");
84
+ */
85
+ createAgent(agentId, seedHex, zone = "governed") {
86
+ return request(this.config, "POST", "/v1/agents", {
87
+ agent_id: agentId,
88
+ seed_hex: seedHex,
89
+ zone,
90
+ });
91
+ }
92
+ /**
93
+ * List all agents running on this node (GET /v1/agents).
94
+ */
95
+ listAgents() {
96
+ return request(this.config, "GET", "/v1/agents");
97
+ }
98
+ /**
99
+ * Ingest a record into a named agent's strand.
100
+ * Designed for AI agents, webhooks, and automated pipelines.
101
+ * If agentId is omitted or empty, writes to the primary agent.
102
+ *
103
+ * @example
104
+ * await db.ingest("ai-decisions-agt", {
105
+ * model: "claude-opus-4-7",
106
+ * action: "approve_loan",
107
+ * confidence: 0.94,
108
+ * });
109
+ */
110
+ ingest(agentId, data) {
111
+ const path = agentId ? `/v1/agents/${agentId}/records/json` : "/v1/records/json";
112
+ return request(this.config, "POST", path, { data });
113
+ }
114
+ /**
115
+ * Subscribe to realtime writes on a named agent via SSE.
116
+ * Returns an EventSource — call `.close()` to unsubscribe.
117
+ *
118
+ * @example
119
+ * const es = db.subscribeAgent("orders", (event) => {
120
+ * console.log("new record:", event.record_id, event.payload);
121
+ * });
122
+ * // Later:
123
+ * es.close();
124
+ *
125
+ * // With backfill from an HLC timestamp:
126
+ * const es = db.subscribeAgent("orders", handler, { since: lastSeenHlc });
127
+ */
128
+ subscribeAgent(agentId, onEvent, opts) {
129
+ return subscribeAgent(this.config, agentId, onEvent, opts);
130
+ }
131
+ /**
132
+ * Subscribe to realtime writes on all agents via SSE.
133
+ * Returns an EventSource — call `.close()` to unsubscribe.
134
+ *
135
+ * @example
136
+ * const es = db.subscribeGlobal((event) => {
137
+ * console.log(event.agent_id, event.record_id);
138
+ * }, { agents: ["orders", "payments"] });
139
+ */
140
+ subscribeGlobal(onEvent, opts) {
141
+ return subscribeGlobal(this.config, onEvent, opts);
142
+ }
143
+ /**
144
+ * Seal and delete all agent WAL files so no plaintext remains on disk.
145
+ * Requires root key or a key with `admin:*` scope.
146
+ * Returns the number of agents checkpointed.
147
+ *
148
+ * @example
149
+ * const result = await db.checkpoint();
150
+ * console.log(`Sealed ${result.agents_checkpointed} agents`);
151
+ */
152
+ checkpoint() {
153
+ return request(this.config, "POST", "/v1/control/checkpoint");
154
+ }
155
+ }
156
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAc9D,MAAM,OAAO,WAAW;IAMtB,YAAY,MAAyB;QACnC,IAAI,CAAC,MAAM,GAAG;YACZ,OAAO,EAAE,KAAM;YACf,GAAG,MAAM;YACT,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;SACnC,CAAC;QACF,IAAI,CAAC,KAAK,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;IAED;;;;;;;;;OASG;IACH,UAAU,CAA8B,IAAY;QAClD,OAAO,IAAI,gBAAgB,CAAI,IAAI,CAA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E,MAAM,EAAE,YAAY,EAAE;YACrE,QAAQ,EAAE,OAAO;YACjB,QAAQ,EAAE,OAAO;YACjB,IAAI;SACL,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,OAAO,CAAoB,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC,CAAC;IACtE,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,OAAe,EAAE,IAA6B;QACnD,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,cAAc,OAAO,eAAe,CAAC,CAAC,CAAC,kBAAkB,CAAC;QACjF,OAAO,OAAO,CAAgB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACrE,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,cAAc,CACZ,OAAe,EACf,OAAqC,EACrC,IAAuB;QAEvB,OAAO,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC7D,CAAC;IAED;;;;;;;;OAQG;IACH,eAAe,CACb,OAAqC,EACrC,IAA+C;QAE/C,OAAO,eAAe,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IACrD,CAAC;IAED;;;;;;;;OAQG;IACH,UAAU;QACR,OAAO,OAAO,CAAqB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,wBAAwB,CAAC,CAAC;IACpF,CAAC;CACF"}
@@ -0,0 +1,59 @@
1
+ import type { SapixClientConfig, WriteResponse, RecordView, SaqlQueryResult, ChainHeadResponse, AgentStatusResponse } from "./types.js";
2
+ export interface DeletedRecord {
3
+ record_id: string;
4
+ content_hash: string;
5
+ deleted_at_ms: number;
6
+ }
7
+ export declare class CollectionClient<T = Record<string, unknown>> {
8
+ private readonly config;
9
+ private readonly name;
10
+ constructor(config: SapixClientConfig, name: string);
11
+ /**
12
+ * Append a JSON record to the agent's strand. Nothing is ever overwritten.
13
+ *
14
+ * @example
15
+ * const result = await products.write({ name: "T-Shirt", price: 29.99 });
16
+ * console.log(result.record_id, result.content_hash);
17
+ */
18
+ write(data: Partial<T> & Record<string, unknown>): Promise<WriteResponse>;
19
+ /**
20
+ * Append multiple records sequentially.
21
+ */
22
+ writeBatch(records: Array<Partial<T> & Record<string, unknown>>): Promise<WriteResponse[]>;
23
+ /**
24
+ * Fetch a record by content hash.
25
+ */
26
+ get(contentHash: string): Promise<RecordView>;
27
+ /**
28
+ * Return the most recent N records from the agent.
29
+ *
30
+ * @example
31
+ * const result = await products.latest(10);
32
+ * result.records.forEach(r => console.log(r.payload));
33
+ */
34
+ latest(limit?: number): Promise<SaqlQueryResult>;
35
+ /**
36
+ * Execute a structured SaQL query against the agent.
37
+ * body must have at least a "type" key.
38
+ *
39
+ * @example
40
+ * await products.query({ type: "time_range", from_ts: 0, to_ts: 18446744073709551615 });
41
+ * await products.query({ type: "hash", content_hash: "e7f2..." });
42
+ */
43
+ query(body: Record<string, unknown>): Promise<SaqlQueryResult>;
44
+ /** Return the agent's current chain head and record count. */
45
+ head(): Promise<ChainHeadResponse>;
46
+ /** Return the agent's status (record count + chain head). */
47
+ status(): Promise<AgentStatusResponse>;
48
+ /**
49
+ * Soft-delete a record by content hash. Writes a tombstone — the record is
50
+ * excluded from `latest()` and `find()` but remains in the strand for audit.
51
+ * Restore with `restore(contentHash)`.
52
+ */
53
+ deleteRecord(contentHash: string): Promise<void>;
54
+ /** List all soft-deleted (tombstoned) records for this agent. */
55
+ listDeleted(): Promise<DeletedRecord[]>;
56
+ /** Restore a previously soft-deleted record. */
57
+ restore(contentHash: string): Promise<void>;
58
+ }
59
+ //# sourceMappingURL=collection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collection.d.ts","sourceRoot":"","sources":["../src/collection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,aAAa,EACb,UAAU,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AC;IAQvC,gDAAgD;IAChD,OAAO,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAO5C"}
@@ -0,0 +1,78 @@
1
+ import { request } from "./http.js";
2
+ // CollectionClient routes all operations to /v1/agents/{name}/...
3
+ // In SapixDB, every collection IS an agent — the agent-as-table paradigm.
4
+ export class CollectionClient {
5
+ constructor(config, name) {
6
+ this.config = config;
7
+ this.name = name;
8
+ }
9
+ /**
10
+ * Append a JSON record to the agent's strand. Nothing is ever overwritten.
11
+ *
12
+ * @example
13
+ * const result = await products.write({ name: "T-Shirt", price: 29.99 });
14
+ * console.log(result.record_id, result.content_hash);
15
+ */
16
+ write(data) {
17
+ return request(this.config, "POST", `/v1/agents/${this.name}/records/json`, { data });
18
+ }
19
+ /**
20
+ * Append multiple records sequentially.
21
+ */
22
+ async writeBatch(records) {
23
+ const results = await Promise.all(records.map((data) => this.write(data)));
24
+ return results;
25
+ }
26
+ /**
27
+ * Fetch a record by content hash.
28
+ */
29
+ get(contentHash) {
30
+ return request(this.config, "GET", `/v1/agents/${this.name}/records/${contentHash}`);
31
+ }
32
+ /**
33
+ * Return the most recent N records from the agent.
34
+ *
35
+ * @example
36
+ * const result = await products.latest(10);
37
+ * result.records.forEach(r => console.log(r.payload));
38
+ */
39
+ latest(limit = 20) {
40
+ return this.query({ type: "latest", limit });
41
+ }
42
+ /**
43
+ * Execute a structured SaQL query against the agent.
44
+ * body must have at least a "type" key.
45
+ *
46
+ * @example
47
+ * await products.query({ type: "time_range", from_ts: 0, to_ts: 18446744073709551615 });
48
+ * await products.query({ type: "hash", content_hash: "e7f2..." });
49
+ */
50
+ query(body) {
51
+ return request(this.config, "POST", `/v1/agents/${this.name}/query`, body);
52
+ }
53
+ /** Return the agent's current chain head and record count. */
54
+ head() {
55
+ return request(this.config, "GET", `/v1/agents/${this.name}/strand/head`);
56
+ }
57
+ /** Return the agent's status (record count + chain head). */
58
+ status() {
59
+ return request(this.config, "GET", `/v1/agents/${this.name}/status`);
60
+ }
61
+ /**
62
+ * Soft-delete a record by content hash. Writes a tombstone — the record is
63
+ * excluded from `latest()` and `find()` but remains in the strand for audit.
64
+ * Restore with `restore(contentHash)`.
65
+ */
66
+ deleteRecord(contentHash) {
67
+ return request(this.config, "DELETE", `/v1/agents/${this.name}/records/${contentHash}`);
68
+ }
69
+ /** List all soft-deleted (tombstoned) records for this agent. */
70
+ listDeleted() {
71
+ return request(this.config, "GET", `/v1/agents/${this.name}/records/deleted`);
72
+ }
73
+ /** Restore a previously soft-deleted record. */
74
+ restore(contentHash) {
75
+ return request(this.config, "POST", `/v1/agents/${this.name}/records/${contentHash}/restore`);
76
+ }
77
+ }
78
+ //# sourceMappingURL=collection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collection.js","sourceRoot":"","sources":["../src/collection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAgBpC,kEAAkE;AAClE,0EAA0E;AAC1E,MAAM,OAAO,gBAAgB;IAC3B,YACmB,MAAyB,EACzB,IAAY;QADZ,WAAM,GAAN,MAAM,CAAmB;QACzB,SAAI,GAAJ,IAAI,CAAQ;IAC5B,CAAC;IAEJ;;;;;;OAMG;IACH,KAAK,CAAC,IAA0C;QAC9C,OAAO,OAAO,CACZ,IAAI,CAAC,MAAM,EACX,MAAM,EACN,cAAc,IAAI,CAAC,IAAI,eAAe,EACtC,EAAE,IAAI,EAAE,CACT,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,UAAU,CAAC,OAAoD;QACnE,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC3E,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;OAEG;IACH,GAAG,CAAC,WAAmB;QACrB,OAAO,OAAO,CACZ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ined;
3
+ readonly code?: string | undefined;
4
+ constructor(message: string, status?: number | undefined, code?: string | undefined);
5
+ }
6
+ export declare class SapixNetworkError extends SapixError {
7
+ constructor(cause: unknown);
8
+ }
9
+ export declare class SapixNotFoundError extends SapixError {
10
+ constructor(id: string);
11
+ }
12
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,UAAW,SAAQ,KAAK;aAGjB,MAAM,CAAC,EAAE,MAAM;aACf,IAAI,CAAC,EAAE,MAAM;gBAF7B,OAAO,EAAE,MAAM,EACC,MAAM,CAAC,EAAE,MAAM,YAAA,EACf,IAAI,CAAC,EAAE,MAAM,YAAA;CAKhC;AAED,qBAAa,iBAAkB,SAAQ,UAAU;gBACnC,KAAK,EAAE,OAAO;CAI3B;AAED,qBAAa,kBAAmB,SAAQ,UAAU;gBACpC,EAAE,EAAE,MAAM;CAIvB"}
package/dist/errors.js ADDED
@@ -0,0 +1,21 @@
1
+ export class SapixError extends Error {
2
+ constructor(message, status, code) {
3
+ super(message);
4
+ this.status = status;
5
+ this.code = code;
6
+ this.name = "SapixError";
7
+ }
8
+ }
9
+ export class SapixNetworkError extends SapixError {
10
+ constructor(cause) {
11
+ super(`Network error: ${cause instanceof Error ? cause.message : String(cause)}`);
12
+ this.name = "SapixNetworkError";
13
+ }
14
+ }
15
+ export class SapixNotFoundError extends SapixError {
16
+ constructor(id) {
17
+ super(`Record not found: ${id}`, 404, "NOT_FOUND");
18
+ this.name = "SapixNotFoundError";
19
+ }
20
+ }
21
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,UAAW,SAAQ,KAAK;IACnC,YACE,OAAe,EACC,MAAe,EACf,IAAa;QAE7B,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,WAAM,GAAN,MAAM,CAAS;QACf,SAAI,GAAJ,IAAI,CAAS;QAG7B,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;IAC3B,CAAC;CACF;AAED,MAAM,OAAO,iBAAkB,SAAQ,UAAU;IAC/C,YAAY,KAAc;QACxB,KAAK,CAAC,kBAAkB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClF,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,UAAU;IAChD,YAAY,EAAU;QACpB,KAAK,CAAC,qBAAqB,EAAE,EAAE,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;QACnD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF"}
@@ -0,0 +1,26 @@
1
+ import type { SapixClientConfig, GraphEdgeInput, GraphEdge, TraverseOptions, TraversalResult } from "./types.js";
2
+ export declare class GraphClient {
3
+ private readonly config;
4
+ constructor(config: SapixClientConfig);
5
+ /** Create a directed edge between two agents or records. */
6
+ addEdge(edge: GraphEdgeInput): Promise<void>;
7
+ /** Convenience: create an edge with weight 1.0. */
8
+ relate(src: string, dst: string, edgeType: string, weight?: number): Promise<void>;
9
+ /** Delete a directed edge. */
10
+ removeEdge(src: string, edgeType: string, dst: string): Promise<void>;
11
+ /** Get all outbound edges from an agent. */
12
+ edges(agentId: string): Promise<GraphEdge[]>;
13
+ /** Get all inbound edges to an agent. */
14
+ inboundEdges(agentId: string): Promise<GraphEdge[]>;
15
+ /**
16
+ * Traverse the agent graph from a starting agent.
17
+ * Returns agents visited and the edges connecting them.
18
+ *
19
+ * @example
20
+ * const result = await db.graph.traverse("orders-agt", { depth: 2 });
21
+ */
22
+ traverse(agentId: string, options?: TraverseOptions): Promise<TraversalResult>;
23
+ /** Add a cross-agent record reference edge. */
24
+ addRecordRef(srcAgent: string, srcHash: string, edgeType: string, dstAgent: string, dstHash: string): Promise<void>;
25
+ }
26
+ //# sourceMappingURL=graph.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.d.ts","sourceRoot":"","sources":["../src/graph.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,cAAc,EACd,SAAS,EACT,eAAe,EACf,eAAe,EAChB,MAAM,YAAY,CAAC;AAEpB,qBAAa,WAAW;IACV,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,iBAAiB;IAEtD,4DAA4D;IAC5D,OAAO,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAS5C,mDAAmD;IACnD,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,SAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/E,8BAA8B;IAC9B,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQrE,4CAA4C;IAC5C,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAQ5C,yCAAyC;IACzC,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAQnD;;;;;;OAMG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,eAAe,CAAC;IASlF,+CAA+C;IAC/C,YAAY,CACV,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,IAAI,CAAC;CASjB"}
package/dist/graph.js ADDED
@@ -0,0 +1,52 @@
1
+ import { request } from "./http.js";
2
+ export class GraphClient {
3
+ constructor(config) {
4
+ this.config = config;
5
+ }
6
+ /** Create a directed edge between two agents or records. */
7
+ addEdge(edge) {
8
+ return request(this.config, "POST", "/v1/graph/edges", { ...edge, weight: edge.weight ?? 1.0 });
9
+ }
10
+ /** Convenience: create an edge with weight 1.0. */
11
+ relate(src, dst, edgeType, weight = 1.0) {
12
+ return this.addEdge({ src, dst, edge_type: edgeType, weight });
13
+ }
14
+ /** Delete a directed edge. */
15
+ removeEdge(src, edgeType, dst) {
16
+ return request(this.config, "DELETE", `/v1/graph/edges/${src}/${edgeType}/${dst}`);
17
+ }
18
+ /** Get all outbound edges from an agent. */
19
+ edges(agentId) {
20
+ return request(this.config, "GET", `/v1/graph/edges/${agentId}`);
21
+ }
22
+ /** Get all inbound edges to an agent. */
23
+ inboundEdges(agentId) {
24
+ return request(this.config, "GET", `/v1/graph/edges/${agentId}?direction=in`);
25
+ }
26
+ /**
27
+ * Traverse the agent graph from a starting agent.
28
+ * Returns agents visited and the edges connecting them.
29
+ *
30
+ * @example
31
+ * const result = await db.graph.traverse("orders-agt", { depth: 2 });
32
+ */
33
+ traverse(agentId, options = {}) {
34
+ const depth = options.depth ?? 1;
35
+ let path = `/v1/graph/traverse?agent_id=${encodeURIComponent(agentId)}&depth=${depth}`;
36
+ if (options.edge_type) {
37
+ path += `&edge_type=${encodeURIComponent(options.edge_type)}`;
38
+ }
39
+ return request(this.config, "GET", path);
40
+ }
41
+ /** Add a cross-agent record reference edge. */
42
+ addRecordRef(srcAgent, srcHash, edgeType, dstAgent, dstHash) {
43
+ return request(this.config, "POST", "/v1/graph/refs", {
44
+ src_agent: srcAgent,
45
+ src_content_hash: srcHash,
46
+ edge_type: edgeType,
47
+ dst_agent: dstAgent,
48
+ dst_content_hash: dstHash,
49
+ });
50
+ }
51
+ }
52
+ //# sourceMappingURL=graph.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sourceR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BAAkB,CAAC,OAAO,CAAC,UAAU,KAAK,EAAE,CAAC;QACvF,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;YACtB,IAAI,IAAI,cAAc,kBAAkB,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;QAChE,CAAC;QACD,OAAO,OAAO,CAAkB,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IAC5D,CAAC;IAED,+CAA+C;IAC/C,YAAY,CACV,QAAgB,EAChB,OAAe,EACf,QAAgB,EAChB,QAAgB,EAChB,OAAe;QAEf,OAAO,OAAO,CAAO,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,gBAAgB,EAAE;YAC1D,SAAS,EAAE,QAAQ;YACnB,gBAAgB,EAAE,OAAO;YACzB,SAAS,EAAE,QAAQ;YACnB,SAAS,EAAE,QAAQ;YACnB,gBAAgB,EAAE,OAAO;SAC1B,CAAC,CAAC;IACL,CAAC;CACF"}
package/dist/http.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { SapixClientConfig } from "./types.js";
2
+ export declare function request<T>(config: SapixClientConfig, method: string, path: string, body?: unknown): Promise<T>;
3
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,wBAAsB,OAAO,CAAC,CAAC,EAC7B,MAAM,EAAE,iBAAiB,EACzB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,OAAO,GACb,OAAO,CAAC,CAAC,CAAC,CA2CZ"}
package/dist/http.js ADDED
@@ -0,0 +1,48 @@
1
+ import { SapixError, SapixNetworkError } from "./errors.js";
2
+ export async function request(config, method, path, body) {
3
+ const url = `${config.url}${path}`;
4
+ const headers = {
5
+ "Content-Type": "application/json",
6
+ ...config.headers,
7
+ };
8
+ if (config.apiKey) {
9
+ headers["Authorization"] = `Bearer ${config.apiKey}`;
10
+ }
11
+ if (config.callerId) {
12
+ headers["X-Sapix-Caller"] = config.callerId;
13
+ }
14
+ let res;
15
+ try {
16
+ const opts = { method, headers };
17
+ if (body !== undefined)
18
+ opts.body = JSON.stringify(body);
19
+ if (config.timeout) {
20
+ const ac = new AbortController();
21
+ const timer = setTimeout(() => ac.abort(), config.timeout);
22
+ opts.signal = ac.signal;
23
+ res = await fetch(url, opts);
24
+ clearTimeout(timer);
25
+ }
26
+ else {
27
+ res = await fetch(url, opts);
28
+ }
29
+ }
30
+ catch (err) {
31
+ throw new SapixNetworkError(err);
32
+ }
33
+ if (!res.ok) {
34
+ let message = `HTTP ${res.status}`;
35
+ let code;
36
+ try {
37
+ const body = await res.json();
38
+ if (body.error)
39
+ message = body.error;
40
+ if (body.code)
41
+ code = body.code;
42
+ }
43
+ catch { /* ignore parse error */ }
44
+ throw new SapixError(message, res.status, code);
45
+ }
46
+ return res.json();
47
+ }
48
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAG5D,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,MAAyB,EACzB,MAAc,EACd,IAAY,EACZ,IAAc;IAEd,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,GAAG,GAAG,IAAI,EAAE,CAAC;IACnC,MAAM,OAAO,GAA2B;QACtC,cAAc,EAAE,kBAAkB;QAClC,GAAG,MAAM,CAAC,OAAO;KAClB,CAAC;IACF,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,MAAM,CAAC,MAAM,EAAE,CAAC;IACvD,CAAC;IACD,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;QACpB,OAAO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AC,wBAAwB,CAAC,CAAC;QACpC,MAAM,IAAI,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAClD,CAAC;IAED,OAAO,GAAG,CAAC,IAAI,EAAgB,CAAC;AAClC,CAAC"}
@@ -0,0 +1,9 @@
1
+ export { SapixClient } from "./client.js";
2
+ export { CollectionClient } from "./collection.js";
3
+ export type { DeletedRecord } from "./collection.js";
4
+ export { GraphClient } from "./graph.js";
5
+ export { SapixError, SapixNetworkError, SapixNotFoundError } from "./errors.js";
6
+ export { subscribeAgent, subscribeGlobal } from "./stream.js";
7
+ export type { SapixClientConfig, WriteResponse, CheckpointResponse, RecordView, ChainHeadResponse, AgentStatusResponse, CreateAgentResponse, AgentListResponse, GraphEdge, GraphEdgeInput, TraverseOptions, TraversalResult, TraversalEdge, HealthResponse, SaqlQueryResult, SemanticQueryResult, } from "./types.js";
8
+ export type { StreamEvent, SubscribeOptions } from "./stream.js";
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,YAAY,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9D,YAAY,EACV,iBAAiB,EACjB,aAAa,EACb,kBAAkB,EAClB,UAAU,EACV,iBAAiB,EACjB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,SAAS,EACT,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,cAAc,EACd,eAAe,EACf,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { SapixClient } from "./client.js";
2
+ export { CollectionClient } from "./collection.js";
3
+ export { GraphClient } from "./graph.js";
4
+ export { SapixError, SapixNetworkError, SapixNotFoundError } from "./errors.js";
5
+ export { subscribeAgent, subscribeGlobal } from "./stream.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,42 @@
1
+ import type { SapixClientConfig } from "./types.js";
2
+ /** A realtime write event pushed via SSE from SapixDB. */
3
+ export interface StreamEvent {
4
+ agent_id: string;
5
+ event_type: string;
6
+ record_id: string;
7
+ content_hash: string;
8
+ timestamp_ms: number;
9
+ payload?: unknown;
10
+ }
11
+ /** Options for SSE subscriptions. */
12
+ export interface SubscribeOptions {
13
+ /** HLC timestamp — server replays records written after this value before going live. */
14
+ since?: number;
15
+ /** Only emit events whose JSON payload contains this top-level field name. */
16
+ filter?: string;
17
+ }
18
+ /**
19
+ * Open an SSE stream for a single named agent.
20
+ * Returns an EventSource — call `.close()` to unsubscribe.
21
+ *
22
+ * @example
23
+ * const es = db.subscribeAgent("orders", (event) => {
24
+ * console.log("new record:", event.record_id, event.payload);
25
+ * });
26
+ * // Later:
27
+ * es.close();
28
+ */
29
+ export declare function subscribeAgent(config: SapixClientConfig, agentId: string, onEvent: (event: StreamEvent) => void, opts?: SubscribeOptions): EventSource;
30
+ /**
31
+ * Open an SSE stream for all agents (optionally filtered).
32
+ * Returns an EventSource — call `.close()` to unsubscribe.
33
+ *
34
+ * @example
35
+ * const es = db.subscribeGlobal((event) => {
36
+ * console.log(event.agent_id, event.record_id);
37
+ * }, { agents: ["orders", "payments"] });
38
+ */
39
+ export declare function subscribeGlobal(config: SapixClientConfig, onEvent: (event: StreamEvent) => void, opts?: SubscribeOptions & {
40
+ agents?: string[];
41
+ }): EventSource;
42
+ //# sourceMappingURL=stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,0DAA0D;AAC1D,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,qCAAqC;AACrC,MAAM,WAAW,gBAAgB;IAC/B,yFAAyF;IACzF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8EAA8E;IAC9E,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,iBAAiB,EACzB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,EACrC,IAAI,CAAC,EAAE,gBAAgB,GACtB,WAAW,CAcb;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,iBAAiB,EACzB,OAAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,EACrC,IAAI,CAAC,EAAE,gBAAgB,GAAG;IAAE,MAAM,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GAC9C,WAAW,CAeb"}
package/dist/stream.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Open an SSE stream for a single named agent.
3
+ * Returns an EventSource — call `.close()` to unsubscribe.
4
+ *
5
+ * @example
6
+ * const es = db.subscribeAgent("orders", (event) => {
7
+ * console.log("new record:", event.record_id, event.payload);
8
+ * });
9
+ * // Later:
10
+ * es.close();
11
+ */
12
+ export function subscribeAgent(config, agentId, onEvent, opts) {
13
+ const params = new URLSearchParams();
14
+ if (opts?.since != null)
15
+ params.set("since", String(opts.since));
16
+ if (opts?.filter)
17
+ params.set("filter", opts.filter);
18
+ const qs = params.size > 0 ? `?${params}` : "";
19
+ const es = new EventSource(`${config.url}/v1/agents/${agentId}/stream${qs}`);
20
+ es.addEventListener("record.written", (e) => {
21
+ try {
22
+ onEvent(JSON.parse(e.data));
23
+ }
24
+ catch {
25
+ // ignore malformed events
26
+ }
27
+ });
28
+ return es;
29
+ }
30
+ /**
31
+ * Open an SSE stream for all agents (optionally filtered).
32
+ * Returns an EventSource — call `.close()` to unsubscribe.
33
+ *
34
+ * @example
35
+ * const es = db.subscribeGlobal((event) => {
36
+ * console.log(event.agent_id, event.record_id);
37
+ * }, { agents: ["orders", "payments"] });
38
+ */
39
+ export function subscribeGlobal(config, onEvent, opts) {
40
+ const params = new URLSearchParams();
41
+ if (opts?.agents?.length)
42
+ params.set("agents", opts.agents.join(","));
43
+ if (opts?.since != null)
44
+ params.set("since", String(opts.since));
45
+ if (opts?.filter)
46
+ params.set("filter", opts.filter);
47
+ const qs = params.size > 0 ? `?${params}` : "";
48
+ const es = new EventSource(`${config.url}/v1/stream${qs}`);
49
+ es.addEventListener("record.written", (e) => {
50
+ try {
51
+ onEvent(JSON.parse(e.data));
52
+ }
53
+ catch {
54
+ // ignore malformed events
55
+ }
56
+ });
57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,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACtE,IAAI,IAAI,EAAE,KAAK,IAAI,IAAI;QAAE,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACjE,IAAI,IAAI,EAAE,MAAM;QAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,EAAE,GAAG,MAAM,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/C,MAAM,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,MAAM,CAAC,GAAG,aAAa,EAAE,EAAE,CAAC,CAAC;IAC3D,EAAE,CAAC,gBAAgB,CAAC,gBAAgB,EAAE,CAAC,CAAQ,EAAE,EAAE;QACjD,IAAI,CAAC;YACH,OAAO,CAAC,IAAI,CAAC,KAAK,CAAE,CAAkB,CAAC,IAAI,CAAgB,CAAC,CAAC;QAC/D,CAAC;QAAC,MAAM,CAAC;YACP,0BAA0B;QAC5B,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,CAAC;AACZ,CAAC"}
@@ -0,0 +1,124 @@
1
+ export interface SapixClientConfig {
2
+ /** Base URL of the SapixDB agent, e.g. "http://localhost:7475" */
3
+ url: string;
4
+ /**
5
+ * API key for SapixDB bearer-token authentication (`SAPIX_API_KEY` on the server).
6
+ * When set, every request will include `Authorization: Bearer <apiKey>`.
7
+ * Takes precedence over a manually specified `Authorization` header in `headers`.
8
+ */
9
+ apiKey?: string;
10
+ /**
11
+ * Caller identity forwarded to Codios as `caller_identity`.
12
+ * Sent as `X-Sapix-Caller: <callerId>`. Use your Codios agent ID here
13
+ * so Codios can enforce per-caller policies.
14
+ */
15
+ callerId?: string;
16
+ /** Optional extra headers sent with every request */
17
+ headers?: Record<string, string>;
18
+ /** Request timeout in milliseconds (default: 10000) */
19
+ timeout?: number;
20
+ }
21
+ /** Returned by every write operation. */
22
+ export interface WriteResponse {
23
+ record_id: string;
24
+ content_hash: string;
25
+ chain_head: string;
26
+ /** null = Codios not configured (open mode); true = Codios authorized. */
27
+ codios_verified: boolean | null;
28
+ /** "open" or "enforced" */
29
+ codios_mode: string;
30
+ codios_contract_id?: string;
31
+ }
32
+ /** Returned by POST /v1/control/checkpoint. Requires root key or admin:* scope. */
33
+ export interface CheckpointResponse {
34
+ status: string;
35
+ agents_checkpointed: number;
36
+ }
37
+ /** A single strand record returned by reads and queries. */
38
+ export interface RecordView {
39
+ record_id: string;
40
+ content_hash: string;
41
+ parent_hash: string;
42
+ /** HLC timestamp packed as u64. */
43
+ timestamp_hlc: number;
44
+ timestamp_ms: number;
45
+ /** Base64-encoded raw payload bytes. */
46
+ payload_b64: string;
47
+ /** Decoded JSON payload (present on /json endpoints). */
48
+ payload?: unknown;
49
+ flags: number;
50
+ schema_version: number;
51
+ }
52
+ /** Response from GET /v1/strand/head and GET /v1/agents/:id/strand/head. */
53
+ export interface ChainHeadResponse {
54
+ chain_head: string;
55
+ record_count: number;
56
+ }
57
+ /** Response from GET /v1/agents/:id/status. */
58
+ export interface AgentStatusResponse {
59
+ agent_id: string;
60
+ record_count: number;
61
+ chain_head: string;
62
+ }
63
+ /** Response from POST /v1/agents. */
64
+ export interface CreateAgentResponse {
65
+ agent_id: string;
66
+ public_key_hex: string;
67
+ genesis_record_id: string;
68
+ chain_head_hex: string;
69
+ zone: string;
70
+ }
71
+ /** Response from GET /v1/agents. */
72
+ export interface AgentListResponse {
73
+ agents: string[];
74
+ total: number;
75
+ }
76
+ export interface GraphEdgeInput {
77
+ src: string;
78
+ dst: string;
79
+ edge_type: string;
80
+ weight?: number;
81
+ }
82
+ export interface GraphEdge {
83
+ src: string;
84
+ edge_type: string;
85
+ dst: string;
86
+ timestamp_hlc: number;
87
+ weight: number;
88
+ }
89
+ export interface TraversalEdge {
90
+ src: string;
91
+ dst: string;
92
+ edge_type: string;
93
+ weight: number;
94
+ across_peer: boolean;
95
+ peer_endpoint?: string;
96
+ }
97
+ export interface TraversalResult {
98
+ start_agent: string;
99
+ agents_visited: string[];
100
+ edges: TraversalEdge[];
101
+ depth_reached: number;
102
+ }
103
+ export interface TraverseOptions {
104
+ depth?: number;
105
+ edge_type?: string;
106
+ }
107
+ export interface HealthResponse {
108
+ status: string;
109
+ agent_id: string;
110
+ record_count: number;
111
+ chain_head: string;
112
+ }
113
+ /** Response from POST /v1/query and POST /v1/agents/:id/query. */
114
+ export interface SaqlQueryResult {
115
+ records: RecordView[];
116
+ total: number;
117
+ }
118
+ /** Response from POST /v1/query/semantic. */
119
+ export interface SemanticQueryResult {
120
+ source: string;
121
+ plan: Record<string, unknown>;
122
+ records: RecordView[];
123
+ }
124
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,iBAAiB;IAChC,kEAAkE;IAClE,GAAG,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,yCAAyC;AACzC,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,0EAA0E;IAC1E,eAAe,EAAE,OAAO,GAAG,IAAI,CAAC;IAChC,2BAA2B;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED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;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,OAAO,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,KAAK,EAAE,aAAa,EAAE,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,eAAe;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,kEAAkE;AAClE,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,6CAA6C;AAC7C,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,OAAO,EAAE,UAAU,EAAE,CAAC;CACvB"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "sapixdb-js",
3
+ "version": "0.3.0",
4
+ "description": "Official JavaScript/TypeScript SDK for SapixDB — the agent-native living database",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "dev": "tsc --watch",
17
+ "test": "node --experimental-vm-modules node_modules/.bin/jest"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "keywords": [
24
+ "sapixdb",
25
+ "database",
26
+ "agent-native",
27
+ "ai-database",
28
+ "sdk",
29
+ "typescript"
30
+ ],
31
+ "author": "Sensart Technologies LLC",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/sensart/sapixdb"
36
+ },
37
+ "devDependencies": {
38
+ "typescript": "^5.4.0"
39
+ },
40
+ "engines": {
41
+ "node": ">=18.0.0"
42
+ }
43
+ }