bonescript-compiler 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +21 -21
  2. package/dist/algorithm_catalog.js +166 -166
  3. package/dist/cli.d.ts +2 -1
  4. package/dist/cli.js +75 -543
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/check.d.ts +5 -0
  7. package/dist/commands/check.js +34 -0
  8. package/dist/commands/check.js.map +1 -0
  9. package/dist/commands/compile.d.ts +5 -0
  10. package/dist/commands/compile.js +215 -0
  11. package/dist/commands/compile.js.map +1 -0
  12. package/dist/commands/debug.d.ts +5 -0
  13. package/dist/commands/debug.js +59 -0
  14. package/dist/commands/debug.js.map +1 -0
  15. package/dist/commands/diff.d.ts +5 -0
  16. package/dist/commands/diff.js +125 -0
  17. package/dist/commands/diff.js.map +1 -0
  18. package/dist/commands/fmt.d.ts +5 -0
  19. package/dist/commands/fmt.js +49 -0
  20. package/dist/commands/fmt.js.map +1 -0
  21. package/dist/commands/init.d.ts +5 -0
  22. package/dist/commands/init.js +96 -0
  23. package/dist/commands/init.js.map +1 -0
  24. package/dist/commands/ir.d.ts +5 -0
  25. package/dist/commands/ir.js +27 -0
  26. package/dist/commands/ir.js.map +1 -0
  27. package/dist/commands/lex.d.ts +5 -0
  28. package/dist/commands/lex.js +21 -0
  29. package/dist/commands/lex.js.map +1 -0
  30. package/dist/commands/parse.d.ts +5 -0
  31. package/dist/commands/parse.js +30 -0
  32. package/dist/commands/parse.js.map +1 -0
  33. package/dist/commands/test.d.ts +5 -0
  34. package/dist/commands/test.js +61 -0
  35. package/dist/commands/test.js.map +1 -0
  36. package/dist/commands/verify_determinism.d.ts +5 -0
  37. package/dist/commands/verify_determinism.js +64 -0
  38. package/dist/commands/verify_determinism.js.map +1 -0
  39. package/dist/commands/watch.d.ts +5 -0
  40. package/dist/commands/watch.js +50 -0
  41. package/dist/commands/watch.js.map +1 -0
  42. package/dist/emit_auth.d.ts +6 -0
  43. package/dist/emit_auth.js +69 -0
  44. package/dist/emit_auth.js.map +1 -0
  45. package/dist/emit_capability.d.ts +13 -0
  46. package/dist/emit_capability.js +292 -128
  47. package/dist/emit_capability.js.map +1 -1
  48. package/dist/emit_composition.js +37 -3
  49. package/dist/emit_composition.js.map +1 -1
  50. package/dist/emit_database.d.ts +7 -0
  51. package/dist/emit_database.js +74 -0
  52. package/dist/emit_database.js.map +1 -0
  53. package/dist/emit_deploy.js +162 -162
  54. package/dist/emit_events.d.ts +1 -0
  55. package/dist/emit_events.js +342 -275
  56. package/dist/emit_events.js.map +1 -1
  57. package/dist/emit_full.js +135 -95
  58. package/dist/emit_full.js.map +1 -1
  59. package/dist/emit_index.d.ts +6 -0
  60. package/dist/emit_index.js +157 -0
  61. package/dist/emit_index.js.map +1 -0
  62. package/dist/emit_maintenance.js +249 -249
  63. package/dist/emit_models.d.ts +12 -0
  64. package/dist/emit_models.js +171 -0
  65. package/dist/emit_models.js.map +1 -0
  66. package/dist/emit_openapi.d.ts +9 -0
  67. package/dist/emit_openapi.js +308 -0
  68. package/dist/emit_openapi.js.map +1 -0
  69. package/dist/emit_package.d.ts +7 -0
  70. package/dist/emit_package.js +70 -0
  71. package/dist/emit_package.js.map +1 -0
  72. package/dist/emit_router.d.ts +12 -0
  73. package/dist/emit_router.js +390 -0
  74. package/dist/emit_router.js.map +1 -0
  75. package/dist/emit_runtime.d.ts +17 -11
  76. package/dist/emit_runtime.js +29 -686
  77. package/dist/emit_runtime.js.map +1 -1
  78. package/dist/emit_sourcemap.js +66 -66
  79. package/dist/emit_tests.js +37 -0
  80. package/dist/emit_tests.js.map +1 -1
  81. package/dist/emitter.js +34 -5
  82. package/dist/emitter.js.map +1 -1
  83. package/dist/extension_manager.d.ts +2 -2
  84. package/dist/extension_manager.js +6 -3
  85. package/dist/extension_manager.js.map +1 -1
  86. package/dist/lowering.d.ts +5 -14
  87. package/dist/lowering.js +47 -417
  88. package/dist/lowering.js.map +1 -1
  89. package/dist/lowering_channels.d.ts +11 -0
  90. package/dist/lowering_channels.js +102 -0
  91. package/dist/lowering_channels.js.map +1 -0
  92. package/dist/lowering_entities.d.ts +11 -0
  93. package/dist/lowering_entities.js +222 -0
  94. package/dist/lowering_entities.js.map +1 -0
  95. package/dist/lowering_helpers.d.ts +13 -0
  96. package/dist/lowering_helpers.js +76 -0
  97. package/dist/lowering_helpers.js.map +1 -0
  98. package/dist/module_loader.d.ts +2 -2
  99. package/dist/module_loader.js +20 -23
  100. package/dist/module_loader.js.map +1 -1
  101. package/dist/scaffold.d.ts +2 -2
  102. package/dist/scaffold.js +316 -319
  103. package/dist/scaffold.js.map +1 -1
  104. package/dist/typechecker.js +32 -13
  105. package/dist/typechecker.js.map +1 -1
  106. package/dist/verifier.d.ts +5 -0
  107. package/dist/verifier.js +140 -2
  108. package/dist/verifier.js.map +1 -1
  109. package/package.json +62 -52
  110. package/src/algorithm_catalog.ts +345 -345
  111. package/src/ast.ts +334 -334
  112. package/src/cli.ts +98 -624
  113. package/src/commands/check.ts +33 -0
  114. package/src/commands/compile.ts +191 -0
  115. package/src/commands/debug.ts +33 -0
  116. package/src/commands/diff.ts +108 -0
  117. package/src/commands/fmt.ts +22 -0
  118. package/src/commands/init.ts +72 -0
  119. package/src/commands/ir.ts +23 -0
  120. package/src/commands/lex.ts +17 -0
  121. package/src/commands/parse.ts +24 -0
  122. package/src/commands/test.ts +36 -0
  123. package/src/commands/verify_determinism.ts +66 -0
  124. package/src/commands/watch.ts +25 -0
  125. package/src/emit_auth.ts +67 -0
  126. package/src/emit_batch.ts +140 -140
  127. package/src/emit_capability.ts +617 -436
  128. package/src/emit_composition.ts +229 -196
  129. package/src/emit_database.ts +75 -0
  130. package/src/emit_deploy.ts +190 -190
  131. package/src/emit_events.ts +377 -307
  132. package/src/emit_extras.ts +240 -240
  133. package/src/emit_full.ts +351 -309
  134. package/src/emit_index.ts +161 -0
  135. package/src/emit_maintenance.ts +459 -459
  136. package/src/emit_models.ts +176 -0
  137. package/src/emit_openapi.ts +318 -0
  138. package/src/emit_package.ts +69 -0
  139. package/src/emit_router.ts +409 -0
  140. package/src/emit_runtime.ts +17 -728
  141. package/src/emit_sourcemap.ts +140 -140
  142. package/src/emit_tests.ts +246 -205
  143. package/src/emit_websocket.ts +229 -229
  144. package/src/emitter.ts +31 -5
  145. package/src/extension_manager.ts +189 -187
  146. package/src/formatter.ts +297 -297
  147. package/src/index.ts +88 -88
  148. package/src/ir.ts +215 -215
  149. package/src/lexer.ts +630 -630
  150. package/src/lowering.ts +142 -556
  151. package/src/lowering_channels.ts +107 -0
  152. package/src/lowering_entities.ts +248 -0
  153. package/src/lowering_helpers.ts +75 -0
  154. package/src/module_loader.ts +112 -114
  155. package/src/optimizer.ts +196 -196
  156. package/src/parse_decls.ts +409 -409
  157. package/src/parse_decls2.ts +244 -244
  158. package/src/parse_expr.ts +197 -197
  159. package/src/parse_types.ts +54 -54
  160. package/src/parser.ts +1 -1
  161. package/src/parser_base.ts +57 -57
  162. package/src/parser_recovery.ts +153 -153
  163. package/src/scaffold.ts +372 -375
  164. package/src/solver.ts +330 -330
  165. package/src/typechecker.ts +30 -15
  166. package/src/types.ts +122 -122
  167. package/src/verifier.ts +151 -4
