bonescript-compiler 0.6.2 → 0.8.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.
@@ -0,0 +1,346 @@
1
+ /**
2
+ * BoneScript Prisma Schema Emitter
3
+ * Generates a Prisma schema file from the IR.
4
+ *
5
+ * Maps BoneScript entities, relations, and constraints to Prisma's
6
+ * schema language. Produces a single `schema.prisma` file that can
7
+ * be used with `npx prisma migrate dev` and `npx prisma generate`.
8
+ */
9
+
10
+ import * as IR from "./ir";
11
+ import { EmittedFile } from "./emitter";
12
+
13
+ function toSnakeCase(s: string): string {
14
+ return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
15
+ }
16
+
17
+ function toPascalCase(s: string): string {
18
+ return s.replace(/(^|[-_\s])(\w)/g, (_, __, c: string) => c.toUpperCase());
19
+ }
20
+
21
+ // ─── Type Mapping ─────────────────────────────────────────────────────────────
22
+
23
+ const PRISMA_TYPE_MAP: Record<string, string> = {
24
+ string: "String",
25
+ uint: "Int",
26
+ int: "Int",
27
+ float: "Float",
28
+ bool: "Boolean",
29
+ timestamp: "DateTime",
30
+ uuid: "String",
31
+ bytes: "Bytes",
32
+ json: "Json",
33
+ };
34
+
35
+ function toPrismaType(irType: string): string {
36
+ if (PRISMA_TYPE_MAP[irType]) return PRISMA_TYPE_MAP[irType];
37
+ const listMatch = irType.match(/^(list|set)<(.+)>$/);
38
+ if (listMatch) return `${toPrismaType(listMatch[2])}[]`;
39
+ const optMatch = irType.match(/^optional<(.+)>$/);
40
+ if (optMatch) return `${toPrismaType(optMatch[1])}?`;
41
+ // Entity reference — will be handled as a relation
42
+ return "String";
43
+ }
44
+
45
+ function toPrismaNativeType(irType: string): string | null {
46
+ switch (irType) {
47
+ case "uuid": return "@db.Uuid";
48
+ case "string": return null; // default is fine
49
+ case "json": return null; // Json maps directly
50
+ case "bytes": return null;
51
+ case "timestamp": return "@db.Timestamptz";
52
+ case "float": return "@db.DoublePrecision";
53
+ case "uint": return "@db.BigInt";
54
+ case "int": return "@db.BigInt";
55
+ default: return null;
56
+ }
57
+ }
58
+
59
+ // ─── Prisma Emitter ───────────────────────────────────────────────────────────
60
+
61
+ export class PrismaEmitter {
62
+ emit(system: IR.IRSystem): EmittedFile[] {
63
+ const files: EmittedFile[] = [];
64
+ files.push({
65
+ path: "prisma/schema.prisma",
66
+ content: this.emitSchema(system),
67
+ language: "typescript", // closest match for syntax highlighting
68
+ source_module: "prisma",
69
+ });
70
+ return files;
71
+ }
72
+
73
+ private emitSchema(system: IR.IRSystem): string {
74
+ const lines: string[] = [];
75
+
76
+ // Header
77
+ lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
78
+ lines.push(`// Source: ${system.name} (${system.source_hash})`);
79
+ lines.push(`// Run: npx prisma migrate dev --name init`);
80
+ lines.push(`// npx prisma generate`);
81
+ lines.push(``);
82
+
83
+ // Datasource
84
+ lines.push(`datasource db {`);
85
+ lines.push(` provider = "postgresql"`);
86
+ lines.push(` url = env("DATABASE_URL")`);
87
+ lines.push(`}`);
88
+ lines.push(``);
89
+
90
+ // Generator
91
+ lines.push(`generator client {`);
92
+ lines.push(` provider = "prisma-client-js"`);
93
+ lines.push(`}`);
94
+ lines.push(``);
95
+
96
+ // Collect all models across modules, deduplicating by name
97
+ const modelMap = new Map<string, { model: IR.IRModel; mod: IR.IRModule }>();
98
+ const allRelations: IR.IRRelation[] = [];
99
+
100
+ for (const mod of system.modules) {
101
+ if (mod.kind === "data_store" || mod.kind === "api_service") {
102
+ for (const model of mod.models) {
103
+ if (!modelMap.has(model.name)) {
104
+ modelMap.set(model.name, { model, mod });
105
+ }
106
+ }
107
+ allRelations.push(...mod.relations);
108
+ }
109
+ }
110
+
111
+ // Deduplicate relations by a stable key
112
+ const seenRelations = new Set<string>();
113
+ const uniqueRelations: IR.IRRelation[] = [];
114
+ for (const rel of allRelations) {
115
+ const key = `${rel.from_entity}:${rel.to_entity}:${rel.kind}:${rel.foreign_key}`;
116
+ if (!seenRelations.has(key)) {
117
+ seenRelations.add(key);
118
+ uniqueRelations.push(rel);
119
+ }
120
+ }
121
+
122
+ // Build a lookup: entity name → relations where it's the "from" side
123
+ const relationsFrom = new Map<string, IR.IRRelation[]>();
124
+ const relationsTo = new Map<string, IR.IRRelation[]>();
125
+ for (const rel of uniqueRelations) {
126
+ if (!relationsFrom.has(rel.from_entity)) relationsFrom.set(rel.from_entity, []);
127
+ relationsFrom.get(rel.from_entity)!.push(rel);
128
+ if (!relationsTo.has(rel.to_entity)) relationsTo.set(rel.to_entity, []);
129
+ relationsTo.get(rel.to_entity)!.push(rel);
130
+ }
131
+
132
+ // Emit each model
133
+ for (const [name, { model, mod }] of modelMap) {
134
+ lines.push(this.emitModel(name, model, mod, relationsFrom.get(name) || [], relationsTo.get(name) || [], modelMap));
135
+ lines.push(``);
136
+ }
137
+
138
+ // Emit junction tables for many_to_many
139
+ for (const rel of uniqueRelations) {
140
+ if (rel.kind === "many_to_many" && rel.junction_table) {
141
+ lines.push(this.emitJunctionModel(rel));
142
+ lines.push(``);
143
+ }
144
+ }
145
+
146
+ // Emit audit_log and event_outbox models (infrastructure)
147
+ lines.push(this.emitAuditLogModel());
148
+ lines.push(``);
149
+ lines.push(this.emitEventOutboxModel());
150
+ lines.push(``);
151
+
152
+ return lines.join("\n");
153
+ }
154
+
155
+ private emitModel(
156
+ name: string,
157
+ model: IR.IRModel,
158
+ mod: IR.IRModule,
159
+ relationsFrom: IR.IRRelation[],
160
+ relationsTo: IR.IRRelation[],
161
+ allModels: Map<string, { model: IR.IRModel; mod: IR.IRModule }>
162
+ ): string {
163
+ const lines: string[] = [];
164
+ const tableName = toSnakeCase(name) + "s";
165
+
166
+ lines.push(`model ${toPascalCase(name)} {`);
167
+
168
+ // Fields
169
+ for (const field of model.fields) {
170
+ lines.push(` ${this.emitField(field, model, name)}`);
171
+ }
172
+
173
+ // State field (if entity has a state machine)
174
+ const hasSM = mod.state_machines.some(sm => sm.entity === name);
175
+ const hasStateField = model.fields.some(f => f.name === "state");
176
+ if (hasSM && !hasStateField) {
177
+ lines.push(` state String`);
178
+ }
179
+
180
+ // Relation fields
181
+ for (const rel of relationsFrom) {
182
+ if (rel.kind === "belongs_to") {
183
+ // The FK field is already in the model fields. Add the relation object.
184
+ const targetModel = toPascalCase(rel.to_entity);
185
+ const fieldName = toSnakeCase(rel.to_entity);
186
+ lines.push(` ${fieldName} ${targetModel} @relation(fields: [${rel.foreign_key}], references: [id], onDelete: Cascade)`);
187
+ } else if (rel.kind === "has_many") {
188
+ const targetModel = toPascalCase(rel.to_entity);
189
+ const fieldName = toSnakeCase(rel.to_entity) + "s";
190
+ lines.push(` ${fieldName} ${targetModel}[]`);
191
+ } else if (rel.kind === "has_one") {
192
+ const targetModel = toPascalCase(rel.to_entity);
193
+ const fieldName = toSnakeCase(rel.to_entity);
194
+ lines.push(` ${fieldName} ${targetModel}?`);
195
+ }
196
+ }
197
+
198
+ // Inverse relations (where this model is the "to" side)
199
+ for (const rel of relationsTo) {
200
+ if (rel.kind === "belongs_to") {
201
+ // This model is the target of a belongs_to — add the inverse has_many
202
+ const sourceModel = toPascalCase(rel.from_entity);
203
+ const fieldName = toSnakeCase(rel.from_entity) + "s";
204
+ // Only add if not already covered by relationsFrom
205
+ const alreadyCovered = relationsFrom.some(r =>
206
+ r.to_entity === rel.from_entity && r.kind === "has_many"
207
+ );
208
+ if (!alreadyCovered) {
209
+ lines.push(` ${fieldName} ${sourceModel}[]`);
210
+ }
211
+ }
212
+ }
213
+
214
+ // Table mapping
215
+ lines.push(``);
216
+ lines.push(` @@map("${tableName}")`);
217
+
218
+ // Indexes
219
+ for (const idx of model.indexes) {
220
+ if (idx.unique) {
221
+ lines.push(` @@unique([${idx.fields.join(", ")}])`);
222
+ } else {
223
+ lines.push(` @@index([${idx.fields.join(", ")}])`);
224
+ }
225
+ }
226
+
227
+ lines.push(`}`);
228
+ return lines.join("\n");
229
+ }
230
+
231
+ private emitField(field: IR.IRField, model: IR.IRModel, entityName: string): string {
232
+ const parts: string[] = [];
233
+
234
+ // Field name (padded for alignment)
235
+ parts.push(field.name.padEnd(14));
236
+
237
+ // Type
238
+ let prismaType = toPrismaType(field.type);
239
+ if (field.nullable) prismaType += "?";
240
+ parts.push(prismaType.padEnd(12));
241
+
242
+ // Attributes
243
+ const attrs: string[] = [];
244
+
245
+ // Primary key
246
+ if (field.name === model.primary_key) {
247
+ attrs.push("@id");
248
+ }
249
+
250
+ // Default values
251
+ if (field.name === "id" && field.type === "uuid") {
252
+ attrs.push("@default(uuid())");
253
+ } else if (field.name === "created_at" || (field.type === "timestamp" && field.name.includes("created"))) {
254
+ attrs.push("@default(now())");
255
+ } else if (field.name === "updated_at") {
256
+ attrs.push("@updatedAt");
257
+ } else if (field.default_value) {
258
+ const dv = this.mapDefaultValue(field.default_value, field.type);
259
+ if (dv) attrs.push(dv);
260
+ }
261
+
262
+ // Unique constraint (skip if already primary key — @id implies uniqueness)
263
+ if (field.unique && field.name !== model.primary_key) {
264
+ attrs.push("@unique");
265
+ }
266
+
267
+ // Native type annotation
268
+ const nativeType = toPrismaNativeType(field.type);
269
+ if (nativeType) {
270
+ attrs.push(nativeType);
271
+ }
272
+
273
+ if (attrs.length > 0) {
274
+ parts.push(attrs.join(" "));
275
+ }
276
+
277
+ return parts.join(" ").trimEnd();
278
+ }
279
+
280
+ private mapDefaultValue(value: string, type: string): string | null {
281
+ if (value === "gen_random_uuid()" || value === "uuid()") return "@default(uuid())";
282
+ if (value === "now()") return "@default(now())";
283
+ if (value === "true" || value === "false") return `@default(${value})`;
284
+ if (/^\d+$/.test(value)) return `@default(${value})`;
285
+ if (/^\d+\.\d+$/.test(value)) return `@default(${value})`;
286
+ if (value.startsWith('"') && value.endsWith('"')) return `@default(${value})`;
287
+ return null;
288
+ }
289
+
290
+ private emitJunctionModel(rel: IR.IRRelation): string {
291
+ const lines: string[] = [];
292
+ const fromCol = toSnakeCase(rel.from_entity) + "_id";
293
+ const toCol = toSnakeCase(rel.to_entity) + "_id";
294
+
295
+ lines.push(`model ${toPascalCase(rel.junction_table!)} {`);
296
+ lines.push(` ${fromCol.padEnd(14)} String @db.Uuid`);
297
+ lines.push(` ${toCol.padEnd(14)} String @db.Uuid`);
298
+ lines.push(` created_at DateTime @default(now()) @db.Timestamptz`);
299
+ lines.push(``);
300
+ lines.push(` ${toSnakeCase(rel.from_entity).padEnd(14)} ${toPascalCase(rel.from_entity)} @relation(fields: [${fromCol}], references: [id], onDelete: Cascade)`);
301
+ lines.push(` ${toSnakeCase(rel.to_entity).padEnd(14)} ${toPascalCase(rel.to_entity)} @relation(fields: [${toCol}], references: [id], onDelete: Cascade)`);
302
+ lines.push(``);
303
+ lines.push(` @@id([${fromCol}, ${toCol}])`);
304
+ lines.push(` @@index([${fromCol}])`);
305
+ lines.push(` @@index([${toCol}])`);
306
+ lines.push(` @@map("${rel.junction_table}")`);
307
+ lines.push(`}`);
308
+ return lines.join("\n");
309
+ }
310
+
311
+ private emitAuditLogModel(): string {
312
+ return `model AuditLog {
313
+ id String @id @default(uuid()) @db.Uuid
314
+ actor_id String? @db.Uuid
315
+ action String
316
+ entity_type String
317
+ entity_id String? @db.Uuid
318
+ payload Json?
319
+ ip String?
320
+ user_agent String?
321
+ trace_id String? @db.Uuid
322
+ created_at DateTime @default(now()) @db.Timestamptz
323
+
324
+ @@index([actor_id])
325
+ @@index([entity_type, entity_id])
326
+ @@index([created_at])
327
+ @@map("audit_log")
328
+ }`;
329
+ }
330
+
331
+ private emitEventOutboxModel(): string {
332
+ return `model EventOutbox {
333
+ id String @id @default(uuid()) @db.Uuid
334
+ event_type String
335
+ payload Json
336
+ status String @default("pending")
337
+ attempts Int @default(0)
338
+ created_at DateTime @default(now()) @db.Timestamptz
339
+ processed_at DateTime? @db.Timestamptz
340
+ error String?
341
+
342
+ @@index([status, created_at])
343
+ @@map("event_outbox")
344
+ }`;
345
+ }
346
+ }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * BoneScript React Hooks Emitter
3
+ *
4
+ * Generates a typed React hooks file (sdk/react.ts) on top of the existing
5
+ * fetch SDK. Hooks are zero-dep — they use React's built-in useState +
6
+ * useEffect rather than pulling in @tanstack/react-query so consumers can
7
+ * decide their own data layer.
8
+ *
9
+ * For each entity:
10
+ * useList<Entity>() → { data, loading, error, refetch }
11
+ * use<Entity>(id) → { data, loading, error, refetch }
12
+ * useCreate<Entity>() → mutate(input) → Promise<Entity>
13
+ * useUpdate<Entity>() → mutate(id, patch) → Promise<Entity>
14
+ * useDelete<Entity>() → mutate(id) → Promise<void>
15
+ *
16
+ * For each capability:
17
+ * useCapability<Name>() → mutate(input) → Promise<unknown>
18
+ *
19
+ * Hooks are framework-agnostic in shape (no react-query, no SWR) so they work
20
+ * with Next.js, Vite, CRA, or any plain React app.
21
+ */
22
+
23
+ import * as IR from "./ir";
24
+ import { EmittedFile } from "./emitter";
25
+
26
+ function toSnakeCase(s: string): string {
27
+ return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
28
+ }
29
+
30
+ function toPascalCase(s: string): string {
31
+ return s.replace(/(^|[-_\s])(\w)/g, (_, __, c: string) => c.toUpperCase());
32
+ }
33
+
34
+ const TS_TYPE_MAP: Record<string, string> = {
35
+ string: "string", uint: "number", int: "number", float: "number",
36
+ bool: "boolean", timestamp: "string", uuid: "string", bytes: "string", json: "unknown",
37
+ };
38
+
39
+ function toTsType(irType: string): string {
40
+ if (TS_TYPE_MAP[irType]) return TS_TYPE_MAP[irType];
41
+ const m = irType.match(/^(list|set)<(.+)>$/);
42
+ if (m) return `${toTsType(m[2])}[]`;
43
+ const om = irType.match(/^optional<(.+)>$/);
44
+ if (om) return `${toTsType(om[1])} | null`;
45
+ return irType;
46
+ }
47
+
48
+ export function emitReactHooks(system: IR.IRSystem): EmittedFile {
49
+ const lines: string[] = [];
50
+
51
+ lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
52
+ lines.push(`// React hooks for the ${system.name} API.`);
53
+ lines.push(`//`);
54
+ lines.push(`// Pair with sdk/client.ts. Pass an instance of <System>Client to <ApiProvider>.`);
55
+ lines.push(``);
56
+ lines.push(`import { useCallback, useEffect, useState, createContext, useContext, ReactNode, createElement } from "react";`);
57
+ lines.push(``);
58
+
59
+ // Entity types (forward-declared so the hooks compile without importing the SDK)
60
+ // We re-declare them here to keep this file independent — the consumer can
61
+ // also import these types from sdk/client.ts if they prefer.
62
+ const apiModules = system.modules.filter(m => m.kind === "api_service" && m.models.length > 0);
63
+ for (const mod of apiModules) {
64
+ const model = mod.models[0];
65
+ lines.push(`export interface ${toPascalCase(model.name)} {`);
66
+ for (const field of model.fields) {
67
+ const optional = field.nullable ? "?" : "";
68
+ lines.push(` ${field.name}${optional}: ${toTsType(field.type)};`);
69
+ }
70
+ lines.push(`}`);
71
+ lines.push(``);
72
+ }
73
+
74
+ lines.push(`export interface ApiClient {`);
75
+ lines.push(` baseUrl: string;`);
76
+ lines.push(` getToken: () => string | null;`);
77
+ lines.push(`}`);
78
+ lines.push(``);
79
+ lines.push(`async function apiFetch<T>(client: ApiClient, method: string, path: string, body?: unknown): Promise<T> {`);
80
+ lines.push(` const headers: Record<string, string> = { "Content-Type": "application/json" };`);
81
+ lines.push(` const token = client.getToken();`);
82
+ lines.push(` if (token) headers["Authorization"] = "Bearer " + token;`);
83
+ lines.push(` const res = await fetch(client.baseUrl + path, {`);
84
+ lines.push(` method,`);
85
+ lines.push(` headers,`);
86
+ lines.push(` body: body !== undefined ? JSON.stringify(body) : undefined,`);
87
+ lines.push(` });`);
88
+ lines.push(` if (!res.ok) {`);
89
+ lines.push(` let errMsg = "Request failed: " + res.status;`);
90
+ lines.push(` try { const j = await res.json() as { error?: { message?: string } }; if (j.error?.message) errMsg = j.error.message; } catch {}`);
91
+ lines.push(` throw new Error(errMsg);`);
92
+ lines.push(` }`);
93
+ lines.push(` if (res.status === 204) return undefined as unknown as T;`);
94
+ lines.push(` return await res.json() as T;`);
95
+ lines.push(`}`);
96
+ lines.push(``);
97
+
98
+ // Provider + context. createElement avoids needing JSX in this generated file.
99
+ lines.push(`const ApiContext = createContext<ApiClient | null>(null);`);
100
+ lines.push(``);
101
+ lines.push(`export interface ApiProviderProps {`);
102
+ lines.push(` client: ApiClient;`);
103
+ lines.push(` children: ReactNode;`);
104
+ lines.push(`}`);
105
+ lines.push(``);
106
+ lines.push(`export function ApiProvider(props: ApiProviderProps) {`);
107
+ lines.push(` return createElement(ApiContext.Provider, { value: props.client }, props.children);`);
108
+ lines.push(`}`);
109
+ lines.push(``);
110
+ lines.push(`function useApi(): ApiClient {`);
111
+ lines.push(` const ctx = useContext(ApiContext);`);
112
+ lines.push(` if (!ctx) throw new Error("useApi must be used inside <ApiProvider>");`);
113
+ lines.push(` return ctx;`);
114
+ lines.push(`}`);
115
+ lines.push(``);
116
+
117
+ // Generic shape helpers
118
+ lines.push(`export interface QueryState<T> {`);
119
+ lines.push(` data: T | null;`);
120
+ lines.push(` loading: boolean;`);
121
+ lines.push(` error: Error | null;`);
122
+ lines.push(` refetch: () => Promise<void>;`);
123
+ lines.push(`}`);
124
+ lines.push(``);
125
+ lines.push(`export interface MutationState<TInput, TOutput> {`);
126
+ lines.push(` mutate: (input: TInput) => Promise<TOutput>;`);
127
+ lines.push(` loading: boolean;`);
128
+ lines.push(` error: Error | null;`);
129
+ lines.push(` reset: () => void;`);
130
+ lines.push(`}`);
131
+ lines.push(``);
132
+ lines.push(`export interface PaginatedResponse<T> {`);
133
+ lines.push(` items: T[];`);
134
+ lines.push(` total: number;`);
135
+ lines.push(` page: number;`);
136
+ lines.push(` page_size: number;`);
137
+ lines.push(`}`);
138
+ lines.push(``);
139
+
140
+ // Generic primitive hooks. Specific entity / capability hooks below wrap these.
141
+ lines.push(`function useQueryGeneric<T>(method: string, path: string, deps: unknown[]): QueryState<T> {`);
142
+ lines.push(` const client = useApi();`);
143
+ lines.push(` const [data, setData] = useState<T | null>(null);`);
144
+ lines.push(` const [loading, setLoading] = useState(true);`);
145
+ lines.push(` const [error, setError] = useState<Error | null>(null);`);
146
+ lines.push(` const fetchOnce = useCallback(async () => {`);
147
+ lines.push(` setLoading(true); setError(null);`);
148
+ lines.push(` try { const result = await apiFetch<T>(client, method, path); setData(result); }`);
149
+ lines.push(` catch (e: unknown) { setError(e instanceof Error ? e : new Error(String(e))); }`);
150
+ lines.push(` finally { setLoading(false); }`);
151
+ // eslint-disable-next-line react-hooks/exhaustive-deps
152
+ lines.push(` }, [client, method, path]);`);
153
+ lines.push(` useEffect(() => { void fetchOnce(); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, deps);`);
154
+ lines.push(` return { data, loading, error, refetch: fetchOnce };`);
155
+ lines.push(`}`);
156
+ lines.push(``);
157
+ lines.push(`function useMutationGeneric<TInput, TOutput>(builder: (input: TInput) => { method: string; path: string; body?: unknown }): MutationState<TInput, TOutput> {`);
158
+ lines.push(` const client = useApi();`);
159
+ lines.push(` const [loading, setLoading] = useState(false);`);
160
+ lines.push(` const [error, setError] = useState<Error | null>(null);`);
161
+ lines.push(` const mutate = useCallback(async (input: TInput): Promise<TOutput> => {`);
162
+ lines.push(` setLoading(true); setError(null);`);
163
+ lines.push(` try { const req = builder(input); return await apiFetch<TOutput>(client, req.method, req.path, req.body); }`);
164
+ lines.push(` catch (e: unknown) { const err = e instanceof Error ? e : new Error(String(e)); setError(err); throw err; }`);
165
+ lines.push(` finally { setLoading(false); }`);
166
+ lines.push(` }, [client, builder]);`);
167
+ lines.push(` const reset = useCallback(() => setError(null), []);`);
168
+ lines.push(` return { mutate, loading, error, reset };`);
169
+ lines.push(`}`);
170
+ lines.push(``);
171
+
172
+ // Per-entity hooks
173
+ for (const mod of apiModules) {
174
+ const model = mod.models[0];
175
+ const entity = toPascalCase(model.name);
176
+ const tableName = toSnakeCase(model.name) + "s";
177
+ const route = `/${tableName}`;
178
+
179
+ lines.push(`// ─── ${entity} ───────────────────────────────────────────────────────────`);
180
+ lines.push(``);
181
+
182
+ // List
183
+ lines.push(`export function useList${entity}(): QueryState<PaginatedResponse<${entity}>> {`);
184
+ lines.push(` return useQueryGeneric<PaginatedResponse<${entity}>>("GET", "${route}", []);`);
185
+ lines.push(`}`);
186
+ lines.push(``);
187
+
188
+ // Read
189
+ lines.push(`export function use${entity}(id: string | null): QueryState<${entity}> {`);
190
+ lines.push(` return useQueryGeneric<${entity}>("GET", id ? \`${route}/\${id}\` : "${route}", [id]);`);
191
+ lines.push(`}`);
192
+ lines.push(``);
193
+
194
+ // Create
195
+ const createInputType = `Partial<${entity}>`;
196
+ lines.push(`export function useCreate${entity}(): MutationState<${createInputType}, ${entity}> {`);
197
+ lines.push(` return useMutationGeneric<${createInputType}, ${entity}>((input) => ({ method: "POST", path: "${route}", body: input }));`);
198
+ lines.push(`}`);
199
+ lines.push(``);
200
+
201
+ // Update
202
+ lines.push(`export function useUpdate${entity}(): MutationState<{ id: string; patch: Partial<${entity}> }, ${entity}> {`);
203
+ lines.push(` return useMutationGeneric<{ id: string; patch: Partial<${entity}> }, ${entity}>(({ id, patch }) => ({ method: "PUT", path: \`${route}/\${id}\`, body: patch }));`);
204
+ lines.push(`}`);
205
+ lines.push(``);
206
+
207
+ // Delete
208
+ lines.push(`export function useDelete${entity}(): MutationState<string, void> {`);
209
+ lines.push(` return useMutationGeneric<string, void>((id) => ({ method: "DELETE", path: \`${route}/\${id}\` }));`);
210
+ lines.push(`}`);
211
+ lines.push(``);
212
+
213
+ // Capability hooks
214
+ for (const iface of mod.interfaces) {
215
+ for (const method of iface.methods) {
216
+ if (["create", "read", "update", "delete", "list"].includes(method.name)) continue;
217
+ const capName = toPascalCase(method.name);
218
+ const inputType = method.input.length > 0
219
+ ? `{ ${method.input.map(p => `${p.name}${p.nullable ? "?" : ""}: ${toTsType(p.type)}`).join("; ")} }`
220
+ : "Record<string, never>";
221
+ const endpoint = `${route}/${method.name.replace(/_/g, "-")}`;
222
+ lines.push(`export function useCapability${capName}(): MutationState<${inputType}, unknown> {`);
223
+ lines.push(` return useMutationGeneric<${inputType}, unknown>((input) => ({ method: "POST", path: "${endpoint}", body: input }));`);
224
+ lines.push(`}`);
225
+ lines.push(``);
226
+ }
227
+ }
228
+ }
229
+
230
+ return {
231
+ path: "sdk/react.ts",
232
+ content: lines.join("\n"),
233
+ language: "typescript",
234
+ source_module: "sdk",
235
+ };
236
+ }