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