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