@brickkit/core 0.13.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["sqliteTable","sqliteText","sqliteInteger","sqliteReal","pgText","pgInteger","pgBoolean","pgTimestamp","getTableName","getTableName","migratePostgres","getTableName","getTableColumns","sql","and","eq","getTableColumns","inArray"],"sources":["../src/plugin-hooks.ts","../src/plugin-tables.ts","../src/version.ts","../src/define-plugin.ts","../src/tool.ts","../src/db/sqlite.ts","../src/db/postgres.ts","../src/db/define.ts","../src/db/column.ts","../src/db/index.ts","../src/resource.ts","../src/service.ts","../src/socket-redis.ts","../src/rpc.ts","../src/events/emit.ts","../src/mcp.ts"],"sourcesContent":["import type { ActionContext } from \"./types\";\n\n/** Where `hooks.*` stores a plugin's hooks on its host; `@brickkit/crud` runs them. */\nexport const 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/** The arguments each host CRUD hook receives, by hook name. */\nexport interface PluginHookArgs<C = ActionContext> {\n beforeCreate: HookBase<C> & { data: Record<string, unknown> };\n afterCreate: HookBase<C> & { row: Record<string, unknown> };\n beforeUpdate: HookBase<C> & { id: unknown; data: Record<string, unknown> };\n afterUpdate: HookBase<C> & { id: unknown; row: Record<string, unknown> };\n beforeDelete: HookBase<C> & { id: unknown };\n afterDelete: HookBase<C> & { id: unknown };\n afterCommit: {\n operation: \"create\" | \"update\" | \"delete\";\n id: unknown;\n row?: Record<string, unknown>;\n ctx: C;\n };\n}\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 type PluginHooks<C = ActionContext> = {\n [K in keyof PluginHookArgs<C>]: (\n hook: (args: PluginHookArgs<C>[K]) => unknown,\n ) => void;\n};\n\nexport type HostHooks = {\n [K in keyof PluginHookArgs]?: ((args: PluginHookArgs[K]) => unknown)[];\n};\n\n// A record, so adding a hook to `PluginHookArgs` without listing it here fails to compile.\nconst HOOKS: Record<keyof PluginHookArgs, true> = {\n beforeCreate: true,\n afterCreate: true,\n beforeUpdate: true,\n afterUpdate: true,\n beforeDelete: true,\n afterDelete: true,\n afterCommit: true,\n};\nexport const HOOK_NAMES = Object.keys(HOOKS) as (keyof PluginHookArgs)[];\n\n/** The plugin hooks installed on a service or resource, by hook name. */\nexport function getHostHooks(host: object): HostHooks | undefined {\n return (host as Record<symbol, HostHooks | undefined>)[HOST_HOOKS];\n}\n\n/** Add hooks to a host, after those already there. */\nexport function addHostHooks(host: object, added: HostHooks): void {\n const store = ((host as Record<symbol, HostHooks>)[HOST_HOOKS] ??= {});\n for (const name of HOOK_NAMES)\n if (added[name])\n (store[name] ??= [] as never[]).push(...(added[name] as never[]));\n}\n","import {\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\";\n\nconst OWNER = Symbol.for(\"brickkit.plugin.owner\");\nexport function setPluginOwner(table: object, plugin: string): void {\n Object.defineProperty(table, OWNER, { value: plugin });\n}\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\nexport function 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","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\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","import { 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 type { DepsOf, Ports } from \"./deps\";\nimport { actionMeta } from \"./action-meta\";\nimport { portOf } from \"./service-port\";\nimport type { EventCatalog, EventRef, EventRefs } from \"./events/catalog\";\nimport type { EventListener } from \"./events/types\";\nimport { hasPlugin, validateName } from \"./plugin\";\nimport {\n PLUGIN_KIND,\n PLUGIN_COMMIT,\n type PluginRouteRegistrar,\n type ResourcePlugin,\n type ServicePlugin,\n} from \"./plugin-types\";\nimport {\n addHostHooks,\n HOOK_NAMES,\n type HostHooks,\n type PluginHooks,\n} from \"./plugin-hooks\";\nimport {\n builders,\n setPluginOwner,\n type PluginTableBuilders,\n} from \"./plugin-tables\";\nimport { brickVersion, satisfiesRange } from \"./version\";\nimport { INTERNALS, type Internals } from \"./plugin-app\";\nimport { definitionSite } from \"./definition-site\";\nimport type { SecretRef } from \"./secrets\";\nimport { validateWithSchema } from \"./typebox\";\nimport type { Action, 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\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.12.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\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.12.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 validateName(name);\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 const setup = (context: {\n service: Service<any, any>;\n resource?: Resource<any, any, any>;\n routes: PluginRouteRegistrar<any>;\n [PLUGIN_COMMIT]?: (commit: () => void) => void;\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 setPluginOwner(table, name);\n portOf(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 claim: (segment) => context.routes.claim(segment),\n };\n const before = new Set<unknown>([\n ...service.listActions(),\n ...service.listTools(),\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 // Every action and socket the setup added (its own, its resources', crud's) runs with the plugin's deps.\n for (const action of [...service.listActions(), ...service.listTools()])\n if (!before.has(action)) bindPluginDeps(name, action, deps, started);\n for (const socket of service.listSockets())\n if (!before.has(socket)) socket.deps ??= deps;\n\n context[PLUGIN_COMMIT]?.(() => {\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 portOf(service).addEvents(\n Object.fromEntries(\n Object.entries(events).map(([key, ref]) => [\n `${eventSpace}.${key}`,\n ref,\n ]),\n ),\n );\n addHostHooks(host, added as HostHooks);\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 [PLUGIN_KIND]: \"plugin\",\n name,\n info,\n setup,\n [INTERNALS]: internals,\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 * Run an action with the plugin's deps as `ctx.deps`: context resolution\n * reads them from its metadata. A nested definePlugin binds its own actions\n * 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: Action<any, any, any, any>,\n deps: Readonly<Record<string, unknown>>,\n started: number,\n) {\n const meta = actionMeta(action);\n if (meta.deps) {\n if (meta.deps.values === deps || meta.deps.at > started) return;\n throw new Error(\n `${plugin}: action \"${action.name}\" is already bound to the deps of another install; create the action inside the setup so each install gets its own`,\n );\n }\n meta.deps = { values: deps, at: ++bindings };\n}\n\n/** Check the deps passed at install against the ports the plugin declares. */\nfunction checkDeps(\n plugin: string,\n /** The plugin's factory as the user imports it (its camelCase name), for the hint. */\n camelName: 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: ${camelName}(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","import type { TSchema } from \"@sinclair/typebox\";\nimport { defineAction } from \"./action\";\nimport type {\n Tool,\n ToolConfigWithAuthorize,\n ToolConfigWithoutAuthorize,\n ActionErrorDefinition,\n ActionContext,\n} from \"./types\";\n\n/**\n * Define a tool: an action that AI agents can call through MCP. It takes the\n * same configuration as `defineAction` (validation, `authorize`, errors), plus\n * `title`, `annotations` (the MCP hints about what the tool does), and `http`\n * to also serve it over HTTP and in OpenAPI (off by default).\n *\n * @param config - An action configuration and tool options. `input` must be an\n * object schema, since MCP passes arguments by name.\n * @returns The tool, which is also an action. Register it with `service.tool(tool)`.\n * @throws When `input` is not an object schema.\n * @example\n * import { defineTool, t } from \"@brickkit/core\";\n *\n * export const echoTool = defineTool({\n * name: \"echo\",\n * title: \"Echo a message\",\n * description: \"Returns the message it is given.\",\n * input: t.Object({ message: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `Echo: ${input.message}`,\n * });\n */\nexport function defineTool<\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: ToolConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineTool<\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: ToolConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineTool(config: any): any {\n if (config.input && config.input.type !== \"object\") {\n throw new Error(`Tool '${config.name}' input must be an object schema`);\n }\n const tool = defineAction(config);\n Object.defineProperty(tool, \"kind\", { value: \"tool\" });\n return tool;\n}\n\n/**\n * Whether a value was made with `defineTool`, as opposed to `defineAction`.\n *\n * @param value - Anything.\n * @returns `true` for a tool, narrowing its type.\n */\nexport function isTool(value: unknown): value is Tool<any, any, any, any> {\n return typeof value === \"function\" && (value as Tool).kind === \"tool\";\n}\n","import type { Database } from \"bun:sqlite\";\nimport type { BunSQLiteDatabase } from \"drizzle-orm/bun-sqlite\";\n\nimport { createRequire } from \"node:module\";\n\nconst requireSQLite = createRequire(import.meta.url);\n\nexport type { BunSQLiteDatabase } from \"drizzle-orm/bun-sqlite\";\n\nexport {\n sqliteTable,\n text,\n integer,\n real,\n blob,\n index,\n uniqueIndex,\n primaryKey,\n foreignKey,\n} from \"drizzle-orm/sqlite-core\";\n\nexport interface SQLiteDatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Database file path or ':memory:' (default: ':memory:') */\n path?: string;\n /** Alias for path */\n filename?: string;\n /** Whether to enable WAL journal mode for file-based DBs (default: true) */\n wal?: boolean;\n /** Whether to enforce foreign key constraints (default: true) */\n foreignKeys?: boolean;\n /** Optional existing bun:sqlite Database instance */\n client?: Database;\n /** Optional Drizzle schema object for typed relational queries */\n schema?: TSchema;\n}\n\nexport type BrickSQLiteDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = BunSQLiteDatabase<TSchema> & {\n $client: Database;\n};\n\n/**\n * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine\n * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).\n *\n * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on\n * other runtimes (e.g. Node) stays safe until this function is actually\n * called.\n */\nexport function createSQLiteDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(config: SQLiteDatabaseConfig<TSchema> = {}): BunSQLiteDatabase<TSchema> {\n let Database: new (path: string) => Database;\n let drizzle: (\n client: Database,\n config?: { schema?: TSchema },\n ) => BunSQLiteDatabase<TSchema>;\n try {\n ({ Database } = requireSQLite(\"bun:sqlite\"));\n // Keep the adapter lazy for Node imports, but visible to Bun's bundler.\n ({ drizzle } = require(\"drizzle-orm/bun-sqlite\"));\n } catch (err: any) {\n throw new Error(\n `[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`,\n );\n }\n const filePath = config.filename ?? config.path ?? \":memory:\";\n const client = config.client ?? new Database(filePath);\n\n if (config.foreignKeys !== false) {\n client.run(\"PRAGMA foreign_keys = ON;\");\n }\n\n if (config.wal !== false && filePath !== \":memory:\") {\n client.run(\"PRAGMA journal_mode = WAL;\");\n }\n\n const db = (\n config.schema ? drizzle(client, { schema: config.schema }) : drizzle(client)\n ) as BunSQLiteDatabase<TSchema>;\n\n if (!(db as any).$client) {\n (db as any).$client = client;\n }\n\n return db;\n}\n","import postgres, { type Sql } from \"postgres\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\n\nexport interface PostgresDatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */\n client?: Sql;\n /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */\n url?: string;\n /** Connection string alias */\n connectionString?: string;\n host?: string;\n port?: number;\n user?: string;\n password?: string;\n database?: string;\n ssl?: boolean | \"require\" | \"allow\" | \"prefer\" | \"verify-full\";\n max?: number;\n /**\n * Disable prepared statements (required for transaction-mode poolers such\n * as Supabase's Supavisor on :6543, which cannot hold named prepared\n * statements across transactions).\n */\n prepare?: boolean;\n /** Optional Drizzle schema for relational queries */\n schema?: TSchema;\n /** Custom schema name for Encore-style isolated schemas */\n schemaName?: string;\n}\n\nexport type PostgresDatabase<\n _TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = any;\n\n/**\n * Creates a PostgreSQL Drizzle instance using postgres-js.\n * Static imports so bundlers (Nitro/Rollup) trace and ship the driver.\n * `bun:sqlite` stays lazy in `sqlite.ts` since it only exists under Bun.\n */\nexport function createPostgresDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(config: PostgresDatabaseConfig<TSchema> = {}): PostgresDatabase<TSchema> {\n const connectionUrl =\n config.url ??\n config.connectionString ??\n (typeof process !== \"undefined\" ? process.env?.DATABASE_URL : undefined);\n\n const client =\n config.client ??\n (connectionUrl\n ? postgres(connectionUrl, {\n max: config.max,\n prepare: config.prepare,\n ssl: config.ssl,\n })\n : postgres({\n host: config.host ?? \"localhost\",\n port: config.port ?? 5432,\n user: config.user,\n password: config.password,\n database: config.database,\n max: config.max,\n prepare: config.prepare,\n ssl: config.ssl,\n }));\n\n return drizzle(client, {\n schema: config.schema,\n ...(config.schemaName ? { schemaFilter: [config.schemaName] } : {}),\n });\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { type Table, getTableName } from \"drizzle-orm\";\nimport type { PostgresJsDatabase } from \"drizzle-orm/postgres-js\";\nimport type { Sql } from \"postgres\";\nimport { SecretRef } from \"../secrets\";\nimport {\n createSQLiteDatabase,\n type SQLiteDatabaseConfig,\n type BunSQLiteDatabase,\n type BrickSQLiteDatabase,\n} from \"./sqlite\";\nimport {\n createPostgresDatabase,\n type PostgresDatabaseConfig,\n} from \"./postgres\";\n\nexport type EnvInput<T> = T | SecretRef<T>;\ntype EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>> };\n\ninterface DefinitionOptions<TSchema extends Record<string, unknown>> {\n name?: string;\n /** Drizzle tables retained for schema tooling. Never applied at runtime. */\n tables?: (TSchema & Record<string, Table>) | readonly Table[];\n schema?: TSchema;\n}\n\nexport type SQLiteDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = DefinitionOptions<TSchema> &\n EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, \"schema\" | \"client\">> & {\n engine?: \"sqlite\";\n client?: SQLiteDatabaseConfig<TSchema>[\"client\"];\n url?: never;\n connectionString?: never;\n };\n\nexport type PostgresDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = DefinitionOptions<TSchema> &\n EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, \"schema\" | \"client\">> & {\n engine: \"postgres\";\n path?: never;\n filename?: never;\n wal?: never;\n foreignKeys?: never;\n client?: PostgresDatabaseConfig<TSchema>[\"client\"];\n };\n\nexport type DatabaseDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;\n\nexport interface DatabaseHandle<\n TDb,\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n readonly kind: \"brick-database\";\n readonly name?: string;\n readonly engine: \"sqlite\" | \"postgres\";\n readonly tables: Readonly<Record<string, Table>>;\n readonly schema: TSchema;\n /**\n * Add a table after definition, as `definePlugin` does for the tables a\n * plugin owns. Before `getDb()` it also joins the relational schema.\n */\n addTable?(key: string, table: Table): void;\n getDb(): TDb;\n close?(): void | Promise<void>;\n}\n\n/**\n * Whether a value is a database handle made by `defineDatabase`.\n *\n * @param value - Anything.\n * @returns `true` for a handle, narrowing its type.\n */\nexport function isDatabaseHandle(\n value: unknown,\n): value is DatabaseHandle<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n value.kind === \"brick-database\"\n );\n}\n\n/**\n * Declare a service's database: its engine, its Drizzle tables, and how to\n * reach it. Nothing connects until the handle is used (`getDb()`), so defining\n * one has no side effects.\n *\n * SQLite is the default and needs no options. Pass `engine: \"postgres\"` with a\n * `url` for Postgres. Options that belong to the other engine (such as `url` for\n * SQLite, or `path` for Postgres) are refused.\n *\n * @param options - `engine` (`\"sqlite\"` or `\"postgres\"`), `tables`, an optional\n * `name`, and the engine's connection settings.\n * @returns A handle to give to `defineService({ database })`. `getDb()` returns\n * the Drizzle database.\n * @throws When the engine is unsupported, or an option does not suit the engine.\n * @example\n * import { defineDatabase } from \"@brickkit/core\";\n * import { sqliteTable, text } from \"drizzle-orm/sqlite-core\";\n *\n * const pages = sqliteTable(\"pages\", {\n * id: text(\"id\").primaryKey(),\n * title: text(\"title\").notNull(),\n * });\n *\n * export const database = defineDatabase({ tables: { pages } });\n */\nexport function defineDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n options?: SQLiteDefinition<TSchema>,\n): DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema>;\nexport function defineDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n options: PostgresDefinition<TSchema>,\n): DatabaseHandle<PostgresJsDatabase<TSchema> & { $client: Sql }, TSchema>;\nexport function defineDatabase(\n options: DatabaseDefinition = {},\n): DatabaseHandle<unknown> {\n const engine = options.engine ?? \"sqlite\";\n if (engine !== \"sqlite\" && engine !== \"postgres\") {\n throw new Error(`Unsupported database engine: ${engine}`);\n }\n const forbidden =\n engine === \"sqlite\"\n ? [\n \"url\",\n \"connectionString\",\n \"host\",\n \"port\",\n \"user\",\n \"password\",\n \"database\",\n \"ssl\",\n \"max\",\n \"prepare\",\n \"schemaName\",\n ]\n : [\"path\", \"filename\", \"wal\", \"foreignKeys\"];\n for (const key of forbidden) {\n if (key in options)\n throw new Error(`Database option \"${key}\" is not valid for ${engine}`);\n }\n const declared = options.tables ?? {};\n const tables: Record<string, Table> = Array.isArray(declared)\n ? Object.fromEntries(declared.map((table) => [getTableName(table), table]))\n : { ...declared };\n const schema = options.schema ?? tables;\n let frozen = Object.freeze({ ...tables });\n let db: unknown;\n let closeClient: (() => void | Promise<void>) | undefined;\n let closed = false;\n let closing: void | Promise<void>;\n\n return {\n kind: \"brick-database\",\n name: options.name,\n engine,\n get tables() {\n return frozen;\n },\n schema,\n addTable(key, table) {\n const name = getTableName(table);\n if (\n Object.hasOwn(tables, key) ||\n Object.values(tables).some((item) => getTableName(item) === name)\n )\n throw new Error(\n `Database already has a table \"${key}\" or one named \"${name}\"`,\n );\n // Also joins `schema` when that is `tables` itself (no `schema` given).\n tables[key] = table;\n frozen = Object.freeze({ ...tables });\n },\n close() {\n if (closed) return closing;\n closed = true;\n closing = closeClient?.();\n return closing;\n },\n getDb() {\n if (closed) throw new Error(\"Brick database handle is closed\");\n if (db !== undefined) return db;\n const config: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(options)) {\n if ([\"tables\", \"schema\", \"name\", \"engine\"].includes(key)) continue;\n // An injected Postgres client already owns all connection settings.\n if (\n engine === \"postgres\" &&\n options.client &&\n key !== \"client\" &&\n key !== \"schemaName\"\n )\n continue;\n config[key] = value instanceof SecretRef ? value.require() : value;\n }\n if (engine === \"sqlite\") {\n const path = (config.filename ?? config.path ?? \":memory:\") as string;\n if (!config.client && path !== \":memory:\")\n mkdirSync(dirname(path), { recursive: true });\n const instance = createSQLiteDatabase({ ...config, schema });\n db = instance;\n if (!options.client)\n closeClient = () => (instance as BrickSQLiteDatabase).$client.close();\n } else {\n const instance: PostgresJsDatabase & { $client: Sql } =\n createPostgresDatabase({ ...config, schema });\n db = instance;\n if (!options.client) closeClient = () => instance.$client.end();\n }\n return db;\n },\n };\n}\n","import type { Column } from \"drizzle-orm\";\n\n/**\n * A JSON value as its column stores it: an ISO string becomes a Date for a date\n * column, an integer string a BigInt for a bigint column. Other values pass\n * through.\n *\n * @returns `undefined` when the string can't be a value of the column.\n */\nexport function columnValue(column: Column, value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n if (column.dataType === \"date\") {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? undefined : date;\n }\n if (column.dataType === \"bigint\")\n return /^-?\\d+$/.test(value) ? BigInt(value) : undefined;\n return value;\n}\n","import type { Service } from \"../types\";\nimport type { DatabaseHandle } from \"./define\";\nimport { getTableColumns, getTableName, sql, type Table } from \"drizzle-orm\";\nimport { getTableConfig, isPgEnum, pgSchema } from \"drizzle-orm/pg-core\";\nimport { migrate as migratePostgres } from \"drizzle-orm/postgres-js/migrator\";\nimport { migrate as migrateSQLite } from \"drizzle-orm/bun-sqlite/migrator\";\n\nexport * from \"./sqlite\";\nexport * from \"./postgres\";\nexport * from \"./define\";\nexport { columnValue } from \"./column\";\n\nexport {\n sql,\n eq,\n ne,\n gt,\n gte,\n lt,\n lte,\n and,\n or,\n not,\n desc,\n asc,\n inArray,\n notInArray,\n isNull,\n isNotNull,\n like,\n ilike,\n relations,\n getTableColumns,\n getTableName,\n Table,\n is,\n} from \"drizzle-orm\";\n\n/**\n * Apply the migrations in a folder that have not run yet, in order, and record\n * them in the database's `__drizzle_migrations` table. The folder is the one\n * `brick db generate` (or drizzle-kit) writes: `<out>/<database name>`.\n *\n * @param database - A handle from `defineDatabase`.\n * @param migrationsFolder - The folder holding `meta/_journal.json`.\n * @example\n * await migrateDatabase(database, \"./drizzle/pages\");\n */\nexport async function migrateDatabase(\n database: DatabaseHandle<unknown>,\n migrationsFolder: string,\n): Promise<void> {\n const db = database.getDb() as any;\n if (database.engine === \"postgres\")\n await migratePostgres(db, { migrationsFolder });\n else migrateSQLite(db, { migrationsFolder });\n}\n\n/** Attach a defined database. Schema changes remain the caller's responsibility. */\nexport function attachDatabase<TDb>(\n service: Service<TDb, any>,\n database: DatabaseHandle<TDb>,\n): TDb {\n service.setDb(database);\n return database.getDb();\n}\n\n/**\n * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition\n * directly from a Drizzle table schema.\n */\nexport function generateSQLiteTableDdl(table: any): string {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colDefs: string[] = [];\n\n for (const [, col] of Object.entries(columns) as [string, any][]) {\n let def = `\"${col.name}\" ${col.getSQLType().toUpperCase()}`;\n if (col.primary) def += \" PRIMARY KEY\";\n if (col.notNull) def += \" NOT NULL\";\n if (col.isUnique) def += \" UNIQUE\";\n if (col.hasDefault) {\n if (typeof col.default === \"string\") {\n def += ` DEFAULT '${col.default.replace(/'/g, \"''\")}'`;\n } else if (typeof col.default === \"boolean\") {\n def += ` DEFAULT ${col.default ? 1 : 0}`;\n } else if (typeof col.default === \"number\") {\n def += ` DEFAULT ${col.default}`;\n } else if (col.default !== undefined) {\n def += ` DEFAULT ${col.default}`;\n }\n }\n colDefs.push(def);\n }\n\n return `CREATE TABLE IF NOT EXISTS \"${tableName}\" (\\n ${colDefs.join(\",\\n \")}\\n);`;\n}\n\n/**\n * Generates idempotent secondary index DDL for a Drizzle table.\n * Covers owner scoping, sort columns, and exact-match filters.\n * UNIQUE columns already carry an implicit index — skipped here.\n * FTS/trigram indexes are handled separately by the search layer.\n */\nexport function generateSQLiteIndexDdl(\n table: any,\n opts: { ownerField?: string; sortFields?: string[] } = {},\n): string[] {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const stmts: string[] = [];\n const seen = new Set<string>();\n const push = (name: string, cols: string[]) => {\n const clean = cols.filter(Boolean);\n if (clean.length === 0) return;\n const key = `${name}(${clean.join(\",\")})`;\n if (seen.has(key)) return;\n seen.add(key);\n const colList = clean.map((c) => `\"${c}\"`).join(\", \");\n stmts.push(\n `CREATE INDEX IF NOT EXISTS \"${name}\" ON \"${tableName}\" (${colList});`,\n );\n };\n\n const colNameOf = (field: string): string | undefined => {\n if ((columns as any)[field]) return (columns as any)[field].name ?? field;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === field) return col.name;\n }\n return undefined;\n };\n\n // Owner scope index: WHERE user_id = ? (+ sort composite below).\n let ownerCol: string | undefined;\n if (opts.ownerField) {\n const oc = colNameOf(opts.ownerField);\n if (oc) {\n ownerCol = oc;\n push(`idx_${tableName}_${oc}`, [oc]);\n }\n }\n\n // Sort column indexes (updated_at / created_at drive default ORDER BY).\n const sorts = opts.sortFields ?? [\"updated_at\", \"created_at\"];\n const sortCols: string[] = [];\n for (const f of sorts) {\n const c = colNameOf(f);\n if (c) {\n sortCols.push(c);\n push(`idx_${tableName}_${c}`, [c]);\n }\n }\n\n // Composite owner+sort — the hot path for scoped sorted lists.\n if (ownerCol && sortCols.length > 0) {\n push(`idx_${tableName}_${ownerCol}_${sortCols[0]}`, [\n ownerCol,\n sortCols[0],\n ]);\n }\n\n return stmts;\n}\n\n/**\n * Ensures secondary indexes exist for a resource table.\n * SQLite: B-tree indexes for owner scope + sort + composite hot path.\n * Postgres: same B-trees plus pg_trgm GIN indexes for substring search,\n * created one after another (each GIN index needs the extension).\n * Best-effort: a failed statement warns and the rest still run (e.g. a\n * read-only replica, or no right to create pg_trgm); queries still work, only\n * slower. On SQLite every statement has run when it returns.\n */\nexport async function ensureResourceIndexes(\n db: any,\n table: any,\n opts: {\n ownerField?: string;\n sortFields?: string[];\n searchFields?: string[];\n } = {},\n): Promise<void> {\n if (!db) return;\n const isPostgres =\n typeof (db as any).execute === \"function\" && !(db as any).$client?.run;\n const stmts = generateSQLiteIndexDdl(table, opts);\n if (isPostgres && opts.searchFields && opts.searchFields.length > 0) {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colNameOf = (f: string): string | undefined => {\n if ((columns as any)[f]) return (columns as any)[f].name ?? f;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === f) return col.name;\n }\n return undefined;\n };\n for (const f of opts.searchFields) {\n const c = colNameOf(f);\n if (c) {\n stmts.push(\n `CREATE INDEX IF NOT EXISTS \"idx_${tableName}_${c}_trgm\" ON \"${tableName}\" USING gin (\"${c}\" gin_trgm_ops);`,\n );\n }\n }\n }\n if (stmts.length === 0) return;\n if (isPostgres) stmts.unshift(`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);\n for (const stmt of stmts) {\n try {\n if ((db as any).$client?.run) (db as any).$client.run(stmt);\n else if (isPostgres) await (db as any).execute(sql.raw(stmt));\n else (db as any).run?.(stmt);\n } catch (error) {\n console.warn(\n `[Brick-TS DB] Skipped an index: ${stmt} (${error instanceof Error ? error.message : String(error)})`,\n );\n }\n }\n}\n\n/**\n * SQLite FTS5 search layer for resource list (?search=).\n * B-tree indexes cannot serve LIKE '%term%' (leading wildcard forces a full\n * scan). FTS5 gives indexed substring/prefix search on title/slug-scale text.\n * Postgres uses ilike + pg_trgm GIN indexes instead (see ensureResourceIndexes).\n */\n\nfunction ftsTableName(table: any): string {\n return `${getTableName(table)}_fts`;\n}\n\nfunction quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.\n * Idempotent; safe to call on every resource registration.\n * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.\n */\nexport function ensureSQLiteFts(\n db: any,\n table: any,\n searchCols: string[],\n): void {\n if (!db || searchCols.length === 0) return;\n // SQLite only: Postgres has execute() but no $client.run.\n const client = (db as any).$client;\n const runRaw = (db as any).run;\n if (!client?.run && !runRaw) return;\n const run = (stmt: string) => {\n if (client?.run) client.run(stmt);\n else runRaw(stmt);\n };\n try {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colNameOf = (f: string): string | undefined => {\n if ((columns as any)[f]) return (columns as any)[f].name ?? f;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === f) return col.name;\n }\n return undefined;\n };\n // Resolve to DB column names, drop unknowns.\n const dbCols = searchCols.map(colNameOf).filter((c): c is string => !!c);\n if (dbCols.length === 0) return;\n const idCol =\n colNameOf(\"id\") ??\n (Object.values(columns) as any[]).find((c) => c.primary)?.name ??\n \"id\";\n const fts = ftsTableName(table);\n const ftsCols = [\n `\"id\" UNINDEXED`,\n ...dbCols.map((c) => quoteIdent(c)),\n ].join(\", \");\n run(\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${quoteIdent(fts)} USING fts5(${ftsCols}, tokenize='porter');`,\n );\n const colList = dbCols.map(quoteIdent).join(\", \");\n const newVals = dbCols.map((c) => `new.${quoteIdent(c)}`).join(\", \");\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ai`)} AFTER INSERT ON ${quoteIdent(tableName)} BEGIN INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`,\n );\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ad`)} AFTER DELETE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE \"id\" = old.${quoteIdent(idCol)}; END;`,\n );\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_au`)} AFTER UPDATE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE \"id\" = old.${quoteIdent(idCol)}; INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`,\n );\n // Backfill rows predating the FTS table (dedupe via NOT IN).\n run(\n `INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) SELECT ${quoteIdent(idCol)}, ${colList} FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(idCol)} NOT IN (SELECT \"id\" FROM ${quoteIdent(fts)});`,\n );\n } catch (error) {\n // Best effort, as for indexes: search without FTS still works, but say why it is missing.\n console.warn(\n `[Brick-TS DB] Skipped full-text search for ${getTableName(table)}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/**\n * Builds an FTS5 MATCH condition for a resource search term.\n * Returns null when the term has no usable tokens or FTS errors.\n * Caller falls back to LIKE in that case.\n */\nexport function buildFtsMatchQuery(search: string): string | null {\n const terms = search\n .split(/\\s+/)\n .map((s) => s.trim())\n .filter(Boolean)\n .slice(0, 10);\n if (terms.length === 0) return null;\n const escaped = terms\n .map((term) => {\n const clean = term.replace(/\"/g, \"\").trim();\n if (!clean) return null;\n return `\"${clean.replace(/\"/g, '\"\"')}\"*`;\n })\n .filter((x): x is string => !!x);\n if (escaped.length === 0) return null;\n return escaped.join(\" AND \");\n}\n\n/**\n * The schema drizzle-kit reads: the tables, plus the Postgres schemas\n * (namespaces) and enums they use, which drizzle-kit only creates when handed.\n *\n * @param tables - Drizzle tables, all of one engine.\n * @returns A record to pass to drizzle-kit's API (`pushSchema`, `generateDrizzleJson`).\n */\nexport function drizzleSchema(\n tables: readonly Table[],\n): Record<string, unknown> {\n const schema: Record<string, unknown> = {};\n for (const table of tables) {\n // What getTableConfig(table).schema reads, for tables of any engine.\n const namespace = (table as any)[Symbol.for(\"drizzle:Schema\")] as\n | string\n | undefined;\n schema[`table:${namespace ?? \"public\"}.${getTableName(table)}`] = table;\n if (namespace && namespace !== \"public\")\n schema[`schema:${namespace}`] = pgSchema(namespace);\n for (const column of Object.values(getTableColumns(table)) as any[])\n if (isPgEnum(column.enum))\n schema[`enum:${column.enum.enumName}`] = column.enum;\n }\n return schema;\n}\n\n/** drizzle-kit's programmatic API, an optional peer dependency. */\nasync function loadDrizzleKit(): Promise<typeof import(\"drizzle-kit/api\")> {\n // A variable specifier keeps `brick build` from bundling drizzle-kit (and\n // every driver it can load) into the app server.\n const specifier = \"drizzle-kit/api\";\n let kit: typeof import(\"drizzle-kit/api\");\n try {\n kit = await import(specifier);\n } catch (err: any) {\n throw new Error(\n `[Brick-TS DB] Postgres schema tools need drizzle-kit: run \\`bun add -d drizzle-kit\\`, or use \\`brick db push\\`. (${err?.message ?? err})`,\n );\n }\n // drizzle-kit assigns helpers to built-in prototypes when imported\n // (Array.prototype.random, String.prototype.camelCase, ...). Hide them from\n // for...in loops in this process, which break Elysia's AOT compiler among others.\n for (const proto of [\n Object.prototype,\n Array.prototype,\n String.prototype,\n Function.prototype,\n ])\n for (const key of Reflect.ownKeys(proto))\n if (Object.getOwnPropertyDescriptor(proto, key)?.enumerable)\n Object.defineProperty(proto, key, { enumerable: false });\n return kit;\n}\n\n/**\n * Create the declared tables that do not exist yet. A development and test\n * helper: never called by services, resources or server startup, and never\n * changes a table that exists. Use `brick db generate` / `brick db migrate`\n * for production schema changes.\n *\n * SQLite: `CREATE TABLE IF NOT EXISTS` per table, synchronously.\n * Postgres: drizzle-kit (an optional peer dependency) writes the DDL for the\n * missing tables, their enums, indexes and foreign keys, applied in one\n * transaction. Returns a promise to await.\n */\nexport function syncSchema(\n tablesOrService: Map<string, any> | any[] | Record<string, any> | Service,\n dbInstance?: any,\n): Promise<void> | void {\n let db = dbInstance;\n let tables: any[] = [];\n\n if (\n tablesOrService &&\n typeof (tablesOrService as any).listActions === \"function\" &&\n (tablesOrService as any).tables\n ) {\n const service = tablesOrService as Service;\n tables = Array.from(service.tables.values());\n if (!db) {\n db = service.getDb();\n }\n } else if (tablesOrService instanceof Map) {\n tables = Array.from(tablesOrService.values());\n } else if (Array.isArray(tablesOrService)) {\n tables = tablesOrService;\n } else if (tablesOrService && typeof tablesOrService === \"object\") {\n tables = Object.values(tablesOrService);\n }\n\n if (!db || tables.length === 0) return;\n\n if ((db as any).$client?.run || (db as any).run) {\n for (const table of tables) {\n try {\n const ddl = generateSQLiteTableDdl(table);\n if ((db as any).$client?.run) {\n (db as any).$client.run(ddl);\n } else if ((db as any).run) {\n (db as any).run(sql.raw(ddl));\n }\n } catch (err: any) {\n console.warn(`[Brick-TS DB] Failed to create table:`, err.message);\n }\n }\n return;\n }\n\n return createMissingPostgresTables(db, tables);\n}\n\nasync function createMissingPostgresTables(\n db: any,\n tables: Table[],\n): Promise<void> {\n const kit = await loadDrizzleKit();\n const rows: { schema: string; name: string }[] = await db.execute(\n sql`select table_schema as schema, table_name as name from information_schema.tables`,\n );\n const present = new Set(rows.map((row) => `${row.schema}.${row.name}`));\n const existing = tables.filter((table) => {\n const { schema = \"public\", name } = getTableConfig(table as any);\n return present.has(`${schema}.${name}`);\n });\n if (existing.length === tables.length) return;\n // Diff the tables that exist against all of them: only the missing tables\n // (and what only they use) come out, as CREATE statements.\n const before = drizzleSchema(existing);\n const after = drizzleSchema(tables);\n // A namespace may exist without any of these tables: don't create it again.\n const namespaces: { name: string }[] = await db.execute(\n sql`select schema_name as name from information_schema.schemata`,\n );\n for (const { name } of namespaces)\n if (after[`schema:${name}`])\n before[`schema:${name}`] = after[`schema:${name}`];\n // Likewise an enum that exists while only missing tables use it.\n const enums: { schema: string; name: string }[] = await db.execute(\n sql`select n.nspname as schema, t.typname as name from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typtype = 'e'`,\n );\n for (const { schema, name } of enums) {\n const pgEnumValue = after[`enum:${name}`] as any;\n if (pgEnumValue && (pgEnumValue.schema ?? \"public\") === schema)\n before[`enum:${name}`] = pgEnumValue;\n }\n const statements = await kit.generateMigration(\n kit.generateDrizzleJson(before),\n kit.generateDrizzleJson(after),\n );\n await db.transaction(async (tx: any) => {\n for (const statement of statements) await tx.execute(sql.raw(statement));\n });\n}\n","import { and, eq, getTableColumns, inArray, type Column } from \"drizzle-orm\";\nimport type { TObject, TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport { installPlugin, segmentClaimant } from \"./plugin\";\nimport { columnValue } from \"./db/column\";\nimport type { ResourcePlugin } from \"./plugin-types\";\nimport { buildErrorHelpers, defineAction } from \"./action\";\nimport { kebabCase } from \"./kebab\";\nimport { actionMeta, type ResourceActionInfo } from \"./action-meta\";\nimport { portOf } from \"./service-port\";\nimport { Type } from \"./typebox\";\nimport { runInTransaction } from \"./events/transaction\";\nimport { checkPayload, crudEventSource, type EventRef } from \"./events/catalog\";\nimport {\n ActionExecutionError,\n DuplicateNameError,\n type ActionContext,\n type ActionErrorDefinition,\n type CommandConfig,\n type CommandDecision,\n type Resource,\n type ResourceActionAccess,\n type ResourceActionConfig,\n type ResourceChild,\n type ResourceConfig,\n type ResourceTypeOptions,\n type ResourceIdentity,\n type Service,\n} from \"./types\";\n\n/**\n * Load the row a record action (or command) works on, through its `access`.\n *\n * @returns The row, or `undefined` when it is missing or hidden.\n * @throws When `access` is missing.\n */\nexport async function loadRecord(\n resource: Resource<any, any, any>,\n args: {\n id: unknown;\n ctx: any;\n db?: any;\n access?: ResourceActionAccess;\n },\n): Promise<Record<string, unknown> | undefined> {\n if (!args.access)\n throw new Error(\n `Resource '${resource.name}' has no access rule for loading records: set \\`access\\` on the record action`,\n );\n const db = args.db ?? args.ctx?.db;\n // An id its column can't hold names no row.\n const id = columnValue(resource.id, args.id);\n if (id === undefined) return undefined;\n if (!db) throw new Error(\"Record actions require a configured database\");\n const scope =\n args.access === \"public\"\n ? undefined\n : await args.access.scope({ ctx: args.ctx });\n const [row] = await db\n .select()\n .from(resource.table)\n .where(and(scope, eq(resource.id, id)))\n .limit(1);\n return row;\n}\n\n/** Startup check: a record action needs its own `access`. */\nexport function checkRecordAccess(\n resource: Resource<any, any, any>,\n info: ResourceActionInfo,\n): void {\n const name = `${resource.name}.${info.name}`;\n if (info.access === undefined)\n throw new Error(\n `Record action '${name}' needs \\`access\\` (\"public\" or { scope })`,\n );\n}\n\nfunction notFound(\n resource: Resource<any, any, any>,\n id: unknown,\n error: { NOT_FOUND(message: string): never },\n): never {\n error.NOT_FOUND(`${resource.name} '${String(id)}' not found`);\n}\n\n/** The schema of a resource's `:id`. */\nexport function idSchema(column: Column): TSchema {\n return column.dataType === \"number\" ? Type.Number() : Type.String();\n}\n\nfunction defineResourceAction(\n service: Service<any, any>,\n resource: Resource<any, any, any>,\n config: ResourceActionConfig<any, any, any, any, any, boolean>,\n /** A command's body: it loads the row itself, in its transaction. */\n command?: (args: { input: any; ctx: any; error: any }) => Promise<unknown>,\n) {\n const { record = false, access, execute, ...rest } = config;\n if (!config.name || /[./]/.test(config.name))\n throw new Error(`Invalid resource action name '${config.name}'`);\n const name = `${resource.name}.${config.name}`;\n const segment = kebabCase(config.name);\n // A plugin route on this resource (crud's `/count`) owns its first segment.\n const claimant = segmentClaimant(service, resource, segment);\n if (claimant)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${name}\" in service \"${service.name}\": \"${segment}\" is a ${claimant} route`,\n );\n const existing = service.getAction(name);\n if (existing && actionMeta(existing).route)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${name}\" in service \"${service.name}\"`,\n );\n if (!record && access !== undefined)\n throw new Error(`Only record actions take \\`access\\` ('${name}')`);\n if (record && config.path !== undefined && !/\\/:id(\\/|$)/.test(config.path))\n throw new Error(`Record action '${name}' needs ':id' in its path`);\n let input = config.input as TSchema | undefined;\n if (record) {\n const own = input as TObject | undefined;\n if (own && own.type !== \"object\")\n throw new Error(`Record action '${name}' input must be an object`);\n input = Type.Object(\n { ...own?.properties, id: idSchema(resource.id) },\n own?.additionalProperties === undefined\n ? {}\n : { additionalProperties: own.additionalProperties },\n );\n }\n const action = defineAction({\n ...rest,\n name,\n input,\n execute: async ({ input, ctx, error }: any) => {\n if (command) return command({ input, ctx, error });\n const row = record\n ? await loadRecord(resource, { id: input.id, ctx, access })\n : undefined;\n if (record && row === undefined) notFound(resource, input.id, error);\n return execute({ input, ctx, error, row } as any);\n },\n } as any);\n const info: ResourceActionInfo = {\n resource: resource.name,\n name: config.name,\n record,\n ...(access === undefined ? {} : { access }),\n };\n actionMeta(action).resourceAction = info;\n service.action(action);\n return action;\n}\n\nfunction primaryColumn(table: unknown): [string, Column] | undefined {\n const primary = Object.entries(\n getTableColumns(table as Parameters<typeof getTableColumns>[0]),\n ).filter(([, column]) => column.primary);\n return primary.length === 1 ? primary[0] : undefined;\n}\n\nfunction fieldOf(table: unknown, column: Column): string | undefined {\n return Object.entries(\n getTableColumns(table as Parameters<typeof getTableColumns>[0]),\n ).find(([, own]) => own === column)?.[0];\n}\n\ninterface ChildInfo {\n table: any;\n parent: Column;\n parentField: string;\n id: Column;\n idField: string;\n}\n\nfunction childInfo(\n resource: Resource<any, any, any>,\n name: string,\n where: string,\n): ChildInfo {\n const child = (\n resource.config as { children?: Record<string, ResourceChild> }\n ).children?.[name];\n if (!child || !Object.hasOwn(resource.config.children ?? {}, name))\n throw new Error(\n `${where}: resource '${resource.name}' has no child table '${name}'`,\n );\n const parentField = fieldOf(child.table, child.parent);\n const id = child.id ?? primaryColumn(child.table)?.[1];\n const idField = id && fieldOf(child.table, id);\n if (!parentField || !id || !idField)\n throw new Error(\n `Resource '${resource.name}' child '${name}' needs a parent column and an id column of its table`,\n );\n return { table: child.table, parent: child.parent, parentField, id, idField };\n}\n\n/** The `error` helpers of `decide`: they return the rejection, not throw it. */\nfunction commandErrors(errors?: Record<string, ActionErrorDefinition>) {\n const throwing = buildErrorHelpers(errors) as Record<\n string,\n (message?: string, details?: unknown) => never\n >;\n return Object.fromEntries(\n Object.entries(throwing).map(([code, helper]) => [\n code,\n (message?: string, details?: unknown) => {\n try {\n helper(message, details);\n } catch (rejection) {\n return rejection;\n }\n },\n ]),\n );\n}\n\nfunction defineCommand(\n service: Service<any, any>,\n resource: Resource<any, any, any>,\n name: string,\n config: CommandConfig<any, any, any, any, any, any, any, readonly string[]>,\n) {\n const where = `Command '${resource.name}.${name}'`;\n if (typeof config.decide !== \"function\")\n throw new Error(`${where} needs a decide function`);\n const loaded = (config.load?.children ?? []).map((child) => ({\n name: child,\n ...childInfo(resource, child, where),\n }));\n const error = commandErrors(config.errors);\n const decide = (row: any, input: any) =>\n config.decide(row, input, { error } as any);\n const events = service.events as Record<string, EventRef>;\n\n const run = async ({\n input,\n ctx,\n error: helpers,\n }: {\n input: any;\n ctx: any;\n error: any;\n }) => {\n const db = ctx.db;\n if (!db) throw new Error(`${where} requires a configured database`);\n const recorder = service.recorder;\n const body = async (\n tx: any,\n record?: (name: string, payload: unknown) => Promise<void>,\n ) => {\n const row = await loadRecord(resource, {\n id: input.id,\n ctx,\n db: tx,\n access: config.access,\n });\n if (row === undefined) notFound(resource, input.id, helpers);\n const id = row[resource.idField];\n for (const child of loaded)\n row[child.name] = await tx\n .select()\n .from(child.table)\n .where(eq(child.parent, id));\n\n const decision = decide(row, input);\n if (decision instanceof ActionExecutionError) throw decision;\n const { set, children, emit } = (decision ?? {}) as CommandDecision<\n any,\n Record<string, unknown>\n >;\n // Every event is checked before anything is written.\n const emits = Object.entries(emit ?? {})\n .filter(([, payload]) => payload !== undefined)\n .map(([key, payload]) => {\n const ref = Object.hasOwn(events, key) ? events[key] : undefined;\n if (!ref)\n throw new Error(\n `${where} emits '${key}', which is not in the event catalog of service '${service.name}'`,\n );\n checkPayload(ref, payload);\n return [ref.name, payload] as const;\n });\n if (emits.length && !record)\n throw new Error(\n `${where} emits events, but service '${service.name}' records none: give its database an outbox table and the app \\`events\\``,\n );\n\n if (set && Object.keys(set).length)\n await tx.update(resource.table).set(set).where(eq(resource.id, id));\n for (const [childName, changes] of Object.entries(children ?? {})) {\n if (!changes) continue;\n const child = childInfo(resource, childName, where);\n const own = eq(child.parent, id);\n if (changes.insert?.length)\n await tx.insert(child.table).values(\n changes.insert.map((item) => ({\n ...item,\n [child.parentField]: id,\n })),\n );\n for (const item of changes.update ?? []) {\n const { [child.idField]: childId, ...values } = item as Record<\n string,\n unknown\n >;\n if (childId === undefined)\n throw new Error(\n `${where}: an update of child '${childName}' needs its '${child.idField}'`,\n );\n if (Object.keys(values).length)\n await tx\n .update(child.table)\n .set(values)\n .where(and(eq(child.id, childId), own));\n }\n if (changes.delete?.length)\n await tx\n .delete(child.table)\n .where(and(inArray(child.id, changes.delete), own));\n }\n for (const [eventName, payload] of emits)\n await record!(eventName, payload);\n\n if (!config.output) return { id };\n const [updated] = await tx\n .select()\n .from(resource.table)\n .where(eq(resource.id, id))\n .limit(1);\n for (const child of loaded)\n updated[child.name] = await tx\n .select()\n .from(child.table)\n .where(eq(child.parent, id));\n return Value.Clean(config.output, updated);\n };\n return recorder\n ? recorder.transaction(\n db,\n {\n traceId: ctx.traceId,\n source: crudEventSource(service.name, resource.name),\n },\n body,\n )\n : runInTransaction(db, (tx) => body(tx));\n };\n\n const action = defineResourceAction(\n service,\n resource,\n {\n name,\n record: true,\n description: config.description,\n tags: config.tags,\n input: config.input,\n output: config.output ?? Type.Object({ id: idSchema(resource.id) }),\n errors: config.errors,\n ...(config.access === undefined ? {} : { access: config.access }),\n ...(config.authorize ? { authorize: config.authorize } : {}),\n execute: () => undefined,\n } as ResourceActionConfig<any, any, any, any, any, boolean>,\n run,\n );\n Object.assign(action, { decide });\n return action;\n}\n\n/** Declares a resource: a plugin host over a table, with its own `action()` and `command()`. */\nexport function defineResource<\n TTable = any,\n TCtx extends ActionContext = ActionContext,\n const O extends ResourceTypeOptions = ResourceTypeOptions,\n>(\n service: Service<any, any>,\n config: ResourceConfig<TTable, TCtx> & O,\n): Resource<TTable, TCtx, ResourceIdentity<TTable, O>> {\n const columns = getTableColumns(\n config.table as Parameters<typeof getTableColumns>[0],\n );\n const id: Column | undefined = config.id ?? primaryColumn(config.table)?.[1];\n const entry = Object.entries(columns).find(([, column]) => column === id);\n if (!entry || !id)\n throw new Error(\n `Resource '${config.name}' requires an id column belonging to its table`,\n );\n if (\n !config.name ||\n config.name.includes(\"/\") ||\n [\"__proto__\", \"constructor\", \"prototype\"].includes(config.name)\n )\n throw new Error(`Invalid resource name '${config.name}'`);\n portOf(service).registerTable(config.table);\n const resource = {\n name: config.name,\n serviceName: service.name,\n table: config.table,\n id,\n idField: entry[0],\n config: Object.freeze({ ...config, id }),\n use(plugin: ResourcePlugin<any, any, any>) {\n return installPlugin(\n service,\n resource as unknown as Resource<\n TTable,\n TCtx,\n ResourceIdentity<TTable, O>\n >,\n plugin,\n );\n },\n action(\n actionConfig: ResourceActionConfig<any, any, any, any, any, boolean>,\n ) {\n return defineResourceAction(\n service,\n resource as unknown as Resource<any, any, any>,\n actionConfig,\n );\n },\n command(name: string, commandConfig: CommandConfig<any, any, any, any>) {\n return defineCommand(\n service,\n resource as unknown as Resource<any, any, any>,\n name,\n commandConfig as CommandConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n readonly string[]\n >,\n );\n },\n };\n return resource as unknown as Resource<\n TTable,\n TCtx,\n ResourceIdentity<TTable, O>\n >;\n}\n","import { installPlugin, isInstallingPlugin } from \"./plugin\";\nimport type { ServicePlugin } from \"./plugin-types\";\nimport type { BunSQLiteDatabase } from \"./db/sqlite\";\nimport type {\n Service,\n ServiceOptions,\n Action,\n Tool,\n ActionErrorDefinition,\n ServiceSchema,\n BaseContext,\n Resource,\n PreparationContribution,\n} from \"./types\";\nimport { defineTool, isTool } from \"./tool\";\nimport { defineAction } from \"./action\";\nimport { claimName, definitionSite } from \"./definition-site\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getTableName, isDatabaseHandle, type DatabaseHandle } from \"./db\";\nimport { checkRecordAccess, defineResource } from \"./resource\";\nimport { actionMeta } from \"./action-meta\";\nimport { actionOwners } from \"./routes\";\nimport type { ServicePort } from \"./service-port\";\nimport { isOutboxTable, type OutboxTable } from \"./events/outbox\";\nimport type { ServiceEvents } from \"./events/types\";\nimport {\n checkEvent,\n eventRefs,\n type EventCatalog,\n type EventRef,\n} from \"./events/catalog\";\nimport { getActionAccess } from \"./access\";\nimport { pluginOwner } from \"./plugin-tables\";\nimport { baseContext, pickContextEnvelope } from \"./context\";\nimport type { DepsOf, Ports } from \"./deps\";\nimport type { NamedService } from \"./rpc\";\nimport { defineServiceSocket } from \"./socket\";\nimport type {\n BrickSocketConfig,\n BrickSocketHandle,\n SocketPayloads,\n SocketSchemas,\n RegisteredSocket,\n} from \"./socket-types\";\n\n// Symbol to tie context resolution to a specific service instance and invocation\nconst RESOLVED_SYMBOL = Symbol(\"resolved\");\n/** The deps a resolved context was resolved with, to restore them when a plugin's copy comes back. */\nconst OWN_DEPS = Symbol(\"ownDeps\");\n\n// The public overloads of `action`, `tool` and `resource`; the class implements them once, untyped.\n// Safe: the interface only adds signatures of methods the class defines.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\nexport interface ServiceImpl<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> extends Pick<Service<TDb, TServiceContext>, \"action\" | \"tool\" | \"resource\"> {}\nexport class ServiceImpl<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> implements ServicePort<TDb, TServiceContext> {\n readonly name: string;\n readonly options: ServiceOptions<TServiceContext, TDb>;\n private readonly actions = new Map<string, Action<any, any, any, any>>();\n private readonly tools = new Map<string, Tool<any, any, any, any>>();\n readonly tables = new Map<string, any>();\n private readonly sockets = new Map<string, RegisteredSocket>();\n private readonly resources = new Map<\n string,\n Resource<any, BaseContext<TDb> & TServiceContext>\n >();\n private readonly preparations = new Map<string, PreparationContribution>();\n /** Where each `kind:name` was defined, to reject duplicates from another file. */\n private readonly sites = new Map<string, string | undefined>();\n private database?: DatabaseHandle<TDb>;\n private _isBuilt = false;\n private _events: Readonly<Record<string, EventRef>>;\n /** What a write needs to record events. Set by `brick({ events })`. */\n recorder?: ServiceEvents;\n /** The values of this service's `deps`. Set by `brick({ deps })`. */\n deps?: Readonly<Record<string, unknown>>;\n\n constructor(\n name: string,\n options: ServiceOptions<TServiceContext, TDb> = {},\n ) {\n this.name = name;\n this.options = options;\n this._events = eventRefs(name, options.events);\n for (const key of Object.keys(this._events)) this.claim(\"event\", key);\n if (options.database !== undefined && !isDatabaseHandle(options.database)) {\n throw new Error(\"Service database must be created with defineDatabase()\");\n }\n this.database = options.database;\n }\n\n /** The declared events: `service.events.<name>`. */\n get events(): Readonly<Record<string, EventRef>> {\n return this._events;\n }\n\n use<A>(plugin: ServicePlugin<this, A>): A {\n return installPlugin(this, undefined, plugin) as A;\n }\n\n get db(): TDb | undefined {\n return this.getDb();\n }\n\n get isBuilt(): boolean {\n return this._isBuilt;\n }\n\n /** Every definition change passes here, so cached architecture and OpenAPI are rebuilt. */\n touch(): void {\n getGlobalRegistry().touch();\n }\n\n snapshot(): () => void {\n const maps = [\n this.actions,\n this.tools,\n this.tables,\n this.sockets,\n this.resources,\n this.preparations,\n this.sites,\n ] as Map<unknown, unknown>[];\n const saved = maps.map((map) => new Map(map));\n const events = this._events;\n const properties = new Map(\n [...this.resources.values()].map((item) => [\n item,\n Object.getOwnPropertyDescriptors(item),\n ]),\n );\n return () => {\n maps.forEach((map, index) => {\n map.clear();\n for (const [key, value] of saved[index]!) map.set(key, value);\n });\n this._events = events;\n for (const [item, own] of properties) {\n for (const key of Reflect.ownKeys(item))\n if (!Object.hasOwn(own, key)) Reflect.deleteProperty(item, key);\n Object.defineProperties(item, own);\n }\n this.touch();\n };\n }\n\n addEvents(refs: Readonly<Record<string, EventRef>>): void {\n this._events = Object.freeze({ ...this._events, ...refs });\n this.touch();\n }\n\n /**\n * Closes declarations after plugins have registered their actions and preparations.\n */\n build(): this {\n if (isInstallingPlugin(this))\n throw new Error(\"Cannot build a service during plugin setup\");\n if (this._isBuilt) return this;\n for (const action of this.actions.values()) {\n const info = actionMeta(action).resourceAction;\n const resource = info?.record && this.resources.get(info.resource);\n if (resource) checkRecordAccess(resource, info);\n }\n this._isBuilt = true;\n return this;\n }\n\n private claim(kind: string, name: string): void {\n claimName(\n this.sites,\n `${kind} \"${name}\" in service \"${this.name}\"`,\n `${kind}:${name}`,\n definitionSite(),\n );\n }\n\n contributePreparation(contribution: PreparationContribution): void {\n if (this._isBuilt)\n throw new Error(\"Preparations must be registered before service build\");\n if (this.preparations.has(contribution.name))\n throw new Error(`Duplicate preparation '${contribution.name}'`);\n this.preparations.set(contribution.name, contribution);\n this.touch();\n }\n\n listPreparations(): PreparationContribution[] {\n return [...this.preparations.values()];\n }\n prepareContributions(): void {\n for (const contribution of this.preparations.values())\n contribution.prepare();\n }\n\n registerTable(table: any): this {\n this.tables.set(getTableName(table), table);\n this.touch();\n return this;\n }\n\n resource(config: any): any {\n if (this._isBuilt)\n throw new Error(\"Resources must be registered before service build\");\n this.claim(\"resource\", config.name);\n const resourceInstance = defineResource(this, config);\n this.resources.set(resourceInstance.name, resourceInstance as any);\n this.touch();\n return resourceInstance;\n }\n\n getResource(\n name: string,\n ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined {\n return this.resources.get(name);\n }\n\n listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[] {\n return Array.from(this.resources.values());\n }\n\n action(actionOrConfig: any): any {\n const isActionFunction =\n typeof actionOrConfig === \"function\" && \"config\" in actionOrConfig;\n const actionInstance: Action<any, any, any, any> = isActionFunction\n ? actionOrConfig\n : defineAction(actionOrConfig);\n\n if (this.actions.get(actionInstance.name) !== actionInstance)\n this.claim(\"action\", actionInstance.name);\n if (isTool(actionInstance)) actionInstance.config.http = true;\n actionInstance.serviceName = this.name;\n actionMeta(actionInstance).service = this;\n this.actions.set(actionInstance.name, actionInstance);\n this.touch();\n return isActionFunction ? this : actionInstance;\n }\n\n tool(toolOrConfig: any): any {\n const existing = isTool(toolOrConfig);\n const tool = existing ? toolOrConfig : defineTool(toolOrConfig);\n this.claim(\"tool\", tool.name);\n tool.serviceName = this.name;\n actionMeta(tool).service = this;\n this.tools.set(tool.name, tool);\n if (tool.config.http) this.action(tool);\n this.touch();\n return existing ? this : tool;\n }\n\n getTool(name: string): Tool<any, any, any, any> | undefined {\n return this.tools.get(name);\n }\n\n socket<\n const I extends SocketSchemas,\n const O extends SocketSchemas,\n const E extends Record<string, ActionErrorDefinition> = {},\n >(\n config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext, E>,\n ): BrickSocketHandle<SocketPayloads<O>> {\n if (this._isBuilt)\n throw new Error(\"Sockets must be declared before service build\");\n this.claim(\"socket\", config.name);\n const socket: RegisteredSocket = defineServiceSocket(\n this.name,\n config,\n (request) => resolveServiceContext(this, { request }, socket.deps),\n );\n this.sockets.set(config.name, socket);\n this.touch();\n return socket.handle;\n }\n\n listSockets(): RegisteredSocket[] {\n return [...this.sockets.values()];\n }\n\n listTools(): Tool<any, any, any, any>[] {\n return Array.from(this.tools.values());\n }\n\n getAction(name: string): Action<any, any, any, any> | undefined {\n return this.actions.get(name);\n }\n\n listActions(): Action<any, any, any, any>[] {\n return Array.from(new Set(this.actions.values()));\n }\n\n getDb(): TDb | undefined {\n return this.database?.getDb();\n }\n\n /** The handle from `defineDatabase`, without connecting. */\n getDatabaseHandle(): DatabaseHandle<TDb> | undefined {\n return this.database;\n }\n\n getOutbox(): OutboxTable | undefined {\n return Object.values(this.database?.tables ?? {}).find(isOutboxTable);\n }\n\n setRecorder(recorder: ServiceEvents | undefined): void {\n this.recorder = recorder;\n }\n\n get hasCatalog(): boolean {\n return this.options.events !== undefined;\n }\n\n /** @throws When the event is not in the catalog or its payload does not match. */\n checkEvent(name: string, payload: unknown): void {\n checkEvent(this, name, payload);\n }\n\n setDeps(deps: Readonly<Record<string, unknown>>): void {\n this.deps = deps;\n }\n\n setDb(database: DatabaseHandle<TDb>): void {\n if (!isDatabaseHandle(database))\n throw new Error(\"Use defineDatabase() to set a service database\");\n this.database = database;\n this.touch();\n }\n\n /**\n * Resolves the complete service execution context once per incoming request.\n * Merges framework BaseContext with the service's custom context hook.\n * Always rebuilds context for this service to prevent caller context from overriding.\n */\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n pluginDeps?: Readonly<Record<string, unknown>>,\n ): Promise<BaseContext<TDb> & TServiceContext> {\n return resolveServiceContext(this, callCtx, pluginDeps);\n }\n\n introspect(): ServiceSchema {\n const databaseConfig = this.database\n ? {\n name: this.database.name,\n engine: this.database.engine,\n tables: Object.keys(this.database.tables),\n ...pluginTables(this.database.tables),\n }\n : undefined;\n // The schema is data. A function among the options (such as `context`)\n // cannot cross to the dev dashboard: structured clone\n // refuses the whole architecture. JSON keeps the data and drops the rest.\n const { database: _database, events: _events, ...config } = this.options;\n const options: ServiceSchema[\"options\"] = JSON.parse(\n JSON.stringify(config),\n );\n return {\n name: this.name,\n options,\n hasDatabase: Boolean(this.database),\n sockets: this.listSockets().map((socket) => socket.schema),\n databaseConfig,\n actions: this.listActions().map((act) => {\n const access = getActionAccess(act);\n return {\n name: act.name,\n serviceName: this.name,\n ...actionOwners(act),\n description: act.config.description,\n inputSchema: act.config.input,\n outputSchema: act.config.output,\n hasAuthorize: access.hasAuthorize,\n hasScope: access.hasScope,\n accessPolicy: access.policy,\n errors: act.config.errors,\n emits: act.config.emits,\n tags: act.config.tags,\n };\n }),\n tools: this.listTools().map((tool) => ({ name: tool.name })),\n ...(this.hasCatalog || Object.keys(this.events).length\n ? {\n events: Object.values(this.events).map((ref) => ({\n name: ref.name,\n schema: JSON.parse(JSON.stringify(ref.schema)),\n ...(ref.plugin ? { plugin: ref.plugin } : {}),\n })),\n }\n : {}),\n resources: this.listResources().map((res) => ({\n name: res.name,\n })),\n };\n }\n}\n\n/** `plugins`: which plugin owns each table it contributed, by table key. */\nfunction pluginTables(tables: Record<string, unknown>) {\n const owners = Object.entries(tables).flatMap(([key, table]) => {\n const plugin = pluginOwner(table);\n return plugin ? [[key, plugin] as const] : [];\n });\n return owners.length ? { plugins: Object.fromEntries(owners) } : {};\n}\n\n/**\n * The context of a call to one of the service's actions or sockets. The one\n * rule for which deps it sees: those of the plugin install that created the\n * action or socket (`pluginDeps`), else the service's own. The service's\n * `context` hook always sees the service's own.\n */\nasync function resolveServiceContext<\n TDb,\n TServiceContext extends Record<string, any>,\n>(\n service: ServiceImpl<TDb, TServiceContext>,\n callCtx?: Partial<BaseContext<TDb>> & { user?: unknown },\n pluginDeps?: Readonly<Record<string, unknown>>,\n): Promise<BaseContext<TDb> & TServiceContext> {\n // Only a context this service resolved itself is accepted as it is.\n if ((callCtx as any)?.[RESOLVED_SYMBOL] === service) {\n const deps = pluginDeps ?? (callCtx as any)[OWN_DEPS];\n return (\n (callCtx as { deps?: unknown }).deps === deps\n ? callCtx\n : { ...callCtx, deps }\n ) as BaseContext<TDb> & TServiceContext;\n }\n const framework = baseContext({\n request: callCtx?.request,\n // Always this service's own database, never the caller's.\n db: service.getDb(),\n logger: callCtx?.logger,\n traceId: callCtx?.traceId,\n requestId: callCtx?.requestId,\n services: callCtx?.services,\n metadata: callCtx?.metadata,\n // The app's deps for this service; a direct call with no app (a unit test) may pass its own,\n // but never those of a context another service (or a plugin) resolved.\n deps:\n service.deps ??\n ((callCtx as any)?.[RESOLVED_SYMBOL]\n ? undefined\n : (callCtx as { deps?: Readonly<Record<string, unknown>> } | undefined)\n ?.deps),\n });\n const fullBaseCtx: BaseContext<TDb> = {\n ...framework,\n ...pickContextEnvelope(callCtx),\n };\n\n const resolvedExtra = service.options.context\n ? await service.options.context(fullBaseCtx)\n : {};\n const finalCtx: any = {\n ...fullBaseCtx,\n ...resolvedExtra,\n deps: pluginDeps ?? framework.deps,\n [RESOLVED_SYMBOL]: service,\n [OWN_DEPS]: framework.deps,\n };\n return finalCtx;\n}\n\n/**\n * Declare a service: a named group of actions, tools, and resources with its own\n * database and request context. It is registered globally, so `brick()`, the\n * OpenAPI generator, and `useService` find it by name.\n *\n * Add actions with `service.action(...)`, tools with `service.tool(...)`,\n * resources with `service.resource(...)`, and plugins with `service.use(...)`.\n *\n * @param name - Unique name. It is the service's segment of every action route\n * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it\n * again from the same file (a dev reload) replaces it; from another file throws.\n * @param options - `database` (a handle from `defineDatabase`), `deps` (typed\n * slots from `port<T>()` that `brick({ deps })` fills, read as `ctx.deps`),\n * `context` (adds fields such as the signed-in user to every action's `ctx`),\n * `events` (the event catalog: a payload schema per event name, recorded as\n * `<service>.<name>` and offered as `service.events.<name>`).\n * @returns The service.\n * @example\n * import { defineDatabase, defineService, t } from \"@brickkit/core\";\n *\n * const database = defineDatabase({ tables: { pages } });\n *\n * export const pagesService = defineService(\"pages\", {\n * database,\n * // Added to `ctx` in every action of this service.\n * context: async ({ request }) => ({ user: await readUser(request) }),\n * });\n *\n * pagesService.action({\n * name: \"list\",\n * input: t.Object({ limit: t.Optional(t.Number()) }),\n * output: t.Array(t.Object({ id: t.String(), title: t.String() })),\n * execute: ({ input, ctx }) =>\n * ctx.db.select().from(pages).limit(input.limit ?? 20),\n * });\n */\nexport function defineService<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n const TEvents extends EventCatalog = {},\n const TName extends string = string,\n TPorts extends Ports = {},\n>(\n name: TName,\n options?: ServiceOptions<TServiceContext, TDb> & {\n events?: TEvents;\n deps?: TPorts;\n },\n): Service<\n TDb,\n {} extends TPorts\n ? TServiceContext\n : TServiceContext & { deps: DepsOf<TPorts> },\n TEvents\n> &\n NamedService<TName> {\n const service = new ServiceImpl<TDb, TServiceContext>(name, options);\n getGlobalRegistry().register(service as any);\n return service as any;\n}\n","import { compareSocketSeq } from \"./protocol\";\nimport type { SocketBroker, SocketBrokerMessage } from \"./socket-types\";\n\n// From the global, as @types/bun doesn't export RedisClient from \"bun\" for the .d.ts build.\ntype RedisClient = InstanceType<typeof Bun.RedisClient>;\n\nexport interface RedisBrokerOptions {\n /** Defaults to `REDIS_URL`, then `redis://localhost:6379`. */\n url?: string;\n /** Emits held while Redis is unreachable; older ones are dropped. Default 1000. */\n queue?: number;\n}\n\n/** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */\nexport function reconnectDelay(failures: number): number {\n const ceiling = Math.min(30_000, 500 * 2 ** failures);\n return ceiling / 2 + Math.random() * (ceiling / 2);\n}\n\n/** How long a call waits for Redis to connect before going on without it. */\nconst REDIS_WAIT_MS = 1000;\n\n/** One Redis connection that reconnects by itself and reports each fresh connection. */\nexport function connection(\n url: string | undefined,\n connected: (redis: RedisClient) => void,\n) {\n let redis: RedisClient | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let failures = 0;\n const waiters: (() => void)[] = [];\n const lost = (client: RedisClient) => {\n if (redis !== client) return;\n redis = undefined;\n if (closed || timer) return;\n timer = setTimeout(() => {\n timer = undefined;\n start();\n }, reconnectDelay(failures++));\n };\n const start = () => {\n if (closed || redis || timer) return;\n // Bun's own reconnect keeps no subscriptions we can see; a fresh client resubscribes explicitly.\n const client = new Bun.RedisClient(url, {\n autoReconnect: false,\n enableOfflineQueue: false,\n });\n redis = client;\n client.onclose = () => lost(client);\n client.connect().then(\n () => {\n if (redis !== client) return;\n failures = 0;\n connected(client);\n for (const wake of waiters.splice(0)) wake();\n },\n () => lost(client),\n );\n };\n return {\n get(): RedisClient | undefined {\n start();\n return redis?.connected ? redis : undefined;\n },\n /** Resolves after the next connection is made and announced, or after `ms`. */\n opened(ms: number): Promise<void> {\n if (redis?.connected) return Promise.resolve();\n start();\n return new Promise((resolve) => {\n const timeout = setTimeout(resolve, ms);\n waiters.push(() => {\n clearTimeout(timeout);\n resolve();\n });\n });\n },\n close() {\n closed = true;\n clearTimeout(timer);\n for (const wake of waiters.splice(0)) wake();\n const client = redis;\n redis = undefined;\n client?.close();\n },\n };\n}\n\n/**\n * Fans socket emits and kicks out across processes through Redis pub/sub, one\n * channel per room topic. An emit is a PUBLISH only: every process, the emitting\n * one included, delivers it once to its own connections. Uses Bun's built-in\n * Redis client and two connections, one to publish and one to subscribe.\n */\nexport function redisBroker(options: RedisBrokerOptions = {}): SocketBroker {\n const limit = options.queue ?? 1000;\n if (!Number.isInteger(limit) || limit < 0)\n throw new Error(\"redisBroker queue must be a nonnegative integer\");\n const channel = (topic: string) => `brick:socket:${topic}`;\n const listeners = new Map<\n string,\n Set<(message: SocketBrokerMessage) => void>\n >();\n const pending = new Map<string, Promise<unknown>>();\n const stream = (topic: string) => `brick:socket:stream:${topic}`;\n // Failures stay non-fatal (an emit is best effort) but leave a trace, once per kind.\n const warned = new Set<string>();\n const warn = (what: string) => (error: unknown) => {\n if (warned.has(what)) return;\n warned.add(what);\n console.warn(\n `[Brick-TS] Redis socket broker: ${what} failed; later failures of it are not logged.`,\n error,\n );\n };\n const queue: ((redis: RedisClient) => void)[] = [];\n const send = (work: (redis: RedisClient) => void) => {\n const redis = publisher.get();\n if (redis) return work(redis);\n queue.push(work);\n if (queue.length > limit) queue.shift();\n };\n const receive = (payload: string, name: string) => {\n let message: SocketBrokerMessage;\n try {\n message = JSON.parse(payload);\n } catch {\n return;\n }\n for (const deliver of listeners.get(name) ?? []) deliver(message);\n };\n const subscribe = (redis: RedisClient, name: string) => {\n const done = redis.subscribe(name, receive).catch(warn(\"SUBSCRIBE\"));\n pending.set(name, done);\n void done.then(() => {\n if (pending.get(name) === done) pending.delete(name);\n });\n };\n const publisher = connection(options.url, (redis) => {\n for (const work of queue.splice(0)) work(redis);\n });\n const subscriber = connection(options.url, (redis) => {\n for (const name of listeners.keys()) subscribe(redis, name);\n });\n return {\n publish(message, replay) {\n const name = channel(message.topic);\n if (message.type !== \"emit\" || !replay)\n return send(\n (redis) =>\n void redis\n .publish(name, JSON.stringify(message))\n .catch(warn(\"PUBLISH\")),\n );\n const key = stream(message.topic);\n send((redis) => {\n // Replies come back in order, so each PUBLISH follows its XADD in emit order.\n void redis\n .send(\"XADD\", [\n key,\n \"MAXLEN\",\n \"~\",\n String(replay.keep),\n \"*\",\n \"m\",\n message.frame,\n ])\n .then((seq: string) => {\n void redis\n .send(\"PEXPIRE\", [key, String(replay.maxAgeMs)])\n .catch(warn(\"PEXPIRE\"));\n return redis.publish(name, JSON.stringify({ ...message, seq }));\n })\n .catch(warn(\"XADD/PUBLISH\"));\n });\n },\n async head() {\n try {\n await publisher.opened(REDIS_WAIT_MS);\n const [seconds, micros] = (await publisher.get()!.send(\"TIME\", [])) as [\n string,\n string,\n ];\n return `${Number(seconds) * 1000 + Math.floor(Number(micros) / 1000) - 1}-0`;\n } catch {\n return `${Date.now() - 1}-0`;\n }\n },\n async history(topic, since, replay) {\n let raw: [string, string[]][];\n try {\n await publisher.opened(REDIS_WAIT_MS);\n raw = await publisher.get()!.send(\"XRANGE\", [stream(topic), \"-\", \"+\"]);\n } catch {\n return undefined;\n }\n const ms = (seq: string) => Number(seq.split(\"-\")[0]);\n const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);\n // Nothing kept at or before `since`: entries after it may have been trimmed or expired.\n if (\n after.length === raw.length &&\n (raw.length >= replay.keep ||\n (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)\n )\n return undefined;\n return after.map(([seq, fields]) => ({\n type: \"emit\" as const,\n topic,\n frame: fields[fields.indexOf(\"m\") + 1]!,\n seq,\n }));\n },\n subscribe(topic, deliver) {\n const name = channel(topic);\n let local = listeners.get(name);\n if (!local) {\n local = new Set();\n listeners.set(name, local);\n const redis = subscriber.get();\n if (redis) subscribe(redis, name);\n }\n local.add(deliver);\n return () => {\n local.delete(deliver);\n if (local.size || listeners.get(name) !== local) return;\n listeners.delete(name);\n pending.delete(name);\n void subscriber.get()?.unsubscribe(name).catch(warn(\"UNSUBSCRIBE\"));\n };\n },\n async ready(topic) {\n const name = channel(topic);\n // Wait briefly for Redis, so a join is acknowledged once its emits can arrive.\n if (!pending.has(name)) await subscriber.opened(REDIS_WAIT_MS);\n await pending.get(name);\n },\n close() {\n publisher.close();\n subscriber.close();\n },\n };\n}\n","import { ATTR, SPAN } from \"./telemetry-names\";\nimport type { Action, ActionContext, ProxyOptions, Service } from \"./types\";\nimport type {\n BrickClientAction,\n BrickClientSocket,\n BrickServices,\n InferActionInput,\n InferActionOutput,\n} from \"./client\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getPluginActionRoute } from \"./routes\";\nimport { pickContextEnvelope } from \"./context\";\nimport { withCallSpan } from \"./telemetry\";\n\n/** An in-process caller for one action: its input, then an optional call context. */\nexport type ServiceActionCaller<A> =\n undefined extends InferActionInput<A>\n ? (\n input?: InferActionInput<A>,\n ctx?: Partial<ActionContext>,\n ) => Promise<InferActionOutput<A>>\n : (\n input: InferActionInput<A>,\n ctx?: Partial<ActionContext>,\n ) => Promise<InferActionOutput<A>>;\n\n/**\n * What `useService` returns: the service's actions as methods, with each\n * resource's actions under the resource's name. Sockets are left out.\n */\nexport type ServiceClient<T> = {\n [\n K in keyof T as T[K] extends BrickClientSocket<any, any> ? never : K\n ]: T[K] extends\n | BrickClientAction<any, any, any>\n | Action<any, any, any, any>\n | ((...args: any[]) => any)\n ? ServiceActionCaller<T[K]>\n : ServiceClient<T[K]>;\n};\n\ndeclare const serviceNameType: unique symbol;\n\n/** Type only: the literal name of a service, which `useService` finds its contract by. */\nexport interface NamedService<N extends string> {\n readonly [serviceNameType]?: N;\n}\n\n/** What `useService` returns while the contract does not describe the service yet. */\nexport type UntypedServiceClient = { [name: string]: any };\n\n/**\n * Call another service's actions in-process, typed from that service. Each\n * action is a method, and each resource's actions sit under the resource's\n * name: `billing.charge(input)`, `billing.invoice.list()`.\n *\n * The types come from the app's generated contract (`_brick/contract.ts`, which\n * `brick dev` and `brick gen client` keep current), so renaming an action or\n * changing its input is a compile error at every caller. Until the contract\n * describes the service, the client is untyped.\n *\n * A call runs through the target's own validation and authorization, with the\n * target's database, context and deps (never the caller's), and shows as an\n * `rpc` span in the trace.\n *\n * @param service - The service to call, as `defineService` returned it.\n * @param options - `from` (the calling service's name, which becomes `ctx.caller`\n * in the target and cannot be spoofed) and `context` (defaults for every call).\n * Each call also takes an optional call context after its input.\n * @returns The client.\n * @throws On a call, when the service is not registered or has no such action.\n * @example\n * import { useService } from \"@brickkit/core\";\n * import { billingService } from \"../billing/billing.service\";\n *\n * const billing = useService(billingService, { from: \"orders\" });\n * await billing.charge({ orderId, amountCents });\n * await billing.invoice.list({ limit: 10 });\n */\nexport function useService<const N extends string = string>(\n service: { readonly name: string } & NamedService<N>,\n options: ProxyOptions = {},\n): N extends keyof BrickServices\n ? ServiceClient<BrickServices[N]>\n : UntypedServiceClient {\n return serviceRef(service.name, options, []);\n}\n\nfunction serviceRef(\n serviceName: string,\n options: ProxyOptions,\n path: readonly string[],\n): any {\n return new Proxy(function () {}, {\n get(_, key) {\n // Only string keys name actions; `then` stays unset so the client is not a promise.\n if (typeof key !== \"string\" || key === \"then\") return undefined;\n return serviceRef(serviceName, options, [...path, key]);\n },\n apply(_, __, [payload, callCtx]) {\n const name = path.join(\".\");\n const clientPath = [serviceName, ...path].join(\".\");\n return callAction(\n serviceName,\n name,\n (service) =>\n service.getAction(name) ??\n // Plugin actions (CRUD) are found by the path the typed client uses.\n service\n .listActions()\n .find(\n (action) =>\n (getPluginActionRoute(action) || undefined)?.clientPath?.join(\n \".\",\n ) === clientPath,\n ),\n payload,\n callCtx,\n options,\n );\n },\n });\n}\n\nasync function callAction(\n serviceName: string,\n actionName: string,\n find: (service: Service<any, any>) => Action<any, any, any, any> | undefined,\n payload: unknown,\n callCtx: Partial<ActionContext> | undefined,\n options: ProxyOptions,\n) {\n const service = getGlobalRegistry().get(serviceName);\n if (!service) {\n throw new Error(\n `[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`,\n );\n }\n const action = find(service);\n if (!action) {\n throw new Error(\n `[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`,\n );\n }\n const envelopeCtx = createRpcEnvelope(options.from, options.context, callCtx);\n return withCallSpan(\n `${SPAN.rpcPrefix}${serviceName}.${actionName}`,\n { [ATTR.service]: serviceName, [ATTR.action]: actionName },\n () => action.execute({ input: payload, ctx: envelopeCtx }),\n );\n}\n\n/** Build the trusted envelope for a proxy call.\n *\n * When `from` is provided, it identifies the service that created the proxy\n * and always sets `caller` — any `caller` supplied via `options.context` or\n * the per-call context is ignored so it cannot be spoofed. When `from` is\n * omitted, an explicitly supplied `caller` still passes through for backward\n * compatibility; otherwise `caller` stays unset (never the target service).\n */\nexport function createRpcEnvelope(\n from: string | undefined,\n defaultContext?: Partial<ActionContext>,\n callContext?: Partial<ActionContext>,\n): Partial<ActionContext> {\n const envelope = {\n ...pickContextEnvelope(defaultContext),\n ...pickContextEnvelope(callContext),\n } as Partial<ActionContext> & { caller?: string };\n if (from !== undefined) {\n envelope.caller = from;\n }\n return envelope;\n}\n","import { checkPayload, type EventRef } from \"./catalog\";\nimport { recordingServices } from \"./hub\";\n\n/**\n * Record an event of your own from an action, a tool or a hook. Listeners get it\n * as they get a generated CRUD event, with the payload you give.\n *\n * By default the event is committed in a transaction of its own. Pass the `tx`\n * of a transaction you have open to commit it with your writes instead: then it\n * is delivered at the dispatcher's next poll, because Brick does not see your\n * commit. Nothing is recorded when no listener wants the event.\n *\n * @param ctx - The action context: its `db` finds the service's outbox, and its\n * `traceId` follows the event to its listeners.\n * @param event - A declared event, such as `orders.events.shipped`, whose payload\n * is typed and checked against its schema; or an event name such as\n * `orders.refunded`. A service with an event catalog only records names from it\n * (and the CRUD events of its resources).\n * @param payload - JSON data for the listeners.\n * @param options - `tx`: an open transaction on the service's database. `source`:\n * what emitted it, shown to listeners.\n * @throws When the context's database has no outbox table, or the app has no\n * `events`; when the event is not in the service's catalog, or its payload does\n * not match the declared schema.\n * @example\n * refund: service.action({\n * name: \"refund\",\n * execute: async ({ ctx, input }) => {\n * await ctx.db.update(orders).set({ status: \"refunded\" }).where(eq(orders.id, input.id));\n * await emitEvent(ctx, orders.events.refunded, { id: input.id });\n * },\n * });\n */\nexport async function emitEvent<TPayload>(\n ctx: { db?: unknown; traceId?: string },\n event: EventRef<TPayload>,\n payload: NoInfer<TPayload>,\n options?: { tx?: unknown; source?: string },\n): Promise<void>;\nexport async function emitEvent(\n ctx: { db?: unknown; traceId?: string },\n name: string,\n payload: unknown,\n options?: { tx?: unknown; source?: string },\n): Promise<void>;\nexport async function emitEvent(\n ctx: { db?: unknown; traceId?: string },\n event: string | EventRef,\n payload: unknown,\n options: { tx?: unknown; source?: string } = {},\n): Promise<void> {\n const name = typeof event === \"string\" ? event : event.name;\n const service =\n ctx.db && typeof ctx.db === \"object\"\n ? recordingServices.get(ctx.db)\n : undefined;\n // The recording service checks its own events; one declared elsewhere is checked here.\n if (typeof event !== \"string\" && event.service !== service?.name)\n checkPayload(event, payload);\n const events = service?.recorder;\n if (!events)\n throw new Error(\n `Cannot emit '${name}': ctx.db is not the database of a service with an outbox table (the app needs events, and ctx.db must be the service's own database, not a transaction)`,\n );\n const context = { traceId: ctx.traceId, source: options.source };\n if (options.tx !== undefined)\n return events.record(options.tx, context, name, payload);\n await events.transaction(ctx.db, context, async (_tx, record) => {\n await record(name, payload);\n });\n}\n","import {\n DuplicateNameError,\n type ActionContext,\n type Service,\n type Tool,\n type ToolAnnotations,\n} from \"./types\";\n\nexport interface McpToolDefinition {\n name: string;\n title?: string;\n description: string;\n inputSchema: unknown;\n /** The tool's `output` schema; a non-object one is wrapped as `{ result }`. */\n outputSchema?: unknown;\n annotations: ToolAnnotations;\n}\n\nexport interface McpRegistryOptions {\n services?: readonly Pick<Service<any, any>, \"listTools\">[];\n tools?: readonly Tool<any, any, any, any>[];\n}\n\nexport interface McpRegistry {\n listTools(): McpToolDefinition[];\n callTool(\n name: string,\n args?: Record<string, unknown>,\n ctx?: Partial<ActionContext>,\n ): Promise<unknown>;\n}\n\nexport class UnknownToolError extends Error {\n constructor(name: string) {\n super(`unknown tool: ${name}`);\n this.name = \"UnknownToolError\";\n }\n}\n\n/** Collect only explicitly defined tools, without exposing ordinary actions. */\nexport function createMcpRegistry(options: McpRegistryOptions): McpRegistry {\n function toolsByName() {\n const tools = new Map<string, Tool<any, any, any, any>>();\n for (const tool of [\n ...(options.tools ?? []),\n ...(options.services ?? []).flatMap((service) => service.listTools()),\n ]) {\n const existing = tools.get(tool.name);\n if (existing && existing !== tool)\n throw new DuplicateNameError(`Duplicate MCP tool: ${tool.name}`);\n tools.set(tool.name, tool);\n }\n return tools;\n }\n toolsByName();\n return {\n listTools: () =>\n Array.from(toolsByName().values(), (tool) => ({\n name: tool.name,\n ...((tool.config.title ?? tool.config.annotations?.title)\n ? { title: tool.config.title ?? tool.config.annotations?.title }\n : {}),\n description: tool.config.description ?? \"\",\n inputSchema: tool.config.input ?? {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n ...(tool.config.output\n ? { outputSchema: outputSchema(tool.config.output) }\n : {}),\n annotations: tool.config.annotations ?? {},\n })),\n async callTool(name, args = {}, ctx) {\n const tool = toolsByName().get(name);\n if (!tool) throw new UnknownToolError(name);\n return tool({ input: args, ctx });\n },\n };\n}\n\n// MCP requires an object outputSchema, so other outputs travel as `{ result }`.\nconst WRAP_RESULT = \"x-brick-wrap-result\";\nfunction outputSchema(schema: { type?: unknown }) {\n return schema.type === \"object\"\n ? schema\n : {\n type: \"object\",\n properties: { result: schema },\n required: [\"result\"],\n [WRAP_RESULT]: true,\n };\n}\n\nexport interface McpHandlerOptions {\n registry: McpRegistry;\n serverInfo: { name: string; version: string; title?: string };\n /** Versions supported by this transport, newest first. */\n protocolVersions?: readonly string[];\n}\n\nfunction result(id: unknown, value: unknown) {\n return Response.json({ jsonrpc: \"2.0\", id, result: value });\n}\nfunction rpcError(id: unknown, code: number, message: string) {\n return Response.json({ jsonrpc: \"2.0\", id, error: { code, message } });\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */\nexport function createMcpHandler(options: McpHandlerOptions) {\n const versions = options.protocolVersions ?? [\"2025-06-18\"];\n if (!versions.length)\n throw new Error(\"At least one MCP protocol version is required\");\n return async (\n request: Request,\n ctx?: Partial<ActionContext>,\n ): Promise<Response> => {\n if (request.method !== \"POST\")\n return new Response(null, { status: 405, headers: { Allow: \"POST\" } });\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return rpcError(null, -32700, \"parse error\");\n }\n if (\n !isRecord(body) ||\n body.jsonrpc !== \"2.0\" ||\n typeof body.method !== \"string\" ||\n (body.id !== undefined &&\n body.id !== null &&\n typeof body.id !== \"string\" &&\n typeof body.id !== \"number\") ||\n (body.params !== undefined && !isRecord(body.params))\n ) {\n return rpcError(null, -32600, \"invalid request\");\n }\n if (body.id === undefined) return new Response(null, { status: 202 });\n const { id, method } = body;\n const params = body.params as Record<string, unknown> | undefined;\n switch (method) {\n case \"initialize\": {\n const requested = params?.protocolVersion;\n return result(id, {\n capabilities: { tools: {} },\n protocolVersion:\n typeof requested === \"string\" && versions.includes(requested)\n ? requested\n : versions[0],\n serverInfo: options.serverInfo,\n });\n }\n case \"ping\":\n return result(id, {});\n case \"tools/list\":\n try {\n return result(id, { tools: options.registry.listTools() });\n } catch {\n return rpcError(id, -32603, \"internal error\");\n }\n case \"tools/call\": {\n if (\n typeof params?.name !== \"string\" ||\n (params.arguments !== undefined && !isRecord(params.arguments))\n ) {\n return rpcError(id, -32602, \"invalid tool parameters\");\n }\n try {\n const value = await options.registry.callTool(\n params.name,\n params.arguments as Record<string, unknown> | undefined,\n { ...ctx, request },\n );\n const schema = options.registry\n .listTools()\n .find((tool) => tool.name === params.name)?.outputSchema as\n | Record<string, unknown>\n | undefined;\n return result(id, {\n content: [\n {\n type: \"text\",\n text:\n typeof value === \"string\"\n ? value\n : (JSON.stringify(value, null, 2) ?? \"null\"),\n },\n ],\n ...(schema\n ? {\n structuredContent: schema[WRAP_RESULT]\n ? { result: value }\n : value,\n }\n : {}),\n });\n } catch (error) {\n if (error instanceof UnknownToolError)\n return rpcError(id, -32602, error.message);\n return result(id, {\n content: [\n {\n type: \"text\",\n text: error instanceof Error ? error.message : String(error),\n },\n ],\n isError: true,\n });\n }\n }\n default:\n return rpcError(id, -32601, `method not found: ${method}`);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAGA,MAAa,aAAa,OAAO,IAAI,uBAAuB;AAiD5D,MAAa,aAAa,OAAO,KAAK;CARpC,cAAc;CACd,aAAa;CACb,cAAc;CACd,aAAa;CACb,cAAc;CACd,aAAa;CACb,aAAa;AAEuB,CA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AC;GACtB,KAAK,cACH,IAAI;IACF,OAAO,OAAO,IAAI,EAAE,OAAO,QAAQ,SAAS,UAAU,EAAE,CAAC;GAC3D,QAAQ;IACN,OAAO,SAAS,IAAI,QAAQ,gBAAgB;GAC9C;GACF,KAAK;IACH,IACE,OAAO,QAAQ,SAAS,YACvB,OAAO,cAAc,KAAA,KAAa,CAAC,SAAS,OAAO,SAAS,GAE7D,OAAO,SAAS,IAAI,QAAQ,yBAAyB;IAEvD,IAAI;KACF,MAAM,QAAQ,MAAM,QAAQ,SAAS,SACnC,OAAO,MACP,OAAO,WACP;MAAE,GAAG;MAAK;KAAQ,CACpB;KACA,MAAM,SAAS,QAAQ,SACpB,UAAU,CAAC,CACX,MAAM,SAAS,KAAK,SAAS,OAAO,IAAI,CAAC,EAAE;KAG9C,OAAO,OAAO,IAAI;MAChB,SAAS,CACP;OACE,MAAM;OACN,MACE,OAAO,UAAU,WACb,QACC,KAAK,UAAU,OAAO,MAAM,CAAC,KAAK;MAC3C,CACF;MACA,GAAI,SACA,EACE,mBAAmB,OAAO,eACtB,EAAE,QAAQ,MAAM,IAChB,MACN,IACA,CAAC;KACP,CAAC;IACH,SAAS,OAAO;KACd,IAAI,iBAAiB,kBACnB,OAAO,SAAS,IAAI,QAAQ,MAAM,OAAO;KAC3C,OAAO,OAAO,IAAI;MAChB,SAAS,CACP;OACE,MAAM;OACN,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;MAC7D,CACF;MACA,SAAS;KACX,CAAC;IACH;GAEF,SACE,OAAO,SAAS,IAAI,QAAQ,qBAAqB,QAAQ;EAC7D;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["sqliteTable","sqliteText","sqliteInteger","sqliteReal","pgText","pgInteger","pgBoolean","pgTimestamp","getTableName","getTableName","migratePostgres","getTableName","getTableColumns","sql","and","eq","getTableColumns","inArray","sqliteInteger","sqliteTable","sqliteText","pgText","pgInteger"],"sources":["../src/plugin-hooks.ts","../src/plugin-tables.ts","../src/version.ts","../src/define-plugin.ts","../src/tool.ts","../src/db/sqlite.ts","../src/db/postgres.ts","../src/db/define.ts","../src/db/column.ts","../src/db/index.ts","../src/resource.ts","../src/schedules/table.ts","../src/service.ts","../src/socket-redis.ts","../src/rpc.ts","../src/events/emit.ts","../src/mcp.ts"],"sourcesContent":["import type { ActionContext } from \"./types\";\n\n/** Where `hooks.*` stores a plugin's hooks on its host; `@brickkit/crud` runs them. */\nexport const 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/** The arguments each host CRUD hook receives, by hook name. */\nexport interface PluginHookArgs<C = ActionContext> {\n beforeCreate: HookBase<C> & { data: Record<string, unknown> };\n afterCreate: HookBase<C> & { row: Record<string, unknown> };\n beforeUpdate: HookBase<C> & { id: unknown; data: Record<string, unknown> };\n afterUpdate: HookBase<C> & { id: unknown; row: Record<string, unknown> };\n beforeDelete: HookBase<C> & { id: unknown };\n afterDelete: HookBase<C> & { id: unknown };\n afterCommit: {\n operation: \"create\" | \"update\" | \"delete\";\n id: unknown;\n row?: Record<string, unknown>;\n ctx: C;\n };\n}\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 type PluginHooks<C = ActionContext> = {\n [K in keyof PluginHookArgs<C>]: (\n hook: (args: PluginHookArgs<C>[K]) => unknown,\n ) => void;\n};\n\nexport type HostHooks = {\n [K in keyof PluginHookArgs]?: ((args: PluginHookArgs[K]) => unknown)[];\n};\n\n// A record, so adding a hook to `PluginHookArgs` without listing it here fails to compile.\nconst HOOKS: Record<keyof PluginHookArgs, true> = {\n beforeCreate: true,\n afterCreate: true,\n beforeUpdate: true,\n afterUpdate: true,\n beforeDelete: true,\n afterDelete: true,\n afterCommit: true,\n};\nexport const HOOK_NAMES = Object.keys(HOOKS) as (keyof PluginHookArgs)[];\n\n/** The plugin hooks installed on a service or resource, by hook name. */\nexport function getHostHooks(host: object): HostHooks | undefined {\n return (host as Record<symbol, HostHooks | undefined>)[HOST_HOOKS];\n}\n\n/** Add hooks to a host, after those already there. */\nexport function addHostHooks(host: object, added: HostHooks): void {\n const store = ((host as Record<symbol, HostHooks>)[HOST_HOOKS] ??= {});\n for (const name of HOOK_NAMES)\n if (added[name])\n (store[name] ??= [] as never[]).push(...(added[name] as never[]));\n}\n","import {\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\";\n\nconst OWNER = Symbol.for(\"brickkit.plugin.owner\");\nexport function setPluginOwner(table: object, plugin: string): void {\n Object.defineProperty(table, OWNER, { value: plugin });\n}\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\nexport function 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","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\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","import { 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 type { DepsOf, Ports } from \"./deps\";\nimport { actionMeta } from \"./action-meta\";\nimport { portOf } from \"./service-port\";\nimport type { EventCatalog, EventRef, EventRefs } from \"./events/catalog\";\nimport type { EventListener } from \"./events/types\";\nimport { hasPlugin, validateName } from \"./plugin\";\nimport {\n PLUGIN_KIND,\n PLUGIN_COMMIT,\n type PluginRouteRegistrar,\n type ResourcePlugin,\n type ServicePlugin,\n} from \"./plugin-types\";\nimport {\n addHostHooks,\n HOOK_NAMES,\n type HostHooks,\n type PluginHooks,\n} from \"./plugin-hooks\";\nimport {\n builders,\n setPluginOwner,\n type PluginTableBuilders,\n} from \"./plugin-tables\";\nimport { brickVersion, satisfiesRange } from \"./version\";\nimport { INTERNALS, type Internals } from \"./plugin-app\";\nimport { definitionSite } from \"./definition-site\";\nimport type { SecretRef } from \"./secrets\";\nimport { validateWithSchema } from \"./typebox\";\nimport type { Action, 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\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.12.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\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.12.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 validateName(name);\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 const setup = (context: {\n service: Service<any, any>;\n resource?: Resource<any, any, any>;\n routes: PluginRouteRegistrar<any>;\n [PLUGIN_COMMIT]?: (commit: () => void) => void;\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 setPluginOwner(table, name);\n portOf(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 claim: (segment) => context.routes.claim(segment),\n };\n const before = new Set<unknown>([\n ...service.listActions(),\n ...service.listTools(),\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 // Every action and socket the setup added (its own, its resources', crud's) runs with the plugin's deps.\n for (const action of [...service.listActions(), ...service.listTools()])\n if (!before.has(action)) bindPluginDeps(name, action, deps, started);\n for (const socket of service.listSockets())\n if (!before.has(socket)) socket.deps ??= deps;\n\n context[PLUGIN_COMMIT]?.(() => {\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 portOf(service).addEvents(\n Object.fromEntries(\n Object.entries(events).map(([key, ref]) => [\n `${eventSpace}.${key}`,\n ref,\n ]),\n ),\n );\n addHostHooks(host, added as HostHooks);\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 [PLUGIN_KIND]: \"plugin\",\n name,\n info,\n setup,\n [INTERNALS]: internals,\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 * Run an action with the plugin's deps as `ctx.deps`: context resolution\n * reads them from its metadata. A nested definePlugin binds its own actions\n * 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: Action<any, any, any, any>,\n deps: Readonly<Record<string, unknown>>,\n started: number,\n) {\n const meta = actionMeta(action);\n if (meta.deps) {\n if (meta.deps.values === deps || meta.deps.at > started) return;\n throw new Error(\n `${plugin}: action \"${action.name}\" is already bound to the deps of another install; create the action inside the setup so each install gets its own`,\n );\n }\n meta.deps = { values: deps, at: ++bindings };\n}\n\n/** Check the deps passed at install against the ports the plugin declares. */\nfunction checkDeps(\n plugin: string,\n /** The plugin's factory as the user imports it (its camelCase name), for the hint. */\n camelName: 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: ${camelName}(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","import type { TSchema } from \"@sinclair/typebox\";\nimport { defineAction } from \"./action\";\nimport type {\n Tool,\n ToolConfigWithAuthorize,\n ToolConfigWithoutAuthorize,\n ActionErrorDefinition,\n ActionContext,\n} from \"./types\";\n\n/**\n * Define a tool: an action that AI agents can call through MCP. It takes the\n * same configuration as `defineAction` (validation, `authorize`, errors), plus\n * `title`, `annotations` (the MCP hints about what the tool does), and `http`\n * to also serve it over HTTP and in OpenAPI (off by default).\n *\n * @param config - An action configuration and tool options. `input` must be an\n * object schema, since MCP passes arguments by name.\n * @returns The tool, which is also an action. Register it with `service.tool(tool)`.\n * @throws When `input` is not an object schema.\n * @example\n * import { defineTool, t } from \"@brickkit/core\";\n *\n * export const echoTool = defineTool({\n * name: \"echo\",\n * title: \"Echo a message\",\n * description: \"Returns the message it is given.\",\n * input: t.Object({ message: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `Echo: ${input.message}`,\n * });\n */\nexport function defineTool<\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: ToolConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineTool<\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: ToolConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineTool(config: any): any {\n if (config.input && config.input.type !== \"object\") {\n throw new Error(`Tool '${config.name}' input must be an object schema`);\n }\n const tool = defineAction(config);\n Object.defineProperty(tool, \"kind\", { value: \"tool\" });\n return tool;\n}\n\n/**\n * Whether a value was made with `defineTool`, as opposed to `defineAction`.\n *\n * @param value - Anything.\n * @returns `true` for a tool, narrowing its type.\n */\nexport function isTool(value: unknown): value is Tool<any, any, any, any> {\n return typeof value === \"function\" && (value as Tool).kind === \"tool\";\n}\n","import type { Database } from \"bun:sqlite\";\nimport type { BunSQLiteDatabase } from \"drizzle-orm/bun-sqlite\";\n\nimport { createRequire } from \"node:module\";\n\nconst requireSQLite = createRequire(import.meta.url);\n\nexport type { BunSQLiteDatabase } from \"drizzle-orm/bun-sqlite\";\n\nexport {\n sqliteTable,\n text,\n integer,\n real,\n blob,\n index,\n uniqueIndex,\n primaryKey,\n foreignKey,\n} from \"drizzle-orm/sqlite-core\";\n\nexport interface SQLiteDatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Database file path or ':memory:' (default: ':memory:') */\n path?: string;\n /** Alias for path */\n filename?: string;\n /** Whether to enable WAL journal mode for file-based DBs (default: true) */\n wal?: boolean;\n /** Whether to enforce foreign key constraints (default: true) */\n foreignKeys?: boolean;\n /** Optional existing bun:sqlite Database instance */\n client?: Database;\n /** Optional Drizzle schema object for typed relational queries */\n schema?: TSchema;\n}\n\nexport type BrickSQLiteDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = BunSQLiteDatabase<TSchema> & {\n $client: Database;\n};\n\n/**\n * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine\n * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).\n *\n * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on\n * other runtimes (e.g. Node) stays safe until this function is actually\n * called.\n */\nexport function createSQLiteDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(config: SQLiteDatabaseConfig<TSchema> = {}): BunSQLiteDatabase<TSchema> {\n let Database: new (path: string) => Database;\n let drizzle: (\n client: Database,\n config?: { schema?: TSchema },\n ) => BunSQLiteDatabase<TSchema>;\n try {\n ({ Database } = requireSQLite(\"bun:sqlite\"));\n // Keep the adapter lazy for Node imports, but visible to Bun's bundler.\n ({ drizzle } = require(\"drizzle-orm/bun-sqlite\"));\n } catch (err: any) {\n throw new Error(\n `[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`,\n );\n }\n const filePath = config.filename ?? config.path ?? \":memory:\";\n const client = config.client ?? new Database(filePath);\n\n if (config.foreignKeys !== false) {\n client.run(\"PRAGMA foreign_keys = ON;\");\n }\n\n if (config.wal !== false && filePath !== \":memory:\") {\n client.run(\"PRAGMA journal_mode = WAL;\");\n }\n\n const db = (\n config.schema ? drizzle(client, { schema: config.schema }) : drizzle(client)\n ) as BunSQLiteDatabase<TSchema>;\n\n if (!(db as any).$client) {\n (db as any).$client = client;\n }\n\n return db;\n}\n","import postgres, { type Sql } from \"postgres\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\n\nexport interface PostgresDatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */\n client?: Sql;\n /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */\n url?: string;\n /** Connection string alias */\n connectionString?: string;\n host?: string;\n port?: number;\n user?: string;\n password?: string;\n database?: string;\n ssl?: boolean | \"require\" | \"allow\" | \"prefer\" | \"verify-full\";\n max?: number;\n /**\n * Disable prepared statements (required for transaction-mode poolers such\n * as Supabase's Supavisor on :6543, which cannot hold named prepared\n * statements across transactions).\n */\n prepare?: boolean;\n /** Optional Drizzle schema for relational queries */\n schema?: TSchema;\n /** Custom schema name for Encore-style isolated schemas */\n schemaName?: string;\n}\n\nexport type PostgresDatabase<\n _TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = any;\n\n/**\n * Creates a PostgreSQL Drizzle instance using postgres-js.\n * Static imports so bundlers (Nitro/Rollup) trace and ship the driver.\n * `bun:sqlite` stays lazy in `sqlite.ts` since it only exists under Bun.\n */\nexport function createPostgresDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(config: PostgresDatabaseConfig<TSchema> = {}): PostgresDatabase<TSchema> {\n const connectionUrl =\n config.url ??\n config.connectionString ??\n (typeof process !== \"undefined\" ? process.env?.DATABASE_URL : undefined);\n\n const client =\n config.client ??\n (connectionUrl\n ? postgres(connectionUrl, {\n max: config.max,\n prepare: config.prepare,\n ssl: config.ssl,\n })\n : postgres({\n host: config.host ?? \"localhost\",\n port: config.port ?? 5432,\n user: config.user,\n password: config.password,\n database: config.database,\n max: config.max,\n prepare: config.prepare,\n ssl: config.ssl,\n }));\n\n return drizzle(client, {\n schema: config.schema,\n ...(config.schemaName ? { schemaFilter: [config.schemaName] } : {}),\n });\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { type Table, getTableName } from \"drizzle-orm\";\nimport type { PostgresJsDatabase } from \"drizzle-orm/postgres-js\";\nimport type { Sql } from \"postgres\";\nimport { SecretRef } from \"../secrets\";\nimport {\n createSQLiteDatabase,\n type SQLiteDatabaseConfig,\n type BunSQLiteDatabase,\n type BrickSQLiteDatabase,\n} from \"./sqlite\";\nimport {\n createPostgresDatabase,\n type PostgresDatabaseConfig,\n} from \"./postgres\";\n\nexport type EnvInput<T> = T | SecretRef<T>;\ntype EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>> };\n\ninterface DefinitionOptions<TSchema extends Record<string, unknown>> {\n name?: string;\n /** Drizzle tables retained for schema tooling. Never applied at runtime. */\n tables?: (TSchema & Record<string, Table>) | readonly Table[];\n schema?: TSchema;\n}\n\nexport type SQLiteDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = DefinitionOptions<TSchema> &\n EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, \"schema\" | \"client\">> & {\n engine?: \"sqlite\";\n client?: SQLiteDatabaseConfig<TSchema>[\"client\"];\n url?: never;\n connectionString?: never;\n };\n\nexport type PostgresDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = DefinitionOptions<TSchema> &\n EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, \"schema\" | \"client\">> & {\n engine: \"postgres\";\n path?: never;\n filename?: never;\n wal?: never;\n foreignKeys?: never;\n client?: PostgresDatabaseConfig<TSchema>[\"client\"];\n };\n\nexport type DatabaseDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;\n\nexport interface DatabaseHandle<\n TDb,\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n readonly kind: \"brick-database\";\n readonly name?: string;\n readonly engine: \"sqlite\" | \"postgres\";\n readonly tables: Readonly<Record<string, Table>>;\n readonly schema: TSchema;\n /**\n * Add a table after definition, as `definePlugin` does for the tables a\n * plugin owns. Before `getDb()` it also joins the relational schema.\n */\n addTable?(key: string, table: Table): void;\n getDb(): TDb;\n close?(): void | Promise<void>;\n}\n\n/**\n * Whether a value is a database handle made by `defineDatabase`.\n *\n * @param value - Anything.\n * @returns `true` for a handle, narrowing its type.\n */\nexport function isDatabaseHandle(\n value: unknown,\n): value is DatabaseHandle<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n value.kind === \"brick-database\"\n );\n}\n\n/**\n * Declare a service's database: its engine, its Drizzle tables, and how to\n * reach it. Nothing connects until the handle is used (`getDb()`), so defining\n * one has no side effects.\n *\n * SQLite is the default and needs no options. Pass `engine: \"postgres\"` with a\n * `url` for Postgres. Options that belong to the other engine (such as `url` for\n * SQLite, or `path` for Postgres) are refused.\n *\n * @param options - `engine` (`\"sqlite\"` or `\"postgres\"`), `tables`, an optional\n * `name`, and the engine's connection settings.\n * @returns A handle to give to `defineService({ database })`. `getDb()` returns\n * the Drizzle database.\n * @throws When the engine is unsupported, or an option does not suit the engine.\n * @example\n * import { defineDatabase } from \"@brickkit/core\";\n * import { sqliteTable, text } from \"drizzle-orm/sqlite-core\";\n *\n * const pages = sqliteTable(\"pages\", {\n * id: text(\"id\").primaryKey(),\n * title: text(\"title\").notNull(),\n * });\n *\n * export const database = defineDatabase({ tables: { pages } });\n */\nexport function defineDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n options?: SQLiteDefinition<TSchema>,\n): DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema>;\nexport function defineDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n options: PostgresDefinition<TSchema>,\n): DatabaseHandle<PostgresJsDatabase<TSchema> & { $client: Sql }, TSchema>;\nexport function defineDatabase(\n options: DatabaseDefinition = {},\n): DatabaseHandle<unknown> {\n const engine = options.engine ?? \"sqlite\";\n if (engine !== \"sqlite\" && engine !== \"postgres\") {\n throw new Error(`Unsupported database engine: ${engine}`);\n }\n const forbidden =\n engine === \"sqlite\"\n ? [\n \"url\",\n \"connectionString\",\n \"host\",\n \"port\",\n \"user\",\n \"password\",\n \"database\",\n \"ssl\",\n \"max\",\n \"prepare\",\n \"schemaName\",\n ]\n : [\"path\", \"filename\", \"wal\", \"foreignKeys\"];\n for (const key of forbidden) {\n if (key in options)\n throw new Error(`Database option \"${key}\" is not valid for ${engine}`);\n }\n const declared = options.tables ?? {};\n const tables: Record<string, Table> = Array.isArray(declared)\n ? Object.fromEntries(declared.map((table) => [getTableName(table), table]))\n : { ...declared };\n const schema = options.schema ?? tables;\n let frozen = Object.freeze({ ...tables });\n let db: unknown;\n let closeClient: (() => void | Promise<void>) | undefined;\n let closed = false;\n let closing: void | Promise<void>;\n\n return {\n kind: \"brick-database\",\n name: options.name,\n engine,\n get tables() {\n return frozen;\n },\n schema,\n addTable(key, table) {\n const name = getTableName(table);\n if (\n Object.hasOwn(tables, key) ||\n Object.values(tables).some((item) => getTableName(item) === name)\n )\n throw new Error(\n `Database already has a table \"${key}\" or one named \"${name}\"`,\n );\n // Also joins `schema` when that is `tables` itself (no `schema` given).\n tables[key] = table;\n frozen = Object.freeze({ ...tables });\n },\n close() {\n if (closed) return closing;\n closed = true;\n closing = closeClient?.();\n return closing;\n },\n getDb() {\n if (closed) throw new Error(\"Brick database handle is closed\");\n if (db !== undefined) return db;\n const config: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(options)) {\n if ([\"tables\", \"schema\", \"name\", \"engine\"].includes(key)) continue;\n // An injected Postgres client already owns all connection settings.\n if (\n engine === \"postgres\" &&\n options.client &&\n key !== \"client\" &&\n key !== \"schemaName\"\n )\n continue;\n config[key] = value instanceof SecretRef ? value.require() : value;\n }\n if (engine === \"sqlite\") {\n const path = (config.filename ?? config.path ?? \":memory:\") as string;\n if (!config.client && path !== \":memory:\")\n mkdirSync(dirname(path), { recursive: true });\n const instance = createSQLiteDatabase({ ...config, schema });\n db = instance;\n if (!options.client)\n closeClient = () => (instance as BrickSQLiteDatabase).$client.close();\n } else {\n const instance: PostgresJsDatabase & { $client: Sql } =\n createPostgresDatabase({ ...config, schema });\n db = instance;\n if (!options.client) closeClient = () => instance.$client.end();\n }\n return db;\n },\n };\n}\n","import type { Column } from \"drizzle-orm\";\n\n/**\n * A JSON value as its column stores it: an ISO string becomes a Date for a date\n * column, an integer string a BigInt for a bigint column. Other values pass\n * through.\n *\n * @returns `undefined` when the string can't be a value of the column.\n */\nexport function columnValue(column: Column, value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n if (column.dataType === \"date\") {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? undefined : date;\n }\n if (column.dataType === \"bigint\")\n return /^-?\\d+$/.test(value) ? BigInt(value) : undefined;\n return value;\n}\n","import type { Service } from \"../types\";\nimport type { DatabaseHandle } from \"./define\";\nimport { getTableColumns, getTableName, sql, type Table } from \"drizzle-orm\";\nimport { getTableConfig, isPgEnum, pgSchema } from \"drizzle-orm/pg-core\";\nimport { migrate as migratePostgres } from \"drizzle-orm/postgres-js/migrator\";\nimport { migrate as migrateSQLite } from \"drizzle-orm/bun-sqlite/migrator\";\n\nexport * from \"./sqlite\";\nexport * from \"./postgres\";\nexport * from \"./define\";\nexport { columnValue } from \"./column\";\n\nexport {\n sql,\n eq,\n ne,\n gt,\n gte,\n lt,\n lte,\n and,\n or,\n not,\n desc,\n asc,\n inArray,\n notInArray,\n isNull,\n isNotNull,\n like,\n ilike,\n relations,\n getTableColumns,\n getTableName,\n Table,\n is,\n} from \"drizzle-orm\";\n\n/**\n * Apply the migrations in a folder that have not run yet, in order, and record\n * them in the database's `__drizzle_migrations` table. The folder is the one\n * `brick db generate` (or drizzle-kit) writes: `<out>/<database name>`.\n *\n * @param database - A handle from `defineDatabase`.\n * @param migrationsFolder - The folder holding `meta/_journal.json`.\n * @example\n * await migrateDatabase(database, \"./drizzle/pages\");\n */\nexport async function migrateDatabase(\n database: DatabaseHandle<unknown>,\n migrationsFolder: string,\n): Promise<void> {\n const db = database.getDb() as any;\n if (database.engine === \"postgres\")\n await migratePostgres(db, { migrationsFolder });\n else migrateSQLite(db, { migrationsFolder });\n}\n\n/** Attach a defined database. Schema changes remain the caller's responsibility. */\nexport function attachDatabase<TDb>(\n service: Service<TDb, any>,\n database: DatabaseHandle<TDb>,\n): TDb {\n service.setDb(database);\n return database.getDb();\n}\n\n/**\n * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition\n * directly from a Drizzle table schema.\n */\nexport function generateSQLiteTableDdl(table: any): string {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colDefs: string[] = [];\n\n for (const [, col] of Object.entries(columns) as [string, any][]) {\n let def = `\"${col.name}\" ${col.getSQLType().toUpperCase()}`;\n if (col.primary) def += \" PRIMARY KEY\";\n if (col.notNull) def += \" NOT NULL\";\n if (col.isUnique) def += \" UNIQUE\";\n if (col.hasDefault) {\n if (typeof col.default === \"string\") {\n def += ` DEFAULT '${col.default.replace(/'/g, \"''\")}'`;\n } else if (typeof col.default === \"boolean\") {\n def += ` DEFAULT ${col.default ? 1 : 0}`;\n } else if (typeof col.default === \"number\") {\n def += ` DEFAULT ${col.default}`;\n } else if (col.default !== undefined) {\n def += ` DEFAULT ${col.default}`;\n }\n }\n colDefs.push(def);\n }\n\n return `CREATE TABLE IF NOT EXISTS \"${tableName}\" (\\n ${colDefs.join(\",\\n \")}\\n);`;\n}\n\n/**\n * Generates idempotent secondary index DDL for a Drizzle table.\n * Covers owner scoping, sort columns, and exact-match filters.\n * UNIQUE columns already carry an implicit index — skipped here.\n * FTS/trigram indexes are handled separately by the search layer.\n */\nexport function generateSQLiteIndexDdl(\n table: any,\n opts: { ownerField?: string; sortFields?: string[] } = {},\n): string[] {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const stmts: string[] = [];\n const seen = new Set<string>();\n const push = (name: string, cols: string[]) => {\n const clean = cols.filter(Boolean);\n if (clean.length === 0) return;\n const key = `${name}(${clean.join(\",\")})`;\n if (seen.has(key)) return;\n seen.add(key);\n const colList = clean.map((c) => `\"${c}\"`).join(\", \");\n stmts.push(\n `CREATE INDEX IF NOT EXISTS \"${name}\" ON \"${tableName}\" (${colList});`,\n );\n };\n\n const colNameOf = (field: string): string | undefined => {\n if ((columns as any)[field]) return (columns as any)[field].name ?? field;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === field) return col.name;\n }\n return undefined;\n };\n\n // Owner scope index: WHERE user_id = ? (+ sort composite below).\n let ownerCol: string | undefined;\n if (opts.ownerField) {\n const oc = colNameOf(opts.ownerField);\n if (oc) {\n ownerCol = oc;\n push(`idx_${tableName}_${oc}`, [oc]);\n }\n }\n\n // Sort column indexes (updated_at / created_at drive default ORDER BY).\n const sorts = opts.sortFields ?? [\"updated_at\", \"created_at\"];\n const sortCols: string[] = [];\n for (const f of sorts) {\n const c = colNameOf(f);\n if (c) {\n sortCols.push(c);\n push(`idx_${tableName}_${c}`, [c]);\n }\n }\n\n // Composite owner+sort — the hot path for scoped sorted lists.\n if (ownerCol && sortCols.length > 0) {\n push(`idx_${tableName}_${ownerCol}_${sortCols[0]}`, [\n ownerCol,\n sortCols[0],\n ]);\n }\n\n return stmts;\n}\n\n/**\n * Ensures secondary indexes exist for a resource table.\n * SQLite: B-tree indexes for owner scope + sort + composite hot path.\n * Postgres: same B-trees plus pg_trgm GIN indexes for substring search,\n * created one after another (each GIN index needs the extension).\n * Best-effort: a failed statement warns and the rest still run (e.g. a\n * read-only replica, or no right to create pg_trgm); queries still work, only\n * slower. On SQLite every statement has run when it returns.\n */\nexport async function ensureResourceIndexes(\n db: any,\n table: any,\n opts: {\n ownerField?: string;\n sortFields?: string[];\n searchFields?: string[];\n } = {},\n): Promise<void> {\n if (!db) return;\n const isPostgres =\n typeof (db as any).execute === \"function\" && !(db as any).$client?.run;\n const stmts = generateSQLiteIndexDdl(table, opts);\n if (isPostgres && opts.searchFields && opts.searchFields.length > 0) {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colNameOf = (f: string): string | undefined => {\n if ((columns as any)[f]) return (columns as any)[f].name ?? f;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === f) return col.name;\n }\n return undefined;\n };\n for (const f of opts.searchFields) {\n const c = colNameOf(f);\n if (c) {\n stmts.push(\n `CREATE INDEX IF NOT EXISTS \"idx_${tableName}_${c}_trgm\" ON \"${tableName}\" USING gin (\"${c}\" gin_trgm_ops);`,\n );\n }\n }\n }\n if (stmts.length === 0) return;\n if (isPostgres) stmts.unshift(`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);\n for (const stmt of stmts) {\n try {\n if ((db as any).$client?.run) (db as any).$client.run(stmt);\n else if (isPostgres) await (db as any).execute(sql.raw(stmt));\n else (db as any).run?.(stmt);\n } catch (error) {\n console.warn(\n `[Brick-TS DB] Skipped an index: ${stmt} (${error instanceof Error ? error.message : String(error)})`,\n );\n }\n }\n}\n\n/**\n * SQLite FTS5 search layer for resource list (?search=).\n * B-tree indexes cannot serve LIKE '%term%' (leading wildcard forces a full\n * scan). FTS5 gives indexed substring/prefix search on title/slug-scale text.\n * Postgres uses ilike + pg_trgm GIN indexes instead (see ensureResourceIndexes).\n */\n\nfunction ftsTableName(table: any): string {\n return `${getTableName(table)}_fts`;\n}\n\nfunction quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.\n * Idempotent; safe to call on every resource registration.\n * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.\n */\nexport function ensureSQLiteFts(\n db: any,\n table: any,\n searchCols: string[],\n): void {\n if (!db || searchCols.length === 0) return;\n // SQLite only: Postgres has execute() but no $client.run.\n const client = (db as any).$client;\n const runRaw = (db as any).run;\n if (!client?.run && !runRaw) return;\n const run = (stmt: string) => {\n if (client?.run) client.run(stmt);\n else runRaw(stmt);\n };\n try {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colNameOf = (f: string): string | undefined => {\n if ((columns as any)[f]) return (columns as any)[f].name ?? f;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === f) return col.name;\n }\n return undefined;\n };\n // Resolve to DB column names, drop unknowns.\n const dbCols = searchCols.map(colNameOf).filter((c): c is string => !!c);\n if (dbCols.length === 0) return;\n const idCol =\n colNameOf(\"id\") ??\n (Object.values(columns) as any[]).find((c) => c.primary)?.name ??\n \"id\";\n const fts = ftsTableName(table);\n const ftsCols = [\n `\"id\" UNINDEXED`,\n ...dbCols.map((c) => quoteIdent(c)),\n ].join(\", \");\n run(\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${quoteIdent(fts)} USING fts5(${ftsCols}, tokenize='porter');`,\n );\n const colList = dbCols.map(quoteIdent).join(\", \");\n const newVals = dbCols.map((c) => `new.${quoteIdent(c)}`).join(\", \");\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ai`)} AFTER INSERT ON ${quoteIdent(tableName)} BEGIN INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`,\n );\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ad`)} AFTER DELETE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE \"id\" = old.${quoteIdent(idCol)}; END;`,\n );\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_au`)} AFTER UPDATE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE \"id\" = old.${quoteIdent(idCol)}; INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`,\n );\n // Backfill rows predating the FTS table (dedupe via NOT IN).\n run(\n `INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) SELECT ${quoteIdent(idCol)}, ${colList} FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(idCol)} NOT IN (SELECT \"id\" FROM ${quoteIdent(fts)});`,\n );\n } catch (error) {\n // Best effort, as for indexes: search without FTS still works, but say why it is missing.\n console.warn(\n `[Brick-TS DB] Skipped full-text search for ${getTableName(table)}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/**\n * Builds an FTS5 MATCH condition for a resource search term.\n * Returns null when the term has no usable tokens or FTS errors.\n * Caller falls back to LIKE in that case.\n */\nexport function buildFtsMatchQuery(search: string): string | null {\n const terms = search\n .split(/\\s+/)\n .map((s) => s.trim())\n .filter(Boolean)\n .slice(0, 10);\n if (terms.length === 0) return null;\n const escaped = terms\n .map((term) => {\n const clean = term.replace(/\"/g, \"\").trim();\n if (!clean) return null;\n return `\"${clean.replace(/\"/g, '\"\"')}\"*`;\n })\n .filter((x): x is string => !!x);\n if (escaped.length === 0) return null;\n return escaped.join(\" AND \");\n}\n\n/**\n * The schema drizzle-kit reads: the tables, plus the Postgres schemas\n * (namespaces) and enums they use, which drizzle-kit only creates when handed.\n *\n * @param tables - Drizzle tables, all of one engine.\n * @returns A record to pass to drizzle-kit's API (`pushSchema`, `generateDrizzleJson`).\n */\nexport function drizzleSchema(\n tables: readonly Table[],\n): Record<string, unknown> {\n const schema: Record<string, unknown> = {};\n for (const table of tables) {\n // What getTableConfig(table).schema reads, for tables of any engine.\n const namespace = (table as any)[Symbol.for(\"drizzle:Schema\")] as\n | string\n | undefined;\n schema[`table:${namespace ?? \"public\"}.${getTableName(table)}`] = table;\n if (namespace && namespace !== \"public\")\n schema[`schema:${namespace}`] = pgSchema(namespace);\n for (const column of Object.values(getTableColumns(table)) as any[])\n if (isPgEnum(column.enum))\n schema[`enum:${column.enum.enumName}`] = column.enum;\n }\n return schema;\n}\n\n/** drizzle-kit's programmatic API, an optional peer dependency. */\nasync function loadDrizzleKit(): Promise<typeof import(\"drizzle-kit/api\")> {\n // A variable specifier keeps `brick build` from bundling drizzle-kit (and\n // every driver it can load) into the app server.\n const specifier = \"drizzle-kit/api\";\n let kit: typeof import(\"drizzle-kit/api\");\n try {\n kit = await import(specifier);\n } catch (err: any) {\n throw new Error(\n `[Brick-TS DB] Postgres schema tools need drizzle-kit: run \\`bun add -d drizzle-kit\\`, or use \\`brick db push\\`. (${err?.message ?? err})`,\n );\n }\n // drizzle-kit assigns helpers to built-in prototypes when imported\n // (Array.prototype.random, String.prototype.camelCase, ...). Hide them from\n // for...in loops in this process, which break Elysia's AOT compiler among others.\n for (const proto of [\n Object.prototype,\n Array.prototype,\n String.prototype,\n Function.prototype,\n ])\n for (const key of Reflect.ownKeys(proto))\n if (Object.getOwnPropertyDescriptor(proto, key)?.enumerable)\n Object.defineProperty(proto, key, { enumerable: false });\n return kit;\n}\n\n/**\n * Create the declared tables that do not exist yet. A development and test\n * helper: never called by services, resources or server startup, and never\n * changes a table that exists. Use `brick db generate` / `brick db migrate`\n * for production schema changes.\n *\n * SQLite: `CREATE TABLE IF NOT EXISTS` per table, synchronously.\n * Postgres: drizzle-kit (an optional peer dependency) writes the DDL for the\n * missing tables, their enums, indexes and foreign keys, applied in one\n * transaction. Returns a promise to await.\n */\nexport function syncSchema(\n tablesOrService: Map<string, any> | any[] | Record<string, any> | Service,\n dbInstance?: any,\n): Promise<void> | void {\n let db = dbInstance;\n let tables: any[] = [];\n\n if (\n tablesOrService &&\n typeof (tablesOrService as any).listActions === \"function\" &&\n (tablesOrService as any).tables\n ) {\n const service = tablesOrService as Service;\n tables = Array.from(service.tables.values());\n if (!db) {\n db = service.getDb();\n }\n } else if (tablesOrService instanceof Map) {\n tables = Array.from(tablesOrService.values());\n } else if (Array.isArray(tablesOrService)) {\n tables = tablesOrService;\n } else if (tablesOrService && typeof tablesOrService === \"object\") {\n tables = Object.values(tablesOrService);\n }\n\n if (!db || tables.length === 0) return;\n\n if ((db as any).$client?.run || (db as any).run) {\n for (const table of tables) {\n try {\n const ddl = generateSQLiteTableDdl(table);\n if ((db as any).$client?.run) {\n (db as any).$client.run(ddl);\n } else if ((db as any).run) {\n (db as any).run(sql.raw(ddl));\n }\n } catch (err: any) {\n console.warn(`[Brick-TS DB] Failed to create table:`, err.message);\n }\n }\n return;\n }\n\n return createMissingPostgresTables(db, tables);\n}\n\nasync function createMissingPostgresTables(\n db: any,\n tables: Table[],\n): Promise<void> {\n const kit = await loadDrizzleKit();\n const rows: { schema: string; name: string }[] = await db.execute(\n sql`select table_schema as schema, table_name as name from information_schema.tables`,\n );\n const present = new Set(rows.map((row) => `${row.schema}.${row.name}`));\n const existing = tables.filter((table) => {\n const { schema = \"public\", name } = getTableConfig(table as any);\n return present.has(`${schema}.${name}`);\n });\n if (existing.length === tables.length) return;\n // Diff the tables that exist against all of them: only the missing tables\n // (and what only they use) come out, as CREATE statements.\n const before = drizzleSchema(existing);\n const after = drizzleSchema(tables);\n // A namespace may exist without any of these tables: don't create it again.\n const namespaces: { name: string }[] = await db.execute(\n sql`select schema_name as name from information_schema.schemata`,\n );\n for (const { name } of namespaces)\n if (after[`schema:${name}`])\n before[`schema:${name}`] = after[`schema:${name}`];\n // Likewise an enum that exists while only missing tables use it.\n const enums: { schema: string; name: string }[] = await db.execute(\n sql`select n.nspname as schema, t.typname as name from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typtype = 'e'`,\n );\n for (const { schema, name } of enums) {\n const pgEnumValue = after[`enum:${name}`] as any;\n if (pgEnumValue && (pgEnumValue.schema ?? \"public\") === schema)\n before[`enum:${name}`] = pgEnumValue;\n }\n const statements = await kit.generateMigration(\n kit.generateDrizzleJson(before),\n kit.generateDrizzleJson(after),\n );\n await db.transaction(async (tx: any) => {\n for (const statement of statements) await tx.execute(sql.raw(statement));\n });\n}\n","import { and, eq, getTableColumns, inArray, type Column } from \"drizzle-orm\";\nimport type { TObject, TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport { installPlugin, segmentClaimant } from \"./plugin\";\nimport { columnValue } from \"./db/column\";\nimport type { ResourcePlugin } from \"./plugin-types\";\nimport { buildErrorHelpers, defineAction } from \"./action\";\nimport { kebabCase } from \"./kebab\";\nimport { actionMeta, type ResourceActionInfo } from \"./action-meta\";\nimport { portOf } from \"./service-port\";\nimport { Type } from \"./typebox\";\nimport { runInTransaction } from \"./events/transaction\";\nimport { checkPayload, crudEventSource, type EventRef } from \"./events/catalog\";\nimport {\n ActionExecutionError,\n DuplicateNameError,\n type ActionContext,\n type ActionErrorDefinition,\n type CommandConfig,\n type CommandDecision,\n type Resource,\n type ResourceActionAccess,\n type ResourceActionConfig,\n type ResourceChild,\n type ResourceConfig,\n type ResourceTypeOptions,\n type ResourceIdentity,\n type Service,\n} from \"./types\";\n\n/**\n * Load the row a record action (or command) works on, through its `access`.\n *\n * @returns The row, or `undefined` when it is missing or hidden.\n * @throws When `access` is missing.\n */\nexport async function loadRecord(\n resource: Resource<any, any, any>,\n args: {\n id: unknown;\n ctx: any;\n db?: any;\n access?: ResourceActionAccess;\n },\n): Promise<Record<string, unknown> | undefined> {\n if (!args.access)\n throw new Error(\n `Resource '${resource.name}' has no access rule for loading records: set \\`access\\` on the record action`,\n );\n const db = args.db ?? args.ctx?.db;\n // An id its column can't hold names no row.\n const id = columnValue(resource.id, args.id);\n if (id === undefined) return undefined;\n if (!db) throw new Error(\"Record actions require a configured database\");\n const scope =\n args.access === \"public\"\n ? undefined\n : await args.access.scope({ ctx: args.ctx });\n const [row] = await db\n .select()\n .from(resource.table)\n .where(and(scope, eq(resource.id, id)))\n .limit(1);\n return row;\n}\n\n/** Startup check: a record action needs its own `access`. */\nexport function checkRecordAccess(\n resource: Resource<any, any, any>,\n info: ResourceActionInfo,\n): void {\n const name = `${resource.name}.${info.name}`;\n if (info.access === undefined)\n throw new Error(\n `Record action '${name}' needs \\`access\\` (\"public\" or { scope })`,\n );\n}\n\nfunction notFound(\n resource: Resource<any, any, any>,\n id: unknown,\n error: { NOT_FOUND(message: string): never },\n): never {\n error.NOT_FOUND(`${resource.name} '${String(id)}' not found`);\n}\n\n/** The schema of a resource's `:id`. */\nexport function idSchema(column: Column): TSchema {\n return column.dataType === \"number\" ? Type.Number() : Type.String();\n}\n\nfunction defineResourceAction(\n service: Service<any, any>,\n resource: Resource<any, any, any>,\n config: ResourceActionConfig<any, any, any, any, any, boolean>,\n /** A command's body: it loads the row itself, in its transaction. */\n command?: (args: { input: any; ctx: any; error: any }) => Promise<unknown>,\n) {\n const { record = false, access, execute, ...rest } = config;\n if (!config.name || /[./]/.test(config.name))\n throw new Error(`Invalid resource action name '${config.name}'`);\n const name = `${resource.name}.${config.name}`;\n const segment = kebabCase(config.name);\n // A plugin route on this resource (crud's `/count`) owns its first segment.\n const claimant = segmentClaimant(service, resource, segment);\n if (claimant)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${name}\" in service \"${service.name}\": \"${segment}\" is a ${claimant} route`,\n );\n const existing = service.getAction(name);\n if (existing && actionMeta(existing).route)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${name}\" in service \"${service.name}\"`,\n );\n if (!record && access !== undefined)\n throw new Error(`Only record actions take \\`access\\` ('${name}')`);\n if (record && config.path !== undefined && !/\\/:id(\\/|$)/.test(config.path))\n throw new Error(`Record action '${name}' needs ':id' in its path`);\n let input = config.input as TSchema | undefined;\n if (record) {\n const own = input as TObject | undefined;\n if (own && own.type !== \"object\")\n throw new Error(`Record action '${name}' input must be an object`);\n input = Type.Object(\n { ...own?.properties, id: idSchema(resource.id) },\n own?.additionalProperties === undefined\n ? {}\n : { additionalProperties: own.additionalProperties },\n );\n }\n const action = defineAction({\n ...rest,\n name,\n input,\n execute: async ({ input, ctx, error }: any) => {\n if (command) return command({ input, ctx, error });\n const row = record\n ? await loadRecord(resource, { id: input.id, ctx, access })\n : undefined;\n if (record && row === undefined) notFound(resource, input.id, error);\n return execute({ input, ctx, error, row } as any);\n },\n } as any);\n const info: ResourceActionInfo = {\n resource: resource.name,\n name: config.name,\n record,\n ...(access === undefined ? {} : { access }),\n };\n actionMeta(action).resourceAction = info;\n service.action(action);\n return action;\n}\n\nfunction primaryColumn(table: unknown): [string, Column] | undefined {\n const primary = Object.entries(\n getTableColumns(table as Parameters<typeof getTableColumns>[0]),\n ).filter(([, column]) => column.primary);\n return primary.length === 1 ? primary[0] : undefined;\n}\n\nfunction fieldOf(table: unknown, column: Column): string | undefined {\n return Object.entries(\n getTableColumns(table as Parameters<typeof getTableColumns>[0]),\n ).find(([, own]) => own === column)?.[0];\n}\n\ninterface ChildInfo {\n table: any;\n parent: Column;\n parentField: string;\n id: Column;\n idField: string;\n}\n\nfunction childInfo(\n resource: Resource<any, any, any>,\n name: string,\n where: string,\n): ChildInfo {\n const child = (\n resource.config as { children?: Record<string, ResourceChild> }\n ).children?.[name];\n if (!child || !Object.hasOwn(resource.config.children ?? {}, name))\n throw new Error(\n `${where}: resource '${resource.name}' has no child table '${name}'`,\n );\n const parentField = fieldOf(child.table, child.parent);\n const id = child.id ?? primaryColumn(child.table)?.[1];\n const idField = id && fieldOf(child.table, id);\n if (!parentField || !id || !idField)\n throw new Error(\n `Resource '${resource.name}' child '${name}' needs a parent column and an id column of its table`,\n );\n return { table: child.table, parent: child.parent, parentField, id, idField };\n}\n\n/** The `error` helpers of `decide`: they return the rejection, not throw it. */\nfunction commandErrors(errors?: Record<string, ActionErrorDefinition>) {\n const throwing = buildErrorHelpers(errors) as Record<\n string,\n (message?: string, details?: unknown) => never\n >;\n return Object.fromEntries(\n Object.entries(throwing).map(([code, helper]) => [\n code,\n (message?: string, details?: unknown) => {\n try {\n helper(message, details);\n } catch (rejection) {\n return rejection;\n }\n },\n ]),\n );\n}\n\nfunction defineCommand(\n service: Service<any, any>,\n resource: Resource<any, any, any>,\n name: string,\n config: CommandConfig<any, any, any, any, any, any, any, readonly string[]>,\n) {\n const where = `Command '${resource.name}.${name}'`;\n if (typeof config.decide !== \"function\")\n throw new Error(`${where} needs a decide function`);\n const loaded = (config.load?.children ?? []).map((child) => ({\n name: child,\n ...childInfo(resource, child, where),\n }));\n const error = commandErrors(config.errors);\n const decide = (row: any, input: any) =>\n config.decide(row, input, { error } as any);\n const events = service.events as Record<string, EventRef>;\n\n const run = async ({\n input,\n ctx,\n error: helpers,\n }: {\n input: any;\n ctx: any;\n error: any;\n }) => {\n const db = ctx.db;\n if (!db) throw new Error(`${where} requires a configured database`);\n const recorder = service.recorder;\n const body = async (\n tx: any,\n record?: (name: string, payload: unknown) => Promise<void>,\n ) => {\n const row = await loadRecord(resource, {\n id: input.id,\n ctx,\n db: tx,\n access: config.access,\n });\n if (row === undefined) notFound(resource, input.id, helpers);\n const id = row[resource.idField];\n for (const child of loaded)\n row[child.name] = await tx\n .select()\n .from(child.table)\n .where(eq(child.parent, id));\n\n const decision = decide(row, input);\n if (decision instanceof ActionExecutionError) throw decision;\n const { set, children, emit } = (decision ?? {}) as CommandDecision<\n any,\n Record<string, unknown>\n >;\n // Every event is checked before anything is written.\n const emits = Object.entries(emit ?? {})\n .filter(([, payload]) => payload !== undefined)\n .map(([key, payload]) => {\n const ref = Object.hasOwn(events, key) ? events[key] : undefined;\n if (!ref)\n throw new Error(\n `${where} emits '${key}', which is not in the event catalog of service '${service.name}'`,\n );\n checkPayload(ref, payload);\n return [ref.name, payload] as const;\n });\n if (emits.length && !record)\n throw new Error(\n `${where} emits events, but service '${service.name}' records none: give its database an outbox table and the app \\`events\\``,\n );\n\n if (set && Object.keys(set).length)\n await tx.update(resource.table).set(set).where(eq(resource.id, id));\n for (const [childName, changes] of Object.entries(children ?? {})) {\n if (!changes) continue;\n const child = childInfo(resource, childName, where);\n const own = eq(child.parent, id);\n if (changes.insert?.length)\n await tx.insert(child.table).values(\n changes.insert.map((item) => ({\n ...item,\n [child.parentField]: id,\n })),\n );\n for (const item of changes.update ?? []) {\n const { [child.idField]: childId, ...values } = item as Record<\n string,\n unknown\n >;\n if (childId === undefined)\n throw new Error(\n `${where}: an update of child '${childName}' needs its '${child.idField}'`,\n );\n if (Object.keys(values).length)\n await tx\n .update(child.table)\n .set(values)\n .where(and(eq(child.id, childId), own));\n }\n if (changes.delete?.length)\n await tx\n .delete(child.table)\n .where(and(inArray(child.id, changes.delete), own));\n }\n for (const [eventName, payload] of emits)\n await record!(eventName, payload);\n\n if (!config.output) return { id };\n const [updated] = await tx\n .select()\n .from(resource.table)\n .where(eq(resource.id, id))\n .limit(1);\n for (const child of loaded)\n updated[child.name] = await tx\n .select()\n .from(child.table)\n .where(eq(child.parent, id));\n return Value.Clean(config.output, updated);\n };\n return recorder\n ? recorder.transaction(\n db,\n {\n traceId: ctx.traceId,\n source: crudEventSource(service.name, resource.name),\n },\n body,\n )\n : runInTransaction(db, (tx) => body(tx));\n };\n\n const action = defineResourceAction(\n service,\n resource,\n {\n name,\n record: true,\n description: config.description,\n tags: config.tags,\n input: config.input,\n output: config.output ?? Type.Object({ id: idSchema(resource.id) }),\n errors: config.errors,\n ...(config.access === undefined ? {} : { access: config.access }),\n ...(config.authorize ? { authorize: config.authorize } : {}),\n execute: () => undefined,\n } as ResourceActionConfig<any, any, any, any, any, boolean>,\n run,\n );\n Object.assign(action, { decide });\n return action;\n}\n\n/** Declares a resource: a plugin host over a table, with its own `action()` and `command()`. */\nexport function defineResource<\n TTable = any,\n TCtx extends ActionContext = ActionContext,\n const O extends ResourceTypeOptions = ResourceTypeOptions,\n>(\n service: Service<any, any>,\n config: ResourceConfig<TTable, TCtx> & O,\n): Resource<TTable, TCtx, ResourceIdentity<TTable, O>> {\n const columns = getTableColumns(\n config.table as Parameters<typeof getTableColumns>[0],\n );\n const id: Column | undefined = config.id ?? primaryColumn(config.table)?.[1];\n const entry = Object.entries(columns).find(([, column]) => column === id);\n if (!entry || !id)\n throw new Error(\n `Resource '${config.name}' requires an id column belonging to its table`,\n );\n if (\n !config.name ||\n config.name.includes(\"/\") ||\n [\"__proto__\", \"constructor\", \"prototype\"].includes(config.name)\n )\n throw new Error(`Invalid resource name '${config.name}'`);\n portOf(service).registerTable(config.table);\n const resource = {\n name: config.name,\n serviceName: service.name,\n table: config.table,\n id,\n idField: entry[0],\n config: Object.freeze({ ...config, id }),\n use(plugin: ResourcePlugin<any, any, any>) {\n return installPlugin(\n service,\n resource as unknown as Resource<\n TTable,\n TCtx,\n ResourceIdentity<TTable, O>\n >,\n plugin,\n );\n },\n action(\n actionConfig: ResourceActionConfig<any, any, any, any, any, boolean>,\n ) {\n return defineResourceAction(\n service,\n resource as unknown as Resource<any, any, any>,\n actionConfig,\n );\n },\n command(name: string, commandConfig: CommandConfig<any, any, any, any>) {\n return defineCommand(\n service,\n resource as unknown as Resource<any, any, any>,\n name,\n commandConfig as CommandConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n readonly string[]\n >,\n );\n },\n };\n return resource as unknown as Resource<\n TTable,\n TCtx,\n ResourceIdentity<TTable, O>\n >;\n}\n","import {\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp,\n} from \"drizzle-orm/pg-core\";\nimport {\n integer as sqliteInteger,\n sqliteTable,\n text as sqliteText,\n} from \"drizzle-orm/sqlite-core\";\n\nconst SCHEDULES = Symbol.for(\"brick.schedules\");\n\n/** One finished run of a schedule, as the schedule table keeps it. */\nexport interface ScheduleRunRecord {\n /** The time the run was due, as an ISO timestamp. */\n slot: string;\n trigger: \"schedule\" | \"manual\";\n attempt: number;\n startedAt: string;\n finishedAt: string;\n /** `skipped`: a slot missed while no process ran, with `catchUp: \"skip\"`. */\n outcome: \"succeeded\" | \"failed\" | \"skipped\";\n error?: string;\n}\n\nfunction sqliteSchedules(name: string) {\n const at = (column: string) =>\n sqliteInteger(column, { mode: \"timestamp_ms\" });\n return sqliteTable(name, {\n name: sqliteText(\"name\").primaryKey(),\n spec: sqliteText(\"spec\").notNull(),\n slot: at(\"slot\").notNull(),\n nextAt: at(\"next_at\").notNull(),\n attempts: sqliteInteger(\"attempts\").notNull().default(0),\n trigger: sqliteText(\"trigger\")\n .$type<ScheduleRunRecord[\"trigger\"]>()\n .notNull(),\n runId: sqliteText(\"run_id\"),\n startedAt: at(\"started_at\"),\n leaseUntil: at(\"lease_until\"),\n lastSuccessAt: at(\"last_success_at\"),\n runs: sqliteText(\"runs\", { mode: \"json\" })\n .$type<ScheduleRunRecord[]>()\n .notNull(),\n });\n}\n\nfunction postgresSchedules(name: string) {\n const at = (column: string) => timestamp(column, { withTimezone: true });\n return pgTable(name, {\n name: pgText(\"name\").primaryKey(),\n spec: pgText(\"spec\").notNull(),\n slot: at(\"slot\").notNull(),\n nextAt: at(\"next_at\").notNull(),\n attempts: pgInteger(\"attempts\").notNull().default(0),\n trigger: pgText(\"trigger\").$type<ScheduleRunRecord[\"trigger\"]>().notNull(),\n runId: pgText(\"run_id\"),\n startedAt: at(\"started_at\"),\n leaseUntil: at(\"lease_until\"),\n lastSuccessAt: at(\"last_success_at\"),\n runs: jsonb(\"runs\").$type<ScheduleRunRecord[]>().notNull(),\n });\n}\n\n/** The schedule table of a SQLite database. */\nexport type SQLiteScheduleTable = ReturnType<typeof sqliteSchedules>;\n/** The schedule table of a Postgres database. */\nexport type PostgresScheduleTable = ReturnType<typeof postgresSchedules>;\n/** A schedule table, made by `scheduleTable`. */\nexport type ScheduleTable = SQLiteScheduleTable | PostgresScheduleTable;\nexport type ScheduleRow = ScheduleTable[\"$inferSelect\"];\n\n/**\n * The schedule table: one row per schedule, holding when it is next due, which\n * process is running it, and its last runs. Processes that share the table\n * share the schedules: each due time runs once among them, and a restart\n * picks up where the last process stopped.\n *\n * Brick does not create tables for you. Put it in the schema of one of the\n * app's databases, and your migration tool (such as drizzle-kit) creates it.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_schedules`.\n * @returns A Drizzle table.\n * @example\n * import { defineDatabase, outboxTable, scheduleTable } from \"@brickkit/core\";\n *\n * export const schedules = scheduleTable(\"postgres\");\n * export const database = defineDatabase({\n * engine: \"postgres\",\n * tables: { users, schedules },\n * });\n */\nexport function scheduleTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteScheduleTable;\nexport function scheduleTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresScheduleTable;\nexport function scheduleTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): ScheduleTable {\n const name = options.name ?? \"brick_schedules\";\n const table =\n engine === \"sqlite\" ? sqliteSchedules(name) : postgresSchedules(name);\n Object.defineProperty(table, SCHEDULES, { value: { engine } });\n return table;\n}\n\n/** Whether a value is a table made by `scheduleTable`. */\nexport function isScheduleTable(value: unknown): value is ScheduleTable {\n return typeof value === \"object\" && value !== null && SCHEDULES in value;\n}\n","import { installPlugin, isInstallingPlugin } from \"./plugin\";\nimport type { ServicePlugin } from \"./plugin-types\";\nimport type { BunSQLiteDatabase } from \"./db/sqlite\";\nimport type {\n Service,\n ServiceOptions,\n Action,\n Tool,\n ActionErrorDefinition,\n ServiceSchema,\n BaseContext,\n Resource,\n PreparationContribution,\n} from \"./types\";\nimport { defineTool, isTool } from \"./tool\";\nimport { defineAction } from \"./action\";\nimport { claimName, definitionSite } from \"./definition-site\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getTableName, isDatabaseHandle, type DatabaseHandle } from \"./db\";\nimport { checkRecordAccess, defineResource } from \"./resource\";\nimport { actionMeta } from \"./action-meta\";\nimport { actionOwners } from \"./routes\";\nimport type { ServicePort } from \"./service-port\";\nimport { isOutboxTable, type OutboxTable } from \"./events/outbox\";\nimport { isScheduleTable, type ScheduleTable } from \"./schedules/table\";\nimport type { ServiceEvents } from \"./events/types\";\nimport {\n checkEvent,\n eventRefs,\n type EventCatalog,\n type EventRef,\n} from \"./events/catalog\";\nimport { getActionAccess } from \"./access\";\nimport { pluginOwner } from \"./plugin-tables\";\nimport { baseContext, pickContextEnvelope } from \"./context\";\nimport type { DepsOf, Ports } from \"./deps\";\nimport type { NamedService } from \"./rpc\";\nimport { defineServiceSocket } from \"./socket\";\nimport type {\n BrickSocketConfig,\n BrickSocketHandle,\n SocketPayloads,\n SocketSchemas,\n RegisteredSocket,\n} from \"./socket-types\";\n\n// Symbol to tie context resolution to a specific service instance and invocation\nconst RESOLVED_SYMBOL = Symbol(\"resolved\");\n/** The deps a resolved context was resolved with, to restore them when a plugin's copy comes back. */\nconst OWN_DEPS = Symbol(\"ownDeps\");\n\n// The public overloads of `action`, `tool` and `resource`; the class implements them once, untyped.\n// Safe: the interface only adds signatures of methods the class defines.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\nexport interface ServiceImpl<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> extends Pick<Service<TDb, TServiceContext>, \"action\" | \"tool\" | \"resource\"> {}\nexport class ServiceImpl<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> implements ServicePort<TDb, TServiceContext> {\n readonly name: string;\n readonly options: ServiceOptions<TServiceContext, TDb>;\n private readonly actions = new Map<string, Action<any, any, any, any>>();\n private readonly tools = new Map<string, Tool<any, any, any, any>>();\n readonly tables = new Map<string, any>();\n private readonly sockets = new Map<string, RegisteredSocket>();\n private readonly resources = new Map<\n string,\n Resource<any, BaseContext<TDb> & TServiceContext>\n >();\n private readonly preparations = new Map<string, PreparationContribution>();\n /** Where each `kind:name` was defined, to reject duplicates from another file. */\n private readonly sites = new Map<string, string | undefined>();\n private database?: DatabaseHandle<TDb>;\n private _isBuilt = false;\n private _events: Readonly<Record<string, EventRef>>;\n /** What a write needs to record events. Set by `brick({ events })`. */\n recorder?: ServiceEvents;\n /** The values of this service's `deps`. Set by `brick({ deps })`. */\n deps?: Readonly<Record<string, unknown>>;\n\n constructor(\n name: string,\n options: ServiceOptions<TServiceContext, TDb> = {},\n ) {\n this.name = name;\n this.options = options;\n this._events = eventRefs(name, options.events);\n for (const key of Object.keys(this._events)) this.claim(\"event\", key);\n if (options.database !== undefined && !isDatabaseHandle(options.database)) {\n throw new Error(\"Service database must be created with defineDatabase()\");\n }\n this.database = options.database;\n }\n\n /** The declared events: `service.events.<name>`. */\n get events(): Readonly<Record<string, EventRef>> {\n return this._events;\n }\n\n use<A>(plugin: ServicePlugin<this, A>): A {\n return installPlugin(this, undefined, plugin) as A;\n }\n\n get db(): TDb | undefined {\n return this.getDb();\n }\n\n get isBuilt(): boolean {\n return this._isBuilt;\n }\n\n /** Every definition change passes here, so cached architecture and OpenAPI are rebuilt. */\n touch(): void {\n getGlobalRegistry().touch();\n }\n\n snapshot(): () => void {\n const maps = [\n this.actions,\n this.tools,\n this.tables,\n this.sockets,\n this.resources,\n this.preparations,\n this.sites,\n ] as Map<unknown, unknown>[];\n const saved = maps.map((map) => new Map(map));\n const events = this._events;\n const properties = new Map(\n [...this.resources.values()].map((item) => [\n item,\n Object.getOwnPropertyDescriptors(item),\n ]),\n );\n return () => {\n maps.forEach((map, index) => {\n map.clear();\n for (const [key, value] of saved[index]!) map.set(key, value);\n });\n this._events = events;\n for (const [item, own] of properties) {\n for (const key of Reflect.ownKeys(item))\n if (!Object.hasOwn(own, key)) Reflect.deleteProperty(item, key);\n Object.defineProperties(item, own);\n }\n this.touch();\n };\n }\n\n addEvents(refs: Readonly<Record<string, EventRef>>): void {\n this._events = Object.freeze({ ...this._events, ...refs });\n this.touch();\n }\n\n /**\n * Closes declarations after plugins have registered their actions and preparations.\n */\n build(): this {\n if (isInstallingPlugin(this))\n throw new Error(\"Cannot build a service during plugin setup\");\n if (this._isBuilt) return this;\n for (const action of this.actions.values()) {\n const info = actionMeta(action).resourceAction;\n const resource = info?.record && this.resources.get(info.resource);\n if (resource) checkRecordAccess(resource, info);\n }\n this._isBuilt = true;\n return this;\n }\n\n private claim(kind: string, name: string): void {\n claimName(\n this.sites,\n `${kind} \"${name}\" in service \"${this.name}\"`,\n `${kind}:${name}`,\n definitionSite(),\n );\n }\n\n contributePreparation(contribution: PreparationContribution): void {\n if (this._isBuilt)\n throw new Error(\"Preparations must be registered before service build\");\n if (this.preparations.has(contribution.name))\n throw new Error(`Duplicate preparation '${contribution.name}'`);\n this.preparations.set(contribution.name, contribution);\n this.touch();\n }\n\n listPreparations(): PreparationContribution[] {\n return [...this.preparations.values()];\n }\n prepareContributions(): void {\n for (const contribution of this.preparations.values())\n contribution.prepare();\n }\n\n registerTable(table: any): this {\n this.tables.set(getTableName(table), table);\n this.touch();\n return this;\n }\n\n resource(config: any): any {\n if (this._isBuilt)\n throw new Error(\"Resources must be registered before service build\");\n this.claim(\"resource\", config.name);\n const resourceInstance = defineResource(this, config);\n this.resources.set(resourceInstance.name, resourceInstance as any);\n this.touch();\n return resourceInstance;\n }\n\n getResource(\n name: string,\n ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined {\n return this.resources.get(name);\n }\n\n listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[] {\n return Array.from(this.resources.values());\n }\n\n action(actionOrConfig: any): any {\n const isActionFunction =\n typeof actionOrConfig === \"function\" && \"config\" in actionOrConfig;\n const actionInstance: Action<any, any, any, any> = isActionFunction\n ? actionOrConfig\n : defineAction(actionOrConfig);\n\n if (this.actions.get(actionInstance.name) !== actionInstance)\n this.claim(\"action\", actionInstance.name);\n if (isTool(actionInstance)) actionInstance.config.http = true;\n actionInstance.serviceName = this.name;\n actionMeta(actionInstance).service = this;\n this.actions.set(actionInstance.name, actionInstance);\n this.touch();\n return isActionFunction ? this : actionInstance;\n }\n\n tool(toolOrConfig: any): any {\n const existing = isTool(toolOrConfig);\n const tool = existing ? toolOrConfig : defineTool(toolOrConfig);\n this.claim(\"tool\", tool.name);\n tool.serviceName = this.name;\n actionMeta(tool).service = this;\n this.tools.set(tool.name, tool);\n if (tool.config.http) this.action(tool);\n this.touch();\n return existing ? this : tool;\n }\n\n getTool(name: string): Tool<any, any, any, any> | undefined {\n return this.tools.get(name);\n }\n\n socket<\n const I extends SocketSchemas,\n const O extends SocketSchemas,\n const E extends Record<string, ActionErrorDefinition> = {},\n >(\n config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext, E>,\n ): BrickSocketHandle<SocketPayloads<O>> {\n if (this._isBuilt)\n throw new Error(\"Sockets must be declared before service build\");\n this.claim(\"socket\", config.name);\n const socket: RegisteredSocket = defineServiceSocket(\n this.name,\n config,\n (request) => resolveServiceContext(this, { request }, socket.deps),\n );\n this.sockets.set(config.name, socket);\n this.touch();\n return socket.handle;\n }\n\n listSockets(): RegisteredSocket[] {\n return [...this.sockets.values()];\n }\n\n listTools(): Tool<any, any, any, any>[] {\n return Array.from(this.tools.values());\n }\n\n getAction(name: string): Action<any, any, any, any> | undefined {\n return this.actions.get(name);\n }\n\n listActions(): Action<any, any, any, any>[] {\n return Array.from(new Set(this.actions.values()));\n }\n\n getDb(): TDb | undefined {\n return this.database?.getDb();\n }\n\n /** The handle from `defineDatabase`, without connecting. */\n getDatabaseHandle(): DatabaseHandle<TDb> | undefined {\n return this.database;\n }\n\n getOutbox(): OutboxTable | undefined {\n return Object.values(this.database?.tables ?? {}).find(isOutboxTable);\n }\n\n getScheduleTable(): ScheduleTable | undefined {\n return Object.values(this.database?.tables ?? {}).find(isScheduleTable);\n }\n\n setRecorder(recorder: ServiceEvents | undefined): void {\n this.recorder = recorder;\n }\n\n get hasCatalog(): boolean {\n return this.options.events !== undefined;\n }\n\n /** @throws When the event is not in the catalog or its payload does not match. */\n checkEvent(name: string, payload: unknown): void {\n checkEvent(this, name, payload);\n }\n\n setDeps(deps: Readonly<Record<string, unknown>>): void {\n this.deps = deps;\n }\n\n setDb(database: DatabaseHandle<TDb>): void {\n if (!isDatabaseHandle(database))\n throw new Error(\"Use defineDatabase() to set a service database\");\n this.database = database;\n this.touch();\n }\n\n /**\n * Resolves the complete service execution context once per incoming request.\n * Merges framework BaseContext with the service's custom context hook.\n * Always rebuilds context for this service to prevent caller context from overriding.\n */\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n pluginDeps?: Readonly<Record<string, unknown>>,\n ): Promise<BaseContext<TDb> & TServiceContext> {\n return resolveServiceContext(this, callCtx, pluginDeps);\n }\n\n introspect(): ServiceSchema {\n const databaseConfig = this.database\n ? {\n name: this.database.name,\n engine: this.database.engine,\n tables: Object.keys(this.database.tables),\n ...pluginTables(this.database.tables),\n }\n : undefined;\n // The schema is data. A function among the options (such as `context`)\n // cannot cross to the dev dashboard: structured clone\n // refuses the whole architecture. JSON keeps the data and drops the rest.\n const { database: _database, events: _events, ...config } = this.options;\n const options: ServiceSchema[\"options\"] = JSON.parse(\n JSON.stringify(config),\n );\n return {\n name: this.name,\n options,\n hasDatabase: Boolean(this.database),\n sockets: this.listSockets().map((socket) => socket.schema),\n databaseConfig,\n actions: this.listActions().map((act) => {\n const access = getActionAccess(act);\n return {\n name: act.name,\n serviceName: this.name,\n ...actionOwners(act),\n description: act.config.description,\n inputSchema: act.config.input,\n outputSchema: act.config.output,\n hasAuthorize: access.hasAuthorize,\n hasScope: access.hasScope,\n accessPolicy: access.policy,\n errors: act.config.errors,\n emits: act.config.emits,\n tags: act.config.tags,\n };\n }),\n tools: this.listTools().map((tool) => ({ name: tool.name })),\n ...(this.hasCatalog || Object.keys(this.events).length\n ? {\n events: Object.values(this.events).map((ref) => ({\n name: ref.name,\n schema: JSON.parse(JSON.stringify(ref.schema)),\n ...(ref.plugin ? { plugin: ref.plugin } : {}),\n })),\n }\n : {}),\n resources: this.listResources().map((res) => ({\n name: res.name,\n })),\n };\n }\n}\n\n/** `plugins`: which plugin owns each table it contributed, by table key. */\nfunction pluginTables(tables: Record<string, unknown>) {\n const owners = Object.entries(tables).flatMap(([key, table]) => {\n const plugin = pluginOwner(table);\n return plugin ? [[key, plugin] as const] : [];\n });\n return owners.length ? { plugins: Object.fromEntries(owners) } : {};\n}\n\n/**\n * The context of a call to one of the service's actions or sockets. The one\n * rule for which deps it sees: those of the plugin install that created the\n * action or socket (`pluginDeps`), else the service's own. The service's\n * `context` hook always sees the service's own.\n */\nasync function resolveServiceContext<\n TDb,\n TServiceContext extends Record<string, any>,\n>(\n service: ServiceImpl<TDb, TServiceContext>,\n callCtx?: Partial<BaseContext<TDb>> & { user?: unknown },\n pluginDeps?: Readonly<Record<string, unknown>>,\n): Promise<BaseContext<TDb> & TServiceContext> {\n // Only a context this service resolved itself is accepted as it is.\n if ((callCtx as any)?.[RESOLVED_SYMBOL] === service) {\n const deps = pluginDeps ?? (callCtx as any)[OWN_DEPS];\n return (\n (callCtx as { deps?: unknown }).deps === deps\n ? callCtx\n : { ...callCtx, deps }\n ) as BaseContext<TDb> & TServiceContext;\n }\n const framework = baseContext({\n request: callCtx?.request,\n // Always this service's own database, never the caller's.\n db: service.getDb(),\n logger: callCtx?.logger,\n traceId: callCtx?.traceId,\n requestId: callCtx?.requestId,\n services: callCtx?.services,\n metadata: callCtx?.metadata,\n // The app's deps for this service; a direct call with no app (a unit test) may pass its own,\n // but never those of a context another service (or a plugin) resolved.\n deps:\n service.deps ??\n ((callCtx as any)?.[RESOLVED_SYMBOL]\n ? undefined\n : (callCtx as { deps?: Readonly<Record<string, unknown>> } | undefined)\n ?.deps),\n });\n const fullBaseCtx: BaseContext<TDb> = {\n ...framework,\n ...pickContextEnvelope(callCtx),\n };\n\n const resolvedExtra = service.options.context\n ? await service.options.context(fullBaseCtx)\n : {};\n const finalCtx: any = {\n ...fullBaseCtx,\n ...resolvedExtra,\n deps: pluginDeps ?? framework.deps,\n [RESOLVED_SYMBOL]: service,\n [OWN_DEPS]: framework.deps,\n };\n return finalCtx;\n}\n\n/**\n * Declare a service: a named group of actions, tools, and resources with its own\n * database and request context. It is registered globally, so `brick()`, the\n * OpenAPI generator, and `useService` find it by name.\n *\n * Add actions with `service.action(...)`, tools with `service.tool(...)`,\n * resources with `service.resource(...)`, and plugins with `service.use(...)`.\n *\n * @param name - Unique name. It is the service's segment of every action route\n * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it\n * again from the same file (a dev reload) replaces it; from another file throws.\n * @param options - `database` (a handle from `defineDatabase`), `deps` (typed\n * slots from `port<T>()` that `brick({ deps })` fills, read as `ctx.deps`),\n * `context` (adds fields such as the signed-in user to every action's `ctx`),\n * `events` (the event catalog: a payload schema per event name, recorded as\n * `<service>.<name>` and offered as `service.events.<name>`).\n * @returns The service.\n * @example\n * import { defineDatabase, defineService, t } from \"@brickkit/core\";\n *\n * const database = defineDatabase({ tables: { pages } });\n *\n * export const pagesService = defineService(\"pages\", {\n * database,\n * // Added to `ctx` in every action of this service.\n * context: async ({ request }) => ({ user: await readUser(request) }),\n * });\n *\n * pagesService.action({\n * name: \"list\",\n * input: t.Object({ limit: t.Optional(t.Number()) }),\n * output: t.Array(t.Object({ id: t.String(), title: t.String() })),\n * execute: ({ input, ctx }) =>\n * ctx.db.select().from(pages).limit(input.limit ?? 20),\n * });\n */\nexport function defineService<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n const TEvents extends EventCatalog = {},\n const TName extends string = string,\n TPorts extends Ports = {},\n>(\n name: TName,\n options?: ServiceOptions<TServiceContext, TDb> & {\n events?: TEvents;\n deps?: TPorts;\n },\n): Service<\n TDb,\n {} extends TPorts\n ? TServiceContext\n : TServiceContext & { deps: DepsOf<TPorts> },\n TEvents\n> &\n NamedService<TName> {\n const service = new ServiceImpl<TDb, TServiceContext>(name, options);\n getGlobalRegistry().register(service as any);\n return service as any;\n}\n","import { compareSocketSeq } from \"./protocol\";\nimport type { SocketBroker, SocketBrokerMessage } from \"./socket-types\";\n\n// From the global, as @types/bun doesn't export RedisClient from \"bun\" for the .d.ts build.\ntype RedisClient = InstanceType<typeof Bun.RedisClient>;\n\nexport interface RedisBrokerOptions {\n /** Defaults to `REDIS_URL`, then `redis://localhost:6379`. */\n url?: string;\n /** Emits held while Redis is unreachable; older ones are dropped. Default 1000. */\n queue?: number;\n}\n\n/** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */\nexport function reconnectDelay(failures: number): number {\n const ceiling = Math.min(30_000, 500 * 2 ** failures);\n return ceiling / 2 + Math.random() * (ceiling / 2);\n}\n\n/** How long a call waits for Redis to connect before going on without it. */\nconst REDIS_WAIT_MS = 1000;\n\n/** One Redis connection that reconnects by itself and reports each fresh connection. */\nexport function connection(\n url: string | undefined,\n connected: (redis: RedisClient) => void,\n) {\n let redis: RedisClient | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let failures = 0;\n const waiters: (() => void)[] = [];\n const lost = (client: RedisClient) => {\n if (redis !== client) return;\n redis = undefined;\n if (closed || timer) return;\n timer = setTimeout(() => {\n timer = undefined;\n start();\n }, reconnectDelay(failures++));\n };\n const start = () => {\n if (closed || redis || timer) return;\n // Bun's own reconnect keeps no subscriptions we can see; a fresh client resubscribes explicitly.\n const client = new Bun.RedisClient(url, {\n autoReconnect: false,\n enableOfflineQueue: false,\n });\n redis = client;\n client.onclose = () => lost(client);\n client.connect().then(\n () => {\n if (redis !== client) return;\n failures = 0;\n connected(client);\n for (const wake of waiters.splice(0)) wake();\n },\n () => lost(client),\n );\n };\n return {\n get(): RedisClient | undefined {\n start();\n return redis?.connected ? redis : undefined;\n },\n /** Resolves after the next connection is made and announced, or after `ms`. */\n opened(ms: number): Promise<void> {\n if (redis?.connected) return Promise.resolve();\n start();\n return new Promise((resolve) => {\n const timeout = setTimeout(resolve, ms);\n waiters.push(() => {\n clearTimeout(timeout);\n resolve();\n });\n });\n },\n close() {\n closed = true;\n clearTimeout(timer);\n for (const wake of waiters.splice(0)) wake();\n const client = redis;\n redis = undefined;\n client?.close();\n },\n };\n}\n\n/**\n * Fans socket emits and kicks out across processes through Redis pub/sub, one\n * channel per room topic. An emit is a PUBLISH only: every process, the emitting\n * one included, delivers it once to its own connections. Uses Bun's built-in\n * Redis client and two connections, one to publish and one to subscribe.\n */\nexport function redisBroker(options: RedisBrokerOptions = {}): SocketBroker {\n const limit = options.queue ?? 1000;\n if (!Number.isInteger(limit) || limit < 0)\n throw new Error(\"redisBroker queue must be a nonnegative integer\");\n const channel = (topic: string) => `brick:socket:${topic}`;\n const listeners = new Map<\n string,\n Set<(message: SocketBrokerMessage) => void>\n >();\n const pending = new Map<string, Promise<unknown>>();\n const stream = (topic: string) => `brick:socket:stream:${topic}`;\n // Failures stay non-fatal (an emit is best effort) but leave a trace, once per kind.\n const warned = new Set<string>();\n const warn = (what: string) => (error: unknown) => {\n if (warned.has(what)) return;\n warned.add(what);\n console.warn(\n `[Brick-TS] Redis socket broker: ${what} failed; later failures of it are not logged.`,\n error,\n );\n };\n const queue: ((redis: RedisClient) => void)[] = [];\n const send = (work: (redis: RedisClient) => void) => {\n const redis = publisher.get();\n if (redis) return work(redis);\n queue.push(work);\n if (queue.length > limit) queue.shift();\n };\n const receive = (payload: string, name: string) => {\n let message: SocketBrokerMessage;\n try {\n message = JSON.parse(payload);\n } catch {\n return;\n }\n for (const deliver of listeners.get(name) ?? []) deliver(message);\n };\n const subscribe = (redis: RedisClient, name: string) => {\n const done = redis.subscribe(name, receive).catch(warn(\"SUBSCRIBE\"));\n pending.set(name, done);\n void done.then(() => {\n if (pending.get(name) === done) pending.delete(name);\n });\n };\n const publisher = connection(options.url, (redis) => {\n for (const work of queue.splice(0)) work(redis);\n });\n const subscriber = connection(options.url, (redis) => {\n for (const name of listeners.keys()) subscribe(redis, name);\n });\n return {\n publish(message, replay) {\n const name = channel(message.topic);\n if (message.type !== \"emit\" || !replay)\n return send(\n (redis) =>\n void redis\n .publish(name, JSON.stringify(message))\n .catch(warn(\"PUBLISH\")),\n );\n const key = stream(message.topic);\n send((redis) => {\n // Replies come back in order, so each PUBLISH follows its XADD in emit order.\n void redis\n .send(\"XADD\", [\n key,\n \"MAXLEN\",\n \"~\",\n String(replay.keep),\n \"*\",\n \"m\",\n message.frame,\n ])\n .then((seq: string) => {\n void redis\n .send(\"PEXPIRE\", [key, String(replay.maxAgeMs)])\n .catch(warn(\"PEXPIRE\"));\n return redis.publish(name, JSON.stringify({ ...message, seq }));\n })\n .catch(warn(\"XADD/PUBLISH\"));\n });\n },\n async head() {\n try {\n await publisher.opened(REDIS_WAIT_MS);\n const [seconds, micros] = (await publisher.get()!.send(\"TIME\", [])) as [\n string,\n string,\n ];\n return `${Number(seconds) * 1000 + Math.floor(Number(micros) / 1000) - 1}-0`;\n } catch {\n return `${Date.now() - 1}-0`;\n }\n },\n async history(topic, since, replay) {\n let raw: [string, string[]][];\n try {\n await publisher.opened(REDIS_WAIT_MS);\n raw = await publisher.get()!.send(\"XRANGE\", [stream(topic), \"-\", \"+\"]);\n } catch {\n return undefined;\n }\n const ms = (seq: string) => Number(seq.split(\"-\")[0]);\n const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);\n // Nothing kept at or before `since`: entries after it may have been trimmed or expired.\n if (\n after.length === raw.length &&\n (raw.length >= replay.keep ||\n (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)\n )\n return undefined;\n return after.map(([seq, fields]) => ({\n type: \"emit\" as const,\n topic,\n frame: fields[fields.indexOf(\"m\") + 1]!,\n seq,\n }));\n },\n subscribe(topic, deliver) {\n const name = channel(topic);\n let local = listeners.get(name);\n if (!local) {\n local = new Set();\n listeners.set(name, local);\n const redis = subscriber.get();\n if (redis) subscribe(redis, name);\n }\n local.add(deliver);\n return () => {\n local.delete(deliver);\n if (local.size || listeners.get(name) !== local) return;\n listeners.delete(name);\n pending.delete(name);\n void subscriber.get()?.unsubscribe(name).catch(warn(\"UNSUBSCRIBE\"));\n };\n },\n async ready(topic) {\n const name = channel(topic);\n // Wait briefly for Redis, so a join is acknowledged once its emits can arrive.\n if (!pending.has(name)) await subscriber.opened(REDIS_WAIT_MS);\n await pending.get(name);\n },\n close() {\n publisher.close();\n subscriber.close();\n },\n };\n}\n","import { ATTR, SPAN } from \"./telemetry-names\";\nimport type { Action, ActionContext, ProxyOptions, Service } from \"./types\";\nimport type {\n BrickClientAction,\n BrickClientSocket,\n BrickServices,\n InferActionInput,\n InferActionOutput,\n} from \"./client\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getPluginActionRoute } from \"./routes\";\nimport { pickContextEnvelope } from \"./context\";\nimport { withCallSpan } from \"./telemetry\";\n\n/** An in-process caller for one action: its input, then an optional call context. */\nexport type ServiceActionCaller<A> =\n undefined extends InferActionInput<A>\n ? (\n input?: InferActionInput<A>,\n ctx?: Partial<ActionContext>,\n ) => Promise<InferActionOutput<A>>\n : (\n input: InferActionInput<A>,\n ctx?: Partial<ActionContext>,\n ) => Promise<InferActionOutput<A>>;\n\n/**\n * What `useService` returns: the service's actions as methods, with each\n * resource's actions under the resource's name. Sockets are left out.\n */\nexport type ServiceClient<T> = {\n [\n K in keyof T as T[K] extends BrickClientSocket<any, any> ? never : K\n ]: T[K] extends\n | BrickClientAction<any, any, any>\n | Action<any, any, any, any>\n | ((...args: any[]) => any)\n ? ServiceActionCaller<T[K]>\n : ServiceClient<T[K]>;\n};\n\ndeclare const serviceNameType: unique symbol;\n\n/** Type only: the literal name of a service, which `useService` finds its contract by. */\nexport interface NamedService<N extends string> {\n readonly [serviceNameType]?: N;\n}\n\n/** What `useService` returns while the contract does not describe the service yet. */\nexport type UntypedServiceClient = { [name: string]: any };\n\n/**\n * Call another service's actions in-process, typed from that service. Each\n * action is a method, and each resource's actions sit under the resource's\n * name: `billing.charge(input)`, `billing.invoice.list()`.\n *\n * The types come from the app's generated contract (`_brick/contract.ts`, which\n * `brick dev` and `brick gen client` keep current), so renaming an action or\n * changing its input is a compile error at every caller. Until the contract\n * describes the service, the client is untyped.\n *\n * A call runs through the target's own validation and authorization, with the\n * target's database, context and deps (never the caller's), and shows as an\n * `rpc` span in the trace.\n *\n * @param service - The service to call, as `defineService` returned it.\n * @param options - `from` (the calling service's name, which becomes `ctx.caller`\n * in the target and cannot be spoofed) and `context` (defaults for every call).\n * Each call also takes an optional call context after its input.\n * @returns The client.\n * @throws On a call, when the service is not registered or has no such action.\n * @example\n * import { useService } from \"@brickkit/core\";\n * import { billingService } from \"../billing/billing.service\";\n *\n * const billing = useService(billingService, { from: \"orders\" });\n * await billing.charge({ orderId, amountCents });\n * await billing.invoice.list({ limit: 10 });\n */\nexport function useService<const N extends string = string>(\n service: { readonly name: string } & NamedService<N>,\n options: ProxyOptions = {},\n): N extends keyof BrickServices\n ? ServiceClient<BrickServices[N]>\n : UntypedServiceClient {\n return serviceRef(service.name, options, []);\n}\n\nfunction serviceRef(\n serviceName: string,\n options: ProxyOptions,\n path: readonly string[],\n): any {\n return new Proxy(function () {}, {\n get(_, key) {\n // Only string keys name actions; `then` stays unset so the client is not a promise.\n if (typeof key !== \"string\" || key === \"then\") return undefined;\n return serviceRef(serviceName, options, [...path, key]);\n },\n apply(_, __, [payload, callCtx]) {\n const name = path.join(\".\");\n const clientPath = [serviceName, ...path].join(\".\");\n return callAction(\n serviceName,\n name,\n (service) =>\n service.getAction(name) ??\n // Plugin actions (CRUD) are found by the path the typed client uses.\n service\n .listActions()\n .find(\n (action) =>\n (getPluginActionRoute(action) || undefined)?.clientPath?.join(\n \".\",\n ) === clientPath,\n ),\n payload,\n callCtx,\n options,\n );\n },\n });\n}\n\nasync function callAction(\n serviceName: string,\n actionName: string,\n find: (service: Service<any, any>) => Action<any, any, any, any> | undefined,\n payload: unknown,\n callCtx: Partial<ActionContext> | undefined,\n options: ProxyOptions,\n) {\n const service = getGlobalRegistry().get(serviceName);\n if (!service) {\n throw new Error(\n `[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`,\n );\n }\n const action = find(service);\n if (!action) {\n throw new Error(\n `[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`,\n );\n }\n const envelopeCtx = createRpcEnvelope(options.from, options.context, callCtx);\n return withCallSpan(\n `${SPAN.rpcPrefix}${serviceName}.${actionName}`,\n { [ATTR.service]: serviceName, [ATTR.action]: actionName },\n () => action.execute({ input: payload, ctx: envelopeCtx }),\n );\n}\n\n/** Build the trusted envelope for a proxy call.\n *\n * When `from` is provided, it identifies the service that created the proxy\n * and always sets `caller` — any `caller` supplied via `options.context` or\n * the per-call context is ignored so it cannot be spoofed. When `from` is\n * omitted, an explicitly supplied `caller` still passes through for backward\n * compatibility; otherwise `caller` stays unset (never the target service).\n */\nexport function createRpcEnvelope(\n from: string | undefined,\n defaultContext?: Partial<ActionContext>,\n callContext?: Partial<ActionContext>,\n): Partial<ActionContext> {\n const envelope = {\n ...pickContextEnvelope(defaultContext),\n ...pickContextEnvelope(callContext),\n } as Partial<ActionContext> & { caller?: string };\n if (from !== undefined) {\n envelope.caller = from;\n }\n return envelope;\n}\n","import { checkPayload, type EventRef } from \"./catalog\";\nimport { recordingServices } from \"./hub\";\n\n/**\n * Record an event of your own from an action, a tool or a hook. Listeners get it\n * as they get a generated CRUD event, with the payload you give.\n *\n * By default the event is committed in a transaction of its own. Pass the `tx`\n * of a transaction you have open to commit it with your writes instead: then it\n * is delivered at the dispatcher's next poll, because Brick does not see your\n * commit. Nothing is recorded when no listener wants the event.\n *\n * @param ctx - The action context: its `db` finds the service's outbox, and its\n * `traceId` follows the event to its listeners.\n * @param event - A declared event, such as `orders.events.shipped`, whose payload\n * is typed and checked against its schema; or an event name such as\n * `orders.refunded`. A service with an event catalog only records names from it\n * (and the CRUD events of its resources).\n * @param payload - JSON data for the listeners.\n * @param options - `tx`: an open transaction on the service's database. `source`:\n * what emitted it, shown to listeners.\n * @throws When the context's database has no outbox table, or the app has no\n * `events`; when the event is not in the service's catalog, or its payload does\n * not match the declared schema.\n * @example\n * refund: service.action({\n * name: \"refund\",\n * execute: async ({ ctx, input }) => {\n * await ctx.db.update(orders).set({ status: \"refunded\" }).where(eq(orders.id, input.id));\n * await emitEvent(ctx, orders.events.refunded, { id: input.id });\n * },\n * });\n */\nexport async function emitEvent<TPayload>(\n ctx: { db?: unknown; traceId?: string },\n event: EventRef<TPayload>,\n payload: NoInfer<TPayload>,\n options?: { tx?: unknown; source?: string },\n): Promise<void>;\nexport async function emitEvent(\n ctx: { db?: unknown; traceId?: string },\n name: string,\n payload: unknown,\n options?: { tx?: unknown; source?: string },\n): Promise<void>;\nexport async function emitEvent(\n ctx: { db?: unknown; traceId?: string },\n event: string | EventRef,\n payload: unknown,\n options: { tx?: unknown; source?: string } = {},\n): Promise<void> {\n const name = typeof event === \"string\" ? event : event.name;\n const service =\n ctx.db && typeof ctx.db === \"object\"\n ? recordingServices.get(ctx.db)\n : undefined;\n // The recording service checks its own events; one declared elsewhere is checked here.\n if (typeof event !== \"string\" && event.service !== service?.name)\n checkPayload(event, payload);\n const events = service?.recorder;\n if (!events)\n throw new Error(\n `Cannot emit '${name}': ctx.db is not the database of a service with an outbox table (the app needs events, and ctx.db must be the service's own database, not a transaction)`,\n );\n const context = { traceId: ctx.traceId, source: options.source };\n if (options.tx !== undefined)\n return events.record(options.tx, context, name, payload);\n await events.transaction(ctx.db, context, async (_tx, record) => {\n await record(name, payload);\n });\n}\n","import {\n DuplicateNameError,\n type ActionContext,\n type Service,\n type Tool,\n type ToolAnnotations,\n} from \"./types\";\n\nexport interface McpToolDefinition {\n name: string;\n title?: string;\n description: string;\n inputSchema: unknown;\n /** The tool's `output` schema; a non-object one is wrapped as `{ result }`. */\n outputSchema?: unknown;\n annotations: ToolAnnotations;\n}\n\nexport interface McpRegistryOptions {\n services?: readonly Pick<Service<any, any>, \"listTools\">[];\n tools?: readonly Tool<any, any, any, any>[];\n}\n\nexport interface McpRegistry {\n listTools(): McpToolDefinition[];\n callTool(\n name: string,\n args?: Record<string, unknown>,\n ctx?: Partial<ActionContext>,\n ): Promise<unknown>;\n}\n\nexport class UnknownToolError extends Error {\n constructor(name: string) {\n super(`unknown tool: ${name}`);\n this.name = \"UnknownToolError\";\n }\n}\n\n/** Collect only explicitly defined tools, without exposing ordinary actions. */\nexport function createMcpRegistry(options: McpRegistryOptions): McpRegistry {\n function toolsByName() {\n const tools = new Map<string, Tool<any, any, any, any>>();\n for (const tool of [\n ...(options.tools ?? []),\n ...(options.services ?? []).flatMap((service) => service.listTools()),\n ]) {\n const existing = tools.get(tool.name);\n if (existing && existing !== tool)\n throw new DuplicateNameError(`Duplicate MCP tool: ${tool.name}`);\n tools.set(tool.name, tool);\n }\n return tools;\n }\n toolsByName();\n return {\n listTools: () =>\n Array.from(toolsByName().values(), (tool) => ({\n name: tool.name,\n ...((tool.config.title ?? tool.config.annotations?.title)\n ? { title: tool.config.title ?? tool.config.annotations?.title }\n : {}),\n description: tool.config.description ?? \"\",\n inputSchema: tool.config.input ?? {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n ...(tool.config.output\n ? { outputSchema: outputSchema(tool.config.output) }\n : {}),\n annotations: tool.config.annotations ?? {},\n })),\n async callTool(name, args = {}, ctx) {\n const tool = toolsByName().get(name);\n if (!tool) throw new UnknownToolError(name);\n return tool({ input: args, ctx });\n },\n };\n}\n\n// MCP requires an object outputSchema, so other outputs travel as `{ result }`.\nconst WRAP_RESULT = \"x-brick-wrap-result\";\nfunction outputSchema(schema: { type?: unknown }) {\n return schema.type === \"object\"\n ? schema\n : {\n type: \"object\",\n properties: { result: schema },\n required: [\"result\"],\n [WRAP_RESULT]: true,\n };\n}\n\nexport interface McpHandlerOptions {\n registry: McpRegistry;\n serverInfo: { name: string; version: string; title?: string };\n /** Versions supported by this transport, newest first. */\n protocolVersions?: readonly string[];\n}\n\nfunction result(id: unknown, value: unknown) {\n return Response.json({ jsonrpc: \"2.0\", id, result: value });\n}\nfunction rpcError(id: unknown, code: number, message: string) {\n return Response.json({ jsonrpc: \"2.0\", id, error: { code, message } });\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */\nexport function createMcpHandler(options: McpHandlerOptions) {\n const versions = options.protocolVersions ?? [\"2025-06-18\"];\n if (!versions.length)\n throw new Error(\"At least one MCP protocol version is required\");\n return async (\n request: Request,\n ctx?: Partial<ActionContext>,\n ): Promise<Response> => {\n if (request.method !== \"POST\")\n return new Response(null, { status: 405, headers: { Allow: \"POST\" } });\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return rpcError(null, -32700, \"parse error\");\n }\n if (\n !isRecord(body) ||\n body.jsonrpc !== \"2.0\" ||\n typeof body.method !== \"string\" ||\n (body.id !== undefined &&\n body.id !== null &&\n typeof body.id !== \"string\" &&\n typeof body.id !== \"number\") ||\n (body.params !== undefined && !isRecord(body.params))\n ) {\n return rpcError(null, -32600, \"invalid request\");\n }\n if (body.id === undefined) return new Response(null, { status: 202 });\n const { id, method } = body;\n const params = body.params as Record<string, unknown> | undefined;\n switch (method) {\n case \"initialize\": {\n const requested = params?.protocolVersion;\n return result(id, {\n capabilities: { tools: {} },\n protocolVersion:\n typeof requested === \"string\" && versions.includes(requested)\n ? requested\n : versions[0],\n serverInfo: options.serverInfo,\n });\n }\n case \"ping\":\n return result(id, {});\n case \"tools/list\":\n try {\n return result(id, { tools: options.registry.listTools() });\n } catch {\n return rpcError(id, -32603, \"internal error\");\n }\n case \"tools/call\": {\n if (\n typeof params?.name !== \"string\" ||\n (params.arguments !== undefined && !isRecord(params.arguments))\n ) {\n return rpcError(id, -32602, \"invalid tool parameters\");\n }\n try {\n const value = await options.registry.callTool(\n params.name,\n params.arguments as Record<string, unknown> | undefined,\n { ...ctx, request },\n );\n const schema = options.registry\n .listTools()\n .find((tool) => tool.name === params.name)?.outputSchema as\n | Record<string, unknown>\n | undefined;\n return result(id, {\n content: [\n {\n type: \"text\",\n text:\n typeof value === \"string\"\n ? value\n : (JSON.stringify(value, null, 2) ?? \"null\"),\n },\n ],\n ...(schema\n ? {\n structuredContent: schema[WRAP_RESULT]\n ? { result: value }\n : value,\n }\n : {}),\n });\n } catch (error) {\n if (error instanceof UnknownToolError)\n return rpcError(id, -32602, error.message);\n return result(id, {\n content: [\n {\n type: \"text\",\n text: error instanceof Error ? error.message : String(error),\n },\n ],\n isError: true,\n });\n }\n }\n default:\n return rpcError(id, -32601, `method not found: ${method}`);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAGA,MAAa,aAAa,OAAO,IAAI,uBAAuB;AAiD5D,MAAa,aAAa,OAAO,KAAK;CARpC,cAAc;CACd,aAAa;CACb,cAAc;CACd,aAAa;CACb,cAAc;CACd,aAAa;CACb,aAAa;AAEuB,CAAK;;AAG3C,SAAgB,aAAa,MAAqC;CAChE,OAAQ,KAA+C;AACzD;;AAGA,SAAgB,aAAa,MAAc,OAAwB;CACjE,MAAM,QAAS,KAAoC,gBAAgB,CAAC;CACpE,KAAK,MAAM,QAAQ,YACjB,IAAI,MAAM,OACR,CAAC,MAAM,UAAU,CAAC,EAAA,CAAc,KAAK,GAAI,MAAM,KAAiB;AACtE;;AChDA,MAAM,QAAQ,OAAO,IAAI,uBAAuB;AAChD,SAAgB,eAAe,OAAe,QAAsB;CAClE,O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