@brickkit/core 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","names":["sqliteInteger","sqliteText","sqliteIndex","pgText","pgInteger","pgIndex"],"sources":["../../src/plugin-types.ts","../../src/telemetry.ts","../../src/error-response.ts","../../src/typebox.ts","../../src/logger.ts","../../src/context.ts","../../src/compiler/runtime.ts","../../src/action.ts","../../src/http.ts","../../src/service-port.ts","../../src/plugin.ts","../../src/deps.ts","../../src/plugin-app.ts","../../src/definition-site.ts","../../src/compiler/ir.ts","../../src/action-handler.ts","../../src/app-entry.ts","../../src/compiler.ts","../../src/registry.ts","../../src/access.ts","../../src/openapi.ts","../../src/secrets.ts","../../src/request-logger.ts","../../src/docs.ts","../../src/dashboard.ts","../../src/endpoints.ts","../../src/events/id.ts","../../src/events/outbox.ts","../../src/events/transaction.ts","../../src/events/dispatcher.ts","../../src/events/catalog.ts","../../src/events/listener.ts","../../src/events/workflows.ts","../../src/events/hub.ts","../../src/cors.ts","../../src/socket.ts","../../src/server.ts"],"sourcesContent":["import type { HttpMethod } from \"./http\";\nimport type { TSchema } from \"@sinclair/typebox\";\nimport type { PluginInstance } from \"./define-plugin\";\nimport type { PluginActionChecks } from \"./action-meta\";\nimport type {\n Action,\n ActionConfigWithAuthorize,\n ActionConfigWithoutAuthorize,\n ActionContext,\n ActionErrorDefinition,\n BaseContext,\n Resource,\n Service,\n} from \"./types\";\n\nexport type PluginRouteMethod = HttpMethod;\n/** Where a plugin route mounts: under the app prefix, its service, or its resource. */\nexport const PLUGIN_ROUTE_SCOPES = [\"app\", \"service\", \"resource\"] as const;\nexport type PluginRouteScope = (typeof PLUGIN_ROUTE_SCOPES)[number];\nexport type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =\n | false\n | Readonly<Record<string, false | { path?: string; scope?: S }>>;\n\nexport type ContextOf<S> =\n S extends Service<infer D, infer C> ? BaseContext<D> & C : never;\n\nexport interface PluginEndpointContext<\n C extends ActionContext = ActionContext,\n> {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n set: { status?: number; headers: Record<string, string> };\n ctx: C;\n}\n\nexport interface PluginRouteRegistrar<\n C extends ActionContext = ActionContext,\n S extends PluginRouteScope = PluginRouteScope,\n> {\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<I, O, E, C> &\n PluginActionChecks & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<I, O, E, C> &\n PluginActionChecks & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n endpoint(config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n }): void;\n /**\n * Reserve a URL segment under the resource, so no resource action takes it,\n * for a route the plugin may add later. Resource-scoped routes claim their\n * first segment themselves.\n */\n claim(segment: string): void;\n}\n\nexport interface ServicePluginContext<\n S extends Service<any, any> = Service<any, any>,\n> {\n service: S;\n routes: PluginRouteRegistrar<ContextOf<S>, \"app\" | \"service\">;\n}\nexport interface ResourcePluginContext<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n> {\n service: S;\n resource: R;\n routes: PluginRouteRegistrar<ContextOf<S>>;\n}\n\n/** Plugins may specialize their returned API for the installation host. */\nexport interface ResourcePluginTypes {\n readonly table: unknown;\n readonly context: unknown;\n readonly resource: unknown;\n readonly api: object;\n}\nexport type ResourcePluginAPI<P, T, C, R = unknown> = P extends {\n readonly types: infer H extends ResourcePluginTypes;\n}\n ? (H & {\n readonly table: T;\n readonly context: C;\n readonly resource: R;\n })[\"api\"]\n : P extends PluginInstance<infer A extends object, any>\n ? A\n : P extends ResourcePlugin<any, any, infer A>\n ? A\n : never;\n\n/** Which host a plugin descriptor installs on. Process-global, so descriptors survive a second core copy. */\nexport const PLUGIN_KIND: unique symbol = Symbol.for(\"brickkit.plugin.kind\");\n/**\n * The setup context's slot where a `definePlugin` setup hands over what to do\n * once its install succeeds; a failed install drops it.\n */\nexport const PLUGIN_COMMIT: unique symbol = Symbol.for(\n \"brickkit.plugin.commit\",\n);\nexport interface ServicePlugin<S extends Service<any, any>, A> {\n readonly [PLUGIN_KIND]: \"service\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes<\"app\" | \"service\">;\n readonly setup: (context: ServicePluginContext<S>) => A;\n}\nexport interface ResourcePlugin<\n S extends Service<any, any>,\n R extends Resource<any, any, any>,\n A extends object,\n> {\n readonly [PLUGIN_KIND]: \"resource\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes;\n readonly setup: (context: ResourcePluginContext<S, R>) => A;\n}\n\n/** A plugin as `app.definition.plugins` lists it. */\nexport interface InstalledPlugin {\n readonly name: string;\n readonly brick?: string;\n readonly scope: \"app\" | \"service\" | \"resource\";\n readonly service?: string;\n readonly resource?: string;\n /** The plugin's dashboard extension, an absolute path. */\n readonly dashboard?: string;\n}\n","import { ATTR } from \"./telemetry-names\";\nimport {\n context,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n type Attributes,\n type Span,\n} from \"@opentelemetry/api\";\n\nconst INSTRUMENTATION_SCOPE = \"@brickkit/core\";\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STATEMENT_LENGTH = 2000;\nconst DATABASE_INSTRUMENTED = Symbol.for(\"brickkit.telemetry.database\");\nconst SQLITE_STATEMENT_METHODS = [\"all\", \"get\", \"run\", \"values\"] as const;\n\ntype Outcome =\n | { failed: false; value: unknown }\n | { failed: true; error: unknown };\n\n/** Run `fn` as a child of the active span, ending the span when its result settles. */\nexport function withSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n kind: SpanKind = SpanKind.INTERNAL,\n): T {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(name, { kind, attributes }, (span) =>\n settle(fn, (outcome) => {\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n }),\n );\n}\n\n/**\n * Add a child span for an in-process call, but only inside a request that is\n * already traced. Calls made outside instrumented requests run unchanged.\n */\nexport function withCallSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n): T {\n return trace.getActiveSpan() ? withSpan(name, attributes, fn) : fn();\n}\n\ninterface HttpContext {\n request?: Request;\n headers?: Record<string, string | undefined>;\n set?: { status?: unknown; headers?: Record<string, unknown> };\n}\n\n/** What a raw route handler receives from `traceRoute`. Read the body from `request`. */\nexport interface RawRouteContext {\n request: Request;\n headers: Record<string, string | undefined>;\n set: { status?: unknown; headers?: Record<string, unknown> };\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n}\n\n/**\n * Wrap a raw route handler so each of its requests gets a server span. Use it\n * for routes registered directly on the app, outside actions and endpoints,\n * such as auth or webhook routes. Spans are recorded whenever a tracer provider\n * is registered; `brick({ telemetry })` does not apply to these routes.\n *\n * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia\n * decides what to parse from the handler's destructuring, and forwarding the\n * whole context would parse the body and leave `request.json()` with nothing.\n */\nexport function traceRoute<T>(\n route: string,\n handler: (context: RawRouteContext) => T,\n): (context: RawRouteContext) => T {\n return ({ request, headers, set, params, query }) =>\n traceHttpRequest({ request, headers, set }, request.method, route, () =>\n handler({ request, headers, set, params, query }),\n );\n}\n\n/**\n * Wrap one HTTP request in a server span. The span continues the caller's\n * trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the\n * request id Brick returns is the span's trace id, so clients can find the\n * request in the dashboard.\n */\nexport function traceHttpRequest<T>(\n request: HttpContext,\n method: string,\n route: string,\n fn: () => T,\n): T {\n const attributes: Attributes = {\n [ATTR.httpMethod]: method,\n [ATTR.httpRoute]: route,\n };\n if (request.request) {\n attributes[ATTR.urlPath] = new URL(request.request.url).pathname;\n }\n const headers = request.headers ?? {};\n const parent = propagation.extract(context.active(), headers);\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(\n `${method} ${route}`,\n { kind: SpanKind.SERVER, attributes },\n parent,\n (span) => {\n if (!headers[\"x-trace-id\"]) {\n headers[\"x-trace-id\"] = span.spanContext().traceId;\n }\n const outgoing: Record<string, string> = {};\n propagation.inject(context.active(), outgoing);\n if (request.set?.headers) Object.assign(request.set.headers, outgoing);\n return settle(fn, (outcome) => {\n // Raw handlers often return a Response, whose status Elysia's `set` never sees.\n const status = outcome.failed\n ? 500\n : outcome.value instanceof Response\n ? outcome.value.status\n : responseStatus(request.set?.status);\n if (outcome.failed) recordThrown(span, outcome.error);\n span.setAttribute(ATTR.httpStatus, status);\n const traceId = headers[\"x-trace-id\"];\n if (traceId) span.setAttribute(ATTR.traceId, traceId);\n if (status >= 500) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${status}`,\n });\n }\n span.end();\n });\n },\n );\n}\n\n/**\n * Attach a handled failure to the active span. Brick returns these as\n * responses rather than throwing, so only server faults (5xx) mark the span\n * as errored; client errors keep their code as an attribute.\n */\nexport function recordFailure(\n error: unknown,\n failure: { status: number; code: string; message: string },\n): void {\n const span = trace.getActiveSpan();\n if (!span) return;\n span.setAttributes({\n [ATTR.errorCode]: failure.code,\n [ATTR.errorStatus]: failure.status,\n [ATTR.errorMessage]: truncate(failure.message),\n });\n if (failure.status >= 500) recordThrown(span, error);\n}\n\n/**\n * Record SQL statements as client spans for the database behind a service.\n * Drizzle's logger has no timing, so the hook sits on the driver: each\n * statement is timed where the driver runs it. Statements outside traced\n * requests are not recorded. Calling this again on the same client is a no-op.\n */\nexport function instrumentDatabase(db: unknown): void {\n const client = (db as { $client?: unknown } | undefined)?.$client;\n // postgres.js clients are callable functions, so accept both shapes.\n if (\n (typeof client !== \"object\" && typeof client !== \"function\") ||\n client === null\n ) {\n return;\n }\n const driver = client as Record<PropertyKey, unknown>;\n if (driver[DATABASE_INSTRUMENTED]) return;\n if (typeof driver.prepare === \"function\") {\n instrumentBunSqlite(driver as unknown as BunSqliteClient);\n } else if (typeof driver.unsafe === \"function\") {\n instrumentPostgres(driver as unknown as PostgresClient);\n } else {\n return;\n }\n driver[DATABASE_INSTRUMENTED] = true;\n}\n\ntype BunSqliteStatement = Record<\n (typeof SQLITE_STATEMENT_METHODS)[number],\n (...args: unknown[]) => unknown\n>;\n\ninterface BunSqliteClient {\n prepare: (sql: string) => BunSqliteStatement;\n}\n\nfunction instrumentBunSqlite(client: BunSqliteClient): void {\n const prepare = client.prepare.bind(client);\n client.prepare = (sql: string) => {\n const statement = prepare(sql);\n for (const method of SQLITE_STATEMENT_METHODS) {\n const original = statement[method];\n if (typeof original !== \"function\") continue;\n statement[method] = (...args: unknown[]) =>\n recordStatement(sql, \"sqlite\", () => original.apply(statement, args));\n }\n return statement;\n };\n}\n\ninterface PostgresQuery {\n then: (\n onFulfilled?: (value: unknown) => unknown,\n onRejected?: (reason: unknown) => unknown,\n ) => Promise<unknown>;\n}\n\ninterface PostgresClient {\n unsafe: (sql: string, ...rest: unknown[]) => PostgresQuery;\n}\n\n/**\n * postgres.js returns a query that runs when awaited, and `values()` returns\n * that same object, so overriding `then` on it times the whole round trip.\n */\nfunction instrumentPostgres(client: PostgresClient): void {\n const unsafe = client.unsafe.bind(client);\n client.unsafe = (sql: string, ...rest: unknown[]) => {\n const query = unsafe(sql, ...rest);\n if (!trace.getActiveSpan() || typeof query?.then !== \"function\") {\n return query;\n }\n const span = startStatementSpan(sql, \"postgresql\");\n let finished = false;\n const finish = (outcome: Outcome) => {\n if (finished) return;\n finished = true;\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n };\n const then = query.then.bind(query);\n // The query is already thenable; this wraps its own `then` to time the\n // round trip, so the no-thenable rule does not apply.\n // oxlint-disable-next-line unicorn/no-thenable\n query.then = (onFulfilled, onRejected) =>\n then(\n (value) => {\n finish({ failed: false, value });\n return onFulfilled ? onFulfilled(value) : value;\n },\n (error: unknown) => {\n finish({ failed: true, error });\n if (onRejected) return onRejected(error);\n throw error;\n },\n );\n return query;\n };\n}\n\nfunction recordStatement<T>(sql: string, system: string, fn: () => T): T {\n if (!trace.getActiveSpan()) return fn();\n return withSpan(\n statementName(sql),\n statementAttributes(sql, system),\n fn,\n SpanKind.CLIENT,\n );\n}\n\nfunction startStatementSpan(sql: string, system: string): Span {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startSpan(\n statementName(sql),\n { kind: SpanKind.CLIENT, attributes: statementAttributes(sql, system) },\n context.active(),\n );\n}\n\nfunction statementName(sql: string): string {\n return `SQL ${operationOf(sql)}`;\n}\n\nfunction statementAttributes(sql: string, system: string): Attributes {\n return {\n [ATTR.dbSystem]: system,\n [ATTR.dbOperation]: operationOf(sql),\n [ATTR.dbStatement]: truncate(sql, MAX_STATEMENT_LENGTH),\n };\n}\n\nfunction operationOf(sql: string): string {\n return sql.trim().split(/\\s+/, 1)[0]?.toUpperCase() || \"SQL\";\n}\n\nfunction settle<T>(fn: () => T, done: (outcome: Outcome) => void): T {\n let result: T;\n try {\n result = fn();\n } catch (error) {\n done({ failed: true, error });\n throw error;\n }\n if (isPromiseLike(result)) {\n return result.then(\n (value) => {\n done({ failed: false, value });\n return value;\n },\n (error: unknown) => {\n done({ failed: true, error });\n throw error;\n },\n ) as unknown as T;\n }\n done({ failed: false, value: result });\n return result;\n}\n\nfunction recordThrown(span: Span, error: unknown): void {\n span.recordException(error instanceof Error ? error : String(error));\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncate(messageOf(error)),\n });\n}\n\nfunction responseStatus(value: unknown): number {\n const status = typeof value === \"number\" ? value : Number(value ?? 200);\n return Number.isInteger(status) ? status : 200;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n","import { ActionExecutionError, ValidationError, type Logger } from \"./types\";\nimport { recordFailure } from \"./telemetry\";\nimport type { WireError } from \"./protocol\";\n\n/** The JSON body of a failed HTTP call. */\nexport interface ErrorEnvelope extends WireError {\n requestId: string;\n}\n\ntype ErrorContext = { logger: Pick<Logger, \"error\">; requestId: string };\n\n/** Preserve declared failures, log and wrap unexpected throws without exposing internals. */\nexport function normalizeActionError(\n err: unknown,\n { logger, requestId }: ErrorContext,\n): ActionExecutionError | ValidationError {\n if (err instanceof ActionExecutionError || err instanceof ValidationError)\n return err;\n logger.error(\"Unexpected action error\", { requestId }, err);\n const failure = new ActionExecutionError(\n \"INTERNAL_SERVER_ERROR\",\n \"Internal Server Error\",\n 500,\n undefined,\n { cause: err },\n );\n failure.name = \"InternalServerError\";\n return failure;\n}\n\n/**\n * Turn what an action threw into the JSON body of its HTTP response, and record\n * the failure on the active trace. Declared failures and validation errors keep\n * their code, status, and details; anything else is logged and answered as a\n * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.\n *\n * @param err - Whatever was thrown.\n * @param context - A `logger` with `error()`, and the `requestId` to put in the body.\n * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and\n * `details` or `errors` when there are any.\n */\nexport function toErrorResponse(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const envelope = buildErrorEnvelope(err, context);\n recordFailure(err, envelope);\n return envelope;\n}\n\nfunction buildErrorEnvelope(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const failure = normalizeActionError(err, context);\n if (\n failure.status >= 500 &&\n (err instanceof ActionExecutionError || err instanceof ValidationError)\n ) {\n context.logger.error(\n \"Server action error\",\n { requestId: context.requestId },\n err,\n );\n }\n if (failure instanceof ValidationError && failure.status >= 500) {\n return {\n name: failure.name,\n code: failure.code,\n message: failure.message,\n status: failure.status,\n requestId: context.requestId,\n };\n }\n return { ...failure.toJSON(), requestId: context.requestId };\n}\n","import { Type, type TSchema, type Static } from \"@sinclair/typebox\";\nimport { TypeCompiler, type TypeCheck } from \"@sinclair/typebox/compiler\";\nimport type { ValidationErrorItem } from \"./types\";\n\nexport { Type, Type as t };\nexport type { TSchema, Static };\n\nconst compilerCache = new WeakMap<TSchema, TypeCheck<TSchema>>();\n\n/**\n * The compiled validator for a TypeBox schema. Compiling is slow and checking\n * is fast, so each schema is compiled once and kept for as long as the schema\n * object lives.\n *\n * @param schema - A TypeBox schema.\n * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.\n */\nexport function getCompiledCheck<T extends TSchema>(schema: T): TypeCheck<T> {\n let compiled = compilerCache.get(schema) as TypeCheck<T> | undefined;\n if (!compiled) {\n compiled = TypeCompiler.Compile(schema);\n compilerCache.set(schema, compiled);\n }\n return compiled;\n}\n\n/**\n * Check a value against a schema, the way actions check their input and output.\n *\n * @param schema - A TypeBox schema, or `undefined` to accept anything.\n * @param value - The value to check.\n * @returns `{ success: true, data }`, or `{ success: false, errors }` with a\n * `path`, `message`, `type`, and the offending `value` for each problem.\n */\nexport function validateWithSchema<T extends TSchema>(\n schema: T | undefined,\n value: unknown,\n):\n | { success: true; data: Static<T> }\n | { success: false; errors: ValidationErrorItem[] } {\n if (!schema) {\n return { success: true, data: value as Static<T> };\n }\n\n const check = getCompiledCheck(schema);\n if (check.Check(value)) {\n return { success: true, data: value as Static<T> };\n }\n\n const errors: ValidationErrorItem[] = [];\n for (const error of check.Errors(value)) {\n errors.push({\n path: error.path,\n message: error.message,\n value: error.value,\n type: error.type,\n });\n }\n\n return { success: false, errors };\n}\n","import { ATTR, GLOBAL_SYMBOL, SPAN } from \"./telemetry-names\";\nimport { formatWithOptions } from \"node:util\";\nimport { trace, type Span } from \"@opentelemetry/api\";\nimport type { Logger } from \"./types\";\n\ntype Level = keyof Logger;\n\n/**\n * Set by the CLI when a dashboard is collecting logs, in `brick dev` or in\n * `brick start` with the `dashboard` option. A shared symbol, not an option or\n * an export: the CLI and the app may each hold their own copy of this package,\n * and nothing but a dashboard turns it on.\n */\nconst CAPTURE = Symbol.for(GLOBAL_SYMBOL.logsCapture);\nconst MAX_MESSAGE_LENGTH = 4000;\n/**\n * Logs one span keeps. OpenTelemetry keeps 128 events per span by default,\n * exceptions among them, so a chatty action must not use them all up and\n * lose the stack trace of the error that ends it.\n */\nconst MAX_LOGS_PER_SPAN = 100;\n\nconst logged = new WeakMap<Span, number>();\n\n/**\n * Terminal formatting: colors and styles (`ESC [ … m`, and other CSI codes) and\n * titles or links (`ESC ] … BEL`). Libraries such as Better Auth color their\n * console output, which in a web page shows as stray characters.\n */\n// oxlint-disable no-control-regex\nconst ANSI =\n /\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\))/g;\n// oxlint-enable no-control-regex\n\nexport function stripAnsi(text: string): string {\n return text.includes(\"\\u001b\") ? text.replace(ANSI, \"\") : text;\n}\n\n/**\n * What `console.log` would print, without terminal colors, with objects cut off\n * at a sensible size.\n */\nfunction render(args: unknown[]): string {\n const text = stripAnsi(\n formatWithOptions(\n { depth: 3, breakLength: 120, maxArrayLength: 50, maxStringLength: 1000 },\n ...args,\n ),\n );\n return text.length > MAX_MESSAGE_LENGTH\n ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…`\n : text;\n}\n\nfunction record(span: Span, level: Level, args: unknown[]): void {\n const count = (logged.get(span) ?? 0) + 1;\n logged.set(span, count);\n if (count > MAX_LOGS_PER_SPAN) {\n // Counted, so the dashboard can say how many it left out.\n span.setAttribute(ATTR.logsDropped, count - MAX_LOGS_PER_SPAN);\n return;\n }\n span.addEvent(SPAN.logEvent, {\n [ATTR.logLevel]: level,\n [ATTR.logMessage]: render(args),\n });\n}\n\n/**\n * Record a line on the running span, if a recording one is running. Returns\n * whether it did, so the caller prints only when it did not.\n */\nfunction recordActive(level: Level, args: unknown[]): boolean {\n const span = trace.getActiveSpan();\n if (!span?.isRecording()) return false;\n record(span, level, args);\n return true;\n}\n\n// The dev server's console capture calls this by name, for the same reason\n// `CAPTURE` is a shared symbol: it may hold a different copy of this package.\n(globalThis as Record<symbol, unknown>)[Symbol.for(GLOBAL_SYMBOL.logsRecord)] =\n recordActive;\n\n/**\n * A logger for actions, tools, and endpoints. While a dashboard is on, a line\n * logged while a request is being traced becomes an event on the span that is\n * running, which the dashboard shows with that request (and in its Logs tab);\n * it is not printed. Everywhere else, and for lines logged outside a request,\n * it prints to the console, prefixed by `prefix`: one for all levels, or one\n * per level.\n *\n * Capturing costs one context lookup and a span event per line, and nothing\n * is serialized for the dashboard until the span ends, so it is cheaper than\n * a console write. Lines are cut at 4,000 characters and a span keeps 100.\n */\nexport function createLogger(prefix: string | Record<Level, string>): Logger {\n const level =\n (name: Level, print: (...args: unknown[]) => void) =>\n (...args: unknown[]): void => {\n if (\n (globalThis as Record<symbol, unknown>)[CAPTURE] === true &&\n recordActive(name, args)\n )\n return;\n print(typeof prefix === \"string\" ? prefix : prefix[name], ...args);\n };\n return {\n info: level(\"info\", (...args) => console.log(...args)),\n warn: level(\"warn\", (...args) => console.warn(...args)),\n error: level(\"error\", (...args) => console.error(...args)),\n debug: level(\"debug\", (...args) => console.debug(...args)),\n };\n}\n\n/** The prefixes of loggers a caller did not supply. */\nexport const DEFAULT_LOG_PREFIXES: Record<Level, string> = {\n info: \"[INFO]\",\n warn: \"[WARN]\",\n error: \"[ERROR]\",\n debug: \"[DEBUG]\",\n};\n","import type { BaseContext, Logger } from \"./types\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nconst EMPTY = Object.freeze({});\nconst defaultLogger: Logger = createLogger(DEFAULT_LOG_PREFIXES);\n/** Random, so ids never repeat across restarts or processes. */\nconst newId = (kind: \"tr\" | \"req\") => `${kind}_${crypto.randomUUID()}`;\n\n/**\n * The trace and request ids of an HTTP request: the caller's `x-trace-id` and\n * `x-request-id` headers, else fresh ones. Both are echoed on the response.\n */\nexport function requestIds(\n headers: Record<string, string | undefined> | undefined,\n set: { headers?: Record<string, unknown> } | undefined,\n): { traceId: string; requestId: string } {\n const traceId = headers?.[\"x-trace-id\"] || newId(\"tr\");\n const requestId = headers?.[\"x-request-id\"] || newId(\"req\");\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n return { traceId, requestId };\n}\n\n/**\n * The framework fields of an action context: what the caller gave, the rest\n * defaulted. A missing trace or request id gets a fresh `tr_`/`req_` one.\n */\nexport function baseContext(\n fields: Partial<BaseContext> & { deps?: Readonly<Record<string, unknown>> },\n): BaseContext & { deps: Readonly<Record<string, unknown>> } {\n return {\n request: fields.request ?? DEFAULT_REQUEST,\n db: fields.db,\n logger: fields.logger ?? defaultLogger,\n traceId: fields.traceId ?? newId(\"tr\"),\n requestId: fields.requestId ?? newId(\"req\"),\n services: fields.services ?? EMPTY,\n metadata: fields.metadata ?? EMPTY,\n deps: fields.deps ?? EMPTY,\n };\n}\n\ntype ContextEnvelope = Pick<\n BaseContext,\n \"caller\" | \"traceId\" | \"requestId\" | \"tenantId\"\n> & { user?: unknown };\n\nexport function pickContextEnvelope(\n context?: Partial<BaseContext> & { user?: unknown },\n): Partial<ContextEnvelope> {\n if (!context) return {};\n const envelope: Partial<ContextEnvelope> = {};\n if (context.caller !== undefined) envelope.caller = context.caller;\n if (context.user !== undefined) envelope.user = context.user;\n if (context.traceId !== undefined) envelope.traceId = context.traceId;\n if (context.requestId !== undefined) envelope.requestId = context.requestId;\n if (context.tenantId !== undefined) envelope.tenantId = context.tenantId;\n return envelope;\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type Action,\n type ActionContext,\n type Logger,\n type ValidationErrorItem,\n} from \"../types\";\nimport { toErrorResponse } from \"../error-response\";\nimport { baseContext, requestIds } from \"../context\";\nimport type { ServicePort } from \"../service-port\";\nimport type { RouteIR } from \"./ir\";\n\n/*\n * The action pipeline, as stages: request ids → read input → validate →\n * authorize → execute → validate output → map error. `bindRoute` runs them\n * for an HTTP route; `action.execute` runs the same stages in-process.\n */\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\n/** @deprecated `brick build` no longer emits handler factories; see `bindCompiledApplication`. */\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\ninterface Checker {\n Check(value: unknown): boolean;\n Errors(value: unknown): Iterable<any>;\n}\n\n/** Everything one route needs to answer a request, worked out once at startup. */\nexport interface CompiledRoutePlan {\n readonly route: RouteIR;\n readonly service: ServicePort;\n readonly action: Action<any, any, any, any>;\n readonly execute: (params: any) => unknown;\n readonly authorize?: (params: any) => boolean | Promise<boolean>;\n readonly contextHook?: (baseCtx: any) => unknown;\n readonly inputChecker?: Checker;\n readonly outputChecker?: Checker;\n /** A plugin's check that runs before `inputChecker`. */\n readonly checkInput?: (input: unknown) => ValidationErrorItem[] | undefined;\n readonly errorBuilder: unknown;\n readonly logger: Logger;\n readonly cachedDb: unknown;\n /** The deps of the plugin install that created the action; else the service's. */\n readonly deps?: Readonly<Record<string, unknown>>;\n}\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true; // NOSONAR\n return false;\n}\n\n/** One source alone is the input as it is; several merge, later ones winning. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction coerceQueryValue(\n value: unknown,\n type: RouteIR[\"coercions\"][number][\"type\"],\n request: Request | undefined,\n key: string,\n) {\n if (type === \"number\") {\n const number = Number(value);\n return Number.isNaN(number) ? value : number;\n }\n if (type === \"array\") {\n const values = request ? new URL(request.url).searchParams.getAll(key) : [];\n return values.length ? values : Array.isArray(value) ? value : [value];\n }\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n return value;\n}\n\n/** The action's input from the path, query and body, coerced by its schema. */\nexport function readInput(\n route: RouteIR,\n { params, body, query, request }: any,\n): unknown {\n if (!route.input) return undefined;\n let coercedQuery = query;\n let coercedParams = params;\n if (route.coercions.length) {\n if (query) {\n coercedQuery = { ...query };\n for (const { key, type } of route.coercions)\n if (query[key] !== undefined)\n coercedQuery[key] = coerceQueryValue(query[key], type, request, key);\n }\n for (const { key, type } of route.coercions) {\n if (type !== \"number\" || typeof params?.[key] !== \"string\") continue;\n const value = Number(params[key]);\n if (Number.isNaN(value)) continue;\n if (coercedParams === params) coercedParams = { ...params };\n coercedParams[key] = value;\n }\n }\n const input = route.readLike\n ? mergeInput(coercedQuery, coercedParams, body)\n : mergeInput(coercedParams, body, coercedQuery);\n return input === undefined &&\n (route.inputSchema as { type?: string } | undefined)?.type === \"object\"\n ? {}\n : input;\n}\n\n// Generic pre-validation nesting cap for parsed HTTP input. Compiled input\n// validators recurse, so unbounded nesting (e.g. a 20k-deep filter object)\n// would throw RangeError (HTTP 500) instead of failing validation with a\n// 400. The walk is iterative and far above legitimate depths (a max-depth\n// CRUD filter is ~45 levels of JSON).\nconst MAX_INPUT_DEPTH = 128;\nexport function inputTooDeep(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const stack: { node: unknown; depth: number }[] = [{ node: value, depth: 0 }];\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (depth > MAX_INPUT_DEPTH) return true;\n if (node && typeof node === \"object\") {\n const children = Array.isArray(node) ? node : Object.values(node);\n for (const child of children)\n if (child && typeof child === \"object\")\n stack.push({ node: child, depth: depth + 1 });\n }\n }\n return false;\n}\n\n/** The error for input (400) or output (500) that fails its schema. */\nexport function invalid(\n action: string,\n stage: \"input\" | \"output\",\n errors: ValidationErrorItem[],\n): ValidationError {\n return new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction validate(\n check: Checker,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n throw invalid(\n action,\n stage,\n Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n })),\n );\n}\n\nfunction validateInput(\n check: Checker,\n input: unknown,\n action: string,\n checkInput: CompiledRoutePlan[\"checkInput\"],\n) {\n const errors = checkInput?.(input);\n if (errors) throw invalid(action, \"input\", errors);\n if (inputTooDeep(input))\n throw invalid(action, \"input\", [\n { path: \"\", message: \"Input exceeds maximum nesting depth\" },\n ]);\n validate(check, input, action, \"input\");\n}\n\n/** A refused `authorize`: 401 without a user, 403 with one. */\nexport function deny(action: string, user: unknown): never {\n throw new ActionExecutionError(\n user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${action}'`,\n user == null ? 401 : 403,\n );\n}\n\n/** Runs `authorize`, if any, and denies the call when it refuses. */\nasync function authorizeCall(\n authorize: ((params: any) => unknown) | undefined,\n ctx: { user?: unknown },\n input: unknown,\n action: string,\n): Promise<void> {\n if (authorize && !(await authorize({ ctx, input, user: ctx.user })))\n deny(action, ctx.user);\n}\n\n/** What a call runs once its context is ready. */\nexport interface Stages {\n readonly name: string;\n /** @throws The input's validation error. */\n readonly checkInput: (input: unknown) => void;\n readonly authorize?: (params: any) => unknown;\n readonly execute: (params: any) => unknown;\n readonly errorBuilder: unknown;\n /** @throws The output's validation error; else returns the output. */\n readonly checkOutput: (result: unknown) => unknown;\n}\n\n/** The stage order of every call, over HTTP and in-process: check input → authorize → execute → check output. */\nexport async function runStages(\n stages: Stages,\n input: unknown,\n ctx: { user?: unknown },\n): Promise<unknown> {\n stages.checkInput(input);\n await authorizeCall(stages.authorize, ctx, input, stages.name);\n return stages.checkOutput(\n await stages.execute({ input, ctx, error: stages.errorBuilder }),\n );\n}\n\nfunction mapError(\n err: unknown,\n set: any,\n options: { logger: Logger; requestId: string },\n) {\n const response = toErrorResponse(err, options);\n set.status = response.status;\n return response;\n}\n\nconst isThenable = (value: any): value is PromiseLike<unknown> =>\n value != null && typeof value.then === \"function\";\n\n/** The context of one HTTP request, with the trace and request id headers set. */\nfunction requestContext(\n plan: CompiledRoutePlan,\n { headers, request, set }: any,\n): ActionContext & { requestId: string } {\n return baseContext({\n ...requestIds(headers, set),\n request: request instanceof Request ? request : undefined,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n metadata: { headers },\n // resolveServiceContext's rule: the hook sees the service's deps; a plugin's action then gets its own.\n deps: plan.contextHook\n ? plan.service.deps\n : (plan.deps ?? plan.service.deps),\n }) as ActionContext & { requestId: string };\n}\n\n/** The HTTP handler of one route: the pipeline's stages, synchronous when no stage needs to wait. */\nexport function bindRoute(plan: CompiledRoutePlan): CompiledHandler {\n const {\n route,\n execute,\n contextHook,\n authorize,\n inputChecker,\n outputChecker,\n checkInput,\n errorBuilder,\n } = plan;\n const name = route.action;\n const stages: Stages = {\n name,\n checkInput: (input) => {\n if (inputChecker) validateInput(inputChecker, input, name, checkInput);\n },\n authorize,\n execute,\n errorBuilder,\n checkOutput: (result) => {\n if (outputChecker) validate(outputChecker, result, name, \"output\");\n return result;\n },\n };\n if (contextHook || authorize) {\n return async function brickAction(context) {\n const input = readInput(route, context);\n const ctx = requestContext(plan, context);\n try {\n if (contextHook) {\n const extra = await contextHook(ctx);\n if (extra) Object.assign(ctx, extra);\n if (plan.deps) ctx.deps = plan.deps;\n }\n return await runStages(stages, input, ctx);\n } catch (err) {\n return mapError(err, context.set, ctx);\n }\n };\n }\n // Nothing to wait for before `execute`: the same stages, without `authorize`, synchronously.\n return function brickAction(context) {\n const input = readInput(route, context);\n const ctx = requestContext(plan, context);\n try {\n stages.checkInput(input);\n const result = execute({ input, ctx, error: errorBuilder });\n if (isThenable(result))\n return Promise.resolve(result)\n .then(stages.checkOutput)\n .catch((err) => mapError(err, context.set, ctx));\n return stages.checkOutput(result);\n } catch (err) {\n return mapError(err, context.set, ctx);\n }\n };\n}\n\n/** What `bindCompiledApplication`'s handler factories receive. */\nexport const compilerRuntime = Object.freeze({ bindRoute });\n","import type { TSchema } from \"@sinclair/typebox\";\nimport {\n type Action,\n type ActionConfigWithAuthorize,\n type ActionConfigWithoutAuthorize,\n type ActionContext,\n type ActionErrorDefinition,\n type ErrorBuilder,\n ActionExecutionError,\n} from \"./types\";\nimport { normalizeActionError } from \"./error-response\";\nimport { STANDARD_ERRORS } from \"./protocol\";\nimport { validateWithSchema } from \"./typebox\";\nimport { actionMeta } from \"./action-meta\";\nimport { baseContext } from \"./context\";\nimport { invalid, runStages, type Stages } from \"./compiler/runtime\";\n\n/**\n * The `error` helpers an action receives: one function per error code that\n * throws an `ActionExecutionError` with that code and status. The standard HTTP\n * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,\n * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to\n * them or replace one.\n *\n * @param errorsDef - The action's `errors`: for each code, its `message` and\n * `status` (default 400).\n * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,\n * and always throw.\n */\nexport function buildErrorHelpers<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(errorsDef?: TErrors): ErrorBuilder<TErrors> {\n const helpers: Record<string, any> = {};\n // An action's own errors override the standard ones of the same code.\n for (const [code, def] of Object.entries({\n ...STANDARD_ERRORS,\n ...errorsDef,\n }) as [string, ActionErrorDefinition][])\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n throw new ActionExecutionError(\n code,\n overrideMessage || def.message,\n def.status || 400,\n details,\n options,\n );\n };\n\n return helpers as ErrorBuilder<TErrors>;\n}\n\n/** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */\nexport function errorsOf<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(action: { config: { errors?: TErrors } }): TErrors {\n return (action.config.errors ?? {}) as TErrors;\n}\n\n/**\n * Define an action: a typed, validated function that Brick serves over HTTP,\n * runs in-process, and exposes to the typed client and OpenAPI.\n *\n * A call runs in order: the input is validated against `input` (an invalid one\n * is a `VALIDATION_FAILED` error, HTTP 400); `authorize` runs, if there is one;\n * `execute` runs; and its result is validated against `output` (a mismatch is a\n * server error, HTTP 500). Throw `error.CODE(...)` from `execute` for a declared\n * failure or a standard one such as `error.NOT_FOUND()`. Any other thrown value\n * becomes `INTERNAL_SERVER_ERROR` (500), with the cause kept out of the response\n * and in the log.\n *\n * `authorize` returns `false` to refuse: the call fails with `UNAUTHORIZED`\n * (401) when there is no `ctx.user`, and `FORBIDDEN` (403) when there is one.\n * Where it is given, `execute` can rely on what it checked.\n *\n * @param config - `name`, `execute`, and optionally `description`, `input` and\n * `output` (TypeBox schemas), `errors`, `authorize`, `method` and `path` to\n * change the route (POST by default), `tags`, and `emits`.\n * @returns The action. Register it with `service.action(action)`; call it\n * directly with `action.run(input, ctx)`.\n * @example\n * import { defineAction, t } from \"@brickkit/core\";\n *\n * export const getPage = defineAction({\n * name: \"get\",\n * method: \"GET\",\n * input: t.Object({ id: t.String() }),\n * output: t.Object({ id: t.String(), title: t.String() }),\n * errors: { PAGE_GONE: { message: \"That page was removed\", status: 410 } },\n * authorize: ({ user }) => user != null,\n * execute: async ({ input, ctx, error }) => {\n * const page = await findPage(ctx.db, input.id);\n * if (!page) throw error.NOT_FOUND(\"No such page\");\n * return page;\n * },\n * });\n */\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction(config: any): any {\n const errorHelpers = buildErrorHelpers(config.errors);\n\n const actionFn = (async (params: { input?: any; ctx?: any }) => {\n return actionFn.execute(params);\n }) as any;\n\n Object.defineProperty(actionFn, \"name\", {\n value: config.name,\n configurable: true,\n });\n\n actionFn.config = config;\n actionFn.errorHelpers = errorHelpers;\n\n actionFn.validateInput = (input: unknown) => {\n const errors = actionMeta(actionFn).checkInput?.(input);\n return errors\n ? { success: false as const, errors }\n : validateWithSchema(config.input, input);\n };\n\n actionFn.validateOutput = (output: unknown) =>\n validateWithSchema(\n actionMeta(actionFn).runtimeOutput ?? config.output,\n output,\n );\n\n actionFn.run = async (input?: any, ctx?: any) => {\n return actionFn.execute({ input, ctx });\n };\n\n const stages: Stages = {\n name: config.name,\n checkInput: (input) => {\n if (!config.input) return;\n const checked = actionFn.validateInput(input);\n if (!checked.success) throw invalid(config.name, \"input\", checked.errors);\n },\n authorize: config.authorize,\n execute: config.execute,\n errorBuilder: errorHelpers,\n checkOutput: (result) => {\n if (!(actionMeta(actionFn).runtimeOutput ?? config.output)) return result;\n const checked = actionFn.validateOutput(result);\n if (!checked.success)\n throw invalid(config.name, \"output\", checked.errors);\n return result;\n },\n };\n\n actionFn.execute = async (params: { input?: any; ctx?: any }) => {\n const meta = actionMeta(actionFn);\n // The registered service resolves the context once per request, and\n // recognizes one it already resolved.\n const ctx: any = meta.service\n ? await meta.service.resolveContext(params?.ctx, meta.deps?.values)\n : { ...baseContext(params?.ctx ?? {}), ...params?.ctx };\n try {\n return await runStages(stages, params?.input, ctx);\n } catch (err) {\n throw normalizeActionError(err, ctx);\n }\n };\n\n return actionFn;\n}\n","/** The HTTP methods an action, endpoint or plugin route can use. */\nexport const HTTP_METHODS = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"] as const;\nexport type HttpMethod = (typeof HTTP_METHODS)[number];\n","import type { BaseContext, PreparationContribution, Service } from \"./types\";\nimport type { OutboxTable } from \"./events/outbox\";\nimport type { ServiceEvents } from \"./events/types\";\nimport type { EventRef } from \"./events/catalog\";\n\n/**\n * What core's own modules use of a service, beyond the public `Service`. Every\n * service `defineService` makes is one.\n */\nexport interface ServicePort<\n TDb = any,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> extends Service<TDb, TServiceContext> {\n /** The values of this service's `deps`. Set by `brick({ deps })`. */\n readonly deps?: Readonly<Record<string, unknown>>;\n /** Whether the service declares an event catalog. */\n readonly hasCatalog: boolean;\n setDeps(deps: Readonly<Record<string, unknown>>): void;\n /** `resolveContext`, for an action or socket a plugin install created: it sees `pluginDeps`. */\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n pluginDeps?: Readonly<Record<string, unknown>>,\n ): Promise<BaseContext<TDb> & TServiceContext>;\n setRecorder(recorder: ServiceEvents | undefined): void;\n getOutbox(): OutboxTable | undefined;\n /** @throws When the event is not in the catalog or its payload does not match. */\n checkEvent(name: string, payload: unknown): void;\n /** Adds events to the catalog (a plugin's). */\n addEvents(refs: Readonly<Record<string, EventRef>>): void;\n registerTable(table: unknown): this;\n listPreparations(): PreparationContribution[];\n prepareContributions(): void;\n /** Records the declarations; the returned function puts them back (plugin rollback). */\n snapshot(): () => void;\n /** Marks the definitions changed, so cached architecture and OpenAPI are rebuilt. */\n touch(): void;\n}\n\n/** The port of a service: every `Service` is a `ServicePort`. */\nexport function portOf<TDb, TCtx extends Record<string, any>>(\n service: Service<TDb, TCtx>,\n): ServicePort<TDb, TCtx> {\n return service as ServicePort<TDb, TCtx>;\n}\n","import {\n DuplicateNameError,\n type Action,\n type Resource,\n type Service,\n} from \"./types\";\nimport {\n PLUGIN_KIND,\n PLUGIN_COMMIT,\n type PluginEndpointContext,\n type PluginRouteMethod,\n type PluginRouteRegistrar,\n type PluginRoutes,\n type PluginRouteScope,\n PLUGIN_ROUTE_SCOPES,\n type ContextOf,\n type ResourcePlugin,\n type ResourcePluginContext,\n type ServicePlugin,\n type ServicePluginContext,\n} from \"./plugin-types\";\nimport { defineAction } from \"./action\";\nimport { actionMeta, type PluginRouteBinding } from \"./action-meta\";\nimport { kebabCase } from \"./kebab\";\nimport { DEFAULT_PREFIX, pathParamNames, pluginRoutePath } from \"./routes\";\nimport { HTTP_METHODS } from \"./http\";\nimport { portOf } from \"./service-port\";\n\n/**\n * Define a plugin that installs onto a service with `service.use(plugin)`. Its\n * `setup` receives the service and a `routes` registrar for adding actions and\n * raw HTTP endpoints, and returns the typed API that `service.use` hands back.\n *\n * @param definition - A unique `name`, optional `routes` controls that let the\n * user move or switch off the plugin's routes, and `setup`, which must be\n * synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n * @example\n * import { defineServicePlugin, t } from \"@brickkit/core\";\n *\n * export const greeting = (salutation = \"Hello\") =>\n * defineServicePlugin({\n * name: \"example/greeting\",\n * setup({ routes }) {\n * const hello = routes.action({\n * name: \"hello\",\n * input: t.Object({ name: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `${salutation}, ${input.name}!`,\n * });\n * return { hello };\n * },\n * });\n *\n * const api = greeterService.use(greeting(\"Welcome\"));\n * await api.hello({ input: { name: \"Ada\" } });\n */\nexport function defineServicePlugin<\n S extends Service<any, any> = Service<any, any>,\n A = unknown,\n>(\n definition: Omit<ServicePlugin<S, A>, typeof PLUGIN_KIND> & {\n setup: (\n context: ServicePluginContext<S>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ServicePlugin<S, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [PLUGIN_KIND]: \"service\" as const,\n });\n}\n/**\n * Define a plugin that installs onto a resource (a table and its entity) with\n * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a\n * `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and\n * returns the typed API that `resource.use` hands back. `crud` is built this way.\n *\n * @param definition - A unique `name`, optional `routes` controls, and `setup`,\n * which must be synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n */\nexport function defineResourcePlugin<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n A extends object = object,\n>(\n definition: Omit<ResourcePlugin<S, R, A>, typeof PLUGIN_KIND> & {\n setup: (\n context: ResourcePluginContext<S, R>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ResourcePlugin<S, R, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [PLUGIN_KIND]: \"resource\" as const,\n });\n}\n\nexport function validateName(name: string) {\n if (!name || name.trim() !== name)\n throw new Error(\n \"Plugin and route names must be nonempty and have no surrounding whitespace\",\n );\n}\nfunction validatePath(path: string) {\n if (\n !path.startsWith(\"/\") ||\n path.includes(\"?\") ||\n path.includes(\"#\") ||\n path.includes(\"//\") ||\n path.split(\"/\").some((part) => part === \".\" || part === \"..\")\n ) {\n throw new Error(`Invalid plugin route path '${path}'`);\n }\n}\nfunction copyControls<S extends PluginRouteScope>(\n controls: PluginRoutes<S> | undefined,\n): PluginRoutes<S> | undefined {\n if (controls === undefined || controls === false) return controls;\n const result: Record<string, false | { path?: string; scope?: S }> =\n Object.create(null);\n for (const [name, value] of Object.entries(controls)) {\n validateName(name);\n if (value === false) {\n result[name] = false;\n continue;\n }\n if (value.path !== undefined) validatePath(value.path);\n if (value.scope !== undefined && !PLUGIN_ROUTE_SCOPES.includes(value.scope))\n throw new Error(`Invalid plugin route scope '${value.scope}'`);\n result[name] = Object.freeze({ ...value });\n }\n return Object.freeze(result);\n}\n\ntype Binding = PluginRouteBinding;\ninterface RawBinding extends Binding {\n handler: (context: PluginEndpointContext<any>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\ninterface Installation {\n descriptor: object;\n status: \"installing\" | \"installed\";\n api?: unknown;\n}\ninterface PluginState {\n hosts: Map<object, Map<string, Installation>>;\n actions: Map<Action<any, any, any, any>, Binding>;\n endpoints: RawBinding[];\n /** The URL segments under each resource that its plugins claim, and which plugin. */\n claims: Map<object, Map<string, string>>;\n}\nconst states = new WeakMap<object, PluginState>();\n\n/** Records the plugin state; the returned function puts all of it back (a failed install's rollback). */\nfunction snapshotState(state: PluginState): () => void {\n const copy = <V>(maps: Map<object, Map<string, V>>) =>\n new Map([...maps].map(([key, inner]) => [key, new Map(inner)]));\n const saved: PluginState = {\n hosts: copy(state.hosts),\n actions: new Map(state.actions),\n endpoints: [...state.endpoints],\n claims: copy(state.claims),\n };\n return () => {\n // Actions the failed install bound lose their route too.\n for (const action of state.actions.keys())\n if (!saved.actions.has(action)) delete actionMeta(action).route;\n Object.assign(state, saved);\n };\n}\nfunction stateOf(service: Service<any, any>): PluginState {\n let state = states.get(service);\n if (!state) {\n state = {\n hosts: new Map(),\n actions: new Map(),\n endpoints: [],\n claims: new Map(),\n };\n states.set(service, state);\n }\n return state;\n}\nexport function isInstallingPlugin(service: Service<any, any>): boolean {\n return [...(states.get(service)?.hosts.values() ?? [])].some(\n (installations) =>\n [...installations.values()].some((item) => item.status === \"installing\"),\n );\n}\n\n/**\n * The raw HTTP endpoints plugins registered on a service, ready to mount on the\n * application. Each handler resolves the service's context before it runs.\n *\n * @param service - The service plugins were installed on.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns The enabled endpoints: `path`, `method`, `handler`, and the\n * `summary`, `description`, and `tags` for OpenAPI.\n */\nexport function getPluginEndpoints(\n service: Service<any, any>,\n prefix = DEFAULT_PREFIX,\n) {\n return stateOf(service)\n .endpoints.filter((binding) => binding.enabled)\n .map((binding) => ({\n path: pluginRoutePath(binding, prefix),\n method: binding.method,\n service,\n plugin: binding.plugin,\n summary: binding.summary,\n description: binding.description,\n tags: binding.tags,\n handler: async (context: Omit<PluginEndpointContext, \"ctx\">) =>\n binding.handler({\n ...context,\n ctx: await service.resolveContext({ request: context.request }),\n }),\n }));\n}\n\n/** The plugin that claimed `segment` under `resource`, if one did. */\nexport function segmentClaimant(\n service: Service<any, any>,\n resource: object,\n segment: string,\n): string | undefined {\n return states.get(service)?.claims.get(resource)?.get(segment);\n}\n\n/** Descriptor identity is scoped to the service or resource installation host. */\nexport function installPlugin(\n service: Service<any, any>,\n resource: Resource<any, any, any> | undefined,\n descriptor: ServicePlugin<any, any> | ResourcePlugin<any, any, any>,\n) {\n if (service.isBuilt)\n throw new Error(\"Plugins must be installed before service build\");\n if (\n descriptor[PLUGIN_KIND] !== (resource ? \"resource\" : \"service\") &&\n descriptor[PLUGIN_KIND] !== \"plugin\"\n )\n throw new Error(\"Plugin does not support this installation host\");\n const state = stateOf(service);\n const host = resource ?? service;\n const existing = state.hosts.get(host)?.get(descriptor.name);\n if (existing) {\n if (existing.status === \"installing\")\n throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);\n if (existing.descriptor !== descriptor)\n throw new Error(\n `Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`,\n );\n return resource ?? existing.api;\n }\n const restoreService = portOf(service).snapshot();\n const restoreState = snapshotState(state);\n const installations =\n state.hosts.get(host) ?? new Map<string, Installation>();\n state.hosts.set(host, installations);\n installations.set(descriptor.name, { descriptor, status: \"installing\" });\n const names = new Set<string>();\n const commits: (() => void)[] = [];\n const ownedActions = new Set<Action<any, any, any, any>>();\n let active = true;\n const claim = (segment: string) => {\n if (!resource) throw new Error(\"Only resource plugins claim URL segments\");\n const claims = state.claims.get(resource) ?? new Map<string, string>();\n state.claims.set(resource, claims);\n if (claims.has(segment)) return;\n const taken = service.listActions().find((action) => {\n const info = actionMeta(action).resourceAction;\n return (\n info?.resource === resource.name && kebabCase(info.name) === segment\n );\n });\n if (taken)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${taken.name}\" in service \"${service.name}\": \"${segment}\" is a ${descriptor.name} route`,\n );\n claims.set(segment, descriptor.name);\n };\n const bindingFor = (config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: PluginRouteScope;\n }): Binding => {\n if (!active || service.isBuilt)\n throw new Error(\"Plugin routes can only be registered during setup\");\n validateName(config.name);\n validatePath(config.path);\n if (names.has(config.name))\n throw new DuplicateNameError(\n `Duplicate plugin route name '${config.name}'`,\n );\n names.add(config.name);\n const control =\n descriptor.routes === false ? false : descriptor.routes?.[config.name];\n const scope =\n (control && control.scope) ||\n config.scope ||\n (resource ? \"resource\" : \"service\");\n if (scope === \"resource\" && !resource)\n throw new Error(\"Service plugin routes cannot use resource scope\");\n if (!PLUGIN_ROUTE_SCOPES.includes(scope))\n throw new Error(`Invalid plugin route scope '${scope}'`);\n if (!HTTP_METHODS.includes(config.method))\n throw new Error(`Invalid plugin route method '${config.method}'`);\n const path = (control && control.path) || config.path;\n validatePath(path);\n const segment = path.split(\"/\")[1]!;\n if (scope === \"resource\" && segment && !segment.startsWith(\":\"))\n claim(segment);\n return {\n service: service.name,\n resource: resource?.name,\n plugin: descriptor.name,\n path,\n method: config.method,\n scope,\n enabled: control !== false,\n };\n };\n const routes: PluginRouteRegistrar<any> = {\n action(config: any) {\n const binding = bindingFor(config);\n for (const name of pathParamNames(binding.path)) {\n if (\n !config.input?.properties ||\n !Object.hasOwn(config.input.properties, name)\n )\n throw new Error(\n `Plugin action path parameter '${name}' must be declared in its input schema`,\n );\n }\n // Public contract name: resource/operation only (e.g. `page.list`).\n // The owning plugin stays in binding metadata (`plugin`) and on the\n // action (`plugin`/`resource`) so it never leaks into exported names,\n // OpenAPI, or client contracts.\n const name = `${resource ? `${resource.name}.` : \"\"}${config.name}`;\n if (service.getAction(name))\n throw new DuplicateNameError(\n `Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`,\n );\n const {\n scope: _scope,\n runtimeOutput,\n checkInput,\n ...actionConfig\n } = config;\n const action = defineAction({ ...actionConfig, name });\n Object.assign(actionMeta(action), {\n route: binding,\n runtimeOutput,\n checkInput,\n });\n service.action(action);\n ownedActions.add(action);\n state.actions.set(action, binding);\n return action;\n },\n endpoint(config) {\n const binding = bindingFor(config);\n state.endpoints.push({\n ...binding,\n handler: config.handler,\n summary: config.summary,\n description: config.description,\n tags: config.tags,\n });\n },\n claim,\n };\n try {\n const context = {\n service,\n ...(resource ? { resource } : {}),\n routes,\n [PLUGIN_COMMIT]: (commit: () => void) => commits.push(commit),\n };\n const api = resource\n ? (descriptor as ResourcePlugin<any, any, any>).setup(\n context as typeof context & { resource: Resource<any, any, any> },\n )\n : (descriptor as ServicePlugin<any, any>).setup(context);\n if (api && typeof api === \"object\" && \"then\" in api)\n throw new Error(\"Plugin setup must be synchronous\");\n if (\n descriptor.routes &&\n Object.keys(descriptor.routes).some((name) => !names.has(name))\n )\n throw new Error(\n `Plugin '${descriptor.name}' has an override for an unknown route`,\n );\n const walk = (value: unknown, path: string[], ancestors: Set<object>) => {\n if (typeof value === \"function\") {\n const binding = state.actions.get(value as Action<any, any, any, any>);\n if (binding && ownedActions.has(value as Action<any, any, any, any>)) {\n if (binding.clientPath)\n throw new Error(\"Plugin actions must have one returned API path\");\n binding.clientPath = resource\n ? [service.name, resource.name, ...path]\n : [service.name, ...path];\n }\n } else if (value && typeof value === \"object\" && !ancestors.has(value)) {\n const next = new Set(ancestors).add(value);\n for (const [key, child] of Object.entries(value))\n walk(child, [...path, key], next);\n }\n };\n walk(api, [], new Set());\n if (resource) {\n if (!api || typeof api !== \"object\" || Array.isArray(api))\n throw new Error(\"Resource plugins must return named API contributions\");\n for (const key of Object.keys(api)) {\n if (\n key in resource ||\n [\"__proto__\", \"prototype\", \"constructor\"].includes(key)\n )\n throw new Error(\n `Resource plugin contribution '${key}' collides with an existing property`,\n );\n }\n Object.assign(resource, api);\n }\n state.hosts.get(host)!.set(descriptor.name, {\n descriptor,\n status: \"installed\",\n api,\n });\n for (const commit of commits) commit();\n return resource ?? api;\n } catch (error) {\n restoreService();\n restoreState();\n throw error;\n } finally {\n active = false;\n }\n}\n/** Whether a plugin named `name` is installed on `host` (the service or a resource). */\nexport function hasPlugin(\n service: Service<any, any>,\n host: object,\n name: string,\n): boolean {\n return (\n states.get(service)?.hosts.get(host)?.get(name)?.status === \"installed\"\n );\n}\n/** Every descriptor installed on the service or its resources, in install order per host. */\nexport function installedPlugins(service: Service<any, any>): object[] {\n return [...(states.get(service)?.hosts.values() ?? [])].flatMap(\n (installations) =>\n [...installations.values()]\n .filter((item) => item.status === \"installed\")\n .map((item) => item.descriptor),\n );\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Service } from \"./types\";\nimport { portOf } from \"./service-port\";\n\ndeclare const portType: unique symbol;\n\n/** A typed dependency slot, declared with `port<T>()` and filled by `brick({ deps })`. */\nexport interface Port<T> {\n readonly [portType]?: T;\n}\n\n/** The dependency slots of a service: `{ carrier: port<Carrier>() }`. */\nexport type Ports = Record<string, Port<unknown>>;\n\n/** The values a set of ports is filled with: `{ carrier: Carrier }`. */\nexport type DepsOf<P> = {\n [K in keyof P]: P[K] extends Port<infer T> ? T : never;\n};\n\n/**\n * Declare a dependency a service needs, without creating it. The app provides\n * the value with `brick({ deps })`, and the service's code reads it as\n * `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).\n *\n * @returns A slot typed as `T`. It holds nothing at runtime.\n * @example\n * import { defineService, port } from \"@brickkit/core\";\n *\n * export const orders = defineService(\"orders\", {\n * database,\n * deps: { carrier: port<Carrier>() },\n * });\n *\n * // app.ts\n * export default brick({ services: [orders], deps: { carrier: createCarrier() } });\n */\nexport function port<T>(): Port<T> {\n return Object.freeze({}) as Port<T>;\n}\n\n/** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */\nexport const PLUGIN_DEPS: unique symbol = Symbol.for(\"brickkit.plugin.deps\");\n\nconst running = new AsyncLocalStorage<Record<string, unknown>>();\n\n/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */\nexport function runWithDeps<T>(deps: Record<string, unknown>, fn: () => T): T {\n return running.run(deps, fn);\n}\n\n/**\n * The deps of the app that is running the current listener or workflow step.\n * Actions, tools and socket handlers read `ctx.deps` instead.\n *\n * A workflow step is a plain function the Workflow SDK calls by name, so it\n * cannot close over the app that started it. Brick runs every listener and every\n * step inside its app, and this returns that app's `brick({ deps })`.\n *\n * @param ports - Optional: the ports to type the result by (the same object a\n * service passes as its `deps` option). Otherwise pass the type: `useDeps<{ carrier: Carrier }>()`.\n * @returns The app's deps.\n * @throws When called outside a listener or workflow step of a Brick app.\n * @example\n * export const ordersDeps = { carrier: port<Carrier>() };\n *\n * async function bookCarrier(orderId: string) {\n * \"use step\";\n * return useDeps(ordersDeps).carrier.book(orderId);\n * }\n */\nexport function useDeps<const P extends Ports>(ports: P): DepsOf<P>;\nexport function useDeps<T = Record<string, unknown>>(): T;\nexport function useDeps(): Record<string, unknown> {\n const deps = running.getStore();\n if (!deps)\n throw new Error(\n \"useDeps() was called outside a Brick app: call it from a listener or a workflow step (actions read ctx.deps).\",\n );\n return deps;\n}\n\n/**\n * Check `brick({ deps })` against what the services declare, and give each\n * service the values of its own ports.\n *\n * @throws When a service declares a dep the app does not provide, or the app\n * provides one that no service declares.\n */\nexport function bindDeps(\n services: readonly Service<any, any>[],\n provided: Record<string, unknown> = {},\n): void {\n const declared = new Set<string>();\n for (const service of services) {\n const own: Record<string, unknown> = {};\n for (const name of Object.keys(service.options.deps ?? {})) {\n if (!Object.hasOwn(provided, name) || provided[name] === undefined)\n throw new Error(\n `Brick: service \"${service.name}\" declares dep \"${name}\", but brick({ deps }) does not provide it`,\n );\n declared.add(name);\n own[name] = provided[name];\n }\n portOf(service).setDeps(Object.freeze(own));\n }\n for (const name of Object.keys(provided))\n if (!declared.has(name))\n throw new Error(\n `Brick: brick({ deps }) provides \"${name}\", but no service declares it (services: ${services.map((service) => service.name).join(\", \") || \"none\"})`,\n );\n}\n","import { PLUGIN_DEPS } from \"./deps\";\nimport type { EventListener } from \"./events/types\";\nimport type {\n PluginInstallOptions,\n PluginInstance,\n PluginManifest,\n} from \"./define-plugin\";\nimport type { InstalledPlugin } from \"./plugin-types\";\n\nexport const INTERNALS = Symbol.for(\"brickkit.plugin.internals\");\ninterface Installation {\n scope: \"app\" | \"service\" | \"resource\";\n service?: string;\n resource?: string;\n}\nexport interface Internals {\n manifest: PluginManifest<any, any, any, any, any, any, any>;\n options: Record<string, unknown>;\n deps: Readonly<Record<string, unknown>>;\n install: PluginInstallOptions;\n dashboard?: string;\n installs: Installation[];\n /** When it was first installed, to run `app` parts in install order. */\n order?: number;\n}\n\nexport function isPluginInstance(value: unknown): value is PluginInstance {\n return (\n typeof value === \"object\" &&\n value !== null &&\n INTERNALS in (value as object)\n );\n}\nfunction internalsOf(value: unknown): Internals | undefined {\n return isPluginInstance(value)\n ? ((value as unknown as Record<symbol, Internals>)[INTERNALS] ?? undefined)\n : undefined;\n}\n\n/**\n * What `brick()` does with plugins: install those given in `plugins` on the\n * app, run every plugin's `app` part in install order, and return the\n * lifecycle, middleware and listeners they contributed.\n */\nexport function setupAppPlugins(\n installedOnServices: readonly object[],\n appPlugins: readonly unknown[],\n) {\n const instances = new Set<PluginInstance>();\n for (const descriptor of installedOnServices)\n if (isPluginInstance(descriptor)) instances.add(descriptor);\n const ordered = [...instances].sort(\n (a, b) => (internalsOf(a)!.order ?? 0) - (internalsOf(b)!.order ?? 0),\n );\n const onApp = new Set<string>();\n for (const plugin of appPlugins) {\n const internals = internalsOf(plugin);\n if (!internals)\n throw new Error(\n \"brick({ plugins }) takes instances from definePlugin(), such as audit()\",\n );\n const { manifest } = internals;\n if (!manifest.app || manifest.tables || manifest.events)\n throw new Error(\n `${manifest.name} cannot be installed on the app; ${\n manifest.resource ? \"use resource.use()\" : \"use service.use()\"\n }`,\n );\n for (const required of manifest.requires ?? [])\n if (!onApp.has(required))\n throw new Error(\n `${manifest.name} requires ${required}, installed in brick({ plugins }) before it`,\n );\n if (onApp.has(manifest.name))\n throw new Error(`Plugin ${manifest.name} is installed on the app twice`);\n // Its `app` part already runs from the service or resource install; running it again would double every hook.\n const installed = ordered.find(\n (other) => internalsOf(other)!.manifest.name === manifest.name,\n );\n if (installed)\n throw new Error(\n `Plugin ${manifest.name} is already installed with ${internalsOf(\n installed,\n )!\n .installs.map((install) =>\n install.scope === \"resource\"\n ? `${install.service}.${install.resource}.use()`\n : `${install.service}.use()`,\n )\n .join(\n \", \",\n )}, which runs its app part too; remove it from brick({ plugins })`,\n );\n onApp.add(manifest.name);\n if (!internals.installs.some((item) => item.scope === \"app\"))\n internals.installs.push({ scope: \"app\" });\n ordered.push(plugin as PluginInstance);\n }\n\n const lifecycles: Lifecycle[] = [];\n const middleware: ((context: any) => unknown)[] = [];\n const listeners: EventListener[] = [];\n const listed: InstalledPlugin[] = [];\n for (const plugin of ordered) {\n const { manifest, options, deps, installs, dashboard } =\n internalsOf(plugin)!;\n for (const install of installs)\n listed.push(\n Object.freeze({\n name: manifest.name,\n ...(manifest.brick ? { brick: manifest.brick } : {}),\n ...install,\n ...(dashboard ? { dashboard } : {}),\n }),\n );\n if (!manifest.app) continue;\n const lifecycle = { options, secrets: manifest.secrets ?? {}, deps };\n // A plugin's start and stop pair up, so stop runs only after its start did.\n const own = { start: [] as Function[], stop: [] as Function[] };\n manifest.app({\n ...lifecycle,\n on(event, handler) {\n if (event !== \"start\" && event !== \"stop\")\n throw new Error(`${manifest.name}: on() takes \"start\" or \"stop\"`);\n own[event].push(handler);\n },\n middleware(handler) {\n middleware.push(handler);\n },\n listeners(...items) {\n // `useDeps()` in a plugin's listener, and its workflow's steps, return the plugin's deps.\n listeners.push(\n ...items.map((listener) => ({ ...listener, [PLUGIN_DEPS]: deps })),\n );\n },\n });\n lifecycles.push({\n start: async () => {\n for (const handler of own.start) await handler(lifecycle);\n },\n stop: async () => {\n for (const handler of own.stop) await handler(lifecycle);\n },\n });\n }\n return { lifecycles, middleware, listeners, plugins: listed };\n}\n\ninterface Lifecycle {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\n/**\n * Start in install order. Stop what started, in reverse order; a start that\n * fails stops those before it and rethrows.\n */\nexport function pluginLifecycle(lifecycles: readonly Lifecycle[]) {\n let started: Promise<void> | undefined;\n const running: Lifecycle[] = [];\n const stopAll = async () => {\n const errors: unknown[] = [];\n for (const item of running.splice(0).reverse())\n try {\n await item.stop();\n } catch (error) {\n errors.push(error);\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length)\n throw new AggregateError(errors, \"Plugins failed to stop\");\n };\n return {\n start(): Promise<void> {\n return (started ??= (async () => {\n for (const item of lifecycles) {\n try {\n await item.start();\n } catch (error) {\n await stopAll().catch(() => undefined);\n started = undefined;\n throw error;\n }\n running.push(item);\n }\n })());\n },\n async stop(): Promise<void> {\n await started?.catch(() => undefined);\n started = undefined;\n await stopAll();\n },\n };\n}\n","import { fileURLToPath } from \"node:url\";\nimport { DuplicateNameError } from \"./types\";\n\n// The package root (src/ or dist/ is beneath it), so Brick's own frames are skipped.\nconst brickRoot = fileURLToPath(new URL(\"..\", import.meta.url));\n\n/**\n * The first `file:line` outside Brick on the current stack: where a name is\n * being defined. Best-effort: `undefined` when there is no stack.\n */\nexport function definitionSite(): string | undefined {\n // Plugins nest several Brick frames above the caller's.\n const limit = Error.stackTraceLimit;\n Error.stackTraceLimit = 50;\n const stack = new Error().stack;\n Error.stackTraceLimit = limit;\n for (const line of stack?.split(\"\\n\").slice(1) ?? []) {\n const match =\n /(?:\\(|at )(?:file:\\/\\/)?([^\\s()?]+)(?:\\?[^\\s():]*)?:(\\d+):\\d+\\)?$/.exec(\n line,\n );\n if (!match) continue;\n const [, file, row] = match;\n if (\n file!.startsWith(`${brickRoot}src/`) ||\n file!.startsWith(`${brickRoot}dist/`)\n )\n continue;\n return `${file}:${row}`;\n }\n return undefined;\n}\n\n/**\n * Records where `name` is defined. The same file defining it again (a dev\n * reload) replaces the old definition.\n *\n * @throws When a different file already defined `name`.\n */\nexport function claimName(\n sites: Map<string, string | undefined>,\n label: string,\n name: string,\n site: string | undefined,\n): void {\n const file = (at: string | undefined) => at?.replace(/:\\d+$/, \"\");\n if (sites.has(name) && file(sites.get(name)) !== file(site))\n throw new DuplicateNameError(\n `Brick: duplicate ${label}\\n ${sites.get(name) ?? \"unknown\"}\\n ${site ?? \"unknown\"}`,\n );\n sites.set(name, site);\n}\n","import type { HttpMethod } from \"../http\";\nimport { DuplicateNameError, type Service, type Action } from \"../types\";\nimport { actionMeta } from \"../action-meta\";\nimport {\n DEFAULT_PREFIX,\n checkSegments,\n getActionRoute,\n inputSource,\n isReadLike,\n routeKey,\n} from \"../routes\";\nimport { portOf } from \"../service-port\";\n\nexport type RouteMethod = HttpMethod;\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\";\n /** The plugin that registered the action, if one did. */\n readonly plugin?: string;\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n /** Whether the server reads the query first (else path parameters, then body). */\n readonly readLike: boolean;\n /** Where callers send the input: the query (GET, DELETE) or the body. */\n readonly inputSource: \"query\" | \"body\";\n readonly coercions: readonly {\n readonly key: string;\n readonly type: \"number\" | \"boolean\" | \"array\";\n }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly preparations: readonly {\n service: string;\n name: string;\n metadata: unknown;\n }[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = DEFAULT_PREFIX,\n) {\n for (const service of services) service.build();\n return analyzeDeclaredApplication(services, prefix);\n}\n\n/** Inspect current declarations without closing service/plugin setup. */\nexport function analyzeDeclaredApplication(\n services: Service<any, any>[],\n prefix = DEFAULT_PREFIX,\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new DuplicateNameError(\n `Brick compiler: duplicate service '${service.name}'`,\n );\n names.add(service.name);\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, { name: string; plugin: boolean }>();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const route = describeRoute(service, action, method, path);\n const key = routeKey(method, path);\n const previous = registered.get(key);\n if (previous) {\n if (route.plugin || previous.plugin)\n throw new DuplicateNameError(\n `Brick compiler: duplicate plugin route '${method} ${path}'`,\n );\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, {\n name: `${service.name}.${action.name}`,\n plugin: Boolean(route.plugin),\n });\n routes.push(route);\n bindings.push({ service, action });\n };\n for (const service of services) {\n checkSegments(service);\n for (const action of service.listActions()) {\n const route = getActionRoute(action, prefix);\n if (route === false) continue;\n add(service, action, route.method, route.path);\n }\n }\n const preparations = services.flatMap((service) =>\n portOf(service)\n .listPreparations()\n .map((contribution) => ({\n service: service.name,\n name: contribution.name,\n metadata: schemaSnapshot(contribution.describe?.()),\n })),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n preparations,\n diagnostics,\n });\n return { ir, bindings };\n}\n\n/** What the compiler records about one action route. */\nexport function describeRoute(\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n): RouteIR {\n const coercions: { key: string; type: \"number\" | \"boolean\" | \"array\" }[] = [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\")\n coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\") coercions.push({ key, type: \"boolean\" });\n else if (prop.type === \"array\") coercions.push({ key, type: \"array\" });\n }\n const plugin = actionMeta(action).route?.plugin;\n return {\n method,\n path,\n service: service.name,\n action: action.name,\n kind: \"action\",\n ...(plugin ? { plugin } : {}),\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n readLike: isReadLike(method, action.name),\n inputSource: inputSource(method),\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n };\n}\n","import type { Service, Action } from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { createLogger } from \"./logger\";\nimport { actionMeta } from \"./action-meta\";\nimport { describeRoute, type RouteIR } from \"./compiler/ir\";\nimport { portOf } from \"./service-port\";\nimport { bindRoute, type CompiledRoutePlan } from \"./compiler/runtime\";\n\n/** The plan of an analyzed route: its callbacks, validators and logger. */\nexport function planRoute(\n route: RouteIR,\n service: Service,\n action: Action,\n): CompiledRoutePlan {\n const meta = actionMeta(action);\n const outputSchema = meta.runtimeOutput ?? action.config.output;\n return {\n route,\n service: portOf(service),\n action,\n execute: action.config.execute,\n authorize: action.config.authorize,\n contextHook: service.options.context,\n inputChecker: action.config.input\n ? (getCompiledCheck(action.config.input) as any)\n : undefined,\n outputChecker: outputSchema\n ? (getCompiledCheck(outputSchema) as any)\n : undefined,\n errorBuilder: action.errorHelpers,\n logger: createLogger(`[${service.name}:${action.name}]`),\n cachedDb: service.getDb(),\n checkInput: meta.checkInput,\n deps: meta.deps?.values,\n };\n}\n\n/**\n * An Elysia handler for one action. Use it to mount an action on your own\n * Elysia app; `brick()` does it for you.\n *\n * @deprecated Serve actions with `brick()`, or bind every route at once with\n * `compileBrickApplication`.\n * @param service - The service the action belongs to.\n * @param action - The action.\n * @param routePath - The route's path.\n * @param method - The HTTP method (POST by default).\n * @returns A function from the Elysia context to the response.\n */\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n return bindRoute(\n planRoute(\n describeRoute(\n service,\n action,\n (method ?? \"POST\") as RouteIR[\"method\"],\n routePath,\n ),\n service,\n action,\n ),\n );\n}\n","import type { BrickApp } from \"./endpoints\";\n\n/**\n * Whether a value is an application made by `brick()`. It checks for the\n * methods and `definition` a `BrickApp` has, so it also recognizes one built by\n * another copy of the package.\n *\n * @param app - Anything, such as the default export of an entry file.\n * @returns `true` for a `BrickApp`, narrowing its type.\n */\nexport function isBrickApp(app: unknown): app is BrickApp {\n if (!app || typeof app !== \"object\") return false;\n return (\n \"endpoint\" in app &&\n typeof app.endpoint === \"function\" &&\n \"fetch\" in app &&\n typeof app.fetch === \"function\" &&\n \"listen\" in app &&\n typeof app.listen === \"function\" &&\n \"definition\" in app &&\n !!app.definition &&\n typeof app.definition === \"object\" &&\n \"services\" in app.definition &&\n Array.isArray(app.definition.services) &&\n \"prefix\" in app.definition &&\n typeof app.definition.prefix === \"string\"\n );\n}\n\n/**\n * Check that a module's default export is an application ready to be served,\n * for tools that load an entry file.\n *\n * @param app - The default export of an entry file.\n * @returns The app.\n * @throws When it is not a `BrickApp`, or it already called `.listen()`: the\n * entry must only build the app, and leave listening to the server bootstrap.\n */\nexport function requireBrickApp(app: unknown): BrickApp {\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n if (app.server)\n throw new Error(\n \"Brick: the app entry must not call .listen(); use a separate server bootstrap.\",\n );\n return app;\n}\n","import type { Service } from \"./types\";\nimport { planRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport {\n bindRoute,\n compilerRuntime,\n type CompiledHandler,\n type CompiledRoutePlan,\n type HandlerFactory,\n} from \"./compiler/runtime\";\nimport { requireBrickApp } from \"./app-entry\";\nimport { portOf } from \"./service-port\";\n\n/** @throws When the services no longer analyze to `ir`, so the build is stale. */\nfunction analyzeMatching(services: Service<any, any>[], ir: BrickIR) {\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n return analyzed;\n}\n\n/**\n * Build artifact bootstrap: import the app and check that its definitions\n * still match the IR `brick build` compiled.\n *\n * @throws When the app's definitions differ from `ir`.\n */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n ir: BrickIR,\n) {\n const app = requireBrickApp((await load()).default);\n analyzeMatching([...app.definition.services], ir);\n return app;\n}\n\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type {\n CompiledHandler,\n CompiledRoutePlan,\n HandlerFactory,\n} from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n bind: (plan: CompiledRoutePlan, index: number) => CompiledHandler = bindRoute,\n): CompiledApplication {\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(planRoute(route, service, action));\n return Object.freeze({ ir: route, handler: bind(plan, index) });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n /** `\"generic\"` skips the plugins' preparations (no prewarm). */\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n if (options.mode !== \"generic\")\n for (const service of options.services)\n portOf(service).prepareContributions();\n return bindAnalyzed(ir, bindings);\n}\n\n/**\n * Build artifact binder: consumes emitted functions, with no runtime handler code generation.\n *\n * @deprecated `brick build` no longer emits handler factories; built servers\n * use `loadCompiledBrickApp`. Pass `compileBrickApplication(...)` as\n * `brick({ compilation })` instead.\n */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeMatching(services, ir);\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n for (const service of services) portOf(service).prepareContributions();\n return bindAnalyzed(ir, analyzed.bindings, (plan, index) =>\n factories[index]!(plan, compilerRuntime),\n );\n}\n","import type { InstalledPlugin } from \"./plugin-types\";\nimport type { Service, ArchitectureSchema } from \"./types\";\nimport type { RouteIR } from \"./compiler/ir\";\nimport { getActionRoute } from \"./routes\";\nimport type { EventsDefinition } from \"./events/hub\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport { claimName, definitionSite } from \"./definition-site\";\n\nexport interface ArchitectureApplication {\n services: readonly Service<any, any>[];\n routes: readonly RouteIR[];\n events?: EventsDefinition;\n sockets?: readonly (BrickSocketSchema & { service: string; path: string })[];\n plugins?: readonly InstalledPlugin[];\n}\n\nexport class ServiceRegistry {\n private _revision = 0;\n /** Definition revision for invalidating serialized architecture snapshots. */\n get revision(): number {\n return this._revision;\n }\n touch(): void {\n this._revision++;\n }\n\n private services = new Map<string, Service>();\n private sites = new Map<string, string | undefined>();\n\n /** @throws When a different file already registered a service with this name. */\n register(service: Service, site = definitionSite()): void {\n claimName(this.sites, `service \"${service.name}\"`, service.name, site);\n this.services.set(service.name, service);\n this.touch();\n }\n\n get(name: string): Service | undefined {\n return this.services.get(name);\n }\n\n has(name: string): boolean {\n return this.services.has(name);\n }\n\n list(): Service[] {\n return Array.from(this.services.values());\n }\n\n /**\n * The architecture of an app (`app.definition`): its mounted routes. Without\n * one, every registered service with its default routes under `/api`.\n */\n exportArchitecture(\n application?: ArchitectureApplication,\n ): ArchitectureSchema {\n return {\n version: \"1.0.0\",\n ...(application?.events ? { events: application.events } : {}),\n ...(application?.plugins?.length\n ? { plugins: [...application.plugins] }\n : {}),\n services: (application?.services ?? this.list()).map((service) => {\n const byAction = new Map(\n application\n ? application.routes\n .filter((route) => route.service === service.name)\n .map((route) => [route.action, route])\n : service.listActions().flatMap((action) => {\n const route = getActionRoute(action);\n return route ? [[action.name, route] as const] : [];\n }),\n );\n const schema = service.introspect();\n return {\n ...schema,\n ...(application?.sockets\n ? {\n sockets: application.sockets.filter(\n (socket) => socket.service === service.name,\n ),\n }\n : {}),\n actions: schema.actions.map((action) => {\n const route = byAction.get(action.name);\n return route\n ? { ...action, method: route.method, path: route.path }\n : action;\n }),\n };\n }),\n };\n }\n}\n\nlet globalRegistry = new ServiceRegistry();\n\n/**\n * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI\n * generator, `useService`, and the dashboard find services by name.\n *\n * @returns The current global registry.\n */\nexport function getGlobalRegistry(): ServiceRegistry {\n return globalRegistry;\n}\n\n/**\n * Start over with an empty global registry. For tests, which define the same\n * services again in each case; an application never needs it.\n */\nexport function resetGlobalRegistry(): void {\n globalRegistry = new ServiceRegistry();\n}\n","import type { Action, ActionAccessPolicy } from \"./types\";\nimport { actionMeta, type ActionAccessInfo } from \"./action-meta\";\n\nexport type { ActionAccessPolicy, ActionAccessInfo };\n\n/**\n * Record how an action is protected, for tools that cannot read it from the\n * configuration: plugins such as `crud` enforce access inside `execute`, so the\n * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard\n * read what is recorded here.\n *\n * @param action - The action to describe.\n * @param info - Whether it checks authorization and whether it scopes queries,\n * and the resulting policy.\n */\nexport function setActionAccess(action: object, info: ActionAccessInfo): void {\n actionMeta(action).access = {\n hasAuthorize: info.hasAuthorize,\n hasScope: info.hasScope,\n policy: info.policy,\n };\n}\n\n/**\n * How an action is protected: `\"public\"` when nothing checks the caller,\n * `\"authorized\"` when an `authorize` does, and `\"scoped\"` when the action also\n * limits what rows the caller can reach. It reads what a plugin recorded with\n * `setActionAccess`, else the action's own `authorize`, and keeps the policy\n * consistent with the flags.\n *\n * @param action - An action, or any object a plugin described.\n * @returns `hasAuthorize`, `hasScope`, and `policy`.\n */\nexport function getActionAccess(action: Action | object): ActionAccessInfo {\n const meta = actionMeta(action).access;\n const configAuthorize =\n typeof (action as Partial<Action>).config?.authorize === \"function\";\n if (!meta) {\n return {\n hasAuthorize: configAuthorize,\n hasScope: false,\n policy: configAuthorize ? \"authorized\" : \"public\",\n };\n }\n const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);\n const hasScope = Boolean(meta.hasScope);\n let policy: ActionAccessPolicy =\n meta.policy ??\n (hasAuthorize ? (hasScope ? \"scoped\" : \"authorized\") : \"public\");\n // Normalize conflicting metadata so the policy always agrees with the\n // effective flags (e.g. metadata stamped \"public\" on an action that also\n // declares config.authorize must not report policy \"public\").\n if (policy === \"public\" && hasAuthorize)\n policy = hasScope ? \"scoped\" : \"authorized\";\n else if (policy !== \"public\" && !hasAuthorize) policy = \"public\";\n else if (policy === \"scoped\" && !hasScope) policy = \"authorized\";\n return { hasAuthorize, hasScope, policy };\n}\n","import type { EventRef } from \"./events/catalog\";\nimport {\n DEFAULT_PREFIX,\n actionOwners,\n pathParamNames,\n toOpenApiPath,\n} from \"./routes\";\nimport { analyzeDeclaredApplication } from \"./compiler/ir\";\nimport { getActionAccess } from \"./access\";\nimport { getGlobalRegistry } from \"./registry\";\nimport type { Service, ActionErrorDefinition } from \"./types\";\n\n/** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */\nexport const OPENAPI_DEFAULTS = Object.freeze({\n title: \"Brick-TS API Mesh\",\n version: \"1.0.0\",\n path: \"/openapi.json\",\n});\n\nexport interface OpenApiGeneratorOptions {\n title?: string;\n version?: string;\n description?: string;\n prefix?: string;\n services?: Service<any, any>[];\n}\n\nfunction isAnchor(\n node: unknown,\n): node is { $id: string } & Record<string, any> {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$id === \"string\"\n );\n}\n\nfunction isBareRef(node: unknown): node is { $ref: string } {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$ref === \"string\" &&\n !(node as { $ref: string }).$ref.startsWith(\"#\")\n );\n}\n\nfunction toComponentKey(id: string): string {\n return id.replace(/[^A-Za-z0-9.\\-_]+/g, \"_\");\n}\n\n/**\n * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors\n * (`{ $id: \"T0\", ..., { $ref: \"T0\" } }`). OpenAPI interprets a bare `$ref`\n * as an external file reference, so downstream tooling tries to load a\n * file named `T0` and fails. Hoist every anchored subschema into\n * `#/components/schemas/` and rewrite the refs to local pointers.\n * First definition wins when one `$id` is declared twice.\n */\nfunction hoistAnchoredSchemas(spec: Record<string, any>): void {\n const anchored = new Map<string, any>();\n\n const collect = (node: any): any => {\n if (Array.isArray(node)) return node.map(collect);\n if (typeof node !== \"object\" || node === null) return node;\n if (isAnchor(node)) {\n const id = node.$id;\n const { $id: _dropped, ...rest } = node;\n const collected = collect(rest);\n if (!anchored.has(id)) anchored.set(id, collected);\n return { $ref: `#/components/schemas/${toComponentKey(id)}` };\n }\n for (const key of Object.keys(node)) {\n node[key] = collect(node[key]);\n }\n return node;\n };\n\n const rewrite = (node: any): void => {\n if (Array.isArray(node)) {\n for (const child of node) rewrite(child);\n return;\n }\n if (typeof node !== \"object\" || node === null) return;\n if (isBareRef(node)) {\n node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;\n }\n for (const key of Object.keys(node)) rewrite(node[key]);\n };\n\n collect(spec);\n\n const components = (spec.components ??= {}) as Record<string, any>;\n const schemas = (components.schemas ??= {}) as Record<string, any>;\n for (const [id, schema] of anchored) {\n schemas[toComponentKey(id)] = schema;\n }\n\n // Second pass covers refs inside the hoisted copies themselves\n // (e.g. the self-recursive JSON-value schema).\n rewrite(spec);\n}\n\n/**\n * Build the OpenAPI 3.1 document for the services: one path per action route,\n * with request and response schemas from the actions' TypeBox schemas, their\n * declared errors, tags by service, and a bearer security scheme where any\n * action needs authorization. Declared events are listed under `x-brick-events`,\n * by wire name, with their service and payload schema.\n *\n * `brick()` calls this for `/openapi.json`; call it yourself to write the\n * document to a file or feed another tool.\n *\n * @param options - `title`, `version`, and `description` for the `info` block,\n * `prefix` (default `/api`), and the `services` to describe (the global\n * registry's by default).\n * @returns The document as a plain object.\n */\nexport function generateOpenApiSpec(\n options: OpenApiGeneratorOptions = {},\n): Record<string, any> {\n const title = options.title ?? OPENAPI_DEFAULTS.title;\n const version = options.version ?? OPENAPI_DEFAULTS.version;\n const description =\n options.description ??\n \"Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.\";\n const prefix = options.prefix ?? DEFAULT_PREFIX;\n\n const services = options.services ?? getGlobalRegistry().list();\n\n const paths: Record<string, any> = {};\n const tags = new Map<string, string>();\n let hasAnyAuthorizedAction = false;\n\n // The routes the server mounts: shadowed ones are left out, as the router leaves them out.\n const { ir, bindings } = analyzeDeclaredApplication([...services], prefix);\n for (const service of services) {\n tags.set(service.name, `Actions exposed by '${service.name}' service`);\n\n for (const [index, route] of ir.routes.entries()) {\n if (route.service !== service.name) continue;\n const { action } = bindings[index]!;\n const routePath = route.path;\n const method = route.method.toLowerCase();\n const pathParams = pathParamNames(routePath);\n const actionPath = toOpenApiPath(routePath);\n if (!paths[actionPath]) paths[actionPath] = {};\n\n const { plugin, resource } = actionOwners(action);\n // Resource routes group under `service · resource`.\n const group = resource ? `${service.name} · ${resource}` : service.name;\n if (resource)\n tags.set(\n group,\n `Routes of resource '${resource}' in service '${service.name}'`,\n );\n\n const hasAuth = getActionAccess(action).hasAuthorize;\n if (hasAuth) {\n hasAnyAuthorizedAction = true;\n }\n\n const responses: Record<string, any> = {};\n\n if (action.config.output) {\n responses[\"200\"] = {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: action.config.output,\n },\n },\n };\n } else {\n responses[\"200\"] = {\n description: \"Successful response\",\n };\n }\n\n const errorAlternatives = new Set<string>();\n const addError = (\n code: string,\n status: number,\n message: string,\n details?: unknown,\n ) => {\n const key = `${status}:${code}`;\n if (errorAlternatives.has(key)) return;\n errorAlternatives.add(key);\n const schema = {\n allOf: [\n { $ref: \"#/components/schemas/ErrorEnvelope\" },\n {\n type: \"object\",\n properties: {\n code: { const: code },\n status: { const: status },\n ...(details ? { details } : {}),\n },\n },\n ],\n };\n const existing = responses[String(status)];\n if (existing) {\n existing.description += \"; \" + message;\n existing.content[\"application/json\"].schema.oneOf.push(schema);\n } else {\n responses[String(status)] = {\n description: message,\n content: { \"application/json\": { schema: { oneOf: [schema] } } },\n };\n }\n };\n if (action.config.input)\n addError(\"VALIDATION_FAILED\", 400, \"Validation error\");\n if (hasAuth) {\n addError(\"UNAUTHORIZED\", 401, \"Authentication required\");\n addError(\"FORBIDDEN\", 403, \"Access denied\");\n }\n if (action.config.errors) {\n for (const [code, errorDef] of Object.entries(action.config.errors)) {\n const def = errorDef as ActionErrorDefinition;\n addError(code, def.status || 400, def.message || code, def.details);\n }\n }\n addError(\"INTERNAL_SERVER_ERROR\", 500, \"Internal server error\");\n if (action.config.output)\n addError(\"VALIDATION_FAILED\", 500, \"Output validation error\");\n\n const operation: Record<string, any> = {\n operationId: `${service.name}_${action.name}_${method}`,\n summary: `${service.name}.${action.name}`,\n description:\n action.config.description ??\n `Execute action '${action.name}' on service '${service.name}'`,\n tags: [...new Set([group, ...(action.config.tags ?? [])])],\n ...(plugin ? { \"x-brick-plugin\": plugin } : {}),\n ...(resource ? { \"x-brick-resource\": resource } : {}),\n responses,\n };\n\n const inputSchema = action.config.input;\n const properties = inputSchema?.properties ?? {};\n const parameters: any[] = [...new Set(pathParams)].map((key) => ({\n name: key,\n in: \"path\",\n required: true,\n schema: properties[key] ?? { type: \"string\" },\n }));\n if (route.inputSource === \"query\") {\n for (const [key, schema] of Object.entries(properties)) {\n if (pathParams.includes(key)) continue;\n parameters.push({\n name: key,\n in: \"query\",\n required: inputSchema?.required?.includes(key) ?? false,\n schema,\n });\n }\n } else if (inputSchema) {\n const bodySchema =\n pathParams.length && inputSchema.properties\n ? {\n ...inputSchema,\n properties: Object.fromEntries(\n Object.entries(properties).filter(\n ([key]) => !pathParams.includes(key),\n ),\n ),\n required: (inputSchema.required ?? []).filter(\n (key: string) => !pathParams.includes(key),\n ),\n }\n : inputSchema;\n operation.requestBody = {\n required: true,\n content: { \"application/json\": { schema: bodySchema } },\n };\n }\n if (parameters.length) operation.parameters = parameters;\n if (hasAuth) operation.security = [{ bearerAuth: [] }];\n paths[actionPath][method] = operation;\n }\n }\n\n const spec: Record<string, any> = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n description,\n },\n paths,\n tags: Array.from(tags, ([name, description]) => ({ name, description })),\n };\n\n spec.components = {\n schemas: {\n ErrorEnvelope: {\n type: \"object\",\n required: [\"name\", \"code\", \"message\", \"status\", \"requestId\"],\n properties: {\n name: { type: \"string\" },\n code: { type: \"string\" },\n message: { type: \"string\" },\n status: { type: \"integer\" },\n requestId: { type: \"string\" },\n details: {},\n errors: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"path\", \"message\"],\n properties: {\n path: { type: \"string\" },\n message: { type: \"string\" },\n value: {},\n },\n },\n },\n },\n },\n },\n };\n if (hasAnyAuthorizedAction) {\n Object.assign(spec.components, {\n securitySchemes: {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n description: \"Enter your Bearer authentication token\",\n },\n },\n });\n }\n\n const events = Object.fromEntries(\n services.flatMap((service) =>\n Object.values(\n (service as { events?: Record<string, EventRef> }).events ?? {},\n ).map((ref) => [\n ref.name,\n {\n service: service.name,\n payload: ref.schema,\n ...(ref.plugin ? { \"x-brick-plugin\": ref.plugin } : {}),\n },\n ]),\n ),\n );\n if (Object.keys(events).length) spec[\"x-brick-events\"] = events;\n\n // Operations reference live TypeBox schemas. Rewrite only the serialized\n // document so OpenAPI pointers cannot corrupt runtime validation schemas.\n const document: Record<string, any> = JSON.parse(JSON.stringify(spec));\n hoistAnchoredSchemas(document);\n\n return document;\n}\n","/**\n * Type-safe secrets & environment variables.\n *\n * Declare each secret once at module scope instead of scattering untyped\n * `process.env.FOO` reads:\n *\n * const port = defineSecret(\"PORT\").default(\"3333\").transform(Number).require();\n * const baseUrl = defineSecret(\"BASE_URL\").url().require();\n * const key = defineSecret(\"STRIPE_KEY\").validate((v) =>\n * v.startsWith(\"sk_\") || \"must start with sk_\"\n * ).require();\n *\n * Values resolve from the environment (Bun populates `process.env` from\n * `.env` locally; in prod the same env source applies — a future\n * `SecretSource` such as AWS can slot in without touching call sites).\n *\n * Resolution order per secret: test/session override → source (`process.env`\n * by default) → declared `default`. `resolveSecrets()` validates every\n * registered secret at boot and throws listing all missing required ones.\n */\n\nimport { definitionSite } from \"./definition-site\";\n\nexport interface SecretSource {\n get(name: string): string | undefined;\n}\n\n/** Default source: `process.env` (Bun loads `.env` into it automatically). */\nexport const envSource: SecretSource = {\n get: (name: string) => process.env[name],\n};\n\nexport interface SecretOptions {\n /** Fallback when the source has no value. Secrets without a default are required. */\n default?: string;\n}\n\n/** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */\nexport type SecretValidator<T> = (value: T) => void | boolean | string;\n\nconst registry = new Map<string, SecretRef<any>>();\nconst overrides = new Map<string, string>();\n/** Where each secret was first declared. */\nconst sites = new Map<string, string | undefined>();\n\nexport class SecretRef<T = string> {\n readonly name: string;\n readonly options: SecretOptions;\n private transformFn?: (raw: string) => T;\n private validators: SecretValidator<T>[] = [];\n\n constructor(name: string, options: SecretOptions = {}) {\n this.name = name;\n this.options = options;\n }\n\n /** True when a default was declared (i.e. the secret is optional). */\n get hasDefault(): boolean {\n return this.options.default !== undefined;\n }\n\n /** Fallback used when the source has no value. Makes the secret optional. */\n default(value: string): this {\n this.options.default = value;\n return this;\n }\n\n /**\n * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === \"true\"`).\n * Runs before validators; a throwing transform fails resolution.\n */\n transform<U>(fn: (raw: string) => U): SecretRef<U> {\n this.transformFn = fn as unknown as (raw: string) => T;\n return this as unknown as SecretRef<U>;\n }\n\n /** Run a custom check on the (transformed) value at every resolution. */\n validate(fn: SecretValidator<T>): this {\n this.validators.push(fn);\n return this;\n }\n\n /** Shorthand validator: value must parse as a URL. String refs only. */\n url(this: SecretRef<string>): SecretRef<string> {\n this.validators.push((v) => {\n try {\n new URL(v);\n } catch {\n return \"must be a valid URL\";\n }\n });\n return this;\n }\n\n private resolveRaw(source: SecretSource): string | undefined {\n return (\n overrides.get(this.name) ?? source.get(this.name) ?? this.options.default\n );\n }\n\n private coerce(raw: string): T {\n let value: T;\n if (this.transformFn) {\n try {\n value = this.transformFn(raw);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": transform failed (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n } else {\n value = raw as unknown as T;\n }\n for (const fn of this.validators) {\n let result: void | boolean | string;\n try {\n result = fn(value);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (result === false) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": validation failed`,\n );\n }\n if (typeof result === \"string\") {\n throw new Error(`Invalid value for secret \"${this.name}\": ${result}`);\n }\n }\n return value;\n }\n\n /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */\n value(source: SecretSource = envSource): T | undefined {\n const raw = this.resolveRaw(source);\n if (raw === undefined) return undefined;\n return this.coerce(raw);\n }\n\n /** Resolved value, or throws naming the missing/invalid secret. */\n require(source: SecretSource = envSource): T {\n const raw = this.resolveRaw(source);\n if (raw === undefined) {\n throw new Error(\n `Missing required secret \"${this.name}\": set it in .env (local) or the environment (prod)`,\n );\n }\n return this.coerce(raw);\n }\n\n /** True when a value would resolve (override, source, or default). */\n isSet(source: SecretSource = envSource): boolean {\n return this.resolveRaw(source) !== undefined;\n }\n}\n\n/**\n * Declare a secret. Calling it again for the name returns the same ref. From\n * the same line (a module evaluated again) it starts the declaration over, so\n * its builder calls replace the earlier ones instead of adding to them.\n */\nexport function defineSecret(\n name: string,\n options: SecretOptions = {},\n): SecretRef<string> {\n const site = definitionSite();\n const existing = registry.get(name);\n if (existing) {\n if (site !== undefined && sites.get(name) === site) {\n (existing as { options: SecretOptions }).options = options;\n existing[\"validators\"] = [];\n existing[\"transformFn\"] = undefined;\n }\n return existing;\n }\n sites.set(name, site);\n const ref = new SecretRef<string>(name, options);\n registry.set(name, ref);\n return ref;\n}\n\n/**\n * Validate every registered secret at boot. Throws a single error listing\n * all missing required secrets. Returns the resolved values.\n */\nexport function resolveSecrets(\n opts: { source?: SecretSource } = {},\n): Record<string, unknown> {\n const source = opts.source ?? envSource;\n const missing: string[] = [];\n const resolved: Record<string, unknown> = {};\n for (const ref of registry.values()) {\n const v = ref.value(source);\n if (v === undefined) missing.push(ref.name);\n else resolved[ref.name] = v;\n }\n if (missing.length > 0) {\n throw new Error(\n `Missing required secrets: ${missing.join(\", \")}. Set them in .env (local) or the environment (prod)`,\n );\n }\n return resolved;\n}\n\n/** Metadata for introspection (values never exposed — future dashboard use). */\nexport function listSecrets(\n opts: { source?: SecretSource } = {},\n): Array<{ name: string; hasDefault: boolean; isSet: boolean }> {\n const source = opts.source ?? envSource;\n return [...registry.values()].map((ref) => ({\n hasDefault: ref.hasDefault,\n isSet: ref.isSet(source),\n name: ref.name,\n }));\n}\n\n/** Test/session override for one secret (`undefined` clears the override). */\nexport function overrideSecret(name: string, value: string | undefined): void {\n if (value === undefined) overrides.delete(name);\n else overrides.set(name, value);\n}\n\n/** Clear registry and overrides. Test-only. */\nexport function resetSecrets(): void {\n registry.clear();\n overrides.clear();\n sites.clear();\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface RequestLoggingOptions {\n enabled?: boolean;\n logger?: (msg: string) => void;\n}\n\nfunction formatLog(\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number,\n): string {\n return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n}\n\n/**\n * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError\n * while `set.status` may still hold the 200 default when onError runs).\n */\nfunction thrownStatus(error: unknown): number | undefined {\n if (typeof error === \"object\" && error !== null && \"status\" in error) {\n const status: unknown = error.status;\n if (typeof status === \"number\") return status;\n }\n return undefined;\n}\n\n/**\n * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.\n * Timing is tracked per-Request via a WeakMap. The onError hook only logs and\n * returns undefined so existing error mapping is preserved.\n *\n * Hooks are registered with the \"global\" scope so they propagate to the\n * parent app when mounted via `app.use(...)` — Elysia scopes plain instance\n * hooks to the plugin's own routes. Timing is captured in beforeHandle\n * because request hooks are not propagated from a\n * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().\n */\nexport function requestLoggingPlugin(opts: RequestLoggingOptions = {}): Elysia {\n const plugin = new Elysia();\n const enabled = opts.enabled ?? true;\n if (!enabled) return plugin;\n const logger = opts.logger ?? console.log;\n const startedAt = new WeakMap<object, number>();\n\n const markStarted = ({ request }: Pick<Context, \"request\">): void => {\n startedAt.set(request, Date.now());\n };\n\n const logSuccess = ({\n request,\n set,\n }: Pick<Context, \"request\" | \"set\">): void => {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n logger(\n formatLog(request.method, path, set.status ?? 200, Date.now() - start),\n );\n };\n\n const logError = ({\n request,\n set,\n error,\n }: Pick<Context, \"request\" | \"set\"> & { error?: unknown }): undefined => {\n if (request) {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n const status = thrownStatus(error) ?? set.status ?? 500;\n logger(formatLog(request.method, path, status, Date.now() - start));\n }\n return undefined;\n };\n\n plugin.onBeforeHandle(\"global\", markStarted);\n plugin.onAfterHandle(\"global\", logSuccess);\n plugin.onError(\"global\", logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\nimport { OPENAPI_DEFAULTS } from \"./openapi\";\n\n/** An OpenAPI document as plain JSON. */\nexport type OpenApiDocument = Record<string, unknown>;\n\n/** An extra OpenAPI document for the API reference, such as Better Auth's. */\nexport interface ReferenceDocument {\n /** Name in the reference's list of documents. */\n title: string;\n /** The document, or a function returning it; called each time the app starts. */\n document:\n | OpenApiDocument\n | (() => OpenApiDocument | Promise<OpenApiDocument>);\n}\n\n/** A named OpenAPI document ready to render. */\nexport interface ApiDocument {\n title: string;\n document: OpenApiDocument;\n}\n\n/** Developer documentation for the `brick dev` dashboard. */\nexport interface DocumentationOptions {\n /**\n * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the\n * app entry, as it reads in the file that sets it.\n */\n dir: string;\n /**\n * Module whose exports are React components for MDX, added to the built-in\n * ones; a relative path starts where `dir` does. A default export or a\n * `components` export holds the name-to-component map. The dashboard bundles\n * it, so it may import anything the project has.\n */\n components?: string;\n}\n\nexport interface ReferenceOptions {\n /** Also serve a standalone Scalar page here. Without a path, no page is served. */\n path?: string;\n title?: string;\n specUrl?: string;\n /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */\n documents?: ReferenceDocument[];\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/**\n * Standalone Elysia plugin serving GET <path> with the Scalar HTML page.\n *\n * @deprecated Use `brick({ reference: true })` or `reference: { path }`.\n */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? OPENAPI_DEFAULTS.title;\n const specUrl = opts.specUrl ?? OPENAPI_DEFAULTS.path;\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/**\n * Mounts the Scalar reference route onto an existing app.\n *\n * @deprecated Use `brick({ reference: true })` or `reference: { path }`.\n */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","/** Who may open the dashboard that `brick start` serves for monitoring. */\nexport interface DashboardAuth {\n /**\n * Secrets that let a request in. A browser asks for one in its sign-in\n * prompt (any user name, the secret as the password), and monitors and\n * scripts send `Authorization: Bearer <secret>`. Give several to rotate one\n * while the other still works. Each is at least 16 characters long;\n * `openssl rand -base64 32` makes a good one.\n */\n token?: string | readonly string[];\n /**\n * Your own check, to sign people in with the auth the app already has: read\n * a session cookie, verify a Better Auth or Clerk session, look at a header\n * a proxy adds. It receives the request (method, URL, and headers; no body)\n * and returns `true` to let it in, `false` to refuse it with 401, or a\n * `Response` to send instead, such as a redirect to your login page. If it\n * throws or takes longer than five seconds, the request is refused with 503.\n *\n * A request is let in when it carries a valid `token`, or when this\n * returns `true`; give both to let monitors in by token and people in by\n * sign-in.\n */\n authorize?: (\n request: Request,\n ) => boolean | Response | Promise<boolean | Response>;\n}\n\n/**\n * The monitoring dashboard `brick start` serves beside the app, on a port of\n * its own: live requests, logs, errors, and the shape of the service, so it\n * stays reachable when the app's own routes are not. `brick dev` has its own\n * dashboard, set by command line options, and ignores this.\n *\n * Setting it turns on `telemetry`, since the dashboard shows what is traced.\n * While it is on, `ctx.logger` and `console` lines written during a request\n * go to the dashboard instead of the console.\n */\nexport interface DashboardOptions {\n /** Default 9400. */\n port?: number;\n /**\n * The address to listen on. Default `127.0.0.1`, reachable only from the same\n * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard\n * will not start on any other address without it.\n */\n host?: string;\n auth?: DashboardAuth;\n /**\n * Days of finished requests to keep on disk, in `.brick/` of the working\n * folder. Default 0: only what happened since the process started, which is\n * lost when it restarts. Needs a folder that outlives the container.\n */\n historyDays?: number;\n}\n\nconst MIN_TOKEN_LENGTH = 16;\n\n/**\n * Check what `brick()` was given, and freeze it. The secrets sit behind a getter\n * that is not enumerable, so logging or serializing the application definition\n * does not print them.\n */\nexport function normalizeDashboard(\n options: DashboardOptions | undefined,\n): DashboardOptions | undefined {\n if (options === undefined) return undefined;\n const { port, host, auth, historyDays } = options;\n if (\n port !== undefined &&\n (!Number.isInteger(port) || port < 1 || port > 65535)\n )\n throw new Error(\n `Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`,\n );\n if (host !== undefined && (typeof host !== \"string\" || host.trim() === \"\"))\n throw new Error(\n \"Brick: dashboard host must be an address, such as '0.0.0.0'.\",\n );\n if (\n historyDays !== undefined &&\n (!Number.isInteger(historyDays) || historyDays < 0)\n )\n throw new Error(\n `Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`,\n );\n const normalized: DashboardOptions = {\n ...(port !== undefined ? { port } : {}),\n ...(host !== undefined ? { host: host.trim() } : {}),\n ...(historyDays !== undefined ? { historyDays } : {}),\n };\n if (auth !== undefined) {\n const tokens =\n auth.token === undefined\n ? undefined\n : typeof auth.token === \"string\"\n ? [auth.token]\n : [...auth.token];\n if (\n tokens?.some(\n (token) => typeof token !== \"string\" || token.length < MIN_TOKEN_LENGTH,\n )\n )\n throw new Error(\n `Brick: a dashboard token must be at least ${MIN_TOKEN_LENGTH} characters. Try: openssl rand -base64 32`,\n );\n if (auth.authorize !== undefined && typeof auth.authorize !== \"function\")\n throw new Error(\"Brick: dashboard authorize must be a function.\");\n if ((tokens === undefined || tokens.length === 0) && !auth.authorize)\n throw new Error(\n \"Brick: dashboard auth needs a token or an authorize function.\",\n );\n const secrets = Object.freeze({\n ...(tokens ? { token: Object.freeze(tokens) } : {}),\n ...(auth.authorize ? { authorize: auth.authorize } : {}),\n });\n // A getter, so inspecting the object (Bun prints hidden fields too) shows\n // `[Getter]` and not the secrets.\n Object.defineProperty(normalized, \"auth\", {\n enumerable: false,\n get: () => secrets,\n });\n }\n return Object.freeze(normalized);\n}\n","import type { HttpMethod } from \"./http\";\nimport type { RouteIR } from \"./compiler/ir\";\nimport type { Elysia } from \"elysia\";\nimport type { Logger, Service } from \"./types\";\nimport type { DatabaseHandle } from \"./db/define\";\nimport type { ApiDocument, DocumentationOptions } from \"./docs\";\nimport type { DashboardOptions } from \"./dashboard\";\nimport type { EventsDefinition, EventsHub } from \"./events/hub\";\nimport { toErrorResponse } from \"./error-response\";\nimport { pathParamNames, toOpenApiPath } from \"./routes\";\nimport { createLogger } from \"./logger\";\nimport { requestIds } from \"./context\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport type { InstalledPlugin } from \"./plugin-types\";\n\nexport type EndpointMethod = HttpMethod;\n\n/** The logger handed to endpoint handlers (the same one actions get). */\nexport type EndpointLogger = Logger;\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n /** The plugin that contributed it; OpenAPI labels it `x-brick-plugin`. */\n plugin?: string;\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb();\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n const tag = `endpoint:${def.method} ${def.path}`;\n const logger = createLogger(`[${tag}]`);\n return async ({ params, body, query, headers, request, set }: any) => {\n const { traceId, requestId } = requestIds(headers, set);\n\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger,\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err) {\n const failure =\n !(\n err instanceof ActionExecutionError || err instanceof ValidationError\n ) &&\n err !== null &&\n typeof err === \"object\" &&\n \"status\" in err &&\n typeof err.status === \"number\" &&\n Number.isInteger(err.status) &&\n err.status >= 400 &&\n err.status < 500\n ? new ActionExecutionError(\n \"HTTP_ERROR\",\n \"message\" in err && typeof err.message === \"string\"\n ? err.message\n : \"Endpoint error\",\n err.status,\n undefined,\n { cause: err },\n )\n : err;\n const response = toErrorResponse(failure, {\n logger: ctx.logger,\n requestId,\n });\n set.status = response.status;\n return response;\n }\n };\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(def.plugin ? { \"x-brick-plugin\": def.plugin } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Service definitions, prefix, and telemetry setting chosen at construction. */\n readonly definition: {\n readonly routes: readonly RouteIR[];\n readonly sockets: readonly (BrickSocketSchema & {\n service: string;\n path: string;\n })[];\n readonly services: readonly Service<any, any>[];\n readonly prefix: string;\n readonly telemetry: boolean;\n readonly documentation?: DocumentationOptions;\n /** What `brick start` serves for monitoring; its `auth` is not enumerable. */\n readonly dashboard?: DashboardOptions;\n /** The listeners and settings of `events`, as plain data. */\n readonly events?: EventsDefinition;\n /** Every `definePlugin` installation, in install order. */\n readonly plugins?: readonly InstalledPlugin[];\n };\n /**\n * Run the plugins' `on(\"start\")` handlers in install order, once. `listen`\n * calls it; `brick dev` and `brick start` await it before serving. `stop()`\n * runs their `on(\"stop\")` handlers in reverse order.\n */\n start(): Promise<void>;\n /**\n * Start the plugins, listen on `port`, then start event delivery. What\n * `brick dev`, `brick start` and a built server run.\n */\n serve(options: { port: number }): Promise<BrickApp>;\n /**\n * Stop event delivery (finishing deliveries in flight), then the server, then\n * the plugins. `closeActiveConnections` is passed to `stop()`.\n */\n shutdown(closeActiveConnections?: boolean): Promise<void>;\n /**\n * The events of this app, when `events` is set: start and stop delivery, drain\n * what is due, and see or retry what is parked. `brick dev` and `brick start`\n * start it for you.\n */\n readonly events?: EventsHub;\n /** Register a raw endpoint (a plain route, not an action). */\n endpoint(def: EndpointDefinition): void;\n /**\n * The OpenAPI documents behind the dashboard's APIs view: this app's own\n * unless `docs` is false, then those from `reference.documents`.\n */\n referenceDocuments(): Promise<ApiDocument[]>;\n /** This app's OpenAPI document, as `/openapi.json` serves it (also when `docs` is false). */\n openApiDocument(): Record<string, any>;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","const ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nexport function newEventId(now: number = Date.now()): string {\n let time = \"\";\n let remaining = now;\n for (let index = 0; index < 10; index++) {\n time = ALPHABET[remaining % 32] + time;\n remaining = Math.floor(remaining / 32);\n }\n let random = \"\";\n for (const byte of crypto.getRandomValues(new Uint8Array(16))) {\n random += ALPHABET[byte % 32];\n }\n return `evt_${time}${random}`;\n}\n\n/**\n * A delivery's id: `<event id>:<listener>`, which is why a listener name cannot\n * contain `:`.\n */\nexport const deliveryId = (eventId: string, listener: string) =>\n `${eventId}:${listener}`;\n","import {\n bigserial,\n index as pgIndex,\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp,\n} from \"drizzle-orm/pg-core\";\nimport {\n index as sqliteIndex,\n integer as sqliteInteger,\n sqliteTable,\n text as sqliteText,\n} from \"drizzle-orm/sqlite-core\";\nimport { deliveryId } from \"./id\";\nimport type { EventDelivery, EventEnvelope } from \"./types\";\n\nconst OUTBOX = Symbol.for(\"brick.outbox\");\n\nexport const OUTBOX_STATUSES = [\n \"pending\",\n \"claimed\",\n \"delivered\",\n \"dead\",\n] as const;\n/** What the outbox rows are in, by state. */\nexport type OutboxStatus = (typeof OUTBOX_STATUSES)[number];\n\nfunction sqliteOutbox(name: string) {\n const timestampMs = (column: string) =>\n sqliteInteger(column, { mode: \"timestamp_ms\" });\n return sqliteTable(\n name,\n {\n seq: sqliteInteger(\"seq\").primaryKey({ autoIncrement: true }),\n id: sqliteText(\"id\").notNull().unique(),\n eventId: sqliteText(\"event_id\").notNull(),\n listener: sqliteText(\"listener\").notNull(),\n name: sqliteText(\"name\").notNull(),\n payload: sqliteText(\"payload\", { mode: \"json\" }).notNull(),\n traceId: sqliteText(\"trace_id\"),\n source: sqliteText(\"source\"),\n occurredAt: timestampMs(\"occurred_at\").notNull(),\n status: sqliteText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: sqliteInteger(\"attempts\").notNull().default(0),\n lastError: sqliteText(\"last_error\"),\n availableAt: timestampMs(\"available_at\").notNull(),\n claimedAt: timestampMs(\"claimed_at\"),\n deliveredAt: timestampMs(\"delivered_at\"),\n },\n (table) => [\n sqliteIndex(`${name}_due`).on(table.status, table.availableAt),\n sqliteIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\nfunction postgresOutbox(name: string) {\n const at = (column: string) => timestamp(column, { withTimezone: true });\n return pgTable(\n name,\n {\n seq: bigserial(\"seq\", { mode: \"number\" }).primaryKey(),\n id: pgText(\"id\").notNull().unique(),\n eventId: pgText(\"event_id\").notNull(),\n listener: pgText(\"listener\").notNull(),\n name: pgText(\"name\").notNull(),\n payload: jsonb(\"payload\").notNull(),\n traceId: pgText(\"trace_id\"),\n source: pgText(\"source\"),\n occurredAt: at(\"occurred_at\").notNull(),\n status: pgText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: pgInteger(\"attempts\").notNull().default(0),\n lastError: pgText(\"last_error\"),\n availableAt: at(\"available_at\").notNull(),\n claimedAt: at(\"claimed_at\"),\n deliveredAt: at(\"delivered_at\"),\n },\n (table) => [\n pgIndex(`${name}_due`).on(table.status, table.availableAt),\n pgIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\n/** The outbox table of a SQLite database. */\nexport type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;\n/** The outbox table of a Postgres database. */\nexport type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;\n/** An outbox table, made by `outboxTable`. */\nexport type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;\n\n/**\n * The outbox table: where recorded events wait, one row per listener, until they\n * are delivered. A write and the events it causes are inserted in one transaction,\n * so an event is neither lost when the process dies after the write nor sent for a\n * write that was rolled back.\n *\n * Brick does not create tables for you. Put this in the schema of the database\n * whose writes emit events, and your migration tool (such as drizzle-kit) creates\n * it. A service whose database holds the table records events; one without it does\n * not.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_outbox`.\n * @returns A Drizzle table.\n * @example\n * import { defineDatabase, outboxTable } from \"@brickkit/core\";\n *\n * export const outbox = outboxTable(\"postgres\");\n * export const database = defineDatabase({\n * engine: \"postgres\",\n * tables: { users, outbox },\n * });\n */\nexport function outboxTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteOutboxTable;\nexport function outboxTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresOutboxTable;\nexport function outboxTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): OutboxTable {\n const name = options.name ?? \"brick_outbox\";\n const table = engine === \"sqlite\" ? sqliteOutbox(name) : postgresOutbox(name);\n Object.defineProperty(table, OUTBOX, { value: { engine } });\n return table;\n}\n\n/**\n * Whether a value is an outbox table made by `outboxTable`.\n *\n * @param value - Anything.\n * @returns `true` for an outbox table, narrowing its type.\n */\nexport function isOutboxTable(value: unknown): value is OutboxTable {\n return typeof value === \"object\" && value !== null && OUTBOX in value;\n}\n\nexport type OutboxRow = OutboxTable[\"$inferSelect\"];\n\n/** The rows that record an event: one per listener, due now. */\nexport function outboxRows(\n event: Omit<EventEnvelope, \"occurredAt\"> & { occurredAt: Date },\n listeners: readonly string[],\n) {\n return listeners.map((listener) => ({\n id: deliveryId(event.id, listener),\n eventId: event.id,\n listener,\n name: event.name,\n payload: event.payload,\n traceId: event.traceId ?? null,\n source: event.source ?? null,\n occurredAt: event.occurredAt,\n status: \"pending\" as const,\n attempts: 0,\n availableAt: event.occurredAt,\n }));\n}\n\n/** The delivery a row of `outboxRows` is. */\nexport function deliveryOf(row: OutboxRow): EventDelivery {\n return {\n id: row.eventId,\n name: row.name,\n payload: row.payload,\n occurredAt: row.occurredAt.toISOString(),\n ...(row.traceId ? { traceId: row.traceId } : {}),\n ...(row.source ? { source: row.source } : {}),\n listener: row.listener,\n deliveryId: row.id,\n attempt: row.attempts,\n };\n}\n\nexport function outboxEngine(table: OutboxTable): \"sqlite\" | \"postgres\" {\n return (\n table as unknown as Record<symbol, { engine: \"sqlite\" | \"postgres\" }>\n )[OUTBOX].engine;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst sqliteQueues = new WeakMap<object, Promise<unknown>>();\n\ninterface OpenTransaction {\n /** The handles a nested call can pass to join this transaction. */\n handles: Set<unknown>;\n commits: (() => unknown)[];\n open: boolean;\n savepoints: number;\n}\nconst active = new AsyncLocalStorage<OpenTransaction>();\n\nfunction joined(db: unknown): OpenTransaction | undefined {\n const open = active.getStore();\n return open?.open && open.handles.has(db) ? open : undefined;\n}\n\nexport function isSqliteDatabase(db: any): boolean {\n return (\n typeof db?.$client?.prepare === \"function\" &&\n typeof db?.$client?.run === \"function\"\n );\n}\n\nfunction rollbackQuietly(db: any, statement = \"ROLLBACK\"): void {\n try {\n db.$client.run(statement);\n } catch {\n return;\n }\n}\n\nasync function nested<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const commits = open.commits.length;\n try {\n if (!isSqliteDatabase(db))\n // Drizzle runs a nested transaction as a savepoint.\n return await db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n const name = `brick_${++open.savepoints}`;\n db.$client.run(`SAVEPOINT ${name}`);\n try {\n const result = await fn(db);\n db.$client.run(`RELEASE ${name}`);\n return result;\n } catch (error) {\n rollbackQuietly(db, `ROLLBACK TO ${name}`);\n rollbackQuietly(db, `RELEASE ${name}`);\n throw error;\n }\n } catch (error) {\n // Work that was rolled back must not run its commit callbacks.\n open.commits.length = commits;\n throw error;\n }\n}\n\n/**\n * Run `fn` in a database transaction: everything it writes through the `tx` it is\n * given is committed together when it returns, or undone if it throws.\n *\n * Postgres uses a real transaction on one connection. SQLite has one connection\n * and a synchronous driver, which Drizzle's own `transaction` cannot use with an\n * async callback (it would commit before the callback finished). So transactions\n * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.\n * A write made elsewhere in the process during that time, outside this helper,\n * would join the transaction; use Postgres where that matters.\n *\n * A call made inside `fn` with the `tx` it was given (on SQLite, the database\n * itself) joins the open transaction as a savepoint instead of waiting for it: a\n * nested failure undoes only the nested work, and the outer transaction decides\n * the commit. Nested calls must run one at a time.\n *\n * @param db - A Drizzle database, from `service.getDb()`.\n * @param fn - Receives the transaction handle to run queries on.\n * @returns What `fn` returned.\n * @throws What `fn` threw, after rolling back.\n */\nexport async function runInTransaction<T>(\n db: any,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const outer = joined(db);\n if (outer) return nested(db, outer, fn);\n const open: OpenTransaction = {\n handles: new Set(),\n commits: [],\n open: true,\n savepoints: 0,\n };\n let result: T;\n try {\n result = await active.run(open, () => begin(db, open, fn));\n } finally {\n open.open = false;\n }\n for (const commit of open.commits) await commit();\n return result;\n}\n\nasync function begin<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n if (!isSqliteDatabase(db)) {\n return db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n }\n\n open.handles.add(db);\n const previous = sqliteQueues.get(db) ?? Promise.resolve();\n let release!: () => void;\n const turn = new Promise<void>((resolve) => {\n release = resolve;\n });\n sqliteQueues.set(\n db,\n previous.then(() => turn),\n );\n await previous;\n try {\n db.$client.run(\"BEGIN IMMEDIATE\");\n try {\n const result = await fn(db);\n db.$client.run(\"COMMIT\");\n return result;\n } catch (error) {\n rollbackQuietly(db);\n throw error;\n }\n } finally {\n release();\n }\n}\n\n/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */\nexport function inTransaction(db: unknown): boolean {\n return joined(db) !== undefined;\n}\n\n/**\n * Run `fn` once the transaction that `db` belongs to has committed, or now when\n * `db` is not in one opened by `runInTransaction`. It never runs when that\n * transaction, or the savepoint it was queued in, rolls back. An error it throws\n * reaches the caller of the outermost `runInTransaction`, after the commit.\n *\n * @param db - The handle the work ran on: a `tx`, or a database.\n * @param fn - The side effect, such as clearing a cache.\n */\nexport async function onTransactionCommit(\n db: unknown,\n fn: () => unknown,\n): Promise<void> {\n const open = joined(db);\n if (open) open.commits.push(fn);\n else await fn();\n}\n","import { and, asc, eq, inArray, lt, lte, or, sql } from \"drizzle-orm\";\nimport {\n deliveryOf,\n OUTBOX_STATUSES,\n outboxEngine,\n type OutboxRow,\n type OutboxStatus,\n type OutboxTable,\n} from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type { Deliverable } from \"./hub\";\nimport { ActionExecutionError } from \"../types\";\nimport type { DispatchOptions } from \"./types\";\n\nfunction resolveDispatchOptions(\n options: DispatchOptions,\n): Required<DispatchOptions> {\n return {\n timer: options.timer ?? true,\n intervalMs: options.intervalMs ?? 1_000,\n batchSize: options.batchSize ?? 50,\n maxAttempts: options.maxAttempts ?? 8,\n claimTimeoutMs: options.claimTimeoutMs ?? 60_000,\n maxBackoffMs: options.maxBackoffMs ?? 300_000,\n retainDeliveredMs: options.retainDeliveredMs ?? 86_400_000,\n };\n}\n\n/** How many outbox rows are in each state. */\nexport type OutboxCounts = Record<OutboxStatus, number>;\n\nconst PURGE_INTERVAL_MS = 60_000;\n\n/** Listeners whose `retry` threw, logged once each. */\nconst brokenRetry = new WeakSet<Deliverable>();\n\n/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as \"retry\", and is logged once. */\nfunction decideRetry(\n name: string,\n listener: Deliverable,\n error: unknown,\n): \"retry\" | \"dead\" {\n if (!listener.retry) return \"retry\";\n try {\n return listener.retry(\n error instanceof ActionExecutionError && listener.errors?.[error.code]\n ? { code: error.code, message: error.message, details: error.details }\n : {\n code: \"UNKNOWN\",\n message: error instanceof Error ? error.message : String(error),\n cause: error,\n },\n );\n } catch (thrown) {\n if (!brokenRetry.has(listener)) {\n brokenRetry.add(listener);\n console.error(\n `[Brick-TS events] Listener '${name}': its retry() threw, so the failure is retried. Later throws are not logged.`,\n thrown,\n );\n }\n return \"retry\";\n }\n}\n\nexport function backoffMs(attempt: number, maxBackoffMs: number): number {\n return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);\n}\n\n/**\n * Delivers the events recorded in one outbox table to the app's listeners.\n *\n * It claims a batch of due rows, runs each listener, and marks the row delivered.\n * A listener that throws is retried later with a growing delay, and parked as\n * dead after its attempts run out. Several dispatchers can share a table: on\n * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not\n * finished within `claimTimeoutMs` (the process died) is taken by another.\n * Delivery is at least once, so a listener should tolerate running twice for the\n * same `deliveryId`.\n */\nexport class Dispatcher {\n private readonly engine: \"sqlite\" | \"postgres\";\n private readonly options: Required<DispatchOptions>;\n private readonly inFlight = new Set<Promise<void>>();\n private timer?: ReturnType<typeof setInterval>;\n private tickQueue?: Promise<number>;\n private lastPurge = 0;\n\n constructor(\n private readonly db: any,\n private readonly table: OutboxTable,\n private readonly listeners: (name: string) => Deliverable | undefined,\n options: DispatchOptions = {},\n ) {\n this.engine = outboxEngine(table);\n this.options = resolveDispatchOptions(options);\n }\n\n /** Start looking for due deliveries on a timer. Does nothing if it already is. */\n start(): void {\n if (this.timer || !this.options.timer) return;\n this.timer = setInterval(() => void this.tick(), this.options.intervalMs);\n this.timer.unref?.();\n void this.tick();\n }\n\n /** Stop the timer and wait for the deliveries that are running to finish. */\n async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n await this.tickQueue;\n await Promise.allSettled(this.inFlight);\n }\n\n /** Look for work soon, without waiting for the timer. Safe to call often. */\n notify(): void {\n if (!this.timer) return;\n setTimeout(() => void this.tick(), 0).unref?.();\n }\n\n /** Claim what is due and run it, once. @returns How many deliveries it started. */\n private tick(): Promise<number> {\n this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(\n () => this.claimAndRun(),\n () => this.claimAndRun(),\n );\n return this.tickQueue;\n }\n\n /**\n * Deliver everything that is due now and wait until those deliveries are done.\n * Deliveries that fail and are rescheduled are not waited for again.\n *\n * @returns How many deliveries it ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (;;) {\n const started = await this.tick();\n await Promise.allSettled(this.inFlight);\n if (started === 0) return total;\n total += started;\n }\n }\n\n async counts(): Promise<OutboxCounts> {\n const t = this.table as any;\n const rows: { status: OutboxStatus; count: number }[] = await this.db\n .select({ status: t.status, count: sql<number>`count(*)` })\n .from(t)\n .groupBy(t.status);\n const counts = Object.fromEntries(\n OUTBOX_STATUSES.map((status) => [status, 0]),\n ) as OutboxCounts;\n for (const row of rows) counts[row.status] = Number(row.count);\n return counts;\n }\n\n /**\n * Put parked deliveries back in line, with their attempts reset.\n *\n * @param deliveryId - One delivery to retry. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n const t = this.table as any;\n const rows: { id: string }[] = await this.db\n .update(t)\n .set({ status: \"pending\", attempts: 0, availableAt: new Date() })\n .where(\n deliveryId\n ? and(eq(t.status, \"dead\"), eq(t.id, deliveryId))\n : eq(t.status, \"dead\"),\n )\n .returning({ id: t.id });\n if (rows.length) this.notify();\n return rows.length;\n }\n\n private async claimAndRun(): Promise<number> {\n try {\n const room = this.options.batchSize - this.inFlight.size;\n if (room <= 0) return 0;\n const rows = await this.claim(room);\n for (const row of rows) {\n const run = this.deliver(row).finally(() => {\n this.inFlight.delete(run);\n });\n this.inFlight.add(run);\n }\n await this.purgeDelivered();\n return rows.length;\n } catch (error) {\n this.logError(error);\n return 0;\n }\n }\n\n private async claim(limit: number): Promise<OutboxRow[]> {\n const t = this.table as any;\n const now = new Date();\n const stale = new Date(now.getTime() - this.options.claimTimeoutMs);\n const due = or(\n and(eq(t.status, \"pending\"), lte(t.availableAt, now)),\n and(eq(t.status, \"claimed\"), lt(t.claimedAt, stale)),\n );\n const claimIn = async (tx: any): Promise<OutboxRow[]> => {\n let select = tx\n .select()\n .from(t)\n .where(due)\n .orderBy(asc(t.seq))\n .limit(limit);\n if (this.engine === \"postgres\")\n select = select.for(\"update\", { skipLocked: true });\n const picked: OutboxRow[] = await select;\n if (!picked.length) return [];\n await tx\n .update(t)\n .set({\n status: \"claimed\",\n claimedAt: now,\n attempts: sql`${t.attempts} + 1`,\n })\n .where(\n inArray(\n t.seq,\n picked.map((row) => row.seq),\n ),\n );\n return picked.map((row) => ({ ...row, attempts: row.attempts + 1 }));\n };\n return this.engine === \"postgres\"\n ? this.db.transaction(claimIn)\n : runInTransaction(this.db, claimIn);\n }\n\n private async deliver(row: OutboxRow): Promise<void> {\n const listener = this.listeners(row.listener);\n if (!listener) {\n await this.park(row, `No listener named '${row.listener}' is registered`);\n return;\n }\n try {\n await listener.run(deliveryOf(row));\n } catch (error) {\n await this.fail(\n row,\n error,\n listener.maxAttempts ?? this.options.maxAttempts,\n decideRetry(row.listener, listener, error),\n );\n return;\n }\n await this.markDelivered(row);\n }\n\n private async markDelivered(row: OutboxRow): Promise<void> {\n const t = this.table as any;\n try {\n if (this.options.retainDeliveredMs === 0)\n await this.db.delete(t).where(eq(t.seq, row.seq));\n else\n await this.db\n .update(t)\n .set({\n status: \"delivered\",\n deliveredAt: new Date(),\n lastError: null,\n })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.logError(error);\n }\n }\n\n private async fail(\n row: OutboxRow,\n error: unknown,\n maxAttempts: number,\n decision: \"retry\" | \"dead\",\n ): Promise<void> {\n const message = error instanceof Error ? error.message : String(error);\n if (decision === \"dead\" || row.attempts >= maxAttempts) {\n await this.park(row, message);\n return;\n }\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({\n status: \"pending\",\n lastError: message,\n claimedAt: null,\n availableAt: new Date(\n Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs),\n ),\n })\n .where(eq(t.seq, row.seq));\n } catch (writeError) {\n this.logError(writeError);\n }\n }\n\n private async park(row: OutboxRow, message: string): Promise<void> {\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({ status: \"dead\", lastError: message, claimedAt: null })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.logError(error);\n }\n }\n\n private logError(error: unknown): void {\n console.error(\"[Brick-TS events]\", error);\n }\n\n private async purgeDelivered(): Promise<void> {\n const keep = this.options.retainDeliveredMs;\n const now = Date.now();\n if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;\n this.lastPurge = now;\n const t = this.table as any;\n await this.db\n .delete(t)\n .where(\n and(eq(t.status, \"delivered\"), lt(t.deliveredAt, new Date(now - keep))),\n );\n }\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport { validateWithSchema } from \"../typebox\";\n\n/** A service's declared events: payload schema by event name. */\nexport type EventCatalog = Record<string, TSchema>;\n\n/**\n * One declared event, as `service.events.<name>`. Pass it to `defineListener({ on })`\n * for a typed payload, or to `emitEvent` for a checked one.\n */\nexport interface EventRef<TPayload = unknown> {\n /** The event name on the wire: `<service>.<event>`, such as `orders.shipped`. */\n readonly name: string;\n readonly service: string;\n readonly schema: TSchema;\n /** The plugin that declared it, for events a `definePlugin` adds. */\n readonly plugin?: string;\n /** Type-level only: the payload this event carries. */\n readonly __payload?: TPayload;\n}\n\n/** `service.events`: one `EventRef` per catalog entry. */\nexport type EventRefs<C extends EventCatalog> = {\n readonly [K in keyof C & string]: EventRef<Static<C[K]>>;\n};\n\n/** What a service with a catalog checks before recording an event. */\nexport interface EventChecker {\n readonly name: string;\n readonly events: Readonly<Record<string, EventRef>>;\n /** Whether the service has a catalog at all. */\n readonly hasCatalog: boolean;\n listResources(): readonly { name: string }[];\n}\n\nexport function isEventRef(value: unknown): value is EventRef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as EventRef).name === \"string\" &&\n typeof (value as EventRef).service === \"string\" &&\n typeof (value as EventRef).schema === \"object\"\n );\n}\n\n/** Build `service.events` from its catalog. */\nexport function eventRefs(\n service: string,\n catalog: EventCatalog | undefined,\n): Record<string, EventRef> {\n const refs: Record<string, EventRef> = Object.create(null);\n for (const [key, schema] of Object.entries(catalog ?? {})) {\n if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key))\n throw new Error(\n `Event \"${key}\" in service \"${service}\" must be a plain name such as shipped or itemAdded`,\n );\n if (!schema || typeof schema !== \"object\")\n throw new Error(\n `Event \"${service}.${key}\" needs a payload schema, such as t.Object({ ... })`,\n );\n refs[key] = Object.freeze({ name: `${service}.${key}`, service, schema });\n }\n return Object.freeze(refs);\n}\n\n/** @throws When the payload does not match the event's schema. */\nexport function checkPayload(ref: EventRef, payload: unknown): void {\n const result = validateWithSchema(ref.schema, payload);\n if (!result.success)\n throw new Error(\n `Event \"${ref.name}\" payload does not match its schema: ${result.errors\n .map((error) => `${error.path || \"/\"} ${error.message}`)\n .join(\"; \")}`,\n );\n}\n\n/** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */\nexport const CRUD_EVENT_OPERATIONS = [\"create\", \"update\", \"delete\"] as const;\nexport type CrudEventOperation = (typeof CRUD_EVENT_OPERATIONS)[number];\n\n/** The event a CRUD write records: `<resource>.<operation>`. */\nexport const crudEventName = (\n resource: string,\n operation: CrudEventOperation,\n): string => `${resource}.${operation}`;\n\n/** The `source` of a resource's events: `<service>.<resource>`. */\nexport const crudEventSource = (service: string, resource: string): string =>\n `${service}.${resource}`;\n\n/** Whether `name` is the CRUD event of one of `resources`. */\nexport function isCrudEvent(\n name: string,\n resources: readonly string[],\n): boolean {\n const dot = name.indexOf(\".\");\n return (\n dot > 0 &&\n (CRUD_EVENT_OPERATIONS as readonly string[]).includes(\n name.slice(dot + 1),\n ) &&\n resources.includes(name.slice(0, dot))\n );\n}\n\n/**\n * Check an event against the catalog of the service recording it. Without a\n * catalog any name goes. With one, the name must be `<service>.<event>` from it\n * (the payload is checked against its schema) or a CRUD event of one of the\n * service's resources (`<resource>.create|update|delete`).\n *\n * @throws When the name is not declared or the payload does not match.\n */\nexport function checkEvent(\n service: EventChecker,\n name: string,\n payload: unknown,\n): void {\n const prefix = `${service.name}.`;\n const ref = name.startsWith(prefix)\n ? service.events[name.slice(prefix.length)]\n : undefined;\n if (ref) return checkPayload(ref, payload);\n if (!service.hasCatalog) return;\n if (\n isCrudEvent(\n name,\n service.listResources().map((r) => r.name),\n )\n )\n return;\n throw new Error(\n `Event \"${name}\" is not in the event catalog of service \"${service.name}\" (declared: ${\n Object.values(service.events)\n .map((ref) => ref.name)\n .join(\", \") || \"none\"\n })`,\n );\n}\n","import { isEventRef, type EventRef } from \"./catalog\";\nimport { buildErrorHelpers } from \"../action\";\nimport { PLUGIN_DEPS } from \"../deps\";\nimport type { ActionErrorDefinition, ErrorBuilder } from \"../types\";\nimport type {\n EventDelivery,\n EventListener,\n EventWorkflow,\n ListenerFailure,\n RetryDecision,\n} from \"./types\";\n\ntype EventOn = EventRef<any> | readonly EventRef<any>[];\ntype PayloadOf<O> =\n O extends EventRef<infer P>\n ? P\n : O extends readonly EventRef<infer P>[]\n ? P\n : never;\n\ntype ListenerConfig<\n TPayload,\n TOn = string | readonly string[],\n TErrors extends Record<string, ActionErrorDefinition> = {},\n> = {\n name: string;\n on: TOn;\n maxAttempts?: number;\n /** Errors `run` may raise with `error.CODE()`. Spread `defineError(...)` results or `errorsOf(action)` here. */\n errors?: TErrors;\n /** Decides what a failure does next. Without it every failure retries until `maxAttempts`. */\n retry?: (error: ListenerFailure<TErrors>) => RetryDecision;\n} & (\n | {\n run: (\n delivery: EventDelivery<TPayload>,\n helpers: { error: ErrorBuilder<TErrors> },\n ) => void | Promise<void>;\n workflow?: never;\n }\n | { workflow: EventWorkflow<TPayload>; run?: never }\n);\n\n/**\n * Define a listener: code that runs for each event it listens for, after the write\n * that caused the event has been committed. Pass it to `brick({ events: {\n * listeners } })`.\n *\n * It either runs a handler (`run`) in the process that delivers events, or starts\n * a durable workflow (`workflow`) on the app's `events.world`. Delivery is at\n * least once. A handler that throws is retried later with a growing delay, then\n * parked as dead, so it can run again for the same event: use\n * `delivery.deliveryId` to make its work idempotent. A workflow needs no such\n * care: a delivery starts one run however often it is tried, and the workflow\n * retries its own steps.\n *\n * A listener can declare `errors`, as an action does, and raise them in `run` with\n * `error.CODE()`. `retry(error)` then picks `\"retry\"` or `\"dead\"` from the typed\n * `error.code`; anything not declared arrives as `{ code: \"UNKNOWN\", cause }`.\n *\n * @param config - `name` (unique; it is part of each delivery's id), `on` (a\n * declared event such as `orders.events.shipped`, which types the payload, or an\n * event name; or a list of either; a trailing `*` matches a prefix, as in\n * `user.*`), `run` or `workflow`, and optionally `maxAttempts`.\n * @returns The listener.\n * @throws When the name is empty or contains `:`, `on` is empty, or the listener\n * has both or neither of `run` and `workflow`.\n * @example\n * import { brick, defineListener } from \"@brickkit/core\";\n *\n * const welcome = defineListener({\n * name: \"welcome-email\",\n * on: \"user.create\",\n * run: async ({ payload, deliveryId }) => {\n * await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });\n * },\n * });\n *\n * export default brick({ services, events: { listeners: [welcome] } });\n * @example\n * // src/workflows/onboard.ts\n * export async function onboard(event: WorkflowEvent<CrudEventPayload>) {\n * \"use workflow\";\n * await sendWelcome(event.payload.row.email);\n * }\n *\n * defineListener({ name: \"onboard\", on: \"user.create\", workflow: onboard });\n * @example\n * // payload is { id: string; trackingId: string }, from the orders catalog.\n * defineListener({\n * name: \"notify-shipped\",\n * on: orders.events.shipped,\n * run: ({ payload }) => notify(payload.id, payload.trackingId),\n * });\n */\nexport function defineListener<\n const TOn extends EventOn,\n const TErrors extends Record<string, ActionErrorDefinition> = {},\n>(\n config: ListenerConfig<PayloadOf<TOn>, TOn, TErrors>,\n): EventListener<PayloadOf<TOn>>;\nexport function defineListener<\n TPayload = any,\n const TErrors extends Record<string, ActionErrorDefinition> = {},\n>(\n config: ListenerConfig<\n TPayload,\n string | EventRef<any> | readonly (string | EventRef<any>)[],\n TErrors\n >,\n): EventListener<TPayload>;\nexport function defineListener(\n config: ListenerConfig<any, unknown, any>,\n): EventListener {\n const on = (Array.isArray(config.on) ? config.on : [config.on]).map(\n (item: unknown) => (isEventRef(item) ? item.name : item),\n ) as string[];\n validateListener({ ...config, on } as EventListener);\n const helpers = buildErrorHelpers(config.errors);\n return Object.freeze({\n name: config.name,\n on: Object.freeze(on),\n ...(config.run !== undefined\n ? {\n run: ((delivery: EventDelivery) =>\n config.run!(delivery, { error: helpers })) as EventListener[\"run\"],\n }\n : {}),\n ...(config.errors ? { errors: config.errors } : {}),\n ...(config.retry ? { retry: config.retry } : {}),\n ...(config.workflow !== undefined ? { workflow: config.workflow } : {}),\n ...(config.maxAttempts !== undefined\n ? { maxAttempts: config.maxAttempts }\n : {}),\n });\n}\n\n/**\n * @throws When the name is empty or contains `:`, `on` is empty, `maxAttempts`\n * is not a positive integer, or the listener has both or neither of `run` and\n * `workflow`.\n */\nexport function validateListener(listener: EventListener): void {\n const { name, on, maxAttempts, run, workflow } = listener;\n if (typeof name !== \"string\" || !name)\n throw new Error(\"An event listener needs a name\");\n // A listener's name ends its delivery ids: see `deliveryId`.\n if (name.includes(\":\"))\n throw new Error(`Event listener name '${name}' must not contain ':'`);\n if (\n !Array.isArray(on) ||\n !on.length ||\n on.some((pattern) => !pattern || typeof pattern !== \"string\")\n )\n throw new Error(`Event listener '${name}' listens for nothing`);\n if (\n maxAttempts !== undefined &&\n (!Number.isInteger(maxAttempts) || maxAttempts < 1)\n )\n throw new Error(\n `Event listener '${name}': maxAttempts must be a positive integer`,\n );\n if (run !== undefined && workflow !== undefined)\n throw new Error(\n `Event listener '${name}' has both run and workflow; give it one`,\n );\n if (run === undefined && workflow === undefined)\n throw new Error(\n `Event listener '${name}' needs a run handler or a workflow`,\n );\n if (run !== undefined && typeof run !== \"function\")\n throw new Error(`Event listener '${name}': run must be a function`);\n if (workflow !== undefined && typeof workflow !== \"function\")\n throw new Error(\n `Event listener '${name}': workflow must be a function marked \"use workflow\"`,\n );\n}\n\n/** The deps a plugin's listener runs with, set by the plugin install; `undefined` for the app's own. */\nexport const listenerDeps = (listener: EventListener) =>\n (listener as { [PLUGIN_DEPS]?: Record<string, unknown> })[PLUGIN_DEPS];\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { runWithDeps } from \"../deps\";\nimport { listenerDeps } from \"./listener\";\nimport type {\n EventDelivery,\n EventListener,\n EventsWorld,\n WorkflowEvent,\n WorkflowsOptions,\n} from \"./types\";\n\n/** The workflow bundle `buildWorkflows()` writes and the runtime reads: its directory under the project root, and its files. */\nexport const WORKFLOW_BUNDLE = {\n dir: \".well-known/workflow/v1\",\n flow: \"flow.mjs\",\n steps: \"__step_registrations.mjs\",\n webhook: \"webhook.mjs\",\n manifest: \"manifest.json\",\n} as const;\n/** From the Workflow SDK: the queue a workflow run goes to (`getQueueTopicPrefix(\"workflow\")` in `@workflow/world`), and the header a world names it in. */\nexport const WORKFLOW_QUEUE = {\n prefix: \"__wkf_workflow_\",\n header: \"x-vqs-queue-name\",\n} as const;\nconst STOPPED = \"The events were stopped, so workflows can no longer run\";\nconst NOT_BUILT =\n \"brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\";\n/** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */\nexport const WEBHOOK_ROUTE = `/${WORKFLOW_BUNDLE.dir}/webhook/*`;\n/** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */\nconst STEP_REGISTRY = Symbol.for(\"@workflow/core//registeredSteps\");\n\ninterface WorkflowSdk {\n start(\n workflow: unknown,\n args: unknown[],\n options: Record<string, unknown>,\n ): Promise<{ runId: string }>;\n setWorld(world: unknown): void;\n}\n\ninterface BundleManifest {\n steps?: Record<string, unknown>;\n workflows?: Record<string, Record<string, { workflowId?: string }>>;\n}\n\n/**\n * Where the workflow bundle is read from, and the project it is built from.\n *\n * @param options - The `events.workflows` option.\n * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the\n * builder finds the SDK from where it writes, and skips only this directory when it\n * looks for workflows.\n */\nexport function resolveWorkflowPaths(options: WorkflowsOptions = {}): {\n root: string;\n dir: string;\n} {\n const root = resolve(options.root ?? process.cwd());\n return { root, dir: join(root, WORKFLOW_BUNDLE.dir) };\n}\n\n/**\n * Runs workflow listeners: wires the world into the Workflow SDK, serves the\n * built bundle from this process, and starts one run for each delivery.\n *\n * Nothing is loaded until it is needed, so an app without workflow listeners\n * never imports the SDK.\n */\nexport class WorkflowRuntime {\n readonly root: string;\n readonly dir: string;\n private ready: Promise<WorkflowSdk> | undefined;\n private connected: Promise<WorkflowSdk> | undefined;\n private closed = false;\n\n constructor(\n readonly world: EventsWorld,\n options: WorkflowsOptions | undefined,\n private readonly listeners: readonly EventListener[],\n private readonly deps: Record<string, unknown> = {},\n ) {\n ({ root: this.root, dir: this.dir } = resolveWorkflowPaths(options));\n }\n\n /** Begin loading the runtime now rather than at the first delivery. */\n warmUp(): void {\n this.ensure().catch((error) =>\n console.error(\n `[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n\n /**\n * Start the run for a delivery.\n *\n * The run is named after the delivery id, so a delivery that is tried again\n * finds the run it already started instead of starting another.\n *\n * @param listener - The workflow listener the delivery is for.\n * @param delivery - The delivery.\n */\n async startRun(\n listener: EventListener,\n delivery: EventDelivery,\n ): Promise<void> {\n const sdk = await this.ensure();\n const { attempt: _attempt, ...event } = delivery;\n await sdk.start(listener.workflow, [event satisfies WorkflowEvent], {\n world: this.world,\n runKey: delivery.deliveryId,\n runKeyTime: Date.parse(delivery.occurredAt),\n });\n }\n\n /**\n * Answer a request to a webhook a workflow created with `createWebhook`, by\n * resuming the workflow that waits on it. Needs the world but not the queue\n * consumer, so a process that only records events (`dispatch: false`) serves\n * webhooks too.\n *\n * @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.\n * @returns The response the bundle's webhook handler gives.\n */\n async handleWebhook(request: Request): Promise<Response> {\n await this.connect();\n const file = join(this.dir, WORKFLOW_BUNDLE.webhook);\n if (!existsSync(file))\n throw new Error(`No webhook bundle at ${file}. ${NOT_BUILT}`);\n const handlers = await import(pathToFileURL(file).href);\n const handler = handlers[request.method];\n if (typeof handler !== \"function\")\n return new Response(null, { status: 405 });\n return handler(request);\n }\n\n /** Stop the world. The runtime cannot be started again afterwards. */\n async close(): Promise<void> {\n this.closed = true;\n await this.ready?.catch(() => {});\n await this.connected?.catch(() => {});\n await this.world.close?.();\n }\n\n private ensure(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.ready ??= this.initialize().catch((error) => {\n this.ready = undefined;\n throw error;\n });\n return this.ready;\n }\n\n /** Load the SDK and give it the world: all a webhook needs. */\n private connect(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.connected ??= this.loadSdk()\n .then((sdk) => {\n sdk.setWorld(this.world);\n return sdk;\n })\n .catch((error) => {\n this.connected = undefined;\n throw error;\n });\n return this.connected;\n }\n\n private async initialize(): Promise<WorkflowSdk> {\n if (typeof this.world.createRunId !== \"function\")\n throw new Error(\n \"This world cannot name a run after its key, so an event delivered twice would start two runs. \" +\n \"Use the world from @brickkit/redis-world or @brickkit/bullmq-world.\",\n );\n const sdk = await this.connect();\n const flow = join(this.dir, WORKFLOW_BUNDLE.flow);\n if (!existsSync(flow))\n throw new Error(`No workflow bundle at ${flow}. ${NOT_BUILT}`);\n const manifest = this.readManifest();\n const depsOf = this.checkListeners(manifest);\n const bundle = await this.loadBundle(flow);\n if (typeof bundle.POST !== \"function\")\n throw new Error(`${flow} does not export a POST handler`);\n const post = bundle.POST;\n // Steps run inside this handler, so `useDeps()` in a step finds the deps of\n // the app, or of the plugin whose listener runs the workflow. The queue is\n // named after the workflow: `__wkf_workflow_<workflowId>`.\n this.world.registerHandler?.(WORKFLOW_QUEUE.prefix, (request: Request) => {\n const queue = request.headers.get(WORKFLOW_QUEUE.header) ?? \"\";\n const deps =\n depsOf.get(queue.slice(WORKFLOW_QUEUE.prefix.length)) ?? this.deps;\n return runWithDeps(deps, () => post(request));\n });\n await this.world.start?.();\n return sdk;\n }\n\n private async loadSdk(): Promise<WorkflowSdk> {\n const from = createRequire(join(this.root, \"package.json\"));\n const load = async (specifier: string) => {\n let path: string;\n try {\n path = from.resolve(specifier);\n } catch {\n throw new Error(\n `The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`,\n );\n }\n return import(pathToFileURL(path).href);\n };\n const [api, runtime] = await Promise.all([\n load(\"workflow/api\"),\n load(\"workflow/runtime\"),\n ]);\n return { start: api.start, setWorld: runtime.setWorld };\n }\n\n /**\n * The bundle holds its own copy of every step and registers them all when it\n * loads, replacing the ones the app registered. A copy has its own module state:\n * a step would find no database connection, no config, none of what the app set\n * up. So the app's steps are put back, and the bundle's copies serve only the\n * steps the app never loaded.\n */\n private async loadBundle(\n flow: string,\n ): Promise<{ POST?: (request: Request) => Promise<Response> }> {\n const registry = () =>\n (globalThis as Record<symbol, unknown>)[STEP_REGISTRY] as\n | Map<string, unknown>\n | undefined;\n const app = new Map(registry());\n const bundle = await import(pathToFileURL(flow).href);\n const registered = registry();\n if (registered) for (const [id, step] of app) registered.set(id, step);\n return bundle;\n }\n\n private readManifest(): BundleManifest | undefined {\n const path = join(this.dir, WORKFLOW_BUNDLE.manifest);\n if (!existsSync(path)) return undefined;\n return JSON.parse(readFileSync(path, \"utf8\")) as BundleManifest;\n }\n\n /**\n * A listener's workflow must carry the id the transform gives it, and the bundle\n * must know that id: a function that was never transformed, or a bundle built\n * before the workflow existed, would fail on its first delivery with a less\n * helpful message.\n *\n * @returns The deps each workflow's steps run with, by workflow id.\n * @throws When one workflow is run by listeners with different deps (an app\n * and a plugin, or two plugin installs): its steps could see only one set.\n */\n private checkListeners(\n manifest: BundleManifest | undefined,\n ): Map<string, Record<string, unknown>> {\n const depsOf = new Map<string, Record<string, unknown>>();\n const known = new Set<string>();\n for (const file of Object.values(manifest?.workflows ?? {}))\n for (const entry of Object.values(file))\n if (entry.workflowId) known.add(entry.workflowId);\n for (const listener of this.listeners) {\n const id = (listener.workflow as { workflowId?: unknown } | undefined)\n ?.workflowId;\n if (typeof id !== \"string\")\n throw new Error(\n `The workflow of listener '${listener.name}' was not transformed. ` +\n \"Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.\",\n );\n if (manifest && !known.has(id))\n throw new Error(\n `The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`,\n );\n const deps = listenerDeps(listener) ?? this.deps;\n if ((depsOf.get(id) ?? deps) !== deps)\n throw new Error(\n `Workflow '${id}' is run by listeners with different deps (listener '${listener.name}'); give each app or plugin install its own workflow.`,\n );\n depsOf.set(id, deps);\n }\n return depsOf;\n }\n}\n","import { GLOBAL_SYMBOL } from \"../telemetry-names\";\nimport { Dispatcher, type OutboxCounts } from \"./dispatcher\";\nimport { newEventId } from \"./id\";\nimport { listenerDeps, validateListener } from \"./listener\";\nimport { outboxRows, OUTBOX_STATUSES, type OutboxTable } from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type {\n DispatchOptions,\n EventDelivery,\n EventListener,\n EventRecorder,\n EventsOptions,\n EventsWorld,\n ServiceEvents,\n} from \"./types\";\nimport { WorkflowRuntime } from \"./workflows\";\nimport { runWithDeps } from \"../deps\";\nimport { portOf, type ServicePort } from \"../service-port\";\nimport { DuplicateNameError, type Service } from \"../types\";\n\nexport function matchesEvent(pattern: string, name: string): boolean {\n if (pattern === \"*\") return true;\n if (pattern.endsWith(\"*\")) return name.startsWith(pattern.slice(0, -1));\n return pattern === name;\n}\n\n/** The service of each database that records events, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */\nexport const recordingServices = new WeakMap<object, ServicePort>();\n\n// Shared by name: the CLI that stops the hubs may hold another copy of this package.\nconst startedHubs = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(GLOBAL_SYMBOL.eventsStarted)\n] ??= new Set()) as Set<Pick<EventsHub, \"stop\">>;\n\n/**\n * Stop every events hub started in this process, by any copy of `@brickkit/core`,\n * and wait for their deliveries. A hub that fails to stop does not cut the wait\n * for the others: the first failure is thrown once every hub is done.\n */\nexport async function stopAllEvents(): Promise<void> {\n const results = await Promise.allSettled(\n [...startedHubs].map((hub) => hub.stop()),\n );\n const failed = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (failed) throw failed.reason;\n}\n\n/**\n * What an app's `events` option describes, as plain data. It goes in the app\n * definition, which is sent to the dev dashboard, so it holds no functions.\n */\nexport interface EventsDefinition {\n listeners: { name: string; on: string[]; kind: \"handler\" | \"workflow\" }[];\n dispatch: boolean;\n /** Names of the services whose writes record events. */\n recorders: string[];\n}\n\n/** What the dispatcher runs for a delivery. */\nexport interface Deliverable {\n readonly maxAttempts?: number;\n readonly errors?: EventListener[\"errors\"];\n readonly retry?: EventListener[\"retry\"];\n run(delivery: EventDelivery): void | Promise<void>;\n}\n\n/**\n * The events of one app: who listens, where events are recorded, and the\n * dispatchers that deliver them. `brick({ events })` makes one and puts it on\n * `app.events`.\n */\nexport class EventsHub {\n private readonly byName = new Map<string, EventListener>();\n private readonly dispatchers = new Map<OutboxTable, Dispatcher>();\n private readonly deliverables = new Map<string, Deliverable>();\n private readonly dispatchOptions: DispatchOptions | false;\n private readonly runtime: WorkflowRuntime | undefined;\n private readonly recorderNames: string[] = [];\n private started = false;\n private stopping: Promise<void> | undefined;\n\n /**\n * @param options - The `events` option.\n * @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its\n * listeners and workflow steps.\n */\n constructor(\n options: EventsOptions,\n private readonly deps: Record<string, unknown> = {},\n ) {\n for (const listener of options.listeners ?? []) {\n validateListener(listener);\n if (this.byName.has(listener.name))\n throw new DuplicateNameError(\n `Duplicate event listener '${listener.name}'`,\n );\n this.byName.set(listener.name, listener);\n }\n const workflowListeners = [...this.byName.values()].filter(\n (listener) => listener.workflow,\n );\n if (workflowListeners.length) {\n if (!options.world)\n throw new Error(\n `Event listener '${workflowListeners[0]!.name}' runs a workflow, so events needs a world: ` +\n \"brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.\",\n );\n this.runtime = new WorkflowRuntime(\n options.world,\n options.workflows,\n workflowListeners,\n deps,\n );\n }\n this.dispatchOptions =\n options.dispatch === false\n ? false\n : options.dispatch === true || options.dispatch === undefined\n ? {}\n : options.dispatch;\n }\n\n /**\n * Give each service whose database holds an outbox table a recorder, and a\n * dispatcher for that table. Call it before the first request: a service has no\n * recorder until then.\n *\n * @param services - The app's services.\n * @returns The hub, for chaining.\n */\n attach(services: readonly Service<any, any>[]): this {\n for (const service of services.map(portOf)) {\n const table = service.getOutbox();\n if (!table) continue;\n this.recorderNames.push(service.name);\n service.setRecorder(\n this.bind(table, (name, payload) => service.checkEvent(name, payload)),\n );\n const db = service.getDb();\n if (db && typeof db === \"object\") recordingServices.set(db, service);\n if (!this.dispatchers.has(table))\n this.dispatchers.set(\n table,\n new Dispatcher(\n db,\n table,\n (name) => this.deliverable(name),\n this.dispatchOptions || {},\n ),\n );\n }\n if (this.recorderNames.length === 0 && this.byName.size > 0) {\n console.warn(\n \"[Brick-TS] events are configured, but no service database has an outbox table. \" +\n \"Add outboxTable() to a database's tables so its writes can record events.\",\n );\n }\n return this;\n }\n\n matching(name: string): EventListener[] {\n const found: EventListener[] = [];\n for (const listener of this.byName.values())\n if (listener.on.some((pattern) => matchesEvent(pattern, name)))\n found.push(listener);\n return found;\n }\n\n describe(): EventsDefinition {\n return {\n listeners: [...this.byName.values()].map((listener) => ({\n name: listener.name,\n on: [...listener.on],\n kind: listener.workflow ? (\"workflow\" as const) : (\"handler\" as const),\n })),\n dispatch: this.dispatchOptions !== false,\n recorders: [...this.recorderNames],\n };\n }\n\n /**\n * Where the workflow bundle is read from, the project it is built from, and\n * the world the workflows run on. Only set when a listener runs a workflow.\n * The CLI builds the bundle there before events start, and shows the world's\n * runs in the dev dashboard.\n */\n get workflows():\n | { root: string; dir: string; world: EventsWorld }\n | undefined {\n return (\n this.runtime && {\n root: this.runtime.root,\n dir: this.runtime.dir,\n world: this.runtime.world,\n }\n );\n }\n\n /**\n * Resume the workflow that waits on a webhook. The server mounts this on the\n * route the Workflow SDK puts in webhook URLs.\n */\n webhook(request: Request): Promise<Response> {\n if (!this.runtime)\n throw new Error(\"No listener of this app runs a workflow\");\n return this.runtime.handleWebhook(request);\n }\n\n /**\n * Start delivering recorded events from this process, and start the world that\n * runs workflow listeners. Does nothing if this process only records events\n * (`dispatch: false`), already started, or a stop is still waiting.\n */\n start(): void {\n // A process being stopped exits when the stop is done, and would drop what\n // this start claims. A startup that finishes late, or a commit, lands here.\n if (this.dispatchOptions === false || this.started || this.stopping) return;\n this.started = true;\n startedHubs.add(this);\n this.runtime?.warmUp();\n for (const dispatcher of this.dispatchers.values()) dispatcher.start();\n }\n\n /**\n * Stop delivering, wait for the deliveries that are running, and close the\n * world. A world cannot be started again, so workflow listeners stop for good.\n * A stop that arrives while another runs waits for that one.\n */\n stop(): Promise<void> {\n return (this.stopping ??= this.shutDown().finally(() => {\n // Removed only when done, so a stop-all waits for a stop already running.\n this.stopping = undefined;\n startedHubs.delete(this);\n }));\n }\n\n private async shutDown(): Promise<void> {\n this.started = false;\n await Promise.all(\n [...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()),\n );\n await this.runtime?.close();\n }\n\n /**\n * Deliver everything that is due now and wait for it. For tests and for\n * workers that drive delivery themselves.\n *\n * @returns How many deliveries ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.drain();\n return total;\n }\n\n /** How many rows are in each state, across the app's outbox tables. */\n async counts(): Promise<OutboxCounts> {\n const total = Object.fromEntries(\n OUTBOX_STATUSES.map((status) => [status, 0]),\n ) as OutboxCounts;\n for (const dispatcher of this.dispatchers.values()) {\n const counts = await dispatcher.counts();\n for (const status of OUTBOX_STATUSES) total[status] += counts[status];\n }\n return total;\n }\n\n /**\n * Put parked deliveries back in line.\n *\n * @param deliveryId - One delivery. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.retryDead(deliveryId);\n return total;\n }\n\n private deliverable(name: string): Deliverable | undefined {\n const listener = this.byName.get(name);\n if (!listener) return undefined;\n let found = this.deliverables.get(name);\n if (!found) {\n const { run, workflow, maxAttempts, errors, retry } = listener;\n const deps = listenerDeps(listener) ?? this.deps;\n found = {\n ...(errors ? { errors } : {}),\n ...(retry ? { retry } : {}),\n ...(maxAttempts !== undefined ? { maxAttempts } : {}),\n run: workflow\n ? (delivery) => this.runtime!.startRun(listener, delivery)\n : (delivery) => runWithDeps(deps, () => run!(delivery)),\n };\n this.deliverables.set(name, found);\n }\n return found;\n }\n\n private bind(\n table: OutboxTable,\n check: (name: string, payload: unknown) => void,\n ): ServiceEvents {\n const startAndNotify = () => {\n this.start();\n this.dispatchers.get(table)?.notify();\n };\n const insert = async (\n tx: any,\n context: { traceId?: string; source?: string },\n name: string,\n payload: unknown,\n ): Promise<boolean> => {\n check(name, payload);\n const listeners = this.matching(name);\n if (!listeners.length) return false;\n await tx.insert(table as any).values(\n outboxRows(\n {\n id: newEventId(),\n name,\n payload,\n occurredAt: new Date(),\n ...context,\n },\n listeners.map((listener) => listener.name),\n ),\n );\n return true;\n };\n return {\n wants: (name) => this.matching(name).length > 0,\n transaction: async (db, context, fn) => {\n let recorded = false;\n const result = await runInTransaction(db, async (tx) => {\n const record: EventRecorder = async (name, payload) => {\n if (await insert(tx, context, name, payload)) recorded = true;\n };\n return fn(tx, record);\n });\n if (recorded) startAndNotify();\n return result;\n },\n record: async (tx, context, name, payload) => {\n await insert(tx, context, name, payload);\n },\n };\n }\n}\n","/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */\nexport function publicOrigin(request: Request): string {\n // Browsers cannot set X-Forwarded-* on a WebSocket handshake, so a cross-site page cannot forge a match.\n const forwarded = (name: string) =>\n request.headers.get(name)?.split(\",\")[0]?.trim() || undefined;\n const url = new URL(request.url);\n const proto = forwarded(\"x-forwarded-proto\");\n return `${proto ? `${proto}:` : url.protocol}//${forwarded(\"x-forwarded-host\") ?? url.host}`;\n}\n\n/**\n * Which origins may call the app: an exact origin (`\"https://app.example.com\"`),\n * a list of them, or a predicate. `true` allows only the app's own origin.\n */\nexport type CorsOrigin =\n | true\n | string\n | readonly string[]\n | ((origin: string, request: Request) => boolean);\n\n/** `brick({ cors })`: an origin rule, or the rule plus `credentials`. */\nexport type CorsOptions =\n | CorsOrigin\n | {\n /** Default `true`: the app's own origin only. */\n origin?: CorsOrigin;\n /** Send `Access-Control-Allow-Credentials: true` to allowed origins (cookies, auth headers). */\n credentials?: boolean;\n };\n\nconst METHODS = \"GET, POST, PUT, PATCH, DELETE\";\n\n/**\n * A request hook that adds CORS headers for allowed origins and answers\n * preflights. An origin that doesn't match gets no `Access-Control-Allow-Origin`,\n * so the browser blocks it; origins are compared exactly and never reflected\n * unless the rule allows them.\n */\nexport function corsHook(cors: CorsOptions) {\n const { origin = true, credentials = false } =\n typeof cors === \"object\" && !Array.isArray(cors)\n ? (cors as Exclude<CorsOptions, CorsOrigin>)\n : { origin: cors as CorsOrigin };\n const list =\n typeof origin === \"string\"\n ? [origin]\n : Array.isArray(origin)\n ? (origin as readonly string[])\n : undefined;\n if (list?.includes(\"*\"))\n throw new Error(\n 'Brick: cors origin \"*\" is not supported. List the origins, or pass a predicate.',\n );\n const allows = (from: string, request: Request) =>\n origin === true\n ? from === publicOrigin(request)\n : typeof origin === \"function\"\n ? origin(from, request) === true\n : list!.includes(from);\n\n return ({\n request,\n set,\n }: {\n request: Request;\n set: { headers: Record<string, unknown> };\n }) => {\n const from = request.headers.get(\"origin\");\n if (from === null) return;\n const headers: Record<string, string> = { vary: \"Origin\" };\n if (allows(from, request)) {\n headers[\"access-control-allow-origin\"] = from;\n if (credentials) headers[\"access-control-allow-credentials\"] = \"true\";\n }\n const preflight =\n request.method === \"OPTIONS\" &&\n request.headers.has(\"access-control-request-method\");\n if (!preflight) {\n Object.assign(set.headers, headers);\n return;\n }\n if (headers[\"access-control-allow-origin\"]) {\n headers[\"access-control-allow-methods\"] = METHODS;\n const requested = request.headers.get(\"access-control-request-headers\");\n if (requested) headers[\"access-control-allow-headers\"] = requested;\n }\n return new Response(null, { status: 204, headers });\n };\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { Elysia } from \"elysia\";\nimport { websocket } from \"elysia/websocket\";\nimport { createLogger } from \"./logger\";\nimport { kebabCase } from \"./kebab\";\nimport { joinRoute, ownerPath } from \"./routes\";\nimport { buildErrorHelpers } from \"./action\";\nimport {\n ActionExecutionError,\n type ActionErrorDefinition,\n type BaseContext,\n} from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { inTransaction, onTransactionCommit } from \"./events/transaction\";\nimport { serializeSocketSchema } from \"./socket-schema\";\nimport {\n byteLength,\n encodeFrame,\n isControlEvent,\n isSocketEnvelope,\n isSocketRoom,\n isSocketSeq,\n replayFrame,\n replayHeadroom,\n signSeq,\n splitSeq,\n SOCKET_BUFFER_BYTES,\n SOCKET_BUFFER_MESSAGES,\n STANDARD_ERRORS,\n SOCKET_CLOSE,\n SOCKET_CONTROL,\n SOCKET_MAX_BYTES,\n SOCKET_PROTOCOL,\n SOCKET_SIGNATURE_LENGTH,\n SOCKET_TOKEN_PROTOCOL,\n} from \"./protocol\";\nimport { publicOrigin } from \"./cors\";\nimport type {\n BrickSocketConfig,\n BrickSocketSender,\n SocketBroker,\n SocketBrokerMessage,\n SocketEmitArgs,\n SocketPayloads,\n SocketSchemas,\n RegisteredSocket,\n SocketSender,\n SocketSession,\n} from \"./socket-types\";\n\nexport type { RegisteredSocket };\n\nclass SocketDenied extends Error {}\n\n/** Validates and serializes one output message, rechecking what survives JSON. */\nfunction outputFrame(\n output: SocketSchemas,\n event: string,\n data: unknown,\n): string {\n const schema = Object.hasOwn(output, event) ? output[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new Error(\"Invalid socket output\");\n const frame = encodeFrame(event, data);\n if (byteLength(frame) > SOCKET_MAX_BYTES)\n throw new Error(\"Socket output too large\");\n if (!getCompiledCheck(schema).Check(JSON.parse(frame).data))\n throw new Error(\"Socket output is not JSON-compatible\");\n return frame;\n}\n\n/** Delivers within this process. The default broker of every app. */\nexport function localBroker(): SocketBroker {\n const topics = new Map<string, Set<(message: SocketBrokerMessage) => void>>();\n // Replay history: one rising counter per process, prefixed with its start so a restart reads as a gap.\n const epoch = Date.now();\n let counter = 0;\n /** Rooms dropped from `kept` once idle, at counter values up to this. */\n let swept = 0;\n const kept = new Map<\n string,\n {\n entries: { n: number; at: number; message: SocketBrokerMessage }[];\n /** The highest n no longer kept. */\n trimmed: number;\n maxAgeMs: number;\n }\n >();\n const prune = (names: Iterable<string>) => {\n for (const topic of names) {\n const room = kept.get(topic);\n if (!room) continue;\n const oldest = Date.now() - room.maxAgeMs;\n while (room.entries[0] && room.entries[0].at < oldest)\n room.trimmed = room.entries.shift()!.n;\n if (!room.entries.length) {\n kept.delete(topic);\n swept = counter;\n }\n }\n };\n return {\n publish(message, replay) {\n if (message.type === \"emit\" && replay) {\n const n = ++counter;\n message = { ...message, seq: `${epoch}-${n}` };\n const room = kept.get(message.topic) ?? {\n entries: [],\n trimmed: 0,\n maxAgeMs: replay.maxAgeMs,\n };\n kept.set(message.topic, room);\n room.entries.push({ n, at: Date.now(), message });\n if (room.entries.length > replay.keep)\n room.trimmed = room.entries.shift()!.n;\n // shortcut: idle rooms are swept every 1000 emits, not on a timer; fine while emits keep coming.\n if (n % 1000 === 0) prune([...kept.keys()]);\n }\n for (const deliver of topics.get(message.topic) ?? []) deliver(message);\n },\n head: () => `${epoch}-${counter}`,\n history(topic, since) {\n const [from, n] = since.split(\"-\").map(Number) as [number, number];\n if (from !== epoch || n > counter) return undefined;\n prune([topic]);\n const room = kept.get(topic);\n if (!room) return n >= swept ? [] : undefined;\n if (n < room.trimmed) return undefined;\n return room.entries\n .filter((entry) => entry.n > n)\n .map((entry) => entry.message);\n },\n subscribe(topic, deliver) {\n const listeners = topics.get(topic) ?? new Set();\n listeners.add(deliver);\n topics.set(topic, listeners);\n return () => {\n listeners.delete(deliver);\n if (!listeners.size) topics.delete(topic);\n };\n },\n };\n}\n\nexport function defineServiceSocket<\n I extends SocketSchemas,\n O extends SocketSchemas,\n Ctx extends BaseContext,\n E extends Record<string, ActionErrorDefinition> = {},\n>(\n service: string,\n config: BrickSocketConfig<I, O, Ctx, E>,\n resolve: (request: Request) => Promise<Ctx>,\n): RegisteredSocket {\n if (\n !config.name ||\n config.name.split(\".\").some((part) => !/^[a-zA-Z_][\\w-]*$/.test(part))\n )\n throw new Error(\"Invalid socket name\");\n if (\n config.path !== undefined &&\n (!config.path.startsWith(\"/\") ||\n /[?#*]/.test(config.path) ||\n config.path.split(\"/\").some((segment) => segment.startsWith(\":\")))\n )\n throw new Error(\n \"Socket path must be a static route (relative to its service) without a query or fragment\",\n );\n const input = Object.freeze({ ...config.input });\n const output = Object.freeze({ ...config.output });\n const handlers = { ...config.handlers };\n if (\n Object.keys(input).length !== Object.keys(handlers).length ||\n Object.keys(input).some(\n (key) =>\n !Object.hasOwn(handlers, key) || typeof handlers[key] !== \"function\",\n )\n )\n throw new Error(\"Every socket input event needs exactly one handler\");\n if ([...Object.keys(input), ...Object.keys(output)].some(isControlEvent))\n throw new Error(\"Socket event names starting with $ are reserved\");\n const maxRooms = config.maxRooms ?? 100;\n if (!Number.isInteger(maxRooms) || maxRooms < 1)\n throw new Error(\"Socket maxRooms must be a positive integer\");\n const replay = config.replay && { ...config.replay };\n if (\n replay &&\n !(\n Number.isInteger(replay.keep) &&\n replay.keep > 0 &&\n replay.maxAgeMs > 0 &&\n Number.isFinite(replay.maxAgeMs)\n )\n )\n throw new Error(\n \"Socket replay needs a positive integer keep and a positive finite maxAgeMs\",\n );\n for (const schema of [...Object.values(input), ...Object.values(output)]) {\n serializeSocketSchema(schema);\n getCompiledCheck(schema);\n }\n const typed = (socket: SocketSender): BrickSocketSender<SocketPayloads<O>> =>\n socket;\n const error = buildErrorHelpers(config.errors);\n const context = async (request: Request) => {\n const ctx = await resolve(request);\n if (config.authorize && !(await config.authorize({ ctx })))\n throw new SocketDenied();\n return ctx;\n };\n const topicPrefix = `${service}.${config.name}:`;\n const topic = (room: string) => {\n if (!isSocketRoom(room)) throw new Error(`Invalid socket room: ${room}`);\n return topicPrefix + room;\n };\n const brokers = new Set<SocketBroker>();\n const publish = (messages: SocketBrokerMessage[], after: unknown) => {\n const send = () => {\n for (const broker of brokers)\n for (const message of messages) broker.publish(message, replay);\n };\n if (after === undefined) return send();\n if (!inTransaction(after))\n throw new Error(\n \"Socket emit { after: tx } needs a tx from runInTransaction(db, (tx) => ...); a plain db.transaction() is not tracked, so the emit could be sent for a write that rolls back\",\n );\n void onTransactionCommit(after, send);\n };\n return {\n schema: {\n name: config.name,\n path: config.path,\n description: config.description,\n input: Object.keys(input),\n output: Object.keys(output),\n hasAuthorize: !!config.authorize,\n },\n input,\n output,\n ...(config.errors ? { errors: { ...config.errors } } : {}),\n allowedOrigins: config.allowedOrigins\n ? [...config.allowedOrigins]\n : undefined,\n allowMissingOrigin: config.allowMissingOrigin,\n maxRooms,\n replay,\n brokers,\n topicPrefix,\n topic,\n handle: {\n name: config.name,\n emit(rooms, ...[event, payload, options]: SocketEmitArgs<any>) {\n const unique = [\n ...new Set(typeof rooms === \"string\" ? [rooms] : rooms),\n ];\n const topics = unique.map(topic);\n const frame = outputFrame(output, event, payload);\n // Room and sequence are added to each replayed frame on delivery.\n if (\n replay &&\n unique.some(\n (room) =>\n byteLength(frame) + replayHeadroom(room) > SOCKET_MAX_BYTES,\n )\n )\n throw new Error(\"Socket output too large\");\n publish(\n topics.map((topic) => ({ type: \"emit\", topic, frame })),\n options?.after,\n );\n },\n kick(room, options = {}) {\n publish(\n [\n {\n type: \"kick\",\n topic: topic(room),\n ...(options.also !== undefined\n ? { also: topic(options.also) }\n : {}),\n ...(options.reason !== undefined\n ? { reason: String(options.reason) }\n : {}),\n },\n ],\n undefined,\n );\n },\n },\n async connect(request) {\n const initial = await context(request);\n const rooms = [\n ...new Set(config.rooms ? await config.rooms({ ctx: initial }) : []),\n ];\n rooms.forEach(topic);\n if (rooms.length > maxRooms) throw new Error(\"Too many socket rooms\");\n return {\n rooms,\n async open(socket) {\n await config.open?.({ ctx: initial, socket: typed(socket) });\n },\n async message(event, data, socket) {\n const schema = Object.hasOwn(input, event) ? input[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new SocketDenied();\n const ctx = await context(request);\n if (!socket.isOpen) return;\n // The schema and event were checked together before dispatch.\n const handler = handlers[event as keyof I];\n await handler({\n input: data as SocketPayloads<I>[keyof I],\n ctx,\n socket: typed(socket),\n error,\n });\n },\n async join(room) {\n const ctx = await context(request);\n return !!config.join && (await config.join({ ctx, room }));\n },\n async close(socket, code, reason) {\n await config.close?.({\n ctx: initial,\n socket: typed(socket),\n code,\n reason,\n });\n },\n };\n },\n };\n}\n\n/** `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */\nexport function socketPath(\n prefix: string,\n service: string,\n socket: RegisteredSocket,\n): string {\n return joinRoute(\n ownerPath(prefix, service),\n socket.schema.path ?? `/${kebabCase(socket.schema.name)}`,\n );\n}\n\nconst protocols = (request: Request) =>\n (request.headers.get(\"sec-websocket-protocol\") ?? \"\")\n .split(\",\")\n .map((protocol) => protocol.trim())\n .filter(Boolean);\n\n/** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */\nfunction tokenRequest(request: Request): {\n token: boolean;\n request: Request;\n} {\n const offered = protocols(request);\n const token = offered\n .find((protocol) => protocol.startsWith(SOCKET_TOKEN_PROTOCOL))\n ?.slice(SOCKET_TOKEN_PROTOCOL.length);\n if (!token) return { token: false, request };\n const headers = new Headers(request.headers);\n headers.set(\"authorization\", `Bearer ${token}`);\n const rest = offered.filter(\n (protocol) => !protocol.startsWith(SOCKET_TOKEN_PROTOCOL),\n );\n if (rest.length) headers.set(\"sec-websocket-protocol\", rest.join(\", \"));\n else headers.delete(\"sec-websocket-protocol\");\n return {\n token: true,\n request: new Request(request.url, { method: request.method, headers }),\n };\n}\n\n/** Each connection owns its queue and service session. */\nexport function mountSockets(\n app: Elysia,\n sockets: { service: string; path: string; definition: RegisteredSocket }[],\n broker: SocketBroker,\n secret?: string,\n): void {\n if (secret === \"\") throw new Error(\"Brick: sockets.secret can't be empty\");\n // A sequence is signed for its room, so a client resumes only a room it was sent that sequence in.\n const key = secret ?? randomBytes(32);\n const signature = (topic: string, seq: string) =>\n createHmac(\"sha256\", key)\n .update(`${topic}\\n${seq}`)\n .digest(\"base64url\")\n .slice(0, SOCKET_SIGNATURE_LENGTH);\n const sign = (topic: string, seq: string) =>\n signSeq(seq, signature(topic, seq));\n const verify = (topic: string, signed: string) => {\n const [seq, sig] = splitSeq(signed);\n return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq)))\n ? seq\n : undefined;\n };\n if (\n sockets.some(({ definition }) => definition.replay) &&\n !(broker.head && broker.history)\n )\n throw new Error(\"Brick: the socket broker does not support replay\");\n for (const { definition } of sockets) definition.brokers.add(broker);\n app.onStop(async () => {\n for (const { definition } of sockets) definition.brokers.delete(broker);\n await broker.close?.();\n });\n if (!sockets.length) return;\n app.use(\n websocket({\n maxPayloadLength: SOCKET_MAX_BYTES,\n backpressureLimit: SOCKET_BUFFER_BYTES,\n closeOnBackpressureLimit: true,\n }),\n );\n for (const { service, path, definition } of sockets) {\n const logger = createLogger(\n `[Brick socket ${service}.${definition.schema.name}]`,\n );\n const sessions = new WeakMap<Request, SocketSession>();\n type Peer = {\n request: Request;\n send(data: string): number;\n close(code?: number, reason?: string): void;\n subscribe(topic: string): void;\n unsubscribe(topic: string): void;\n isSubscribed(topic: string): boolean;\n readonly readyState: number;\n };\n type Connection = {\n ws: Peer;\n session: SocketSession;\n sender: SocketSender;\n tail: Promise<void>;\n pending: number;\n bytes: number;\n closed: boolean;\n /** Every room topic the connection is in. */\n rooms: Set<string>;\n /** The topics the client joined, which it may leave. */\n requested: Set<string>;\n };\n const connections = new WeakMap<Request, Connection>();\n const roomOf = (topic: string) =>\n topic.slice(definition.topicPrefix.length);\n const holders = new Map<\n string,\n { connections: Set<Connection>; unsubscribe: () => void }\n >();\n const control = (ws: Peer, event: string, data: unknown) => {\n if (ws.readyState === 1) ws.send(encodeFrame(event, data));\n };\n /** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */\n const enter = async (\n connection: Connection,\n topic: string,\n live = true,\n ) => {\n if (connection.rooms.has(topic)) return;\n connection.rooms.add(topic);\n if (live) connection.ws.subscribe(topic);\n let holder = holders.get(topic);\n if (!holder) {\n holder = {\n connections: new Set(),\n unsubscribe: () => {},\n };\n holders.set(topic, holder);\n holder.unsubscribe = broker.subscribe(topic, deliver);\n }\n holder.connections.add(connection);\n await broker.ready?.(topic).catch(() => {});\n };\n const exit = (connection: Connection, topic: string) => {\n if (!connection.rooms.delete(topic)) return;\n connection.requested.delete(topic);\n if (connection.ws.readyState === 1) connection.ws.unsubscribe(topic);\n const holder = holders.get(topic);\n if (!holder?.connections.delete(connection) || holder.connections.size)\n return;\n holders.delete(topic);\n holder.unsubscribe();\n };\n const frameOf = (message: SocketBrokerMessage & { type: \"emit\" }) =>\n message.seq === undefined\n ? message.frame\n : replayFrame(\n message.frame,\n roomOf(message.topic),\n sign(message.topic, message.seq),\n );\n const deliver = (message: SocketBrokerMessage) => {\n if (message.type === \"emit\") {\n app.server?.publish(message.topic, frameOf(message));\n return;\n }\n for (const connection of holders.get(message.topic)?.connections ?? []) {\n if (message.also && !connection.ws.isSubscribed(message.also)) continue;\n exit(connection, message.topic);\n control(connection.ws, SOCKET_CONTROL.left, {\n room: roomOf(message.topic),\n ...(message.reason !== undefined ? { reason: message.reason } : {}),\n });\n }\n };\n /** `$join` and `$leave`, acknowledged with the same event. */\n const room = async (\n connection: Connection,\n event: string,\n data: unknown,\n ) => {\n const fields = (data && typeof data === \"object\" ? data : {}) as Record<\n string,\n unknown\n >;\n const { room: name, since } = fields;\n if (!isSocketRoom(name) || (since !== undefined && !isSocketSeq(since)))\n throw new SocketDenied();\n const topic = definition.topic(name);\n if (event === SOCKET_CONTROL.leave) {\n if (connection.requested.has(topic)) exit(connection, topic);\n control(connection.ws, SOCKET_CONTROL.leave, { room: name });\n return;\n }\n const isOpen = () => !connection.closed && connection.ws.readyState === 1;\n const ok =\n connection.rooms.has(topic) ||\n (connection.rooms.size < definition.maxRooms &&\n (await connection.session.join(name)));\n if (!isOpen()) return;\n const replay = definition.replay;\n let seq: string | undefined;\n if (ok && !connection.rooms.has(topic)) {\n const entered = enter(connection, topic, !replay);\n connection.requested.add(topic);\n await entered;\n if (replay && connection.rooms.has(topic)) {\n // Held in this process before reading history, so later emits are either in it or arrive live.\n // A since not signed for this room gets no history, only $gap.\n const start =\n since === undefined\n ? await broker.head!(topic)\n : verify(topic, since);\n const missed =\n start === undefined\n ? undefined\n : await broker.history!(topic, start, replay);\n const restart = missed ? undefined : await broker.head!(topic);\n if (!isOpen()) return;\n if (connection.rooms.has(topic)) {\n connection.ws.subscribe(topic);\n if (since === undefined) seq = sign(topic, start!);\n for (const message of missed ?? [])\n if (message.type === \"emit\") connection.ws.send(frameOf(message));\n if (restart !== undefined)\n control(connection.ws, SOCKET_CONTROL.gap, {\n room: name,\n seq: sign(topic, restart),\n });\n }\n }\n }\n // A kick while joining wins.\n control(connection.ws, SOCKET_CONTROL.join, {\n room: name,\n ok: ok && connection.rooms.has(topic),\n ...(seq !== undefined ? { seq } : {}),\n });\n };\n // The codes a handler can raise with `error.CODE()`: declared plus standard.\n const raisable = { ...STANDARD_ERRORS, ...definition.errors };\n const fail = (ws: Peer, error: unknown) => {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n if (ws.readyState !== 1) return;\n ws.close(\n error instanceof SocketDenied\n ? SOCKET_CLOSE.policy\n : SOCKET_CLOSE.serverError,\n error instanceof SocketDenied\n ? \"Message refused\"\n : \"Socket handler failed\",\n );\n };\n app.ws(path, {\n async beforeHandle({ request }) {\n if (sessions.has(request)) return;\n const { token, request: resolved } = tokenRequest(request);\n const origin = request.headers.get(\"origin\");\n if (\n origin\n ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(\n origin,\n )\n : // Without cookies a missing Origin is no hijacking risk.\n !(definition.allowMissingOrigin ?? token)\n )\n return new Response(\"Socket origin refused\", { status: 403 });\n try {\n sessions.set(request, await definition.connect(resolved));\n } catch (error) {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n return new Response(\"Socket connection refused\", {\n status: error instanceof SocketDenied ? 403 : 500,\n });\n }\n },\n upgrade: ({ request }: { request: Request }) =>\n protocols(request).includes(SOCKET_PROTOCOL)\n ? { \"Sec-WebSocket-Protocol\": SOCKET_PROTOCOL }\n : undefined,\n async open(ws) {\n const session = sessions.get(ws.request);\n if (!session) {\n ws.close(SOCKET_CLOSE.serverError, \"Missing socket session\");\n return;\n }\n const sender: SocketSender = {\n get isOpen() {\n return !state.closed && ws.readyState === 1;\n },\n close() {\n ws.close(SOCKET_CLOSE.normal, \"\");\n },\n send(event, data) {\n if (!sender.isOpen) throw new Error(\"Socket is closed\");\n const result = ws.send(outputFrame(definition.output, event, data));\n if (result === 0) {\n ws.close(SOCKET_CLOSE.tryAgainLater, \"Socket buffer full\");\n throw new Error(\"Socket buffer full\");\n }\n },\n };\n const state: Connection = {\n ws,\n session,\n sender,\n tail: Promise.resolve(),\n pending: 0,\n bytes: 0,\n closed: false,\n rooms: new Set(),\n requested: new Set(),\n };\n connections.set(ws.request, state);\n try {\n await Promise.all(\n session.rooms.map((room) => enter(state, definition.topic(room))),\n );\n await session.open(sender);\n } catch (error) {\n fail(ws, error);\n }\n },\n message(ws, value: unknown) {\n const state = connections.get(ws.request);\n if (!state || state.closed || ws.readyState !== 1) return;\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n ws.close(SOCKET_CLOSE.unsupportedData, \"Only JSON text is supported\");\n return;\n }\n if (typeof value === \"string\") {\n ws.close(SOCKET_CLOSE.invalidPayload, \"Expected JSON envelope\");\n return;\n }\n if (!isSocketEnvelope(value)) {\n ws.close(SOCKET_CLOSE.policy, \"Invalid socket envelope\");\n return;\n }\n const size = byteLength(JSON.stringify(value));\n if (size > SOCKET_MAX_BYTES) {\n ws.close(SOCKET_CLOSE.tooLarge, \"Message too large\");\n return;\n }\n if (\n state.pending >= SOCKET_BUFFER_MESSAGES ||\n state.bytes + size > SOCKET_BUFFER_BYTES\n ) {\n ws.close(SOCKET_CLOSE.tryAgainLater, \"Socket queue full\");\n return;\n }\n state.pending++;\n state.bytes += size;\n state.tail = state.tail\n .then(async () => {\n if (state.closed || ws.readyState !== 1) return;\n if (\n value.event === SOCKET_CONTROL.join ||\n value.event === SOCKET_CONTROL.leave\n )\n await room(state, value.event, value.data);\n else\n await state.session.message(\n value.event,\n value.data,\n state.sender,\n );\n })\n .catch((error: unknown) => {\n // A declared error answers a handler message; the connection stays\n // open. A failed $join or $leave, or an error with an undeclared\n // code (from a nested action, say), is logged and closes it, which\n // also rejects the client's pending joins.\n if (\n error instanceof ActionExecutionError &&\n !state.closed &&\n value.event !== SOCKET_CONTROL.join &&\n value.event !== SOCKET_CONTROL.leave &&\n Object.hasOwn(raisable, error.code)\n )\n try {\n const frame = encodeFrame(SOCKET_CONTROL.error, {\n event: value.event,\n ...error.toJSON(),\n });\n if (byteLength(frame) > SOCKET_MAX_BYTES)\n throw new Error(\"Socket error too large\", { cause: error });\n if (ws.readyState === 1) ws.send(frame);\n return;\n } catch (unsent) {\n return fail(ws, unsent);\n }\n fail(ws, error);\n })\n .finally(() => {\n state.pending--;\n state.bytes -= size;\n });\n // Brick owns the queue. Returning the tail here makes native close wait on application work.\n },\n async close(ws, code = 1006, reason = \"\") {\n const state = connections.get(ws.request);\n sessions.delete(ws.request);\n if (!state || state.closed) return;\n state.closed = true;\n for (const topic of state.rooms) exit(state, topic);\n try {\n await state.session.close(state.sender, code, reason);\n } catch (error) {\n logger.error({\n error,\n service,\n socket: definition.schema.name,\n phase: \"cleanup\",\n });\n }\n connections.delete(ws.request);\n },\n });\n }\n}\n","import { ATTR, SPAN } from \"./telemetry-names\";\nimport type { HttpMethod } from \"./http\";\nimport { Elysia } from \"elysia\";\nimport {\n compileBrickApplication,\n type CompiledApplication,\n type RouteIR,\n} from \"./compiler\";\nimport { DuplicateNameError, type Service } from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getPluginEndpoints, installedPlugins } from \"./plugin\";\nimport { pluginLifecycle, setupAppPlugins } from \"./plugin-app\";\nimport type { PluginInstance } from \"./define-plugin\";\nimport { OPENAPI_DEFAULTS, generateOpenApiSpec } from \"./openapi\";\nimport { resolveSecrets, type SecretSource } from \"./secrets\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n type ApiDocument,\n type DocumentationOptions,\n type OpenApiDocument,\n type ReferenceOptions,\n} from \"./docs\";\nimport { normalizeDashboard, type DashboardOptions } from \"./dashboard\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\nimport { instrumentDatabase, traceHttpRequest, withSpan } from \"./telemetry\";\nimport { EventsHub } from \"./events/hub\";\nimport { bindDeps } from \"./deps\";\nimport { WEBHOOK_ROUTE } from \"./events/workflows\";\nimport type { EventsOptions } from \"./events/types\";\nimport { localBroker, mountSockets, socketPath } from \"./socket\";\nimport { DEFAULT_PREFIX, routeKey } from \"./routes\";\nimport type { SocketBroker } from \"./socket-types\";\nimport { corsHook, type CorsOptions } from \"./cors\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Run the plugins' preparations (such as CRUD's prepared queries) at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n /**\n * `true` serves a Scalar page at /reference. Options serve one only with a\n * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.\n */\n reference?: boolean | ReferenceOptions; // default false\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (plain routes, not actions), mounted at startup. */\n endpoints?: EndpointDefinition[];\n /**\n * Record request, action, and RPC spans with OpenTelemetry (default false).\n * Spans go to the globally registered tracer provider; without one they are\n * no-ops. `brick dev` shows them in its dashboard.\n */\n telemetry?: boolean;\n /**\n * Developer documentation for the `brick dev` dashboard (its Docs tab): a\n * folder of `.md`/`.mdx` pages in Fumadocs' layout, with frontmatter and\n * `meta.json` for ordering. A string is the folder. Relative paths start at\n * the folder of the app entry, as they read in the file that sets them (from\n * `src/app.ts`, `\"../docs\"` is `docs/` at the project root). Needs\n * `fumadocs-core` and `@mdx-js/mdx` installed.\n */\n documentation?: string | DocumentationOptions;\n /**\n * Monitoring dashboard for `brick start`, on a port of its own and behind\n * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.\n */\n dashboard?: DashboardOptions;\n /**\n * Record events in the same database transaction as the writes that cause them,\n * and deliver them to listeners after the commit. Generated CRUD writes emit\n * `<resource>.create`, `<resource>.update` and `<resource>.delete`. A service\n * records events once its database holds an `outboxTable()`. Reads emit nothing,\n * and an app without this option behaves exactly as before. See `EventsOptions`.\n */\n events?: EventsOptions;\n /**\n * Socket fan-out. `broker` carries emits and kicks between processes\n * (default: this process only). See `redisBroker`. The app closes it on stop.\n * `secret` signs replay sequences; give every process the same one so a\n * client can resume on any of them (default: random per process).\n */\n sockets?: { broker?: SocketBroker; secret?: string };\n /**\n * The values of the services' declared `deps` (`port<T>()`), by name. Every\n * declared dep must be provided, and every provided one declared. Actions read\n * them as `ctx.deps`, listeners and workflow steps with `useDeps()`.\n */\n deps?: Record<string, unknown>;\n /**\n * App-wide plugins from `definePlugin`, in install order: their `app` part\n * adds start/stop lifecycle, middleware and listeners. Plugins installed with\n * `service.use()` or `resource.use()` take part too, before these.\n */\n plugins?: readonly PluginInstance<any, any>[];\n /**\n * CORS for browser callers on other origins. `true` allows the app's own\n * origin; a string, list or predicate names the allowed origins, compared\n * exactly. `{ origin, credentials }` adds `credentials: true` for cookies.\n * Other origins get no `Access-Control-Allow-Origin`. Preflights are answered.\n */\n cors?: false | CorsOptions;\n}\n\n/**\n * Create the HTTP application: an Elysia app that serves every service's\n * actions (and the tools that opt in with `http: true`) as routes, with\n * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,\n * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.\n *\n * Services come from the global registry unless `services` is given. The app\n * does not listen by itself: export it from your entry file, where `brick dev`,\n * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your\n * own server bootstrap.\n *\n * @param options - `prefix` for action routes (default `/api`), `services`,\n * `title`, `version`, and `description` for the OpenAPI document, `docs` and the\n * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,\n * `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.\n * @returns The app, with `definition` (its services, prefix, and routes),\n * `endpoint()` to add raw routes, and `listEndpoints()` to list them.\n * @throws When a required secret is missing, `documentation` or `dashboard`\n * is invalid, or `deps` misses a dep a service declares or has one none declares.\n * @example\n * import { brick } from \"@brickkit/core\";\n * import { pagesService } from \"./services/pages\";\n *\n * export default brick({\n * services: [pagesService],\n * title: \"Pages API\",\n * telemetry: true,\n * });\n */\nexport function brick(options: CreateServerOptions = {}): BrickApp {\n const prefix =\n options.prefix ?? options.compilation?.ir.prefix ?? DEFAULT_PREFIX;\n const title = options.title ?? OPENAPI_DEFAULTS.title;\n const version = options.version ?? OPENAPI_DEFAULTS.version;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? OPENAPI_DEFAULTS.path;\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n const dashboard = normalizeDashboard(options.dashboard);\n // The dashboard shows what is traced, so having one means tracing.\n const telemetry = options.telemetry === true || dashboard !== undefined;\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n const plugins = setupAppPlugins(\n services.flatMap((service) => installedPlugins(service)),\n options.plugins ?? [],\n );\n // CORS first, so preflights are answered and its headers reach responses\n // from middleware, which skips the later lifecycle hooks.\n if (options.cors) app.onRequest(corsHook(options.cors));\n for (const handler of plugins.middleware) app.onRequest(handler);\n\n // Mounted and registered in one call, so actions and sockets can't shadow them.\n const registeredRoutes = new Map<string, boolean>();\n const builtIn = (path: string, handler: any) => {\n app.get(path, handler);\n registeredRoutes.set(routeKey(\"GET\", path), false);\n };\n\n builtIn(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false)\n app.use(\n requestLoggingPlugin(requestLogging === true ? {} : requestLogging),\n );\n\n // Scalar API reference page (opt-in): `reference: true`, or options with a path.\n const reference = options.reference ?? false;\n const referenceOptions: ReferenceOptions =\n typeof reference === \"object\" ? reference : {};\n const referencePath =\n reference === true ? \"/reference\" : referenceOptions.path;\n if (referencePath !== undefined) {\n builtIn(\n referencePath,\n htmlResponse(\n scalarDocsHTML(\n referenceOptions.specUrl ?? openApiPath,\n referenceOptions.title ?? title,\n ),\n ),\n );\n }\n\n const byName = new Map<string, unknown>();\n for (const service of services) {\n if ((byName.get(service.name) ?? service) !== service)\n throw new DuplicateNameError(\n `Brick: duplicate service \"${service.name}\" in brick()`,\n );\n byName.set(service.name, service);\n }\n bindDeps(services, options.deps);\n const eventsOptions = plugins.listeners.length\n ? {\n ...options.events,\n listeners: [...(options.events?.listeners ?? []), ...plugins.listeners],\n }\n : options.events;\n const events = eventsOptions\n ? new EventsHub(eventsOptions, options.deps).attach(services)\n : undefined;\n if (events?.workflows)\n app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));\n if (telemetry) {\n for (const service of services) instrumentDatabase(service.getDb());\n }\n\n // Close declarations before anything reads them.\n for (const service of services) service.build();\n\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n const paths = { ...spec.paths };\n for (const [path, operations] of Object.entries(\n endpointPaths(endpointDefs),\n ))\n paths[path] = { ...paths[path], ...operations };\n return { ...spec, paths };\n };\n\n if (enableDocs) {\n builtIn(\n openApiPath,\n cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n ),\n );\n builtIn(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n builtIn(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n }\n // Built from `definition`, below.\n builtIn(\"/_brick/services\", (context: any) => architecture(context));\n\n const sockets = services.flatMap((service) =>\n service.listSockets().map((definition) => ({\n service: service.name,\n path: socketPath(prefix, service.name, definition),\n definition,\n })),\n );\n const socketRoutes = new Set<string>();\n for (const socket of sockets) {\n const key = routeKey(\"GET\", socket.path);\n if (registeredRoutes.has(key) || socketRoutes.has(key))\n throw new DuplicateNameError(\n `Brick: duplicate socket route '${socket.path}'`,\n );\n socketRoutes.add(key);\n }\n const mountRoute = (\n method: HttpMethod,\n path: string,\n handler: any,\n plugin = false,\n ) => {\n const key = routeKey(method, path);\n if (socketRoutes.has(key))\n throw new DuplicateNameError(\n `Brick: route '${method} ${path}' conflicts with a socket`,\n );\n if (registeredRoutes.has(key)) {\n if (plugin || registeredRoutes.get(key))\n throw new DuplicateNameError(\n `Brick: duplicate plugin route '${method} ${path}'`,\n );\n return false;\n }\n app.route(method, path, handler);\n registeredRoutes.set(key, plugin);\n return true;\n };\n\n const mountEndpoint = (def: EndpointDefinition, plugin = false) => {\n const handler = createEndpointHandler(def, services);\n mountRoute(\n def.method,\n def.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, def.method, def.path, () =>\n handler(context),\n )\n : handler,\n plugin,\n );\n endpointDefs.push(def);\n endpointRevision++;\n };\n\n for (const service of services) {\n for (const def of getPluginEndpoints(service, prefix))\n mountEndpoint(def, true);\n }\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n brickApp.openApiDocument = buildSpec;\n brickApp.referenceDocuments = async () => {\n const documents: ApiDocument[] = enableDocs\n ? [{ title, document: buildSpec() as unknown as OpenApiDocument }]\n : [];\n for (const extra of referenceOptions.documents ?? []) {\n try {\n const document =\n typeof extra.document === \"function\"\n ? await extra.document()\n : extra.document;\n documents.push({ title: extra.title, document });\n } catch (error) {\n console.warn(\n `[Brick-TS] Skipping the \"${extra.title}\" API document: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return documents;\n };\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n const mountedRoutes: RouteIR[] = [];\n for (const route of compilation.routes) {\n const invoke = (context: any) => {\n const result = telemetry\n ? withSpan(\n `${SPAN.actionPrefix}${route.ir.service}.${route.ir.action}`,\n {\n [ATTR.service]: route.ir.service,\n [ATTR.action]: route.ir.action,\n },\n () => route.handler(context),\n )\n : route.handler(context);\n return result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ? Promise.resolve(result).then(jsonActionResult)\n : jsonActionResult(result);\n };\n const mounted = mountRoute(\n route.ir.method,\n route.ir.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, route.ir.method, route.ir.path, () =>\n invoke(context),\n )\n : invoke,\n Boolean(route.ir.plugin),\n );\n if (mounted) mountedRoutes.push(route.ir);\n }\n\n mountSockets(\n app,\n sockets,\n options.sockets?.broker ?? localBroker(),\n options.sockets?.secret,\n );\n const definition = Object.freeze({\n services: Object.freeze([...services]),\n prefix,\n routes: Object.freeze(mountedRoutes),\n sockets: Object.freeze(\n sockets.map(({ service, path, definition }) => ({\n ...definition.schema,\n service,\n path,\n })),\n ),\n telemetry,\n documentation: normalizeDocumentation(options.documentation),\n dashboard,\n ...(events ? { events: events.describe() } : {}),\n plugins: Object.freeze(plugins.plugins),\n });\n Object.defineProperty(brickApp, \"definition\", { value: definition });\n Object.defineProperty(brickApp, \"events\", { value: events });\n // Plugin lifecycle: start before serving, stop after the server stops.\n const lifecycle = pluginLifecycle(plugins.lifecycles);\n const listen = app.listen.bind(app);\n const stop = app.stop.bind(app);\n Object.defineProperty(brickApp, \"start\", { value: lifecycle.start });\n // One rule with serve(): an app whose plugins fail to start does not serve.\n // listen() is synchronous, so it stops the server it already opened.\n brickApp.listen = ((...args: Parameters<typeof listen>) => {\n lifecycle.start().catch((error) => {\n console.error(\"[Brick-TS] A plugin failed to start:\", error);\n return stop(true);\n });\n return listen(...args);\n }) as typeof brickApp.listen;\n brickApp.stop = (async (closeActiveConnections?: boolean) => {\n try {\n await stop(closeActiveConnections);\n } finally {\n await lifecycle.stop();\n }\n }) as typeof brickApp.stop;\n Object.defineProperty(brickApp, \"serve\", {\n value: async ({ port }: { port: number }) => {\n await lifecycle.start();\n listen(port);\n events?.start();\n return brickApp;\n },\n });\n Object.defineProperty(brickApp, \"shutdown\", {\n value: async (closeActiveConnections?: boolean) => {\n await events?.stop();\n await brickApp.stop(closeActiveConnections);\n },\n });\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n const architecture = cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(definition),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n );\n\n return brickApp;\n}\n\nfunction normalizeDocumentation(\n documentation: string | DocumentationOptions | undefined,\n): DocumentationOptions | undefined {\n if (documentation === undefined) return undefined;\n const options =\n typeof documentation === \"string\" ? { dir: documentation } : documentation;\n if (typeof options.dir !== \"string\" || options.dir === \"\")\n throw new Error(\"Brick: documentation needs a folder, such as './docs'.\");\n return Object.freeze({\n dir: options.dir,\n ...(options.components ? { components: options.components } : {}),\n });\n}\n\nfunction jsonActionResult(value: unknown): unknown {\n return value === null\n ? new Response(\"null\", { headers: { \"content-type\": \"application/json\" } })\n : value;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,MAAa,sBAAsB;CAAC;CAAO;CAAW;AAAU;;AA8GhE,MAAa,cAA6B,OAAO,IAAI,sBAAsB;;;;;AAK3E,MAAa,gBAA+B,OAAO,IACjD,wBACF;;AC3HA,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,wBAAwB,OAAO,IAAI,6BAA6B;AACtE,MAAM,2BAA2B;CAAC;CAAO;CAAO;CAAO;AAAQ;;AAO/D,SAAgB,SACd,MACA,YACA,IACA,OAAiB,SAAS,UACvB;CACH,OAAO,MACJ,UAAU,qBAAqB,CAAC,CAChC,gBAAgB,MAAM;EAAE;EAAM;CAAW,IAAI,SAC5C,OAAO,KAAK,YAAY;EACtB,IAAI,QAAQ,QAAQ,aAAa,MAAM,QAAQ,KAAK;EACpD,KAAK,IAAI;CACX,CAAC,CACH;AACJ;;;;;AAMA,SAAgB,aACd,MACA,YACA,IACG;CACH,OAAO,MAAM,cAAc,IAAI,SAAS,MAAM,YAAY,EAAE,IAAI,GAAG;AACrE;;;;;;;;;;;AA2BA,SAAgB,WACd,OACA,SACiC;CACjC,QAAQ,EAAE,SAAS,SAAS,KAAK,QAAQ,YACvC,iBAAiB;EAAE;EAAS;EAAS;CAAI,GAAG,QAAQ,QAAQ,aAC1D,QAAQ;EAAE;EAAS;EAAS;EAAK;EAAQ;CAAM,CAAC,CAClD;AACJ;;;;;;;AAQA,SAAgB,iBACd,SACA,QACA,OACA,IACG;CACH,MAAM,aAAyB;GAC5B,KAAK,aAAa;GAClB,KAAK,YAAY;CACpB;CACA,IAAI,QAAQ,SACV,WAAW,KAAK,WAAW,IAAI,IAAI,QAAQ,QAAQ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