@kitsuden/sdk 0.0.0-stage → 0.9.0-beta

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Victor Antinori Broce
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,476 @@
1
- # Temporary Holding Version
1
+ # @kitsuden/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official JavaScript/TypeScript SDK for Kitsuden — The Modular BaaS/CMS.
4
+
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ ## Features
8
+
9
+ - 🔥 **Edge-Ready** — Works in Cloudflare Workers, Vercel Edge, Deno Deploy
10
+ - 📝 **Type-Safe** — Full TypeScript support with generic table types
11
+ - 🚀 **Zero Dependencies** — Lightweight, only uses native `fetch` and `WebSocket`
12
+ - ⚡ **Lean on the wire** — reads TOON and lets the server pick the shorter of compact JSON / TOON per response
13
+ - 🔒 **Secure** — Agent NHI tokens (`kitsuden_agent_*`) + Bearer auth
14
+ - 🔄 **Real-time** — Live Query subscriptions via WebSocket
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @kitsuden/sdk@beta
20
+ ```
21
+
22
+ (`npm install kitsuden@beta` gives the same module plus the `kitsuden` command.)
23
+ Inside the Kitsuden monorepo, depend on it with `"@kitsuden/sdk": "workspace:*"`
24
+ and build it with `pnpm --filter @kitsuden/sdk build`.
25
+
26
+ ## Typed client: 5 lines to your first call
27
+
28
+ Generated from the API's OpenAPI 3.1 (every `defineOperation` of the installed kons and
29
+ the core: 700+ operations, one property per kon). Set `KITSUDEN_API_URL` (the API origin)
30
+ and `KITSUDEN_API_TOKEN` (`kitsuden_agent_…`):
31
+
32
+ ```typescript
33
+ import { createKitsuden } from "@kitsuden/sdk";
34
+
35
+ const kitsuden = createKitsuden();
36
+ const res = await kitsuden.datasets.listDatasets({ limit: 5 });
37
+ if (res.kind === "ok") console.log(res.data.docs.map((d) => d.name));
38
+ ```
39
+
40
+ - Typed arguments (path and query flat, body under `body`: the MCP tool's shape) and typed
41
+ responses; `KitsudenErrorCode` is the closed union of `KITSUDEN_E_*` codes.
42
+ - `202 KITSUDEN_E_APPROVAL_REQUIRED` comes back as `{ kind: "proposal_pending", proposal }`,
43
+ never retried.
44
+ - Automatic `Idempotency-Key` on writes; retries only when safe, honouring `Retry-After`.
45
+ - `format: "json" | "toon" | "tron" | "auto"`, always decoded; `provenance: true` gives
46
+ `meta.provenance` and `provenanceOf(row)`.
47
+ - `kitsuden.datasets.searchEntries.iterate({ id, limit: 50 })` walks every page.
48
+ - Streaming operations (`output.flow` on the server) return a typed `AsyncIterable`:
49
+ `for await (const event of kitsuden.proposals.proposalEvents({ id })) …`. Standard Server-Sent
50
+ Events underneath (no custom protocol); `event: error` throws `KitsudenApiError`, and
51
+ breaking out of the loop aborts the request.
52
+ - Validate before sending with any Standard Schema consumer (Zod, Valibot, ArkType, form
53
+ libraries): `operationSchemas(spec, "datasets.create-dataset").body` turns the operation's
54
+ JSON Schema into a Standard Schema v1 validator; the spec ships as
55
+ `@kitsuden/sdk/openapi.json`. `toStandardSchema(jsonSchema)` does it for any schema.
56
+ - Zero runtime dependencies: Node 18+, Bun, Deno and browsers.
57
+
58
+ Full guide: [docs/agents/clients.md](../../docs/agents/clients.md). Regenerate after an API
59
+ change with `pnpm sdk:openapi && pnpm sdk:generate` (CI runs `pnpm sdk:check`), or keep
60
+ `pnpm sdk:watch` running: it regenerates on every change to a `defineModel` or
61
+ `defineOperation` (about 3 s) and only rewrites the files that changed, so your editor
62
+ picks up the new types at once.
63
+
64
+ ## Quick Start (CRUD helpers)
65
+
66
+ ```typescript
67
+ import { KitsudenClient } from "@kitsuden/sdk";
68
+
69
+ const kitsuden = new KitsudenClient({
70
+ url: "https://api.example.com",
71
+ apiKey: "kitsuden_agent_your_agent_token",
72
+ });
73
+
74
+ // Explorer API — primary way to interact with data
75
+ const recipes = await kitsuden.from("recipes").list();
76
+ const recipe = await kitsuden.from("recipes").get("uuid-123");
77
+ const newRecipe = await kitsuden.from("recipes").create({ title: "New recipe" });
78
+ await kitsuden.from("recipes").update(newRecipe.id, { status: "published" });
79
+ await kitsuden.from("recipes").delete(newRecipe.id);
80
+ ```
81
+
82
+ ## Usage
83
+
84
+ ### Initialize Client
85
+
86
+ ```typescript
87
+ import { KitsudenClient } from "@kitsuden/sdk";
88
+
89
+ const kitsuden = new KitsudenClient({
90
+ url: "https://api.example.com",
91
+ // Optional: Agent NHI token for authentication
92
+ apiKey: process.env.KITSUDEN_API_KEY,
93
+ });
94
+ ```
95
+
96
+ ### CRUD via Explorer API (Recommended)
97
+
98
+ The `.from(table)` method returns a `TableRef` with full CRUD capabilities:
99
+
100
+ #### List with pagination, sorting, and filtering
101
+
102
+ ```typescript
103
+ const recipes = await kitsuden.from("recipes").list();
104
+ console.log(recipes.data); // Array of records
105
+ console.log(recipes.pagination); // { page, limit, total, totalPages, hasNextPage, hasPrevPage }
106
+
107
+ // With options
108
+ const filtered = await kitsuden.from("recipes").list({
109
+ limit: 10,
110
+ page: 1,
111
+ sort: "title",
112
+ dir: "asc",
113
+ // Text in any textual column, or only in these
114
+ search: "lentil",
115
+ search_fields: ["title", "summary"],
116
+ // Every condition must hold: a value is `equals`; or one of
117
+ // contains, equals, gt, lt, gte, lte
118
+ filters: { status: "published", created_at: { gte: "2026-01-01" } },
119
+ });
120
+ ```
121
+
122
+ On the wire this is
123
+ `?search=lentil&search_fields=title,summary&filter[status]=published&filter[created_at][gte]=2026-01-01`.
124
+ At most 20 conditions and 30 search fields; an unknown operator or column is a 400, and a
125
+ secret column (a name ending in token, password, secret or a hash) can be neither filtered nor
126
+ searched. The older single filter (`filter_field`, `filter_op`, `filter_value`) still works and
127
+ is combined with the others by AND.
128
+
129
+ #### Change history of a record
130
+
131
+ ```typescript
132
+ const { history } = await kitsuden.from("recipes").history("uuid-123");
133
+ // [{ action: "update", at, actor: { type: "user" | "agent" | "system", id, name },
134
+ // changes: [{ field, before, after } | { field, redacted: true }], proposalId, approvedBy }, ...]
135
+ ```
136
+
137
+ It calls `GET /api/history/:table/:id` (admin only). Newest first, with `limit` (1-200,
138
+ default 50) and `offset`. Every create, update and delete
139
+ made through the explorer, a model's routes or a dataset's entry routes is recorded; secret
140
+ columns are listed as `redacted` without values, and long values are cut to a preview. A
141
+ dataset entry's history is also at `GET /api/datasets/:id/entries/:entryId/history`, with the
142
+ same visibility as the entry.
143
+
144
+ #### Get by ID
145
+
146
+ ```typescript
147
+ const recipe = await kitsuden.from("recipes").get("uuid-123");
148
+ ```
149
+
150
+ #### Create
151
+
152
+ ```typescript
153
+ const newRecipe = await kitsuden.from("recipes").create({
154
+ title: "Lemon tart",
155
+ slug: "lemon-tart",
156
+ tags: ["dessert", "baking"],
157
+ });
158
+ ```
159
+
160
+ #### Update
161
+
162
+ ```typescript
163
+ await kitsuden.from("recipes").update("uuid-123", {
164
+ status: "published",
165
+ });
166
+ ```
167
+
168
+ #### Delete
169
+
170
+ ```typescript
171
+ await kitsuden.from("recipes").delete("uuid-123");
172
+ ```
173
+
174
+ #### Dropdown options (for foreign keys)
175
+
176
+ ```typescript
177
+ const categories = await kitsuden.from("categories").options();
178
+ // [{ value: 'uuid-1', label: 'Desserts' }, ...]
179
+ ```
180
+
181
+ ### TypeScript Support
182
+
183
+ ```typescript
184
+ interface Recipe {
185
+ id: string;
186
+ title: string;
187
+ slug: string;
188
+ status: "draft" | "published";
189
+ tags: string[];
190
+ createdAt: string;
191
+ }
192
+
193
+ // Type-safe table reference
194
+ const recipes = kitsuden.from<Recipe>("recipes");
195
+ const allRecipes = await recipes.list();
196
+ // allRecipes.data is typed as Recipe[]
197
+ ```
198
+
199
+ ### Schema Introspection
200
+
201
+ ```typescript
202
+ // Get column types, editability, and relations for a table
203
+ const schema = await kitsuden.schema("recipes");
204
+ console.log(schema.columns);
205
+ // [{ name: 'title', type: 'text', editable: true, nullable: false }, ...]
206
+
207
+ // List all available tables
208
+ const tables = await kitsuden.tables();
209
+ // [{ key: 'recipes', label: 'Recipes', icon: 'book', rowCount: 42 }, ...]
210
+ ```
211
+
212
+ ### Module Management
213
+
214
+ ```typescript
215
+ // List all kons (modules)
216
+ const modules = await kitsuden.modules.list();
217
+
218
+ // Toggle a kon on/off
219
+ await kitsuden.modules.toggle("academy");
220
+
221
+ // Get only enabled modules
222
+ const enabled = await kitsuden.modules.enabled();
223
+ ```
224
+
225
+ ### Wire formats: JSON, TOON, auto
226
+
227
+ The SDK always returns plain objects; `format` only changes what travels over
228
+ the wire:
229
+
230
+ - `"json"` (default): compact JSON.
231
+ - `"toon"`: [TOON](https://toonformat.dev). Shorter than JSON for flat, uniform
232
+ lists (categories, tags, page lists); **longer** for nested records such as
233
+ dataset entries. Measured numbers: `docs/agents/benchmarks.md` in the
234
+ Kitsuden repository.
235
+ - `"auto"`: the server encodes each response as compact JSON and as TOON,
236
+ checks that the TOON version decodes back to exactly the same data, and
237
+ sends the shorter one (`Content-Type` says which).
238
+
239
+ ```typescript
240
+ const agent = new KitsudenClient({
241
+ url: "https://api.example.com",
242
+ apiKey: "kitsuden_agent_xxx",
243
+ format: "auto",
244
+ });
245
+
246
+ const recipes = await agent.from("recipes").list(); // same objects as with "json"
247
+ ```
248
+
249
+ The TOON codec is exported too: `import { encodeToon, decodeToon } from "@kitsuden/sdk"`.
250
+ The API can also answer in TRON (`Accept: application/vnd.tron`); the SDK does
251
+ not decode TRON, to stay dependency-free.
252
+
253
+ ### Error Handling
254
+
255
+ ```typescript
256
+ import { KitsudenClient, KitsudenError } from "@kitsuden/sdk";
257
+
258
+ try {
259
+ const recipes = await kitsuden.from("recipes").list();
260
+ } catch (error) {
261
+ if (error instanceof KitsudenError) {
262
+ console.error(`HTTP ${error.statusCode}:`, error.message);
263
+ } else {
264
+ console.error("Network or unknown error:", error);
265
+ }
266
+ }
267
+ ```
268
+
269
+ ### Real-time Subscriptions
270
+
271
+ ```typescript
272
+ import { createRealtime } from "@kitsuden/sdk/realtime";
273
+
274
+ const rt = createRealtime("https://api.example.com");
275
+
276
+ rt.onStateChange((state) => {
277
+ console.log("Connection:", state); // 'connecting' | 'connected' | 'reconnecting' | 'disconnected'
278
+ });
279
+
280
+ await rt.connect();
281
+
282
+ // Subscribe to dataset changes
283
+ const unsub = rt.subscribeToDataset("recipes-dataset-id", (event) => {
284
+ console.log("Change:", event.event, event.entry);
285
+ });
286
+
287
+ // Presence (who's online)
288
+ rt.joinRoom("editor:doc-123");
289
+ rt.onPresence("editor:doc-123", (users) => {
290
+ console.log("Online users:", users);
291
+ });
292
+
293
+ // Cleanup
294
+ unsub();
295
+ rt.disconnect();
296
+ ```
297
+
298
+ ### Health Check
299
+
300
+ ```typescript
301
+ const healthy = await kitsuden.ping();
302
+ console.log("API is", healthy ? "up" : "down");
303
+ ```
304
+
305
+ ## Edge Runtime Support
306
+
307
+ Works in all edge runtimes with zero dependencies:
308
+
309
+ ```typescript
310
+ // Cloudflare Workers
311
+ export default {
312
+ async fetch(request: Request, env: Env) {
313
+ const kitsuden = new KitsudenClient({
314
+ url: env.KITSUDEN_URL,
315
+ apiKey: env.KITSUDEN_API_KEY,
316
+ });
317
+
318
+ const recipes = await kitsuden.from("recipes").list();
319
+ return Response.json(recipes);
320
+ },
321
+ };
322
+
323
+ // Vercel Edge
324
+ export const config = { runtime: "edge" };
325
+
326
+ export default async function handler(req: Request) {
327
+ const kitsuden = new KitsudenClient({
328
+ url: process.env.KITSUDEN_URL!,
329
+ apiKey: process.env.KITSUDEN_API_KEY,
330
+ });
331
+
332
+ const recipes = await kitsuden.from("recipes").list();
333
+ return new Response(JSON.stringify(recipes));
334
+ }
335
+ ```
336
+
337
+ ## Configuration Options
338
+
339
+ ```typescript
340
+ interface KitsudenClientConfig {
341
+ /** Base URL of your Kitsuden API */
342
+ url: string;
343
+ /** Agent NHI token for authentication (optional) */
344
+ apiKey?: string;
345
+ /** Wire format: 'json' (default), 'toon' or 'auto' */
346
+ format?: "json" | "toon" | "auto";
347
+ }
348
+ ```
349
+
350
+ ## API Reference
351
+
352
+ ### KitsudenClient
353
+
354
+ Main class for interacting with Kitsuden API.
355
+
356
+ #### `new KitsudenClient(config)`
357
+
358
+ Creates a new client instance.
359
+
360
+ #### `from<T>(table: string): TableRef<T>`
361
+
362
+ Returns a table reference for Explorer-based CRUD operations. **This is the recommended API.**
363
+
364
+ #### `schema(table: string): Promise<SchemaInfo>`
365
+
366
+ Returns column definitions, types, and relation info for a table.
367
+
368
+ #### `tables(): Promise<TableListItem[]>`
369
+
370
+ Lists all available tables with metadata.
371
+
372
+ #### `collection<T>(name: string): CollectionRef<T>`
373
+
374
+ Legacy Dataset API (backward compatibility). Use `.from()` for new code.
375
+
376
+ #### `ping(): Promise<boolean>`
377
+
378
+ Health check — returns `true` if the API is reachable.
379
+
380
+ ### TableRef
381
+
382
+ Primary CRUD interface. Returned by `.from(table)`.
383
+
384
+ | Method | Signature | Description |
385
+ | --------- | ----------------------------------------------------- | ---------------------------------- |
386
+ | `list` | `(options?: ListOptions) => Promise<ListResponse<T>>` | List with pagination, sort, filter |
387
+ | `get` | `(id: string) => Promise<T>` | Get single record by ID |
388
+ | `create` | `(data: Partial<T>) => Promise<T>` | Create new record |
389
+ | `update` | `(id: string, data: Partial<T>) => Promise<T>` | Update existing record |
390
+ | `delete` | `(id: string) => Promise<void>` | Delete record |
391
+ | `options` | `() => Promise<OptionItem[]>` | Get dropdown options for FKs |
392
+
393
+ ### KitsudenError
394
+
395
+ ```typescript
396
+ class KitsudenError extends Error {
397
+ statusCode: number; // HTTP status code
398
+ }
399
+ ```
400
+
401
+ ## Examples
402
+
403
+ ### Next.js App Router
404
+
405
+ ```typescript
406
+ // app/recipes/page.tsx
407
+ import { KitsudenClient } from '@kitsuden/sdk';
408
+
409
+ const kitsuden = new KitsudenClient({
410
+ url: process.env.KITSUDEN_URL!,
411
+ apiKey: process.env.KITSUDEN_API_KEY
412
+ });
413
+
414
+ export default async function RecipesPage() {
415
+ const recipes = await kitsuden.from('recipes').list({ limit: 10 });
416
+
417
+ return (
418
+ <ul>
419
+ {recipes.data.map(recipe => (
420
+ <li key={recipe.id}>{recipe.title}</li>
421
+ ))}
422
+ </ul>
423
+ );
424
+ }
425
+ ```
426
+
427
+ ### Astro
428
+
429
+ ```typescript
430
+ ---
431
+ import { KitsudenClient } from '@kitsuden/sdk';
432
+
433
+ const kitsuden = new KitsudenClient({
434
+ url: import.meta.env.KITSUDEN_URL,
435
+ apiKey: import.meta.env.KITSUDEN_API_KEY
436
+ });
437
+
438
+ const recipes = await kitsuden.from('recipes').list();
439
+ ---
440
+
441
+ <ul>
442
+ {recipes.data.map(recipe => (
443
+ <li>{recipe.title}</li>
444
+ ))}
445
+ </ul>
446
+ ```
447
+
448
+ ### SvelteKit
449
+
450
+ ```typescript
451
+ // +page.ts
452
+ import { KitsudenClient } from "@kitsuden/sdk";
453
+
454
+ const kitsuden = new KitsudenClient({
455
+ url: import.meta.env.VITE_KITSUDEN_URL,
456
+ apiKey: import.meta.env.VITE_KITSUDEN_API_KEY,
457
+ });
458
+
459
+ export async function load() {
460
+ const recipes = await kitsuden.from("recipes").list();
461
+ return { recipes };
462
+ }
463
+ ```
464
+
465
+ ## License
466
+
467
+ MIT © Kitsuden Contributors
468
+
469
+ ## Links
470
+
471
+ - [GitHub](https://github.com/Kitsuden/kitsuden)
472
+ - [Issues](https://github.com/Kitsuden/kitsuden/issues)
473
+
474
+ ---
475
+
476
+ Made with ❤️ by the Kitsuden contributors