bonescript-compiler 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +21 -21
  2. package/dist/algorithm_catalog.js +166 -166
  3. package/dist/cli.d.ts +2 -1
  4. package/dist/cli.js +75 -543
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/check.d.ts +5 -0
  7. package/dist/commands/check.js +34 -0
  8. package/dist/commands/check.js.map +1 -0
  9. package/dist/commands/compile.d.ts +5 -0
  10. package/dist/commands/compile.js +215 -0
  11. package/dist/commands/compile.js.map +1 -0
  12. package/dist/commands/debug.d.ts +5 -0
  13. package/dist/commands/debug.js +59 -0
  14. package/dist/commands/debug.js.map +1 -0
  15. package/dist/commands/diff.d.ts +5 -0
  16. package/dist/commands/diff.js +125 -0
  17. package/dist/commands/diff.js.map +1 -0
  18. package/dist/commands/fmt.d.ts +5 -0
  19. package/dist/commands/fmt.js +49 -0
  20. package/dist/commands/fmt.js.map +1 -0
  21. package/dist/commands/init.d.ts +5 -0
  22. package/dist/commands/init.js +96 -0
  23. package/dist/commands/init.js.map +1 -0
  24. package/dist/commands/ir.d.ts +5 -0
  25. package/dist/commands/ir.js +27 -0
  26. package/dist/commands/ir.js.map +1 -0
  27. package/dist/commands/lex.d.ts +5 -0
  28. package/dist/commands/lex.js +21 -0
  29. package/dist/commands/lex.js.map +1 -0
  30. package/dist/commands/parse.d.ts +5 -0
  31. package/dist/commands/parse.js +30 -0
  32. package/dist/commands/parse.js.map +1 -0
  33. package/dist/commands/test.d.ts +5 -0
  34. package/dist/commands/test.js +61 -0
  35. package/dist/commands/test.js.map +1 -0
  36. package/dist/commands/verify_determinism.d.ts +5 -0
  37. package/dist/commands/verify_determinism.js +64 -0
  38. package/dist/commands/verify_determinism.js.map +1 -0
  39. package/dist/commands/watch.d.ts +5 -0
  40. package/dist/commands/watch.js +50 -0
  41. package/dist/commands/watch.js.map +1 -0
  42. package/dist/emit_auth.d.ts +6 -0
  43. package/dist/emit_auth.js +69 -0
  44. package/dist/emit_auth.js.map +1 -0
  45. package/dist/emit_capability.d.ts +13 -0
  46. package/dist/emit_capability.js +292 -128
  47. package/dist/emit_capability.js.map +1 -1
  48. package/dist/emit_composition.js +37 -3
  49. package/dist/emit_composition.js.map +1 -1
  50. package/dist/emit_database.d.ts +7 -0
  51. package/dist/emit_database.js +74 -0
  52. package/dist/emit_database.js.map +1 -0
  53. package/dist/emit_deploy.js +162 -162
  54. package/dist/emit_events.d.ts +1 -0
  55. package/dist/emit_events.js +342 -275
  56. package/dist/emit_events.js.map +1 -1
  57. package/dist/emit_full.js +135 -95
  58. package/dist/emit_full.js.map +1 -1
  59. package/dist/emit_index.d.ts +6 -0
  60. package/dist/emit_index.js +157 -0
  61. package/dist/emit_index.js.map +1 -0
  62. package/dist/emit_maintenance.js +249 -249
  63. package/dist/emit_models.d.ts +12 -0
  64. package/dist/emit_models.js +171 -0
  65. package/dist/emit_models.js.map +1 -0
  66. package/dist/emit_openapi.d.ts +9 -0
  67. package/dist/emit_openapi.js +308 -0
  68. package/dist/emit_openapi.js.map +1 -0
  69. package/dist/emit_package.d.ts +7 -0
  70. package/dist/emit_package.js +70 -0
  71. package/dist/emit_package.js.map +1 -0
  72. package/dist/emit_router.d.ts +12 -0
  73. package/dist/emit_router.js +390 -0
  74. package/dist/emit_router.js.map +1 -0
  75. package/dist/emit_runtime.d.ts +17 -11
  76. package/dist/emit_runtime.js +29 -686
  77. package/dist/emit_runtime.js.map +1 -1
  78. package/dist/emit_sourcemap.js +66 -66
  79. package/dist/emit_tests.js +37 -0
  80. package/dist/emit_tests.js.map +1 -1
  81. package/dist/emitter.js +34 -5
  82. package/dist/emitter.js.map +1 -1
  83. package/dist/extension_manager.d.ts +2 -2
  84. package/dist/extension_manager.js +6 -3
  85. package/dist/extension_manager.js.map +1 -1
  86. package/dist/lowering.d.ts +5 -14
  87. package/dist/lowering.js +47 -417
  88. package/dist/lowering.js.map +1 -1
  89. package/dist/lowering_channels.d.ts +11 -0
  90. package/dist/lowering_channels.js +102 -0
  91. package/dist/lowering_channels.js.map +1 -0
  92. package/dist/lowering_entities.d.ts +11 -0
  93. package/dist/lowering_entities.js +222 -0
  94. package/dist/lowering_entities.js.map +1 -0
  95. package/dist/lowering_helpers.d.ts +13 -0
  96. package/dist/lowering_helpers.js +76 -0
  97. package/dist/lowering_helpers.js.map +1 -0
  98. package/dist/module_loader.d.ts +2 -2
  99. package/dist/module_loader.js +20 -23
  100. package/dist/module_loader.js.map +1 -1
  101. package/dist/scaffold.d.ts +2 -2
  102. package/dist/scaffold.js +316 -319
  103. package/dist/scaffold.js.map +1 -1
  104. package/dist/typechecker.js +32 -13
  105. package/dist/typechecker.js.map +1 -1
  106. package/dist/verifier.d.ts +5 -0
  107. package/dist/verifier.js +140 -2
  108. package/dist/verifier.js.map +1 -1
  109. package/package.json +62 -52
  110. package/src/algorithm_catalog.ts +345 -345
  111. package/src/ast.ts +334 -334
  112. package/src/cli.ts +98 -624
  113. package/src/commands/check.ts +33 -0
  114. package/src/commands/compile.ts +191 -0
  115. package/src/commands/debug.ts +33 -0
  116. package/src/commands/diff.ts +108 -0
  117. package/src/commands/fmt.ts +22 -0
  118. package/src/commands/init.ts +72 -0
  119. package/src/commands/ir.ts +23 -0
  120. package/src/commands/lex.ts +17 -0
  121. package/src/commands/parse.ts +24 -0
  122. package/src/commands/test.ts +36 -0
  123. package/src/commands/verify_determinism.ts +66 -0
  124. package/src/commands/watch.ts +25 -0
  125. package/src/emit_auth.ts +67 -0
  126. package/src/emit_batch.ts +140 -140
  127. package/src/emit_capability.ts +617 -436
  128. package/src/emit_composition.ts +229 -196
  129. package/src/emit_database.ts +75 -0
  130. package/src/emit_deploy.ts +190 -190
  131. package/src/emit_events.ts +377 -307
  132. package/src/emit_extras.ts +240 -240
  133. package/src/emit_full.ts +351 -309
  134. package/src/emit_index.ts +161 -0
  135. package/src/emit_maintenance.ts +459 -459
  136. package/src/emit_models.ts +176 -0
  137. package/src/emit_openapi.ts +318 -0
  138. package/src/emit_package.ts +69 -0
  139. package/src/emit_router.ts +409 -0
  140. package/src/emit_runtime.ts +17 -728
  141. package/src/emit_sourcemap.ts +140 -140
  142. package/src/emit_tests.ts +246 -205
  143. package/src/emit_websocket.ts +229 -229
  144. package/src/emitter.ts +31 -5
  145. package/src/extension_manager.ts +189 -187
  146. package/src/formatter.ts +297 -297
  147. package/src/index.ts +88 -88
  148. package/src/ir.ts +215 -215
  149. package/src/lexer.ts +630 -630
  150. package/src/lowering.ts +142 -556
  151. package/src/lowering_channels.ts +107 -0
  152. package/src/lowering_entities.ts +248 -0
  153. package/src/lowering_helpers.ts +75 -0
  154. package/src/module_loader.ts +112 -114
  155. package/src/optimizer.ts +196 -196
  156. package/src/parse_decls.ts +409 -409
  157. package/src/parse_decls2.ts +244 -244
  158. package/src/parse_expr.ts +197 -197
  159. package/src/parse_types.ts +54 -54
  160. package/src/parser.ts +1 -1
  161. package/src/parser_base.ts +57 -57
  162. package/src/parser_recovery.ts +153 -153
  163. package/src/scaffold.ts +372 -375
  164. package/src/solver.ts +330 -330
  165. package/src/typechecker.ts +30 -15
  166. package/src/types.ts +122 -122
  167. package/src/verifier.ts +151 -4
