@brickkit/core 0.10.0 → 0.12.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.
@@ -0,0 +1,4624 @@
1
+ import { c as SOCKET_MAX_BYTES, d as isSocketRoom, f as isSocketSeq, g as kebabCase, h as ValidationError, m as ActionExecutionError, p as serializeSocketSchema, s as SOCKET_BUFFER_BYTES, u as isSocketEnvelope } from "./client.js";
2
+ import "../workflow.js";
3
+ import { createRequire } from "node:module";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
6
+ import { Type, Type as t } from "@sinclair/typebox";
7
+ import { TypeCompiler } from "@sinclair/typebox/compiler";
8
+ import { formatWithOptions } from "node:util";
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { dirname, isAbsolute, join, resolve } from "node:path";
11
+ import { Value } from "@sinclair/typebox/value";
12
+ import { and, asc, eq, getTableName, inArray, lt, lte, or, sql } from "drizzle-orm";
13
+ import { index, integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
14
+ import { bigserial, boolean, doublePrecision, index as index$1, integer as integer$1, jsonb, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
15
+ import { AsyncLocalStorage } from "node:async_hooks";
16
+ import { Elysia } from "elysia";
17
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
18
+ import { websocket } from "elysia/websocket";
19
+ // src/routes.ts
20
+ /**
21
+ * The route every name of an owner mounts under: `${prefix}`,
22
+ * `${prefix}/${service}`, or `${prefix}/${service}/${resource}`, in kebab-case.
23
+ */
24
+ function ownerPath(prefix, service, resource) {
25
+ let path = prefix.replace(/\/$/, "");
26
+ if (service !== void 0) path += `/${kebabCase(service)}`;
27
+ if (resource !== void 0) path += `/${kebabCase(resource)}`;
28
+ return path;
29
+ }
30
+ /** Joins a path relative to its owner. `/` is the owner's own route. */
31
+ function joinRoute(base, path) {
32
+ return `${base}${path === "/" ? "" : path}` || "/";
33
+ }
34
+ /**
35
+ * Where an action is served over HTTP: its method and its path under the owner
36
+ * tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource
37
+ * action's `${prefix}/${service}/${resource}[/:id]/${action}`).
38
+ *
39
+ * @param action - An action registered on a service.
40
+ * @param prefix - The application's route prefix (default `/api`).
41
+ * @returns `false` when a plugin switched the route off, otherwise the route.
42
+ */
43
+ function getActionRoute(action, prefix = "/api") {
44
+ const plugin = getPluginActionRoute(action, prefix);
45
+ if (plugin === false) return false;
46
+ if (plugin) return {
47
+ method: plugin.method,
48
+ path: plugin.path
49
+ };
50
+ const service = action.serviceName ?? "";
51
+ const method = action.config.method ?? "POST";
52
+ const { resourceAction } = action;
53
+ if (resourceAction) {
54
+ const base = ownerPath(prefix, service, resourceAction.resource);
55
+ return {
56
+ method,
57
+ path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}${resourceAction.record ? "/:id" : ""}/${kebabCase(resourceAction.name)}`
58
+ };
59
+ }
60
+ const base = ownerPath(prefix, service);
61
+ return {
62
+ method,
63
+ path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}/${kebabCase(action.name)}`
64
+ };
65
+ }
66
+ // src/compiler/ir.ts
67
+ function freezeIR(value) {
68
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
69
+ for (const child of Object.values(value)) freezeIR(child);
70
+ Object.freeze(value);
71
+ }
72
+ return value;
73
+ }
74
+ function schemaSnapshot(schema) {
75
+ return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
76
+ }
77
+ function analyzeApplication(services, prefix = "/api") {
78
+ for (const service of services) service.build();
79
+ return analyzeDeclaredApplication(services, prefix);
80
+ }
81
+ /** Inspect current declarations without closing service/plugin setup. */
82
+ function analyzeDeclaredApplication(services, prefix = "/api") {
83
+ if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
84
+ const names = /* @__PURE__ */ new Set();
85
+ for (const service of services) {
86
+ if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
87
+ names.add(service.name);
88
+ }
89
+ const routes = [];
90
+ const bindings = [];
91
+ const registered = /* @__PURE__ */ new Map();
92
+ const diagnostics = [];
93
+ const add = (service, action, method, path, kind) => {
94
+ if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
95
+ const plugin = getPluginActionRoute(action, prefix) !== void 0;
96
+ const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
97
+ const previous = registered.get(key);
98
+ if (previous) {
99
+ if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
100
+ diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
101
+ return;
102
+ }
103
+ if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
104
+ registered.set(key, {
105
+ name: `${service.name}.${action.name}`,
106
+ plugin
107
+ });
108
+ const readLike = method === "GET" || action.name.startsWith("get") || action.name.endsWith(".get") || action.name.startsWith("list") || action.name.endsWith(".list") || action.name.startsWith("find") || action.name.startsWith("read");
109
+ const coercions = [];
110
+ for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
111
+ key,
112
+ type: "number"
113
+ });
114
+ else if (prop.type === "boolean") coercions.push({
115
+ key,
116
+ type: "boolean"
117
+ });
118
+ else if (prop.type === "array") coercions.push({
119
+ key,
120
+ type: "array"
121
+ });
122
+ routes.push({
123
+ method,
124
+ path,
125
+ service: service.name,
126
+ action: action.name,
127
+ kind,
128
+ input: Boolean(action.config.input),
129
+ output: Boolean(action.config.output),
130
+ context: typeof service.options.context === "function",
131
+ authorize: typeof action.config.authorize === "function",
132
+ inputPrecedence: readLike ? [
133
+ "query",
134
+ "params",
135
+ "body"
136
+ ] : [
137
+ "params",
138
+ "body",
139
+ "query"
140
+ ],
141
+ coercions,
142
+ inputSchema: schemaSnapshot(action.config.input),
143
+ outputSchema: schemaSnapshot(action.config.output)
144
+ });
145
+ bindings.push({
146
+ service,
147
+ action
148
+ });
149
+ };
150
+ for (const service of services) {
151
+ checkSegments(service);
152
+ for (const action of service.listActions()) {
153
+ const route = getActionRoute(action, prefix);
154
+ if (route === false) continue;
155
+ add(service, action, route.method, route.path, "action");
156
+ }
157
+ }
158
+ const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
159
+ service: service.name,
160
+ name: contribution.name,
161
+ metadata: schemaSnapshot(contribution.describe?.())
162
+ })));
163
+ return {
164
+ ir: freezeIR({
165
+ version: 1,
166
+ target: "bun-elysia",
167
+ prefix,
168
+ services: [...names],
169
+ routes,
170
+ preparations,
171
+ diagnostics
172
+ }),
173
+ bindings
174
+ };
175
+ }
176
+ /** A service action, resource, and socket own the URL segment after the service. */
177
+ function checkSegments(service) {
178
+ const owners = /* @__PURE__ */ new Map();
179
+ const claim = (segment, owner) => {
180
+ const previous = owners.get(segment);
181
+ if (previous) throw new Error(`Brick: duplicate name "${segment}" in service "${service.name}": ${previous} and ${owner} share the URL segment`);
182
+ owners.set(segment, owner);
183
+ };
184
+ for (const resource of service.listResources()) claim(kebabCase(resource.name), `resource "${resource.name}"`);
185
+ for (const socket of service.listSockets()) if (socket.schema.path === void 0) claim(kebabCase(socket.schema.name), `socket "${socket.schema.name}"`);
186
+ for (const action of service.listActions()) if (action.config.path === void 0 && !action.resourceAction && getPluginActionRoute(action) === void 0) claim(kebabCase(action.name), `action "${action.name}"`);
187
+ }
188
+ // src/registry.ts
189
+ const brickRoot = fileURLToPath(new URL("..", import.meta.url));
190
+ /**
191
+ * The first `file:line` outside Brick on the current stack: where a name is
192
+ * being defined. Best-effort: `undefined` when there is no stack.
193
+ */
194
+ function definitionSite() {
195
+ const limit = Error.stackTraceLimit;
196
+ Error.stackTraceLimit = 50;
197
+ const stack = (/* @__PURE__ */ new Error()).stack;
198
+ Error.stackTraceLimit = limit;
199
+ for (const line of stack?.split("\n").slice(1) ?? []) {
200
+ const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
201
+ if (!match) continue;
202
+ const [, file, row] = match;
203
+ if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
204
+ return `${file}:${row}`;
205
+ }
206
+ }
207
+ /**
208
+ * Records where `name` is defined. The same file defining it again (a dev
209
+ * reload) replaces the old definition.
210
+ *
211
+ * @throws When a different file already defined `name`.
212
+ */
213
+ function claimName(sites, label, name, site) {
214
+ const file = (at) => at?.replace(/:\d+$/, "");
215
+ if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new Error(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
216
+ sites.set(name, site);
217
+ }
218
+ var ServiceRegistry = class {
219
+ _revision = 0;
220
+ /** Definition revision for invalidating serialized architecture snapshots. */
221
+ get revision() {
222
+ return this._revision;
223
+ }
224
+ touch() {
225
+ this._revision++;
226
+ }
227
+ services = /* @__PURE__ */ new Map();
228
+ sites = /* @__PURE__ */ new Map();
229
+ routes = /* @__PURE__ */ new Map();
230
+ /** Remember the actual registered routes for subsequent registry exports. */
231
+ setApplicationRoutes(application) {
232
+ for (const service of application.services) this.routes.set(service, application.routes.filter((route) => route.service === service.name));
233
+ this.touch();
234
+ }
235
+ /** @throws When a different file already registered a service with this name. */
236
+ register(service, site = definitionSite()) {
237
+ claimName(this.sites, `service "${service.name}"`, service.name, site);
238
+ const previous = this.services.get(service.name);
239
+ if (previous) this.routes.delete(previous);
240
+ this.services.set(service.name, service);
241
+ this.touch();
242
+ }
243
+ get(name) {
244
+ return this.services.get(name);
245
+ }
246
+ has(name) {
247
+ return this.services.has(name);
248
+ }
249
+ list() {
250
+ return Array.from(this.services.values());
251
+ }
252
+ clear() {
253
+ this.services.clear();
254
+ this.sites.clear();
255
+ this.routes.clear();
256
+ this.touch();
257
+ }
258
+ exportArchitecture(application) {
259
+ return {
260
+ version: "1.0.0",
261
+ ...application?.events ? { events: application.events } : {},
262
+ ...application?.plugins?.length ? { plugins: [...application.plugins] } : {},
263
+ services: (application?.services ?? this.list()).map((service) => {
264
+ const routes = application ? application.routes.filter((route) => route.service === service.name) : this.routes.get(service) ?? analyzeDeclaredApplication([service]).ir.routes;
265
+ const byAction = new Map(routes.map((route) => [route.action, route]));
266
+ const schema = service.introspect();
267
+ return {
268
+ ...schema,
269
+ ...application?.sockets ? { sockets: application.sockets.filter((socket) => socket.service === service.name) } : {},
270
+ actions: schema.actions.map((action) => {
271
+ const route = byAction.get(action.name);
272
+ return route ? {
273
+ ...action,
274
+ method: route.method,
275
+ path: route.path
276
+ } : action;
277
+ })
278
+ };
279
+ })
280
+ };
281
+ }
282
+ };
283
+ let globalRegistry = new ServiceRegistry();
284
+ /**
285
+ * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
286
+ * generator, `useService`, and the dashboard find services by name.
287
+ *
288
+ * @returns The current global registry.
289
+ */
290
+ function getGlobalRegistry() {
291
+ return globalRegistry;
292
+ }
293
+ /**
294
+ * Start over with an empty global registry. For tests, which define the same
295
+ * services again in each case; an application never needs it.
296
+ */
297
+ function resetGlobalRegistry() {
298
+ globalRegistry = new ServiceRegistry();
299
+ }
300
+ // src/telemetry.ts
301
+ const INSTRUMENTATION_SCOPE = "@brickkit/core";
302
+ const MAX_TEXT_LENGTH = 500;
303
+ const MAX_STATEMENT_LENGTH = 2e3;
304
+ const DATABASE_INSTRUMENTED = Symbol.for("brickkit.telemetry.database");
305
+ const SQLITE_STATEMENT_METHODS = [
306
+ "all",
307
+ "get",
308
+ "run",
309
+ "values"
310
+ ];
311
+ /** Run `fn` as a child of the active span, ending the span when its result settles. */
312
+ function withSpan(name, attributes, fn, kind = SpanKind.INTERNAL) {
313
+ return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(name, {
314
+ kind,
315
+ attributes
316
+ }, (span) => settle(fn, (outcome) => {
317
+ if (outcome.failed) recordThrown(span, outcome.error);
318
+ span.end();
319
+ }));
320
+ }
321
+ /**
322
+ * Add a child span for an in-process call, but only inside a request that is
323
+ * already traced. Calls made outside instrumented requests run unchanged.
324
+ */
325
+ function withCallSpan(name, attributes, fn) {
326
+ return trace.getActiveSpan() ? withSpan(name, attributes, fn) : fn();
327
+ }
328
+ /**
329
+ * Wrap a raw route handler so each of its requests gets a server span. Use it
330
+ * for routes registered directly on the app, outside actions and endpoints,
331
+ * such as auth or webhook routes. Spans are recorded whenever a tracer provider
332
+ * is registered; `brick({ telemetry })` does not apply to these routes.
333
+ *
334
+ * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia
335
+ * decides what to parse from the handler's destructuring, and forwarding the
336
+ * whole context would parse the body and leave `request.json()` with nothing.
337
+ */
338
+ function traceRoute(route, handler) {
339
+ return ({ request, headers, set, params, query }) => traceHttpRequest({
340
+ request,
341
+ headers,
342
+ set
343
+ }, request.method, route, () => handler({
344
+ request,
345
+ headers,
346
+ set,
347
+ params,
348
+ query
349
+ }));
350
+ }
351
+ /**
352
+ * Wrap one HTTP request in a server span. The span continues the caller's
353
+ * trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the
354
+ * request id Brick returns is the span's trace id, so clients can find the
355
+ * request in the dashboard.
356
+ */
357
+ function traceHttpRequest(request, method, route, fn) {
358
+ const attributes = {
359
+ "http.request.method": method,
360
+ "http.route": route
361
+ };
362
+ if (request.request) attributes["url.path"] = new URL(request.request.url).pathname;
363
+ const headers = request.headers ?? {};
364
+ const parent = propagation.extract(context.active(), headers);
365
+ return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(`${method} ${route}`, {
366
+ kind: SpanKind.SERVER,
367
+ attributes
368
+ }, parent, (span) => {
369
+ if (!headers["x-trace-id"]) headers["x-trace-id"] = span.spanContext().traceId;
370
+ const outgoing = {};
371
+ propagation.inject(context.active(), outgoing);
372
+ if (request.set?.headers) Object.assign(request.set.headers, outgoing);
373
+ return settle(fn, (outcome) => {
374
+ const status = outcome.failed ? 500 : outcome.value instanceof Response ? outcome.value.status : responseStatus(request.set?.status);
375
+ if (outcome.failed) recordThrown(span, outcome.error);
376
+ span.setAttribute("http.response.status_code", status);
377
+ const traceId = headers["x-trace-id"];
378
+ if (traceId) span.setAttribute("brick.trace_id", traceId);
379
+ if (status >= 500) span.setStatus({
380
+ code: SpanStatusCode.ERROR,
381
+ message: `HTTP ${status}`
382
+ });
383
+ span.end();
384
+ });
385
+ });
386
+ }
387
+ /**
388
+ * Attach a handled failure to the active span. Brick returns these as
389
+ * responses rather than throwing, so only server faults (5xx) mark the span
390
+ * as errored; client errors keep their code as an attribute.
391
+ */
392
+ function recordFailure(error, failure) {
393
+ const span = trace.getActiveSpan();
394
+ if (!span) return;
395
+ span.setAttributes({
396
+ "brick.error.code": failure.code,
397
+ "brick.error.status": failure.status,
398
+ "brick.error.message": truncate(failure.message)
399
+ });
400
+ if (failure.status >= 500) recordThrown(span, error);
401
+ }
402
+ /**
403
+ * Record SQL statements as client spans for the database behind a service.
404
+ * Drizzle's logger has no timing, so the hook sits on the driver: each
405
+ * statement is timed where the driver runs it. Statements outside traced
406
+ * requests are not recorded. Calling this again on the same client is a no-op.
407
+ */
408
+ function instrumentDatabase(db) {
409
+ const client = db?.$client;
410
+ if (typeof client !== "object" && typeof client !== "function" || client === null) return;
411
+ const driver = client;
412
+ if (driver[DATABASE_INSTRUMENTED]) return;
413
+ if (typeof driver.prepare === "function") instrumentBunSqlite(driver);
414
+ else if (typeof driver.unsafe === "function") instrumentPostgres(driver);
415
+ else return;
416
+ driver[DATABASE_INSTRUMENTED] = true;
417
+ }
418
+ function instrumentBunSqlite(client) {
419
+ const prepare = client.prepare.bind(client);
420
+ client.prepare = (sql) => {
421
+ const statement = prepare(sql);
422
+ for (const method of SQLITE_STATEMENT_METHODS) {
423
+ const original = statement[method];
424
+ if (typeof original !== "function") continue;
425
+ statement[method] = (...args) => recordStatement(sql, "sqlite", () => original.apply(statement, args));
426
+ }
427
+ return statement;
428
+ };
429
+ }
430
+ /**
431
+ * postgres.js returns a query that runs when awaited, and `values()` returns
432
+ * that same object, so overriding `then` on it times the whole round trip.
433
+ */
434
+ function instrumentPostgres(client) {
435
+ const unsafe = client.unsafe.bind(client);
436
+ client.unsafe = (sql, ...rest) => {
437
+ const query = unsafe(sql, ...rest);
438
+ if (!trace.getActiveSpan() || typeof query?.then !== "function") return query;
439
+ const span = startStatementSpan(sql, "postgresql");
440
+ let finished = false;
441
+ const finish = (outcome) => {
442
+ if (finished) return;
443
+ finished = true;
444
+ if (outcome.failed) recordThrown(span, outcome.error);
445
+ span.end();
446
+ };
447
+ const then = query.then.bind(query);
448
+ query.then = (onFulfilled, onRejected) => then((value) => {
449
+ finish({
450
+ failed: false,
451
+ value
452
+ });
453
+ return onFulfilled ? onFulfilled(value) : value;
454
+ }, (error) => {
455
+ finish({
456
+ failed: true,
457
+ error
458
+ });
459
+ if (onRejected) return onRejected(error);
460
+ throw error;
461
+ });
462
+ return query;
463
+ };
464
+ }
465
+ function recordStatement(sql, system, fn) {
466
+ if (!trace.getActiveSpan()) return fn();
467
+ return withSpan(statementName(sql), statementAttributes(sql, system), fn, SpanKind.CLIENT);
468
+ }
469
+ function startStatementSpan(sql, system) {
470
+ return trace.getTracer(INSTRUMENTATION_SCOPE).startSpan(statementName(sql), {
471
+ kind: SpanKind.CLIENT,
472
+ attributes: statementAttributes(sql, system)
473
+ }, context.active());
474
+ }
475
+ function statementName(sql) {
476
+ return `SQL ${operationOf(sql)}`;
477
+ }
478
+ function statementAttributes(sql, system) {
479
+ return {
480
+ "db.system": system,
481
+ "db.operation": operationOf(sql),
482
+ "db.statement": truncate(sql, MAX_STATEMENT_LENGTH)
483
+ };
484
+ }
485
+ function operationOf(sql) {
486
+ return sql.trim().split(/\s+/, 1)[0]?.toUpperCase() || "SQL";
487
+ }
488
+ function settle(fn, done) {
489
+ let result;
490
+ try {
491
+ result = fn();
492
+ } catch (error) {
493
+ done({
494
+ failed: true,
495
+ error
496
+ });
497
+ throw error;
498
+ }
499
+ if (isPromiseLike(result)) return result.then((value) => {
500
+ done({
501
+ failed: false,
502
+ value
503
+ });
504
+ return value;
505
+ }, (error) => {
506
+ done({
507
+ failed: true,
508
+ error
509
+ });
510
+ throw error;
511
+ });
512
+ done({
513
+ failed: false,
514
+ value: result
515
+ });
516
+ return result;
517
+ }
518
+ function recordThrown(span, error) {
519
+ span.recordException(error instanceof Error ? error : String(error));
520
+ span.setStatus({
521
+ code: SpanStatusCode.ERROR,
522
+ message: truncate(messageOf(error))
523
+ });
524
+ }
525
+ function responseStatus(value) {
526
+ const status = typeof value === "number" ? value : Number(value ?? 200);
527
+ return Number.isInteger(status) ? status : 200;
528
+ }
529
+ function isPromiseLike(value) {
530
+ return typeof value === "object" && value !== null && typeof value.then === "function";
531
+ }
532
+ function messageOf(error) {
533
+ return error instanceof Error ? error.message : String(error);
534
+ }
535
+ function truncate(text, limit = MAX_TEXT_LENGTH) {
536
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
537
+ }
538
+ // src/error-response.ts
539
+ /** Preserve declared failures, log and wrap unexpected throws without exposing internals. */
540
+ function normalizeActionError(err, { logger, requestId }) {
541
+ if (err instanceof ActionExecutionError || err instanceof ValidationError) return err;
542
+ logger.error("Unexpected action error", { requestId }, err);
543
+ const failure = new ActionExecutionError("INTERNAL_SERVER_ERROR", "Internal Server Error", 500, void 0, { cause: err });
544
+ failure.name = "InternalServerError";
545
+ return failure;
546
+ }
547
+ /**
548
+ * Turn what an action threw into the JSON body of its HTTP response, and record
549
+ * the failure on the active trace. Declared failures and validation errors keep
550
+ * their code, status, and details; anything else is logged and answered as a
551
+ * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.
552
+ *
553
+ * @param err - Whatever was thrown.
554
+ * @param context - A `logger` with `error()`, and the `requestId` to put in the body.
555
+ * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and
556
+ * `details` or `errors` when there are any.
557
+ */
558
+ function toErrorResponse(err, context) {
559
+ const envelope = buildErrorEnvelope(err, context);
560
+ recordFailure(err, envelope);
561
+ return envelope;
562
+ }
563
+ function buildErrorEnvelope(err, context) {
564
+ const failure = normalizeActionError(err, context);
565
+ if (failure.status >= 500 && (err instanceof ActionExecutionError || err instanceof ValidationError)) context.logger.error("Server action error", { requestId: context.requestId }, err);
566
+ if (failure instanceof ValidationError && failure.status >= 500) return {
567
+ name: failure.name,
568
+ code: failure.code,
569
+ message: failure.message,
570
+ status: failure.status,
571
+ requestId: context.requestId
572
+ };
573
+ return {
574
+ ...failure.toJSON(),
575
+ requestId: context.requestId
576
+ };
577
+ }
578
+ // src/typebox.ts
579
+ const compilerCache = /* @__PURE__ */ new WeakMap();
580
+ /**
581
+ * The compiled validator for a TypeBox schema. Compiling is slow and checking
582
+ * is fast, so each schema is compiled once and kept for as long as the schema
583
+ * object lives.
584
+ *
585
+ * @param schema - A TypeBox schema.
586
+ * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.
587
+ */
588
+ function getCompiledCheck(schema) {
589
+ let compiled = compilerCache.get(schema);
590
+ if (!compiled) {
591
+ compiled = TypeCompiler.Compile(schema);
592
+ compilerCache.set(schema, compiled);
593
+ }
594
+ return compiled;
595
+ }
596
+ /**
597
+ * Check a value against a schema, the way actions check their input and output.
598
+ *
599
+ * @param schema - A TypeBox schema, or `undefined` to accept anything.
600
+ * @param value - The value to check.
601
+ * @returns `{ success: true, data }`, or `{ success: false, errors }` with a
602
+ * `path`, `message`, `type`, and the offending `value` for each problem.
603
+ */
604
+ function validateWithSchema(schema, value) {
605
+ if (!schema) return {
606
+ success: true,
607
+ data: value
608
+ };
609
+ const check = getCompiledCheck(schema);
610
+ if (check.Check(value)) return {
611
+ success: true,
612
+ data: value
613
+ };
614
+ const errors = [];
615
+ for (const error of check.Errors(value)) errors.push({
616
+ path: error.path,
617
+ message: error.message,
618
+ value: error.value,
619
+ type: error.type
620
+ });
621
+ return {
622
+ success: false,
623
+ errors
624
+ };
625
+ }
626
+ // src/logger.ts
627
+ /**
628
+ * Set by the CLI when a dashboard is collecting logs, in `brick dev` or in
629
+ * `brick start` with the `dashboard` option. A shared symbol, not an option or
630
+ * an export: the CLI and the app may each hold their own copy of this package,
631
+ * and nothing but a dashboard turns it on.
632
+ */
633
+ const CAPTURE = Symbol.for("brickkit.logs.capture");
634
+ /** The span event a log line becomes; the dashboard reads these. */
635
+ const LOG_EVENT = "log";
636
+ const MAX_MESSAGE_LENGTH = 4e3;
637
+ /**
638
+ * Logs one span keeps. OpenTelemetry keeps 128 events per span by default,
639
+ * exceptions among them, so a chatty action must not use them all up and
640
+ * lose the stack trace of the error that ends it.
641
+ */
642
+ const MAX_LOGS_PER_SPAN = 100;
643
+ const logged = /* @__PURE__ */ new WeakMap();
644
+ /**
645
+ * Terminal formatting: colors and styles (`ESC [ … m`, and other CSI codes) and
646
+ * titles or links (`ESC ] … BEL`). Libraries such as Better Auth color their
647
+ * console output, which in a web page shows as stray characters.
648
+ */
649
+ const ANSI = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\))/g;
650
+ /** `text` without terminal formatting. */
651
+ function stripAnsi(text) {
652
+ return text.includes("\x1B") ? text.replace(ANSI, "") : text;
653
+ }
654
+ /**
655
+ * What `console.log` would print, without terminal colors, with objects cut off
656
+ * at a sensible size.
657
+ */
658
+ function render(args) {
659
+ const text = stripAnsi(formatWithOptions({
660
+ depth: 3,
661
+ breakLength: 120,
662
+ maxArrayLength: 50,
663
+ maxStringLength: 1e3
664
+ }, ...args));
665
+ return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text;
666
+ }
667
+ function record(span, level, args) {
668
+ const count = (logged.get(span) ?? 0) + 1;
669
+ logged.set(span, count);
670
+ if (count > MAX_LOGS_PER_SPAN) {
671
+ span.setAttribute("brick.logs.dropped", count - MAX_LOGS_PER_SPAN);
672
+ return;
673
+ }
674
+ span.addEvent(LOG_EVENT, {
675
+ "log.level": level,
676
+ "log.message": render(args)
677
+ });
678
+ }
679
+ /**
680
+ * Record a line on the running span, if a recording one is running. Returns
681
+ * whether it did, so the caller prints only when it did not.
682
+ */
683
+ function recordActive(level, args) {
684
+ const span = trace.getActiveSpan();
685
+ if (!span?.isRecording()) return false;
686
+ record(span, level, args);
687
+ return true;
688
+ }
689
+ globalThis[Symbol.for("brickkit.logs.record")] = recordActive;
690
+ /**
691
+ * A logger for actions, tools, and endpoints. While a dashboard is on, a line
692
+ * logged while a request is being traced becomes an event on the span that is
693
+ * running, which the dashboard shows with that request (and in its Logs tab);
694
+ * it is not printed. Everywhere else, and for lines logged outside a request,
695
+ * it prints to the console, prefixed by `prefix`: one for all levels, or one
696
+ * per level.
697
+ *
698
+ * Capturing costs one context lookup and a span event per line, and nothing
699
+ * is serialized for the dashboard until the span ends, so it is cheaper than
700
+ * a console write. Lines are cut at 4,000 characters and a span keeps 100.
701
+ */
702
+ function createLogger(prefix) {
703
+ const level = (name, print) => (...args) => {
704
+ if (globalThis[CAPTURE] === true && recordActive(name, args)) return;
705
+ print(typeof prefix === "string" ? prefix : prefix[name], ...args);
706
+ };
707
+ return {
708
+ info: level("info", (...args) => console.log(...args)),
709
+ warn: level("warn", (...args) => console.warn(...args)),
710
+ error: level("error", (...args) => console.error(...args)),
711
+ debug: level("debug", (...args) => console.debug(...args))
712
+ };
713
+ }
714
+ /** The prefixes of loggers a caller did not supply. */
715
+ const DEFAULT_LOG_PREFIXES = {
716
+ info: "[INFO]",
717
+ warn: "[WARN]",
718
+ error: "[ERROR]",
719
+ debug: "[DEBUG]"
720
+ };
721
+ // src/action.ts
722
+ const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
723
+ const DEFAULT_REQUEST$2 = new Request("http://localhost");
724
+ let _defaultCtxSeq = 0;
725
+ const RESOLVED_SYMBOL = Symbol("resolved");
726
+ const standardErrorDefaults = {
727
+ BAD_REQUEST: {
728
+ status: 400,
729
+ message: "Bad Request"
730
+ },
731
+ UNAUTHORIZED: {
732
+ status: 401,
733
+ message: "Unauthorized"
734
+ },
735
+ FORBIDDEN: {
736
+ status: 403,
737
+ message: "Forbidden"
738
+ },
739
+ NOT_FOUND: {
740
+ status: 404,
741
+ message: "Not Found"
742
+ },
743
+ CONFLICT: {
744
+ status: 409,
745
+ message: "Conflict"
746
+ },
747
+ INTERNAL_SERVER_ERROR: {
748
+ status: 500,
749
+ message: "Internal Server Error"
750
+ }
751
+ };
752
+ function createDefaultContext(partial) {
753
+ if (partial?.[RESOLVED_SYMBOL]) return partial;
754
+ const seq = (++_defaultCtxSeq).toString(36);
755
+ return {
756
+ request: partial?.request ?? DEFAULT_REQUEST$2,
757
+ traceId: partial?.traceId || `tr_${seq}`,
758
+ requestId: partial?.requestId || `req_${seq}`,
759
+ db: partial?.db,
760
+ user: partial?.user,
761
+ logger: partial?.logger || defaultLogger,
762
+ services: partial?.services || {},
763
+ metadata: partial?.metadata || {},
764
+ ...partial,
765
+ [RESOLVED_SYMBOL]: true
766
+ };
767
+ }
768
+ /**
769
+ * The `error` helpers an action receives: one function per error code that
770
+ * throws an `ActionExecutionError` with that code and status. The standard HTTP
771
+ * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
772
+ * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
773
+ * them or replace one.
774
+ *
775
+ * @param errorsDef - The action's `errors`: for each code, its `message` and
776
+ * `status` (default 400).
777
+ * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,
778
+ * and always throw.
779
+ */
780
+ function buildErrorHelpers(errorsDef) {
781
+ const helpers = {};
782
+ for (const [code, def] of Object.entries(standardErrorDefaults)) helpers[code] = (overrideMessage, details, options) => {
783
+ const message = overrideMessage || def.message;
784
+ const status = def.status;
785
+ throw new ActionExecutionError(code, message, status, details, options);
786
+ };
787
+ if (errorsDef) for (const [code, def] of Object.entries(errorsDef)) helpers[code] = (overrideMessage, details, options) => {
788
+ const message = overrideMessage || def.message;
789
+ const status = def.status || 400;
790
+ throw new ActionExecutionError(code, message, status, details, options);
791
+ };
792
+ return helpers;
793
+ }
794
+ /** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */
795
+ function errorsOf(action) {
796
+ return action.config.errors ?? {};
797
+ }
798
+ function defineAction(config) {
799
+ const errorHelpers = buildErrorHelpers(config.errors);
800
+ const actionFn = (async (params) => {
801
+ return actionFn.execute(params);
802
+ });
803
+ Object.defineProperty(actionFn, "name", {
804
+ value: config.name,
805
+ configurable: true
806
+ });
807
+ actionFn.config = config;
808
+ actionFn.errorHelpers = errorHelpers;
809
+ actionFn.validateInput = (input) => {
810
+ return validateWithSchema(config.input, input);
811
+ };
812
+ actionFn.validateOutput = (output) => {
813
+ return validateWithSchema(actionFn.outputValidationSchema ?? config.output, output);
814
+ };
815
+ actionFn.run = async (input, ctx) => {
816
+ return actionFn.execute({
817
+ input,
818
+ ctx
819
+ });
820
+ };
821
+ actionFn.execute = async (params) => {
822
+ const boundService = actionFn.service;
823
+ const fullCtx = boundService?.resolveContext ? await boundService.resolveContext(params?.ctx) : createDefaultContext(params?.ctx);
824
+ try {
825
+ if (!fullCtx.db) {
826
+ const service = boundService ?? (actionFn.serviceName ? getGlobalRegistry().get(actionFn.serviceName) : void 0);
827
+ if (service?.getDb()) fullCtx.db = service.getDb();
828
+ }
829
+ if (config.input) {
830
+ const inputValidation = actionFn.validateInput(params?.input);
831
+ if (!inputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' input`, inputValidation.errors);
832
+ }
833
+ if (config.authorize) {
834
+ if (!await config.authorize({
835
+ user: fullCtx.user,
836
+ input: params?.input,
837
+ ctx: fullCtx
838
+ })) throw new ActionExecutionError(fullCtx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${config.name}'`, fullCtx.user == null ? 401 : 403);
839
+ }
840
+ const result = await config.execute({
841
+ input: params?.input,
842
+ ctx: fullCtx,
843
+ error: errorHelpers
844
+ });
845
+ if (actionFn.outputValidationSchema ?? config.output) {
846
+ const outputValidation = actionFn.validateOutput(result);
847
+ if (!outputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' output`, outputValidation.errors, 500);
848
+ }
849
+ return result;
850
+ } catch (err) {
851
+ throw normalizeActionError(err, fullCtx);
852
+ }
853
+ };
854
+ return actionFn;
855
+ }
856
+ // src/plugin.ts
857
+ const pluginKind = Symbol.for("brickkit.plugin.kind");
858
+ /** `definePlugin` instances install on either host; see `define-plugin.ts`. */
859
+ const pluginFinish = Symbol.for("brickkit.plugin.finish");
860
+ /**
861
+ * Define a plugin that installs onto a service with `service.use(plugin)`. Its
862
+ * `setup` receives the service and a `routes` registrar for adding actions and
863
+ * raw HTTP endpoints, and returns the typed API that `service.use` hands back.
864
+ *
865
+ * @param definition - A unique `name`, optional `routes` controls that let the
866
+ * user move or switch off the plugin's routes, and `setup`, which must be
867
+ * synchronous.
868
+ * @returns The plugin descriptor, frozen.
869
+ * @throws When the name is empty or has surrounding whitespace.
870
+ * @example
871
+ * import { defineServicePlugin, t } from "@brickkit/core";
872
+ *
873
+ * export const greeting = (salutation = "Hello") =>
874
+ * defineServicePlugin({
875
+ * name: "example/greeting",
876
+ * setup({ routes }) {
877
+ * const hello = routes.action({
878
+ * name: "hello",
879
+ * input: t.Object({ name: t.String() }),
880
+ * output: t.String(),
881
+ * execute: ({ input }) => `${salutation}, ${input.name}!`,
882
+ * });
883
+ * return { hello };
884
+ * },
885
+ * });
886
+ *
887
+ * const api = greeterService.use(greeting("Welcome"));
888
+ * await api.hello({ input: { name: "Ada" } });
889
+ */
890
+ function defineServicePlugin(definition) {
891
+ validateName(definition.name);
892
+ return Object.freeze({
893
+ ...definition,
894
+ routes: copyControls(definition.routes),
895
+ [pluginKind]: "service"
896
+ });
897
+ }
898
+ /**
899
+ * Define a plugin that installs onto a resource (a table and its entity) with
900
+ * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
901
+ * `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and
902
+ * returns the typed API that `resource.use` hands back. `crud` is built this way.
903
+ *
904
+ * @param definition - A unique `name`, optional `routes` controls, and `setup`,
905
+ * which must be synchronous.
906
+ * @returns The plugin descriptor, frozen.
907
+ * @throws When the name is empty or has surrounding whitespace.
908
+ */
909
+ function defineResourcePlugin(definition) {
910
+ validateName(definition.name);
911
+ return Object.freeze({
912
+ ...definition,
913
+ routes: copyControls(definition.routes),
914
+ [pluginKind]: "resource"
915
+ });
916
+ }
917
+ function validateName(name) {
918
+ if (!name || name.trim() !== name) throw new Error("Plugin and route names must be nonempty and have no surrounding whitespace");
919
+ }
920
+ function validatePath(path) {
921
+ if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("//") || path.split("/").some((part) => part === "." || part === "..")) throw new Error(`Invalid plugin route path '${path}'`);
922
+ }
923
+ function copyControls(controls) {
924
+ if (controls === void 0 || controls === false) return controls;
925
+ const result = Object.create(null);
926
+ for (const [name, value] of Object.entries(controls)) {
927
+ validateName(name);
928
+ if (value === false) {
929
+ result[name] = false;
930
+ continue;
931
+ }
932
+ if (value.path !== void 0) validatePath(value.path);
933
+ if (value.scope !== void 0 && ![
934
+ "app",
935
+ "service",
936
+ "resource"
937
+ ].includes(value.scope)) throw new Error(`Invalid plugin route scope '${value.scope}'`);
938
+ result[name] = Object.freeze({ ...value });
939
+ }
940
+ return Object.freeze(result);
941
+ }
942
+ const states = /* @__PURE__ */ new WeakMap();
943
+ const actionBindings = /* @__PURE__ */ new WeakMap();
944
+ /**
945
+ * Cross-copy binding protocol. Bundler SSR runtimes (Vite, Nitro, Vitest)
946
+ * may load a second copy of core that owns a different WeakMap, while the
947
+ * action objects themselves cross the boundary by reference. The binding
948
+ * travels on the action under a process-global symbol so route lookups
949
+ * (including disabled-route suppression) keep working there.
950
+ */
951
+ const actionBindingKey = Symbol.for("brickkit.plugin.actionBinding");
952
+ function stateOf(service) {
953
+ let state = states.get(service);
954
+ if (!state) {
955
+ state = {
956
+ hosts: /* @__PURE__ */ new Map(),
957
+ actions: /* @__PURE__ */ new Map(),
958
+ endpoints: []
959
+ };
960
+ states.set(service, state);
961
+ }
962
+ return state;
963
+ }
964
+ function isInstallingPlugin(service) {
965
+ return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
966
+ }
967
+ function pathOf(binding, prefix) {
968
+ return joinRoute(binding.scope === "app" ? ownerPath(prefix) : ownerPath(prefix, binding.service.name, binding.scope === "resource" ? binding.resource.name : void 0), binding.path);
969
+ }
970
+ /**
971
+ * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
972
+ * compiler, and the typed client.
973
+ *
974
+ * @param action - An action.
975
+ * @param prefix - The application's route prefix (default `/api`).
976
+ * @returns `undefined` when no plugin bound the action (it uses its own route),
977
+ * `false` when the plugin's route was switched off, otherwise the route's
978
+ * `path`, `method`, the `clientPath` the typed client uses, and the owning
979
+ * `plugin` and `resource`.
980
+ */
981
+ function getPluginActionRoute(action, prefix = "/api") {
982
+ const binding = action[actionBindingKey] ?? actionBindings.get(action);
983
+ if (!binding) return void 0;
984
+ if (!binding.enabled) return false;
985
+ return {
986
+ path: pathOf(binding, prefix),
987
+ method: binding.method,
988
+ clientPath: binding.clientPath,
989
+ plugin: binding.plugin,
990
+ resource: binding.resource?.name
991
+ };
992
+ }
993
+ /**
994
+ * The raw HTTP endpoints plugins registered on a service, ready to mount on the
995
+ * application. Each handler resolves the service's context before it runs.
996
+ *
997
+ * @param service - The service plugins were installed on.
998
+ * @param prefix - The application's route prefix (default `/api`).
999
+ * @returns The enabled endpoints: `path`, `method`, `handler`, and the
1000
+ * `summary`, `description`, and `tags` for OpenAPI.
1001
+ */
1002
+ function getPluginEndpoints(service, prefix = "/api") {
1003
+ return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
1004
+ path: pathOf(binding, prefix),
1005
+ method: binding.method,
1006
+ service,
1007
+ plugin: binding.plugin,
1008
+ summary: binding.summary,
1009
+ description: binding.description,
1010
+ tags: binding.tags,
1011
+ handler: async (context) => binding.handler({
1012
+ ...context,
1013
+ ctx: await service.resolveContext({ request: context.request })
1014
+ })
1015
+ }));
1016
+ }
1017
+ /** Descriptor identity is scoped to the service or resource installation host. */
1018
+ function installPlugin(service, resource, descriptor) {
1019
+ if (service.isBuilt) throw new Error("Plugins must be installed before service build");
1020
+ if (descriptor[pluginKind] !== (resource ? "resource" : "service") && descriptor[pluginKind] !== "plugin") throw new Error("Plugin does not support this installation host");
1021
+ const state = stateOf(service);
1022
+ const host = resource ?? service;
1023
+ const existing = state.hosts.get(host)?.get(descriptor.name);
1024
+ if (existing) {
1025
+ if (existing.status === "installing") throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);
1026
+ if (existing.descriptor !== descriptor) throw new Error(`Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`);
1027
+ return resource ?? existing.api;
1028
+ }
1029
+ const snapshots = {
1030
+ actions: new Map(service.actions),
1031
+ tools: new Map(service.tools),
1032
+ tables: new Map(service.tables),
1033
+ resources: new Map(service.resources),
1034
+ preparations: new Map(service.preparations),
1035
+ hosts: new Map([...state.hosts].map(([key, installations]) => [key, new Map(installations)])),
1036
+ bindings: new Map(state.actions),
1037
+ endpoints: [...state.endpoints],
1038
+ properties: new Map([...service.resources.values()].map((item) => [item, Object.getOwnPropertyDescriptors(item)]))
1039
+ };
1040
+ const installations = state.hosts.get(host) ?? /* @__PURE__ */ new Map();
1041
+ state.hosts.set(host, installations);
1042
+ installations.set(descriptor.name, {
1043
+ descriptor,
1044
+ status: "installing"
1045
+ });
1046
+ const names = /* @__PURE__ */ new Set();
1047
+ const ownedActions = /* @__PURE__ */ new Set();
1048
+ let active = true;
1049
+ const bindingFor = (config) => {
1050
+ if (!active || service.isBuilt) throw new Error("Plugin routes can only be registered during setup");
1051
+ validateName(config.name);
1052
+ validatePath(config.path);
1053
+ if (names.has(config.name)) throw new Error(`Duplicate plugin route name '${config.name}'`);
1054
+ names.add(config.name);
1055
+ const control = descriptor.routes === false ? false : descriptor.routes?.[config.name];
1056
+ const scope = control && control.scope || config.scope || (resource ? "resource" : "service");
1057
+ if (scope === "resource" && !resource) throw new Error("Service plugin routes cannot use resource scope");
1058
+ if (![
1059
+ "app",
1060
+ "service",
1061
+ "resource"
1062
+ ].includes(scope)) throw new Error(`Invalid plugin route scope '${scope}'`);
1063
+ if (![
1064
+ "GET",
1065
+ "POST",
1066
+ "PUT",
1067
+ "PATCH",
1068
+ "DELETE"
1069
+ ].includes(config.method)) throw new Error(`Invalid plugin route method '${config.method}'`);
1070
+ const path = control && control.path || config.path;
1071
+ validatePath(path);
1072
+ return {
1073
+ service,
1074
+ resource,
1075
+ plugin: descriptor.name,
1076
+ path,
1077
+ method: config.method,
1078
+ scope,
1079
+ enabled: control !== false
1080
+ };
1081
+ };
1082
+ const routes = {
1083
+ action(config) {
1084
+ const binding = bindingFor(config);
1085
+ for (const match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) if (!config.input?.properties || !Object.hasOwn(config.input.properties, match[1])) throw new Error(`Plugin action path parameter '${match[1]}' must be declared in its input schema`);
1086
+ const name = `${resource ? `${resource.name}.` : ""}${config.name}`;
1087
+ if (service.actions.has(name)) throw new Error(`Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`);
1088
+ const { scope: _scope, ...actionConfig } = config;
1089
+ const action = defineAction({
1090
+ ...actionConfig,
1091
+ name
1092
+ });
1093
+ action.plugin = descriptor.name;
1094
+ if (resource) action.resource = resource.name;
1095
+ service.action(action);
1096
+ ownedActions.add(action);
1097
+ state.actions.set(action, binding);
1098
+ actionBindings.set(action, binding);
1099
+ action[actionBindingKey] = binding;
1100
+ return action;
1101
+ },
1102
+ endpoint(config) {
1103
+ const binding = bindingFor(config);
1104
+ state.endpoints.push({
1105
+ ...binding,
1106
+ handler: config.handler,
1107
+ summary: config.summary,
1108
+ description: config.description,
1109
+ tags: config.tags
1110
+ });
1111
+ }
1112
+ };
1113
+ try {
1114
+ const api = resource ? descriptor.setup({
1115
+ service,
1116
+ resource,
1117
+ routes
1118
+ }) : descriptor.setup({
1119
+ service,
1120
+ routes
1121
+ });
1122
+ if (api && typeof api === "object" && "then" in api) throw new Error("Plugin setup must be synchronous");
1123
+ if (descriptor.routes && Object.keys(descriptor.routes).some((name) => !names.has(name))) throw new Error(`Plugin '${descriptor.name}' has an override for an unknown route`);
1124
+ const walk = (value, path, ancestors) => {
1125
+ if (typeof value === "function") {
1126
+ const binding = state.actions.get(value);
1127
+ if (binding && ownedActions.has(value)) {
1128
+ if (binding.clientPath) throw new Error("Plugin actions must have one returned API path");
1129
+ binding.clientPath = resource ? [
1130
+ service.name,
1131
+ resource.name,
1132
+ ...path
1133
+ ] : [service.name, ...path];
1134
+ }
1135
+ } else if (value && typeof value === "object" && !ancestors.has(value)) {
1136
+ const next = new Set(ancestors).add(value);
1137
+ for (const [key, child] of Object.entries(value)) walk(child, [...path, key], next);
1138
+ }
1139
+ };
1140
+ walk(api, [], /* @__PURE__ */ new Set());
1141
+ if (resource) {
1142
+ if (!api || typeof api !== "object" || Array.isArray(api)) throw new Error("Resource plugins must return named API contributions");
1143
+ for (const key of Object.keys(api)) if (key in resource || [
1144
+ "__proto__",
1145
+ "prototype",
1146
+ "constructor"
1147
+ ].includes(key)) throw new Error(`Resource plugin contribution '${key}' collides with an existing property`);
1148
+ Object.assign(resource, api);
1149
+ }
1150
+ state.hosts.get(host).set(descriptor.name, {
1151
+ descriptor,
1152
+ status: "installed",
1153
+ api
1154
+ });
1155
+ finish(descriptor, true);
1156
+ getGlobalRegistry().touch();
1157
+ return resource ?? api;
1158
+ } catch (error) {
1159
+ finish(descriptor, false);
1160
+ for (const action of state.actions.keys()) if (!snapshots.bindings.has(action)) {
1161
+ actionBindings.delete(action);
1162
+ delete action[actionBindingKey];
1163
+ }
1164
+ restoreMap(service.actions, snapshots.actions);
1165
+ restoreMap(service.tools, snapshots.tools);
1166
+ restoreMap(service.tables, snapshots.tables);
1167
+ restoreMap(service.resources, snapshots.resources);
1168
+ restoreMap(service.preparations, snapshots.preparations);
1169
+ state.hosts = snapshots.hosts;
1170
+ state.actions = snapshots.bindings;
1171
+ state.endpoints = snapshots.endpoints;
1172
+ for (const [item, properties] of snapshots.properties) {
1173
+ for (const key of Reflect.ownKeys(item)) if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);
1174
+ Object.defineProperties(item, properties);
1175
+ }
1176
+ getGlobalRegistry().touch();
1177
+ throw error;
1178
+ } finally {
1179
+ active = false;
1180
+ }
1181
+ }
1182
+ function finish(descriptor, installed) {
1183
+ descriptor[pluginFinish]?.(installed);
1184
+ }
1185
+ /** Whether a plugin named `name` is installed on `host` (the service or a resource). */
1186
+ function hasPlugin(service, host, name) {
1187
+ return states.get(service)?.hosts.get(host)?.get(name)?.status === "installed";
1188
+ }
1189
+ /** Every descriptor installed on the service or its resources, in install order per host. */
1190
+ function installedPlugins(service) {
1191
+ return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
1192
+ }
1193
+ function restoreMap(target, snapshot) {
1194
+ target.clear();
1195
+ for (const [key, value] of snapshot) target.set(key, value);
1196
+ }
1197
+ // src/deps.ts
1198
+ /**
1199
+ * Declare a dependency a service needs, without creating it. The app provides
1200
+ * the value with `brick({ deps })`, and the service's code reads it as
1201
+ * `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).
1202
+ *
1203
+ * @returns A slot typed as `T`. It holds nothing at runtime.
1204
+ * @example
1205
+ * import { defineService, port } from "@brickkit/core";
1206
+ *
1207
+ * export const orders = defineService("orders", {
1208
+ * database,
1209
+ * deps: { carrier: port<Carrier>() },
1210
+ * });
1211
+ *
1212
+ * // app.ts
1213
+ * export default brick({ services: [orders], deps: { carrier: createCarrier() } });
1214
+ */
1215
+ function port() {
1216
+ return Object.freeze({});
1217
+ }
1218
+ /** Where a socket a plugin declared keeps the plugin's deps; global so a second core copy finds it. */
1219
+ const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
1220
+ const running = new AsyncLocalStorage();
1221
+ /** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
1222
+ function runWithDeps(deps, fn) {
1223
+ return running.run(deps, fn);
1224
+ }
1225
+ function useDeps() {
1226
+ const deps = running.getStore();
1227
+ if (!deps) throw new Error("useDeps() was called outside a Brick app: call it from a listener or a workflow step (actions read ctx.deps).");
1228
+ return deps;
1229
+ }
1230
+ /**
1231
+ * Check `brick({ deps })` against what the services declare, and give each
1232
+ * service the values of its own ports.
1233
+ *
1234
+ * @throws When a service declares a dep the app does not provide, or the app
1235
+ * provides one that no service declares.
1236
+ */
1237
+ function bindDeps(services, provided = {}) {
1238
+ const declared = /* @__PURE__ */ new Set();
1239
+ for (const service of services) {
1240
+ const own = {};
1241
+ for (const name of Object.keys(service.options.deps ?? {})) {
1242
+ if (!Object.hasOwn(provided, name) || provided[name] === void 0) throw new Error(`Brick: service "${service.name}" declares dep "${name}", but brick({ deps }) does not provide it`);
1243
+ declared.add(name);
1244
+ own[name] = provided[name];
1245
+ }
1246
+ service.setDeps?.(Object.freeze(own));
1247
+ }
1248
+ for (const name of Object.keys(provided)) if (!declared.has(name)) throw new Error(`Brick: brick({ deps }) provides "${name}", but no service declares it (services: ${services.map((service) => service.name).join(", ") || "none"})`);
1249
+ }
1250
+ // src/define-plugin.ts
1251
+ let runningVersion;
1252
+ /** The version of this @brickkit/core, read from its package.json; `""` when unknown. */
1253
+ function brickVersion() {
1254
+ if (runningVersion !== void 0) return runningVersion;
1255
+ for (const relative of ["../package.json", "../../package.json"]) try {
1256
+ const json = JSON.parse(readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8"));
1257
+ if (json.name === "@brickkit/core") return runningVersion = json.version;
1258
+ } catch {}
1259
+ return runningVersion = "";
1260
+ }
1261
+ function parseVersion(version) {
1262
+ const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[-+]/)[0].split(".").map(Number);
1263
+ return [
1264
+ major,
1265
+ minor,
1266
+ patch
1267
+ ];
1268
+ }
1269
+ function compare(a, b) {
1270
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
1271
+ }
1272
+ /**
1273
+ * Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,
1274
+ * `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.
1275
+ */
1276
+ function satisfiesRange(version, range) {
1277
+ const current = parseVersion(version);
1278
+ return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
1279
+ const match = /^(\^|~|>=|<=|>|<|=)?v?([\dx*]+(?:\.[\dx*]+){0,2})?/i.exec(comparator);
1280
+ const operator = match?.[1] ?? "";
1281
+ const parts = (match?.[2] ?? "*").split(".");
1282
+ const wild = parts.findIndex((part) => /^[x*]$/i.test(part));
1283
+ const given = wild === -1 ? parts.length : wild;
1284
+ const low = parseVersion(parts.slice(0, given).join(".") || "0");
1285
+ if (given === 0) return true;
1286
+ const cmp = compare(current, low);
1287
+ if (operator === ">=") return cmp >= 0;
1288
+ if (operator === ">") return cmp > 0;
1289
+ if (operator === "<") return cmp < 0;
1290
+ if (operator === "<=") return cmp <= 0;
1291
+ let high;
1292
+ if (operator === "^") high = low[0] > 0 || given === 1 ? [
1293
+ low[0] + 1,
1294
+ 0,
1295
+ 0
1296
+ ] : low[1] > 0 || given === 2 ? [
1297
+ 0,
1298
+ low[1] + 1,
1299
+ 0
1300
+ ] : [
1301
+ 0,
1302
+ 0,
1303
+ low[2] + 1
1304
+ ];
1305
+ else if (operator === "~" || given < 3) high = given === 1 ? [
1306
+ low[0] + 1,
1307
+ 0,
1308
+ 0
1309
+ ] : [
1310
+ low[0],
1311
+ low[1] + 1,
1312
+ 0
1313
+ ];
1314
+ else return cmp === 0;
1315
+ return cmp >= 0 && compare(current, high) < 0;
1316
+ }));
1317
+ }
1318
+ const OWNER = Symbol.for("brickkit.plugin.owner");
1319
+ /** The plugin that owns a table, for tables a `definePlugin` contributed. */
1320
+ function pluginOwner(table) {
1321
+ return table && typeof table === "object" ? table[OWNER] : void 0;
1322
+ }
1323
+ const sqliteBuilders = {
1324
+ /** A table. Its name gets the plugin's prefix (`page_comments`). */
1325
+ table: (name, columns) => sqliteTable(name, columns),
1326
+ text: (name) => text(name),
1327
+ integer: (name) => integer(name, { mode: "number" }),
1328
+ real: (name) => real(name),
1329
+ boolean: (name) => integer(name, { mode: "boolean" }),
1330
+ /** A `Date`, stored as epoch milliseconds or `timestamptz`. */
1331
+ timestamp: (name) => integer(name, { mode: "timestamp_ms" }),
1332
+ json: (name) => text(name, { mode: "json" })
1333
+ };
1334
+ function builders(engine, tableName) {
1335
+ if (engine === "postgres") return {
1336
+ engine,
1337
+ table: (name, columns) => pgTable(tableName(name), columns),
1338
+ text: (name) => text$1(name),
1339
+ integer: (name) => integer$1(name),
1340
+ real: (name) => doublePrecision(name),
1341
+ boolean: (name) => boolean(name),
1342
+ timestamp: (name) => timestamp(name, {
1343
+ mode: "date",
1344
+ withTimezone: true
1345
+ }),
1346
+ json: (name) => jsonb(name)
1347
+ };
1348
+ return {
1349
+ ...sqliteBuilders,
1350
+ engine,
1351
+ table: (name, columns) => sqliteTable(tableName(name), columns)
1352
+ };
1353
+ }
1354
+ /** Where `hooks.*` stores a plugin's hooks; `@brickkit/crud` runs them. */
1355
+ const HOST_HOOKS = Symbol.for("brickkit.plugin.hooks");
1356
+ const HOOK_NAMES = [
1357
+ "beforeCreate",
1358
+ "afterCreate",
1359
+ "beforeUpdate",
1360
+ "afterUpdate",
1361
+ "beforeDelete",
1362
+ "afterDelete",
1363
+ "afterCommit"
1364
+ ];
1365
+ const INTERNALS = Symbol.for("brickkit.plugin.internals");
1366
+ let installCount = 0;
1367
+ const toWords = (name) => (name.split("/").pop() ?? name).replace(/^brick-/, "").replace(/-plugin$/, "").split(/[^a-zA-Z0-9]+/).filter(Boolean);
1368
+ const snake = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
1369
+ /**
1370
+ * Define a plugin: a manifest Brick checks, plus the capabilities the plugin
1371
+ * brings. Install its instances with `resource.use()`, `service.use()` or
1372
+ * `brick({ plugins })`; scope comes from where it is installed.
1373
+ *
1374
+ * @param manifest - `name`, `brick` (semver range), `requires`, `options`
1375
+ * (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`
1376
+ * parts, and a `dashboard` extension.
1377
+ * @returns A factory: `comments({ maxLength: 500 })` validates the options and
1378
+ * the Brick version and returns an instance to install.
1379
+ * @throws From the factory, when the running Brick is outside `brick` or an
1380
+ * option is invalid; when installed, when a required plugin is missing or the
1381
+ * host does not suit the plugin.
1382
+ * @example
1383
+ * export const audit = definePlugin({
1384
+ * name: "@acme/brick-audit",
1385
+ * brick: "^0.11.0",
1386
+ * requires: ["@brickkit/crud"],
1387
+ * options: t.Object({ table: t.String({ default: "audit" }) }),
1388
+ * tables: ({ table, text, timestamp }) => ({
1389
+ * log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
1390
+ * }),
1391
+ * resource: ({ tables, hooks }) => {
1392
+ * hooks.afterCreate(({ row, tx }) =>
1393
+ * tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
1394
+ * return {};
1395
+ * },
1396
+ * });
1397
+ *
1398
+ * page.use(audit());
1399
+ */
1400
+ function definePlugin(manifest) {
1401
+ const { name } = manifest;
1402
+ if (!name || name.trim() !== name) throw new Error("Plugin names must be nonempty and have no surrounding whitespace");
1403
+ if (!manifest.resource && !manifest.service && !manifest.app) throw new Error(`Plugin "${name}" needs a resource, service or app part to install`);
1404
+ for (const key of Object.keys(manifest.events ?? {})) if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key)) throw new Error(`Event "${key}" of plugin "${name}" must be a plain name such as added`);
1405
+ const site = definitionSite()?.replace(/:\d+$/, "");
1406
+ const dashboard = manifest.dashboard === void 0 ? void 0 : manifest.dashboard.startsWith("file:") ? fileURLToPath(manifest.dashboard) : isAbsolute(manifest.dashboard) || !site ? resolve(manifest.dashboard) : resolve(dirname(site), manifest.dashboard);
1407
+ const info = Object.freeze({
1408
+ name,
1409
+ description: manifest.description,
1410
+ brick: manifest.brick,
1411
+ requires: Object.freeze([...manifest.requires ?? []]),
1412
+ options: manifest.options,
1413
+ secrets: Object.freeze(Object.values(manifest.secrets ?? {}).map((secret) => secret.name)),
1414
+ deps: Object.freeze(Object.keys(manifest.deps ?? {})),
1415
+ capabilities: Object.freeze([
1416
+ "tables",
1417
+ "events",
1418
+ "resource",
1419
+ "service",
1420
+ "app",
1421
+ "dashboard"
1422
+ ].filter((key) => manifest[key] !== void 0))
1423
+ });
1424
+ const words = toWords(name);
1425
+ const eventSpace = words.map((word, index) => index ? word[0].toUpperCase() + word.slice(1) : word).join("");
1426
+ const tableSpace = snake(words.join("_"));
1427
+ if (!eventSpace) throw new Error(`Plugin "${name}" needs letters or digits in its name`);
1428
+ const factory = (input = {}, install = {}) => {
1429
+ const version = brickVersion();
1430
+ if (manifest.brick && version && !satisfiesRange(version, manifest.brick)) throw new Error(`${name} supports Brick ${manifest.brick}; this app runs ${version}`);
1431
+ const options = checkOptions(name, manifest.options, input);
1432
+ const deps = checkDeps(name, eventSpace, manifest.deps, install.deps);
1433
+ const secrets = manifest.secrets ?? {};
1434
+ const internals = {
1435
+ manifest,
1436
+ options,
1437
+ deps,
1438
+ install,
1439
+ dashboard,
1440
+ installs: []
1441
+ };
1442
+ const pending = [];
1443
+ const setup = (context) => {
1444
+ const { service, resource } = context;
1445
+ const host = resource ?? service;
1446
+ const where = resource ? `resource "${resource.name}"` : `service "${service.name}"`;
1447
+ const part = resource ? manifest.resource : manifest.service;
1448
+ if (!part) throw new Error(`${name} cannot be installed on a ${resource ? "resource" : "service"}; ${manifest.resource ? "use resource.use()" : manifest.service ? "use service.use()" : "add it to brick({ plugins })"}`);
1449
+ for (const required of manifest.requires ?? []) if (!hasPlugin(service, host, required)) throw new Error(`${name} requires ${required}, installed on ${where} before it`);
1450
+ let tables = {};
1451
+ if (manifest.tables) {
1452
+ const database = service.getDatabaseHandle?.();
1453
+ if (!database) throw new Error(`${name} owns tables, so service "${service.name}" needs a database`);
1454
+ const prefix = install.prefix ?? `${snake(resource?.name ?? service.name)}_`;
1455
+ tables = manifest.tables(builders(database.engine, (table) => install.prefix !== void 0 || table === tableSpace ? `${prefix}${table}` : `${prefix}${tableSpace}_${table}`));
1456
+ const taken = new Set([...service.tables.values(), ...Object.values(database.tables)].map((table) => getTableName(table)));
1457
+ for (const table of Object.values(tables)) {
1458
+ const tableName = getTableName(table);
1459
+ if (taken.has(tableName)) throw new Error(`${name} table "${tableName}" clashes with a table service "${service.name}" already has; install it with another prefix`);
1460
+ taken.add(tableName);
1461
+ Object.defineProperty(table, OWNER, { value: name });
1462
+ service.registerTable(table);
1463
+ }
1464
+ }
1465
+ const catalog = service.events;
1466
+ const events = {};
1467
+ for (const [key, schema] of Object.entries(manifest.events ?? {})) {
1468
+ const existing = catalog[`${eventSpace}.${key}`];
1469
+ if (existing && existing.plugin !== name) throw new Error(`${name} event "${eventSpace}.${key}" is already in the catalog of service "${service.name}"`);
1470
+ events[key] = existing ?? Object.freeze({
1471
+ name: `${service.name}.${eventSpace}.${key}`,
1472
+ service: service.name,
1473
+ schema,
1474
+ plugin: name
1475
+ });
1476
+ }
1477
+ const added = {};
1478
+ const hooks = Object.fromEntries(HOOK_NAMES.map((hook) => [hook, (fn) => {
1479
+ if (typeof fn !== "function") throw new Error(`${name}: hooks.${hook} needs a function`);
1480
+ (added[hook] ??= []).push((args) => fn({
1481
+ ...args,
1482
+ ctx: {
1483
+ ...args.ctx,
1484
+ deps
1485
+ }
1486
+ }));
1487
+ }]));
1488
+ const routes = {
1489
+ action: (config) => context.routes.action(config),
1490
+ endpoint: (config) => context.routes.endpoint({
1491
+ ...config,
1492
+ handler: (args) => config.handler({
1493
+ ...args,
1494
+ ctx: {
1495
+ ...args.ctx,
1496
+ deps
1497
+ }
1498
+ })
1499
+ })
1500
+ };
1501
+ const before = /* @__PURE__ */ new Set([
1502
+ ...service.actions.values(),
1503
+ ...service.tools.values(),
1504
+ ...service.listSockets()
1505
+ ]);
1506
+ const started = bindings;
1507
+ const api = part({
1508
+ options,
1509
+ secrets,
1510
+ tables,
1511
+ events,
1512
+ deps,
1513
+ service,
1514
+ resource,
1515
+ routes,
1516
+ hooks
1517
+ });
1518
+ if (api && typeof api.then === "function") throw new Error("Plugin setup must be synchronous");
1519
+ for (const action of [...service.actions.values(), ...service.tools.values()]) if (!before.has(action)) bindPluginDeps(name, action, deps, started);
1520
+ for (const socket of service.listSockets()) if (!before.has(socket)) socket[PLUGIN_DEPS] ??= deps;
1521
+ pending.push(() => {
1522
+ const database = service.getDatabaseHandle?.();
1523
+ for (const table of Object.values(tables)) database?.addTable?.(getTableName(table), table);
1524
+ if (Object.keys(events).length) service.events = Object.freeze({
1525
+ ...catalog,
1526
+ ...Object.fromEntries(Object.entries(events).map(([key, ref]) => [`${eventSpace}.${key}`, ref]))
1527
+ });
1528
+ const store = host[HOST_HOOKS] ??= {};
1529
+ for (const [hook, fns] of Object.entries(added)) (store[hook] ??= []).push(...fns);
1530
+ internals.installs.push({
1531
+ scope: resource ? "resource" : "service",
1532
+ service: service.name,
1533
+ resource: resource?.name
1534
+ });
1535
+ internals.order ??= ++installCount;
1536
+ });
1537
+ return resource ? api ?? {} : api;
1538
+ };
1539
+ return Object.freeze({
1540
+ [Symbol.for("brickkit.plugin.kind")]: "plugin",
1541
+ name,
1542
+ info,
1543
+ setup,
1544
+ [INTERNALS]: internals,
1545
+ [pluginFinish]: (installed) => {
1546
+ const commit = pending.pop();
1547
+ if (installed) commit?.();
1548
+ }
1549
+ });
1550
+ };
1551
+ return Object.assign(factory, { info });
1552
+ }
1553
+ /** Counts bindings, so a setup can tell a nested install's from an earlier one's. */
1554
+ let bindings = 0;
1555
+ /**
1556
+ * Give an action's `execute` and `authorize` the plugin's deps as `ctx.deps`.
1557
+ * The config is changed in place: every way an action runs (HTTP, compiled
1558
+ * routes, `action.run`, RPC) reads `config.execute` from it. A nested
1559
+ * definePlugin binds its own actions first, so they keep its deps.
1560
+ *
1561
+ * @throws When the action is already bound to another install's deps: one
1562
+ * action object shared by two installs could only run with one of them.
1563
+ */
1564
+ function bindPluginDeps(plugin, action, deps, started) {
1565
+ const config = action.config;
1566
+ if (!config) return;
1567
+ const bound = config[PLUGIN_DEPS];
1568
+ if (bound) {
1569
+ if (bound.deps === deps || bound.at > started) return;
1570
+ throw new Error(`${plugin}: action "${action.name}" is already bound to the deps of another install; create the action inside the setup so each install gets its own`);
1571
+ }
1572
+ config[PLUGIN_DEPS] = {
1573
+ deps,
1574
+ at: ++bindings
1575
+ };
1576
+ const { execute, authorize } = config;
1577
+ if (typeof execute === "function") config.execute = (args) => execute({
1578
+ ...args,
1579
+ ctx: {
1580
+ ...args.ctx,
1581
+ deps
1582
+ }
1583
+ });
1584
+ if (typeof authorize === "function") config.authorize = (args) => authorize({
1585
+ ...args,
1586
+ ctx: {
1587
+ ...args.ctx,
1588
+ deps
1589
+ }
1590
+ });
1591
+ }
1592
+ /** Check the deps passed at install against the ports the plugin declares. */
1593
+ function checkDeps(plugin, factory, ports, given = {}) {
1594
+ if (given === null || typeof given !== "object" || Array.isArray(given)) throw new Error(`${plugin}: deps must be an object`);
1595
+ const declared = Object.keys(ports ?? {});
1596
+ const provided = given;
1597
+ const extra = Object.keys(provided).filter((key) => !declared.includes(key));
1598
+ if (extra.length) throw new Error(`${plugin} does not declare ${extra.map((key) => `deps.${key}`).join(", ")}; ${declared.length ? `it takes ${declared.join(", ")}` : "it takes no deps"}`);
1599
+ const missing = declared.filter((key) => provided[key] === void 0);
1600
+ if (missing.length) throw new Error(`${plugin} needs ${missing.map((key) => `deps.${key}`).join(", ")}; pass it when installing: ${factory}(options, { deps: { ${missing.join(", ")} } })`);
1601
+ return Object.freeze(Object.fromEntries(declared.map((key) => [key, provided[key]])));
1602
+ }
1603
+ function checkOptions(plugin, schema, input) {
1604
+ if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error(`${plugin}: options must be an object`);
1605
+ if (!schema) {
1606
+ if (Object.keys(input).length) throw new Error(`${plugin} takes no options`);
1607
+ return {};
1608
+ }
1609
+ const value = Value.Default(schema, structuredClone(input));
1610
+ const result = validateWithSchema(schema, value);
1611
+ if (!result.success) {
1612
+ const [first] = result.errors;
1613
+ const option = first.path.replace(/^\//, "").replaceAll("/", ".");
1614
+ throw new Error(`${plugin}: option ${option ? `"${option}"` : ""} ${first.message}`.replace(/\s+/g, " "));
1615
+ }
1616
+ return value;
1617
+ }
1618
+ function isPluginInstance(value) {
1619
+ return typeof value === "object" && value !== null && INTERNALS in value;
1620
+ }
1621
+ function internalsOf(value) {
1622
+ return isPluginInstance(value) ? value[INTERNALS] ?? void 0 : void 0;
1623
+ }
1624
+ /**
1625
+ * What `brick()` does with plugins: install those given in `plugins` on the
1626
+ * app, run every plugin's `app` part in install order, and return the
1627
+ * lifecycle, middleware and listeners they contributed.
1628
+ */
1629
+ function setupAppPlugins(installedOnServices, appPlugins) {
1630
+ const instances = /* @__PURE__ */ new Set();
1631
+ for (const descriptor of installedOnServices) if (isPluginInstance(descriptor)) instances.add(descriptor);
1632
+ const ordered = [...instances].sort((a, b) => (internalsOf(a).order ?? 0) - (internalsOf(b).order ?? 0));
1633
+ const onApp = /* @__PURE__ */ new Set();
1634
+ for (const plugin of appPlugins) {
1635
+ const internals = internalsOf(plugin);
1636
+ if (!internals) throw new Error("brick({ plugins }) takes instances from definePlugin(), such as audit()");
1637
+ const { manifest } = internals;
1638
+ if (!manifest.app || manifest.tables || manifest.events) throw new Error(`${manifest.name} cannot be installed on the app; ${manifest.resource ? "use resource.use()" : "use service.use()"}`);
1639
+ for (const required of manifest.requires ?? []) if (!onApp.has(required)) throw new Error(`${manifest.name} requires ${required}, installed in brick({ plugins }) before it`);
1640
+ if (onApp.has(manifest.name)) throw new Error(`Plugin ${manifest.name} is installed on the app twice`);
1641
+ const installed = ordered.find((other) => internalsOf(other).manifest.name === manifest.name);
1642
+ if (installed) throw new Error(`Plugin ${manifest.name} is already installed with ${internalsOf(installed).installs.map((install) => install.scope === "resource" ? `${install.service}.${install.resource}.use()` : `${install.service}.use()`).join(", ")}, which runs its app part too; remove it from brick({ plugins })`);
1643
+ onApp.add(manifest.name);
1644
+ if (!internals.installs.some((item) => item.scope === "app")) internals.installs.push({ scope: "app" });
1645
+ ordered.push(plugin);
1646
+ }
1647
+ const lifecycles = [];
1648
+ const middleware = [];
1649
+ const listeners = [];
1650
+ const listed = [];
1651
+ for (const plugin of ordered) {
1652
+ const { manifest, options, deps, installs, dashboard } = internalsOf(plugin);
1653
+ for (const install of installs) listed.push(Object.freeze({
1654
+ name: manifest.name,
1655
+ ...manifest.brick ? { brick: manifest.brick } : {},
1656
+ ...install,
1657
+ ...dashboard ? { dashboard } : {}
1658
+ }));
1659
+ if (!manifest.app) continue;
1660
+ const lifecycle = {
1661
+ options,
1662
+ secrets: manifest.secrets ?? {},
1663
+ deps
1664
+ };
1665
+ const own = {
1666
+ start: [],
1667
+ stop: []
1668
+ };
1669
+ manifest.app({
1670
+ ...lifecycle,
1671
+ on(event, handler) {
1672
+ if (event !== "start" && event !== "stop") throw new Error(`${manifest.name}: on() takes "start" or "stop"`);
1673
+ own[event].push(handler);
1674
+ },
1675
+ middleware(handler) {
1676
+ middleware.push(handler);
1677
+ },
1678
+ listeners(...items) {
1679
+ listeners.push(...items.map((listener) => {
1680
+ const run = listener.run;
1681
+ if (!run) return {
1682
+ ...listener,
1683
+ [PLUGIN_DEPS]: deps
1684
+ };
1685
+ return {
1686
+ ...listener,
1687
+ run: (delivery) => runWithDeps(deps, () => run(delivery))
1688
+ };
1689
+ }));
1690
+ }
1691
+ });
1692
+ lifecycles.push({
1693
+ start: async () => {
1694
+ for (const handler of own.start) await handler(lifecycle);
1695
+ },
1696
+ stop: async () => {
1697
+ for (const handler of own.stop) await handler(lifecycle);
1698
+ }
1699
+ });
1700
+ }
1701
+ return {
1702
+ lifecycles,
1703
+ middleware,
1704
+ listeners,
1705
+ plugins: listed
1706
+ };
1707
+ }
1708
+ /**
1709
+ * Start in install order. Stop what started, in reverse order; a start that
1710
+ * fails stops those before it and rethrows.
1711
+ */
1712
+ function pluginLifecycle(lifecycles) {
1713
+ let started;
1714
+ const running = [];
1715
+ const stopAll = async () => {
1716
+ const errors = [];
1717
+ for (const item of running.splice(0).reverse()) try {
1718
+ await item.stop();
1719
+ } catch (error) {
1720
+ errors.push(error);
1721
+ }
1722
+ if (errors.length === 1) throw errors[0];
1723
+ if (errors.length) throw new AggregateError(errors, "Plugins failed to stop");
1724
+ };
1725
+ return {
1726
+ start() {
1727
+ return started ??= (async () => {
1728
+ for (const item of lifecycles) {
1729
+ try {
1730
+ await item.start();
1731
+ } catch (error) {
1732
+ await stopAll().catch(() => void 0);
1733
+ started = void 0;
1734
+ throw error;
1735
+ }
1736
+ running.push(item);
1737
+ }
1738
+ })();
1739
+ },
1740
+ async stop() {
1741
+ await started?.catch(() => void 0);
1742
+ started = void 0;
1743
+ await stopAll();
1744
+ }
1745
+ };
1746
+ }
1747
+ // src/compiler/runtime.ts
1748
+ const EMPTY_SERVICES$1 = Object.freeze({});
1749
+ const DEFAULT_REQUEST$1 = new Request("http://localhost");
1750
+ let sequence = 0;
1751
+ function isNonEmpty$1(value) {
1752
+ if (value == null) return false;
1753
+ for (const _ in value) return true;
1754
+ return false;
1755
+ }
1756
+ /** Retains Brick's existing source precedence and treatment of empty bodies. */
1757
+ function mergeInput(first, second, third) {
1758
+ const a = isNonEmpty$1(first), b = isNonEmpty$1(second), c = isNonEmpty$1(third);
1759
+ if (a && !b && !c) return first;
1760
+ if (b && !a && !c) return second;
1761
+ if (c && !a && !b) return third;
1762
+ if (a || b || c) return Object.assign({}, first, second, third);
1763
+ }
1764
+ const MAX_INPUT_DEPTH = 128;
1765
+ function inputTooDeep(value) {
1766
+ if (!value || typeof value !== "object") return false;
1767
+ const stack = [{
1768
+ node: value,
1769
+ depth: 0
1770
+ }];
1771
+ while (stack.length > 0) {
1772
+ const { node, depth } = stack.pop();
1773
+ if (depth > MAX_INPUT_DEPTH) return true;
1774
+ if (node && typeof node === "object") {
1775
+ const children = Array.isArray(node) ? node : Object.values(node);
1776
+ for (const child of children) if (child && typeof child === "object") stack.push({
1777
+ node: child,
1778
+ depth: depth + 1
1779
+ });
1780
+ }
1781
+ }
1782
+ return false;
1783
+ }
1784
+ function checkDepth(value, action) {
1785
+ if (!inputTooDeep(value)) return;
1786
+ throw new ValidationError(`Validation failed for action '${action}' input`, [{
1787
+ path: "",
1788
+ message: "Input exceeds maximum nesting depth"
1789
+ }]);
1790
+ }
1791
+ function validate(check, value, action, stage) {
1792
+ if (check.Check(value)) return;
1793
+ const errors = Array.from(check.Errors(value)).map((err) => ({
1794
+ path: err.path,
1795
+ message: err.message,
1796
+ value: err.value
1797
+ }));
1798
+ throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
1799
+ }
1800
+ function mapError(err, set, options) {
1801
+ const response = toErrorResponse(err, options);
1802
+ set.status = response.status;
1803
+ return response;
1804
+ }
1805
+ const compilerRuntime = Object.freeze({
1806
+ emptyServices: EMPTY_SERVICES$1,
1807
+ defaultRequest: DEFAULT_REQUEST$1,
1808
+ nextSequence: () => (++sequence).toString(36),
1809
+ mergeInput,
1810
+ checkDepth,
1811
+ validate,
1812
+ mapError,
1813
+ isThenable: (value) => value != null && typeof value.then === "function",
1814
+ deny: (action, user) => {
1815
+ throw new ActionExecutionError(user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${action}'`, user == null ? 401 : 403);
1816
+ }
1817
+ });
1818
+ // src/action-handler.ts
1819
+ let _srvSeq = 0;
1820
+ const EMPTY_SERVICES = Object.freeze({});
1821
+ const DEFAULT_REQUEST = new Request("http://localhost");
1822
+ function isNonEmpty(obj) {
1823
+ if (obj == null) return false;
1824
+ for (const _ in obj) return true;
1825
+ return false;
1826
+ }
1827
+ /**
1828
+ * Work out, once at startup, everything an action's route needs to answer a
1829
+ * request: where its input comes from (body, query, or path), the validators,
1830
+ * the authorization and execute functions, and its logger. Low level: `brick()`
1831
+ * does this for every route.
1832
+ *
1833
+ * @param service - The service the action belongs to.
1834
+ * @param action - The action.
1835
+ * @param routePath - The route's path.
1836
+ * @param method - The HTTP method (POST by default).
1837
+ * @returns The plan `executeCompiledRoute` runs.
1838
+ */
1839
+ function compileRoutePlan(service, action, routePath, method) {
1840
+ const actionName = action.name;
1841
+ const serviceName = service.name;
1842
+ const isGetLike = method === "GET" || actionName.startsWith("get") || actionName.endsWith(".get") || actionName.startsWith("list") || actionName.endsWith(".list") || actionName.startsWith("find") || actionName.startsWith("read");
1843
+ const inputSchema = action.config?.input;
1844
+ const outputSchema = action.config?.output;
1845
+ const hasInput = Boolean(inputSchema);
1846
+ const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
1847
+ const runtimeOutputSchema = action.outputValidationSchema ?? outputSchema;
1848
+ const outputChecker = runtimeOutputSchema ? getCompiledCheck(runtimeOutputSchema) : void 0;
1849
+ let coercions;
1850
+ if (inputSchema && typeof inputSchema.properties === "object") {
1851
+ const list = [];
1852
+ for (const [key, prop] of Object.entries(inputSchema.properties)) {
1853
+ const type = prop?.type;
1854
+ if (type === "number" || type === "integer") list.push({
1855
+ key,
1856
+ isNumber: true,
1857
+ isBoolean: false
1858
+ });
1859
+ else if (type === "boolean") list.push({
1860
+ key,
1861
+ isNumber: false,
1862
+ isBoolean: true
1863
+ });
1864
+ else if (type === "array") list.push({
1865
+ key,
1866
+ isNumber: false,
1867
+ isBoolean: false,
1868
+ isArray: true
1869
+ });
1870
+ }
1871
+ if (list.length > 0) coercions = list;
1872
+ }
1873
+ const contextHook = service.options?.context;
1874
+ const hasContextHook = typeof contextHook === "function";
1875
+ const authorize = action.config?.authorize;
1876
+ const hasAuthorize = typeof authorize === "function";
1877
+ const execute = action.config?.execute;
1878
+ const logger = createLogger(`[${serviceName}:${actionName}]`);
1879
+ const errorBuilder = action.errorHelpers ?? buildErrorHelpers(action.config?.errors);
1880
+ const cachedDb = service.getDb();
1881
+ return {
1882
+ service,
1883
+ action,
1884
+ actionName,
1885
+ serviceName,
1886
+ routePath,
1887
+ method,
1888
+ isGetLike,
1889
+ hasInput,
1890
+ hasContextHook,
1891
+ contextHook,
1892
+ hasAuthorize,
1893
+ authorize,
1894
+ execute,
1895
+ inputChecker,
1896
+ outputChecker,
1897
+ coercions,
1898
+ logger,
1899
+ errorBuilder,
1900
+ cachedDb
1901
+ };
1902
+ }
1903
+ /**
1904
+ * Answer one request for a compiled route: read the input, run the action, and
1905
+ * return its output or the error response, with the `x-trace-id` and
1906
+ * `x-request-id` headers set. Low level: `brick()` mounts this for every route.
1907
+ *
1908
+ * @param plan - From `compileRoutePlan`.
1909
+ * @param elysiaCtx - The Elysia request context: `params`, `body`, `query`,
1910
+ * `headers`, `request`, and `set`.
1911
+ * @returns The action's output, or an error envelope with the status set on `set`.
1912
+ */
1913
+ async function executeCompiledRoute(plan, elysiaCtx) {
1914
+ const { params, body, query, headers, request, set } = elysiaCtx;
1915
+ const seq = (++_srvSeq).toString(36);
1916
+ const traceId = headers && headers["x-trace-id"] || `tr_${seq}`;
1917
+ const requestId = headers && headers["x-request-id"] || `req_${seq}`;
1918
+ if (set?.headers) {
1919
+ set.headers["x-trace-id"] = traceId;
1920
+ set.headers["x-request-id"] = requestId;
1921
+ }
1922
+ let input;
1923
+ if (plan.hasInput) {
1924
+ let coercedQuery = query;
1925
+ if (query && plan.coercions && plan.coercions.length > 0) {
1926
+ coercedQuery = { ...query };
1927
+ for (let i = 0; i < plan.coercions.length; i++) {
1928
+ const c = plan.coercions[i];
1929
+ const val = query[c.key];
1930
+ if (val !== void 0) {
1931
+ if (c.isNumber) {
1932
+ const num = Number(val);
1933
+ if (!isNaN(num)) coercedQuery[c.key] = num;
1934
+ } else if (c.isArray) {
1935
+ const values = request ? new URL(request.url).searchParams.getAll(c.key) : [];
1936
+ coercedQuery[c.key] = values.length ? values : Array.isArray(val) ? val : [val];
1937
+ } else if (c.isBoolean) {
1938
+ if (val === "true" || val === "1") coercedQuery[c.key] = true;
1939
+ else if (val === "false" || val === "0") coercedQuery[c.key] = false;
1940
+ }
1941
+ }
1942
+ }
1943
+ }
1944
+ let coercedParams = params;
1945
+ if (params && plan.coercions) for (const c of plan.coercions) {
1946
+ if (!c.isNumber || typeof params[c.key] !== "string") continue;
1947
+ const num = Number(params[c.key]);
1948
+ if (isNaN(num)) continue;
1949
+ if (coercedParams === params) coercedParams = { ...params };
1950
+ coercedParams[c.key] = num;
1951
+ }
1952
+ const hasP = isNonEmpty(coercedParams);
1953
+ const hasB = isNonEmpty(body);
1954
+ const hasQ = isNonEmpty(coercedQuery);
1955
+ if (plan.isGetLike) {
1956
+ if (hasQ && !hasP && !hasB) input = coercedQuery;
1957
+ else if (hasP && !hasQ && !hasB) input = coercedParams;
1958
+ else if (hasB && !hasP && !hasQ) input = body;
1959
+ else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, coercedParams, body);
1960
+ } else if (hasB && !hasP && !hasQ) input = body;
1961
+ else if (hasP && !hasB && !hasQ) input = coercedParams;
1962
+ else if (hasQ && !hasP && !hasB) input = coercedQuery;
1963
+ else if (hasP || hasB || hasQ) input = Object.assign({}, coercedParams, body, coercedQuery);
1964
+ }
1965
+ const ctx = {
1966
+ request: request instanceof Request ? request : DEFAULT_REQUEST,
1967
+ traceId,
1968
+ requestId,
1969
+ db: plan.cachedDb ?? plan.service.getDb(),
1970
+ logger: plan.logger,
1971
+ services: EMPTY_SERVICES,
1972
+ deps: plan.service.deps ?? EMPTY_SERVICES,
1973
+ metadata: { headers },
1974
+ _resolved: true
1975
+ };
1976
+ try {
1977
+ if (plan.hasContextHook) {
1978
+ const extra = plan.contextHook(ctx);
1979
+ const resolved = extra instanceof Promise ? await extra : extra;
1980
+ if (resolved) Object.assign(ctx, resolved);
1981
+ }
1982
+ if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
1983
+ if (plan.hasInput && plan.inputChecker) {
1984
+ if (inputTooDeep(input)) throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, [{
1985
+ path: "",
1986
+ message: "Input exceeds maximum nesting depth"
1987
+ }]);
1988
+ if (!plan.inputChecker.Check(input)) {
1989
+ const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
1990
+ path: err.path,
1991
+ message: err.message,
1992
+ value: err.value
1993
+ }));
1994
+ throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
1995
+ }
1996
+ }
1997
+ if (plan.hasAuthorize) {
1998
+ const authRes = plan.authorize({
1999
+ ctx,
2000
+ input,
2001
+ user: ctx.user
2002
+ });
2003
+ if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError(ctx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${plan.actionName}'`, ctx.user == null ? 401 : 403);
2004
+ }
2005
+ const execRes = plan.execute({
2006
+ input,
2007
+ ctx,
2008
+ error: plan.errorBuilder
2009
+ });
2010
+ const result = execRes instanceof Promise ? await execRes : execRes;
2011
+ if (plan.outputChecker) {
2012
+ if (!plan.outputChecker.Check(result)) {
2013
+ const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
2014
+ path: err.path,
2015
+ message: err.message,
2016
+ value: err.value
2017
+ }));
2018
+ throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
2019
+ }
2020
+ }
2021
+ return result;
2022
+ } catch (err) {
2023
+ const response = toErrorResponse(err, {
2024
+ logger: ctx.logger,
2025
+ requestId
2026
+ });
2027
+ set.status = response.status;
2028
+ return response;
2029
+ }
2030
+ }
2031
+ /**
2032
+ * An Elysia handler for one action: `compileRoutePlan` and
2033
+ * `executeCompiledRoute` together. Use it to mount an action on your own
2034
+ * Elysia app; `brick()` does it for you.
2035
+ *
2036
+ * @param service - The service the action belongs to.
2037
+ * @param action - The action.
2038
+ * @param routePath - The route's path.
2039
+ * @param method - The HTTP method (POST by default).
2040
+ * @returns A function from the Elysia context to the response.
2041
+ */
2042
+ function createActionHandler(service, action, routePath, method) {
2043
+ const plan = compileRoutePlan(service, action, routePath, method);
2044
+ return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
2045
+ }
2046
+ // src/compiler/handler.ts
2047
+ function coerceQueryValue(value, type, request, key) {
2048
+ if (type === "number" && value !== void 0) {
2049
+ const number = Number(value);
2050
+ return Number.isNaN(number) ? value : number;
2051
+ }
2052
+ if (type === "array") {
2053
+ const values = request ? new URL(request.url).searchParams.getAll(key) : [];
2054
+ return values.length ? values : Array.isArray(value) ? value : [value];
2055
+ }
2056
+ if (type === "boolean") {
2057
+ if (value === "true" || value === "1") return true;
2058
+ if (value === "false" || value === "0") return false;
2059
+ }
2060
+ return value;
2061
+ }
2062
+ /** Bind route metadata with ordinary closures; emitted factories remain build-only. */
2063
+ function createHandlerFactory(route) {
2064
+ return (binding, runtime) => {
2065
+ const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
2066
+ const readLike = route.inputPrecedence[0] === "query";
2067
+ const objectInput = binding.action.config.input?.type === "object";
2068
+ const readInput = route.input ? ({ params, body, query, request }) => {
2069
+ let coercedQuery = query;
2070
+ if (query && route.coercions.length) {
2071
+ coercedQuery = { ...query };
2072
+ for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type, request, key);
2073
+ }
2074
+ let coercedParams = params;
2075
+ if (params && route.coercions.length) for (const { key, type } of route.coercions) {
2076
+ if (type !== "number" || typeof params[key] !== "string") continue;
2077
+ const value = Number(params[key]);
2078
+ if (Number.isNaN(value)) continue;
2079
+ if (coercedParams === params) coercedParams = { ...params };
2080
+ coercedParams[key] = value;
2081
+ }
2082
+ let input = readLike ? runtime.mergeInput(coercedQuery, coercedParams, body) : runtime.mergeInput(coercedParams, body, coercedQuery);
2083
+ if (objectInput) input ??= {};
2084
+ return input;
2085
+ } : () => void 0;
2086
+ const validateInput = (input) => {
2087
+ if (inputChecker) {
2088
+ runtime.checkDepth(input, route.action);
2089
+ runtime.validate(inputChecker, input, route.action, "input");
2090
+ }
2091
+ };
2092
+ const validateOutput = (result) => {
2093
+ if (route.output && outputChecker) runtime.validate(outputChecker, result, route.action, "output");
2094
+ return result;
2095
+ };
2096
+ const createContext = ({ headers, request, set }) => {
2097
+ const seq = runtime.nextSequence();
2098
+ const traceId = headers?.["x-trace-id"] || "tr_" + seq;
2099
+ const requestId = headers?.["x-request-id"] || "req_" + seq;
2100
+ if (set?.headers) {
2101
+ set.headers["x-trace-id"] = traceId;
2102
+ set.headers["x-request-id"] = requestId;
2103
+ }
2104
+ return {
2105
+ request: request instanceof Request ? request : runtime.defaultRequest,
2106
+ traceId,
2107
+ requestId,
2108
+ db: cachedDb ?? service.getDb(),
2109
+ logger,
2110
+ services: runtime.emptyServices,
2111
+ deps: service.deps ?? runtime.emptyServices,
2112
+ metadata: { headers },
2113
+ _resolved: true
2114
+ };
2115
+ };
2116
+ if (contextHook || authorize) return async function brickAction(context) {
2117
+ const input = readInput(context);
2118
+ const ctx = createContext(context);
2119
+ try {
2120
+ if (contextHook) {
2121
+ const extra = await contextHook(ctx);
2122
+ if (extra) Object.assign(ctx, extra);
2123
+ }
2124
+ validateInput(input);
2125
+ if (authorize && !await authorize({
2126
+ ctx,
2127
+ input,
2128
+ user: ctx.user
2129
+ })) runtime.deny(route.action, ctx.user);
2130
+ return validateOutput(await execute({
2131
+ input,
2132
+ ctx,
2133
+ error: errorBuilder
2134
+ }));
2135
+ } catch (err) {
2136
+ return runtime.mapError(err, context.set, ctx);
2137
+ }
2138
+ };
2139
+ return function brickAction(context) {
2140
+ const input = readInput(context);
2141
+ const ctx = createContext(context);
2142
+ try {
2143
+ validateInput(input);
2144
+ const result = execute({
2145
+ input,
2146
+ ctx,
2147
+ error: errorBuilder
2148
+ });
2149
+ if (runtime.isThenable(result)) return Promise.resolve(result).then(validateOutput).catch((err) => runtime.mapError(err, context.set, ctx));
2150
+ return validateOutput(result);
2151
+ } catch (err) {
2152
+ return runtime.mapError(err, context.set, ctx);
2153
+ }
2154
+ };
2155
+ };
2156
+ }
2157
+ // src/app-entry.ts
2158
+ /**
2159
+ * Whether a value is an application made by `brick()`. It checks for the
2160
+ * methods and `definition` a `BrickApp` has, so it also recognizes one built by
2161
+ * another copy of the package.
2162
+ *
2163
+ * @param app - Anything, such as the default export of an entry file.
2164
+ * @returns `true` for a `BrickApp`, narrowing its type.
2165
+ */
2166
+ function isBrickApp(app) {
2167
+ if (!app || typeof app !== "object") return false;
2168
+ return "endpoint" in app && typeof app.endpoint === "function" && "fetch" in app && typeof app.fetch === "function" && "listen" in app && typeof app.listen === "function" && "definition" in app && !!app.definition && typeof app.definition === "object" && "services" in app.definition && Array.isArray(app.definition.services) && "prefix" in app.definition && typeof app.definition.prefix === "string";
2169
+ }
2170
+ /**
2171
+ * Check that a module's default export is an application ready to be served,
2172
+ * for tools that load an entry file.
2173
+ *
2174
+ * @param app - The default export of an entry file.
2175
+ * @returns The app.
2176
+ * @throws When it is not a `BrickApp`, or it already called `.listen()`: the
2177
+ * entry must only build the app, and leave listening to the server bootstrap.
2178
+ */
2179
+ function requireBrickApp(app) {
2180
+ if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
2181
+ if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
2182
+ return app;
2183
+ }
2184
+ // src/compiler.ts
2185
+ const buildBindings = /* @__PURE__ */ new Map();
2186
+ function applicationKey(services, prefix = "/api") {
2187
+ return JSON.stringify([prefix, services.map((service) => service.name)]);
2188
+ }
2189
+ /** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
2190
+ async function loadCompiledBrickApp(load, ir, bind) {
2191
+ const key = JSON.stringify([ir.prefix, ir.services]);
2192
+ if (buildBindings.has(key)) throw new Error("Brick compiler: overlapping compiled app imports");
2193
+ buildBindings.set(key, bind);
2194
+ try {
2195
+ const app = requireBrickApp((await load()).default);
2196
+ if (applicationKey(app.definition.services, app.definition.prefix) !== key) throw new Error("Brick compiler: app services/prefix changed; rebuild the application");
2197
+ return app;
2198
+ } finally {
2199
+ buildBindings.delete(key);
2200
+ }
2201
+ }
2202
+ function bindAnalyzed(ir, bindings, factories) {
2203
+ if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
2204
+ const routes = ir.routes.map((route, index) => {
2205
+ const { service, action } = bindings[index];
2206
+ const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
2207
+ const handler = factories[index](plan, compilerRuntime);
2208
+ return Object.freeze({
2209
+ ir: route,
2210
+ handler
2211
+ });
2212
+ });
2213
+ return Object.freeze({
2214
+ ir: freezeIR(ir),
2215
+ routes: Object.freeze(routes)
2216
+ });
2217
+ }
2218
+ /** Startup compiler: analyzes once, then binds live callbacks. */
2219
+ function compileBrickApplication(options) {
2220
+ const bind = buildBindings.get(applicationKey(options.services, options.prefix));
2221
+ if (bind && options.mode !== "generic") return bind(options.services);
2222
+ const { ir, bindings } = analyzeApplication(options.services, options.prefix);
2223
+ const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map(createHandlerFactory);
2224
+ if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
2225
+ return bindAnalyzed(ir, bindings, factories);
2226
+ }
2227
+ /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
2228
+ function bindCompiledApplication(ir, services, factories) {
2229
+ if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
2230
+ const analyzed = analyzeApplication(services, ir.prefix);
2231
+ if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
2232
+ for (const service of services) service.prepareContributions();
2233
+ return bindAnalyzed(ir, analyzed.bindings, factories);
2234
+ }
2235
+ // src/access.ts
2236
+ /**
2237
+ * Cross-copy access metadata protocol. CRUD enforces its access policy
2238
+ * inside `execute`, so `config.authorize` is absent and introspection
2239
+ * can't see it. The plugin stamps each action under this process-global
2240
+ * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
2241
+ * the binding survives a second copy of core (bundler SSR, Vitest),
2242
+ * same as the plugin action-binding key.
2243
+ */
2244
+ const ACTION_ACCESS_KEY = Symbol.for("brickkit.action.access");
2245
+ /**
2246
+ * Record how an action is protected, for tools that cannot read it from the
2247
+ * configuration: plugins such as `crud` enforce access inside `execute`, so the
2248
+ * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
2249
+ * read what is recorded here.
2250
+ *
2251
+ * @param action - The action to describe.
2252
+ * @param info - Whether it checks authorization and whether it scopes queries,
2253
+ * and the resulting policy.
2254
+ */
2255
+ function setActionAccess(action, info) {
2256
+ action[ACTION_ACCESS_KEY] = {
2257
+ hasAuthorize: info.hasAuthorize,
2258
+ hasScope: info.hasScope,
2259
+ policy: info.policy
2260
+ };
2261
+ }
2262
+ /**
2263
+ * How an action is protected: `"public"` when nothing checks the caller,
2264
+ * `"authorized"` when an `authorize` does, and `"scoped"` when the action also
2265
+ * limits what rows the caller can reach. It reads what a plugin recorded with
2266
+ * `setActionAccess`, else the action's own `authorize`, and keeps the policy
2267
+ * consistent with the flags.
2268
+ *
2269
+ * @param action - An action, or any object a plugin described.
2270
+ * @returns `hasAuthorize`, `hasScope`, and `policy`.
2271
+ */
2272
+ function getActionAccess(action) {
2273
+ const meta = action[ACTION_ACCESS_KEY];
2274
+ const configAuthorize = Boolean(action?.config && typeof action.config === "object" && "authorize" in action.config && typeof action.config.authorize === "function");
2275
+ if (!meta) return {
2276
+ hasAuthorize: configAuthorize,
2277
+ hasScope: false,
2278
+ policy: configAuthorize ? "authorized" : "public"
2279
+ };
2280
+ const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);
2281
+ const hasScope = Boolean(meta.hasScope);
2282
+ let policy = meta.policy ?? (hasAuthorize ? hasScope ? "scoped" : "authorized" : "public");
2283
+ if (policy === "public" && hasAuthorize) policy = hasScope ? "scoped" : "authorized";
2284
+ else if (policy !== "public" && !hasAuthorize) policy = "public";
2285
+ else if (policy === "scoped" && !hasScope) policy = "authorized";
2286
+ return {
2287
+ hasAuthorize,
2288
+ hasScope,
2289
+ policy
2290
+ };
2291
+ }
2292
+ // src/openapi.ts
2293
+ function isAnchor(node) {
2294
+ return typeof node === "object" && node !== null && typeof node.$id === "string";
2295
+ }
2296
+ function isBareRef(node) {
2297
+ return typeof node === "object" && node !== null && typeof node.$ref === "string" && !node.$ref.startsWith("#");
2298
+ }
2299
+ function toComponentKey(id) {
2300
+ return id.replace(/[^A-Za-z0-9.\-_]+/g, "_");
2301
+ }
2302
+ /**
2303
+ * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors
2304
+ * (`{ $id: "T0", ..., { $ref: "T0" } }`). OpenAPI interprets a bare `$ref`
2305
+ * as an external file reference, so downstream tooling tries to load a
2306
+ * file named `T0` and fails. Hoist every anchored subschema into
2307
+ * `#/components/schemas/` and rewrite the refs to local pointers.
2308
+ * First definition wins when one `$id` is declared twice.
2309
+ */
2310
+ function hoistAnchoredSchemas(spec) {
2311
+ const anchored = /* @__PURE__ */ new Map();
2312
+ const conflicts = [];
2313
+ const collect = (node) => {
2314
+ if (Array.isArray(node)) return node.map(collect);
2315
+ if (typeof node !== "object" || node === null) return node;
2316
+ if (isAnchor(node)) {
2317
+ const id = node.$id;
2318
+ const { $id: _dropped, ...rest } = node;
2319
+ const collected = collect(rest);
2320
+ if (anchored.has(id)) {
2321
+ if (JSON.stringify(anchored.get(id)) !== JSON.stringify(collected)) conflicts.push(id);
2322
+ } else anchored.set(id, collected);
2323
+ return { $ref: `#/components/schemas/${toComponentKey(id)}` };
2324
+ }
2325
+ for (const key of Object.keys(node)) node[key] = collect(node[key]);
2326
+ return node;
2327
+ };
2328
+ const rewrite = (node) => {
2329
+ if (Array.isArray(node)) {
2330
+ for (const child of node) rewrite(child);
2331
+ return;
2332
+ }
2333
+ if (typeof node !== "object" || node === null) return;
2334
+ if (isBareRef(node)) node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;
2335
+ for (const key of Object.keys(node)) rewrite(node[key]);
2336
+ };
2337
+ collect(spec);
2338
+ const components = spec.components ??= {};
2339
+ const schemas = components.schemas ??= {};
2340
+ for (const [id, schema] of anchored) schemas[toComponentKey(id)] = schema;
2341
+ rewrite(spec);
2342
+ return [...anchored.keys()];
2343
+ }
2344
+ /**
2345
+ * Build the OpenAPI 3.1 document for the services: one path per action route,
2346
+ * with request and response schemas from the actions' TypeBox schemas, their
2347
+ * declared errors, tags by service, and a bearer security scheme where any
2348
+ * action needs authorization. Declared events are listed under `x-brick-events`,
2349
+ * by wire name, with their service and payload schema.
2350
+ *
2351
+ * `brick()` calls this for `/openapi.json`; call it yourself to write the
2352
+ * document to a file or feed another tool.
2353
+ *
2354
+ * @param options - `title`, `version`, and `description` for the `info` block,
2355
+ * `prefix` (default `/api`), and the `services` or `registry` to describe
2356
+ * (the global registry by default).
2357
+ * @returns The document as a plain object.
2358
+ */
2359
+ function generateOpenApiSpec(options = {}) {
2360
+ const title = options.title ?? "Brick-TS API Mesh";
2361
+ const version = options.version ?? "1.0.0";
2362
+ const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
2363
+ const prefix = options.prefix ?? "/api";
2364
+ const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
2365
+ const paths = {};
2366
+ const tags = /* @__PURE__ */ new Map();
2367
+ let hasAnyAuthorizedAction = false;
2368
+ for (const service of services) {
2369
+ tags.set(service.name, `Actions exposed by '${service.name}' service`);
2370
+ for (const action of service.listActions()) {
2371
+ const route = getActionRoute(action, prefix);
2372
+ if (route === false) continue;
2373
+ const routePath = route.path;
2374
+ const method = route.method.toLowerCase();
2375
+ const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
2376
+ const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
2377
+ if (!paths[actionPath]) paths[actionPath] = {};
2378
+ if (paths[actionPath][method]) continue;
2379
+ const resource = action.resource;
2380
+ const group = resource ? `${service.name} · ${resource}` : service.name;
2381
+ if (resource) tags.set(group, `Routes of resource '${resource}' in service '${service.name}'`);
2382
+ const hasAuth = getActionAccess(action).hasAuthorize;
2383
+ if (hasAuth) hasAnyAuthorizedAction = true;
2384
+ const responses = {};
2385
+ if (action.config.output) responses["200"] = {
2386
+ description: "Successful response",
2387
+ content: { "application/json": { schema: action.config.output } }
2388
+ };
2389
+ else responses["200"] = { description: "Successful response" };
2390
+ const errorAlternatives = /* @__PURE__ */ new Set();
2391
+ const addError = (code, status, message, details) => {
2392
+ const key = `${status}:${code}`;
2393
+ if (errorAlternatives.has(key)) return;
2394
+ errorAlternatives.add(key);
2395
+ const schema = { allOf: [{ $ref: "#/components/schemas/ErrorEnvelope" }, {
2396
+ type: "object",
2397
+ properties: {
2398
+ code: { const: code },
2399
+ status: { const: status },
2400
+ ...details ? { details } : {}
2401
+ }
2402
+ }] };
2403
+ const existing = responses[String(status)];
2404
+ if (existing) {
2405
+ existing.description += "; " + message;
2406
+ existing.content["application/json"].schema.oneOf.push(schema);
2407
+ } else responses[String(status)] = {
2408
+ description: message,
2409
+ content: { "application/json": { schema: { oneOf: [schema] } } }
2410
+ };
2411
+ };
2412
+ if (action.config.input) addError("VALIDATION_FAILED", 400, "Validation error");
2413
+ if (hasAuth) {
2414
+ addError("UNAUTHORIZED", 401, "Authentication required");
2415
+ addError("FORBIDDEN", 403, "Access denied");
2416
+ }
2417
+ if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
2418
+ const def = errorDef;
2419
+ addError(code, def.status || 400, def.message || code, def.details);
2420
+ }
2421
+ addError("INTERNAL_SERVER_ERROR", 500, "Internal server error");
2422
+ if (action.config.output) addError("VALIDATION_FAILED", 500, "Output validation error");
2423
+ const operation = {
2424
+ operationId: `${service.name}_${action.name}_${method}`,
2425
+ summary: `${service.name}.${action.name}`,
2426
+ description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
2427
+ tags: [.../* @__PURE__ */ new Set([group, ...action.config.tags ?? []])],
2428
+ ...action.plugin ? { "x-brick-plugin": action.plugin } : {},
2429
+ ...action.resource ? { "x-brick-resource": action.resource } : {},
2430
+ responses
2431
+ };
2432
+ const inputSchema = action.config.input;
2433
+ const properties = inputSchema?.properties ?? {};
2434
+ const parameters = [...new Set(pathParams)].map((key) => ({
2435
+ name: key,
2436
+ in: "path",
2437
+ required: true,
2438
+ schema: properties[key] ?? { type: "string" }
2439
+ }));
2440
+ if (method === "get" || method === "delete") for (const [key, schema] of Object.entries(properties)) {
2441
+ if (pathParams.includes(key)) continue;
2442
+ parameters.push({
2443
+ name: key,
2444
+ in: "query",
2445
+ required: inputSchema?.required?.includes(key) ?? false,
2446
+ schema
2447
+ });
2448
+ }
2449
+ else if (inputSchema) operation.requestBody = {
2450
+ required: true,
2451
+ content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
2452
+ ...inputSchema,
2453
+ properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
2454
+ required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
2455
+ } : inputSchema } }
2456
+ };
2457
+ if (parameters.length) operation.parameters = parameters;
2458
+ if (hasAuth) operation.security = [{ bearerAuth: [] }];
2459
+ paths[actionPath][method] = operation;
2460
+ }
2461
+ }
2462
+ const spec = {
2463
+ openapi: "3.1.0",
2464
+ info: {
2465
+ title,
2466
+ version,
2467
+ description
2468
+ },
2469
+ paths,
2470
+ tags: Array.from(tags, ([name, description]) => ({
2471
+ name,
2472
+ description
2473
+ }))
2474
+ };
2475
+ spec.components = { schemas: { ErrorEnvelope: {
2476
+ type: "object",
2477
+ required: [
2478
+ "name",
2479
+ "code",
2480
+ "message",
2481
+ "status",
2482
+ "requestId"
2483
+ ],
2484
+ properties: {
2485
+ name: { type: "string" },
2486
+ code: { type: "string" },
2487
+ message: { type: "string" },
2488
+ status: { type: "integer" },
2489
+ requestId: { type: "string" },
2490
+ details: {},
2491
+ errors: {
2492
+ type: "array",
2493
+ items: {
2494
+ type: "object",
2495
+ required: ["path", "message"],
2496
+ properties: {
2497
+ path: { type: "string" },
2498
+ message: { type: "string" },
2499
+ value: {}
2500
+ }
2501
+ }
2502
+ }
2503
+ }
2504
+ } } };
2505
+ if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
2506
+ type: "http",
2507
+ scheme: "bearer",
2508
+ bearerFormat: "JWT",
2509
+ description: "Enter your Bearer authentication token"
2510
+ } } });
2511
+ const events = Object.fromEntries(services.flatMap((service) => Object.values(service.events ?? {}).map((ref) => [ref.name, {
2512
+ service: service.name,
2513
+ payload: ref.schema,
2514
+ ...ref.plugin ? { "x-brick-plugin": ref.plugin } : {}
2515
+ }])));
2516
+ if (Object.keys(events).length) spec["x-brick-events"] = events;
2517
+ const document = JSON.parse(JSON.stringify(spec));
2518
+ hoistAnchoredSchemas(document);
2519
+ return document;
2520
+ }
2521
+ // src/secrets.ts
2522
+ /** Default source: `process.env` (Bun loads `.env` into it automatically). */
2523
+ const envSource = { get: (name) => process.env[name] };
2524
+ const registry = /* @__PURE__ */ new Map();
2525
+ const overrides = /* @__PURE__ */ new Map();
2526
+ var SecretRef = class {
2527
+ name;
2528
+ options;
2529
+ transformFn;
2530
+ validators = [];
2531
+ constructor(name, options = {}) {
2532
+ this.name = name;
2533
+ this.options = options;
2534
+ }
2535
+ /** True when a default was declared (i.e. the secret is optional). */
2536
+ get hasDefault() {
2537
+ return this.options.default !== void 0;
2538
+ }
2539
+ /** Fallback used when the source has no value. Makes the secret optional. */
2540
+ default(value) {
2541
+ this.options.default = value;
2542
+ return this;
2543
+ }
2544
+ /**
2545
+ * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
2546
+ * Runs before validators; a throwing transform fails resolution.
2547
+ */
2548
+ transform(fn) {
2549
+ this.transformFn = fn;
2550
+ return this;
2551
+ }
2552
+ /** Run a custom check on the (transformed) value at every resolution. */
2553
+ validate(fn) {
2554
+ this.validators.push(fn);
2555
+ return this;
2556
+ }
2557
+ /** Shorthand validator: value must parse as a URL. String refs only. */
2558
+ url() {
2559
+ this.validators.push((v) => {
2560
+ try {
2561
+ new URL(v);
2562
+ } catch {
2563
+ return "must be a valid URL";
2564
+ }
2565
+ });
2566
+ return this;
2567
+ }
2568
+ resolveRaw(source) {
2569
+ if (overrides.has(this.name)) {
2570
+ const v = overrides.get(this.name);
2571
+ if (v !== void 0) return v;
2572
+ }
2573
+ return source.get(this.name) ?? this.options.default;
2574
+ }
2575
+ coerce(raw) {
2576
+ let value;
2577
+ if (this.transformFn) try {
2578
+ value = this.transformFn(raw);
2579
+ } catch (err) {
2580
+ throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
2581
+ }
2582
+ else value = raw;
2583
+ for (const fn of this.validators) {
2584
+ let result;
2585
+ try {
2586
+ result = fn(value);
2587
+ } catch (err) {
2588
+ throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
2589
+ }
2590
+ if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
2591
+ if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
2592
+ }
2593
+ return value;
2594
+ }
2595
+ /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
2596
+ value(source = envSource) {
2597
+ const raw = this.resolveRaw(source);
2598
+ if (raw === void 0) return void 0;
2599
+ return this.coerce(raw);
2600
+ }
2601
+ /** Resolved value, or throws naming the missing/invalid secret. */
2602
+ require(source = envSource) {
2603
+ const raw = this.resolveRaw(source);
2604
+ if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
2605
+ return this.coerce(raw);
2606
+ }
2607
+ /** True when a value would resolve (override, source, or default). */
2608
+ isSet(source = envSource) {
2609
+ return this.resolveRaw(source) !== void 0;
2610
+ }
2611
+ };
2612
+ /**
2613
+ * Declare a secret. Idempotent: re-declaring the same name returns the
2614
+ * original ref (first declaration wins) so module re-evaluation is safe.
2615
+ */
2616
+ function defineSecret(name, options = {}) {
2617
+ const existing = registry.get(name);
2618
+ if (existing) return existing;
2619
+ const ref = new SecretRef(name, options);
2620
+ registry.set(name, ref);
2621
+ return ref;
2622
+ }
2623
+ /**
2624
+ * Validate every registered secret at boot. Throws a single error listing
2625
+ * all missing required secrets. Returns the resolved values.
2626
+ */
2627
+ function resolveSecrets(opts = {}) {
2628
+ const source = opts.source ?? envSource;
2629
+ const missing = [];
2630
+ const resolved = {};
2631
+ for (const ref of registry.values()) {
2632
+ const v = ref.value(source);
2633
+ if (v === void 0) missing.push(ref.name);
2634
+ else resolved[ref.name] = v;
2635
+ }
2636
+ if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
2637
+ return resolved;
2638
+ }
2639
+ /** Metadata for introspection (values never exposed — future dashboard use). */
2640
+ function listSecrets(opts = {}) {
2641
+ const source = opts.source ?? envSource;
2642
+ return [...registry.values()].map((ref) => ({
2643
+ hasDefault: ref.hasDefault,
2644
+ isSet: ref.isSet(source),
2645
+ name: ref.name
2646
+ }));
2647
+ }
2648
+ /** Test/session override for one secret (`undefined` clears the override). */
2649
+ function overrideSecret(name, value) {
2650
+ overrides.set(name, value);
2651
+ }
2652
+ /** Bulk overrides (test/session scoped). */
2653
+ function overrideSecrets(values) {
2654
+ for (const [name, value] of Object.entries(values)) overrides.set(name, value);
2655
+ }
2656
+ /** Clear registry and overrides. Test-only. */
2657
+ function resetSecrets() {
2658
+ registry.clear();
2659
+ overrides.clear();
2660
+ }
2661
+ // src/request-logger.ts
2662
+ function formatLog(method, path, status, elapsedMs) {
2663
+ return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;
2664
+ }
2665
+ /**
2666
+ * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError
2667
+ * while `set.status` may still hold the 200 default when onError runs).
2668
+ */
2669
+ function thrownStatus(error) {
2670
+ if (typeof error === "object" && error !== null && "status" in error) {
2671
+ const status = error.status;
2672
+ if (typeof status === "number") return status;
2673
+ }
2674
+ }
2675
+ /**
2676
+ * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
2677
+ * Timing is tracked per-Request via a WeakMap. The onError hook only logs and
2678
+ * returns undefined so existing error mapping is preserved. Logging only —
2679
+ * no CORS headers are set here.
2680
+ *
2681
+ * Hooks are registered with the "global" scope so they propagate to the
2682
+ * parent app when mounted via `app.use(...)` — Elysia scopes plain instance
2683
+ * hooks to the plugin's own routes. Timing is captured in beforeHandle
2684
+ * because request hooks are not propagated from a
2685
+ * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
2686
+ */
2687
+ function requestLoggingPlugin(opts = {}) {
2688
+ const plugin = new Elysia();
2689
+ if (!(opts.enabled ?? true)) return plugin;
2690
+ const logger = opts.logger ?? console.log;
2691
+ const startedAt = /* @__PURE__ */ new WeakMap();
2692
+ const markStarted = ({ request }) => {
2693
+ startedAt.set(request, Date.now());
2694
+ };
2695
+ const logSuccess = ({ request, set }) => {
2696
+ const start = startedAt.get(request) ?? Date.now();
2697
+ const path = new URL(request.url).pathname;
2698
+ logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
2699
+ };
2700
+ const logError = ({ request, set, error }) => {
2701
+ if (request) {
2702
+ const start = startedAt.get(request) ?? Date.now();
2703
+ const path = new URL(request.url).pathname;
2704
+ const status = thrownStatus(error) ?? set.status ?? 500;
2705
+ logger(formatLog(request.method, path, status, Date.now() - start));
2706
+ }
2707
+ };
2708
+ plugin.onBeforeHandle("global", markStarted);
2709
+ plugin.onAfterHandle("global", logSuccess);
2710
+ plugin.onError("global", logError);
2711
+ return plugin;
2712
+ }
2713
+ // src/docs.ts
2714
+ /** Renders the Scalar API reference page for the given OpenAPI URL. */
2715
+ function scalarDocsHTML(specUrl, title) {
2716
+ return `<!doctype html>
2717
+ <html>
2718
+ <head>
2719
+ <title>${title} — API Reference</title>
2720
+ <meta charset="utf-8" />
2721
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
2722
+ <link rel="icon" type="image/svg+xml" href="https://scalar.com/favicon.svg" />
2723
+ <style>
2724
+ body { margin: 0; padding: 0; height: 100vh; }
2725
+ </style>
2726
+ </head>
2727
+ <body>
2728
+ <script
2729
+ id="api-reference"
2730
+ data-url="${specUrl}"
2731
+ data-configuration='{"theme": "purple", "layout": "modern"}'
2732
+ src="https://cdn.jsdelivr.net/npm/@scalar/api-reference">
2733
+ <\/script>
2734
+ </body>
2735
+ </html>`;
2736
+ }
2737
+ /** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */
2738
+ function referencePlugin(opts = {}) {
2739
+ const path = opts.path ?? "/reference";
2740
+ const title = opts.title ?? "Brick-TS API Mesh";
2741
+ const specUrl = opts.specUrl ?? "/openapi.json";
2742
+ const plugin = new Elysia();
2743
+ plugin.get(path, ({ set }) => {
2744
+ set.headers["content-type"] = "text/html; charset=utf-8";
2745
+ return scalarDocsHTML(specUrl, title);
2746
+ });
2747
+ return plugin;
2748
+ }
2749
+ /** Mounts the Scalar reference route onto an existing app. */
2750
+ function registerReferenceRoute(app, opts = {}) {
2751
+ return app.use(referencePlugin(opts));
2752
+ }
2753
+ /** Renders the Swagger UI page. */
2754
+ function swaggerDocsHTML(specUrl, title) {
2755
+ return `<!DOCTYPE html>
2756
+ <html lang="en">
2757
+ <head>
2758
+ <meta charset="UTF-8">
2759
+ <title>${title} — Swagger UI</title>
2760
+ <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
2761
+ <style>
2762
+ html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }
2763
+ *, *:before, *:after { box-sizing: inherit; }
2764
+ body { margin:0; background: #fafafa; }
2765
+ </style>
2766
+ </head>
2767
+ <body>
2768
+ <div id="swagger-ui"></div>
2769
+ <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" charset="UTF-8"><\/script>
2770
+ <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js" charset="UTF-8"><\/script>
2771
+ <script>
2772
+ window.onload = function() {
2773
+ SwaggerUIBundle({
2774
+ url: "${specUrl}",
2775
+ dom_id: '#swagger-ui',
2776
+ deepLinking: true,
2777
+ presets: [
2778
+ SwaggerUIBundle.presets.apis,
2779
+ SwaggerUIStandalonePreset
2780
+ ],
2781
+ plugins: [
2782
+ SwaggerUIBundle.plugins.DownloadUrl
2783
+ ],
2784
+ layout: "StandaloneLayout"
2785
+ });
2786
+ };
2787
+ <\/script>
2788
+ </body>
2789
+ </html>`;
2790
+ }
2791
+ // src/dashboard.ts
2792
+ const MIN_TOKEN_LENGTH = 16;
2793
+ /**
2794
+ * Check what `brick()` was given, and freeze it. The secrets sit behind a getter
2795
+ * that is not enumerable, so logging or serializing the application definition
2796
+ * does not print them.
2797
+ */
2798
+ function normalizeDashboard(options) {
2799
+ if (options === void 0) return void 0;
2800
+ const { port, host, auth, historyDays } = options;
2801
+ if (port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new Error(`Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`);
2802
+ if (host !== void 0 && (typeof host !== "string" || host.trim() === "")) throw new Error("Brick: dashboard host must be an address, such as '0.0.0.0'.");
2803
+ if (historyDays !== void 0 && (!Number.isInteger(historyDays) || historyDays < 0)) throw new Error(`Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`);
2804
+ const normalized = {
2805
+ ...port !== void 0 ? { port } : {},
2806
+ ...host !== void 0 ? { host: host.trim() } : {},
2807
+ ...historyDays !== void 0 ? { historyDays } : {}
2808
+ };
2809
+ if (auth !== void 0) {
2810
+ const tokens = auth.token === void 0 ? void 0 : typeof auth.token === "string" ? [auth.token] : [...auth.token];
2811
+ if (tokens?.some((token) => typeof token !== "string" || token.length < MIN_TOKEN_LENGTH)) throw new Error(`Brick: a dashboard token must be at least ${MIN_TOKEN_LENGTH} characters. Try: openssl rand -base64 32`);
2812
+ if (auth.authorize !== void 0 && typeof auth.authorize !== "function") throw new Error("Brick: dashboard authorize must be a function.");
2813
+ if ((tokens === void 0 || tokens.length === 0) && !auth.authorize) throw new Error("Brick: dashboard auth needs a token or an authorize function.");
2814
+ const secrets = Object.freeze({
2815
+ ...tokens ? { token: Object.freeze(tokens) } : {},
2816
+ ...auth.authorize ? { authorize: auth.authorize } : {}
2817
+ });
2818
+ Object.defineProperty(normalized, "auth", {
2819
+ enumerable: false,
2820
+ get: () => secrets
2821
+ });
2822
+ }
2823
+ return Object.freeze(normalized);
2824
+ }
2825
+ // src/endpoints.ts
2826
+ /** Resolve the db for an endpoint: explicit service first, else first service holding one. */
2827
+ function resolveEndpointDb(service, services) {
2828
+ if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb() ?? void 0;
2829
+ for (const svc of services) {
2830
+ const db = svc.getDb();
2831
+ if (db) return db;
2832
+ }
2833
+ }
2834
+ /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
2835
+ function createEndpointHandler(def, services) {
2836
+ const logger = createLogger(`[${`endpoint:${def.method} ${def.path}`}]`);
2837
+ return async ({ params, body, query, headers, request, set }) => {
2838
+ const traceId = headers?.["x-trace-id"] || `tr_${crypto.randomUUID()}`;
2839
+ const requestId = headers?.["x-request-id"] || `req_${crypto.randomUUID()}`;
2840
+ if (set?.headers) {
2841
+ set.headers["x-trace-id"] = traceId;
2842
+ set.headers["x-request-id"] = requestId;
2843
+ }
2844
+ const ctx = {
2845
+ body,
2846
+ db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
2847
+ headers: headers ?? {},
2848
+ logger,
2849
+ params: params ?? {},
2850
+ query: query ?? {},
2851
+ request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
2852
+ headers: new Headers(headers ?? {}),
2853
+ method: def.method
2854
+ }),
2855
+ requestId,
2856
+ set,
2857
+ traceId
2858
+ };
2859
+ try {
2860
+ return await def.handler(ctx);
2861
+ } catch (err) {
2862
+ const response = toErrorResponse(!(err instanceof ActionExecutionError || err instanceof ValidationError) && err !== null && typeof err === "object" && "status" in err && typeof err.status === "number" && Number.isInteger(err.status) && err.status >= 400 && err.status < 500 ? new ActionExecutionError("HTTP_ERROR", "message" in err && typeof err.message === "string" ? err.message : "Endpoint error", err.status, void 0, { cause: err }) : err, {
2863
+ logger: ctx.logger,
2864
+ requestId
2865
+ });
2866
+ set.status = response.status;
2867
+ return response;
2868
+ }
2869
+ };
2870
+ }
2871
+ /** `/p/:slug` → `/p/{slug}` for OpenAPI. */
2872
+ function toOpenApiPath(elysiaPath) {
2873
+ return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
2874
+ }
2875
+ /** Parameter names (`:slug`) extracted for the OpenAPI path item. */
2876
+ function pathParamNames(elysiaPath) {
2877
+ return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);
2878
+ }
2879
+ /** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
2880
+ function endpointPaths(defs) {
2881
+ const paths = {};
2882
+ for (const def of defs) {
2883
+ const openApiPath = toOpenApiPath(def.path);
2884
+ if (!paths[openApiPath]) paths[openApiPath] = {};
2885
+ const params = pathParamNames(def.path).map((name) => ({
2886
+ in: "path",
2887
+ name,
2888
+ required: true,
2889
+ schema: { type: "string" }
2890
+ }));
2891
+ paths[openApiPath][def.method.toLowerCase()] = {
2892
+ ...def.summary ? { summary: def.summary } : {},
2893
+ ...def.description ? { description: def.description } : {},
2894
+ ...def.tags ? { tags: def.tags } : {},
2895
+ ...def.plugin ? { "x-brick-plugin": def.plugin } : {},
2896
+ ...params.length > 0 ? { parameters: params } : {},
2897
+ responses: { 200: { description: "Successful response" } }
2898
+ };
2899
+ }
2900
+ return paths;
2901
+ }
2902
+ // src/events/outbox.ts
2903
+ const OUTBOX = Symbol.for("brick.outbox");
2904
+ function sqliteOutbox(name) {
2905
+ const timestampMs = (column) => integer(column, { mode: "timestamp_ms" });
2906
+ return sqliteTable(name, {
2907
+ seq: integer("seq").primaryKey({ autoIncrement: true }),
2908
+ id: text("id").notNull().unique(),
2909
+ eventId: text("event_id").notNull(),
2910
+ listener: text("listener").notNull(),
2911
+ name: text("name").notNull(),
2912
+ payload: text("payload", { mode: "json" }).notNull(),
2913
+ traceId: text("trace_id"),
2914
+ source: text("source"),
2915
+ occurredAt: timestampMs("occurred_at").notNull(),
2916
+ status: text("status").$type().notNull(),
2917
+ attempts: integer("attempts").notNull().default(0),
2918
+ lastError: text("last_error"),
2919
+ availableAt: timestampMs("available_at").notNull(),
2920
+ claimedAt: timestampMs("claimed_at"),
2921
+ deliveredAt: timestampMs("delivered_at")
2922
+ }, (table) => [index(`${name}_due`).on(table.status, table.availableAt), index(`${name}_event`).on(table.eventId)]);
2923
+ }
2924
+ function postgresOutbox(name) {
2925
+ const at = (column) => timestamp(column, { withTimezone: true });
2926
+ return pgTable(name, {
2927
+ seq: bigserial("seq", { mode: "number" }).primaryKey(),
2928
+ id: text$1("id").notNull().unique(),
2929
+ eventId: text$1("event_id").notNull(),
2930
+ listener: text$1("listener").notNull(),
2931
+ name: text$1("name").notNull(),
2932
+ payload: jsonb("payload").notNull(),
2933
+ traceId: text$1("trace_id"),
2934
+ source: text$1("source"),
2935
+ occurredAt: at("occurred_at").notNull(),
2936
+ status: text$1("status").$type().notNull(),
2937
+ attempts: integer$1("attempts").notNull().default(0),
2938
+ lastError: text$1("last_error"),
2939
+ availableAt: at("available_at").notNull(),
2940
+ claimedAt: at("claimed_at"),
2941
+ deliveredAt: at("delivered_at")
2942
+ }, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
2943
+ }
2944
+ function outboxTable(engine, options = {}) {
2945
+ const name = options.name ?? "brick_outbox";
2946
+ const table = engine === "sqlite" ? sqliteOutbox(name) : postgresOutbox(name);
2947
+ Object.defineProperty(table, OUTBOX, { value: { engine } });
2948
+ return table;
2949
+ }
2950
+ /**
2951
+ * Whether a value is an outbox table made by `outboxTable`.
2952
+ *
2953
+ * @param value - Anything.
2954
+ * @returns `true` for an outbox table, narrowing its type.
2955
+ */
2956
+ function isOutboxTable(value) {
2957
+ return typeof value === "object" && value !== null && OUTBOX in value;
2958
+ }
2959
+ function outboxEngine(table) {
2960
+ return table[OUTBOX].engine;
2961
+ }
2962
+ // src/events/transaction.ts
2963
+ const sqliteQueues = /* @__PURE__ */ new WeakMap();
2964
+ const active = new AsyncLocalStorage();
2965
+ function joined(db) {
2966
+ const open = active.getStore();
2967
+ return open?.open && open.handles.has(db) ? open : void 0;
2968
+ }
2969
+ function isSqliteDatabase(db) {
2970
+ return typeof db?.$client?.prepare === "function" && typeof db?.$client?.run === "function";
2971
+ }
2972
+ function rollbackQuietly(db, statement = "ROLLBACK") {
2973
+ try {
2974
+ db.$client.run(statement);
2975
+ } catch {
2976
+ return;
2977
+ }
2978
+ }
2979
+ async function nested(db, open, fn) {
2980
+ const commits = open.commits.length;
2981
+ try {
2982
+ if (!isSqliteDatabase(db)) return await db.transaction((tx) => {
2983
+ open.handles.add(tx);
2984
+ return fn(tx);
2985
+ });
2986
+ const name = `brick_${++open.savepoints}`;
2987
+ db.$client.run(`SAVEPOINT ${name}`);
2988
+ try {
2989
+ const result = await fn(db);
2990
+ db.$client.run(`RELEASE ${name}`);
2991
+ return result;
2992
+ } catch (error) {
2993
+ rollbackQuietly(db, `ROLLBACK TO ${name}`);
2994
+ rollbackQuietly(db, `RELEASE ${name}`);
2995
+ throw error;
2996
+ }
2997
+ } catch (error) {
2998
+ open.commits.length = commits;
2999
+ throw error;
3000
+ }
3001
+ }
3002
+ /**
3003
+ * Run `fn` in a database transaction: everything it writes through the `tx` it is
3004
+ * given is committed together when it returns, or undone if it throws.
3005
+ *
3006
+ * Postgres uses a real transaction on one connection. SQLite has one connection
3007
+ * and a synchronous driver, which Drizzle's own `transaction` cannot use with an
3008
+ * async callback (it would commit before the callback finished). So transactions
3009
+ * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
3010
+ * A write made elsewhere in the process during that time, outside this helper,
3011
+ * would join the transaction; use Postgres where that matters.
3012
+ *
3013
+ * A call made inside `fn` with the `tx` it was given (on SQLite, the database
3014
+ * itself) joins the open transaction as a savepoint instead of waiting for it: a
3015
+ * nested failure undoes only the nested work, and the outer transaction decides
3016
+ * the commit. Nested calls must run one at a time.
3017
+ *
3018
+ * @param db - A Drizzle database, from `service.getDb()`.
3019
+ * @param fn - Receives the transaction handle to run queries on.
3020
+ * @returns What `fn` returned.
3021
+ * @throws What `fn` threw, after rolling back.
3022
+ */
3023
+ async function runInTransaction(db, fn) {
3024
+ const outer = joined(db);
3025
+ if (outer) return nested(db, outer, fn);
3026
+ const open = {
3027
+ handles: /* @__PURE__ */ new Set(),
3028
+ commits: [],
3029
+ open: true,
3030
+ savepoints: 0
3031
+ };
3032
+ let result;
3033
+ try {
3034
+ result = await active.run(open, () => begin(db, open, fn));
3035
+ } finally {
3036
+ open.open = false;
3037
+ }
3038
+ for (const commit of open.commits) await commit();
3039
+ return result;
3040
+ }
3041
+ async function begin(db, open, fn) {
3042
+ if (!isSqliteDatabase(db)) return db.transaction((tx) => {
3043
+ open.handles.add(tx);
3044
+ return fn(tx);
3045
+ });
3046
+ open.handles.add(db);
3047
+ const previous = sqliteQueues.get(db) ?? Promise.resolve();
3048
+ let release;
3049
+ const turn = new Promise((resolve) => {
3050
+ release = resolve;
3051
+ });
3052
+ sqliteQueues.set(db, previous.then(() => turn));
3053
+ await previous;
3054
+ try {
3055
+ db.$client.run("BEGIN IMMEDIATE");
3056
+ try {
3057
+ const result = await fn(db);
3058
+ db.$client.run("COMMIT");
3059
+ return result;
3060
+ } catch (error) {
3061
+ rollbackQuietly(db);
3062
+ throw error;
3063
+ }
3064
+ } finally {
3065
+ release();
3066
+ }
3067
+ }
3068
+ /** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
3069
+ function inTransaction(db) {
3070
+ return joined(db) !== void 0;
3071
+ }
3072
+ /**
3073
+ * Run `fn` once the transaction that `db` belongs to has committed, or now when
3074
+ * `db` is not in one opened by `runInTransaction`. It never runs when that
3075
+ * transaction, or the savepoint it was queued in, rolls back. An error it throws
3076
+ * reaches the caller of the outermost `runInTransaction`, after the commit.
3077
+ *
3078
+ * @param db - The handle the work ran on: a `tx`, or a database.
3079
+ * @param fn - The side effect, such as clearing a cache.
3080
+ */
3081
+ async function onTransactionCommit(db, fn) {
3082
+ const open = joined(db);
3083
+ if (open) open.commits.push(fn);
3084
+ else await fn();
3085
+ }
3086
+ // src/events/dispatcher.ts
3087
+ function resolveDispatchOptions(options = {}) {
3088
+ return {
3089
+ timer: options.timer ?? true,
3090
+ intervalMs: options.intervalMs ?? 1e3,
3091
+ batchSize: options.batchSize ?? 50,
3092
+ maxAttempts: options.maxAttempts ?? 8,
3093
+ claimTimeoutMs: options.claimTimeoutMs ?? 6e4,
3094
+ maxBackoffMs: options.maxBackoffMs ?? 3e5,
3095
+ retainDeliveredMs: options.retainDeliveredMs ?? 864e5
3096
+ };
3097
+ }
3098
+ const PURGE_INTERVAL_MS = 6e4;
3099
+ /** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry". */
3100
+ function decideRetry(listener, error) {
3101
+ if (!listener.retry) return "retry";
3102
+ try {
3103
+ return listener.retry(error instanceof ActionExecutionError && listener.errors?.[error.code] ? {
3104
+ code: error.code,
3105
+ message: error.message,
3106
+ details: error.details
3107
+ } : {
3108
+ code: "UNKNOWN",
3109
+ message: error instanceof Error ? error.message : String(error),
3110
+ cause: error
3111
+ });
3112
+ } catch {
3113
+ return "retry";
3114
+ }
3115
+ }
3116
+ function backoffMs(attempt, maxBackoffMs) {
3117
+ return Math.min(1e3 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);
3118
+ }
3119
+ /**
3120
+ * Delivers the events recorded in one outbox table to the app's listeners.
3121
+ *
3122
+ * It claims a batch of due rows, runs each listener, and marks the row delivered.
3123
+ * A listener that throws is retried later with a growing delay, and parked as
3124
+ * dead after its attempts run out. Several dispatchers can share a table: on
3125
+ * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
3126
+ * finished within `claimTimeoutMs` (the process died) is taken by another.
3127
+ * Delivery is at least once, so a listener should tolerate running twice for the
3128
+ * same `deliveryId`.
3129
+ */
3130
+ var Dispatcher = class {
3131
+ db;
3132
+ table;
3133
+ listeners;
3134
+ onError;
3135
+ engine;
3136
+ options;
3137
+ inFlight = /* @__PURE__ */ new Set();
3138
+ timer;
3139
+ tickQueue;
3140
+ lastPurge = 0;
3141
+ constructor(db, table, listeners, options = {}, onError = (error) => console.error("[Brick-TS events]", error)) {
3142
+ this.db = db;
3143
+ this.table = table;
3144
+ this.listeners = listeners;
3145
+ this.onError = onError;
3146
+ this.engine = outboxEngine(table);
3147
+ this.options = resolveDispatchOptions(options);
3148
+ }
3149
+ /** Whether the dispatcher is looking for work on a timer. */
3150
+ get running() {
3151
+ return this.timer !== void 0;
3152
+ }
3153
+ /** Start looking for due deliveries on a timer. Does nothing if it already is. */
3154
+ start() {
3155
+ if (this.timer || !this.options.timer) return;
3156
+ this.timer = setInterval(() => void this.tick(), this.options.intervalMs);
3157
+ this.timer.unref?.();
3158
+ this.tick();
3159
+ }
3160
+ /**
3161
+ * Stop the timer and wait for the deliveries that are running to finish.
3162
+ */
3163
+ async stop() {
3164
+ if (this.timer) clearInterval(this.timer);
3165
+ this.timer = void 0;
3166
+ await this.tickQueue;
3167
+ await Promise.allSettled(this.inFlight);
3168
+ }
3169
+ /** Look for work soon, without waiting for the timer. Safe to call often. */
3170
+ notify() {
3171
+ if (!this.timer) return;
3172
+ setTimeout(() => void this.tick(), 0).unref?.();
3173
+ }
3174
+ /**
3175
+ * Claim what is due and run it, once. Used by the timer, and by tests and
3176
+ * workers that drive delivery themselves.
3177
+ *
3178
+ * @returns How many deliveries it started.
3179
+ */
3180
+ tick() {
3181
+ this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(() => this.claimAndRun(), () => this.claimAndRun());
3182
+ return this.tickQueue;
3183
+ }
3184
+ /**
3185
+ * Deliver everything that is due now and wait until those deliveries are done.
3186
+ * Deliveries that fail and are rescheduled are not waited for again.
3187
+ *
3188
+ * @returns How many deliveries it ran.
3189
+ */
3190
+ async drain() {
3191
+ let total = 0;
3192
+ for (;;) {
3193
+ const started = await this.tick();
3194
+ await Promise.allSettled(this.inFlight);
3195
+ if (started === 0) return total;
3196
+ total += started;
3197
+ }
3198
+ }
3199
+ /**
3200
+ * How many rows are in each state.
3201
+ */
3202
+ async counts() {
3203
+ const t = this.table;
3204
+ const rows = await this.db.select({
3205
+ status: t.status,
3206
+ count: sql`count(*)`
3207
+ }).from(t).groupBy(t.status);
3208
+ const counts = {
3209
+ pending: 0,
3210
+ claimed: 0,
3211
+ delivered: 0,
3212
+ dead: 0
3213
+ };
3214
+ for (const row of rows) counts[row.status] = Number(row.count);
3215
+ return counts;
3216
+ }
3217
+ /**
3218
+ * Put parked deliveries back in line, with their attempts reset.
3219
+ *
3220
+ * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
3221
+ * @returns How many deliveries were put back.
3222
+ */
3223
+ async retryDead(deliveryId) {
3224
+ const t = this.table;
3225
+ const rows = await this.db.update(t).set({
3226
+ status: "pending",
3227
+ attempts: 0,
3228
+ availableAt: /* @__PURE__ */ new Date()
3229
+ }).where(deliveryId ? and(eq(t.status, "dead"), eq(t.id, deliveryId)) : eq(t.status, "dead")).returning({ id: t.id });
3230
+ if (rows.length) this.notify();
3231
+ return rows.length;
3232
+ }
3233
+ async claimAndRun() {
3234
+ try {
3235
+ const room = this.options.batchSize - this.inFlight.size;
3236
+ if (room <= 0) return 0;
3237
+ const rows = await this.claim(room);
3238
+ for (const row of rows) {
3239
+ const run = this.deliver(row).finally(() => {
3240
+ this.inFlight.delete(run);
3241
+ });
3242
+ this.inFlight.add(run);
3243
+ }
3244
+ await this.purgeDelivered();
3245
+ return rows.length;
3246
+ } catch (error) {
3247
+ this.onError(error);
3248
+ return 0;
3249
+ }
3250
+ }
3251
+ async claim(limit) {
3252
+ const t = this.table;
3253
+ const now = /* @__PURE__ */ new Date();
3254
+ const stale = new Date(now.getTime() - this.options.claimTimeoutMs);
3255
+ const due = or(and(eq(t.status, "pending"), lte(t.availableAt, now)), and(eq(t.status, "claimed"), lt(t.claimedAt, stale)));
3256
+ const claimIn = async (tx) => {
3257
+ let select = tx.select().from(t).where(due).orderBy(asc(t.seq)).limit(limit);
3258
+ if (this.engine === "postgres") select = select.for("update", { skipLocked: true });
3259
+ const picked = await select;
3260
+ if (!picked.length) return [];
3261
+ await tx.update(t).set({
3262
+ status: "claimed",
3263
+ claimedAt: now,
3264
+ attempts: sql`${t.attempts} + 1`
3265
+ }).where(inArray(t.seq, picked.map((row) => row.seq)));
3266
+ return picked.map((row) => ({
3267
+ ...row,
3268
+ attempts: row.attempts + 1
3269
+ }));
3270
+ };
3271
+ return this.engine === "postgres" ? this.db.transaction(claimIn) : runInTransaction(this.db, claimIn);
3272
+ }
3273
+ async deliver(row) {
3274
+ const listener = this.listeners(row.listener);
3275
+ if (!listener) {
3276
+ await this.park(row, `No listener named '${row.listener}' is registered`);
3277
+ return;
3278
+ }
3279
+ const delivery = {
3280
+ id: row.eventId,
3281
+ name: row.name,
3282
+ payload: row.payload,
3283
+ occurredAt: row.occurredAt.toISOString(),
3284
+ ...row.traceId ? { traceId: row.traceId } : {},
3285
+ ...row.source ? { source: row.source } : {},
3286
+ listener: row.listener,
3287
+ deliveryId: row.id,
3288
+ attempt: row.attempts
3289
+ };
3290
+ try {
3291
+ await listener.run(delivery);
3292
+ } catch (error) {
3293
+ await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts, decideRetry(listener, error));
3294
+ return;
3295
+ }
3296
+ await this.markDelivered(row);
3297
+ }
3298
+ async markDelivered(row) {
3299
+ const t = this.table;
3300
+ try {
3301
+ if (this.options.retainDeliveredMs === 0) await this.db.delete(t).where(eq(t.seq, row.seq));
3302
+ else await this.db.update(t).set({
3303
+ status: "delivered",
3304
+ deliveredAt: /* @__PURE__ */ new Date(),
3305
+ lastError: null
3306
+ }).where(eq(t.seq, row.seq));
3307
+ } catch (error) {
3308
+ this.onError(error);
3309
+ }
3310
+ }
3311
+ async fail(row, error, maxAttempts, decision = "retry") {
3312
+ const message = error instanceof Error ? error.message : String(error);
3313
+ if (decision === "dead" || row.attempts >= maxAttempts) {
3314
+ await this.park(row, message);
3315
+ return;
3316
+ }
3317
+ const t = this.table;
3318
+ try {
3319
+ await this.db.update(t).set({
3320
+ status: "pending",
3321
+ lastError: message,
3322
+ claimedAt: null,
3323
+ availableAt: new Date(Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs))
3324
+ }).where(eq(t.seq, row.seq));
3325
+ } catch (writeError) {
3326
+ this.onError(writeError);
3327
+ }
3328
+ }
3329
+ async park(row, message) {
3330
+ const t = this.table;
3331
+ try {
3332
+ await this.db.update(t).set({
3333
+ status: "dead",
3334
+ lastError: message,
3335
+ claimedAt: null
3336
+ }).where(eq(t.seq, row.seq));
3337
+ } catch (error) {
3338
+ this.onError(error);
3339
+ }
3340
+ }
3341
+ async purgeDelivered() {
3342
+ const keep = this.options.retainDeliveredMs;
3343
+ const now = Date.now();
3344
+ if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;
3345
+ this.lastPurge = now;
3346
+ const t = this.table;
3347
+ await this.db.delete(t).where(and(eq(t.status, "delivered"), lt(t.deliveredAt, new Date(now - keep))));
3348
+ }
3349
+ };
3350
+ // src/events/id.ts
3351
+ const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
3352
+ function newEventId(now = Date.now()) {
3353
+ let time = "";
3354
+ let remaining = now;
3355
+ for (let index = 0; index < 10; index++) {
3356
+ time = ALPHABET[remaining % 32] + time;
3357
+ remaining = Math.floor(remaining / 32);
3358
+ }
3359
+ let random = "";
3360
+ for (const byte of crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))) random += ALPHABET[byte % 32];
3361
+ return `evt_${time}${random}`;
3362
+ }
3363
+ // src/events/workflows.ts
3364
+ /** `getQueueTopicPrefix("workflow")` from `@workflow/world`: the queue the runtime reads. */
3365
+ const WORKFLOW_QUEUE_PREFIX = "__wkf_workflow_";
3366
+ const BUNDLE_DIR = ".well-known/workflow/v1";
3367
+ const STOPPED = "The events were stopped, so workflows can no longer run";
3368
+ /** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */
3369
+ const WEBHOOK_ROUTE = "/.well-known/workflow/v1/webhook/*";
3370
+ /** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */
3371
+ const STEP_REGISTRY = Symbol.for("@workflow/core//registeredSteps");
3372
+ /**
3373
+ * Where the workflow bundle is read from, and the project it is built from.
3374
+ *
3375
+ * @param options - The `events.workflows` option.
3376
+ * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the
3377
+ * builder finds the SDK from where it writes, and skips only this directory when it
3378
+ * looks for workflows.
3379
+ */
3380
+ function resolveWorkflowPaths(options = {}) {
3381
+ const root = resolve(options.root ?? process.cwd());
3382
+ return {
3383
+ root,
3384
+ dir: join(root, BUNDLE_DIR)
3385
+ };
3386
+ }
3387
+ /**
3388
+ * Runs workflow listeners: wires the world into the Workflow SDK, serves the
3389
+ * built bundle from this process, and starts one run for each delivery.
3390
+ *
3391
+ * Nothing is loaded until it is needed, so an app without workflow listeners
3392
+ * never imports the SDK.
3393
+ */
3394
+ var WorkflowRuntime = class {
3395
+ world;
3396
+ listeners;
3397
+ deps;
3398
+ root;
3399
+ dir;
3400
+ ready;
3401
+ connected;
3402
+ closed = false;
3403
+ constructor(world, options, listeners, deps = {}) {
3404
+ this.world = world;
3405
+ this.listeners = listeners;
3406
+ this.deps = deps;
3407
+ ({root: this.root, dir: this.dir} = resolveWorkflowPaths(options));
3408
+ }
3409
+ /** Begin loading the runtime now rather than at the first delivery. */
3410
+ warmUp() {
3411
+ this.ensure().catch((error) => console.error(`[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`));
3412
+ }
3413
+ /**
3414
+ * Start the run for a delivery.
3415
+ *
3416
+ * The run is named after the delivery id, so a delivery that is tried again
3417
+ * finds the run it already started instead of starting another.
3418
+ *
3419
+ * @param listener - The workflow listener the delivery is for.
3420
+ * @param delivery - The delivery.
3421
+ * @returns The run id.
3422
+ */
3423
+ async startRun(listener, delivery) {
3424
+ const sdk = await this.ensure();
3425
+ const { attempt: _attempt, ...event } = delivery;
3426
+ return (await sdk.start(listener.workflow, [event], {
3427
+ world: this.world,
3428
+ runKey: delivery.deliveryId,
3429
+ runKeyTime: Date.parse(delivery.occurredAt)
3430
+ })).runId;
3431
+ }
3432
+ /**
3433
+ * Answer a request to a webhook a workflow created with `createWebhook`, by
3434
+ * resuming the workflow that waits on it. Needs the world but not the queue
3435
+ * consumer, so a process that only records events (`dispatch: false`) serves
3436
+ * webhooks too.
3437
+ *
3438
+ * @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.
3439
+ * @returns The response the bundle's webhook handler gives.
3440
+ */
3441
+ async handleWebhook(request) {
3442
+ await this.connect();
3443
+ const file = join(this.dir, "webhook.mjs");
3444
+ if (!existsSync(file)) throw new Error(`No webhook bundle at ${file}. brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.`);
3445
+ const handler = (await import(pathToFileURL(file).href))[request.method];
3446
+ if (typeof handler !== "function") return new Response(null, { status: 405 });
3447
+ return handler(request);
3448
+ }
3449
+ /** Stop the world. The runtime cannot be started again afterwards. */
3450
+ async close() {
3451
+ this.closed = true;
3452
+ await this.ready?.catch(() => {});
3453
+ await this.connected?.catch(() => {});
3454
+ await this.world.close?.();
3455
+ }
3456
+ ensure() {
3457
+ if (this.closed) return Promise.reject(/* @__PURE__ */ new Error(STOPPED));
3458
+ this.ready ??= this.initialize().catch((error) => {
3459
+ this.ready = void 0;
3460
+ throw error;
3461
+ });
3462
+ return this.ready;
3463
+ }
3464
+ /** Load the SDK and give it the world: all a webhook needs. */
3465
+ connect() {
3466
+ if (this.closed) return Promise.reject(/* @__PURE__ */ new Error(STOPPED));
3467
+ this.connected ??= this.loadSdk().then((sdk) => {
3468
+ sdk.setWorld(this.world);
3469
+ return sdk;
3470
+ }).catch((error) => {
3471
+ this.connected = void 0;
3472
+ throw error;
3473
+ });
3474
+ return this.connected;
3475
+ }
3476
+ async initialize() {
3477
+ if (typeof this.world.createRunId !== "function") throw new Error("This world cannot name a run after its key, so an event delivered twice would start two runs. Use the world from @brickkit/redis-world or @brickkit/bullmq-world.");
3478
+ const sdk = await this.connect();
3479
+ const flow = join(this.dir, "flow.mjs");
3480
+ if (!existsSync(flow)) throw new Error(`No workflow bundle at ${flow}. brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.`);
3481
+ const manifest = this.readManifest();
3482
+ const depsOf = this.checkListeners(manifest);
3483
+ const bundle = await this.loadBundle(flow);
3484
+ if (typeof bundle.POST !== "function") throw new Error(`${flow} does not export a POST handler`);
3485
+ const post = bundle.POST;
3486
+ this.world.registerHandler?.(WORKFLOW_QUEUE_PREFIX, (request) => {
3487
+ const queue = request.headers.get("x-vqs-queue-name") ?? "";
3488
+ return runWithDeps(depsOf.get(queue.slice(15)) ?? this.deps, () => post(request));
3489
+ });
3490
+ await this.world.start?.();
3491
+ return sdk;
3492
+ }
3493
+ async loadSdk() {
3494
+ const from = createRequire(join(this.root, "package.json"));
3495
+ const load = async (specifier) => {
3496
+ let path;
3497
+ try {
3498
+ path = from.resolve(specifier);
3499
+ } catch {
3500
+ throw new Error(`The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`);
3501
+ }
3502
+ return import(pathToFileURL(path).href);
3503
+ };
3504
+ const [api, runtime] = await Promise.all([load("workflow/api"), load("workflow/runtime")]);
3505
+ return {
3506
+ start: api.start,
3507
+ setWorld: runtime.setWorld
3508
+ };
3509
+ }
3510
+ /**
3511
+ * The bundle holds its own copy of every step and registers them all when it
3512
+ * loads, replacing the ones the app registered. A copy has its own module state:
3513
+ * a step would find no database connection, no config, none of what the app set
3514
+ * up. So the app's steps are put back, and the bundle's copies serve only the
3515
+ * steps the app never loaded.
3516
+ */
3517
+ async loadBundle(flow) {
3518
+ const registry = () => globalThis[STEP_REGISTRY];
3519
+ const app = new Map(registry());
3520
+ const bundle = await import(pathToFileURL(flow).href);
3521
+ const registered = registry();
3522
+ if (registered) for (const [id, step] of app) registered.set(id, step);
3523
+ return bundle;
3524
+ }
3525
+ readManifest() {
3526
+ const path = join(this.dir, "manifest.json");
3527
+ if (!existsSync(path)) return void 0;
3528
+ return JSON.parse(readFileSync(path, "utf8"));
3529
+ }
3530
+ /**
3531
+ * A listener's workflow must carry the id the transform gives it, and the bundle
3532
+ * must know that id: a function that was never transformed, or a bundle built
3533
+ * before the workflow existed, would fail on its first delivery with a less
3534
+ * helpful message.
3535
+ *
3536
+ * @returns The deps each workflow's steps run with, by workflow id.
3537
+ * @throws When one workflow is run by listeners with different deps (an app
3538
+ * and a plugin, or two plugin installs): its steps could see only one set.
3539
+ */
3540
+ checkListeners(manifest) {
3541
+ const depsOf = /* @__PURE__ */ new Map();
3542
+ const known = /* @__PURE__ */ new Set();
3543
+ for (const file of Object.values(manifest?.workflows ?? {})) for (const entry of Object.values(file)) if (entry.workflowId) known.add(entry.workflowId);
3544
+ for (const listener of this.listeners) {
3545
+ const id = listener.workflow?.workflowId;
3546
+ if (typeof id !== "string") throw new Error(`The workflow of listener '${listener.name}' was not transformed. Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.`);
3547
+ if (manifest && !known.has(id)) throw new Error(`The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`);
3548
+ const deps = listener[PLUGIN_DEPS] ?? this.deps;
3549
+ if ((depsOf.get(id) ?? deps) !== deps) throw new Error(`Workflow '${id}' is run by listeners with different deps (listener '${listener.name}'); give each app or plugin install its own workflow.`);
3550
+ depsOf.set(id, deps);
3551
+ }
3552
+ return depsOf;
3553
+ }
3554
+ };
3555
+ // src/events/hub.ts
3556
+ function matchesEvent(pattern, name) {
3557
+ if (pattern === "*") return true;
3558
+ if (pattern.endsWith("*")) return name.startsWith(pattern.slice(0, -1));
3559
+ return pattern === name;
3560
+ }
3561
+ /** The recorder of each service database, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */
3562
+ const recorders = /* @__PURE__ */ new WeakMap();
3563
+ const startedHubs = globalThis[Symbol.for("brickkit.events.started")] ??= /* @__PURE__ */ new Set();
3564
+ /**
3565
+ * Stop every events hub started in this process, by any copy of `@brickkit/core`,
3566
+ * and wait for their deliveries. A hub that fails to stop does not cut the wait
3567
+ * for the others: the first failure is thrown once every hub is done.
3568
+ */
3569
+ async function stopAllEvents() {
3570
+ const failed = (await Promise.allSettled([...startedHubs].map((hub) => hub.stop()))).find((result) => result.status === "rejected");
3571
+ if (failed) throw failed.reason;
3572
+ }
3573
+ /**
3574
+ * The events of one app: who listens, where events are recorded, and the
3575
+ * dispatchers that deliver them. `brick({ events })` makes one and puts it on
3576
+ * `app.events`.
3577
+ */
3578
+ var EventsHub = class {
3579
+ deps;
3580
+ byName = /* @__PURE__ */ new Map();
3581
+ dispatchers = /* @__PURE__ */ new Map();
3582
+ deliverables = /* @__PURE__ */ new Map();
3583
+ dispatchOptions;
3584
+ runtime;
3585
+ recorderNames = [];
3586
+ started = false;
3587
+ stopping;
3588
+ /**
3589
+ * @param options - The `events` option.
3590
+ * @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
3591
+ * listeners and workflow steps.
3592
+ */
3593
+ constructor(options, deps = {}) {
3594
+ this.deps = deps;
3595
+ for (const listener of options.listeners ?? []) {
3596
+ if (typeof listener.name !== "string" || !listener.name) throw new Error("An event listener needs a name");
3597
+ if (listener.name.includes(":")) throw new Error(`Event listener name '${listener.name}' must not contain ':'`);
3598
+ if (!listener.on?.length) throw new Error(`Event listener '${listener.name}' listens for nothing`);
3599
+ if (this.byName.has(listener.name)) throw new Error(`Duplicate event listener '${listener.name}'`);
3600
+ if (!listener.run === !listener.workflow) throw new Error(`Event listener '${listener.name}' needs exactly one of run and workflow`);
3601
+ this.byName.set(listener.name, listener);
3602
+ }
3603
+ const workflowListeners = [...this.byName.values()].filter((listener) => listener.workflow);
3604
+ if (workflowListeners.length) {
3605
+ if (!options.world) throw new Error(`Event listener '${workflowListeners[0].name}' runs a workflow, so events needs a world: brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.`);
3606
+ this.runtime = new WorkflowRuntime(options.world, options.workflows, workflowListeners, deps);
3607
+ }
3608
+ this.dispatchOptions = options.dispatch === false ? false : options.dispatch === true || options.dispatch === void 0 ? {} : options.dispatch;
3609
+ }
3610
+ /**
3611
+ * Give each service whose database holds an outbox table a recorder, and a
3612
+ * dispatcher for that table. Call it before the first request: a service has no
3613
+ * recorder until then.
3614
+ *
3615
+ * @param services - The app's services.
3616
+ * @returns The hub, for chaining.
3617
+ */
3618
+ attach(services) {
3619
+ let attached = 0;
3620
+ for (const service of services) {
3621
+ const table = service.getOutbox?.();
3622
+ if (!table) continue;
3623
+ attached++;
3624
+ this.recorderNames.push(service.name);
3625
+ const bound = this.bind(table, (name, payload) => service.checkEvent?.(name, payload));
3626
+ service.setRecorder?.(bound);
3627
+ const db = service.getDb();
3628
+ if (db && typeof db === "object") recorders.set(db, bound);
3629
+ }
3630
+ if (attached === 0 && this.byName.size > 0) console.warn("[Brick-TS] events are configured, but no service database has an outbox table. Add outboxTable() to a database's tables so its writes can record events.");
3631
+ for (const service of services) {
3632
+ const table = service.getOutbox?.();
3633
+ if (table && !this.dispatchers.has(table)) this.dispatchers.set(table, new Dispatcher(service.getDb(), table, (name) => this.deliverable(name), this.dispatchOptions || {}));
3634
+ }
3635
+ return this;
3636
+ }
3637
+ /** The listeners that want an event. */
3638
+ matching(name) {
3639
+ const found = [];
3640
+ for (const listener of this.byName.values()) if (listener.on.some((pattern) => matchesEvent(pattern, name))) found.push(listener);
3641
+ return found;
3642
+ }
3643
+ /** The listeners and settings, as plain data. */
3644
+ describe() {
3645
+ return {
3646
+ listeners: [...this.byName.values()].map((listener) => ({
3647
+ name: listener.name,
3648
+ on: [...listener.on],
3649
+ kind: listener.workflow ? "workflow" : "handler"
3650
+ })),
3651
+ dispatch: this.dispatchOptions !== false,
3652
+ recorders: [...this.recorderNames]
3653
+ };
3654
+ }
3655
+ /**
3656
+ * Where the workflow bundle is read from, the project it is built from, and
3657
+ * the world the workflows run on. Only set when a listener runs a workflow.
3658
+ * The CLI builds the bundle there before events start, and shows the world's
3659
+ * runs in the dev dashboard.
3660
+ */
3661
+ get workflows() {
3662
+ return this.runtime && {
3663
+ root: this.runtime.root,
3664
+ dir: this.runtime.dir,
3665
+ world: this.runtime.world
3666
+ };
3667
+ }
3668
+ /**
3669
+ * Resume the workflow that waits on a webhook. The server mounts this on the
3670
+ * route the Workflow SDK puts in webhook URLs.
3671
+ */
3672
+ webhook(request) {
3673
+ if (!this.runtime) throw new Error("No listener of this app runs a workflow");
3674
+ return this.runtime.handleWebhook(request);
3675
+ }
3676
+ /**
3677
+ * Start delivering recorded events from this process, and start the world that
3678
+ * runs workflow listeners. Does nothing if this process only records events
3679
+ * (`dispatch: false`), already started, or a stop is still waiting.
3680
+ */
3681
+ start() {
3682
+ if (this.dispatchOptions === false || this.started || this.stopping) return;
3683
+ this.started = true;
3684
+ startedHubs.add(this);
3685
+ this.runtime?.warmUp();
3686
+ for (const dispatcher of this.dispatchers.values()) dispatcher.start();
3687
+ }
3688
+ /**
3689
+ * Stop delivering, wait for the deliveries that are running, and close the
3690
+ * world. A world cannot be started again, so workflow listeners stop for good.
3691
+ * A stop that arrives while another runs waits for that one.
3692
+ */
3693
+ stop() {
3694
+ return this.stopping ??= this.shutDown().finally(() => {
3695
+ this.stopping = void 0;
3696
+ startedHubs.delete(this);
3697
+ });
3698
+ }
3699
+ async shutDown() {
3700
+ this.started = false;
3701
+ await Promise.all([...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()));
3702
+ await this.runtime?.close();
3703
+ }
3704
+ /**
3705
+ * Deliver everything that is due now and wait for it. For tests and for
3706
+ * workers that drive delivery themselves.
3707
+ *
3708
+ * @returns How many deliveries ran.
3709
+ */
3710
+ async drain() {
3711
+ let total = 0;
3712
+ for (const dispatcher of this.dispatchers.values()) total += await dispatcher.drain();
3713
+ return total;
3714
+ }
3715
+ /** How many rows are in each state, across the app's outbox tables. */
3716
+ async counts() {
3717
+ const total = {
3718
+ pending: 0,
3719
+ claimed: 0,
3720
+ delivered: 0,
3721
+ dead: 0
3722
+ };
3723
+ for (const dispatcher of this.dispatchers.values()) {
3724
+ const counts = await dispatcher.counts();
3725
+ for (const status of Object.keys(total)) total[status] += counts[status];
3726
+ }
3727
+ return total;
3728
+ }
3729
+ /**
3730
+ * Put parked deliveries back in line.
3731
+ *
3732
+ * @param deliveryId - One delivery. Omit it to retry every dead one.
3733
+ * @returns How many deliveries were put back.
3734
+ */
3735
+ async retryDead(deliveryId) {
3736
+ let total = 0;
3737
+ for (const dispatcher of this.dispatchers.values()) total += await dispatcher.retryDead(deliveryId);
3738
+ return total;
3739
+ }
3740
+ deliverable(name) {
3741
+ const listener = this.byName.get(name);
3742
+ if (!listener) return void 0;
3743
+ let found = this.deliverables.get(name);
3744
+ if (!found) {
3745
+ const runtime = this.runtime;
3746
+ found = {
3747
+ ...listener.errors ? { errors: listener.errors } : {},
3748
+ ...listener.retry ? { retry: listener.retry } : {},
3749
+ ...listener.workflow ? {
3750
+ ...listener.maxAttempts !== void 0 ? { maxAttempts: listener.maxAttempts } : {},
3751
+ run: async (delivery) => {
3752
+ await runtime.startRun(listener, delivery);
3753
+ }
3754
+ } : {
3755
+ ...listener.maxAttempts !== void 0 ? { maxAttempts: listener.maxAttempts } : {},
3756
+ run: (delivery) => runWithDeps(this.deps, () => listener.run(delivery))
3757
+ }
3758
+ };
3759
+ this.deliverables.set(name, found);
3760
+ }
3761
+ return found;
3762
+ }
3763
+ bind(table, check) {
3764
+ const startAndNotify = () => {
3765
+ this.start();
3766
+ this.dispatchers.get(table)?.notify();
3767
+ };
3768
+ const insert = async (tx, context, name, payload) => {
3769
+ check(name, payload);
3770
+ const listeners = this.matching(name);
3771
+ if (!listeners.length) return false;
3772
+ const eventId = newEventId();
3773
+ const occurredAt = /* @__PURE__ */ new Date();
3774
+ await tx.insert(table).values(listeners.map((listener) => ({
3775
+ id: `${eventId}:${listener.name}`,
3776
+ eventId,
3777
+ listener: listener.name,
3778
+ name,
3779
+ payload,
3780
+ traceId: context.traceId ?? null,
3781
+ source: context.source ?? null,
3782
+ occurredAt,
3783
+ status: "pending",
3784
+ attempts: 0,
3785
+ availableAt: occurredAt
3786
+ })));
3787
+ return true;
3788
+ };
3789
+ return {
3790
+ wants: (name) => this.matching(name).length > 0,
3791
+ transaction: async (db, context, fn) => {
3792
+ let recorded = false;
3793
+ const result = await runInTransaction(db, async (tx) => {
3794
+ const record = async (name, payload) => {
3795
+ if (await insert(tx, context, name, payload)) recorded = true;
3796
+ };
3797
+ return fn(tx, record);
3798
+ });
3799
+ if (recorded) startAndNotify();
3800
+ return result;
3801
+ },
3802
+ record: async (tx, context, name, payload) => {
3803
+ await insert(tx, context, name, payload);
3804
+ }
3805
+ };
3806
+ }
3807
+ };
3808
+ // src/socket.ts
3809
+ var SocketDenied = class extends Error {};
3810
+ const bytes = (value) => new TextEncoder().encode(value).byteLength;
3811
+ /** Validates and serializes one output message, rechecking what survives JSON. */
3812
+ function outputFrame(output, event, data) {
3813
+ const schema = Object.hasOwn(output, event) ? output[event] : void 0;
3814
+ if (!schema || !getCompiledCheck(schema).Check(data)) throw new Error("Invalid socket output");
3815
+ const frame = JSON.stringify({
3816
+ event,
3817
+ data
3818
+ });
3819
+ if (bytes(frame) > 65536) throw new Error("Socket output too large");
3820
+ if (!getCompiledCheck(schema).Check(JSON.parse(frame).data)) throw new Error("Socket output is not JSON-compatible");
3821
+ return frame;
3822
+ }
3823
+ /** Delivers within this process. The default broker of every app. */
3824
+ function localBroker() {
3825
+ const topics = /* @__PURE__ */ new Map();
3826
+ const epoch = Date.now();
3827
+ let counter = 0;
3828
+ /** Rooms dropped from `kept` once idle, at counter values up to this. */
3829
+ let swept = 0;
3830
+ const kept = /* @__PURE__ */ new Map();
3831
+ const prune = (names) => {
3832
+ for (const topic of names) {
3833
+ const room = kept.get(topic);
3834
+ if (!room) continue;
3835
+ const oldest = Date.now() - room.maxAgeMs;
3836
+ while (room.entries[0] && room.entries[0].at < oldest) room.trimmed = room.entries.shift().n;
3837
+ if (!room.entries.length) {
3838
+ kept.delete(topic);
3839
+ swept = counter;
3840
+ }
3841
+ }
3842
+ };
3843
+ return {
3844
+ publish(message, replay) {
3845
+ if (message.type === "emit" && replay) {
3846
+ const n = ++counter;
3847
+ message = {
3848
+ ...message,
3849
+ seq: `${epoch}-${n}`
3850
+ };
3851
+ const room = kept.get(message.topic) ?? {
3852
+ entries: [],
3853
+ trimmed: 0,
3854
+ maxAgeMs: replay.maxAgeMs
3855
+ };
3856
+ kept.set(message.topic, room);
3857
+ room.entries.push({
3858
+ n,
3859
+ at: Date.now(),
3860
+ message
3861
+ });
3862
+ if (room.entries.length > replay.keep) room.trimmed = room.entries.shift().n;
3863
+ if (n % 1e3 === 0) prune([...kept.keys()]);
3864
+ }
3865
+ for (const deliver of topics.get(message.topic) ?? []) deliver(message);
3866
+ },
3867
+ head: () => `${epoch}-${counter}`,
3868
+ history(topic, since) {
3869
+ const [from, n] = since.split("-").map(Number);
3870
+ if (from !== epoch || n > counter) return void 0;
3871
+ prune([topic]);
3872
+ const room = kept.get(topic);
3873
+ if (!room) return n >= swept ? [] : void 0;
3874
+ if (n < room.trimmed) return void 0;
3875
+ return room.entries.filter((entry) => entry.n > n).map((entry) => entry.message);
3876
+ },
3877
+ subscribe(topic, deliver) {
3878
+ const listeners = topics.get(topic) ?? /* @__PURE__ */ new Set();
3879
+ listeners.add(deliver);
3880
+ topics.set(topic, listeners);
3881
+ return () => {
3882
+ listeners.delete(deliver);
3883
+ if (!listeners.size) topics.delete(topic);
3884
+ };
3885
+ }
3886
+ };
3887
+ }
3888
+ function defineServiceSocket(service, config, resolve) {
3889
+ if (!config.name || config.name.split(".").some((part) => !/^[a-zA-Z_][\w-]*$/.test(part))) throw new Error("Invalid socket name");
3890
+ if (config.path !== void 0 && (!config.path.startsWith("/") || /[?#*]/.test(config.path) || config.path.split("/").some((segment) => segment.startsWith(":")))) throw new Error("Socket path must be a static route (relative to its service) without a query or fragment");
3891
+ const input = Object.freeze({ ...config.input });
3892
+ const output = Object.freeze({ ...config.output });
3893
+ const handlers = { ...config.handlers };
3894
+ if (Object.keys(input).length !== Object.keys(handlers).length || Object.keys(input).some((key) => !Object.hasOwn(handlers, key) || typeof handlers[key] !== "function")) throw new Error("Every socket input event needs exactly one handler");
3895
+ if ([...Object.keys(input), ...Object.keys(output)].some((key) => key.startsWith("$"))) throw new Error("Socket event names starting with $ are reserved");
3896
+ const maxRooms = config.maxRooms ?? 100;
3897
+ if (!Number.isInteger(maxRooms) || maxRooms < 1) throw new Error("Socket maxRooms must be a positive integer");
3898
+ const replay = config.replay && { ...config.replay };
3899
+ if (replay && !(Number.isInteger(replay.keep) && replay.keep > 0 && replay.maxAgeMs > 0 && Number.isFinite(replay.maxAgeMs))) throw new Error("Socket replay needs a positive integer keep and a positive finite maxAgeMs");
3900
+ for (const schema of [...Object.values(input), ...Object.values(output)]) {
3901
+ serializeSocketSchema(schema);
3902
+ getCompiledCheck(schema);
3903
+ }
3904
+ const typed = (socket) => socket;
3905
+ const error = buildErrorHelpers(config.errors);
3906
+ const context = async (request) => {
3907
+ const ctx = await resolve(request);
3908
+ if (config.authorize && !await config.authorize({ ctx })) throw new SocketDenied();
3909
+ return ctx;
3910
+ };
3911
+ const topicPrefix = `${service}.${config.name}:`;
3912
+ const topic = (room) => {
3913
+ if (!isSocketRoom(room)) throw new Error(`Invalid socket room: ${room}`);
3914
+ return topicPrefix + room;
3915
+ };
3916
+ const brokers = /* @__PURE__ */ new Set();
3917
+ const publish = (messages, after) => {
3918
+ const send = () => {
3919
+ for (const broker of brokers) for (const message of messages) broker.publish(message, replay);
3920
+ };
3921
+ if (after === void 0) return send();
3922
+ if (!inTransaction(after)) throw new Error("Socket emit { after: tx } needs a tx from runInTransaction(db, (tx) => ...); a plain db.transaction() is not tracked, so the emit could be sent for a write that rolls back");
3923
+ onTransactionCommit(after, send);
3924
+ };
3925
+ return {
3926
+ schema: {
3927
+ name: config.name,
3928
+ path: config.path,
3929
+ description: config.description,
3930
+ input: Object.keys(input),
3931
+ output: Object.keys(output),
3932
+ hasAuthorize: !!config.authorize
3933
+ },
3934
+ input,
3935
+ output,
3936
+ ...config.errors ? { errors: { ...config.errors } } : {},
3937
+ allowedOrigins: config.allowedOrigins ? [...config.allowedOrigins] : void 0,
3938
+ allowMissingOrigin: config.allowMissingOrigin,
3939
+ maxRooms,
3940
+ replay,
3941
+ brokers,
3942
+ topicPrefix,
3943
+ topic,
3944
+ handle: {
3945
+ name: config.name,
3946
+ emit(rooms, ...[event, payload, options]) {
3947
+ const topics = [...new Set(typeof rooms === "string" ? [rooms] : rooms)].map(topic);
3948
+ const frame = outputFrame(output, event, payload);
3949
+ if (replay && bytes(frame) > 65236) throw new Error("Socket output too large");
3950
+ publish(topics.map((topic) => ({
3951
+ type: "emit",
3952
+ topic,
3953
+ frame
3954
+ })), options?.after);
3955
+ },
3956
+ kick(room, options = {}) {
3957
+ publish([{
3958
+ type: "kick",
3959
+ topic: topic(room),
3960
+ ...options.also !== void 0 ? { also: topic(options.also) } : {},
3961
+ ...options.reason !== void 0 ? { reason: String(options.reason) } : {}
3962
+ }], void 0);
3963
+ }
3964
+ },
3965
+ async connect(request) {
3966
+ const initial = await context(request);
3967
+ const rooms = [...new Set(config.rooms ? await config.rooms({ ctx: initial }) : [])];
3968
+ rooms.forEach(topic);
3969
+ if (rooms.length > maxRooms) throw new Error("Too many socket rooms");
3970
+ return {
3971
+ rooms,
3972
+ async open(socket) {
3973
+ await config.open?.({
3974
+ ctx: initial,
3975
+ socket: typed(socket)
3976
+ });
3977
+ },
3978
+ async message(event, data, socket) {
3979
+ const schema = Object.hasOwn(input, event) ? input[event] : void 0;
3980
+ if (!schema || !getCompiledCheck(schema).Check(data)) throw new SocketDenied();
3981
+ const ctx = await context(request);
3982
+ if (!socket.isOpen) return;
3983
+ const handler = handlers[event];
3984
+ await handler({
3985
+ input: data,
3986
+ ctx,
3987
+ socket: typed(socket),
3988
+ error
3989
+ });
3990
+ },
3991
+ async join(room) {
3992
+ const ctx = await context(request);
3993
+ return !!config.join && await config.join({
3994
+ ctx,
3995
+ room
3996
+ });
3997
+ },
3998
+ async close(socket, code, reason) {
3999
+ await config.close?.({
4000
+ ctx: initial,
4001
+ socket: typed(socket),
4002
+ code,
4003
+ reason
4004
+ });
4005
+ }
4006
+ };
4007
+ }
4008
+ };
4009
+ }
4010
+ /** `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */
4011
+ function socketPath(prefix, service, socket) {
4012
+ return joinRoute(ownerPath(prefix, service), socket.schema.path ?? `/${kebabCase(socket.schema.name)}`);
4013
+ }
4014
+ /** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */
4015
+ function publicOrigin(request) {
4016
+ const forwarded = (name) => request.headers.get(name)?.split(",")[0]?.trim() || void 0;
4017
+ const url = new URL(request.url);
4018
+ const proto = forwarded("x-forwarded-proto");
4019
+ return `${proto ? `${proto}:` : url.protocol}//${forwarded("x-forwarded-host") ?? url.host}`;
4020
+ }
4021
+ const TOKEN_PROTOCOL = "brick.token.";
4022
+ const protocols = (request) => (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((protocol) => protocol.trim()).filter(Boolean);
4023
+ /** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */
4024
+ function tokenRequest(request) {
4025
+ const offered = protocols(request);
4026
+ const token = offered.find((protocol) => protocol.startsWith(TOKEN_PROTOCOL))?.slice(12);
4027
+ if (!token) return {
4028
+ token: false,
4029
+ request
4030
+ };
4031
+ const headers = new Headers(request.headers);
4032
+ headers.set("authorization", `Bearer ${token}`);
4033
+ const rest = offered.filter((protocol) => !protocol.startsWith(TOKEN_PROTOCOL));
4034
+ if (rest.length) headers.set("sec-websocket-protocol", rest.join(", "));
4035
+ else headers.delete("sec-websocket-protocol");
4036
+ return {
4037
+ token: true,
4038
+ request: new Request(request.url, {
4039
+ method: request.method,
4040
+ headers
4041
+ })
4042
+ };
4043
+ }
4044
+ /** Mounts native adapters. Each connection owns its queue and service session. */
4045
+ function mountSockets(app, sockets, broker, secret) {
4046
+ if (secret === "") throw new Error("Brick: sockets.secret can't be empty");
4047
+ const key = secret ?? randomBytes(32);
4048
+ const signature = (topic, seq) => createHmac("sha256", key).update(`${topic}\n${seq}`).digest("base64url").slice(0, 22);
4049
+ const sign = (topic, seq) => `${seq}.${signature(topic, seq)}`;
4050
+ const verify = (topic, signed) => {
4051
+ const [seq, sig] = signed.split(".");
4052
+ return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq))) ? seq : void 0;
4053
+ };
4054
+ if (sockets.some(({ definition }) => definition.replay) && !(broker.head && broker.history)) throw new Error("Brick: the socket broker does not support replay");
4055
+ for (const { definition } of sockets) definition.brokers.add(broker);
4056
+ app.onStop(async () => {
4057
+ for (const { definition } of sockets) definition.brokers.delete(broker);
4058
+ await broker.close?.();
4059
+ });
4060
+ if (!sockets.length) return;
4061
+ app.use(websocket({
4062
+ maxPayloadLength: SOCKET_MAX_BYTES,
4063
+ backpressureLimit: SOCKET_BUFFER_BYTES,
4064
+ closeOnBackpressureLimit: true
4065
+ }));
4066
+ for (const { service, path, definition } of sockets) {
4067
+ const logger = createLogger(`[Brick socket ${service}.${definition.schema.name}]`);
4068
+ const sessions = /* @__PURE__ */ new WeakMap();
4069
+ const connections = /* @__PURE__ */ new WeakMap();
4070
+ const roomOf = (topic) => topic.slice(definition.topicPrefix.length);
4071
+ const holders = /* @__PURE__ */ new Map();
4072
+ const control = (ws, event, data) => {
4073
+ if (ws.readyState === 1) ws.send(JSON.stringify({
4074
+ event,
4075
+ data
4076
+ }));
4077
+ };
4078
+ /** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */
4079
+ const enter = async (connection, topic, live = true) => {
4080
+ if (connection.rooms.has(topic)) return;
4081
+ connection.rooms.add(topic);
4082
+ if (live) connection.ws.subscribe(topic);
4083
+ let holder = holders.get(topic);
4084
+ if (!holder) {
4085
+ holder = {
4086
+ connections: /* @__PURE__ */ new Set(),
4087
+ unsubscribe: () => {}
4088
+ };
4089
+ holders.set(topic, holder);
4090
+ holder.unsubscribe = broker.subscribe(topic, deliver);
4091
+ }
4092
+ holder.connections.add(connection);
4093
+ await broker.ready?.(topic).catch(() => {});
4094
+ };
4095
+ const exit = (connection, topic) => {
4096
+ if (!connection.rooms.delete(topic)) return;
4097
+ connection.requested.delete(topic);
4098
+ if (connection.ws.readyState === 1) connection.ws.unsubscribe(topic);
4099
+ const holder = holders.get(topic);
4100
+ if (!holder?.connections.delete(connection) || holder.connections.size) return;
4101
+ holders.delete(topic);
4102
+ holder.unsubscribe();
4103
+ };
4104
+ /** A replayable emit carries its room and sequence. */
4105
+ const frameOf = (message) => message.seq === void 0 ? message.frame : `${message.frame.slice(0, -1)},"room":${JSON.stringify(roomOf(message.topic))},"seq":${JSON.stringify(sign(message.topic, message.seq))}}`;
4106
+ const deliver = (message) => {
4107
+ if (message.type === "emit") {
4108
+ app.server?.publish(message.topic, frameOf(message));
4109
+ return;
4110
+ }
4111
+ for (const connection of holders.get(message.topic)?.connections ?? []) {
4112
+ if (message.also && !connection.ws.isSubscribed(message.also)) continue;
4113
+ exit(connection, message.topic);
4114
+ control(connection.ws, "$left", {
4115
+ room: roomOf(message.topic),
4116
+ ...message.reason !== void 0 ? { reason: message.reason } : {}
4117
+ });
4118
+ }
4119
+ };
4120
+ /** `$join` and `$leave`, acknowledged with the same event. */
4121
+ const room = async (connection, event, data) => {
4122
+ const { room: name, since } = data && typeof data === "object" ? data : {};
4123
+ if (!isSocketRoom(name) || since !== void 0 && !isSocketSeq(since)) throw new SocketDenied();
4124
+ const topic = definition.topic(name);
4125
+ if (event === "$leave") {
4126
+ if (connection.requested.has(topic)) exit(connection, topic);
4127
+ control(connection.ws, "$leave", { room: name });
4128
+ return;
4129
+ }
4130
+ const isOpen = () => !connection.closed && connection.ws.readyState === 1;
4131
+ const ok = connection.rooms.has(topic) || connection.rooms.size < definition.maxRooms && await connection.session.join(name);
4132
+ if (!isOpen()) return;
4133
+ const replay = definition.replay;
4134
+ let seq;
4135
+ if (ok && !connection.rooms.has(topic)) {
4136
+ const entered = enter(connection, topic, !replay);
4137
+ connection.requested.add(topic);
4138
+ await entered;
4139
+ if (replay && connection.rooms.has(topic)) {
4140
+ const start = since === void 0 ? await broker.head(topic) : verify(topic, since);
4141
+ const missed = start === void 0 ? void 0 : await broker.history(topic, start, replay);
4142
+ const restart = missed ? void 0 : await broker.head(topic);
4143
+ if (!isOpen()) return;
4144
+ if (connection.rooms.has(topic)) {
4145
+ connection.ws.subscribe(topic);
4146
+ if (since === void 0) seq = sign(topic, start);
4147
+ for (const message of missed ?? []) if (message.type === "emit") connection.ws.send(frameOf(message));
4148
+ if (restart !== void 0) control(connection.ws, "$gap", {
4149
+ room: name,
4150
+ seq: sign(topic, restart)
4151
+ });
4152
+ }
4153
+ }
4154
+ }
4155
+ control(connection.ws, "$join", {
4156
+ room: name,
4157
+ ok: ok && connection.rooms.has(topic),
4158
+ ...seq !== void 0 ? { seq } : {}
4159
+ });
4160
+ };
4161
+ const raisable = buildErrorHelpers(definition.errors);
4162
+ const fail = (ws, error) => {
4163
+ if (!(error instanceof SocketDenied)) logger.error({
4164
+ error,
4165
+ service,
4166
+ socket: definition.schema.name
4167
+ });
4168
+ if (ws.readyState !== 1) return;
4169
+ ws.close(error instanceof SocketDenied ? 1008 : 1011, error instanceof SocketDenied ? "Message refused" : "Socket handler failed");
4170
+ };
4171
+ app.ws(path, {
4172
+ async beforeHandle({ request }) {
4173
+ if (sessions.has(request)) return;
4174
+ const { token, request: resolved } = tokenRequest(request);
4175
+ const origin = request.headers.get("origin");
4176
+ if (origin ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(origin) : !(definition.allowMissingOrigin ?? token)) return new Response("Socket origin refused", { status: 403 });
4177
+ try {
4178
+ sessions.set(request, await definition.connect(resolved));
4179
+ } catch (error) {
4180
+ if (!(error instanceof SocketDenied)) logger.error({
4181
+ error,
4182
+ service,
4183
+ socket: definition.schema.name
4184
+ });
4185
+ return new Response("Socket connection refused", { status: error instanceof SocketDenied ? 403 : 500 });
4186
+ }
4187
+ },
4188
+ upgrade: ({ request }) => protocols(request).includes("brick.v1") ? { "Sec-WebSocket-Protocol": "brick.v1" } : void 0,
4189
+ async open(ws) {
4190
+ const session = sessions.get(ws.request);
4191
+ if (!session) {
4192
+ ws.close(1011, "Missing socket session");
4193
+ return;
4194
+ }
4195
+ const sender = {
4196
+ get isOpen() {
4197
+ return !state.closed && ws.readyState === 1;
4198
+ },
4199
+ close() {
4200
+ ws.close(1e3, "");
4201
+ },
4202
+ send(event, data) {
4203
+ if (!sender.isOpen) throw new Error("Socket is closed");
4204
+ if (ws.send(outputFrame(definition.output, event, data)) === 0) {
4205
+ ws.close(1013, "Socket buffer full");
4206
+ throw new Error("Socket buffer full");
4207
+ }
4208
+ }
4209
+ };
4210
+ const state = {
4211
+ ws,
4212
+ session,
4213
+ sender,
4214
+ tail: Promise.resolve(),
4215
+ pending: 0,
4216
+ bytes: 0,
4217
+ closed: false,
4218
+ rooms: /* @__PURE__ */ new Set(),
4219
+ requested: /* @__PURE__ */ new Set()
4220
+ };
4221
+ connections.set(ws.request, state);
4222
+ try {
4223
+ await Promise.all(session.rooms.map((room) => enter(state, definition.topic(room))));
4224
+ await session.open(sender);
4225
+ } catch (error) {
4226
+ fail(ws, error);
4227
+ }
4228
+ },
4229
+ message(ws, value) {
4230
+ const state = connections.get(ws.request);
4231
+ if (!state || state.closed || ws.readyState !== 1) return;
4232
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
4233
+ ws.close(1003, "Only JSON text is supported");
4234
+ return;
4235
+ }
4236
+ if (typeof value === "string") {
4237
+ ws.close(1007, "Expected JSON envelope");
4238
+ return;
4239
+ }
4240
+ if (!isSocketEnvelope(value)) {
4241
+ ws.close(1008, "Invalid socket envelope");
4242
+ return;
4243
+ }
4244
+ const size = bytes(JSON.stringify(value));
4245
+ if (size > 65536) {
4246
+ ws.close(1009, "Message too large");
4247
+ return;
4248
+ }
4249
+ if (state.pending >= 32 || state.bytes + size > 1048576) {
4250
+ ws.close(1013, "Socket queue full");
4251
+ return;
4252
+ }
4253
+ state.pending++;
4254
+ state.bytes += size;
4255
+ state.tail = state.tail.then(async () => {
4256
+ if (state.closed || ws.readyState !== 1) return;
4257
+ if (value.event === "$join" || value.event === "$leave") await room(state, value.event, value.data);
4258
+ else await state.session.message(value.event, value.data, state.sender);
4259
+ }).catch((error) => {
4260
+ if (error instanceof ActionExecutionError && !state.closed && value.event !== "$join" && value.event !== "$leave" && Object.hasOwn(raisable, error.code)) try {
4261
+ const frame = JSON.stringify({
4262
+ event: "$error",
4263
+ data: {
4264
+ event: value.event,
4265
+ code: error.code,
4266
+ message: error.message,
4267
+ status: error.status,
4268
+ ...error.details !== void 0 ? { details: error.details } : {}
4269
+ }
4270
+ });
4271
+ if (bytes(frame) > 65536) throw new Error("Socket error too large", { cause: error });
4272
+ if (ws.readyState === 1) ws.send(frame);
4273
+ return;
4274
+ } catch (unsent) {
4275
+ return fail(ws, unsent);
4276
+ }
4277
+ fail(ws, error);
4278
+ }).finally(() => {
4279
+ state.pending--;
4280
+ state.bytes -= size;
4281
+ });
4282
+ },
4283
+ async close(ws, code = 1006, reason = "") {
4284
+ const state = connections.get(ws.request);
4285
+ sessions.delete(ws.request);
4286
+ if (!state || state.closed) return;
4287
+ state.closed = true;
4288
+ for (const topic of state.rooms) exit(state, topic);
4289
+ try {
4290
+ await state.session.close(state.sender, code, reason);
4291
+ } catch (error) {
4292
+ logger.error({
4293
+ error,
4294
+ service,
4295
+ socket: definition.schema.name,
4296
+ phase: "cleanup"
4297
+ });
4298
+ }
4299
+ connections.delete(ws.request);
4300
+ }
4301
+ });
4302
+ }
4303
+ }
4304
+ // src/cors.ts
4305
+ const METHODS = "GET, POST, PUT, PATCH, DELETE";
4306
+ /**
4307
+ * A request hook that adds CORS headers for allowed origins and answers
4308
+ * preflights. An origin that doesn't match gets no `Access-Control-Allow-Origin`,
4309
+ * so the browser blocks it; origins are compared exactly and never reflected
4310
+ * unless the rule allows them.
4311
+ */
4312
+ function corsHook(cors) {
4313
+ const { origin = true, credentials = false } = typeof cors === "object" && !Array.isArray(cors) ? cors : { origin: cors };
4314
+ const list = typeof origin === "string" ? [origin] : Array.isArray(origin) ? origin : void 0;
4315
+ if (list?.includes("*")) throw new Error("Brick: cors origin \"*\" is not supported. List the origins, or pass a predicate.");
4316
+ const allows = (from, request) => origin === true ? from === publicOrigin(request) : typeof origin === "function" ? origin(from, request) === true : list.includes(from);
4317
+ return ({ request, set }) => {
4318
+ const from = request.headers.get("origin");
4319
+ if (from === null) return;
4320
+ const headers = { vary: "Origin" };
4321
+ if (allows(from, request)) {
4322
+ headers["access-control-allow-origin"] = from;
4323
+ if (credentials) headers["access-control-allow-credentials"] = "true";
4324
+ }
4325
+ if (!(request.method === "OPTIONS" && request.headers.has("access-control-request-method"))) {
4326
+ Object.assign(set.headers, headers);
4327
+ return;
4328
+ }
4329
+ if (headers["access-control-allow-origin"]) {
4330
+ headers["access-control-allow-methods"] = METHODS;
4331
+ const requested = request.headers.get("access-control-request-headers");
4332
+ if (requested) headers["access-control-allow-headers"] = requested;
4333
+ }
4334
+ return new Response(null, {
4335
+ status: 204,
4336
+ headers
4337
+ });
4338
+ };
4339
+ }
4340
+ // src/server.ts
4341
+ /**
4342
+ * Create the HTTP application: an Elysia app that serves every service's
4343
+ * actions (and the tools that opt in with `http: true`) as routes, with
4344
+ * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,
4345
+ * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.
4346
+ *
4347
+ * Services come from the global registry unless `services` is given. The app
4348
+ * does not listen by itself: export it from your entry file, where `brick dev`,
4349
+ * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your
4350
+ * own server bootstrap.
4351
+ *
4352
+ * @param options - `prefix` for action routes (default `/api`), `services`,
4353
+ * `title`, `version`, and `description` for the OpenAPI document, `docs` and the
4354
+ * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
4355
+ * `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.
4356
+ * @returns The app, with `definition` (its services, prefix, and routes),
4357
+ * `endpoint()` to add raw routes, and `listEndpoints()` to list them.
4358
+ * @throws When a required secret is missing, `documentation` or `dashboard`
4359
+ * is invalid, or `deps` misses a dep a service declares or has one none declares.
4360
+ * @example
4361
+ * import { brick } from "@brickkit/core";
4362
+ * import { pagesService } from "./services/pages";
4363
+ *
4364
+ * export default brick({
4365
+ * services: [pagesService],
4366
+ * title: "Pages API",
4367
+ * telemetry: true,
4368
+ * });
4369
+ */
4370
+ function brick(options = {}) {
4371
+ const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
4372
+ const title = options.title ?? "Brick-TS API Mesh";
4373
+ const version = options.version ?? "1.0.0";
4374
+ const compiled = options.compiler !== false;
4375
+ const enableDocs = options.docs ?? true;
4376
+ const openApiPath = options.openApiPath ?? "/openapi.json";
4377
+ const docsPath = options.docsPath ?? "/docs";
4378
+ const swaggerPath = options.swaggerPath ?? "/swagger";
4379
+ const dashboard = normalizeDashboard(options.dashboard);
4380
+ const telemetry = options.telemetry === true || dashboard !== void 0;
4381
+ const app = new Elysia();
4382
+ if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
4383
+ const services = options.services ?? getGlobalRegistry().list();
4384
+ const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
4385
+ if (options.cors) app.onRequest(corsHook(options.cors));
4386
+ for (const handler of plugins.middleware) app.onRequest(handler);
4387
+ app.get("/_health", () => ({
4388
+ status: "ok",
4389
+ uptime: process.uptime(),
4390
+ timestamp: Date.now()
4391
+ }));
4392
+ const requestLogging = options.requestLogging ?? true;
4393
+ if (requestLogging !== false) {
4394
+ const pluginOpts = requestLogging === true ? {} : requestLogging;
4395
+ if (pluginOpts.enabled !== false) app.use(requestLoggingPlugin(pluginOpts));
4396
+ }
4397
+ const reference = options.reference ?? false;
4398
+ const referenceOptions = typeof reference === "object" ? reference : {};
4399
+ const referencePath = reference === true ? "/reference" : referenceOptions.path;
4400
+ if (referencePath !== void 0) {
4401
+ const settings = {
4402
+ path: referencePath,
4403
+ title: referenceOptions.title ?? title,
4404
+ specUrl: referenceOptions.specUrl ?? openApiPath
4405
+ };
4406
+ if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
4407
+ else registerReferenceRoute(app, settings);
4408
+ }
4409
+ const byName = /* @__PURE__ */ new Map();
4410
+ for (const service of services) {
4411
+ if ((byName.get(service.name) ?? service) !== service) throw new Error(`Brick: duplicate service "${service.name}" in brick()`);
4412
+ byName.set(service.name, service);
4413
+ }
4414
+ bindDeps(services, options.deps);
4415
+ const eventsOptions = plugins.listeners.length ? {
4416
+ ...options.events,
4417
+ listeners: [...options.events?.listeners ?? [], ...plugins.listeners]
4418
+ } : options.events;
4419
+ const events = eventsOptions ? new EventsHub(eventsOptions, options.deps).attach(services) : void 0;
4420
+ if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
4421
+ if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
4422
+ for (const service of services) if (typeof service.build === "function") service.build();
4423
+ const endpointDefs = [];
4424
+ let endpointRevision = 0;
4425
+ const buildSpec = () => {
4426
+ const spec = generateOpenApiSpec({
4427
+ title,
4428
+ version,
4429
+ description: options.description,
4430
+ prefix,
4431
+ services
4432
+ });
4433
+ const paths = { ...spec.paths };
4434
+ for (const [path, operations] of Object.entries(endpointPaths(endpointDefs))) paths[path] = {
4435
+ ...paths[path],
4436
+ ...operations
4437
+ };
4438
+ return {
4439
+ ...spec,
4440
+ paths
4441
+ };
4442
+ };
4443
+ if (enableDocs) {
4444
+ app.get(openApiPath, compiled ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]) : buildSpec);
4445
+ if (compiled) {
4446
+ app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));
4447
+ app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
4448
+ } else {
4449
+ app.get(docsPath, ({ set }) => {
4450
+ set.headers["content-type"] = "text/html; charset=utf-8";
4451
+ return scalarDocsHTML(openApiPath, title);
4452
+ });
4453
+ app.get(swaggerPath, ({ set }) => {
4454
+ set.headers["content-type"] = "text/html; charset=utf-8";
4455
+ return swaggerDocsHTML(openApiPath, title);
4456
+ });
4457
+ }
4458
+ }
4459
+ const registeredRoutes = /* @__PURE__ */ new Map();
4460
+ const routeKey = (method, path) => `${method} ${path.replace(/:[^/]+/g, ":param")}`;
4461
+ registeredRoutes.set(routeKey("GET", "/_health"), false);
4462
+ registeredRoutes.set(routeKey("GET", "/_brick/services"), false);
4463
+ if (enableDocs) for (const path of [
4464
+ openApiPath,
4465
+ docsPath,
4466
+ swaggerPath
4467
+ ]) registeredRoutes.set(routeKey("GET", path), false);
4468
+ if (referencePath !== void 0) registeredRoutes.set(routeKey("GET", referencePath), false);
4469
+ const sockets = services.flatMap((service) => service.listSockets().map((definition) => ({
4470
+ service: service.name,
4471
+ path: socketPath(prefix, service.name, definition),
4472
+ definition
4473
+ })));
4474
+ const socketRoutes = /* @__PURE__ */ new Set();
4475
+ for (const socket of sockets) {
4476
+ const key = routeKey("GET", socket.path);
4477
+ if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new Error(`Brick: duplicate socket route '${socket.path}'`);
4478
+ socketRoutes.add(key);
4479
+ }
4480
+ const mountRoute = (method, path, handler, plugin = false) => {
4481
+ const key = routeKey(method, path);
4482
+ if (socketRoutes.has(key)) throw new Error(`Brick: route '${method} ${path}' conflicts with a socket`);
4483
+ if (registeredRoutes.has(key)) {
4484
+ if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
4485
+ return false;
4486
+ }
4487
+ switch (method) {
4488
+ case "GET":
4489
+ app.get(path, handler);
4490
+ break;
4491
+ case "POST":
4492
+ app.post(path, handler);
4493
+ break;
4494
+ case "PUT":
4495
+ app.put(path, handler);
4496
+ break;
4497
+ case "PATCH":
4498
+ app.patch(path, handler);
4499
+ break;
4500
+ case "DELETE": app.delete(path, handler);
4501
+ }
4502
+ registeredRoutes.set(key, plugin);
4503
+ return true;
4504
+ };
4505
+ const mountEndpoint = (def, plugin = false) => {
4506
+ const handler = createEndpointHandler(def, services);
4507
+ mountRoute(def.method, def.path, telemetry ? (context) => traceHttpRequest(context, def.method, def.path, () => handler(context)) : handler, plugin);
4508
+ endpointDefs.push(def);
4509
+ endpointRevision++;
4510
+ };
4511
+ for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
4512
+ for (const def of options.endpoints ?? []) mountEndpoint(def);
4513
+ const brickApp = app;
4514
+ brickApp.endpoint = (def) => {
4515
+ mountEndpoint(def);
4516
+ };
4517
+ brickApp.listEndpoints = () => [...endpointDefs];
4518
+ brickApp.referenceDocuments = async () => {
4519
+ const documents = enableDocs ? [{
4520
+ title,
4521
+ document: buildSpec()
4522
+ }] : [];
4523
+ for (const extra of referenceOptions.documents ?? []) try {
4524
+ const document = typeof extra.document === "function" ? await extra.document() : extra.document;
4525
+ documents.push({
4526
+ title: extra.title,
4527
+ document
4528
+ });
4529
+ } catch (error) {
4530
+ console.warn(`[Brick-TS] Skipping the "${extra.title}" API document: ${error instanceof Error ? error.message : String(error)}`);
4531
+ }
4532
+ return documents;
4533
+ };
4534
+ const compilation = options.compilation ?? compileBrickApplication({
4535
+ services,
4536
+ prefix,
4537
+ mode: options.compiler === false ? "generic" : "specialized"
4538
+ });
4539
+ if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
4540
+ const mountedRoutes = [];
4541
+ for (const route of compilation.routes) {
4542
+ const action = services.find((candidate) => candidate.name === route.ir.service).listActions().find((candidate) => candidate.name === route.ir.action);
4543
+ const invoke = (context) => {
4544
+ const result = telemetry ? withSpan(`action ${route.ir.service}.${route.ir.action}`, {
4545
+ "brick.service": route.ir.service,
4546
+ "brick.action": route.ir.action
4547
+ }, () => route.handler(context)) : route.handler(context);
4548
+ return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
4549
+ };
4550
+ if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, getPluginActionRoute(action, prefix) !== void 0)) mountedRoutes.push(route.ir);
4551
+ }
4552
+ mountSockets(app, sockets, options.sockets?.broker ?? localBroker(), options.sockets?.secret);
4553
+ const definition = Object.freeze({
4554
+ services: Object.freeze([...services]),
4555
+ prefix,
4556
+ routes: Object.freeze(mountedRoutes),
4557
+ sockets: Object.freeze(sockets.map(({ service, path, definition }) => ({
4558
+ ...definition.schema,
4559
+ service,
4560
+ path
4561
+ }))),
4562
+ telemetry,
4563
+ documentation: normalizeDocumentation(options.documentation),
4564
+ dashboard,
4565
+ ...events ? { events: events.describe() } : {},
4566
+ plugins: Object.freeze(plugins.plugins)
4567
+ });
4568
+ Object.defineProperty(brickApp, "definition", { value: definition });
4569
+ Object.defineProperty(brickApp, "events", { value: events });
4570
+ const lifecycle = pluginLifecycle(plugins.lifecycles);
4571
+ const listen = app.listen.bind(app);
4572
+ const stop = app.stop.bind(app);
4573
+ Object.defineProperty(brickApp, "start", { value: lifecycle.start });
4574
+ brickApp.listen = ((...args) => {
4575
+ lifecycle.start().catch((error) => console.error("[Brick-TS] A plugin failed to start:", error));
4576
+ return listen(...args);
4577
+ });
4578
+ brickApp.stop = (async (closeActiveConnections) => {
4579
+ try {
4580
+ await stop(closeActiveConnections);
4581
+ } finally {
4582
+ await lifecycle.stop();
4583
+ }
4584
+ });
4585
+ getGlobalRegistry().setApplicationRoutes(definition);
4586
+ app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
4587
+ const registry = getGlobalRegistry();
4588
+ return [registry, registry.revision];
4589
+ }) : () => getGlobalRegistry().exportArchitecture(definition));
4590
+ return brickApp;
4591
+ }
4592
+ function normalizeDocumentation(documentation) {
4593
+ if (documentation === void 0) return void 0;
4594
+ const options = typeof documentation === "string" ? { dir: documentation } : documentation;
4595
+ if (typeof options.dir !== "string" || options.dir === "") throw new Error("Brick: documentation needs a folder, such as './docs'.");
4596
+ return Object.freeze({
4597
+ dir: options.dir,
4598
+ ...options.components ? { components: options.components } : {}
4599
+ });
4600
+ }
4601
+ function jsonActionResult(value) {
4602
+ return value === null ? new Response("null", { headers: { "content-type": "application/json" } }) : value;
4603
+ }
4604
+ function htmlResponse(html) {
4605
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
4606
+ }
4607
+ /** Reuse serialized JSON, without sharing a mutable response body between requests. */
4608
+ function cachedJsonRoute(build, revision) {
4609
+ let [owner, version] = revision();
4610
+ let json = JSON.stringify(build());
4611
+ return ({ set }) => {
4612
+ const [currentOwner, currentVersion] = revision();
4613
+ if (currentOwner !== owner || currentVersion !== version) {
4614
+ json = JSON.stringify(build());
4615
+ owner = currentOwner;
4616
+ version = currentVersion;
4617
+ }
4618
+ set.headers["content-type"] = "application/json;charset=utf-8";
4619
+ return json;
4620
+ };
4621
+ }
4622
+ export { getPluginActionRoute as $, hoistAnchoredSchemas as A, createActionHandler as B, envSource as C, resetSecrets as D, overrideSecrets as E, compileBrickApplication as F, isPluginInstance as G, compilerRuntime as H, loadCompiledBrickApp as I, PLUGIN_DEPS as J, pluginOwner as K, isBrickApp as L, getActionAccess as M, setActionAccess as N, resolveSecrets as O, bindCompiledApplication as P, defineServicePlugin as Q, requireBrickApp as R, defineSecret as S, overrideSecret as T, brickVersion as U, executeCompiledRoute as V, definePlugin as W, useDeps as X, port as Y, defineResourcePlugin as Z, registerReferenceRoute as _, definitionSite as _t, stopAllEvents as a, errorsOf as at, requestLoggingPlugin as b, getActionRoute as bt, onTransactionCommit as c, Type as ct, outboxTable as d, validateWithSchema as dt, getPluginEndpoints as et, createEndpointHandler as f, toErrorResponse as ft, referencePlugin as g, claimName as gt, toOpenApiPath as h, ServiceRegistry as ht, recorders as i, defineAction as it, ACTION_ACCESS_KEY as j, generateOpenApiSpec as k, runInTransaction as l, getCompiledCheck as lt, resolveEndpointDb as m, withCallSpan as mt, defineServiceSocket as n, isInstallingPlugin as nt, resolveWorkflowPaths as o, DEFAULT_LOG_PREFIXES as ot, endpointPaths as p, traceRoute as pt, satisfiesRange as q, EventsHub as r, buildErrorHelpers as rt, Dispatcher as s, createLogger as st, brick as t, installPlugin as tt, isOutboxTable as u, t as ut, scalarDocsHTML as v, getGlobalRegistry as vt, listSecrets as w, SecretRef as x, swaggerDocsHTML as y, resetGlobalRegistry as yt, compileRoutePlan as z };
4623
+
4624
+ //# sourceMappingURL=server.js.map