bonescript-compiler 0.2.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 -0
- package/dist/algorithm_catalog.d.ts +32 -0
- package/dist/algorithm_catalog.js +323 -0
- package/dist/algorithm_catalog.js.map +1 -0
- package/dist/ast.d.ts +244 -0
- package/dist/ast.js +8 -0
- package/dist/ast.js.map +1 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +605 -0
- package/dist/cli.js.map +1 -0
- package/dist/emit_batch.d.ts +7 -0
- package/dist/emit_batch.js +133 -0
- package/dist/emit_batch.js.map +1 -0
- package/dist/emit_capability.d.ts +7 -0
- package/dist/emit_capability.js +376 -0
- package/dist/emit_capability.js.map +1 -0
- package/dist/emit_composition.d.ts +22 -0
- package/dist/emit_composition.js +184 -0
- package/dist/emit_composition.js.map +1 -0
- package/dist/emit_deploy.d.ts +9 -0
- package/dist/emit_deploy.js +191 -0
- package/dist/emit_deploy.js.map +1 -0
- package/dist/emit_events.d.ts +14 -0
- package/dist/emit_events.js +305 -0
- package/dist/emit_events.js.map +1 -0
- package/dist/emit_extras.d.ts +12 -0
- package/dist/emit_extras.js +234 -0
- package/dist/emit_extras.js.map +1 -0
- package/dist/emit_full.d.ts +13 -0
- package/dist/emit_full.js +273 -0
- package/dist/emit_full.js.map +1 -0
- package/dist/emit_maintenance.d.ts +16 -0
- package/dist/emit_maintenance.js +442 -0
- package/dist/emit_maintenance.js.map +1 -0
- package/dist/emit_runtime.d.ts +13 -0
- package/dist/emit_runtime.js +691 -0
- package/dist/emit_runtime.js.map +1 -0
- package/dist/emit_sourcemap.d.ts +29 -0
- package/dist/emit_sourcemap.js +123 -0
- package/dist/emit_sourcemap.js.map +1 -0
- package/dist/emit_tests.d.ts +15 -0
- package/dist/emit_tests.js +185 -0
- package/dist/emit_tests.js.map +1 -0
- package/dist/emit_websocket.d.ts +6 -0
- package/dist/emit_websocket.js +223 -0
- package/dist/emit_websocket.js.map +1 -0
- package/dist/emitter.d.ts +25 -0
- package/dist/emitter.js +511 -0
- package/dist/emitter.js.map +1 -0
- package/dist/extension_manager.d.ts +38 -0
- package/dist/extension_manager.js +170 -0
- package/dist/extension_manager.js.map +1 -0
- package/dist/formatter.d.ts +34 -0
- package/dist/formatter.js +317 -0
- package/dist/formatter.js.map +1 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +113 -0
- package/dist/index.js.map +1 -0
- package/dist/ir.d.ts +168 -0
- package/dist/ir.js +10 -0
- package/dist/ir.js.map +1 -0
- package/dist/lexer.d.ts +195 -0
- package/dist/lexer.js +619 -0
- package/dist/lexer.js.map +1 -0
- package/dist/lowering.d.ts +25 -0
- package/dist/lowering.js +500 -0
- package/dist/lowering.js.map +1 -0
- package/dist/module_loader.d.ts +25 -0
- package/dist/module_loader.js +126 -0
- package/dist/module_loader.js.map +1 -0
- package/dist/optimizer.d.ts +26 -0
- package/dist/optimizer.js +158 -0
- package/dist/optimizer.js.map +1 -0
- package/dist/parse_decls.d.ts +13 -0
- package/dist/parse_decls.js +442 -0
- package/dist/parse_decls.js.map +1 -0
- package/dist/parse_decls2.d.ts +13 -0
- package/dist/parse_decls2.js +295 -0
- package/dist/parse_decls2.js.map +1 -0
- package/dist/parse_expr.d.ts +7 -0
- package/dist/parse_expr.js +197 -0
- package/dist/parse_expr.js.map +1 -0
- package/dist/parse_types.d.ts +6 -0
- package/dist/parse_types.js +51 -0
- package/dist/parse_types.js.map +1 -0
- package/dist/parser.d.ts +10 -0
- package/dist/parser.js +62 -0
- package/dist/parser.js.map +1 -0
- package/dist/parser_base.d.ts +19 -0
- package/dist/parser_base.js +50 -0
- package/dist/parser_base.js.map +1 -0
- package/dist/parser_recovery.d.ts +26 -0
- package/dist/parser_recovery.js +140 -0
- package/dist/parser_recovery.js.map +1 -0
- package/dist/scaffold.d.ts +13 -0
- package/dist/scaffold.js +376 -0
- package/dist/scaffold.js.map +1 -0
- package/dist/solver.d.ts +26 -0
- package/dist/solver.js +281 -0
- package/dist/solver.js.map +1 -0
- package/dist/typechecker.d.ts +52 -0
- package/dist/typechecker.js +534 -0
- package/dist/typechecker.js.map +1 -0
- package/dist/types.d.ts +38 -0
- package/dist/types.js +85 -0
- package/dist/types.js.map +1 -0
- package/dist/verifier.d.ts +46 -0
- package/dist/verifier.js +307 -0
- package/dist/verifier.js.map +1 -0
- package/package.json +52 -0
- package/src/algorithm_catalog.ts +345 -0
- package/src/ast.ts +334 -0
- package/src/cli.ts +624 -0
- package/src/emit_batch.ts +140 -0
- package/src/emit_capability.ts +436 -0
- package/src/emit_composition.ts +196 -0
- package/src/emit_deploy.ts +190 -0
- package/src/emit_events.ts +307 -0
- package/src/emit_extras.ts +240 -0
- package/src/emit_full.ts +309 -0
- package/src/emit_maintenance.ts +459 -0
- package/src/emit_runtime.ts +731 -0
- package/src/emit_sourcemap.ts +140 -0
- package/src/emit_tests.ts +205 -0
- package/src/emit_websocket.ts +229 -0
- package/src/emitter.ts +566 -0
- package/src/extension_manager.ts +187 -0
- package/src/formatter.ts +297 -0
- package/src/index.ts +88 -0
- package/src/ir.ts +215 -0
- package/src/lexer.ts +630 -0
- package/src/lowering.ts +556 -0
- package/src/module_loader.ts +114 -0
- package/src/optimizer.ts +196 -0
- package/src/parse_decls.ts +409 -0
- package/src/parse_decls2.ts +244 -0
- package/src/parse_expr.ts +197 -0
- package/src/parse_types.ts +54 -0
- package/src/parser.ts +64 -0
- package/src/parser_base.ts +57 -0
- package/src/parser_recovery.ts +153 -0
- package/src/scaffold.ts +375 -0
- package/src/solver.ts +330 -0
- package/src/typechecker.ts +591 -0
- package/src/types.ts +122 -0
- package/src/verifier.ts +348 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BoneScript Extras Emitter
|
|
3
|
+
* Handles features that don't fit cleanly into the main emitters:
|
|
4
|
+
* - Derived fields (computed columns / virtual getters)
|
|
5
|
+
* - Channel filter expressions
|
|
6
|
+
* - Flow compensation runtime
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import * as IR from "./ir";
|
|
10
|
+
import * as AST from "./ast";
|
|
11
|
+
|
|
12
|
+
function toSnakeCase(s: string): string {
|
|
13
|
+
return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// ─── Derived Field Emission ──────────────────────────────────────────────────
|
|
17
|
+
// Derived fields become PostgreSQL generated columns (when expression supports it)
|
|
18
|
+
// or TypeScript getters in the model class.
|
|
19
|
+
|
|
20
|
+
export function emitDerivedFields(entity: AST.EntityDeclNode): string {
|
|
21
|
+
if (entity.derived.length === 0) return "";
|
|
22
|
+
const lines: string[] = [];
|
|
23
|
+
lines.push(`// Derived fields for ${entity.name}`);
|
|
24
|
+
lines.push(`export const ${entity.name.toUpperCase()}_DERIVED = {`);
|
|
25
|
+
for (const d of entity.derived) {
|
|
26
|
+
lines.push(` ${d.name}: (entity: any): unknown => {`);
|
|
27
|
+
lines.push(` // ${serializeExpr(d.expr)}`);
|
|
28
|
+
lines.push(` return ${jsExpr(d.expr)};`);
|
|
29
|
+
lines.push(` },`);
|
|
30
|
+
}
|
|
31
|
+
lines.push(`};`);
|
|
32
|
+
return lines.join("\n");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function serializeExpr(e: AST.ExprNode): string {
|
|
36
|
+
switch (e.kind) {
|
|
37
|
+
case "Literal":
|
|
38
|
+
if (e.type === "string") return `"${e.value}"`;
|
|
39
|
+
return String(e.value);
|
|
40
|
+
case "FieldRef": return e.path.join(".");
|
|
41
|
+
case "BinaryExpr": return `${serializeExpr(e.left)} ${e.op} ${serializeExpr(e.right)}`;
|
|
42
|
+
case "UnaryExpr": return `${e.op}${serializeExpr(e.operand)}`;
|
|
43
|
+
case "CallExpr": return `${e.name}(${e.args.map(serializeExpr).join(", ")})`;
|
|
44
|
+
case "TernaryExpr": return `${serializeExpr(e.condition)} ? ${serializeExpr(e.consequent)} : ${serializeExpr(e.alternate)}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function jsExpr(e: AST.ExprNode): string {
|
|
49
|
+
switch (e.kind) {
|
|
50
|
+
case "Literal":
|
|
51
|
+
if (e.type === "string") return JSON.stringify(e.value);
|
|
52
|
+
if (e.type === "none") return "null";
|
|
53
|
+
return String(e.value);
|
|
54
|
+
case "FieldRef":
|
|
55
|
+
return `entity.${e.path.join(".")}`;
|
|
56
|
+
case "BinaryExpr": {
|
|
57
|
+
const op = e.op === "and" ? "&&" : e.op === "or" ? "||" : e.op === "==" ? "===" : e.op === "!=" ? "!==" : e.op;
|
|
58
|
+
return `(${jsExpr(e.left)} ${op} ${jsExpr(e.right)})`;
|
|
59
|
+
}
|
|
60
|
+
case "UnaryExpr":
|
|
61
|
+
return `(${e.op === "not" ? "!" : e.op}${jsExpr(e.operand)})`;
|
|
62
|
+
case "CallExpr":
|
|
63
|
+
if (e.name === "now") return "Date.now()";
|
|
64
|
+
return `${e.name}(${e.args.map(jsExpr).join(", ")})`;
|
|
65
|
+
case "TernaryExpr":
|
|
66
|
+
return `(${jsExpr(e.condition)} ? ${jsExpr(e.consequent)} : ${jsExpr(e.alternate)})`;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ─── Channel Filter Emission ─────────────────────────────────────────────────
|
|
71
|
+
// Channels with filter expressions get a TypeScript predicate function attached
|
|
72
|
+
// to the WebSocket subscription logic.
|
|
73
|
+
|
|
74
|
+
export function emitChannelFilters(channels: AST.ChannelDeclNode[]): string {
|
|
75
|
+
const filtered = channels.filter(c => c.filter);
|
|
76
|
+
if (filtered.length === 0) return "";
|
|
77
|
+
|
|
78
|
+
const lines: string[] = [];
|
|
79
|
+
lines.push(`// Generated channel filter predicates`);
|
|
80
|
+
lines.push(`// Each filter is a deterministic function: (event, participant) -> bool`);
|
|
81
|
+
lines.push(``);
|
|
82
|
+
lines.push(`export const CHANNEL_FILTERS: Record<string, (event: any, participant: any) => boolean> = {`);
|
|
83
|
+
for (const ch of filtered) {
|
|
84
|
+
lines.push(` "${ch.name}": (event, participant) => {`);
|
|
85
|
+
lines.push(` // Filter expression: ${ch.filter ? serializeExpr(ch.filter) : "true"}`);
|
|
86
|
+
lines.push(` return ${ch.filter ? channelFilterExpr(ch.filter) : "true"};`);
|
|
87
|
+
lines.push(` },`);
|
|
88
|
+
}
|
|
89
|
+
lines.push(`};`);
|
|
90
|
+
lines.push(``);
|
|
91
|
+
lines.push(`export function shouldDeliver(channel: string, event: any, participant: any): boolean {`);
|
|
92
|
+
lines.push(` const filter = CHANNEL_FILTERS[channel];`);
|
|
93
|
+
lines.push(` return filter ? filter(event, participant) : true;`);
|
|
94
|
+
lines.push(`}`);
|
|
95
|
+
|
|
96
|
+
return lines.join("\n");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function channelFilterExpr(e: AST.ExprNode): string {
|
|
100
|
+
// Channel filters reference 'event' and 'participant' as implicit names
|
|
101
|
+
switch (e.kind) {
|
|
102
|
+
case "Literal":
|
|
103
|
+
if (e.type === "string") return JSON.stringify(e.value);
|
|
104
|
+
if (e.type === "none") return "null";
|
|
105
|
+
return String(e.value);
|
|
106
|
+
case "FieldRef": {
|
|
107
|
+
// Resolve event.* and participant.* explicitly
|
|
108
|
+
if (e.path[0] === "event" || e.path[0] === "participant") {
|
|
109
|
+
return e.path.join(".");
|
|
110
|
+
}
|
|
111
|
+
return `event.${e.path.join(".")}`;
|
|
112
|
+
}
|
|
113
|
+
case "BinaryExpr": {
|
|
114
|
+
const op = e.op === "and" ? "&&" : e.op === "or" ? "||" : e.op === "==" ? "===" : e.op === "!=" ? "!==" : e.op;
|
|
115
|
+
return `(${channelFilterExpr(e.left)} ${op} ${channelFilterExpr(e.right)})`;
|
|
116
|
+
}
|
|
117
|
+
case "UnaryExpr":
|
|
118
|
+
return `(${e.op === "not" ? "!" : e.op}${channelFilterExpr(e.operand)})`;
|
|
119
|
+
case "CallExpr":
|
|
120
|
+
return `${e.name}(${e.args.map(channelFilterExpr).join(", ")})`;
|
|
121
|
+
case "TernaryExpr":
|
|
122
|
+
return `(${channelFilterExpr(e.condition)} ? ${channelFilterExpr(e.consequent)} : ${channelFilterExpr(e.alternate)})`;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ─── Flow Saga Runtime ───────────────────────────────────────────────────────
|
|
127
|
+
|
|
128
|
+
export function emitFlowRuntime(system: IR.IRSystem): string {
|
|
129
|
+
if (system.flows.length === 0) return "";
|
|
130
|
+
|
|
131
|
+
const lines: string[] = [];
|
|
132
|
+
lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
|
|
133
|
+
lines.push(`// Saga runtime — implements flow declarations with backward compensation.`);
|
|
134
|
+
lines.push(`//`);
|
|
135
|
+
lines.push(`// On step failure, executes compensations for ALL completed steps in reverse order.`);
|
|
136
|
+
lines.push(``);
|
|
137
|
+
lines.push(`import { logger } from "./logger";`);
|
|
138
|
+
lines.push(`import { counter } from "./metrics";`);
|
|
139
|
+
lines.push(``);
|
|
140
|
+
|
|
141
|
+
lines.push(`export interface FlowStep {`);
|
|
142
|
+
lines.push(` name: string;`);
|
|
143
|
+
lines.push(` action: (ctx: any) => Promise<void>;`);
|
|
144
|
+
lines.push(` compensation: ((ctx: any) => Promise<void>) | null;`);
|
|
145
|
+
lines.push(`}`);
|
|
146
|
+
lines.push(``);
|
|
147
|
+
|
|
148
|
+
lines.push(`export interface FlowResult {`);
|
|
149
|
+
lines.push(` ok: boolean;`);
|
|
150
|
+
lines.push(` failed_step?: string;`);
|
|
151
|
+
lines.push(` compensated: string[];`);
|
|
152
|
+
lines.push(` error?: string;`);
|
|
153
|
+
lines.push(`}`);
|
|
154
|
+
lines.push(``);
|
|
155
|
+
|
|
156
|
+
lines.push(`export async function executeFlow(name: string, steps: FlowStep[], ctx: any): Promise<FlowResult> {`);
|
|
157
|
+
lines.push(` const completed: { step: string; compensation: ((c: any) => Promise<void>) | null }[] = [];`);
|
|
158
|
+
lines.push(``);
|
|
159
|
+
lines.push(` for (const step of steps) {`);
|
|
160
|
+
lines.push(` try {`);
|
|
161
|
+
lines.push(` logger.info("flow_step_started", { event: name + "." + step.name });`);
|
|
162
|
+
lines.push(` await step.action(ctx);`);
|
|
163
|
+
lines.push(` completed.push({ step: step.name, compensation: step.compensation });`);
|
|
164
|
+
lines.push(` counter("flow.step_completed", { flow: name, step: step.name });`);
|
|
165
|
+
lines.push(` } catch (e: any) {`);
|
|
166
|
+
lines.push(` logger.error("flow_step_failed", { event: name + "." + step.name, metadata: { error: e.message } });`);
|
|
167
|
+
lines.push(` counter("flow.step_failed", { flow: name, step: step.name });`);
|
|
168
|
+
lines.push(``);
|
|
169
|
+
lines.push(` // Backward compensation in reverse order`);
|
|
170
|
+
lines.push(` const compensated: string[] = [];`);
|
|
171
|
+
lines.push(` for (const c of [...completed].reverse()) {`);
|
|
172
|
+
lines.push(` if (!c.compensation) continue;`);
|
|
173
|
+
lines.push(` try {`);
|
|
174
|
+
lines.push(` await c.compensation(ctx);`);
|
|
175
|
+
lines.push(` compensated.push(c.step);`);
|
|
176
|
+
lines.push(` logger.info("flow_compensated", { event: name + "." + c.step });`);
|
|
177
|
+
lines.push(` } catch (compErr: any) {`);
|
|
178
|
+
lines.push(` logger.error("flow_compensation_failed", { event: name + "." + c.step, metadata: { error: compErr.message } });`);
|
|
179
|
+
lines.push(` // Continue with other compensations even if one fails`);
|
|
180
|
+
lines.push(` }`);
|
|
181
|
+
lines.push(` }`);
|
|
182
|
+
lines.push(``);
|
|
183
|
+
lines.push(` return { ok: false, failed_step: step.name, compensated, error: e.message };`);
|
|
184
|
+
lines.push(` }`);
|
|
185
|
+
lines.push(` }`);
|
|
186
|
+
lines.push(``);
|
|
187
|
+
lines.push(` counter("flow.completed", { flow: name });`);
|
|
188
|
+
lines.push(` return { ok: true, compensated: [] };`);
|
|
189
|
+
lines.push(`}`);
|
|
190
|
+
lines.push(``);
|
|
191
|
+
|
|
192
|
+
// Emit each flow's step definitions
|
|
193
|
+
for (const flow of system.flows) {
|
|
194
|
+
lines.push(`// Flow: ${flow.name}`);
|
|
195
|
+
lines.push(`// ctx must contain: { req, res, auth, client? } for transactional flows`);
|
|
196
|
+
lines.push(`export async function execute_${flow.name}(ctx: { req: any; res: any; auth: any; client?: any }): Promise<FlowResult> {`);
|
|
197
|
+
lines.push(` const steps: FlowStep[] = [`);
|
|
198
|
+
for (const step of flow.steps) {
|
|
199
|
+
// Parse the action string: "capabilityName(arg1, arg2)"
|
|
200
|
+
const actionMatch = step.action.match(/^(\w+)\((.*)\)$/);
|
|
201
|
+
const actionFn = actionMatch ? actionMatch[1] : step.action;
|
|
202
|
+
const actionArgs = actionMatch ? actionMatch[2] : "";
|
|
203
|
+
|
|
204
|
+
lines.push(` {`);
|
|
205
|
+
lines.push(` name: "${step.name}",`);
|
|
206
|
+
lines.push(` action: async (ctx) => {`);
|
|
207
|
+
lines.push(` // Calls capability: ${step.action}`);
|
|
208
|
+
lines.push(` const response = await fetch(\`\${process.env.SERVICE_BASE_URL || "http://localhost:3000"}/${toSnakeCase(actionFn).replace(/_/g, "-")}\`, {`);
|
|
209
|
+
lines.push(` method: "POST",`);
|
|
210
|
+
lines.push(` headers: { "Content-Type": "application/json", "Authorization": ctx.req.headers.authorization || "" },`);
|
|
211
|
+
lines.push(` body: JSON.stringify(ctx.req.body),`);
|
|
212
|
+
lines.push(` });`);
|
|
213
|
+
lines.push(` if (!response.ok) throw new Error(\`Step ${step.name} failed: \${await response.text()}\`);`);
|
|
214
|
+
lines.push(` ctx.${step.name}_result = await response.json();`);
|
|
215
|
+
lines.push(` },`);
|
|
216
|
+
|
|
217
|
+
if (step.compensation) {
|
|
218
|
+
const compMatch = step.compensation.match(/^(\w+)\((.*)\)$/);
|
|
219
|
+
const compFn = compMatch ? compMatch[1] : step.compensation;
|
|
220
|
+
lines.push(` compensation: async (ctx) => {`);
|
|
221
|
+
lines.push(` // Compensates: ${step.compensation}`);
|
|
222
|
+
lines.push(` await fetch(\`\${process.env.SERVICE_BASE_URL || "http://localhost:3000"}/${toSnakeCase(compFn).replace(/_/g, "-")}\`, {`);
|
|
223
|
+
lines.push(` method: "POST",`);
|
|
224
|
+
lines.push(` headers: { "Content-Type": "application/json", "Authorization": ctx.req.headers.authorization || "" },`);
|
|
225
|
+
lines.push(` body: JSON.stringify({ ...ctx.req.body, _compensating: true }),`);
|
|
226
|
+
lines.push(` });`);
|
|
227
|
+
lines.push(` },`);
|
|
228
|
+
} else {
|
|
229
|
+
lines.push(` compensation: null,`);
|
|
230
|
+
}
|
|
231
|
+
lines.push(` },`);
|
|
232
|
+
}
|
|
233
|
+
lines.push(` ];`);
|
|
234
|
+
lines.push(` return executeFlow("${flow.name}", steps, ctx);`);
|
|
235
|
+
lines.push(`}`);
|
|
236
|
+
lines.push(``);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return lines.join("\n");
|
|
240
|
+
}
|
package/src/emit_full.ts
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BoneScript Full Emitter  Produces a complete, runnable project.
|
|
3
|
+
* Combines schema generation with runtime service code.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as IR from "./ir";
|
|
7
|
+
import { Emitter, EmittedFile } from "./emitter";
|
|
8
|
+
import {
|
|
9
|
+
emitPackageJson,
|
|
10
|
+
emitTsConfig,
|
|
11
|
+
emitDbClient,
|
|
12
|
+
emitAuthMiddleware,
|
|
13
|
+
emitEntityRouter,
|
|
14
|
+
emitStateMachineRuntime,
|
|
15
|
+
emitIndex,
|
|
16
|
+
emitMigration,
|
|
17
|
+
} from "./emit_runtime";
|
|
18
|
+
import { emitWebSocketServer } from "./emit_websocket";
|
|
19
|
+
import {
|
|
20
|
+
emitLogger,
|
|
21
|
+
emitMetrics,
|
|
22
|
+
emitHealthChecks,
|
|
23
|
+
emitFailureRules,
|
|
24
|
+
emitMigrationDiff,
|
|
25
|
+
} from "./emit_maintenance";
|
|
26
|
+
import { emitFlowRuntime } from "./emit_extras";
|
|
27
|
+
import { emitAlgorithmsFile, collectUsedAlgorithms } from "./emit_composition";
|
|
28
|
+
import { emitExtensionPointStub } from "./extension_manager";
|
|
29
|
+
import * as AST from "./ast";
|
|
30
|
+
import { emitDurableEventBus, emitOutboxSchema } from "./emit_events";
|
|
31
|
+
import { emitBatchExecutor } from "./emit_batch";
|
|
32
|
+
import { emitSourceMapFile, emitDebugHandler } from "./emit_sourcemap";
|
|
33
|
+
import { emitTestSuite } from "./emit_tests";
|
|
34
|
+
import { emitDockerfile, emitDockerignore, emitK8sDeployment, emitGithubActions } from "./emit_deploy";
|
|
35
|
+
|
|
36
|
+
function toSnakeCase(s: string): string {
|
|
37
|
+
return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export class FullEmitter {
|
|
41
|
+
private schemaEmitter = new Emitter();
|
|
42
|
+
|
|
43
|
+
emit(system: IR.IRSystem): EmittedFile[] {
|
|
44
|
+
const files: EmittedFile[] = [];
|
|
45
|
+
|
|
46
|
+
// 1. Package files
|
|
47
|
+
files.push({ path: "package.json", content: emitPackageJson(system), language: "json", source_module: "root" });
|
|
48
|
+
files.push({ path: "tsconfig.json", content: emitTsConfig(), language: "json", source_module: "root" });
|
|
49
|
+
files.push({ path: ".env.example", content: this.emitEnvExample(system), language: "yaml", source_module: "root" });
|
|
50
|
+
|
|
51
|
+
// 2. Source: infrastructure
|
|
52
|
+
files.push({ path: "src/db.ts", content: emitDbClient(system), language: "typescript", source_module: "infra" });
|
|
53
|
+
// Durable event bus replaces the old in-process stub
|
|
54
|
+
files.push({ path: "src/events.ts", content: emitDurableEventBus(system), language: "typescript", source_module: "infra" });
|
|
55
|
+
// Outbox SQL schema
|
|
56
|
+
files.push({ path: "migrations/event_outbox.sql", content: emitOutboxSchema(), language: "sql", source_module: "infra" });
|
|
57
|
+
files.push({ path: "src/auth.ts", content: emitAuthMiddleware(system), language: "typescript", source_module: "infra" });
|
|
58
|
+
files.push({ path: "src/logger.ts", content: emitLogger(system), language: "typescript", source_module: "infra" });
|
|
59
|
+
files.push({ path: "src/metrics.ts", content: emitMetrics(), language: "typescript", source_module: "infra" });
|
|
60
|
+
files.push({ path: "src/health.ts", content: emitHealthChecks(system), language: "typescript", source_module: "infra" });
|
|
61
|
+
files.push({ path: "src/failure_rules.ts", content: emitFailureRules(system), language: "typescript", source_module: "infra" });
|
|
62
|
+
|
|
63
|
+
// 2a. WebSocket server (only if there are realtime channels)
|
|
64
|
+
const wsContent = emitWebSocketServer(system);
|
|
65
|
+
if (wsContent) {
|
|
66
|
+
files.push({ path: "src/websocket.ts", content: wsContent, language: "typescript", source_module: "infra" });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 2b. Flow saga runtime (only if there are flows)
|
|
70
|
+
const flowContent = emitFlowRuntime(system);
|
|
71
|
+
if (flowContent) {
|
|
72
|
+
files.push({ path: "src/flows.ts", content: flowContent, language: "typescript", source_module: "infra" });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 2b2. Batch executor (only if there are batch capabilities)
|
|
76
|
+
const batchContent = emitBatchExecutor(system);
|
|
77
|
+
if (batchContent) {
|
|
78
|
+
files.push({ path: "src/batch.ts", content: batchContent, language: "typescript", source_module: "infra" });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// 2c. Migration diff utility (always emitted)
|
|
82
|
+
files.push({ path: "src/migration_diff.ts", content: emitMigrationDiff(), language: "typescript", source_module: "infra" });
|
|
83
|
+
|
|
84
|
+
// 2d. Algorithm implementations (only what's used)
|
|
85
|
+
const usedAlgorithms = collectUsedAlgorithms(system);
|
|
86
|
+
if (usedAlgorithms.size > 0) {
|
|
87
|
+
const algoContent = emitAlgorithmsFile(usedAlgorithms);
|
|
88
|
+
files.push({ path: "src/algorithms.ts", content: algoContent, language: "typescript", source_module: "algorithms" });
|
|
89
|
+
} else {
|
|
90
|
+
files.push({
|
|
91
|
+
path: "src/algorithms.ts",
|
|
92
|
+
content: "// No algorithms used in this system.\nexport {};\n",
|
|
93
|
+
language: "typescript",
|
|
94
|
+
source_module: "algorithms",
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 2e. Extension points (escape hatches — preserved across recompilation)
|
|
99
|
+
if (system.extension_points && system.extension_points.length > 0) {
|
|
100
|
+
const extLines: string[] = [
|
|
101
|
+
"// Generated by BoneScript compiler.",
|
|
102
|
+
"// Extension points: implement the functions below.",
|
|
103
|
+
"// Code between sentinel comments is preserved on recompile.",
|
|
104
|
+
"// DO NOT remove the sentinel comments.",
|
|
105
|
+
"",
|
|
106
|
+
];
|
|
107
|
+
for (const ep of system.extension_points) {
|
|
108
|
+
const params = ep.params.map((p: { name: string; type: string }) => `${p.name}: ${p.type}`).join(", ");
|
|
109
|
+
const returnType = ep.returns || "void";
|
|
110
|
+
extLines.push(`/**`);
|
|
111
|
+
extLines.push(` * Extension point: ${ep.name}`);
|
|
112
|
+
extLines.push(` * ${ep.stable ? "STABLE: implementation required." : "Optional."}`);
|
|
113
|
+
extLines.push(` */`);
|
|
114
|
+
extLines.push(`export function ${ep.name}(${params}): ${returnType} {`);
|
|
115
|
+
extLines.push(` // <bonescript:ext:${ep.name}:begin>`);
|
|
116
|
+
extLines.push(` throw new Error("Not implemented: ${ep.name}");`);
|
|
117
|
+
extLines.push(` // <bonescript:ext:${ep.name}:end>`);
|
|
118
|
+
extLines.push(`}`);
|
|
119
|
+
extLines.push("");
|
|
120
|
+
}
|
|
121
|
+
files.push({
|
|
122
|
+
path: "src/extensions.ts",
|
|
123
|
+
content: extLines.join("\n"),
|
|
124
|
+
language: "typescript",
|
|
125
|
+
source_module: "extensions",
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 3. Source: state machines
|
|
130
|
+
for (const mod of system.modules) {
|
|
131
|
+
for (const sm of mod.state_machines) {
|
|
132
|
+
files.push({
|
|
133
|
+
path: `src/state_machines/${toSnakeCase(sm.entity)}.ts`,
|
|
134
|
+
content: emitStateMachineRuntime(sm),
|
|
135
|
+
language: "typescript",
|
|
136
|
+
source_module: mod.id,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 4. Source: route files (CRUD + capabilities)
|
|
142
|
+
for (const mod of system.modules) {
|
|
143
|
+
if (mod.kind === "api_service" && mod.models.length > 0) {
|
|
144
|
+
const content = emitEntityRouter(mod, system);
|
|
145
|
+
if (content) {
|
|
146
|
+
files.push({
|
|
147
|
+
path: `src/routes/${toSnakeCase(mod.models[0].name)}.ts`,
|
|
148
|
+
content,
|
|
149
|
+
language: "typescript",
|
|
150
|
+
source_module: mod.id,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// 5. Source: main entry point
|
|
157
|
+
files.push({ path: "src/index.ts", content: emitIndex(system), language: "typescript", source_module: "root" });
|
|
158
|
+
|
|
159
|
+
// 6. SQL migrations — run schema emitter ONCE, then match by model name
|
|
160
|
+
const schemas: string[] = [];
|
|
161
|
+
const allSchemaFiles = this.schemaEmitter.emit(system);
|
|
162
|
+
for (const mod of system.modules) {
|
|
163
|
+
if (mod.kind === "data_store" || mod.kind === "api_service") {
|
|
164
|
+
for (const model of mod.models) {
|
|
165
|
+
const schemaFile = allSchemaFiles.find(f => f.path.includes(toSnakeCase(model.name)) && f.language === "sql");
|
|
166
|
+
if (schemaFile) {
|
|
167
|
+
files.push({ ...schemaFile, path: `migrations/${schemaFile.path.replace("schema/", "")}` });
|
|
168
|
+
schemas.push(schemaFile.content);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// 7. Migration runner
|
|
175
|
+
files.push({ path: "src/migrate.ts", content: emitMigration(system, schemas), language: "typescript", source_module: "infra" });
|
|
176
|
+
|
|
177
|
+
// 8. Docker compose for local dev
|
|
178
|
+
files.push({ path: "docker-compose.yaml", content: this.emitDockerCompose(system), language: "yaml", source_module: "infra" });
|
|
179
|
+
|
|
180
|
+
// 9. README
|
|
181
|
+
files.push({ path: "README.md", content: this.emitReadme(system), language: "yaml", source_module: "root" });
|
|
182
|
+
|
|
183
|
+
// 10. Source map + debug handler
|
|
184
|
+
files.push({ path: `${system.name}.bone.map`, content: emitSourceMapFile(system, `${system.name}.bone`), language: "json", source_module: "root" });
|
|
185
|
+
files.push({ path: "src/debug.ts", content: emitDebugHandler(system), language: "typescript", source_module: "infra" });
|
|
186
|
+
files.push({ path: "src/tests.ts", content: emitTestSuite(system), language: "typescript", source_module: "tests" });
|
|
187
|
+
|
|
188
|
+
// 11. Deploy targets
|
|
189
|
+
files.push({ path: "Dockerfile", content: emitDockerfile(system), language: "yaml", source_module: "deploy" });
|
|
190
|
+
files.push({ path: ".dockerignore", content: emitDockerignore(), language: "yaml", source_module: "deploy" });
|
|
191
|
+
files.push({ path: "k8s/deployment.yaml", content: emitK8sDeployment(system), language: "yaml", source_module: "deploy" });
|
|
192
|
+
files.push({ path: ".github/workflows/ci.yaml", content: emitGithubActions(system), language: "yaml", source_module: "deploy" });
|
|
193
|
+
|
|
194
|
+
return files;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private emitEnvExample(system: IR.IRSystem): string {
|
|
198
|
+
return `# ${system.name} Environment Variables
|
|
199
|
+
# Copy this file to .env and fill in real values. Never commit .env to source control.
|
|
200
|
+
|
|
201
|
+
# --- Required in production ---
|
|
202
|
+
# Generate with: node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
|
|
203
|
+
JWT_SECRET=
|
|
204
|
+
|
|
205
|
+
# --- Database ---
|
|
206
|
+
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/${toSnakeCase(system.name)}
|
|
207
|
+
|
|
208
|
+
# --- Redis (optional, used by some domain templates) ---
|
|
209
|
+
REDIS_URL=redis://localhost:6379
|
|
210
|
+
|
|
211
|
+
# --- Server ---
|
|
212
|
+
PORT=3000
|
|
213
|
+
NODE_ENV=development
|
|
214
|
+
|
|
215
|
+
# --- CORS ---
|
|
216
|
+
# Comma-separated list of allowed origins. Leave empty to disallow all cross-origin requests.
|
|
217
|
+
# Example: ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
|
|
218
|
+
ALLOWED_ORIGINS=
|
|
219
|
+
|
|
220
|
+
# --- Event delivery mode ---
|
|
221
|
+
# in_process: in-memory, fast, no durability guarantees (default for development)
|
|
222
|
+
# durable: Postgres-backed transactional outbox (recommended for production)
|
|
223
|
+
EVENT_MODE=in_process
|
|
224
|
+
EVENT_WORKER_INTERVAL_MS=1000
|
|
225
|
+
|
|
226
|
+
# --- Request timeout ---
|
|
227
|
+
REQUEST_TIMEOUT_MS=30000
|
|
228
|
+
`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private emitDockerCompose(system: IR.IRSystem): string {
|
|
232
|
+
return `# Generated by BoneScript compiler.
|
|
233
|
+
version: "3.8"
|
|
234
|
+
|
|
235
|
+
services:
|
|
236
|
+
postgres:
|
|
237
|
+
image: postgres:16-alpine
|
|
238
|
+
environment:
|
|
239
|
+
POSTGRES_DB: ${toSnakeCase(system.name)}
|
|
240
|
+
POSTGRES_USER: postgres
|
|
241
|
+
POSTGRES_PASSWORD: postgres
|
|
242
|
+
ports:
|
|
243
|
+
- "5432:5432"
|
|
244
|
+
volumes:
|
|
245
|
+
- pgdata:/var/lib/postgresql/data
|
|
246
|
+
|
|
247
|
+
redis:
|
|
248
|
+
image: redis:7-alpine
|
|
249
|
+
ports:
|
|
250
|
+
- "6379:6379"
|
|
251
|
+
|
|
252
|
+
volumes:
|
|
253
|
+
pgdata:
|
|
254
|
+
`;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private emitReadme(system: IR.IRSystem): string {
|
|
258
|
+
const apiModules = system.modules.filter(m => m.kind === "api_service");
|
|
259
|
+
const routes = apiModules
|
|
260
|
+
.filter(m => m.models.length > 0)
|
|
261
|
+
.map(m => `- \`/${toSnakeCase(m.models[0].name)}s\`  ${m.name}`)
|
|
262
|
+
.join("\n");
|
|
263
|
+
|
|
264
|
+
return `# ${system.name}
|
|
265
|
+
|
|
266
|
+
Generated by BoneScript compiler. Source hash: ${system.source_hash}
|
|
267
|
+
|
|
268
|
+
## Quick Start
|
|
269
|
+
|
|
270
|
+
\`\`\`bash
|
|
271
|
+
# Start dependencies
|
|
272
|
+
docker compose up -d
|
|
273
|
+
|
|
274
|
+
# Install
|
|
275
|
+
npm install
|
|
276
|
+
|
|
277
|
+
# Run migrations
|
|
278
|
+
npm run migrate
|
|
279
|
+
|
|
280
|
+
# Start server
|
|
281
|
+
npm run dev
|
|
282
|
+
\`\`\`
|
|
283
|
+
|
|
284
|
+
## API Routes
|
|
285
|
+
|
|
286
|
+
${routes}
|
|
287
|
+
|
|
288
|
+
Each route supports:
|
|
289
|
+
- \`GET /\`  List (paginated)
|
|
290
|
+
- \`GET /:id\`  Read
|
|
291
|
+
- \`POST /\`  Create
|
|
292
|
+
- \`PUT /:id\`  Update
|
|
293
|
+
- \`DELETE /:id\`  Delete
|
|
294
|
+
|
|
295
|
+
Plus capability-specific endpoints.
|
|
296
|
+
|
|
297
|
+
## Auth
|
|
298
|
+
|
|
299
|
+
Send a Bearer token in the Authorization header:
|
|
300
|
+
\`\`\`
|
|
301
|
+
Authorization: Bearer <jwt-token>
|
|
302
|
+
\`\`\`
|
|
303
|
+
|
|
304
|
+
## Environment
|
|
305
|
+
|
|
306
|
+
Copy \`.env.example\` to \`.env\` and configure.
|
|
307
|
+
`;
|
|
308
|
+
}
|
|
309
|
+
}
|