@@ -1,691 +1,34 @@
1
1
  "use strict";
2
2
  /**
3
- * BoneScript Runtime Code Emitter
4
- * Generates runnable service code from IR.
3
+ * BoneScript Runtime Emitter — barrel re-export.
4
+ *
5
+ * This file previously contained all runtime code generation in one place.
6
+ * It has been split into focused modules:
7
+ *
8
+ * emit_package.ts — emitPackageJson, emitTsConfig
9
+ * emit_database.ts — emitDbClient, emitMigration
10
+ * emit_auth.ts — emitAuthMiddleware
11
+ * emit_router.ts — emitEntityRouter, emitCapabilityEndpoint, emitStateMachineRuntime
12
+ * emit_index.ts — emitIndex (Express server entry point)
13
+ *
14
+ * All exports are re-exported here so existing imports continue to work.
5
15
  */
6
16
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.emitMigration = exports.emitIndex = exports.emitStateMachineRuntime = exports.emitEntityRouter = exports.emitAuthMiddleware = exports.emitDbClient = exports.emitTsConfig = exports.emitPackageJson = void 0;
8
- const emit_capability_1 = require("./emit_capability");
9
- function toSnakeCase(s) {
10
- return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
11
- }
12
- function toCamelCase(s) {
13
- return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
14
- }
15
- function toPascalCase(s) {
16
- const c = toCamelCase(s);
17
- return c.charAt(0).toUpperCase() + c.slice(1);
18
- }
19
- const TS_TYPE_MAP = {
20
- string: "string", uint: "number", int: "number", float: "number",
21
- bool: "boolean", timestamp: "Date", uuid: "string", bytes: "Buffer", json: "unknown",
22
- };
23
- function toTsType(irType) {
24
- if (TS_TYPE_MAP[irType])
25
- return TS_TYPE_MAP[irType];
26
- const m = irType.match(/^(list|set)<(.+)>$/);
27
- if (m)
28
- return `${toTsType(m[2])}[]`;
29
- const om = irType.match(/^optional<(.+)>$/);
30
- if (om)
31
- return `${toTsType(om[1])} | null`;
32
- return irType;
33
- }
34
- // ─── Package.json ─────────────────────────────────────────────────────────────
35
- function emitPackageJson(system) {
36
- const pkg = {
37
- name: toSnakeCase(system.name),
38
- version: system.version,
39
- private: true,
40
- scripts: {
41
- build: "tsc",
42
- start: "node dist/index.js",
43
- dev: "ts-node src/index.ts",
44
- migrate: "ts-node src/migrate.ts",
45
- },
46
- dependencies: {
47
- express: "4.18.2",
48
- pg: "8.11.3",
49
- ioredis: "5.3.2",
50
- ws: "8.16.0",
51
- uuid: "9.0.0",
52
- cors: "2.8.5",
53
- helmet: "7.1.0",
54
- "express-rate-limit": "7.1.5",
55
- jsonwebtoken: "9.0.2",
56
- dotenv: "16.3.1",
57
- },
58
- devDependencies: {
59
- "@types/express": "4.17.21",
60
- "@types/node": "18.19.0",
61
- "@types/pg": "8.10.9",
62
- "@types/ws": "8.5.10",
63
- "@types/cors": "2.8.17",
64
- "@types/jsonwebtoken": "9.0.5",
65
- "@types/uuid": "9.0.7",
66
- typescript: "5.3.3",
67
- "ts-node": "10.9.2",
68
- },
69
- };
70
- return JSON.stringify(pkg, null, 2);
71
- }
72
- exports.emitPackageJson = emitPackageJson;
73
- // ─── tsconfig.json ────────────────────────────────────────────────────────────
74
- function emitTsConfig() {
75
- const cfg = {
76
- compilerOptions: {
77
- target: "ES2020",
78
- module: "commonjs",
79
- lib: ["ES2020"],
80
- outDir: "./dist",
81
- rootDir: "./src",
82
- strict: true,
83
- esModuleInterop: true,
84
- skipLibCheck: true,
85
- forceConsistentCasingInFileNames: true,
86
- declaration: true,
87
- sourceMap: true,
88
- },
89
- include: ["src/**/*"],
90
- exclude: ["node_modules", "dist"],
91
- };
92
- return JSON.stringify(cfg, null, 2);
93
- }
94
- exports.emitTsConfig = emitTsConfig;
95
- // ─── Database Client ──────────────────────────────────────────────────────────
96
- function emitDbClient(system) {
97
- const name = toSnakeCase(system.name);
98
- return [
99
- "// Generated by BoneScript compiler. DO NOT EDIT.",
100
- "import { Pool, PoolClient } from \"pg\";",
101
- "",
102
- "// Lazy pool — created on first use so DATABASE_URL is read after dotenv loads",
103
- "let _pool: Pool | null = null;",
104
- "function getPool(): Pool {",
105
- " if (!_pool) {",
106
- ` _pool = new Pool({ connectionString: process.env.DATABASE_URL || "postgresql://localhost:5432/${name}", max: 20 });`,
107
- " _pool.on(\"error\", (err: Error) => console.error(\"[DB] Pool error (non-fatal):\", err.message));",
108
- " }",
109
- " return _pool;",
110
- "}",
111
- "export const pool = new Proxy({} as Pool, { get(_t: any, p: any) { return (getPool() as any)[p]; } });",
112
- "",
113
- "export async function query<T = any>(text: string, params?: any[]): Promise<T[]> {",
114
- " try { const result = await pool.query(text, params); return result.rows as T[]; }",
115
- " catch (e: any) { throw new Error(`DB query failed: ${e.message}`); }",
116
- "}",
117
- "export async function queryOne<T = any>(text: string, params?: any[]): Promise<T | null> {",
118
- " try { const rows = await query<T>(text, params); return rows[0] || null; }",
119
- " catch (e: any) { throw new Error(`DB query failed: ${e.message}`); }",
120
- "}",
121
- "export async function execute(text: string, params?: any[]): Promise<number> {",
122
- " try { const result = await pool.query(text, params); return result.rowCount || 0; }",
123
- " catch (e: any) { throw new Error(`DB execute failed: ${e.message}`); }",
124
- "}",
125
- "export async function transaction<T>(fn: (client: PoolClient) => Promise<T>): Promise<T> {",
126
- " const client = await pool.connect();",
127
- " try { await client.query(\"BEGIN\"); const result = await fn(client); await client.query(\"COMMIT\"); return result; }",
128
- " catch (e) { await client.query(\"ROLLBACK\"); throw e; }",
129
- " finally { client.release(); }",
130
- "}",
131
- ].join("\n");
132
- }
133
- exports.emitDbClient = emitDbClient;
134
- function emitAuthMiddleware(system) {
135
- return `// Generated by BoneScript compiler. DO NOT EDIT.
136
- import { Request, Response, NextFunction } from "express";
137
- import jwt from "jsonwebtoken";
138
-
139
- // JWT_SECRET must be set in production. The server will refuse to start without it
140
- // when NODE_ENV is "production" to prevent accidental use of a weak fallback.
141
- const JWT_SECRET = (() => {
142
- const secret = process.env.JWT_SECRET;
143
- if (!secret) {
144
- if (process.env.NODE_ENV === "production") {
145
- console.error("[FATAL] JWT_SECRET environment variable is not set. Refusing to start in production.");
146
- process.exit(1);
147
- }
148
- console.warn("[WARN] JWT_SECRET is not set. Using insecure default — do not use in production.");
149
- return "bonescript-dev-secret-do-not-use-in-production";
150
- }
151
- if (secret.length < 32) {
152
- console.warn("[WARN] JWT_SECRET is shorter than 32 characters. Use a longer secret in production.");
153
- }
154
- return secret;
155
- })();
156
-
157
- export interface AuthContext {
158
- authenticated: boolean;
159
- actor_id: string | null;
160
- trace_id: string;
161
- }
162
-
163
- export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
164
- const header = req.headers.authorization;
165
- if (!header || !header.startsWith("Bearer ")) {
166
- (req as any).auth = { authenticated: false, actor_id: null, trace_id: req.headers["x-trace-id"] as string || "" };
167
- next();
168
- return;
169
- }
170
- try {
171
- const token = header.slice(7);
172
- const decoded = jwt.verify(token, JWT_SECRET) as { sub: string };
173
- (req as any).auth = {
174
- authenticated: true,
175
- actor_id: decoded.sub,
176
- trace_id: req.headers["x-trace-id"] as string || "",
177
- };
178
- } catch {
179
- (req as any).auth = { authenticated: false, actor_id: null, trace_id: req.headers["x-trace-id"] as string || "" };
180
- }
181
- next();
182
- }
183
-
184
- export function requireAuth(req: Request, res: Response, next: NextFunction): void {
185
- const auth: AuthContext = (req as any).auth;
186
- if (!auth || !auth.authenticated) {
187
- res.status(401).json({ error: { code: "UNAUTHORIZED", message: "Authentication required" } });
188
- return;
189
- }
190
- next();
191
- }
192
- `;
193
- }
194
- exports.emitAuthMiddleware = emitAuthMiddleware;
195
- // ─── Entity Router ────────────────────────────────────────────────────────────
196
- function emitEntityRouter(mod, system) {
197
- const entityModel = mod.models[0];
198
- if (!entityModel)
199
- return "";
200
- const tableName = toSnakeCase(entityModel.name) + "s";
201
- const routeBase = toSnakeCase(entityModel.name) + "s";
202
- const lines = [];
203
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
204
- lines.push(`// Service: ${mod.name}`);
205
- lines.push(`import { Router, Request, Response } from "express";`);
206
- lines.push(`import { v4 as uuid } from "uuid";`);
207
- lines.push(`import { query, queryOne, execute, pool } from "../db";`);
208
- lines.push(`import { eventBus } from "../events";`);
209
- lines.push(`import { requireAuth, AuthContext } from "../auth";`);
210
- lines.push(`import { logger } from "../logger";`);
211
- lines.push(`import { counter } from "../metrics";`);
212
- lines.push(`import * as __algorithms from "../algorithms";`);
213
- lines.push(`const { shortestPath, topologicalSort, binarySearch, bipartiteMatching, roundRobin, weightedAverage, percentile, rankBy, consistentHash } = __algorithms as any;`);
214
- lines.push(``);
215
- // Collect unknown function calls from capability effects and emit stubs
216
- const unknownFunctions = collectUnknownFunctions(mod);
217
- if (unknownFunctions.size > 0) {
218
- lines.push(`// User-defined functions referenced in effects — implement these or use extension_point`);
219
- for (const fn of unknownFunctions) {
220
- lines.push(`declare function ${fn}(...args: any[]): any;`);
221
- }
222
- lines.push(``);
223
- }
224
- if (mod.state_machines.length > 0) {
225
- const sm = mod.state_machines[0];
226
- lines.push(`import { transition${sm.entity}, ${sm.entity.toUpperCase()}_INITIAL } from "../state_machines/${toSnakeCase(sm.entity)}";`);
227
- lines.push(``);
228
- }
229
- lines.push(`export const ${toCamelCase(routeBase)}Router = Router();`);
230
- lines.push(``);
231
- // CREATE
232
- const insertFields = entityModel.fields.filter(f => f.name !== "id" && f.name !== "created_at" && f.name !== "updated_at");
233
- lines.push(`// CREATE`);
234
- lines.push(`${toCamelCase(routeBase)}Router.post("/", requireAuth, async (req: Request, res: Response) => {`);
235
- lines.push(` try {`);
236
- lines.push(` const id = uuid();`);
237
- lines.push(` const { ${insertFields.map(f => f.name).join(", ")} } = req.body;`);
238
- if (mod.state_machines.length > 0) {
239
- lines.push(` const state = ${mod.state_machines[0].entity.toUpperCase()}_INITIAL;`);
240
- }
241
- const allInsertFields = ["id", ...insertFields.map(f => f.name)];
242
- if (mod.state_machines.length > 0 && !insertFields.find(f => f.name === "state")) {
243
- allInsertFields.push("state");
244
- }
245
- const placeholders = allInsertFields.map((_, i) => `$${i + 1}`).join(", ");
246
- const values = allInsertFields.map(f => f === "id" ? "id" : f === "state" ? "state" : f).join(", ");
247
- lines.push(` const sql = \`INSERT INTO ${tableName} (${allInsertFields.join(", ")}) VALUES (${placeholders}) RETURNING *\`;`);
248
- lines.push(` const rows = await query(sql, [${values}]);`);
249
- lines.push(` counter("entity.created", { entity: "${entityModel.name}" });`);
250
- lines.push(` res.status(201).json(rows[0]);`);
251
- lines.push(` } catch (e: any) {`);
252
- lines.push(` res.status(400).json({ error: { code: "CREATE_FAILED", message: e.message } });`);
253
- lines.push(` }`);
254
- lines.push(`});`);
255
- lines.push(``);
256
- // READ
257
- lines.push(`// READ`);
258
- lines.push(`${toCamelCase(routeBase)}Router.get("/:id", requireAuth, async (req: Request, res: Response) => {`);
259
- lines.push(` try {`);
260
- lines.push(` const row = await queryOne(\`SELECT * FROM ${tableName} WHERE id = $1\`, [req.params.id]);`);
261
- lines.push(` if (!row) return res.status(404).json({ error: { code: "NOT_FOUND", message: "Not found" } });`);
262
- lines.push(` res.json(row);`);
263
- lines.push(` } catch (e: any) {`);
264
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
265
- lines.push(` }`);
266
- lines.push(`});`);
267
- lines.push(``);
268
- // LIST — with optional JOINs for has_one/belongs_to relations
269
- const joinRelations = mod.relations.filter(r => r.kind === "has_one" || r.kind === "belongs_to");
270
- lines.push(`// LIST`);
271
- lines.push(`${toCamelCase(routeBase)}Router.get("/", requireAuth, async (req: Request, res: Response) => {`);
272
- lines.push(` try {`);
273
- lines.push(` const page = parseInt(req.query.page as string) || 1;`);
274
- lines.push(` const pageSize = Math.min(parseInt(req.query.page_size as string) || 50, 100);`);
275
- lines.push(` const offset = (page - 1) * pageSize;`);
276
- if (joinRelations.length > 0) {
277
- const joinClauses = joinRelations.map(r => {
278
- const alias = r.to_table.slice(0, -1);
279
- if (r.kind === "belongs_to") {
280
- return `LEFT JOIN ${r.to_table} ${alias} ON ${tableName}.${r.foreign_key} = ${alias}.id`;
281
- }
282
- else {
283
- return `LEFT JOIN ${r.to_table} ${alias} ON ${alias}.${r.foreign_key} = ${tableName}.id`;
284
- }
285
- }).join(" ");
286
- lines.push(` const rows = await query(\`SELECT ${tableName}.*, ${joinRelations.map(r => `row_to_json(${r.to_table.slice(0, -1)}.*) as ${r.name}`).join(", ")} FROM ${tableName} ${joinClauses} ORDER BY ${tableName}.created_at DESC LIMIT $1 OFFSET $2\`, [pageSize, offset]);`);
287
- }
288
- else {
289
- lines.push(` const rows = await query(\`SELECT * FROM ${tableName} ORDER BY created_at DESC LIMIT $1 OFFSET $2\`, [pageSize, offset]);`);
290
- }
291
- lines.push(` const [{ count }] = await query(\`SELECT COUNT(*) as count FROM ${tableName}\`);`);
292
- lines.push(` res.json({ items: rows, total: parseInt(count), page, page_size: pageSize });`);
293
- lines.push(` } catch (e: any) {`);
294
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
295
- lines.push(` }`);
296
- lines.push(`});`);
297
- lines.push(``);
298
- // UPDATE — with state machine enforcement
299
- lines.push(`// UPDATE`);
300
- lines.push(`${toCamelCase(routeBase)}Router.put("/:id", requireAuth, async (req: Request, res: Response) => {`);
301
- lines.push(` const fields = { ...req.body };`);
302
- if (mod.state_machines.length > 0) {
303
- const sm = mod.state_machines[0];
304
- lines.push(` // State machine enforcement`);
305
- lines.push(` if (fields.state !== undefined) {`);
306
- lines.push(` const current = await queryOne<{ state: string }>(\`SELECT state FROM ${tableName} WHERE id = $1\`, [req.params.id]);`);
307
- lines.push(` if (!current) return res.status(404).json({ error: { code: "NOT_FOUND", message: "Not found" } });`);
308
- lines.push(` // Find the trigger for this state transition`);
309
- lines.push(` const trigger = \`\${current.state}_to_\${fields.state}\`;`);
310
- lines.push(` const tr = transition${sm.entity}(current.state as any, trigger);`);
311
- lines.push(` if (!tr.ok) return res.status(422).json({ error: { code: "INVALID_TRANSITION", message: \`Cannot transition from \${current.state} to \${fields.state}\` } });`);
312
- lines.push(` }`);
313
- }
314
- lines.push(` const sets = Object.keys(fields).map((k, i) => \`\${k} = $\${i + 2}\`).join(", ");`);
315
- lines.push(` const values = Object.values(fields);`);
316
- lines.push(` const sql = \`UPDATE ${tableName} SET \${sets}, updated_at = NOW() WHERE id = $1 RETURNING *\`;`);
317
- lines.push(` const rows = await query(sql, [req.params.id, ...values]);`);
318
- lines.push(` if (rows.length === 0) return res.status(404).json({ error: { code: "NOT_FOUND", message: "Not found" } });`);
319
- lines.push(` res.json(rows[0]);`);
320
- lines.push(`});`);
321
- lines.push(``);
322
- // DELETE
323
- lines.push(`// DELETE`);
324
- lines.push(`${toCamelCase(routeBase)}Router.delete("/:id", requireAuth, async (req: Request, res: Response) => {`);
325
- lines.push(` try {`);
326
- lines.push(` const count = await execute(\`DELETE FROM ${tableName} WHERE id = $1\`, [req.params.id]);`);
327
- lines.push(` if (count === 0) return res.status(404).json({ error: { code: "NOT_FOUND", message: "Not found" } });`);
328
- lines.push(` res.status(204).send();`);
329
- lines.push(` } catch (e: any) {`);
330
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
331
- lines.push(` }`);
332
- lines.push(`});`);
333
- lines.push(``);
334
- // Capability endpoints
335
- for (const iface of mod.interfaces) {
336
- for (const method of iface.methods) {
337
- if (["create", "read", "update", "delete", "list"].includes(method.name))
338
- continue;
339
- lines.push(emitCapabilityEndpoint(method, mod, tableName, system));
340
- }
341
- }
342
- // has_many relation endpoints: GET /:id/relation-name
343
- for (const rel of mod.relations) {
344
- if (rel.kind === "has_many") {
345
- lines.push(`// RELATION: ${rel.name} (has_many ${rel.to_entity})`);
346
- lines.push(`${toCamelCase(routeBase)}Router.get("/:id/${rel.name}", requireAuth, async (req: Request, res: Response) => {`);
347
- lines.push(` try {`);
348
- lines.push(` const page = parseInt(req.query.page as string) || 1;`);
349
- lines.push(` const pageSize = Math.min(parseInt(req.query.page_size as string) || 50, 100);`);
350
- lines.push(` const offset = (page - 1) * pageSize;`);
351
- lines.push(` const rows = await query(\`SELECT * FROM ${rel.to_table} WHERE ${rel.foreign_key} = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3\`, [req.params.id, pageSize, offset]);`);
352
- lines.push(` const [{ count }] = await query(\`SELECT COUNT(*) as count FROM ${rel.to_table} WHERE ${rel.foreign_key} = $1\`, [req.params.id]);`);
353
- lines.push(` res.json({ items: rows, total: parseInt(count), page, page_size: pageSize });`);
354
- lines.push(` } catch (e: any) {`);
355
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
356
- lines.push(` }`);
357
- lines.push(`});`);
358
- lines.push(``);
359
- }
360
- if (rel.kind === "many_to_many" && rel.junction_table) {
361
- lines.push(`// RELATION: ${rel.name} (many_to_many ${rel.to_entity})`);
362
- lines.push(`${toCamelCase(routeBase)}Router.get("/:id/${rel.name}", requireAuth, async (req: Request, res: Response) => {`);
363
- lines.push(` try {`);
364
- lines.push(` const rows = await query(\`SELECT ${rel.to_table}.* FROM ${rel.to_table} INNER JOIN ${rel.junction_table} ON ${rel.junction_table}.${rel.to_table.slice(0, -1)}_id = ${rel.to_table}.id WHERE ${rel.junction_table}.${rel.from_table.slice(0, -1)}_id = $1\`, [req.params.id]);`);
365
- lines.push(` res.json({ items: rows, total: rows.length });`);
366
- lines.push(` } catch (e: any) {`);
367
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
368
- lines.push(` }`);
369
- lines.push(`});`);
370
- lines.push(``);
371
- }
372
- }
373
- return lines.join("\n");
374
- }
375
- exports.emitEntityRouter = emitEntityRouter;
376
- function emitCapabilityEndpoint(method, mod, tableName, system) {
377
- const lines = [];
378
- const routerName = toCamelCase(toSnakeCase(mod.models[0]?.name || mod.name) + "s") + "Router";
379
- const endpoint = `/${method.name.replace(/_/g, "-")}`;
380
- const isTransactional = method.sync === "transactional";
381
- lines.push(`// CAPABILITY: ${method.name}${isTransactional ? " [transactional]" : ""}${method.retry ? ` [retry: ${method.retry.max_attempts}x ${method.retry.backoff}]` : ""}`);
382
- lines.push(`${routerName}.post("${endpoint}", requireAuth, async (req: Request, res: Response) => {`);
383
- lines.push(` const auth: AuthContext = (req as any).auth;`);
384
- // Wrap in retry logic if declared
385
- if (method.retry) {
386
- const { max_attempts, backoff, interval_ms } = method.retry;
387
- lines.push(` let __attempt = 0;`);
388
- lines.push(` const __maxAttempts = ${max_attempts};`);
389
- lines.push(` const __intervalMs = ${interval_ms};`);
390
- lines.push(` const __backoff = "${backoff}";`);
391
- lines.push(` while (__attempt < __maxAttempts) {`);
392
- lines.push(` __attempt++;`);
393
- lines.push(` try {`);
394
- }
395
- if (isTransactional) {
396
- lines.push(` const __client = await pool.connect();`);
397
- lines.push(` try {`);
398
- lines.push(` await __client.query("BEGIN");`);
399
- }
400
- else if (method.sync === "realtime") {
401
- lines.push(` try {`);
402
- lines.push(` // sync: realtime — execute then broadcast to WebSocket channel`);
403
- }
404
- else if (method.sync === "eventual") {
405
- lines.push(` try {`);
406
- lines.push(` // sync: eventual — effects applied, events queued via outbox`);
407
- }
408
- else if (method.sync === "batch") {
409
- lines.push(` try {`);
410
- lines.push(` // sync: batch — enqueued for batch processing`);
411
- lines.push(` const { enqueueBatch } = require("../batch");`);
412
- lines.push(` const result = await enqueueBatch("${mod.name}.${method.name}", req.body);`);
413
- lines.push(` res.json({ ok: true, action: "${method.name}", queued: true, result });`);
414
- lines.push(` return;`);
415
- }
416
- else {
417
- lines.push(` try {`);
418
- }
419
- if (method.pipeline) {
420
- const { emitPipelineBody } = require("./emit_composition");
421
- lines.push(emitPipelineBody(method, " "));
422
- }
423
- else if (method.algorithm) {
424
- const { emitAlgorithmBody } = require("./emit_composition");
425
- lines.push(emitAlgorithmBody(method, " "));
426
- }
427
- else {
428
- // Real capability body: compiled preconditions + effects + emissions
429
- lines.push((0, emit_capability_1.emitCapabilityBody)(method, mod, system, " "));
430
- }
431
- if (isTransactional) {
432
- lines.push(` await __client.query("COMMIT");`);
433
- lines.push(` } catch (e: any) {`);
434
- lines.push(` await __client.query("ROLLBACK");`);
435
- lines.push(` res.status(400).json({ error: { code: "CAPABILITY_FAILED", message: e.message } });`);
436
- lines.push(` } finally {`);
437
- lines.push(` __client.release();`);
438
- lines.push(` }`);
439
- }
440
- else if (method.sync === "realtime") {
441
- lines.push(` // Broadcast to WebSocket subscribers after successful execution`);
442
- lines.push(` if (typeof broadcastToChannel === "function") {`);
443
- lines.push(` broadcastToChannel("${mod.name}", { type: "${method.name}", payload: req.body, actor: auth.actor_id });`);
444
- lines.push(` }`);
445
- lines.push(` } catch (e: any) {`);
446
- lines.push(` res.status(400).json({ error: { code: "CAPABILITY_FAILED", message: e.message } });`);
447
- lines.push(` }`);
448
- }
449
- else {
450
- lines.push(` } catch (e: any) {`);
451
- lines.push(` res.status(400).json({ error: { code: "CAPABILITY_FAILED", message: e.message } });`);
452
- lines.push(` }`);
453
- }
454
- if (method.retry) {
455
- // Close the retry while loop
456
- lines.push(` } catch (e: any) {`);
457
- lines.push(` if (__attempt >= __maxAttempts) {`);
458
- lines.push(` res.status(503).json({ error: { code: "MAX_RETRIES_EXCEEDED", message: e.message, attempts: __attempt } });`);
459
- lines.push(` return;`);
460
- lines.push(` }`);
461
- lines.push(` const delay = __backoff === "exponential" ? __intervalMs * Math.pow(2, __attempt - 1)`);
462
- lines.push(` : __backoff === "linear" ? __intervalMs * __attempt`);
463
- lines.push(` : __intervalMs;`);
464
- lines.push(` await new Promise(r => setTimeout(r, delay));`);
465
- lines.push(` }`);
466
- lines.push(` } // end retry loop`);
467
- }
468
- lines.push(`});`);
469
- lines.push(``);
470
- return lines.join("\n");
471
- }
472
- // ─── State Machine Runtime ────────────────────────────────────────────────────
473
- function emitStateMachineRuntime(sm) {
474
- const lines = [];
475
- const stateUnion = sm.states.map(s => `"${s}"`).join(" | ");
476
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
477
- lines.push(``);
478
- lines.push(`export type ${sm.entity}State = ${stateUnion};`);
479
- lines.push(``);
480
- lines.push(`export const ${sm.entity.toUpperCase()}_INITIAL: ${sm.entity}State = "${sm.initial}";`);
481
- lines.push(``);
482
- lines.push(`const TRANSITIONS: Record<${sm.entity}State, Record<string, ${sm.entity}State>> = {`);
483
- for (const state of sm.states) {
484
- const trans = sm.transitions.filter(t => t.from === state);
485
- const entries = trans.map(t => `"${t.trigger}": "${t.to}"`).join(", ");
486
- lines.push(` "${state}": { ${entries} },`);
487
- }
488
- lines.push(`};`);
489
- lines.push(``);
490
- lines.push(`export function transition${sm.entity}(`);
491
- lines.push(` current: ${sm.entity}State,`);
492
- lines.push(` trigger: string`);
493
- lines.push(`): { ok: true; next: ${sm.entity}State } | { ok: false; error: string } {`);
494
- lines.push(` const next = TRANSITIONS[current]?.[trigger];`);
495
- lines.push(` if (!next) return { ok: false, error: \`Invalid transition: \${current} --[\${trigger}]--> ?\` };`);
496
- lines.push(` return { ok: true, next };`);
497
- lines.push(`}`);
498
- lines.push(``);
499
- return lines.join("\n");
500
- }
501
- exports.emitStateMachineRuntime = emitStateMachineRuntime;
502
- // ─── Main Entry Point ─────────────────────────────────────────────────────────
503
- function emitIndex(system) {
504
- const apiModules = system.modules.filter(m => m.kind === "api_service");
505
- const hasWebSocket = system.modules.some(m => m.kind === "realtime_service");
506
- const lines = [];
507
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
508
- lines.push(`// System: ${system.name}`);
509
- lines.push(`require("dotenv").config();`);
510
- lines.push(`import express from "express";`);
511
- lines.push(`import { createServer } from "http";`);
512
- lines.push(`import cors from "cors";`);
513
- lines.push(`import helmet from "helmet";`);
514
- lines.push(`import rateLimit from "express-rate-limit";`);
515
- lines.push(`import { authMiddleware } from "./auth";`);
516
- lines.push(`import { healthRouter } from "./health";`);
517
- lines.push(`import { logger } from "./logger";`);
518
- lines.push(`import { eventBus } from "./events";`);
519
- lines.push(`import { pool } from "./db";`);
520
- // Import batch worker if any batch capabilities exist
521
- const hasBatch = system.modules.some(m => m.interfaces.some(i => i.methods.some(mth => mth.sync === "batch")));
522
- if (hasBatch) {
523
- lines.push(`import { startBatchWorker } from "./batch";`);
524
- }
525
- if (hasWebSocket) {
526
- lines.push(`import { setupWebSocketServer } from "./websocket";`);
527
- }
528
- lines.push(``);
529
- for (const mod of apiModules) {
530
- const model = mod.models[0];
531
- if (!model)
532
- continue;
533
- const routerName = toCamelCase(toSnakeCase(model.name) + "s") + "Router";
534
- lines.push(`import { ${routerName} } from "./routes/${toSnakeCase(model.name)}";`);
535
- }
536
- lines.push(``);
537
- lines.push(`const app = express();`);
538
- lines.push(`const httpServer = createServer(app);`);
539
- lines.push(`const PORT = parseInt(process.env.PORT || "3000");`);
540
- lines.push(``);
541
- lines.push(`// Middleware`);
542
- lines.push(`app.use(helmet());`);
543
- lines.push(`// CORS: restrict to ALLOWED_ORIGINS env var (comma-separated). Defaults to same-origin only.`);
544
- lines.push(`const __allowedOrigins = (process.env.ALLOWED_ORIGINS || "").split(",").map(s => s.trim()).filter(Boolean);`);
545
- lines.push(`app.use(cors({`);
546
- lines.push(` origin: __allowedOrigins.length > 0`);
547
- lines.push(` ? (origin, cb) => { if (!origin || __allowedOrigins.includes(origin)) cb(null, true); else cb(new Error("Not allowed by CORS")); }`);
548
- lines.push(` : false,`);
549
- lines.push(` credentials: true,`);
550
- lines.push(`}));`);
551
- lines.push(`app.use(express.json({ limit: "1mb" }));`);
552
- lines.push(`app.use(express.urlencoded({ extended: false, limit: "1mb" }));`);
553
- lines.push(`app.use(authMiddleware);`);
554
- const gw = system.modules.find(m => m.kind === "gateway");
555
- const rateVal = gw?.config["rate_limit"] || 1000;
556
- lines.push(`app.use(rateLimit({ windowMs: 60000, max: ${rateVal} }));`);
557
- lines.push(``);
558
- // Request timeout middleware
559
- lines.push(`// Request timeout (default 30s, override per-route)`);
560
- lines.push(`app.use((req: any, res: any, next: any) => {`);
561
- lines.push(` const timeout = parseInt(process.env.REQUEST_TIMEOUT_MS || "30000");`);
562
- lines.push(` const timer = setTimeout(() => {`);
563
- lines.push(` if (!res.headersSent) {`);
564
- lines.push(` res.status(503).json({ error: { code: "REQUEST_TIMEOUT", message: "Request timed out" } });`);
565
- lines.push(` }`);
566
- lines.push(` }, timeout);`);
567
- lines.push(` res.on("finish", () => clearTimeout(timer));`);
568
- lines.push(` next();`);
569
- lines.push(`});`);
570
- lines.push(``);
571
- lines.push(`// Health & metrics`);
572
- lines.push(`app.use("/health", healthRouter);`);
573
- lines.push(``);
574
- lines.push(`// Routes`);
575
- for (const mod of apiModules) {
576
- const model = mod.models[0];
577
- if (!model)
578
- continue;
579
- const routerName = toCamelCase(toSnakeCase(model.name) + "s") + "Router";
580
- lines.push(`app.use("/${toSnakeCase(model.name)}s", ${routerName});`);
581
- }
582
- lines.push(``);
583
- if (hasWebSocket) {
584
- lines.push(`// WebSocket`);
585
- lines.push(`setupWebSocketServer(httpServer);`);
586
- lines.push(``);
587
- }
588
- lines.push(`// Start`);
589
- lines.push(`httpServer.listen(PORT, () => {`);
590
- lines.push(` logger.info("server_started", { event: "startup", metadata: { port: PORT } });`);
591
- lines.push(` // Start durable event worker (no-op in in_process mode)`);
592
- lines.push(` eventBus.startWorker(parseInt(process.env.EVENT_WORKER_INTERVAL_MS || "1000"));`);
593
- if (hasBatch) {
594
- lines.push(` // Start batch executor`);
595
- lines.push(` startBatchWorker();`);
596
- }
597
- lines.push(` console.log(\`[${system.name}] Running on port \${PORT}\`);`);
598
- lines.push(` console.log(\` HTTP routes:\`);`);
599
- for (const mod of apiModules) {
600
- const model = mod.models[0];
601
- if (!model)
602
- continue;
603
- lines.push(` console.log(\` /${toSnakeCase(model.name)}s\`);`);
604
- }
605
- if (hasWebSocket) {
606
- lines.push(` console.log(\` WebSocket: /ws?channel=<name>&token=<jwt>\`);`);
607
- }
608
- lines.push(` console.log(\` Health: /health/live, /health/ready, /health/metrics\`);`);
609
- lines.push(`});`);
610
- lines.push(``);
611
- // Graceful shutdown
612
- lines.push(`// Graceful shutdown`);
613
- lines.push(`const shutdown = async (signal: string) => {`);
614
- lines.push(` logger.info("server_stopping", { event: "shutdown", metadata: { signal } });`);
615
- lines.push(` httpServer.close(async () => {`);
616
- lines.push(` try {`);
617
- lines.push(` await pool.end();`);
618
- lines.push(` logger.info("server_stopped", { event: "shutdown", status: "success" });`);
619
- lines.push(` } catch (e: any) {`);
620
- lines.push(` logger.error("shutdown_error", { event: "shutdown", metadata: { error: e.message } });`);
621
- lines.push(` }`);
622
- lines.push(` process.exit(0);`);
623
- lines.push(` });`);
624
- lines.push(` // Force exit after 10s if connections don't drain`);
625
- lines.push(` setTimeout(() => { logger.error("shutdown_timeout", { event: "shutdown" }); process.exit(1); }, 10000);`);
626
- lines.push(`};`);
627
- lines.push(`process.on("SIGTERM", () => shutdown("SIGTERM"));`);
628
- lines.push(`process.on("SIGINT", () => shutdown("SIGINT"));`);
629
- lines.push(``);
630
- lines.push(`export { app, httpServer };`);
631
- return lines.join("\n");
632
- }
633
- exports.emitIndex = emitIndex;
634
- // ─── Migration Script ─────────────────────────────────────────────────────────
635
- function emitMigration(system, schemas) {
636
- const lines = [];
637
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
638
- lines.push(`require("dotenv").config();`);
639
- lines.push(`import { pool } from "./db";`);
640
- lines.push(``);
641
- lines.push(`async function migrate() {`);
642
- lines.push(` console.log("Running migrations...");`);
643
- lines.push(` const client = await pool.connect();`);
644
- lines.push(` try {`);
645
- for (const schema of schemas) {
646
- const escaped = schema.replace(/`/g, "\\`").replace(/\$/g, "\\$");
647
- lines.push(` await client.query(\`${escaped}\`);`);
648
- }
649
- lines.push(` console.log("Migrations complete.");`);
650
- lines.push(` } finally {`);
651
- lines.push(` client.release();`);
652
- lines.push(` await pool.end();`);
653
- lines.push(` }`);
654
- lines.push(`}`);
655
- lines.push(``);
656
- lines.push(`migrate().catch(e => { console.error(e); process.exit(1); });`);
657
- return lines.join("\n");
658
- }
659
- exports.emitMigration = emitMigration;
660
- // ─── Unknown Function Collector ───────────────────────────────────────────────
661
- // Finds function calls in effect expressions that aren't built-ins or known names.
662
- const KNOWN_FUNCTIONS = new Set([
663
- "now", "count", "sum", "min", "max", "avg", "length", "size",
664
- "shortestPath", "topologicalSort", "binarySearch", "bipartiteMatching",
665
- "roundRobin", "weightedAverage", "percentile", "rankBy", "consistentHash",
666
- ]);
667
- function collectUnknownFunctions(mod) {
668
- const found = new Set();
669
- for (const iface of mod.interfaces) {
670
- for (const method of iface.methods) {
671
- for (const effect of method.effects) {
672
- extractFunctionCalls(effect.value, found);
673
- }
674
- for (const pre of method.preconditions) {
675
- extractFunctionCalls(pre.expression, found);
676
- }
677
- }
678
- }
679
- return found;
680
- }
681
- function extractFunctionCalls(expr, found) {
682
- const pattern = /\b([a-zA-Z_]\w*)\s*\(/g;
683
- let match;
684
- while ((match = pattern.exec(expr)) !== null) {
685
- const name = match[1];
686
- if (!KNOWN_FUNCTIONS.has(name)) {
687
- found.add(name);
688
- }
689
- }
690
- }
17
+ exports.emitIndex = exports.toTsType = exports.toCamelCase = exports.toSnakeCase = exports.emitStateMachineRuntime = exports.emitEntityRouter = exports.emitAuthMiddleware = exports.emitMigration = exports.emitDbClient = exports.emitTsConfig = exports.emitPackageJson = void 0;
18
+ var emit_package_1 = require("./emit_package");
19
+ Object.defineProperty(exports, "emitPackageJson", { enumerable: true, get: function () { return emit_package_1.emitPackageJson; } });
20
+ Object.defineProperty(exports, "emitTsConfig", { enumerable: true, get: function () { return emit_package_1.emitTsConfig; } });
21
+ var emit_database_1 = require("./emit_database");
22
+ Object.defineProperty(exports, "emitDbClient", { enumerable: true, get: function () { return emit_database_1.emitDbClient; } });
23
+ Object.defineProperty(exports, "emitMigration", { enumerable: true, get: function () { return emit_database_1.emitMigration; } });
24
+ var emit_auth_1 = require("./emit_auth");
25
+ Object.defineProperty(exports, "emitAuthMiddleware", { enumerable: true, get: function () { return emit_auth_1.emitAuthMiddleware; } });
26
+ var emit_router_1 = require("./emit_router");
27
+ Object.defineProperty(exports, "emitEntityRouter", { enumerable: true, get: function () { return emit_router_1.emitEntityRouter; } });
28
+ Object.defineProperty(exports, "emitStateMachineRuntime", { enumerable: true, get: function () { return emit_router_1.emitStateMachineRuntime; } });
29
+ Object.defineProperty(exports, "toSnakeCase", { enumerable: true, get: function () { return emit_router_1.toSnakeCase; } });
30
+ Object.defineProperty(exports, "toCamelCase", { enumerable: true, get: function () { return emit_router_1.toCamelCase; } });
31
+ Object.defineProperty(exports, "toTsType", { enumerable: true, get: function () { return emit_router_1.toTsType; } });
32
+ var emit_index_1 = require("./emit_index");
33
+ Object.defineProperty(exports, "emitIndex", { enumerable: true, get: function () { return emit_index_1.emitIndex; } });
691
34
  //# sourceMappingURL=emit_runtime.js.map