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
@@ -11,40 +11,40 @@
11
11
  * exactly_once — deduplicated via event_id table
12
12
  */
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.emitDurableEventBus = exports.emitOutboxSchema = void 0;
14
+ exports.emitTypedEventPublishers = exports.emitDurableEventBus = exports.emitOutboxSchema = void 0;
15
15
  // ─── Outbox SQL Schema ────────────────────────────────────────────────────────
16
16
  function emitOutboxSchema() {
17
- return `-- BoneScript: Transactional Outbox Schema
18
- -- Generated by BoneScript compiler. DO NOT EDIT.
19
-
20
- CREATE TABLE IF NOT EXISTS event_outbox (
21
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
22
- event_type VARCHAR NOT NULL,
23
- payload JSONB NOT NULL,
24
- source VARCHAR NOT NULL,
25
- correlation_id UUID,
26
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
27
- scheduled_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
28
- delivered_at TIMESTAMPTZ,
29
- attempts INT NOT NULL DEFAULT 0,
30
- last_error TEXT,
31
- status VARCHAR NOT NULL DEFAULT 'pending'
32
- CHECK (status IN ('pending', 'delivered', 'failed', 'dead_letter'))
33
- );
34
-
35
- CREATE INDEX IF NOT EXISTS idx_event_outbox_status ON event_outbox (status, scheduled_at)
36
- WHERE status = 'pending';
37
-
38
- CREATE INDEX IF NOT EXISTS idx_event_outbox_created ON event_outbox (created_at);
39
-
40
- -- Deduplication table for exactly_once delivery
41
- CREATE TABLE IF NOT EXISTS event_processed (
42
- event_id UUID PRIMARY KEY,
43
- event_type VARCHAR NOT NULL,
44
- processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
45
- );
46
-
47
- CREATE INDEX IF NOT EXISTS idx_event_processed_type ON event_processed (event_type, processed_at);
17
+ return `-- BoneScript: Transactional Outbox Schema
18
+ -- Generated by BoneScript compiler. DO NOT EDIT.
19
+
20
+ CREATE TABLE IF NOT EXISTS event_outbox (
21
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
22
+ event_type VARCHAR NOT NULL,
23
+ payload JSONB NOT NULL,
24
+ source VARCHAR NOT NULL,
25
+ correlation_id UUID,
26
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
27
+ scheduled_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
28
+ delivered_at TIMESTAMPTZ,
29
+ attempts INT NOT NULL DEFAULT 0,
30
+ last_error TEXT,
31
+ status VARCHAR NOT NULL DEFAULT 'pending'
32
+ CHECK (status IN ('pending', 'delivered', 'failed', 'dead_letter'))
33
+ );
34
+
35
+ CREATE INDEX IF NOT EXISTS idx_event_outbox_status ON event_outbox (status, scheduled_at)
36
+ WHERE status = 'pending';
37
+
38
+ CREATE INDEX IF NOT EXISTS idx_event_outbox_created ON event_outbox (created_at);
39
+
40
+ -- Deduplication table for exactly_once delivery
41
+ CREATE TABLE IF NOT EXISTS event_processed (
42
+ event_id UUID PRIMARY KEY,
43
+ event_type VARCHAR NOT NULL,
44
+ processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
45
+ );
46
+
47
+ CREATE INDEX IF NOT EXISTS idx_event_processed_type ON event_processed (event_type, processed_at);
48
48
  `;
49
49
  }
50
50
  exports.emitOutboxSchema = emitOutboxSchema;
@@ -56,250 +56,317 @@ function emitDurableEventBus(system) {
56
56
  const atLeastOnceEvents = system.events
57
57
  .filter(e => e.delivery === "at_least_once")
58
58
  .map(e => `"${e.name}"`);
59
- return `// Generated by BoneScript compiler. DO NOT EDIT.
60
- // Durable event bus with transactional outbox pattern.
61
- // Set EVENT_MODE=durable in .env to enable.
62
-
63
- import { Pool, PoolClient } from "pg";
64
- import { v4 as uuid } from "uuid";
65
- import { pool } from "./db";
66
- import { logger } from "./logger";
67
- import { counter } from "./metrics";
68
-
69
- export type EventDeliveryMode = "in_process" | "durable";
70
-
71
- const MODE: EventDeliveryMode =
72
- (process.env.EVENT_MODE as EventDeliveryMode) || "in_process";
73
-
74
- // Events requiring exactly_once delivery (deduplicated)
75
- const EXACTLY_ONCE_EVENTS = new Set([${exactlyOnceEvents.join(", ")}]);
76
-
77
- // Events requiring at_least_once delivery (retried until ack)
78
- const AT_LEAST_ONCE_EVENTS = new Set([${atLeastOnceEvents.join(", ")}]);
79
-
80
- export interface EventMetadata {
81
- source: string;
82
- timestamp: Date;
83
- correlation_id: string;
84
- causation_id: string;
85
- }
86
-
87
- export interface SystemEvent {
88
- type: string;
89
- payload: Record<string, unknown>;
90
- metadata: EventMetadata;
91
- }
92
-
93
- type Handler = (event: SystemEvent) => Promise<void>;
94
-
95
- // ─── In-Process Bus ──────────────────────────────────────────────────────────
96
-
97
- class InProcessBus {
98
- private handlers: Map<string, Handler[]> = new Map();
99
-
100
- subscribe(type: string, handler: Handler): void {
101
- const existing = this.handlers.get(type) || [];
102
- existing.push(handler);
103
- this.handlers.set(type, existing);
104
- }
105
-
106
- async publish(type: string, payload: Record<string, unknown>, source: string, correlationId?: string): Promise<void> {
107
- const event: SystemEvent = {
108
- type,
109
- payload,
110
- metadata: {
111
- source,
112
- timestamp: new Date(),
113
- correlation_id: correlationId || uuid(),
114
- causation_id: uuid(),
115
- },
116
- };
117
- counter("event.published", { type, mode: "in_process" });
118
- const handlers = this.handlers.get(type) || [];
119
- for (const handler of handlers) {
120
- try {
121
- await handler(event);
122
- counter("event.delivered", { type, mode: "in_process" });
123
- } catch (e: any) {
124
- counter("event.delivery_failed", { type, mode: "in_process" });
125
- logger.error("event_handler_failed", { event: type, metadata: { error: e.message } });
126
- }
127
- }
128
- }
129
- }
130
-
131
- // ─── Durable Bus (Transactional Outbox) ──────────────────────────────────────
132
-
133
- class DurableBus {
134
- private handlers: Map<string, Handler[]> = new Map();
135
-
136
- subscribe(type: string, handler: Handler): void {
137
- const existing = this.handlers.get(type) || [];
138
- existing.push(handler);
139
- this.handlers.set(type, existing);
140
- }
141
-
142
- // Write event to outbox within the current transaction (or a new one)
143
- async publish(
144
- type: string,
145
- payload: Record<string, unknown>,
146
- source: string,
147
- correlationId?: string,
148
- client?: PoolClient
149
- ): Promise<void> {
150
- const eventId = uuid();
151
- const corrId = correlationId || uuid();
152
- const sql = \`
153
- INSERT INTO event_outbox (id, event_type, payload, source, correlation_id)
154
- VALUES ($1, $2, $3, $4, $5)
155
- \`;
156
- const params = [eventId, type, JSON.stringify({ ...payload, _event_id: eventId }), source, corrId];
157
-
158
- if (client) {
159
- // Write within caller's transaction — atomicity guaranteed
160
- await client.query(sql, params);
161
- } else {
162
- await pool.query(sql, params);
163
- }
164
- counter("event.outboxed", { type });
165
- }
166
-
167
- // Called by the background worker
168
- async flush(): Promise<void> {
169
- const client = await pool.connect();
170
- try {
171
- await client.query("BEGIN");
172
-
173
- // Fetch pending events (lock rows to prevent concurrent processing)
174
- const { rows } = await client.query(\`
175
- SELECT id, event_type, payload, source, correlation_id, attempts
176
- FROM event_outbox
177
- WHERE status = 'pending' AND scheduled_at <= NOW()
178
- ORDER BY scheduled_at ASC
179
- LIMIT 50
180
- FOR UPDATE SKIP LOCKED
181
- \`);
182
-
183
- for (const row of rows) {
184
- try {
185
- // exactly_once: check deduplication table
186
- if (EXACTLY_ONCE_EVENTS.has(row.event_type)) {
187
- const { rows: dup } = await client.query(
188
- "SELECT 1 FROM event_processed WHERE event_id = $1",
189
- [row.payload._event_id || row.id]
190
- );
191
- if (dup.length > 0) {
192
- await client.query(
193
- "UPDATE event_outbox SET status = 'delivered', delivered_at = NOW() WHERE id = $1",
194
- [row.id]
195
- );
196
- continue;
197
- }
198
- }
199
-
200
- const event: SystemEvent = {
201
- type: row.event_type,
202
- payload: row.payload,
203
- metadata: {
204
- source: row.source,
205
- timestamp: new Date(),
206
- correlation_id: row.correlation_id,
207
- causation_id: uuid(),
208
- },
209
- };
210
-
211
- const handlers = this.handlers.get(row.event_type) || [];
212
- for (const handler of handlers) {
213
- await handler(event);
214
- }
215
-
216
- // Mark delivered
217
- await client.query(
218
- "UPDATE event_outbox SET status = 'delivered', delivered_at = NOW(), attempts = attempts + 1 WHERE id = $1",
219
- [row.id]
220
- );
221
-
222
- // Record for exactly_once deduplication
223
- if (EXACTLY_ONCE_EVENTS.has(row.event_type)) {
224
- await client.query(
225
- "INSERT INTO event_processed (event_id, event_type) VALUES ($1, $2) ON CONFLICT DO NOTHING",
226
- [row.payload._event_id || row.id, row.event_type]
227
- );
228
- }
229
-
230
- counter("event.delivered", { type: row.event_type, mode: "durable" });
231
- } catch (e: any) {
232
- const maxAttempts = AT_LEAST_ONCE_EVENTS.has(row.event_type) ? 10 : 3;
233
- const newAttempts = row.attempts + 1;
234
- const status = newAttempts >= maxAttempts ? "dead_letter" : "pending";
235
- const backoffMs = Math.min(1000 * Math.pow(2, newAttempts), 300000);
236
- await client.query(
237
- \`UPDATE event_outbox
238
- SET attempts = $1, last_error = $2, status = $3,
239
- scheduled_at = NOW() + ($4 || ' milliseconds')::interval
240
- WHERE id = $5\`,
241
- [newAttempts, e.message, status, backoffMs, row.id]
242
- );
243
- counter("event.delivery_failed", { type: row.event_type, mode: "durable" });
244
- logger.error("event_delivery_failed", { event: row.event_type, metadata: { error: e.message, attempts: newAttempts } });
245
- }
246
- }
247
-
248
- await client.query("COMMIT");
249
- } catch (e) {
250
- await client.query("ROLLBACK");
251
- throw e;
252
- } finally {
253
- client.release();
254
- }
255
- }
256
-
257
- // Start background worker
258
- startWorker(intervalMs: number = 1000): NodeJS.Timeout {
259
- logger.info("event_worker_started", { event: "startup", metadata: { interval_ms: intervalMs } });
260
- return setInterval(async () => {
261
- try {
262
- await this.flush();
263
- } catch (e: any) {
264
- logger.error("event_worker_error", { event: "flush_failed", metadata: { error: e.message } });
265
- }
266
- }, intervalMs);
267
- }
268
- }
269
-
270
- // ─── Unified Interface ────────────────────────────────────────────────────────
271
-
272
- const inProcess = new InProcessBus();
273
- const durable = new DurableBus();
274
-
275
- export const eventBus = {
276
- subscribe(type: string, handler: Handler): void {
277
- inProcess.subscribe(type, handler);
278
- durable.subscribe(type, handler);
279
- },
280
-
281
- async publish(
282
- type: string,
283
- payload: Record<string, unknown>,
284
- source: string,
285
- correlationId?: string,
286
- client?: PoolClient
287
- ): Promise<void> {
288
- if (MODE === "durable") {
289
- await durable.publish(type, payload, source, correlationId, client);
290
- } else {
291
- await inProcess.publish(type, payload, source, correlationId);
292
- }
293
- },
294
-
295
- startWorker(intervalMs?: number): NodeJS.Timeout | null {
296
- if (MODE === "durable") {
297
- return durable.startWorker(intervalMs);
298
- }
299
- return null;
300
- },
301
- };
59
+ return `// Generated by BoneScript compiler. DO NOT EDIT.
60
+ // Durable event bus with transactional outbox pattern.
61
+ // Set EVENT_MODE=durable in .env to enable.
62
+
63
+ import { Pool, PoolClient } from "pg";
64
+ import { v4 as uuid } from "uuid";
65
+ import { pool } from "./db";
66
+ import { logger } from "./logger";
67
+ import { counter } from "./metrics";
68
+
69
+ export type EventDeliveryMode = "in_process" | "durable";
70
+
71
+ const MODE: EventDeliveryMode =
72
+ (process.env.EVENT_MODE as EventDeliveryMode) || "in_process";
73
+
74
+ // Events requiring exactly_once delivery (deduplicated)
75
+ const EXACTLY_ONCE_EVENTS = new Set([${exactlyOnceEvents.join(", ")}]);
76
+
77
+ // Events requiring at_least_once delivery (retried until ack)
78
+ const AT_LEAST_ONCE_EVENTS = new Set([${atLeastOnceEvents.join(", ")}]);
79
+
80
+ export interface EventMetadata {
81
+ source: string;
82
+ timestamp: Date;
83
+ correlation_id: string;
84
+ causation_id: string;
85
+ }
86
+
87
+ export interface SystemEvent {
88
+ type: string;
89
+ payload: Record<string, unknown>;
90
+ metadata: EventMetadata;
91
+ }
92
+
93
+ type Handler = (event: SystemEvent) => Promise<void>;
94
+
95
+ // ─── In-Process Bus ──────────────────────────────────────────────────────────
96
+
97
+ class InProcessBus {
98
+ private handlers: Map<string, Handler[]> = new Map();
99
+
100
+ subscribe(type: string, handler: Handler): void {
101
+ const existing = this.handlers.get(type) || [];
102
+ existing.push(handler);
103
+ this.handlers.set(type, existing);
104
+ }
105
+
106
+ async publish(type: string, payload: Record<string, unknown>, source: string, correlationId?: string): Promise<void> {
107
+ const event: SystemEvent = {
108
+ type,
109
+ payload,
110
+ metadata: {
111
+ source,
112
+ timestamp: new Date(),
113
+ correlation_id: correlationId || uuid(),
114
+ causation_id: uuid(),
115
+ },
116
+ };
117
+ counter("event.published", { type, mode: "in_process" });
118
+ const handlers = this.handlers.get(type) || [];
119
+ for (const handler of handlers) {
120
+ try {
121
+ await handler(event);
122
+ counter("event.delivered", { type, mode: "in_process" });
123
+ } catch (e: any) {
124
+ counter("event.delivery_failed", { type, mode: "in_process" });
125
+ logger.error("event_handler_failed", { event: type, metadata: { error: e.message } });
126
+ }
127
+ }
128
+ }
129
+ }
130
+
131
+ // ─── Durable Bus (Transactional Outbox) ──────────────────────────────────────
132
+
133
+ class DurableBus {
134
+ private handlers: Map<string, Handler[]> = new Map();
135
+
136
+ subscribe(type: string, handler: Handler): void {
137
+ const existing = this.handlers.get(type) || [];
138
+ existing.push(handler);
139
+ this.handlers.set(type, existing);
140
+ }
141
+
142
+ // Write event to outbox within the current transaction (or a new one)
143
+ async publish(
144
+ type: string,
145
+ payload: Record<string, unknown>,
146
+ source: string,
147
+ correlationId?: string,
148
+ client?: PoolClient
149
+ ): Promise<void> {
150
+ const eventId = uuid();
151
+ const corrId = correlationId || uuid();
152
+ const sql = \`
153
+ INSERT INTO event_outbox (id, event_type, payload, source, correlation_id)
154
+ VALUES ($1, $2, $3, $4, $5)
155
+ \`;
156
+ const params = [eventId, type, JSON.stringify({ ...payload, _event_id: eventId }), source, corrId];
157
+
158
+ if (client) {
159
+ // Write within caller's transaction — atomicity guaranteed
160
+ await client.query(sql, params);
161
+ } else {
162
+ await pool.query(sql, params);
163
+ }
164
+ counter("event.outboxed", { type });
165
+ }
166
+
167
+ // Called by the background worker
168
+ async flush(): Promise<void> {
169
+ const client = await pool.connect();
170
+ try {
171
+ await client.query("BEGIN");
172
+
173
+ // Fetch pending events (lock rows to prevent concurrent processing)
174
+ const { rows } = await client.query(\`
175
+ SELECT id, event_type, payload, source, correlation_id, attempts
176
+ FROM event_outbox
177
+ WHERE status = 'pending' AND scheduled_at <= NOW()
178
+ ORDER BY scheduled_at ASC
179
+ LIMIT 50
180
+ FOR UPDATE SKIP LOCKED
181
+ \`);
182
+
183
+ for (const row of rows) {
184
+ try {
185
+ // exactly_once: check deduplication table
186
+ if (EXACTLY_ONCE_EVENTS.has(row.event_type)) {
187
+ const { rows: dup } = await client.query(
188
+ "SELECT 1 FROM event_processed WHERE event_id = $1",
189
+ [row.payload._event_id || row.id]
190
+ );
191
+ if (dup.length > 0) {
192
+ await client.query(
193
+ "UPDATE event_outbox SET status = 'delivered', delivered_at = NOW() WHERE id = $1",
194
+ [row.id]
195
+ );
196
+ continue;
197
+ }
198
+ }
199
+
200
+ const event: SystemEvent = {
201
+ type: row.event_type,
202
+ payload: row.payload,
203
+ metadata: {
204
+ source: row.source,
205
+ timestamp: new Date(),
206
+ correlation_id: row.correlation_id,
207
+ causation_id: uuid(),
208
+ },
209
+ };
210
+
211
+ const handlers = this.handlers.get(row.event_type) || [];
212
+ for (const handler of handlers) {
213
+ await handler(event);
214
+ }
215
+
216
+ // Mark delivered
217
+ await client.query(
218
+ "UPDATE event_outbox SET status = 'delivered', delivered_at = NOW(), attempts = attempts + 1 WHERE id = $1",
219
+ [row.id]
220
+ );
221
+
222
+ // Record for exactly_once deduplication
223
+ if (EXACTLY_ONCE_EVENTS.has(row.event_type)) {
224
+ await client.query(
225
+ "INSERT INTO event_processed (event_id, event_type) VALUES ($1, $2) ON CONFLICT DO NOTHING",
226
+ [row.payload._event_id || row.id, row.event_type]
227
+ );
228
+ }
229
+
230
+ counter("event.delivered", { type: row.event_type, mode: "durable" });
231
+ } catch (e: any) {
232
+ const maxAttempts = AT_LEAST_ONCE_EVENTS.has(row.event_type) ? 10 : 3;
233
+ const newAttempts = row.attempts + 1;
234
+ const status = newAttempts >= maxAttempts ? "dead_letter" : "pending";
235
+ const backoffMs = Math.min(1000 * Math.pow(2, newAttempts), 300000);
236
+ await client.query(
237
+ \`UPDATE event_outbox
238
+ SET attempts = $1, last_error = $2, status = $3,
239
+ scheduled_at = NOW() + ($4 || ' milliseconds')::interval
240
+ WHERE id = $5\`,
241
+ [newAttempts, e.message, status, backoffMs, row.id]
242
+ );
243
+ counter("event.delivery_failed", { type: row.event_type, mode: "durable" });
244
+ logger.error("event_delivery_failed", { event: row.event_type, metadata: { error: e.message, attempts: newAttempts } });
245
+ }
246
+ }
247
+
248
+ await client.query("COMMIT");
249
+ } catch (e) {
250
+ await client.query("ROLLBACK");
251
+ throw e;
252
+ } finally {
253
+ client.release();
254
+ }
255
+ }
256
+
257
+ // Start background worker
258
+ startWorker(intervalMs: number = 1000): NodeJS.Timeout {
259
+ logger.info("event_worker_started", { event: "startup", metadata: { interval_ms: intervalMs } });
260
+ return setInterval(async () => {
261
+ try {
262
+ await this.flush();
263
+ } catch (e: any) {
264
+ logger.error("event_worker_error", { event: "flush_failed", metadata: { error: e.message } });
265
+ }
266
+ }, intervalMs);
267
+ }
268
+ }
269
+
270
+ // ─── Unified Interface ────────────────────────────────────────────────────────
271
+
272
+ const inProcess = new InProcessBus();
273
+ const durable = new DurableBus();
274
+
275
+ export const eventBus = {
276
+ subscribe(type: string, handler: Handler): void {
277
+ inProcess.subscribe(type, handler);
278
+ durable.subscribe(type, handler);
279
+ },
280
+
281
+ async publish(
282
+ type: string,
283
+ payload: Record<string, unknown>,
284
+ source: string,
285
+ correlationId?: string,
286
+ client?: PoolClient
287
+ ): Promise<void> {
288
+ if (MODE === "durable") {
289
+ await durable.publish(type, payload, source, correlationId, client);
290
+ } else {
291
+ await inProcess.publish(type, payload, source, correlationId);
292
+ }
293
+ },
294
+
295
+ startWorker(intervalMs?: number): NodeJS.Timeout | null {
296
+ if (MODE === "durable") {
297
+ return durable.startWorker(intervalMs);
298
+ }
299
+ return null;
300
+ },
301
+ };
302
302
  `;
303
303
  }
304
304
  exports.emitDurableEventBus = emitDurableEventBus;
305
+ // ─── Typed Event Publishers ───────────────────────────────────────────────────
306
+ // Generates per-event emitXxx() typed publisher functions as specified in
307
+ // spec/09_CODEGEN.md §5.4. These wrap eventBus.publish with a typed payload
308
+ // interface so callers get compile-time safety instead of raw Record<string,unknown>.
309
+ const TS_TYPE_MAP = {
310
+ string: "string", uint: "number", int: "number", float: "number",
311
+ bool: "boolean", timestamp: "Date", uuid: "string", bytes: "Buffer", json: "unknown",
312
+ };
313
+ function toTsType(irType) {
314
+ if (TS_TYPE_MAP[irType])
315
+ return TS_TYPE_MAP[irType];
316
+ const listMatch = irType.match(/^list<(.+)>$/);
317
+ if (listMatch)
318
+ return `${toTsType(listMatch[1])}[]`;
319
+ const setMatch = irType.match(/^set<(.+)>$/);
320
+ if (setMatch)
321
+ return `${toTsType(setMatch[1])}[]`;
322
+ const optMatch = irType.match(/^optional<(.+)>$/);
323
+ if (optMatch)
324
+ return `${toTsType(optMatch[1])} | null`;
325
+ return irType;
326
+ }
327
+ function emitTypedEventPublishers(system) {
328
+ if (system.events.length === 0)
329
+ return "";
330
+ const lines = [];
331
+ lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
332
+ lines.push(`// Typed event publisher functions — one per declared event.`);
333
+ lines.push(`// Import these instead of calling eventBus.publish() directly.`);
334
+ lines.push(``);
335
+ lines.push(`import { eventBus } from "./events";`);
336
+ lines.push(`import type { PoolClient } from "pg";`);
337
+ lines.push(``);
338
+ for (const ev of system.events) {
339
+ const ifaceName = `${ev.name}Payload`;
340
+ // Payload interface
341
+ lines.push(`export interface ${ifaceName} {`);
342
+ for (const field of ev.payload) {
343
+ const nullable = field.nullable ? " | null" : "";
344
+ lines.push(` ${field.name}: ${toTsType(field.type)}${nullable};`);
345
+ }
346
+ lines.push(`}`);
347
+ lines.push(``);
348
+ // Publisher function
349
+ const sourceId = ev.source && ev.source !== "unknown" ? ev.source : system.name;
350
+ lines.push(`/**`);
351
+ lines.push(` * Publish a ${ev.name} event.`);
352
+ lines.push(` * Delivery: ${ev.delivery}${ev.ttl_ms ? ` | TTL: ${ev.ttl_ms}ms` : ""}`);
353
+ lines.push(` */`);
354
+ lines.push(`export async function emit${ev.name}(`);
355
+ lines.push(` payload: ${ifaceName},`);
356
+ lines.push(` correlationId?: string,`);
357
+ lines.push(` client?: PoolClient,`);
358
+ lines.push(`): Promise<void> {`);
359
+ lines.push(` await eventBus.publish(`);
360
+ lines.push(` "${ev.name}",`);
361
+ lines.push(` payload as unknown as Record<string, unknown>,`);
362
+ lines.push(` "${sourceId}",`);
363
+ lines.push(` correlationId,`);
364
+ lines.push(` client,`);
365
+ lines.push(` );`);
366
+ lines.push(`}`);
367
+ lines.push(``);
368
+ }
369
+ return lines.join("\n");
370
+ }
371
+ exports.emitTypedEventPublishers = emitTypedEventPublishers;
305
372
  //# sourceMappingURL=emit_events.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"emit_events.js","sourceRoot":"","sources":["../src/emit_events.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAIH,iFAAiF;AAEjF,SAAgB,gBAAgB;IAC9B,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BR,CAAC;AACF,CAAC;AAjCD,4CAiCC;AAED,iFAAiF;AAEjF,SAAgB,mBAAmB,CAAC,MAAmB;IACrD,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM;SACpC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,cAAc,CAAC;SAC1C,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC;IAE3B,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM;SACpC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,eAAe,CAAC;SAC3C,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC;IAE3B,OAAO;;;;;;;;;;;;;;;;uCAgB8B,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC;;;wCAG3B,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgOnE,CAAC;AACF,CAAC;AA7PD,kDA6PC"}
1
+ {"version":3,"file":"emit_events.js","sourceRoot":"","sources":["../src/emit_events.ts"],"names":[],"mappings":";AAAA;;;;;;;;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