@brickkit/core 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","names":["DEFAULT_REQUEST","sqliteText","sqliteInteger","sqliteReal","pgText","pgInteger","pgBoolean","pgTimestamp","EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty","sqliteInteger","sqliteText","sqliteIndex","pgText","pgInteger","pgIndex"],"sources":["../../src/routes.ts","../../src/compiler/ir.ts","../../src/registry.ts","../../src/telemetry.ts","../../src/error-response.ts","../../src/typebox.ts","../../src/logger.ts","../../src/action.ts","../../src/plugin.ts","../../src/deps.ts","../../src/define-plugin.ts","../../src/compiler/runtime.ts","../../src/action-handler.ts","../../src/compiler/handler.ts","../../src/app-entry.ts","../../src/compiler.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/outbox.ts","../../src/events/transaction.ts","../../src/events/dispatcher.ts","../../src/events/id.ts","../../src/events/workflows.ts","../../src/events/hub.ts","../../src/socket.ts","../../src/cors.ts","../../src/server.ts"],"sourcesContent":["import type { Action, ResourceActionAccess } from \"./types\";\nimport { getPluginActionRoute } from \"./plugin\";\nimport { kebabCase } from \"./kebab\";\n\nexport { kebabCase };\n\n/**\n * The route every name of an owner mounts under: `${prefix}`,\n * `${prefix}/${service}`, or `${prefix}/${service}/${resource}`, in kebab-case.\n */\nexport function ownerPath(\n prefix: string,\n service?: string,\n resource?: string,\n): string {\n let path = prefix.replace(/\\/$/, \"\");\n if (service !== undefined) path += `/${kebabCase(service)}`;\n if (resource !== undefined) path += `/${kebabCase(resource)}`;\n return path;\n}\n\n/** Joins a path relative to its owner. `/` is the owner's own route. */\nexport function joinRoute(base: string, path: string): string {\n return `${base}${path === \"/\" ? \"\" : path}` || \"/\";\n}\n\nexport interface ActionRoute {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n}\n\n/**\n * Where an action is served over HTTP: its method and its path under the owner\n * tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource\n * action's `${prefix}/${service}/${resource}[/:id]/${action}`).\n *\n * @param action - An action registered on a service.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns `false` when a plugin switched the route off, otherwise the route.\n */\nexport function getActionRoute(\n action: Action<any, any, any, any>,\n prefix = \"/api\",\n): ActionRoute | false {\n const plugin = getPluginActionRoute(action, prefix);\n if (plugin === false) return false;\n if (plugin) return { method: plugin.method, path: plugin.path };\n const service = action.serviceName ?? \"\";\n const method = action.config.method ?? \"POST\";\n const { resourceAction } = action as { resourceAction?: ResourceActionInfo };\n if (resourceAction) {\n const base = ownerPath(prefix, service, resourceAction.resource);\n return {\n method,\n path:\n action.config.path !== undefined\n ? joinRoute(base, action.config.path)\n : `${base}${resourceAction.record ? \"/:id\" : \"\"}/${kebabCase(resourceAction.name)}`,\n };\n }\n const base = ownerPath(prefix, service);\n return {\n method,\n path:\n action.config.path !== undefined\n ? joinRoute(base, action.config.path)\n : `${base}/${kebabCase(action.name)}`,\n };\n}\n\n/** Stamped on actions declared with `resource.action(...)`. */\nexport interface ResourceActionInfo {\n resource: string;\n /** The declared name, without the `resource.` prefix. */\n name: string;\n record: boolean;\n /** A record action's own access rule. */\n access?: ResourceActionAccess;\n}\n","import { type Service, type Action } from \"../types\";\nimport { getPluginActionRoute } from \"../plugin\";\nimport { getActionRoute, kebabCase } from \"../routes\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"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 = \"/api\",\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 = \"/api\",\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 Error(`Brick compiler: duplicate service '${service.name}'`);\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 kind: RouteIR[\"kind\"],\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const plugin = getPluginActionRoute(action, prefix) !== undefined;\n const key = `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n const previous = registered.get(key);\n if (previous) {\n if (plugin || previous.plugin)\n throw new Error(\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, { name: `${service.name}.${action.name}`, plugin });\n const readLike =\n method === \"GET\" ||\n action.name.startsWith(\"get\") ||\n action.name.endsWith(\".get\") ||\n action.name.startsWith(\"list\") ||\n action.name.endsWith(\".list\") ||\n action.name.startsWith(\"find\") ||\n action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" | \"array\" }[] =\n [];\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\")\n coercions.push({ key, type: \"boolean\" });\n else if (prop.type === \"array\") coercions.push({ key, type: \"array\" });\n }\n routes.push({\n method,\n path,\n service: service.name,\n action: action.name,\n kind,\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 inputPrecedence: readLike\n ? [\"query\", \"params\", \"body\"]\n : [\"params\", \"body\", \"query\"],\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n });\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, \"action\");\n }\n }\n const preparations = services.flatMap((service) =>\n service.listPreparations().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/** A service action, resource, and socket own the URL segment after the service. */\nfunction checkSegments(service: Service<any, any>) {\n const owners = new Map<string, string>();\n const claim = (segment: string, owner: string) => {\n const previous = owners.get(segment);\n if (previous)\n throw new Error(\n `Brick: duplicate name \"${segment}\" in service \"${service.name}\": ${previous} and ${owner} share the URL segment`,\n );\n owners.set(segment, owner);\n };\n for (const resource of service.listResources())\n claim(kebabCase(resource.name), `resource \"${resource.name}\"`);\n for (const socket of service.listSockets())\n if (socket.schema.path === undefined)\n claim(kebabCase(socket.schema.name), `socket \"${socket.schema.name}\"`);\n for (const action of service.listActions())\n if (\n action.config.path === undefined &&\n !(action as { resourceAction?: unknown }).resourceAction &&\n getPluginActionRoute(action) === undefined\n )\n claim(kebabCase(action.name), `action \"${action.name}\"`);\n}\n","import type { InstalledPlugin } from \"./define-plugin\";\nimport type { Service, ArchitectureSchema } from \"./types\";\nimport { analyzeDeclaredApplication, type RouteIR } from \"./compiler/ir\";\nimport type { EventsDefinition } from \"./events/hub\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport { fileURLToPath } from \"node:url\";\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 Error(\n `Brick: duplicate ${label}\\n ${sites.get(name) ?? \"unknown\"}\\n ${site ?? \"unknown\"}`,\n );\n sites.set(name, site);\n}\n\nexport interface ArchitectureApplication {\n services: readonly Service[];\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 private routes = new Map<Service, readonly RouteIR[]>();\n\n /** Remember the actual registered routes for subsequent registry exports. */\n setApplicationRoutes(application: ArchitectureApplication): void {\n for (const service of application.services) {\n this.routes.set(\n service,\n application.routes.filter((route) => route.service === service.name),\n );\n }\n this.touch();\n }\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 const previous = this.services.get(service.name);\n if (previous) this.routes.delete(previous);\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 clear(): void {\n this.services.clear();\n this.sites.clear();\n this.routes.clear();\n this.touch();\n }\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 routes = application\n ? application.routes.filter((route) => route.service === service.name)\n : (this.routes.get(service) ??\n analyzeDeclaredApplication([service]).ir.routes);\n const byAction = new Map(routes.map((route) => [route.action, route]));\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\n// Global registry instance\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 {\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 \"http.request.method\": method,\n \"http.route\": route,\n };\n if (request.request) {\n attributes[\"url.path\"] = 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(\"http.response.status_code\", status);\n const traceId = headers[\"x-trace-id\"];\n if (traceId) span.setAttribute(\"brick.trace_id\", 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 \"brick.error.code\": failure.code,\n \"brick.error.status\": failure.status,\n \"brick.error.message\": 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 \"db.system\": system,\n \"db.operation\": operationOf(sql),\n \"db.statement\": 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\";\n\nexport interface ErrorEnvelope {\n name: string;\n code: string;\n message: string;\n status: number;\n requestId: string;\n details?: unknown;\n errors?: ValidationError[\"errors\"];\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 { 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(\"brickkit.logs.capture\");\n\n/** The span event a log line becomes; the dashboard reads these. */\nconst LOG_EVENT = \"log\";\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\n/** `text` without terminal formatting. */\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(\"brick.logs.dropped\", count - MAX_LOGS_PER_SPAN);\n return;\n }\n span.addEvent(LOG_EVENT, {\n \"log.level\": level,\n \"log.message\": 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(\"brickkit.logs.record\")] =\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 { TSchema } from \"@sinclair/typebox\";\nimport {\n type Action,\n type ActionConfigWithAuthorize,\n type ActionConfigWithoutAuthorize,\n type ActionContext,\n type ActionErrorDefinition,\n type ErrorBuilder,\n type BaseContext,\n ActionExecutionError,\n ValidationError,\n type Logger,\n} from \"./types\";\nimport { normalizeActionError } from \"./error-response\";\nimport { validateWithSchema } from \"./typebox\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\n\nconst defaultLogger: Logger = createLogger(DEFAULT_LOG_PREFIXES);\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet _defaultCtxSeq = 0;\n\n// Symbol to tie context resolution to a specific service instance and invocation\nconst RESOLVED_SYMBOL = Symbol(\"resolved\");\n\nconst standardErrorDefaults: Record<\n string,\n { status: number; message: string }\n> = {\n BAD_REQUEST: { status: 400, message: \"Bad Request\" },\n UNAUTHORIZED: { status: 401, message: \"Unauthorized\" },\n FORBIDDEN: { status: 403, message: \"Forbidden\" },\n NOT_FOUND: { status: 404, message: \"Not Found\" },\n CONFLICT: { status: 409, message: \"Conflict\" },\n INTERNAL_SERVER_ERROR: { status: 500, message: \"Internal Server Error\" },\n};\n\nfunction createDefaultContext(partial?: any): BaseContext & any {\n // Only accept pre-resolved context with a service-specific marker or when service will handle resolution\n if (partial?.[RESOLVED_SYMBOL]) return partial;\n const seq = (++_defaultCtxSeq).toString(36);\n const req = partial?.request ?? DEFAULT_REQUEST;\n return {\n request: req,\n traceId: partial?.traceId || `tr_${seq}`,\n requestId: partial?.requestId || `req_${seq}`,\n db: partial?.db,\n user: partial?.user,\n logger: partial?.logger || defaultLogger,\n services: partial?.services || {},\n metadata: partial?.metadata || {},\n ...partial,\n [RESOLVED_SYMBOL]: true,\n };\n}\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\n // 1. Populate standard HTTP error helpers\n for (const [code, def] of Object.entries(standardErrorDefaults)) {\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n const message = overrideMessage || def.message;\n const status = def.status;\n throw new ActionExecutionError(code, message, status, details, options);\n };\n }\n\n // 2. Populate or override with user-defined action errors\n if (errorsDef) {\n for (const [code, def] of Object.entries(errorsDef)) {\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n const message = overrideMessage || def.message;\n const status = def.status || 400;\n throw new ActionExecutionError(code, message, status, details, options);\n };\n }\n }\n\n return helpers as ErrorBuilder<TErrors>;\n}\n\n// Lives with the step helpers, which workflow code imports without the server.\nexport { defineError } from \"./workflow\";\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 return validateWithSchema(config.input, input);\n };\n\n actionFn.validateOutput = (output: unknown) => {\n const runtimeSchema =\n (actionFn as { outputValidationSchema?: TSchema })\n .outputValidationSchema ?? config.output;\n return validateWithSchema(runtimeSchema, output);\n };\n\n actionFn.run = async (input?: any, ctx?: any) => {\n return actionFn.execute({ input, ctx });\n };\n\n actionFn.execute = async (params: { input?: any; ctx?: any }) => {\n const boundService = actionFn.service;\n // The bound service resolves the context once per request, and recognizes\n // one it already resolved.\n const fullCtx: any = boundService?.resolveContext\n ? await boundService.resolveContext(params?.ctx)\n : createDefaultContext(params?.ctx);\n\n try {\n // Fill ctx.db from the bound service or the registry when the call has none.\n if (!fullCtx.db) {\n const service =\n boundService ??\n (actionFn.serviceName\n ? getGlobalRegistry().get(actionFn.serviceName)\n : undefined);\n if (service?.getDb()) fullCtx.db = service.getDb();\n }\n\n // 1. Validate Input\n if (config.input) {\n const inputValidation = actionFn.validateInput(params?.input);\n if (!inputValidation.success) {\n throw new ValidationError(\n `Validation failed for action '${config.name}' input` as string,\n inputValidation.errors,\n );\n }\n }\n\n // 2. Authorize\n if (config.authorize) {\n const allowed = await config.authorize({\n user: fullCtx.user,\n input: params?.input,\n ctx: fullCtx,\n });\n if (!allowed) {\n throw new ActionExecutionError(\n fullCtx.user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${config.name}'`,\n fullCtx.user == null ? 401 : 403,\n );\n }\n }\n\n // 3. Execute implementation\n const result = await config.execute({\n input: params?.input,\n ctx: fullCtx,\n error: errorHelpers,\n });\n\n // 4. Validate Output\n const runtimeOutputSchema =\n (actionFn as { outputValidationSchema?: TSchema })\n .outputValidationSchema ?? config.output;\n if (runtimeOutputSchema) {\n const outputValidation = actionFn.validateOutput(result);\n if (!outputValidation.success) {\n throw new ValidationError(\n `Validation failed for action '${config.name}' output` as string,\n outputValidation.errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err) {\n throw normalizeActionError(err, fullCtx);\n }\n };\n\n return actionFn;\n}\n","import type { TSchema } from \"@sinclair/typebox\";\nimport type {\n Action,\n ActionConfigWithAuthorize,\n ActionConfigWithoutAuthorize,\n ActionContext,\n ActionErrorDefinition,\n BaseContext,\n Resource,\n Service,\n} from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { defineAction } from \"./action\";\nimport { joinRoute, ownerPath } from \"./routes\";\n\nexport type PluginRouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport type PluginRouteScope = \"app\" | \"service\" | \"resource\";\nexport type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =\n | false\n | Readonly<Record<string, false | { path?: string; scope?: S }>>;\n\ntype 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 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 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\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 import(\"./define-plugin\").PluginInstance<\n infer A extends object,\n any\n >\n ? A\n : P extends ResourcePlugin<any, any, infer A>\n ? A\n : never;\n\n// Process-global like actionBindingKey, so descriptors survive a second core copy.\nconst pluginKind: unique symbol = Symbol.for(\"brickkit.plugin.kind\");\n/** `definePlugin` instances install on either host; see `define-plugin.ts`. */\nexport const pluginFinish: unique symbol = Symbol.for(\"brickkit.plugin.finish\");\nexport interface ServicePlugin<S extends Service<any, any>, A> {\n readonly [pluginKind]: \"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 [pluginKind]: \"resource\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes;\n readonly setup: (context: ResourcePluginContext<S, R>) => A;\n}\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 pluginKind> & {\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 [pluginKind]: \"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 pluginKind> & {\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 [pluginKind]: \"resource\" as const,\n });\n}\n\nfunction 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 (\n value.scope !== undefined &&\n ![\"app\", \"service\", \"resource\"].includes(value.scope)\n )\n throw new Error(`Invalid plugin route scope '${value.scope}'`);\n result[name] = Object.freeze({ ...value });\n }\n return Object.freeze(result);\n}\n\ninterface Binding {\n service: Service<any, any>;\n resource?: Resource<any, any, any>;\n /** Owning plugin descriptor name (e.g. `@brickkit/crud`). Kept separate from the public action name. */\n plugin: string;\n path: string;\n method: PluginRouteMethod;\n scope: PluginRouteScope;\n enabled: boolean;\n clientPath?: string[];\n}\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}\nconst states = new WeakMap<object, PluginState>();\nconst actionBindings = new WeakMap<Action<any, any, any, any>, Binding>();\n/**\n * Cross-copy binding protocol. Bundler SSR runtimes (Vite, Nitro, Vitest)\n * may load a second copy of core that owns a different WeakMap, while the\n * action objects themselves cross the boundary by reference. The binding\n * travels on the action under a process-global symbol so route lookups\n * (including disabled-route suppression) keep working there.\n */\nconst actionBindingKey = Symbol.for(\"brickkit.plugin.actionBinding\");\nfunction stateOf(service: Service<any, any>): PluginState {\n let state = states.get(service);\n if (!state) {\n state = { hosts: new Map(), actions: new Map(), endpoints: [] };\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\nfunction pathOf(binding: Binding, prefix: string) {\n return joinRoute(\n binding.scope === \"app\"\n ? ownerPath(prefix)\n : ownerPath(\n prefix,\n binding.service.name,\n binding.scope === \"resource\" ? binding.resource!.name : undefined,\n ),\n binding.path,\n );\n}\n/**\n * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the\n * compiler, and the typed client.\n *\n * @param action - An action.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns `undefined` when no plugin bound the action (it uses its own route),\n * `false` when the plugin's route was switched off, otherwise the route's\n * `path`, `method`, the `clientPath` the typed client uses, and the owning\n * `plugin` and `resource`.\n */\nexport function getPluginActionRoute(\n action: Action<any, any, any, any>,\n prefix = \"/api\",\n) {\n const binding =\n (action as unknown as Record<symbol, Binding | undefined>)[\n actionBindingKey\n ] ?? actionBindings.get(action);\n if (!binding) return undefined;\n if (!binding.enabled) return false;\n return {\n path: pathOf(binding, prefix),\n method: binding.method,\n clientPath: binding.clientPath,\n plugin: binding.plugin,\n resource: binding.resource?.name,\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 = \"/api\",\n) {\n return stateOf(service)\n .endpoints.filter((binding) => binding.enabled)\n .map((binding) => ({\n path: pathOf(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/** 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[pluginKind] !== (resource ? \"resource\" : \"service\") &&\n descriptor[pluginKind] !== \"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 snapshots = {\n actions: new Map(service.actions),\n tools: new Map(service.tools),\n tables: new Map(service.tables),\n resources: new Map(service.resources),\n preparations: new Map(service.preparations),\n hosts: new Map(\n [...state.hosts].map(([key, installations]) => [\n key,\n new Map(installations),\n ]),\n ),\n bindings: new Map(state.actions),\n endpoints: [...state.endpoints],\n properties: new Map(\n [...service.resources.values()].map((item) => [\n item,\n Object.getOwnPropertyDescriptors(item),\n ]),\n ),\n };\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 ownedActions = new Set<Action<any, any, any, any>>();\n let active = true;\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 Error(`Duplicate plugin route name '${config.name}'`);\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 (![\"app\", \"service\", \"resource\"].includes(scope))\n throw new Error(`Invalid plugin route scope '${scope}'`);\n if (![\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].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 return {\n service,\n resource,\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 match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) {\n if (\n !config.input?.properties ||\n !Object.hasOwn(config.input.properties, match[1]!)\n )\n throw new Error(\n `Plugin action path parameter '${match[1]}' 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.actions.has(name))\n throw new Error(\n `Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`,\n );\n const { scope: _scope, ...actionConfig } = config;\n const action = defineAction({ ...actionConfig, name });\n (action as unknown as Record<string, unknown>).plugin = descriptor.name;\n if (resource)\n (action as unknown as Record<string, unknown>).resource = resource.name;\n service.action(action);\n ownedActions.add(action);\n state.actions.set(action, binding);\n actionBindings.set(action, binding);\n // Same object travels across bundler module copies; see actionBindingKey.\n (action as unknown as Record<symbol, Binding>)[actionBindingKey] =\n 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 };\n try {\n const api = resource\n ? (descriptor as ResourcePlugin<any, any, any>).setup({\n service,\n resource,\n routes,\n })\n : (descriptor as ServicePlugin<any, any>).setup({ service, routes });\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 finish(descriptor, true);\n getGlobalRegistry().touch();\n return resource ?? api;\n } catch (error) {\n finish(descriptor, false);\n for (const action of state.actions.keys())\n if (!snapshots.bindings.has(action)) {\n actionBindings.delete(action);\n delete (action as unknown as Record<symbol, unknown>)[actionBindingKey];\n }\n restoreMap(service.actions, snapshots.actions);\n restoreMap(service.tools, snapshots.tools);\n restoreMap(service.tables, snapshots.tables);\n restoreMap(service.resources, snapshots.resources);\n restoreMap(service.preparations, snapshots.preparations);\n state.hosts = snapshots.hosts;\n state.actions = snapshots.bindings;\n state.endpoints = snapshots.endpoints;\n for (const [item, properties] of snapshots.properties) {\n for (const key of Reflect.ownKeys(item))\n if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);\n Object.defineProperties(item, properties);\n }\n getGlobalRegistry().touch();\n throw error;\n } finally {\n active = false;\n }\n}\nfunction finish(descriptor: object, installed: boolean) {\n (descriptor as { [pluginFinish]?: (installed: boolean) => void })[\n pluginFinish\n ]?.(installed);\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}\nfunction restoreMap<K, V>(target: Map<K, V>, snapshot: Map<K, V>) {\n target.clear();\n for (const [key, value] of snapshot) target.set(key, value);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\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 socket a plugin declared keeps the plugin's deps; 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 {\n name: string;\n options: { deps?: Ports };\n setDeps?(deps: Record<string, unknown>): void;\n }[],\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 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 { readFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport { getTableName, type Table } from \"drizzle-orm\";\nimport {\n integer as sqliteInteger,\n real as sqliteReal,\n sqliteTable,\n text as sqliteText,\n type SQLiteColumnBuilderBase,\n} from \"drizzle-orm/sqlite-core\";\nimport {\n boolean as pgBoolean,\n doublePrecision,\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp as pgTimestamp,\n} from \"drizzle-orm/pg-core\";\nimport { PLUGIN_DEPS, runWithDeps, type DepsOf, type Ports } from \"./deps\";\nimport type { EventCatalog, EventRef, EventRefs } from \"./events/catalog\";\nimport type { EventListener } from \"./events/types\";\nimport {\n hasPlugin,\n pluginFinish,\n type PluginRouteRegistrar,\n type ResourcePlugin,\n type ServicePlugin,\n} from \"./plugin\";\nimport { definitionSite } from \"./registry\";\nimport type { SecretRef } from \"./secrets\";\nimport { validateWithSchema } from \"./typebox\";\nimport type { ActionContext, BaseContext, Resource, Service } from \"./types\";\n\n/*\n * definePlugin: one plugin with a manifest Brick checks (name, supported Brick\n * versions, required plugins, typed options, secrets) and a place for each\n * capability: owned tables, catalog events, host CRUD hooks, routes, and an\n * app part with start/stop lifecycle, middleware and listeners. Installing on\n * a service or resource reuses `installPlugin`, so route registration,\n * collision checks and rollback are the same as for the older two kinds.\n */\n\n// ---------------------------------------------------------------- versions\n\nlet runningVersion: string | undefined;\n/** The version of this @brickkit/core, read from its package.json; `\"\"` when unknown. */\nexport function brickVersion(): string {\n if (runningVersion !== undefined) return runningVersion;\n // src/ and dist/ sit one level down, a shared chunk two.\n for (const relative of [\"../package.json\", \"../../package.json\"]) {\n try {\n const json = JSON.parse(\n readFileSync(fileURLToPath(new URL(relative, import.meta.url)), \"utf8\"),\n );\n if (json.name === \"@brickkit/core\")\n return (runningVersion = json.version);\n } catch {\n // Not there; try the next one.\n }\n }\n // shortcut: a bundle that inlined core has no package.json; the check then passes.\n return (runningVersion = \"\");\n}\n\ntype Triple = [number, number, number];\nfunction parseVersion(version: string): Triple {\n const [major = 0, minor = 0, patch = 0] = version\n .replace(/^v/, \"\")\n .split(/[-+]/)[0]!\n .split(\".\")\n .map(Number);\n return [major, minor, patch];\n}\nfunction compare(a: Triple, b: Triple): number {\n return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];\n}\n\n/**\n * Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,\n * `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.\n */\nexport function satisfiesRange(version: string, range: string): boolean {\n const current = parseVersion(version);\n return range.split(\"||\").some((set) =>\n set\n .trim()\n .split(/\\s+/)\n .filter(Boolean)\n .every((comparator) => {\n const match =\n /^(\\^|~|>=|<=|>|<|=)?v?([\\dx*]+(?:\\.[\\dx*]+){0,2})?/i.exec(\n comparator,\n );\n const operator = match?.[1] ?? \"\";\n const raw = match?.[2] ?? \"*\";\n const parts = raw.split(\".\");\n const wild = parts.findIndex((part) => /^[x*]$/i.test(part));\n const given = wild === -1 ? parts.length : wild;\n const low = parseVersion(parts.slice(0, given).join(\".\") || \"0\");\n if (given === 0) return true;\n const cmp = compare(current, low);\n if (operator === \">=\") return cmp >= 0;\n if (operator === \">\") return cmp > 0;\n if (operator === \"<\") return cmp < 0;\n if (operator === \"<=\") return cmp <= 0;\n let high: Triple;\n if (operator === \"^\")\n high =\n low[0] > 0 || given === 1\n ? [low[0] + 1, 0, 0]\n : low[1] > 0 || given === 2\n ? [0, low[1] + 1, 0]\n : [0, 0, low[2] + 1];\n else if (operator === \"~\" || given < 3)\n high = given === 1 ? [low[0] + 1, 0, 0] : [low[0], low[1] + 1, 0];\n else return cmp === 0;\n return cmp >= 0 && compare(current, high) < 0;\n }),\n );\n}\n\n// ------------------------------------------------------------------ tables\n\nconst OWNER = Symbol.for(\"brickkit.plugin.owner\");\n/** The plugin that owns a table, for tables a `definePlugin` contributed. */\nexport function pluginOwner(table: unknown): string | undefined {\n return table && typeof table === \"object\"\n ? (table as Record<symbol, string | undefined>)[OWNER]\n : undefined;\n}\n\nconst sqliteBuilders = {\n /** A table. Its name gets the plugin's prefix (`page_comments`). */\n table: <C extends Record<string, SQLiteColumnBuilderBase>>(\n name: string,\n columns: C,\n ) => sqliteTable(name, columns),\n text: (name: string) => sqliteText(name),\n integer: (name: string) => sqliteInteger(name, { mode: \"number\" }),\n real: (name: string) => sqliteReal(name),\n boolean: (name: string) => sqliteInteger(name, { mode: \"boolean\" }),\n /** A `Date`, stored as epoch milliseconds or `timestamptz`. */\n timestamp: (name: string) => sqliteInteger(name, { mode: \"timestamp_ms\" }),\n json: (name: string) => sqliteText(name, { mode: \"json\" }),\n};\n\n/**\n * Engine-neutral column builders for `tables`. Brick passes the SQLite or\n * Postgres ones to match the host database; the types follow SQLite's, and the\n * JavaScript values are the same on both (a `Date` for `timestamp`).\n */\nexport type PluginTableBuilders = typeof sqliteBuilders & {\n /** The host database's engine. */\n readonly engine: \"sqlite\" | \"postgres\";\n};\n\nfunction builders(\n engine: \"sqlite\" | \"postgres\",\n tableName: (name: string) => string,\n): PluginTableBuilders {\n if (engine === \"postgres\")\n return {\n engine,\n table: (name, columns) =>\n pgTable(tableName(name), columns as never) as never,\n text: (name) => pgText(name) as never,\n integer: (name) => pgInteger(name) as never,\n real: (name) => doublePrecision(name) as never,\n boolean: (name) => pgBoolean(name) as never,\n timestamp: (name) =>\n pgTimestamp(name, { mode: \"date\", withTimezone: true }) as never,\n json: (name) => jsonb(name) as never,\n };\n return {\n ...sqliteBuilders,\n engine,\n table: (name, columns) => sqliteTable(tableName(name), columns),\n };\n}\n\n// ------------------------------------------------------------------- hooks\n\n/** Where `hooks.*` stores a plugin's hooks; `@brickkit/crud` runs them. */\nconst HOST_HOOKS = Symbol.for(\"brickkit.plugin.hooks\");\n\ninterface HookBase<C> {\n ctx: C;\n /** The write's open transaction: write other tables through it. */\n tx: any;\n}\n/**\n * Subscribe to the host's CRUD writes (resources with `crud()`). `before*` and\n * `after*` run inside the write's transaction, after the host's own crud hooks;\n * a hook that throws rolls the write back. `afterCommit` runs after the commit.\n */\nexport interface PluginHooks<C = ActionContext> {\n beforeCreate(\n hook: (args: HookBase<C> & { data: Record<string, unknown> }) => unknown,\n ): void;\n afterCreate(\n hook: (args: HookBase<C> & { row: Record<string, unknown> }) => unknown,\n ): void;\n beforeUpdate(\n hook: (\n args: HookBase<C> & { id: unknown; data: Record<string, unknown> },\n ) => unknown,\n ): void;\n afterUpdate(\n hook: (\n args: HookBase<C> & { id: unknown; row: Record<string, unknown> },\n ) => unknown,\n ): void;\n beforeDelete(hook: (args: HookBase<C> & { id: unknown }) => unknown): void;\n afterDelete(hook: (args: HookBase<C> & { id: unknown }) => unknown): void;\n afterCommit(\n hook: (args: {\n operation: \"create\" | \"update\" | \"delete\";\n id: unknown;\n row?: Record<string, unknown>;\n ctx: C;\n }) => unknown,\n ): void;\n}\nconst HOOK_NAMES = [\n \"beforeCreate\",\n \"afterCreate\",\n \"beforeUpdate\",\n \"afterUpdate\",\n \"beforeDelete\",\n \"afterDelete\",\n \"afterCommit\",\n] as const;\n\n// ---------------------------------------------------------------- manifest\n\ntype Secrets = Record<string, SecretRef<any>>;\ntype OptionsOf<O> = O extends TSchema ? Static<O> : {};\n\n/**\n * The context of a plugin's actions, endpoints and hooks: the host's request\n * context, loosely typed, with `deps` set to the plugin's own declared deps.\n */\nexport type PluginContext<P extends Ports = {}> = BaseContext<any> &\n PluginServiceContext<P>;\n/** A plugin's view of its host's service context: loose, except `deps`, which is the plugin's. */\nexport type PluginServiceContext<P extends Ports = {}> = {\n [key: string]: any;\n /** The values passed for the plugin's `deps` when it was installed. */\n deps: DepsOf<P>;\n};\n\n/** What every setup callback receives. */\nexport interface PluginSetupContext<\n O,\n S,\n T,\n E extends EventCatalog,\n P extends Ports = {},\n> {\n /** The validated options, defaults filled in. */\n options: O;\n /** The declared secrets, to read when they are needed. */\n secrets: S;\n /** The tables this plugin owns, by the keys `tables` returned. */\n tables: T;\n /** The plugin's events, as `emitEvent` and `defineListener` take them. */\n events: EventRefs<E>;\n /** The values passed for `deps` when the plugin was installed. */\n deps: DepsOf<P>;\n /** The host service. Actions registered on it read the plugin's deps as `ctx.deps`. */\n service: Service<any, PluginServiceContext<P>>;\n routes: PluginRouteRegistrar<PluginContext<P>>;\n /** The host's CRUD writes: on a service, those of all its resources. */\n hooks: PluginHooks<PluginContext<P>>;\n}\n\n/** The lifecycle context of `on(\"start\")` and `on(\"stop\")`. */\nexport interface PluginLifecycleContext<O, S, P extends Ports = {}> {\n options: O;\n secrets: S;\n deps: DepsOf<P>;\n}\n\n/** What `app` receives: the app-wide part of a plugin. */\nexport interface PluginAppContext<O, S, P extends Ports = {}> {\n options: O;\n secrets: S;\n /** The values passed for `deps` when the plugin was installed. */\n deps: DepsOf<P>;\n /**\n * Run when the app starts (`app.start()`, which `listen`, `brick dev` and\n * `brick start` call) in install order, and when it stops in reverse order.\n */\n on(\n event: \"start\" | \"stop\",\n handler: (context: PluginLifecycleContext<O, S, P>) => void | Promise<void>,\n ): void;\n /**\n * Run before every request is routed. Return a `Response` (or any value) to\n * answer it here; return nothing to let it through.\n */\n middleware(\n handler: (context: {\n request: Request;\n set: { status?: number | string; headers: Record<string, string> };\n }) => unknown,\n ): void;\n /**\n * Event listeners to add to the app's `events`. `useDeps()` in their `run`,\n * and in the steps of their `workflow`, returns the plugin's deps.\n */\n listeners(...listeners: EventListener[]): void;\n}\n\nexport interface PluginManifest<\n O extends TSchema | undefined = undefined,\n S extends Secrets = {},\n T extends Record<string, Table> = {},\n E extends EventCatalog = {},\n RA extends object = {},\n SA = unknown,\n P extends Ports = {},\n> {\n /** The npm package name, scoped: `@acme/brick-comments`. */\n name: string;\n description?: string;\n /** The Brick versions it supports, as a semver range: `^0.11.0`. */\n brick?: string;\n /** Plugins that must be installed on the same host first, by name. */\n requires?: readonly string[];\n /** A TypeBox schema for the options; defaults fill what the user leaves out. */\n options?: O;\n /** Secrets it reads, from `defineSecret`. */\n secrets?: S;\n /**\n * What it needs from the app, declared with `port<T>()`. The user passes the\n * values when installing: `notify(options, { deps: { mailer } })`. Setup\n * parts read them as `deps`, the plugin's actions as `ctx.deps`.\n */\n deps?: P;\n /**\n * Tables it owns. They are created in the host service's database for its\n * engine, named `<host>_<table>` (or with the install's `prefix`), and join\n * schema sync and migrations through `database.tables`.\n */\n tables?: (builders: PluginTableBuilders) => T;\n /** Events it emits; they join the host catalog as `<plugin>.<event>`. */\n events?: E;\n /** Installed with `resource.use()`; returns what the resource gains. */\n resource?: (\n context: PluginSetupContext<OptionsOf<O>, S, T, E, P> & {\n resource: Resource<any, PluginContext<P>, any>;\n },\n ) => RA & (RA extends PromiseLike<unknown> ? never : unknown);\n /** Installed with `service.use()`; returns what `use` hands back. */\n service?: (\n context: PluginSetupContext<OptionsOf<O>, S, T, E, P>,\n ) => SA & (SA extends PromiseLike<unknown> ? never : unknown);\n /**\n * The app-wide part: lifecycle, middleware and listeners. Runs once per\n * plugin instance when `brick()` creates the app, whether the plugin was\n * installed with `brick({ plugins })`, `service.use()` or `resource.use()`.\n */\n app?: (context: PluginAppContext<OptionsOf<O>, S, P>) => void;\n /**\n * A dashboard extension module (`defineDashboard`), relative to the file\n * that calls `definePlugin`. `brick dev` merges it with the app's own.\n */\n dashboard?: string;\n}\n\n/** Where the plugin is installed, besides its options. */\nexport interface PluginInstallOptions {\n /** Table name prefix instead of `<host>_`, such as `\"blog_\"`; `\"\"` for none. */\n prefix?: string;\n}\n\n/** What the plugin's capabilities are, read from its manifest. */\nexport interface PluginInfo {\n readonly name: string;\n readonly description?: string;\n readonly brick?: string;\n readonly requires: readonly string[];\n readonly options?: TSchema;\n readonly secrets: readonly string[];\n /** The names of the deps it declares, passed when installing. */\n readonly deps: readonly string[];\n readonly capabilities: readonly (\n | \"tables\"\n | \"events\"\n | \"resource\"\n | \"service\"\n | \"app\"\n | \"dashboard\"\n )[];\n}\n\nconst INTERNALS = Symbol.for(\"brickkit.plugin.internals\");\ninterface Installation {\n scope: \"app\" | \"service\" | \"resource\";\n service?: string;\n resource?: string;\n}\ninterface 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}\nlet installCount = 0;\n\n/** A plugin ready to install: `resource.use(p)`, `service.use(p)` or `brick({ plugins: [p] })`. */\nexport type PluginInstance<\n RA extends object = {},\n SA = unknown,\n> = ResourcePlugin<any, any, RA> &\n ServicePlugin<any, SA> & { readonly info: PluginInfo };\n\n/** `definePlugin`'s result: call it with options to get an instance. */\nexport type PluginFactory<\n O extends TSchema | undefined,\n RA extends object,\n SA,\n P extends Ports = {},\n> = ((\n // shortcut: every option is optional in the type (TypeBox types carry no\n // defaults); a required one without a default fails when installed.\n ...args: {} extends P\n ? [options?: Partial<OptionsOf<O>>, install?: PluginInstallOptions]\n : [\n options: Partial<OptionsOf<O>> | undefined,\n install: PluginInstallOptions & { deps: DepsOf<P> },\n ]\n) => PluginInstance<RA, SA>) & { readonly info: PluginInfo };\n\nconst toWords = (name: string) =>\n (name.split(\"/\").pop() ?? name)\n .replace(/^brick-/, \"\")\n .replace(/-plugin$/, \"\")\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean);\nconst snake = (value: string) =>\n value.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase();\n\n/**\n * Define a plugin: a manifest Brick checks, plus the capabilities the plugin\n * brings. Install its instances with `resource.use()`, `service.use()` or\n * `brick({ plugins })`; scope comes from where it is installed.\n *\n * @param manifest - `name`, `brick` (semver range), `requires`, `options`\n * (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`\n * parts, and a `dashboard` extension.\n * @returns A factory: `comments({ maxLength: 500 })` validates the options and\n * the Brick version and returns an instance to install.\n * @throws From the factory, when the running Brick is outside `brick` or an\n * option is invalid; when installed, when a required plugin is missing or the\n * host does not suit the plugin.\n * @example\n * export const audit = definePlugin({\n * name: \"@acme/brick-audit\",\n * brick: \"^0.11.0\",\n * requires: [\"@brickkit/crud\"],\n * options: t.Object({ table: t.String({ default: \"audit\" }) }),\n * tables: ({ table, text, timestamp }) => ({\n * log: table(\"log\", { id: text(\"id\").primaryKey(), at: timestamp(\"at\").notNull() }),\n * }),\n * resource: ({ tables, hooks }) => {\n * hooks.afterCreate(({ row, tx }) =>\n * tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));\n * return {};\n * },\n * });\n *\n * page.use(audit());\n */\nexport function definePlugin<\n O extends TSchema | undefined = undefined,\n S extends Secrets = {},\n T extends Record<string, Table> = {},\n const E extends EventCatalog = {},\n RA extends object = {},\n SA = unknown,\n P extends Ports = {},\n>(\n manifest: PluginManifest<O, S, T, E, RA, SA, P>,\n): PluginFactory<O, RA, SA, P> {\n const { name } = manifest;\n if (!name || name.trim() !== name)\n throw new Error(\n \"Plugin names must be nonempty and have no surrounding whitespace\",\n );\n if (!manifest.resource && !manifest.service && !manifest.app)\n throw new Error(\n `Plugin \"${name}\" needs a resource, service or app part to install`,\n );\n for (const key of Object.keys(manifest.events ?? {}))\n if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key))\n throw new Error(\n `Event \"${key}\" of plugin \"${name}\" must be a plain name such as added`,\n );\n const site = definitionSite()?.replace(/:\\d+$/, \"\");\n const dashboard =\n manifest.dashboard === undefined\n ? undefined\n : manifest.dashboard.startsWith(\"file:\")\n ? fileURLToPath(manifest.dashboard)\n : isAbsolute(manifest.dashboard) || !site\n ? resolve(manifest.dashboard)\n : resolve(dirname(site), manifest.dashboard);\n const info: PluginInfo = Object.freeze({\n name,\n description: manifest.description,\n brick: manifest.brick,\n requires: Object.freeze([...(manifest.requires ?? [])]),\n options: manifest.options,\n secrets: Object.freeze(\n Object.values(manifest.secrets ?? {}).map((secret) => secret.name),\n ),\n deps: Object.freeze(Object.keys(manifest.deps ?? {})),\n capabilities: Object.freeze(\n (\n [\"tables\", \"events\", \"resource\", \"service\", \"app\", \"dashboard\"] as const\n ).filter((key) => manifest[key] !== undefined),\n ),\n });\n const words = toWords(name);\n // `comments` for events (`comments.added`), `comments` for tables.\n const eventSpace = words\n .map((word, index) =>\n index ? word[0]!.toUpperCase() + word.slice(1) : word,\n )\n .join(\"\");\n const tableSpace = snake(words.join(\"_\"));\n if (!eventSpace)\n throw new Error(`Plugin \"${name}\" needs letters or digits in its name`);\n\n const factory = (\n input: Partial<OptionsOf<O>> = {},\n install: PluginInstallOptions & { deps?: Record<string, unknown> } = {},\n ): PluginInstance<RA, SA> => {\n const version = brickVersion();\n if (manifest.brick && version && !satisfiesRange(version, manifest.brick))\n throw new Error(\n `${name} supports Brick ${manifest.brick}; this app runs ${version}`,\n );\n const options = checkOptions(name, manifest.options, input);\n const deps = checkDeps(name, eventSpace, manifest.deps, install.deps);\n const secrets = (manifest.secrets ?? {}) as S;\n const internals: Internals = {\n manifest,\n options,\n deps,\n install,\n dashboard,\n installs: [],\n };\n // A stack: a plugin may install another instance of itself during setup.\n const pending: (() => void)[] = [];\n\n const setup = (context: {\n service: Service<any, any>;\n resource?: Resource<any, any, any>;\n routes: PluginRouteRegistrar<any>;\n }) => {\n const { service, resource } = context;\n const host = resource ?? service;\n const where = resource\n ? `resource \"${resource.name}\"`\n : `service \"${service.name}\"`;\n const part = resource ? manifest.resource : manifest.service;\n if (!part)\n throw new Error(\n `${name} cannot be installed on a ${resource ? \"resource\" : \"service\"}; ${\n manifest.resource\n ? \"use resource.use()\"\n : manifest.service\n ? \"use service.use()\"\n : \"add it to brick({ plugins })\"\n }`,\n );\n for (const required of manifest.requires ?? [])\n if (!hasPlugin(service, host, required))\n throw new Error(\n `${name} requires ${required}, installed on ${where} before it`,\n );\n\n // Tables: built for the host's engine, registered with the service now\n // (rolled back with it), added to its database once installed.\n let tables = {} as T;\n if (manifest.tables) {\n const database = service.getDatabaseHandle?.();\n if (!database)\n throw new Error(\n `${name} owns tables, so service \"${service.name}\" needs a database`,\n );\n const prefix =\n install.prefix ?? `${snake(resource?.name ?? service.name)}_`;\n tables = manifest.tables(\n builders(database.engine, (table) =>\n install.prefix !== undefined || table === tableSpace\n ? `${prefix}${table}`\n : `${prefix}${tableSpace}_${table}`,\n ),\n );\n const taken = new Set(\n [...service.tables.values(), ...Object.values(database.tables)].map(\n (table) => getTableName(table),\n ),\n );\n for (const table of Object.values(tables)) {\n const tableName = getTableName(table);\n if (taken.has(tableName))\n throw new Error(\n `${name} table \"${tableName}\" clashes with a table service \"${service.name}\" already has; install it with another prefix`,\n );\n taken.add(tableName);\n Object.defineProperty(table, OWNER, { value: name });\n service.registerTable(table);\n }\n }\n\n // Events: `<plugin>.<event>` in the host catalog. The same plugin on\n // two resources of one service shares them.\n const catalog = service.events as Record<string, EventRef>;\n const events: Record<string, EventRef> = {};\n for (const [key, schema] of Object.entries(manifest.events ?? {})) {\n const existing = catalog[`${eventSpace}.${key}`];\n if (existing && existing.plugin !== name)\n throw new Error(\n `${name} event \"${eventSpace}.${key}\" is already in the catalog of service \"${service.name}\"`,\n );\n events[key] =\n existing ??\n Object.freeze({\n name: `${service.name}.${eventSpace}.${key}`,\n service: service.name,\n schema,\n plugin: name,\n });\n }\n\n const added: Record<string, ((args: any) => unknown)[]> = {};\n const hooks = Object.fromEntries(\n HOOK_NAMES.map((hook) => [\n hook,\n (fn: (args: any) => unknown) => {\n if (typeof fn !== \"function\")\n throw new Error(`${name}: hooks.${hook} needs a function`);\n (added[hook] ??= []).push((args) =>\n fn({ ...args, ctx: { ...args.ctx, deps } }),\n );\n },\n ]),\n ) as unknown as PluginHooks<any>;\n\n const routes: PluginRouteRegistrar<any> = {\n action: (config: any) => context.routes.action(config),\n endpoint: (config) =>\n context.routes.endpoint({\n ...config,\n handler: (args) =>\n config.handler({ ...args, ctx: { ...args.ctx, deps } }),\n }),\n };\n const before = new Set<unknown>([\n ...service.actions.values(),\n ...service.tools.values(),\n ...service.listSockets(),\n ]);\n const started = bindings;\n const api = part({\n options: options as never,\n secrets,\n tables,\n events: events as EventRefs<E>,\n deps: deps as DepsOf<P>,\n service: service as never,\n resource: resource as never,\n routes,\n hooks,\n });\n if (api && typeof (api as { then?: unknown }).then === \"function\")\n throw new Error(\"Plugin setup must be synchronous\");\n // Every action and socket the setup added (its own, its resources', crud's) runs with the plugin's deps.\n for (const action of [\n ...service.actions.values(),\n ...service.tools.values(),\n ])\n if (!before.has(action)) bindPluginDeps(name, action, deps, started);\n for (const socket of service.listSockets())\n if (!before.has(socket))\n (socket as unknown as Record<symbol, unknown>)[PLUGIN_DEPS] ??= deps;\n\n pending.push(() => {\n const database = service.getDatabaseHandle?.();\n for (const table of Object.values(tables))\n database?.addTable?.(getTableName(table), table);\n if (Object.keys(events).length)\n // `readonly` for users; the catalog grows only here.\n (service as { events: Record<string, EventRef> }).events =\n Object.freeze({\n ...catalog,\n ...Object.fromEntries(\n Object.entries(events).map(([key, ref]) => [\n `${eventSpace}.${key}`,\n ref,\n ]),\n ),\n });\n const store = ((host as unknown as Record<symbol, unknown>)[\n HOST_HOOKS\n ] ??= {}) as Record<string, ((args: any) => unknown)[]>;\n for (const [hook, fns] of Object.entries(added))\n (store[hook] ??= []).push(...fns);\n internals.installs.push({\n scope: resource ? \"resource\" : \"service\",\n service: service.name,\n resource: resource?.name,\n });\n internals.order ??= ++installCount;\n });\n return resource ? (api ?? {}) : api;\n };\n\n return Object.freeze({\n [Symbol.for(\"brickkit.plugin.kind\")]: \"plugin\",\n name,\n info,\n setup,\n [INTERNALS]: internals,\n [pluginFinish]: (installed: boolean) => {\n const commit = pending.pop();\n if (installed) commit?.();\n },\n }) as unknown as PluginInstance<RA, SA>;\n };\n return Object.assign(factory, { info });\n}\n\n/** Counts bindings, so a setup can tell a nested install's from an earlier one's. */\nlet bindings = 0;\n/**\n * Give an action's `execute` and `authorize` the plugin's deps as `ctx.deps`.\n * The config is changed in place: every way an action runs (HTTP, compiled\n * routes, `action.run`, RPC) reads `config.execute` from it. A nested\n * definePlugin binds its own actions first, so they keep its deps.\n *\n * @throws When the action is already bound to another install's deps: one\n * action object shared by two installs could only run with one of them.\n */\nfunction bindPluginDeps(\n plugin: string,\n action: unknown,\n deps: Readonly<Record<string, unknown>>,\n started: number,\n) {\n const config = (action as { config?: Record<string | symbol, any> }).config;\n if (!config) return;\n const bound = config[PLUGIN_DEPS] as\n | { deps: Readonly<Record<string, unknown>>; at: number }\n | undefined;\n if (bound) {\n if (bound.deps === deps || bound.at > started) return;\n throw new Error(\n `${plugin}: action \"${(action as { name?: string }).name}\" is already bound to the deps of another install; create the action inside the setup so each install gets its own`,\n );\n }\n config[PLUGIN_DEPS] = { deps, at: ++bindings };\n const { execute, authorize } = config;\n if (typeof execute === \"function\")\n config.execute = (args: { ctx?: object }) =>\n execute({ ...args, ctx: { ...args.ctx, deps } });\n if (typeof authorize === \"function\")\n config.authorize = (args: { ctx?: object }) =>\n authorize({ ...args, ctx: { ...args.ctx, deps } });\n}\n\n/** Check the deps passed at install against the ports the plugin declares. */\nfunction checkDeps(\n plugin: string,\n factory: string,\n ports: Ports | undefined,\n given: unknown = {},\n): Readonly<Record<string, unknown>> {\n if (given === null || typeof given !== \"object\" || Array.isArray(given))\n throw new Error(`${plugin}: deps must be an object`);\n const declared = Object.keys(ports ?? {});\n const provided = given as Record<string, unknown>;\n const extra = Object.keys(provided).filter((key) => !declared.includes(key));\n if (extra.length)\n throw new Error(\n `${plugin} does not declare ${extra.map((key) => `deps.${key}`).join(\", \")}; ${\n declared.length ? `it takes ${declared.join(\", \")}` : \"it takes no deps\"\n }`,\n );\n const missing = declared.filter((key) => provided[key] === undefined);\n if (missing.length)\n throw new Error(\n `${plugin} needs ${missing.map((key) => `deps.${key}`).join(\", \")}; pass it when installing: ${factory}(options, { deps: { ${missing.join(\", \")} } })`,\n );\n return Object.freeze(\n Object.fromEntries(declared.map((key) => [key, provided[key]])),\n );\n}\n\nfunction checkOptions(\n plugin: string,\n schema: TSchema | undefined,\n input: unknown,\n): Record<string, unknown> {\n if (input === null || typeof input !== \"object\" || Array.isArray(input))\n throw new Error(`${plugin}: options must be an object`);\n if (!schema) {\n if (Object.keys(input).length)\n throw new Error(`${plugin} takes no options`);\n return {};\n }\n const value = Value.Default(schema, structuredClone(input));\n const result = validateWithSchema(schema, value);\n if (!result.success) {\n const [first] = result.errors;\n const option = first!.path.replace(/^\\//, \"\").replaceAll(\"/\", \".\");\n throw new Error(\n `${plugin}: option ${option ? `\"${option}\"` : \"\"} ${first!.message}`.replace(\n /\\s+/g,\n \" \",\n ),\n );\n }\n return value as Record<string, unknown>;\n}\n\n// --------------------------------------------------------------- app part\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\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 returns the plugin's deps, not the app's.\n listeners.push(\n ...items.map((listener) => {\n const run = listener.run;\n // The workflow runtime runs this workflow's steps with these deps.\n if (!run) return { ...listener, [PLUGIN_DEPS]: deps };\n return {\n ...listener,\n run: (delivery: Parameters<typeof run>[0]) =>\n runWithDeps(deps, () => run(delivery)),\n };\n }),\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 {\n ValidationError,\n ActionExecutionError,\n type CompiledRoutePlan,\n} from \"../types\";\n\nimport { toErrorResponse } from \"../error-response\";\nimport type { Logger } from \"../types\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n // Early return on the first key: an allocation-free emptiness check.\n for (const _ in value) return true; // NOSONAR\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\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\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\nfunction checkDepth(value: unknown, action: string) {\n if (!inputTooDeep(value)) return;\n throw new ValidationError(`Validation failed for action '${action}' input`, [\n { path: \"\", message: \"Input exceeds maximum nesting depth\" },\n ]);\n}\n\nfunction validate(\n check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\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\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES,\n defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36),\n mergeInput,\n checkDepth,\n validate,\n mapError,\n isThenable: (value: any): boolean =>\n value != null && typeof value.then === \"function\",\n 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","import {\n type Service,\n type Action,\n type Logger,\n type CompiledRoutePlan,\n ValidationError,\n ActionExecutionError,\n} from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { buildErrorHelpers } from \"./action\";\nimport { toErrorResponse } from \"./error-response\";\nimport { inputTooDeep } from \"./compiler/runtime\";\nimport { createLogger } from \"./logger\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n // Early return on the first key: an allocation-free emptiness check.\n for (const _ in obj) return true; // NOSONAR\n return false;\n}\n\n/**\n * Work out, once at startup, everything an action's route needs to answer a\n * request: where its input comes from (body, query, or path), the validators,\n * the authorization and execute functions, and its logger. Low level: `brick()`\n * does this for every route.\n *\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 The plan `executeCompiledRoute` runs.\n */\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema\n ? (getCompiledCheck(inputSchema) as any)\n : undefined;\n // Prefer a runtime-only output schema when the action provides one (CRUD\n // subset projections validate loosely at runtime while `config.output`\n // stays strict for contracts/OpenAPI).\n const runtimeOutputSchema =\n (action as { outputValidationSchema?: typeof outputSchema })\n .outputValidationSchema ?? outputSchema;\n const outputChecker = runtimeOutputSchema\n ? (getCompiledCheck(runtimeOutputSchema) as any)\n : undefined;\n\n let coercions:\n | Array<{\n key: string;\n isNumber: boolean;\n isBoolean: boolean;\n isArray?: boolean;\n }>\n | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{\n key: string;\n isNumber: boolean;\n isBoolean: boolean;\n isArray?: boolean;\n }> = [];\n for (const [key, prop] of Object.entries(\n (inputSchema as any).properties,\n ) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n } else if (type === \"array\") {\n list.push({ key, isNumber: false, isBoolean: false, isArray: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = createLogger(tag);\n\n const errorBuilder =\n (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\n/**\n * Answer one request for a compiled route: read the input, run the action, and\n * return its output or the error response, with the `x-trace-id` and\n * `x-request-id` headers set. Low level: `brick()` mounts this for every route.\n *\n * @param plan - From `compileRoutePlan`.\n * @param elysiaCtx - The Elysia request context: `params`, `body`, `query`,\n * `headers`, `request`, and `set`.\n * @returns The action's output, or an error envelope with the status set on `set`.\n */\nexport async function executeCompiledRoute(\n plan: CompiledRoutePlan,\n elysiaCtx: any,\n) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isArray) {\n const values = request\n ? new URL(request.url).searchParams.getAll(c.key)\n : [];\n coercedQuery[c.key] = values.length\n ? values\n : Array.isArray(val)\n ? val\n : [val];\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\")\n coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n // Path segments are strings; numeric ids (`/:id`) need numbers.\n let coercedParams = params;\n if (params && plan.coercions) {\n for (const c of plan.coercions) {\n if (!c.isNumber || typeof params[c.key] !== \"string\") continue;\n const num = Number(params[c.key]);\n if (isNaN(num)) continue;\n if (coercedParams === params) coercedParams = { ...params };\n coercedParams[c.key] = num;\n }\n }\n const hasP = isNonEmpty(coercedParams);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = coercedParams;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, coercedParams, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = coercedParams;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, coercedParams, body, coercedQuery);\n }\n }\n }\n\n const standardRequest =\n request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n deps: plan.service.deps ?? EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (input === undefined && plan.action.config?.input?.type === \"object\") {\n input = {};\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (inputTooDeep(input)) {\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n [{ path: \"\", message: \"Input exceeds maximum nesting depth\" }],\n );\n }\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n errors,\n );\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\n ctx.user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${plan.actionName}'`,\n ctx.user == null ? 401 : 403,\n );\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' output`,\n errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err) {\n const response = toErrorResponse(err, { logger: ctx.logger, requestId });\n set.status = response.status;\n return response;\n }\n}\n\n/**\n * An Elysia handler for one action: `compileRoutePlan` and\n * `executeCompiledRoute` together. Use it to mount an action on your own\n * Elysia app; `brick()` does it for you.\n *\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 const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import type { RouteIR } from \"./ir\";\nimport type { HandlerFactory } from \"./runtime\";\nimport type { ActionContext } from \"../types\";\n\nfunction coerceQueryValue(\n value: unknown,\n type: RouteIR[\"coercions\"][number][\"type\"],\n request: Request | undefined,\n key: string,\n) {\n if (type === \"number\" && value !== undefined) {\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 (type === \"boolean\") {\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n }\n return value;\n}\n\n/** Bind route metadata with ordinary closures; emitted factories remain build-only. */\nexport function createHandlerFactory(route: RouteIR): HandlerFactory {\n return (binding, runtime) => {\n const {\n execute,\n contextHook,\n authorize,\n inputChecker,\n outputChecker,\n errorBuilder,\n logger,\n cachedDb,\n service,\n } = binding;\n const readLike = route.inputPrecedence[0] === \"query\";\n const objectInput = binding.action.config.input?.type === \"object\";\n const readInput = route.input\n ? ({ params, body, query, request }: any) => {\n let coercedQuery = query;\n if (query && route.coercions.length) {\n coercedQuery = { ...query };\n for (const { key, type } of route.coercions) {\n if (query[key] !== undefined)\n coercedQuery[key] = coerceQueryValue(\n query[key],\n type,\n request,\n key,\n );\n }\n }\n // Path segments are strings; numeric ids (`/:id`) need numbers.\n let coercedParams = params;\n if (params && route.coercions.length) {\n for (const { key, type } of route.coercions) {\n if (type !== \"number\" || typeof params[key] !== \"string\")\n 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 let input = readLike\n ? runtime.mergeInput(coercedQuery, coercedParams, body)\n : runtime.mergeInput(coercedParams, body, coercedQuery);\n if (objectInput) input ??= {};\n return input;\n }\n : () => undefined;\n const validateInput = (input: unknown) => {\n if (inputChecker) {\n runtime.checkDepth(input, route.action);\n runtime.validate(inputChecker, input, route.action, \"input\");\n }\n };\n const validateOutput = (result: unknown) => {\n if (route.output && outputChecker)\n runtime.validate(outputChecker, result, route.action, \"output\");\n return result;\n };\n const createContext = ({\n headers,\n request,\n set,\n }: any): ActionContext & { requestId: string } => {\n const seq = runtime.nextSequence();\n const traceId = headers?.[\"x-trace-id\"] || \"tr_\" + seq;\n const requestId = headers?.[\"x-request-id\"] || \"req_\" + seq;\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n return {\n request: request instanceof Request ? request : runtime.defaultRequest,\n traceId,\n requestId,\n db: cachedDb ?? service.getDb(),\n logger,\n services: runtime.emptyServices,\n deps: service.deps ?? runtime.emptyServices,\n metadata: { headers },\n _resolved: true,\n };\n };\n if (contextHook || authorize) {\n return async function brickAction(context) {\n const input = readInput(context);\n const ctx = createContext(context);\n try {\n if (contextHook) {\n const extra = await contextHook(ctx);\n if (extra) Object.assign(ctx, extra);\n }\n validateInput(input);\n if (authorize && !(await authorize({ ctx, input, user: ctx.user })))\n runtime.deny(route.action, ctx.user);\n return validateOutput(\n await execute({ input, ctx, error: errorBuilder }),\n );\n } catch (err) {\n return runtime.mapError(err, context.set, ctx);\n }\n };\n }\n return function brickAction(context) {\n const input = readInput(context);\n const ctx = createContext(context);\n try {\n validateInput(input);\n const result = execute({ input, ctx, error: errorBuilder });\n if (runtime.isThenable(result))\n return Promise.resolve(result)\n .then(validateOutput)\n .catch((err) => runtime.mapError(err, context.set, ctx));\n return validateOutput(result);\n } catch (err) {\n return runtime.mapError(err, context.set, ctx);\n }\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 { compileRoutePlan, executeCompiledRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport { createHandlerFactory } from \"./compiler/handler\";\nimport {\n compilerRuntime,\n type CompiledHandler,\n type HandlerFactory,\n} from \"./compiler/runtime\";\nimport { requireBrickApp } from \"./app-entry\";\n\ntype ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;\nconst buildBindings = new Map<string, ApplicationBinder>();\n\nfunction applicationKey(\n services: readonly Service<any, any>[],\n prefix = \"/api\",\n) {\n return JSON.stringify([prefix, services.map((service) => service.name)]);\n}\n\n/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n ir: BrickIR,\n bind: ApplicationBinder,\n) {\n const key = JSON.stringify([ir.prefix, ir.services]);\n if (buildBindings.has(key))\n throw new Error(\"Brick compiler: overlapping compiled app imports\");\n buildBindings.set(key, bind);\n try {\n const app = requireBrickApp((await load()).default);\n if (applicationKey(app.definition.services, app.definition.prefix) !== key)\n throw new Error(\n \"Brick compiler: app services/prefix changed; rebuild the application\",\n );\n return app;\n } finally {\n buildBindings.delete(key);\n }\n}\n\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type { CompiledHandler, HandlerFactory } 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 factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(\n compileRoutePlan(service, action, route.path, route.method),\n );\n const handler = factories[index]!(plan, compilerRuntime);\n return Object.freeze({ ir: route, handler });\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 mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const bind = buildBindings.get(\n applicationKey(options.services, options.prefix),\n );\n if (bind && options.mode !== \"generic\") return bind(options.services);\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n const factories: HandlerFactory[] =\n options.mode === \"generic\"\n ? ir.routes.map(\n () => (plan) => (context) => executeCompiledRoute(plan, context),\n )\n : ir.routes.map(createHandlerFactory);\n if (options.mode !== \"generic\")\n for (const service of options.services) {\n service.prepareContributions();\n }\n return bindAnalyzed(ir, bindings, factories);\n}\n\n/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */\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 = 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 for (const service of services) {\n service.prepareContributions();\n }\n return bindAnalyzed(ir, analyzed.bindings, factories);\n}\n","import type { Action, ActionAccessPolicy } from \"./types\";\n\nexport type { ActionAccessPolicy };\nexport interface ActionAccessInfo {\n hasAuthorize: boolean;\n hasScope: boolean;\n policy: ActionAccessPolicy;\n}\n\n/**\n * Cross-copy access metadata protocol. CRUD enforces its access policy\n * inside `execute`, so `config.authorize` is absent and introspection\n * can't see it. The plugin stamps each action under this process-global\n * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so\n * the binding survives a second copy of core (bundler SSR, Vitest),\n * same as the plugin action-binding key.\n */\nexport const ACTION_ACCESS_KEY = Symbol.for(\"brickkit.action.access\");\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 (action as Record<symbol, ActionAccessInfo>)[ACTION_ACCESS_KEY] = {\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 = (action as Record<symbol, unknown>)[ACTION_ACCESS_KEY] as\n | Partial<ActionAccessInfo>\n | undefined;\n const configAuthorize = Boolean(\n (action as Action)?.config &&\n typeof (action as Action).config === \"object\" &&\n \"authorize\" in (action as Action).config &&\n typeof (action as Action).config.authorize === \"function\",\n );\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 { getActionRoute } from \"./routes\";\nimport { getActionAccess } from \"./access\";\nimport type { ServiceRegistry } from \"./registry\";\nimport { getGlobalRegistry } from \"./registry\";\nimport type { Service, ActionErrorDefinition } from \"./types\";\n\nexport interface OpenApiGeneratorOptions {\n title?: string;\n version?: string;\n description?: string;\n prefix?: string;\n services?: Service<any, any>[];\n registry?: ServiceRegistry;\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 */\nexport function hoistAnchoredSchemas(spec: Record<string, any>): string[] {\n const anchored = new Map<string, any>();\n const conflicts: string[] = [];\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)) {\n if (JSON.stringify(anchored.get(id)) !== JSON.stringify(collected)) {\n conflicts.push(id);\n }\n } else {\n anchored.set(id, collected);\n }\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 return [...anchored.keys()];\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` or `registry` to describe\n * (the global registry 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 ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const description =\n options.description ??\n \"Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.\";\n const prefix = options.prefix ?? \"/api\";\n\n const services =\n options.services ??\n (options.registry ? options.registry.list() : getGlobalRegistry().list());\n\n const paths: Record<string, any> = {};\n const tags = new Map<string, string>();\n let hasAnyAuthorizedAction = false;\n\n for (const service of services) {\n tags.set(service.name, `Actions exposed by '${service.name}' service`);\n\n for (const action of service.listActions()) {\n const route = getActionRoute(action, prefix);\n if (route === false) continue;\n const routePath = route.path;\n const method = route.method.toLowerCase();\n const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map(\n (match) => match[1]!,\n );\n const actionPath = routePath.replace(/:([^/]+)/g, \"{$1}\");\n if (!paths[actionPath]) paths[actionPath] = {};\n // Match the compiler's first-registration-wins policy for route collisions.\n if (paths[actionPath][method]) continue;\n\n const resource = (action as { resource?: string }).resource;\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 // Build responses map\n const responses: Record<string, any> = {};\n\n // 200 Success Response\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 ...((action as { plugin?: string }).plugin\n ? { \"x-brick-plugin\": (action as { plugin?: string }).plugin }\n : {}),\n ...((action as { resource?: string }).resource\n ? { \"x-brick-resource\": (action as { resource?: string }).resource }\n : {}),\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 const queryOnly = method === \"get\" || method === \"delete\";\n if (queryOnly) {\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\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 | 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 if (overrides.has(this.name)) {\n const v = overrides.get(this.name);\n if (v !== undefined) return v;\n }\n return source.get(this.name) ?? this.options.default;\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. Idempotent: re-declaring the same name returns the\n * original ref (first declaration wins) so module re-evaluation is safe.\n */\nexport function defineSecret(\n name: string,\n options: SecretOptions = {},\n): SecretRef<string> {\n const existing = registry.get(name);\n if (existing) return existing;\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 overrides.set(name, value);\n}\n\n/** Bulk overrides (test/session scoped). */\nexport function overrideSecrets(\n values: Record<string, string | undefined>,\n): void {\n for (const [name, value] of Object.entries(values)) {\n overrides.set(name, value);\n }\n}\n\n/** Clear registry and overrides. Test-only. */\nexport function resetSecrets(): void {\n registry.clear();\n overrides.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. Logging only —\n * no CORS headers are set here.\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\";\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/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? \"Brick-TS API Mesh\";\n const specUrl = opts.specUrl ?? \"/openapi.json\";\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/** Mounts the Scalar reference route onto an existing app. */\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 { RouteIR } from \"./compiler/ir\";\nimport type { Elysia } from \"elysia\";\nimport type { 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 { createLogger } from \"./logger\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport type { InstalledPlugin } from \"./define-plugin\";\n\nexport type EndpointMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Logger subset handed to endpoint handlers (mirrors action context loggers). */\nexport interface EndpointLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\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() ?? undefined;\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 = headers?.[\"x-trace-id\"] || `tr_${crypto.randomUUID()}`;\n const requestId = headers?.[\"x-request-id\"] || `req_${crypto.randomUUID()}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\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/** `/p/:slug` → `/p/{slug}` for OpenAPI. */\nexport function toOpenApiPath(elysiaPath: string): string {\n return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\n/** Parameter names (`:slug`) extracted for the OpenAPI path item. */\nfunction pathParamNames(elysiaPath: string): string[] {\n return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);\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 * 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 (outside the JSON action mesh). */\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 /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\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\";\n\nconst OUTBOX = Symbol.for(\"brick.outbox\");\n\n/** What the outbox rows are in, by state. */\nexport type OutboxStatus = \"pending\" | \"claimed\" | \"delivered\" | \"dead\";\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 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 { type OutboxStatus, type OutboxTable, outboxEngine } from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type { Deliverable } from \"./hub\";\nimport { ActionExecutionError } from \"../types\";\nimport type { DispatchOptions, EventDelivery } from \"./types\";\n\nexport type ResolvedDispatchOptions = Required<DispatchOptions>;\n\nexport function resolveDispatchOptions(\n options: DispatchOptions = {},\n): ResolvedDispatchOptions {\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\ninterface OutboxRow {\n seq: number;\n id: string;\n eventId: string;\n listener: string;\n name: string;\n payload: unknown;\n traceId: string | null;\n source: string | null;\n occurredAt: Date;\n status: OutboxStatus;\n attempts: number;\n lastError: string | null;\n}\n\nconst PURGE_INTERVAL_MS = 60_000;\n\n/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as \"retry\". */\nfunction decideRetry(listener: Deliverable, error: unknown): \"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 {\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: ResolvedDispatchOptions;\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 private readonly onError: (error: unknown) => void = (error) =>\n console.error(\"[Brick-TS events]\", error),\n ) {\n this.engine = outboxEngine(table);\n this.options = resolveDispatchOptions(options);\n }\n\n /** Whether the dispatcher is looking for work on a timer. */\n get running(): boolean {\n return this.timer !== undefined;\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 /**\n * Stop the timer and wait for the deliveries that are running to finish.\n */\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 /**\n * Claim what is due and run it, once. Used by the timer, and by tests and\n * workers that drive delivery themselves.\n *\n * @returns How many deliveries it started.\n */\n 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 /**\n * How many rows are in each state.\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: OutboxCounts = {\n pending: 0,\n claimed: 0,\n delivered: 0,\n dead: 0,\n };\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.onError(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 const delivery: EventDelivery = {\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 try {\n await listener.run(delivery);\n } catch (error) {\n await this.fail(\n row,\n error,\n listener.maxAttempts ?? this.options.maxAttempts,\n decideRetry(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.onError(error);\n }\n }\n\n private async fail(\n row: OutboxRow,\n error: unknown,\n maxAttempts: number,\n decision: \"retry\" | \"dead\" = \"retry\",\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.onError(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.onError(error);\n }\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","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","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { PLUGIN_DEPS, runWithDeps } from \"../deps\";\nimport type {\n EventDelivery,\n EventListener,\n EventsWorld,\n WorkflowEvent,\n WorkflowsOptions,\n} from \"./types\";\n\n/** `getQueueTopicPrefix(\"workflow\")` from `@workflow/world`: the queue the runtime reads. */\nconst WORKFLOW_QUEUE_PREFIX = \"__wkf_workflow_\";\nconst BUNDLE_DIR = \".well-known/workflow/v1\";\nconst STOPPED = \"The events were stopped, so workflows can no longer run\";\n/** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */\nexport const WEBHOOK_ROUTE = \"/.well-known/workflow/v1/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, 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 * @returns The run id.\n */\n async startRun(\n listener: EventListener,\n delivery: EventDelivery,\n ): Promise<string> {\n const sdk = await this.ensure();\n const { attempt: _attempt, ...event } = delivery;\n const run = await sdk.start(\n listener.workflow,\n [event satisfies WorkflowEvent],\n {\n world: this.world,\n runKey: delivery.deliveryId,\n runKeyTime: Date.parse(delivery.occurredAt),\n },\n );\n return run.runId;\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, \"webhook.mjs\");\n if (!existsSync(file))\n throw new Error(\n `No webhook bundle at ${file}. brick dev and brick start build it; ` +\n \"in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\",\n );\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, \"flow.mjs\");\n if (!existsSync(flow))\n throw new Error(\n `No workflow bundle at ${flow}. brick dev and brick start build it; ` +\n \"in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\",\n );\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(\"x-vqs-queue-name\") ?? \"\";\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, \"manifest.json\");\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 =\n ((listener as unknown as Record<symbol, unknown>)[PLUGIN_DEPS] as\n | Record<string, unknown>\n | undefined) ?? 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 { Dispatcher, type OutboxCounts } from \"./dispatcher\";\nimport { newEventId } from \"./id\";\nimport 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\";\n\ninterface EventsHost {\n readonly name: string;\n getDb(): unknown;\n getOutbox?(): OutboxTable | undefined;\n setRecorder?(recorder: ServiceEvents | undefined): void;\n /** Throws for an event the service's catalog does not allow. */\n checkEvent?(name: string, payload: unknown): void;\n}\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 recorder of each service database, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */\nexport const recorders = new WeakMap<object, ServiceEvents>();\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(\"brickkit.events.started\")\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 if (typeof listener.name !== \"string\" || !listener.name)\n throw new Error(\"An event listener needs a name\");\n if (listener.name.includes(\":\"))\n throw new Error(\n `Event listener name '${listener.name}' must not contain ':'`,\n );\n if (!listener.on?.length)\n throw new Error(\n `Event listener '${listener.name}' listens for nothing`,\n );\n if (this.byName.has(listener.name))\n throw new Error(`Duplicate event listener '${listener.name}'`);\n if (!listener.run === !listener.workflow)\n throw new Error(\n `Event listener '${listener.name}' needs exactly one of run and workflow`,\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 EventsHost[]): this {\n let attached = 0;\n for (const service of services) {\n const table = service.getOutbox?.();\n if (!table) continue;\n attached++;\n this.recorderNames.push(service.name);\n const bound = this.bind(table, (name, payload) =>\n service.checkEvent?.(name, payload),\n );\n service.setRecorder?.(bound);\n const db = service.getDb();\n if (db && typeof db === \"object\") recorders.set(db, bound);\n }\n if (attached === 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 for (const service of services) {\n const table = service.getOutbox?.();\n if (table && !this.dispatchers.has(table)) {\n this.dispatchers.set(\n table,\n new Dispatcher(\n service.getDb(),\n table,\n (name) => this.deliverable(name),\n this.dispatchOptions || {},\n ),\n );\n }\n }\n return this;\n }\n\n /** The listeners that want an event. */\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 /** The listeners and settings, as plain data. */\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: OutboxCounts = {\n pending: 0,\n claimed: 0,\n delivered: 0,\n dead: 0,\n };\n for (const dispatcher of this.dispatchers.values()) {\n const counts = await dispatcher.counts();\n for (const status of Object.keys(total) as (keyof OutboxCounts)[])\n 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 runtime = this.runtime;\n found = {\n ...(listener.errors ? { errors: listener.errors } : {}),\n ...(listener.retry ? { retry: listener.retry } : {}),\n ...(listener.workflow\n ? {\n ...(listener.maxAttempts !== undefined\n ? { maxAttempts: listener.maxAttempts }\n : {}),\n run: async (delivery) => {\n await runtime!.startRun(listener, delivery);\n },\n }\n : {\n ...(listener.maxAttempts !== undefined\n ? { maxAttempts: listener.maxAttempts }\n : {}),\n run: (delivery) =>\n runWithDeps(this.deps, () => listener.run!(delivery)),\n }),\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 const eventId = newEventId();\n const occurredAt = new Date();\n await tx.insert(table as any).values(\n listeners.map((listener) => ({\n id: `${eventId}:${listener.name}`,\n eventId,\n listener: listener.name,\n name,\n payload,\n traceId: context.traceId ?? null,\n source: context.source ?? null,\n occurredAt,\n status: \"pending\",\n attempts: 0,\n availableAt: occurredAt,\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","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { Elysia } from \"elysia\";\nimport { websocket } from \"elysia/websocket\";\nimport { createLogger } from \"./logger\";\nimport { joinRoute, kebabCase, 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 {\n serializeSocketSchema,\n isSocketEnvelope,\n isSocketRoom,\n isSocketSeq,\n SOCKET_MAX_BYTES,\n SOCKET_BUFFER_BYTES,\n} from \"./socket-schema\";\nimport type {\n BrickSocketConfig,\n BrickSocketHandle,\n BrickSocketSchema,\n BrickSocketSender,\n SocketBroker,\n SocketBrokerMessage,\n SocketEmitArgs,\n SocketPayloads,\n SocketReplay,\n SocketSchemas,\n} from \"./socket-types\";\n\ninterface SocketSender {\n readonly isOpen: boolean;\n send(event: string, payload: unknown): void;\n close(): void;\n}\ninterface SocketSession {\n /** Server rooms, resolved from the handshake context. */\n rooms: readonly string[];\n open(socket: SocketSender): Promise<void>;\n message(event: string, data: unknown, socket: SocketSender): Promise<void>;\n join(room: string): Promise<boolean>;\n close(socket: SocketSender, code: number, reason: string): Promise<void>;\n}\nexport interface RegisteredSocket {\n schema: BrickSocketSchema;\n input: SocketSchemas;\n output: SocketSchemas;\n /** The errors its handlers declare, for the client contract. */\n errors?: Record<string, ActionErrorDefinition>;\n allowedOrigins?: readonly string[];\n allowMissingOrigin?: boolean;\n maxRooms: number;\n replay?: SocketReplay;\n /** Brokers of the apps this socket is mounted in. */\n brokers: Set<SocketBroker>;\n handle: BrickSocketHandle<any>;\n topicPrefix: string;\n topic(room: string): string;\n connect(request: Request): Promise<SocketSession>;\n}\n\nclass SocketDenied extends Error {}\n\nconst bytes = (value: string) => new TextEncoder().encode(value).byteLength;\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 = JSON.stringify({ event, data });\n if (bytes(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 (\n [...Object.keys(input), ...Object.keys(output)].some((key) =>\n key.startsWith(\"$\"),\n )\n )\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 topics = [\n ...new Set(typeof rooms === \"string\" ? [rooms] : rooms),\n ].map(topic);\n const frame = outputFrame(output, event, payload);\n // Room and sequence are added to each replayed frame on delivery.\n if (replay && bytes(frame) > SOCKET_MAX_BYTES - 300)\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\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\nconst TOKEN_PROTOCOL = \"brick.token.\";\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(TOKEN_PROTOCOL))\n ?.slice(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(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/** Mounts native adapters. 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, 22);\n const sign = (topic: string, seq: string) =>\n `${seq}.${signature(topic, seq)}`;\n const verify = (topic: string, signed: string) => {\n const [seq, sig] = signed.split(\".\") as [string, string];\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(JSON.stringify({ 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 /** A replayable emit carries its room and sequence. */\n const frameOf = (message: SocketBrokerMessage & { type: \"emit\" }) =>\n message.seq === undefined\n ? message.frame\n : `${message.frame.slice(0, -1)},\"room\":${JSON.stringify(roomOf(message.topic))},\"seq\":${JSON.stringify(sign(message.topic, message.seq))}}`;\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, \"$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 === \"$leave\") {\n if (connection.requested.has(topic)) exit(connection, topic);\n control(connection.ws, \"$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, \"$gap\", {\n room: name,\n seq: sign(topic, restart),\n });\n }\n }\n }\n // A kick while joining wins.\n control(connection.ws, \"$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 = buildErrorHelpers(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 ? 1008 : 1011,\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(\"brick.v1\")\n ? { \"Sec-WebSocket-Protocol\": \"brick.v1\" }\n : undefined,\n async open(ws) {\n const session = sessions.get(ws.request);\n if (!session) {\n ws.close(1011, \"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(1000, \"\");\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(1013, \"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(1003, \"Only JSON text is supported\");\n return;\n }\n if (typeof value === \"string\") {\n ws.close(1007, \"Expected JSON envelope\");\n return;\n }\n if (!isSocketEnvelope(value)) {\n ws.close(1008, \"Invalid socket envelope\");\n return;\n }\n const size = bytes(JSON.stringify(value));\n if (size > SOCKET_MAX_BYTES) {\n ws.close(1009, \"Message too large\");\n return;\n }\n if (state.pending >= 32 || state.bytes + size > SOCKET_BUFFER_BYTES) {\n ws.close(1013, \"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 (value.event === \"$join\" || value.event === \"$leave\")\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 !== \"$join\" &&\n value.event !== \"$leave\" &&\n Object.hasOwn(raisable, error.code)\n )\n try {\n const frame = JSON.stringify({\n event: \"$error\",\n data: {\n event: value.event,\n code: error.code,\n message: error.message,\n status: error.status,\n ...(error.details !== undefined\n ? { details: error.details }\n : {}),\n },\n });\n if (bytes(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 { publicOrigin } from \"./socket\";\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 { Elysia } from \"elysia\";\nimport {\n compileBrickApplication,\n type CompiledApplication,\n type RouteIR,\n} from \"./compiler\";\nimport type { Service } from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport {\n getPluginActionRoute,\n getPluginEndpoints,\n installedPlugins,\n} from \"./plugin\";\nimport {\n pluginLifecycle,\n setupAppPlugins,\n type PluginInstance,\n} from \"./define-plugin\";\nimport { 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 registerReferenceRoute,\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 type { SocketBroker } from \"./socket-types\";\nimport { corsHook, type CorsOptions } from \"./cors\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Generate specialized handlers once 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 (outside the JSON action mesh), 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\nexport {\n compileRoutePlan,\n executeCompiledRoute,\n createActionHandler,\n} from \"./action-handler\";\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 = options.prefix ?? options.compilation?.ir.prefix ?? \"/api\";\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const compiled = options.compiler !== false;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? \"/openapi.json\";\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 // Diagnostics & health\n app.get(\"/_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 const pluginOpts = requestLogging === true ? {} : requestLogging;\n if (pluginOpts.enabled !== false) {\n app.use(requestLoggingPlugin(pluginOpts));\n }\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 const settings = {\n path: referencePath,\n title: referenceOptions.title ?? title,\n specUrl: referenceOptions.specUrl ?? openApiPath,\n };\n if (compiled)\n app.get(\n settings.path,\n htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)),\n );\n else registerReferenceRoute(app, settings);\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 Error(`Brick: duplicate service \"${service.name}\" in brick()`);\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 // Precompute plans and freeze immutable plans across all services\n for (const service of services) {\n if (typeof (service as any).build === \"function\") {\n (service as any).build();\n }\n }\n\n // Raw endpoints declared via options or app.endpoint() (declaration order).\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 // OpenAPI 3.1 & Interactive Documentation Endpoints\n if (enableDocs) {\n app.get(\n openApiPath,\n compiled\n ? cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n )\n : buildSpec,\n );\n\n if (compiled) {\n app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n } else {\n app.get(docsPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(openApiPath, title);\n });\n\n app.get(swaggerPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return swaggerDocsHTML(openApiPath, title);\n });\n }\n }\n\n // Dedicated Route Registry\n const registeredRoutes = new Map<string, boolean>();\n const routeKey = (method: string, path: string) =>\n `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n registeredRoutes.set(routeKey(\"GET\", \"/_health\"), false);\n registeredRoutes.set(routeKey(\"GET\", \"/_brick/services\"), false);\n if (enableDocs) {\n for (const path of [openApiPath, docsPath, swaggerPath])\n registeredRoutes.set(routeKey(\"GET\", path), false);\n }\n if (referencePath !== undefined)\n registeredRoutes.set(routeKey(\"GET\", referencePath), false);\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 Error(`Brick: duplicate socket route '${socket.path}'`);\n socketRoutes.add(key);\n }\n const mountRoute = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n handler: any,\n plugin = false,\n ) => {\n const key = routeKey(method, path);\n if (socketRoutes.has(key))\n throw new Error(\n `Brick: route '${method} ${path}' conflicts with a socket`,\n );\n if (registeredRoutes.has(key)) {\n if (plugin || registeredRoutes.get(key))\n throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);\n return false;\n }\n switch (method) {\n case \"GET\":\n app.get(path, handler);\n break;\n case \"POST\":\n app.post(path, handler);\n break;\n case \"PUT\":\n app.put(path, handler);\n break;\n case \"PATCH\":\n app.patch(path, handler);\n break;\n case \"DELETE\":\n app.delete(path, handler);\n break;\n }\n registeredRoutes.set(key, plugin);\n return true;\n };\n\n // Raw endpoints (outside the JSON action mesh).\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.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 service = services.find(\n (candidate) => candidate.name === route.ir.service,\n )!;\n const action = service\n .listActions()\n .find((candidate) => candidate.name === route.ir.action)!;\n const invoke = (context: any) => {\n const result = telemetry\n ? withSpan(\n `action ${route.ir.service}.${route.ir.action}`,\n {\n \"brick.service\": route.ir.service,\n \"brick.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 getPluginActionRoute(action, prefix) !== undefined,\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 brickApp.listen = ((...args: Parameters<typeof listen>) => {\n lifecycle\n .start()\n .catch((error) =>\n console.error(\"[Brick-TS] A plugin failed to start:\", error),\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 getGlobalRegistry().setApplicationRoutes(definition);\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n app.get(\n \"/_brick/services\",\n compiled\n ? cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(definition),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n )\n : () => getGlobalRegistry().exportArchitecture(definition),\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":";;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAgB,UACd,QACA,SACA,UACQ;CACR,IAAI,OAAO,OAAO,QAAQ,OAAO,EAAE;CACnC,IAAI,YAAY,KAAA,GAAW,QAAQ,IAAI,UAAU,OAAO;CACxD,IAAI,aAAa,KAAA,GAAW,QAAQ,IAAI,UAAU,QAAQ;CAC1D,OAAO;AACT;;AAGA,SAAgB,UAAU,MAAc,MAAsB;CAC5D,OAAO,GAAG,OAAO,SAAS,MAAM,KAAK,UAAU;AAC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