bonescript-compiler 0.5.3 → 0.5.4

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