package/src/emit_full.ts CHANGED
@@ -1,309 +1,351 @@
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
- }
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, emitTypedEventPublishers } 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
+ import { emitModelFile, emitModelsIndex } from "./emit_models";
36
+ import { emitOpenApiSchema } from "./emit_openapi";
37
+
38
+ function toSnakeCase(s: string): string {
39
+ return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
40
+ }
41
+
42
+ export class FullEmitter {
43
+ private schemaEmitter = new Emitter();
44
+
45
+ emit(system: IR.IRSystem): EmittedFile[] {
46
+ const files: EmittedFile[] = [];
47
+
48
+ // 1. Package files
49
+ files.push({ path: "package.json", content: emitPackageJson(system), language: "json", source_module: "root" });
50
+ files.push({ path: "tsconfig.json", content: emitTsConfig(), language: "json", source_module: "root" });
51
+ files.push({ path: ".env.example", content: this.emitEnvExample(system), language: "yaml", source_module: "root" });
52
+
53
+ // 2. Source: infrastructure
54
+ files.push({ path: "src/db.ts", content: emitDbClient(system), language: "typescript", source_module: "infra" });
55
+ // Durable event bus replaces the old in-process stub
56
+ files.push({ path: "src/events.ts", content: emitDurableEventBus(system), language: "typescript", source_module: "infra" });
57
+ // Outbox SQL schema
58
+ files.push({ path: "migrations/event_outbox.sql", content: emitOutboxSchema(), language: "sql", source_module: "infra" });
59
+ // Typed event publisher functions (one per declared event)
60
+ if (system.events.length > 0) {
61
+ files.push({ path: "src/publishers.ts", content: emitTypedEventPublishers(system), language: "typescript", source_module: "infra" });
62
+ }
63
+ files.push({ path: "src/auth.ts", content: emitAuthMiddleware(system), language: "typescript", source_module: "infra" });
64
+ files.push({ path: "src/logger.ts", content: emitLogger(system), language: "typescript", source_module: "infra" });
65
+ files.push({ path: "src/metrics.ts", content: emitMetrics(), language: "typescript", source_module: "infra" });
66
+ files.push({ path: "src/health.ts", content: emitHealthChecks(system), language: "typescript", source_module: "infra" });
67
+ files.push({ path: "src/failure_rules.ts", content: emitFailureRules(system), language: "typescript", source_module: "infra" });
68
+
69
+ // 2a. WebSocket server (only if there are realtime channels)
70
+ const wsContent = emitWebSocketServer(system);
71
+ if (wsContent) {
72
+ files.push({ path: "src/websocket.ts", content: wsContent, language: "typescript", source_module: "infra" });
73
+ }
74
+
75
+ // 2b. Flow saga runtime (only if there are flows)
76
+ const flowContent = emitFlowRuntime(system);
77
+ if (flowContent) {
78
+ files.push({ path: "src/flows.ts", content: flowContent, language: "typescript", source_module: "infra" });
79
+ }
80
+
81
+ // 2b2. Batch executor (only if there are batch capabilities)
82
+ const batchContent = emitBatchExecutor(system);
83
+ if (batchContent) {
84
+ files.push({ path: "src/batch.ts", content: batchContent, language: "typescript", source_module: "infra" });
85
+ }
86
+
87
+ // 2c. Migration diff utility (always emitted)
88
+ files.push({ path: "src/migration_diff.ts", content: emitMigrationDiff(), language: "typescript", source_module: "infra" });
89
+
90
+ // 2d. Algorithm implementations (only what's used)
91
+ const usedAlgorithms = collectUsedAlgorithms(system);
92
+ if (usedAlgorithms.size > 0) {
93
+ const algoContent = emitAlgorithmsFile(usedAlgorithms);
94
+ files.push({ path: "src/algorithms.ts", content: algoContent, language: "typescript", source_module: "algorithms" });
95
+ } else {
96
+ files.push({
97
+ path: "src/algorithms.ts",
98
+ content: "// No algorithms used in this system.\nexport {};\n",
99
+ language: "typescript",
100
+ source_module: "algorithms",
101
+ });
102
+ }
103
+
104
+ // 2e. Extension points (escape hatches — preserved across recompilation)
105
+ if (system.extension_points && system.extension_points.length > 0) {
106
+ const extLines: string[] = [
107
+ "// Generated by BoneScript compiler.",
108
+ "// Extension points: implement the functions below.",
109
+ "// Code between sentinel comments is preserved on recompile.",
110
+ "// DO NOT remove the sentinel comments.",
111
+ "",
112
+ ];
113
+ for (const ep of system.extension_points) {
114
+ const params = ep.params.map((p: { name: string; type: string }) => `${p.name}: ${p.type}`).join(", ");
115
+ const returnType = ep.returns || "void";
116
+ extLines.push(`/**`);
117
+ extLines.push(` * Extension point: ${ep.name}`);
118
+ extLines.push(` * ${ep.stable ? "STABLE: implementation required." : "Optional."}`);
119
+ extLines.push(` */`);
120
+ extLines.push(`export function ${ep.name}(${params}): ${returnType} {`);
121
+ extLines.push(` // <bonescript:ext:${ep.name}:begin>`);
122
+ extLines.push(` throw new Error("Not implemented: ${ep.name}");`);
123
+ extLines.push(` // <bonescript:ext:${ep.name}:end>`);
124
+ extLines.push(`}`);
125
+ extLines.push("");
126
+ }
127
+ files.push({
128
+ path: "src/extensions.ts",
129
+ content: extLines.join("\n"),
130
+ language: "typescript",
131
+ source_module: "extensions",
132
+ });
133
+ }
134
+
135
+ // 3. Source: state machines
136
+ for (const mod of system.modules) {
137
+ for (const sm of mod.state_machines) {
138
+ files.push({
139
+ path: `src/state_machines/${toSnakeCase(sm.entity)}.ts`,
140
+ content: emitStateMachineRuntime(sm),
141
+ language: "typescript",
142
+ source_module: mod.id,
143
+ });
144
+ }
145
+ }
146
+
147
+ // 4. Source: route files (CRUD + capabilities)
148
+ for (const mod of system.modules) {
149
+ if (mod.kind === "api_service" && mod.models.length > 0) {
150
+ const content = emitEntityRouter(mod, system);
151
+ if (content) {
152
+ files.push({
153
+ path: `src/routes/${toSnakeCase(mod.models[0].name)}.ts`,
154
+ content,
155
+ language: "typescript",
156
+ source_module: mod.id,
157
+ });
158
+ }
159
+ }
160
+ }
161
+
162
+ // 5. Source: main entry point
163
+ files.push({ path: "src/index.ts", content: emitIndex(system), language: "typescript", source_module: "root" });
164
+
165
+ // 5a. Model interfaces, schemas, and validators (one file per model)
166
+ const modelFiles: string[] = [];
167
+ for (const mod of system.modules) {
168
+ for (const model of mod.models) {
169
+ const modelPath = `src/models/${toSnakeCase(model.name)}.ts`;
170
+ files.push({
171
+ path: modelPath,
172
+ content: emitModelFile(model, mod, system),
173
+ language: "typescript",
174
+ source_module: mod.id,
175
+ });
176
+ modelFiles.push(modelPath);
177
+ }
178
+ }
179
+ if (modelFiles.length > 0) {
180
+ files.push({
181
+ path: "src/models/index.ts",
182
+ content: emitModelsIndex(system),
183
+ language: "typescript",
184
+ source_module: "shared",
185
+ });
186
+ }
187
+
188
+ // 6. SQL migrations — run schema emitter ONCE, then match by model name
189
+ const schemas: string[] = [];
190
+ const allSchemaFiles = this.schemaEmitter.emit(system);
191
+ for (const mod of system.modules) {
192
+ if (mod.kind === "data_store" || mod.kind === "api_service") {
193
+ for (const model of mod.models) {
194
+ const schemaFile = allSchemaFiles.find(f => f.path.includes(toSnakeCase(model.name)) && f.language === "sql");
195
+ if (schemaFile) {
196
+ files.push({ ...schemaFile, path: `migrations/${schemaFile.path.replace("schema/", "")}` });
197
+ schemas.push(schemaFile.content);
198
+ }
199
+ }
200
+ }
201
+ }
202
+
203
+ // 7. Migration runner
204
+ files.push({ path: "src/migrate.ts", content: emitMigration(system, schemas), language: "typescript", source_module: "infra" });
205
+
206
+ // 8. Docker compose for local dev
207
+ files.push({ path: "docker-compose.yaml", content: this.emitDockerCompose(system), language: "yaml", source_module: "infra" });
208
+
209
+ // 9. README
210
+ files.push({ path: "README.md", content: this.emitReadme(system), language: "yaml", source_module: "root" });
211
+
212
+ // 9a. OpenAPI schema (spec/09_CODEGEN.md §2 — ApiService secondary target)
213
+ const openApiContent = emitOpenApiSchema(system);
214
+ if (openApiContent) {
215
+ files.push({ path: "openapi.json", content: openApiContent, language: "json", source_module: "root" });
216
+ }
217
+
218
+ // 10. Source map + debug handler
219
+ files.push({ path: `${system.name}.bone.map`, content: emitSourceMapFile(system, `${system.name}.bone`), language: "json", source_module: "root" });
220
+ files.push({ path: "src/debug.ts", content: emitDebugHandler(system), language: "typescript", source_module: "infra" });
221
+ files.push({ path: "src/tests.ts", content: emitTestSuite(system), language: "typescript", source_module: "tests" });
222
+
223
+ // 11. Deploy targets
224
+ files.push({ path: "Dockerfile", content: emitDockerfile(system), language: "yaml", source_module: "deploy" });
225
+ files.push({ path: ".dockerignore", content: emitDockerignore(), language: "yaml", source_module: "deploy" });
226
+ files.push({ path: "k8s/deployment.yaml", content: emitK8sDeployment(system), language: "yaml", source_module: "deploy" });
227
+ files.push({ path: ".github/workflows/ci.yaml", content: emitGithubActions(system), language: "yaml", source_module: "deploy" });
228
+
229
+ return files;
230
+ }
231
+
232
+ private emitEnvExample(system: IR.IRSystem): string {
233
+ return `# ${system.name} Environment Variables
234
+ # Copy this file to .env and fill in real values. Never commit .env to source control.
235
+
236
+ # --- Required in production ---
237
+ # Generate with: node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
238
+ JWT_SECRET=
239
+
240
+ # --- Database ---
241
+ DATABASE_URL=postgresql://postgres:postgres@localhost:5432/${toSnakeCase(system.name)}
242
+
243
+ # --- Redis (optional, used by some domain templates) ---
244
+ REDIS_URL=redis://localhost:6379
245
+
246
+ # --- Server ---
247
+ PORT=3000
248
+ NODE_ENV=development
249
+
250
+ # --- CORS ---
251
+ # Comma-separated list of allowed origins. Leave empty to disallow all cross-origin requests.
252
+ # Example: ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
253
+ ALLOWED_ORIGINS=
254
+
255
+ # --- Rate limiting ---
256
+ # Global limit: requests per window per IP (default 300/min)
257
+ RATE_LIMIT_MAX=300
258
+ RATE_LIMIT_WINDOW_MS=60000
259
+ # Auth endpoints (login/register) limit per IP (default 20/min — brute-force protection)
260
+ AUTH_RATE_LIMIT_MAX=20
261
+
262
+ # --- Event delivery mode ---
263
+ # in_process: in-memory, fast, no durability guarantees (default for development)
264
+ # durable: Postgres-backed transactional outbox (recommended for production)
265
+ EVENT_MODE=in_process
266
+ EVENT_WORKER_INTERVAL_MS=1000
267
+
268
+ # --- Request timeout ---
269
+ REQUEST_TIMEOUT_MS=30000
270
+ `;
271
+ }
272
+
273
+ private emitDockerCompose(system: IR.IRSystem): string {
274
+ return `# Generated by BoneScript compiler.
275
+ version: "3.8"
276
+
277
+ services:
278
+ postgres:
279
+ image: postgres:16-alpine
280
+ environment:
281
+ POSTGRES_DB: ${toSnakeCase(system.name)}
282
+ POSTGRES_USER: postgres
283
+ POSTGRES_PASSWORD: postgres
284
+ ports:
285
+ - "5432:5432"
286
+ volumes:
287
+ - pgdata:/var/lib/postgresql/data
288
+
289
+ redis:
290
+ image: redis:7-alpine
291
+ ports:
292
+ - "6379:6379"
293
+
294
+ volumes:
295
+ pgdata:
296
+ `;
297
+ }
298
+
299
+ private emitReadme(system: IR.IRSystem): string {
300
+ const apiModules = system.modules.filter(m => m.kind === "api_service");
301
+ const routes = apiModules
302
+ .filter(m => m.models.length > 0)
303
+ .map(m => `- \`/${toSnakeCase(m.models[0].name)}s\` — ${m.name}`)
304
+ .join("\n");
305
+
306
+ return `# ${system.name}
307
+
308
+ Generated by BoneScript compiler. Source hash: ${system.source_hash}
309
+
310
+ ## Quick Start
311
+
312
+ \`\`\`bash
313
+ # Start dependencies
314
+ docker compose up -d
315
+
316
+ # Install
317
+ npm install
318
+
319
+ # Run migrations
320
+ npm run migrate
321
+
322
+ # Start server
323
+ npm run dev
324
+ \`\`\`
325
+
326
+ ## API Routes
327
+
328
+ ${routes}
329
+
330
+ Each route supports:
331
+ - \`GET /\` — List (paginated)
332
+ - \`GET /:id\` — Read
333
+ - \`POST /\` — Create
334
+ - \`PUT /:id\` — Update
335
+ - \`DELETE /:id\` — Delete
336
+
337
+ Plus capability-specific endpoints.
338
+
339
+ ## Auth
340
+
341
+ Send a Bearer token in the Authorization header:
342
+ \`\`\`
343
+ Authorization: Bearer <jwt-token>
344
+ \`\`\`
345
+
346
+ ## Environment
347
+
348
+ Copy \`.env.example\` to \`.env\` and configure.
349
+ `;
350
+ }
351
+ }