@brickkit/core 0.16.0-beta.4 → 0.16.0-beta.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["warned","TypeBox","mac","sqliteInteger","sqliteText","pgText","sqliteInteger","sqliteText","sqliteIndex","pgText","pgInteger","pgIndex"],"sources":["../../src/plugin-types.ts","../../src/sensitive.ts","../../src/telemetry.ts","../../src/error-response.ts","../../src/typebox.ts","../../src/logger.ts","../../src/dashboard-identity.ts","../../src/identity.ts","../../src/service-port.ts","../../src/deps.ts","../../src/definition-site.ts","../../src/secrets.ts","../../src/file-storage.ts","../../src/socket-redis.ts","../../src/storage.ts","../../src/rate-limit.ts","../../src/context.ts","../../src/webhook.ts","../../src/events/transaction.ts","../../src/audit.ts","../../src/compiler/runtime.ts","../../src/action.ts","../../src/http.ts","../../src/plugin.ts","../../src/plugin-app.ts","../../src/compiler/ir.ts","../../src/action-handler.ts","../../src/app-entry.ts","../../src/events/catalog.ts","../../src/events/listener.ts","../../src/events/workflows.ts","../../src/compiler.ts","../../src/registry.ts","../../src/access.ts","../../src/openapi.ts","../../src/request-logger.ts","../../src/docs.ts","../../src/dashboard.ts","../../src/mcp.ts","../../src/endpoints.ts","../../src/events/id.ts","../../src/events/outbox.ts","../../src/events/dispatcher.ts","../../src/schedules/cron.ts","../../src/schedules/schedule.ts","../../src/schedules/scheduler.ts","../../src/events/hub.ts","../../src/cors.ts","../../src/socket.ts","../../src/server.ts"],"sourcesContent":["import type { HttpMethod } from \"./http\";\nimport type { TSchema } from \"@sinclair/typebox\";\nimport type { PluginInstance } from \"./define-plugin\";\nimport type { PluginActionChecks } from \"./action-meta\";\nimport type {\n Action,\n ActionConfigWithAuthorize,\n ActionConfigWithoutAuthorize,\n ActionContext,\n ActionErrorDefinition,\n BaseContext,\n Resource,\n Service,\n} from \"./types\";\n\nexport type PluginRouteMethod = HttpMethod;\n/** Where a plugin route mounts: under the app prefix, its service, or its resource. */\nexport const PLUGIN_ROUTE_SCOPES = [\"app\", \"service\", \"resource\"] as const;\nexport type PluginRouteScope = (typeof PLUGIN_ROUTE_SCOPES)[number];\nexport type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =\n | false\n | Readonly<Record<string, false | { path?: string; scope?: S }>>;\n\nexport type ContextOf<S> =\n S extends Service<infer D, infer C> ? BaseContext<D> & C : never;\n\nexport interface PluginEndpointContext<\n C extends ActionContext = ActionContext,\n> {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n set: { status?: number; headers: Record<string, string> };\n ctx: C;\n}\n\nexport interface PluginRouteRegistrar<\n C extends ActionContext = ActionContext,\n S extends PluginRouteScope = PluginRouteScope,\n> {\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<I, O, E, C> &\n PluginActionChecks & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<I, O, E, C> &\n PluginActionChecks & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n endpoint(config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n }): void;\n /**\n * Reserve a URL segment under the resource, so no resource action takes it,\n * for a route the plugin may add later. Resource-scoped routes claim their\n * first segment themselves.\n */\n claim(segment: string): void;\n}\n\nexport interface ServicePluginContext<\n S extends Service<any, any> = Service<any, any>,\n> {\n service: S;\n routes: PluginRouteRegistrar<ContextOf<S>, \"app\" | \"service\">;\n}\nexport interface ResourcePluginContext<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n> {\n service: S;\n resource: R;\n routes: PluginRouteRegistrar<ContextOf<S>>;\n}\n\n/** Plugins may specialize their returned API for the installation host. */\nexport interface ResourcePluginTypes {\n readonly table: unknown;\n readonly context: unknown;\n readonly resource: unknown;\n readonly api: object;\n}\nexport type ResourcePluginAPI<P, T, C, R = unknown> = P extends {\n readonly types: infer H extends ResourcePluginTypes;\n}\n ? (H & {\n readonly table: T;\n readonly context: C;\n readonly resource: R;\n })[\"api\"]\n : P extends PluginInstance<infer A extends object, any>\n ? A\n : P extends ResourcePlugin<any, any, infer A>\n ? A\n : never;\n\n/** Which host a plugin descriptor installs on. Process-global, so descriptors survive a second core copy. */\nexport const PLUGIN_KIND: unique symbol = Symbol.for(\"brickkit.plugin.kind\");\n/**\n * The setup context's slot where a `definePlugin` setup hands over what to do\n * once its install succeeds; a failed install drops it.\n */\nexport const PLUGIN_COMMIT: unique symbol = Symbol.for(\n \"brickkit.plugin.commit\",\n);\nexport interface ServicePlugin<S extends Service<any, any>, A> {\n readonly [PLUGIN_KIND]: \"service\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes<\"app\" | \"service\">;\n readonly setup: (context: ServicePluginContext<S>) => A;\n}\nexport interface ResourcePlugin<\n S extends Service<any, any>,\n R extends Resource<any, any, any>,\n A extends object,\n> {\n readonly [PLUGIN_KIND]: \"resource\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes;\n readonly setup: (context: ResourcePluginContext<S, R>) => A;\n}\n\n/** A plugin as `app.definition.plugins` lists it. */\nexport interface InstalledPlugin {\n readonly name: string;\n readonly brick?: string;\n readonly scope: \"app\" | \"service\" | \"resource\";\n readonly service?: string;\n readonly resource?: string;\n /** The plugin's dashboard extension, an absolute path. */\n readonly dashboard?: string;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { inspect } from \"node:util\";\nimport type { TSchema } from \"@sinclair/typebox\";\n\nconst SENSITIVE = Symbol.for(\"brickkit.sensitive\");\n\n/** The schema, unchanged in type and validation, marked sensitive. */\nexport function Sensitive<T extends TSchema>(schema: T): T {\n return { ...schema, [SENSITIVE]: true };\n}\n\nexport const isSensitive = (schema: any): boolean =>\n schema?.[SENSITIVE] === true;\n\ntype Segment = string | null | { except: string[] };\n\ninterface SensitivePath {\n segments: Segment[];\n optional: boolean;\n}\n\ninterface Analysis {\n paths: SensitivePath[];\n publics: { segments: Segment[]; required: boolean }[];\n ref?: string;\n hidden?: string;\n}\n\ninterface Walk extends Analysis {\n markedIds: Set<string>;\n loops: Map<string, string>;\n external?: string;\n}\n\nconst analyses = new WeakMap<object, Analysis>();\n\nfunction analyze(schema: unknown): Analysis {\n if (!schema || typeof schema !== \"object\") return { paths: [], publics: [] };\n let analysis = analyses.get(schema);\n if (!analysis) {\n const walk: Walk = {\n paths: [],\n publics: [],\n markedIds: new Set(),\n loops: new Map(),\n };\n collect(schema, [], false, [], walk);\n analysis = {\n paths: walk.paths,\n publics: walk.publics,\n hidden: walk.hidden,\n };\n if (walk.paths.length || walk.hidden)\n analysis.ref =\n walk.external ??\n [...walk.markedIds].map((id) => walk.loops.get(id)).find(Boolean);\n analyses.set(schema, analysis);\n }\n return analysis;\n}\n\nexport function sensitivePaths(schema: unknown): SensitivePath[] {\n return analyze(schema).paths;\n}\n\nconst holdsMark = (node: unknown, seen = new Set<unknown>()): boolean => {\n if (!node || typeof node !== \"object\" || seen.has(node)) return false;\n seen.add(node);\n return (\n isSensitive(node) ||\n Object.values(node).some((child) => holdsMark(child, seen))\n );\n};\n\nfunction collect(\n schema: any,\n segments: Segment[],\n optional: boolean,\n ids: string[],\n walk: Walk,\n): void {\n if (!schema || typeof schema !== \"object\") return;\n if (isSensitive(schema)) {\n walk.paths.push({ segments, optional });\n for (const id of ids) walk.markedIds.add(id);\n return;\n }\n if (typeof schema.$ref === \"string\") {\n if (!ids.includes(schema.$ref)) walk.external ??= pointer(segments);\n else if (!walk.loops.has(schema.$ref))\n walk.loops.set(schema.$ref, pointer(segments));\n }\n if (typeof schema.$id === \"string\") ids = [...ids, schema.$id];\n const list = schema.type === \"array\" && !Array.isArray(schema.items);\n for (const key of Object.keys(schema))\n if (\n !WALKED.has(key) ||\n (key === \"items\" && !list && !Array.isArray(schema.items))\n )\n if (holdsMark(schema[key])) walk.hidden ??= pointer([...segments, key]);\n const branchesSharingOnePath = [\n ...(schema.anyOf ?? []),\n ...(schema.allOf ?? []),\n ...(schema.oneOf ?? []),\n ];\n for (const branch of branchesSharingOnePath)\n collect(branch, segments, optional, ids, walk);\n const declared = Object.keys(schema.properties ?? {});\n const required = new Set<string>(schema.required ?? []);\n const removable = !(\n schema.minProperties >\n declared.filter(\n (key) => required.has(key) && !isSensitive(schema.properties[key]),\n ).length\n );\n for (const key of declared) {\n const child = schema.properties[key];\n if (!isSensitive(child))\n walk.publics.push({\n segments: [...segments, key],\n required: required.has(key),\n });\n collect(\n child,\n [...segments, key],\n removable && !required.has(key),\n ids,\n walk,\n );\n }\n for (const child of Object.values(schema.patternProperties ?? {}))\n collect(child, [...segments, null], removable, ids, walk);\n if (\n schema.additionalProperties &&\n typeof schema.additionalProperties === \"object\"\n )\n collect(\n schema.additionalProperties,\n [...segments, declared.length ? { except: declared } : null],\n removable,\n ids,\n walk,\n );\n const before = walk.paths.length;\n const items: [unknown, Segment][] = Array.isArray(schema.items)\n ? schema.items.map((child: unknown, index: number) => [\n child,\n String(index),\n ])\n : list\n ? [[schema.items, null]]\n : [];\n for (const [child, segment] of items) {\n if (!isSensitive(child))\n walk.publics.push({ segments: [...segments, segment], required: true });\n collect(child, [...segments, segment], false, ids, walk);\n }\n if (schema.uniqueItems)\n for (const path of walk.paths.slice(before)) path.optional = false;\n}\n\nconst WALKED = new Set([\n \"anyOf\",\n \"allOf\",\n \"oneOf\",\n \"properties\",\n \"patternProperties\",\n \"additionalProperties\",\n \"items\",\n]);\n\nconst admits = (segment: Segment, key: string): boolean =>\n segment === null ||\n (typeof segment === \"string\"\n ? segment === key\n : !segment.except.includes(key));\n\nconst overlap = (a: Segment, b: Segment): boolean =>\n typeof a === \"string\"\n ? admits(b, a)\n : typeof b === \"string\"\n ? admits(a, b)\n : true;\n\nexport const marksKey = (schema: unknown, key: string): boolean =>\n sensitivePaths(schema).some(\n ({ segments: [first] }) => first === undefined || admits(first, key),\n );\n\n/** Whether any part of a schema is marked sensitive. */\nexport function hasSensitive(schema: unknown): boolean {\n const { paths, hidden } = analyze(schema);\n return paths.length > 0 || hidden !== undefined;\n}\n\nexport function writeOnly<T>(schema: T): T {\n if (!hasSensitive(schema)) return schema;\n const visit = (node: any): any => {\n if (Array.isArray(node)) return node.map(visit);\n if (!node || typeof node !== \"object\") return node;\n const copy = { ...node };\n for (const key of Object.keys(copy)) copy[key] = visit(copy[key]);\n if (isSensitive(node)) copy.writeOnly = true;\n return copy;\n };\n return visit(schema);\n}\n\nconst pointer = (segments: Segment[]) =>\n segments.map((key) => `/${typeof key === \"string\" ? key : \"*\"}`).join(\"\") ||\n \"/\";\n\nexport function sensitivePointer(schema: unknown): string | undefined {\n const { paths, hidden } = analyze(schema);\n return paths[0] ? pointer(paths[0].segments) : hidden;\n}\n\nconst escape = (key: string) => key.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n\nconst keysAt = (value: object, segment: Segment): string[] =>\n segment === null\n ? Object.keys(value)\n : typeof segment === \"object\"\n ? Object.keys(value).filter((key) => !segment.except.includes(key))\n : Object.hasOwn(value, segment)\n ? [segment]\n : [];\n\nfunction* found(\n value: any,\n segments: Segment[],\n index = 0,\n at = \"\",\n): Generator<[parent: any, key: string, field: string]> {\n if (value === null || typeof value !== \"object\") return;\n for (const key of keysAt(value, segments[index]!)) {\n const field = `${at}/${escape(key)}`;\n if (index === segments.length - 1) yield [value, key, field];\n else yield* found(value[key], segments, index + 1, field);\n }\n}\n\nfunction omit(\n value: any,\n segments: Segment[],\n hidden: Set<string>,\n index = 0,\n at = \"\",\n): unknown {\n if (value === null || typeof value !== \"object\") return value;\n let copy: any;\n for (const key of keysAt(value, segments[index]!)) {\n const field = `${at}/${escape(key)}`;\n if (index === segments.length - 1) {\n if (!hidden.has(field)) continue;\n copy ??= Array.isArray(value) ? [...value] : { ...value };\n delete copy[key];\n } else {\n const next = omit(value[key], segments, hidden, index + 1, field);\n if (next === value[key]) continue;\n copy ??= Array.isArray(value) ? [...value] : { ...value };\n copy[key] = next;\n }\n }\n return copy ?? value;\n}\n\nexport type Reveal<TInput = unknown, TContext = any> =\n | boolean\n | ((args: {\n field: string;\n input: TInput;\n ctx: TContext;\n }) => boolean | Promise<boolean>);\n\nexport interface Sensitivity {\n input(input: unknown): void;\n output(output: unknown, input: unknown, ctx: unknown): Promise<unknown>;\n}\n\nexport function sensitivity(\n config: {\n name: string;\n input?: unknown;\n output?: unknown;\n reveal?: Reveal<any>;\n },\n service?: string,\n): Sensitivity | undefined {\n const input = analyze(config.input);\n const output = analyze(config.output);\n const inputs = input.paths;\n const outputs = output.paths;\n if (!hasSensitive(config.input) && !hasSensitive(config.output))\n return undefined;\n const owner = service\n ? `Service '${service}' action '${config.name}'`\n : `Action '${config.name}'`;\n for (const [kind, { ref, hidden }] of [\n [\"input\", input],\n [\"output\", output],\n ] as const) {\n if (ref !== undefined)\n throw new Error(\n `${owner}: the ${kind} schema marks a field t.Sensitive and has a $ref at '${ref}' (t.Recursive, t.Module or t.Ref), which sensitive fields do not follow; move the secret out of the recursive or referenced schema`,\n );\n if (hidden !== undefined)\n throw new Error(\n `${owner}: the ${kind} schema marks a field t.Sensitive under '${hidden}', which sensitive fields do not follow; mark it in properties, items, records or union branches`,\n );\n }\n const { reveal = false } = config;\n if (reveal !== true)\n for (const path of outputs) {\n const at = pointer(path.segments);\n if (!path.optional)\n throw new Error(\n `${owner}: sensitive output field '${at}' is removed unless \\`reveal\\` allows it, so the schema must let it be absent: make it t.Optional in every union or intersect branch, not an array item, a record value or a property under minProperties, nor inside a uniqueItems array (or set \\`reveal: true\\`)`,\n );\n const exact = JSON.stringify(path.segments);\n const hit = output.publics.find(\n ({ segments, required }) =>\n segments.length === path.segments.length &&\n segments.every((segment, index) =>\n overlap(segment, path.segments[index]!),\n ) &&\n (required || JSON.stringify(segments) !== exact),\n );\n if (hit)\n throw new Error(\n `${owner}: sensitive output field '${at}' is removed unless \\`reveal\\` allows it, and that path also matches the unmarked field '${pointer(hit.segments)}', which would be removed with it; give the secret a name of its own (or set \\`reveal: true\\`)`,\n );\n }\n const values = (value: unknown, paths: SensitivePath[]) => {\n const all: unknown[] = [];\n for (const { segments } of paths)\n if (!segments.length) all.push(value);\n else\n for (const [parent, key] of found(value, segments))\n all.push(parent[key]);\n return all;\n };\n return {\n input(input) {\n for (const value of values(input, inputs)) redact(value);\n },\n async output(output, input, ctx) {\n for (const value of values(output, outputs)) redact(value);\n if (reveal === true) return output;\n let result = output;\n for (const { segments } of outputs) {\n const hidden = new Set<string>();\n for (const [, , field] of found(output, segments))\n if (\n typeof reveal !== \"function\" ||\n (await reveal({ field, input, ctx })) !== true\n )\n hidden.add(field);\n if (hidden.size) result = omit(result, segments, hidden);\n }\n return result;\n },\n };\n}\n\nconst MIN_REDACTED_LENGTH = 8;\nconst MIN_REDACTED_DIGITS = 4;\nconst MAX_REDACTED_VALUES = 10_000;\nconst MAX_WALKED_ENTRIES = 100;\nconst REDACTED = \"[REDACTED]\";\nconst WITHHELD = \"[REDACTED: too many sensitive values in this call]\";\n\ninterface Redactions {\n values: Set<string>;\n count: number;\n sorted?: string[];\n full?: boolean;\n}\n\nconst redactions = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(\"brickkit.redactions\")\n] ??= new AsyncLocalStorage<Redactions>()) as AsyncLocalStorage<Redactions>;\n\nlet warned = false;\n\nfunction add(set: Redactions, value: string): void {\n if (set.values.has(value)) return;\n if (set.count >= MAX_REDACTED_VALUES) {\n if (!warned)\n console.warn(\n `[brick] A call's redaction set reached ${MAX_REDACTED_VALUES} values, so its log lines are now withheld. A timer or task started inside a call with t.Sensitive fields joins that call's set; bound an input's sensitive records and arrays with maxProperties or maxItems.`,\n );\n warned = true;\n set.full = true;\n return;\n }\n set.count++;\n set.values.add(value);\n set.values.add(JSON.stringify(value).slice(1, -1));\n set.sorted = undefined;\n}\n\nconst longNumber = (value: number | bigint) =>\n String(value).replace(/\\D/g, \"\").length >= MIN_REDACTED_DIGITS;\n\n/**\n * Keep a secret out of what Brick logs and traces for the rest of the running\n * call: the logger, the span recorder and error responses replace it with\n * `[REDACTED]`. Call it as soon as `execute` loads a secret, before it can be\n * logged. It takes each string and number in the value, as a `t.Sensitive`\n * field's value is taken: booleans, and numbers under 4 digits, are left out.\n * Outside a call with `t.Sensitive` fields it does nothing.\n */\nexport function redact(value: unknown): void {\n const set = redactions.getStore();\n if (set) register(set, value, new Set());\n}\n\nfunction register(set: Redactions, value: unknown, seen: Set<object>): void {\n if (typeof value === \"string\") {\n if (value) add(set, value);\n } else if (typeof value === \"number\" || typeof value === \"bigint\") {\n if (longNumber(value)) add(set, String(value));\n } else if (value && typeof value === \"object\" && !seen.has(value)) {\n seen.add(value);\n for (const child of Object.values(value)) register(set, child, seen);\n }\n}\n\nexport function redacting(): boolean {\n const set = redactions.getStore();\n return !!set && (set.full || set.values.size > 0);\n}\n\nexport function redactText(text: string): string;\nexport function redactText(text: unknown): unknown;\nexport function redactText(text: unknown): unknown {\n const set = redactions.getStore();\n if (!set || typeof text !== \"string\") return text;\n if (set.full) return WITHHELD;\n set.sorted ??= [...set.values]\n .filter((value) => value.length >= MIN_REDACTED_LENGTH)\n .sort((a, b) => b.length - a.length);\n let redacted: string = text;\n for (const value of set.sorted)\n if (redacted.includes(value))\n redacted = redacted.split(value).join(REDACTED);\n return redacted;\n}\n\nfunction redactLeaf(set: Redactions, value: unknown): unknown {\n if (typeof value === \"string\")\n return set.values.has(value) ? REDACTED : redactText(value);\n if (typeof value === \"number\" || typeof value === \"bigint\")\n return longNumber(value) && set.values.has(String(value))\n ? REDACTED\n : value;\n return value;\n}\n\nconst LEAF_DEPTH = 5;\n\nfunction publicFieldsCopy(\n original: object,\n props: [PropertyKey, unknown][],\n): object {\n const copy = Object.create(Object.getPrototypeOf(original));\n for (const [key, next] of props)\n Object.defineProperty(copy, key, {\n value: next,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return copy;\n}\n\nexport function redactValues<T>(value: T): T {\n const set = redactions.getStore();\n if (!set || (!set.full && !set.values.size)) return value;\n const walking = new Set<object>();\n const done = new Map<object, unknown>();\n const visit = (value: any, depth: number): any => {\n if (typeof value === \"function\")\n return Object.keys(value).length ? \"[Function]\" : value;\n if (!value || typeof value !== \"object\") return redactLeaf(set, value);\n if (value instanceof Date) return value;\n if (walking.has(value)) return \"[Circular]\";\n if (done.has(value)) return done.get(value);\n if (depth > LEAF_DEPTH) return \"[Object]\";\n walking.add(value);\n let copy: unknown;\n try {\n copy = inside(value, depth);\n } catch {\n copy = \"[Unreadable]\";\n }\n walking.delete(value);\n done.set(value, copy);\n return copy;\n };\n const entries = (value: Iterable<unknown>, size: number, depth: number) => {\n const items: unknown[] = [];\n for (const item of value) {\n if (items.length === MAX_WALKED_ENTRIES) break;\n items.push(item);\n }\n const next = items.map((item) =>\n visit(item, value instanceof Map ? depth : depth + 1),\n );\n const more = size - items.length;\n const changed = more > 0 || next.some((item, i) => item !== items[i]);\n return { next, more, changed };\n };\n const inside = (value: object, depth: number): unknown => {\n if (Array.isArray(value)) {\n const { next, more, changed } = entries(value, value.length, depth);\n if (more) next.push(`... ${more} more items not shown`);\n return changed || Object.keys(value).length !== value.length\n ? next\n : value;\n }\n if (value instanceof Map || value instanceof Set) {\n const { next, more, changed } = entries(value, value.size, depth);\n if (!changed) return value;\n if (value instanceof Set) {\n if (more) next.push(`... ${more} more items not shown`);\n return new Set(next);\n }\n const map = new Map(next as [unknown, unknown][]);\n if (more) map.set(\"...\", `${more} more entries not shown`);\n return map;\n }\n if (value instanceof Error) {\n let text = redactText(\n String(value.stack || `${value.name}: ${value.message}`),\n );\n if (Object.keys(value).length)\n text += ` ${inspect(visit({ ...value }, depth + 1), { depth: 2 })}`;\n if (value.cause !== undefined) {\n const cause = visit(value.cause, depth + 1);\n text += `\\n [cause]: ${typeof cause === \"string\" ? cause : inspect(cause, { depth: 2 })}`;\n }\n return text;\n }\n const tag = Object.prototype.toString.call(value);\n if (tag !== \"[object Object]\") return `[${tag.slice(8, -1)}]`;\n const descriptors = Object.getOwnPropertyDescriptors(value);\n let changed = false;\n const props: [PropertyKey, unknown][] = [];\n for (const key of Reflect.ownKeys(descriptors)) {\n const descriptor = descriptors[key as any]!;\n if (!descriptor.enumerable) continue;\n const name = typeof key === \"string\" ? redactLeaf(set, key) : key;\n const next =\n \"value\" in descriptor ? visit(descriptor.value, depth + 1) : \"[Getter]\";\n if (name !== key || next !== descriptor.value) changed = true;\n props.push([name as PropertyKey, next]);\n }\n return changed ? publicFieldsCopy(value, props) : value;\n };\n return visit(value, 0);\n}\n\nexport function redactDetails(details: unknown): unknown {\n const set = redactions.getStore();\n if (!set || details === undefined || (!set.full && !set.values.size))\n return details;\n if (set.full) return WITHHELD;\n try {\n const text = JSON.stringify(details);\n if (text === undefined) return details;\n const copy = JSON.parse(text, (_key, value) =>\n value && typeof value === \"object\" && !Array.isArray(value)\n ? Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n redactLeaf(set, key),\n child,\n ]),\n )\n : redactLeaf(set, value),\n );\n return JSON.stringify(copy) === text ? details : copy;\n } catch {\n return REDACTED;\n }\n}\n\nexport const outsideRedaction = <T>(fn: () => T): T => redactions.exit(fn);\n\n/** Set a property of an error, unless it is read-only (a `DOMException`, a frozen error). */\nfunction assign(target: any, key: string, value: unknown): void {\n try {\n target[key] = value;\n } catch {}\n}\n\nconst ESCAPED_ERROR_FIELDS = new Set([\"message\", \"stack\", \"cause\", \"details\"]);\nconst MAX_CAUSE_DEPTH = 8;\n\n/** `err`, redacted in place along its cause chain, for whoever logs it outside the call. */\nfunction redactEscaped(err: unknown): unknown {\n if (!(err instanceof Error)) return redactValues(err);\n let e: any = err;\n for (let n = 0; n < MAX_CAUSE_DEPTH; n++) {\n assign(e, \"message\", redactText(e.message));\n if (e.stack) assign(e, \"stack\", redactText(e.stack));\n if (\"details\" in e) assign(e, \"details\", redactDetails(e.details));\n for (const [key, descriptor] of Object.entries(\n Object.getOwnPropertyDescriptors(e),\n ))\n if (\n descriptor.enumerable &&\n \"value\" in descriptor &&\n !ESCAPED_ERROR_FIELDS.has(key)\n )\n assign(e, key, redactValues(descriptor.value));\n if (!(e.cause instanceof Error)) {\n if (e.cause !== undefined) assign(e, \"cause\", redactValues(e.cause));\n break;\n }\n e = e.cause;\n }\n return err;\n}\n\nexport async function withRedaction<T>(fn: () => Promise<T>): Promise<T> {\n if (redactions.getStore()) return fn();\n const set: Redactions = { values: new Set(), count: 0 };\n try {\n return await redactions.run(set, fn);\n } catch (err) {\n throw redactions.run(set, () => redactEscaped(err));\n }\n}\n","import { ATTR } from \"./telemetry-names\";\nimport { redactText, redacting } from \"./sensitive\";\nimport {\n context,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n type Attributes,\n type Span,\n} from \"@opentelemetry/api\";\n\nconst INSTRUMENTATION_SCOPE = \"@brickkit/core\";\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STATEMENT_LENGTH = 2000;\nconst DATABASE_INSTRUMENTED = Symbol.for(\"brickkit.telemetry.database\");\nconst FETCH_INSTRUMENTED = Symbol.for(\"brickkit.telemetry.fetch\");\nconst SQLITE_STATEMENT_METHODS = [\"all\", \"get\", \"run\", \"values\"] as const;\n\ntype Outcome =\n | { failed: false; value: unknown }\n | { failed: true; error: unknown };\n\n/** Run `fn` as a child of the active span, ending the span when its result settles. */\nexport function withSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n kind: SpanKind = SpanKind.INTERNAL,\n): T {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(name, { kind, attributes }, (span) =>\n settle(fn, (outcome) => {\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n }),\n );\n}\n\n/**\n * Add a child span for an in-process call, but only inside a request that is\n * already traced. Calls made outside instrumented requests run unchanged.\n */\nexport function withCallSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n): T {\n return trace.getActiveSpan() ? withSpan(name, attributes, fn) : fn();\n}\n\ninterface HttpContext {\n request?: Request;\n headers?: Record<string, string | undefined>;\n set?: { status?: unknown; headers?: Record<string, unknown> };\n}\n\n/** What a raw route handler receives from `traceRoute`. Read the body from `request`. */\nexport interface RawRouteContext {\n request: Request;\n headers: Record<string, string | undefined>;\n set: { status?: unknown; headers?: Record<string, unknown> };\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n}\n\n/**\n * Wrap a raw route handler so each of its requests gets a server span. Use it\n * for routes registered directly on the app, outside actions and endpoints,\n * such as auth or webhook routes. Spans are recorded whenever a tracer provider\n * is registered; `brick({ telemetry })` does not apply to these routes.\n *\n * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia\n * decides what to parse from the handler's destructuring, and forwarding the\n * whole context would parse the body and leave `request.json()` with nothing.\n */\nexport function traceRoute<T>(\n route: string,\n handler: (context: RawRouteContext) => T,\n): (context: RawRouteContext) => T {\n return ({ request, headers, set, params, query }) =>\n traceHttpRequest({ request, headers, set }, request.method, route, () =>\n handler({ request, headers, set, params, query }),\n );\n}\n\n/**\n * Wrap one HTTP request in a server span. The span continues the caller's\n * trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the\n * request id Brick returns is the span's trace id, so clients can find the\n * request in the dashboard.\n */\nexport function traceHttpRequest<T>(\n request: HttpContext,\n method: string,\n route: string,\n fn: () => T,\n): T {\n const attributes: Attributes = {\n [ATTR.httpMethod]: method,\n [ATTR.httpRoute]: route,\n };\n if (request.request) {\n attributes[ATTR.urlPath] = new URL(request.request.url).pathname;\n }\n const headers = request.headers ?? {};\n const parent = propagation.extract(context.active(), headers);\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(\n `${method} ${route}`,\n { kind: SpanKind.SERVER, attributes },\n parent,\n (span) => {\n if (!headers[\"x-trace-id\"]) {\n headers[\"x-trace-id\"] = span.spanContext().traceId;\n }\n const outgoing: Record<string, string> = {};\n propagation.inject(context.active(), outgoing);\n if (request.set?.headers) Object.assign(request.set.headers, outgoing);\n return settle(fn, (outcome) => {\n // Raw handlers often return a Response, whose status Elysia's `set` never sees.\n const status = outcome.failed\n ? 500\n : outcome.value instanceof Response\n ? outcome.value.status\n : responseStatus(request.set?.status);\n if (outcome.failed) recordThrown(span, outcome.error);\n span.setAttribute(ATTR.httpStatus, status);\n const traceId = headers[\"x-trace-id\"];\n if (traceId) span.setAttribute(ATTR.traceId, traceId);\n if (status >= 500) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${status}`,\n });\n }\n span.end();\n });\n },\n );\n}\n\n/**\n * Attach a handled failure to the active span. Brick returns these as\n * responses rather than throwing, so only server faults (5xx) mark the span\n * as errored; client errors keep their code as an attribute.\n */\nexport function recordFailure(\n error: unknown,\n failure: { status: number; code: string; message: string },\n): void {\n const span = trace.getActiveSpan();\n if (!span) return;\n span.setAttributes({\n [ATTR.errorCode]: failure.code,\n [ATTR.errorStatus]: failure.status,\n [ATTR.errorMessage]: truncate(failure.message),\n });\n if (failure.status >= 500) recordThrown(span, error);\n}\n\nexport function recordWebhook(\n name: string,\n eventId: string | undefined,\n outcome: string,\n): void {\n trace.getActiveSpan()?.setAttributes({\n [ATTR.webhook]: name,\n ...(eventId === undefined ? {} : { [ATTR.webhookEventId]: eventId }),\n [ATTR.webhookOutcome]: outcome,\n });\n}\n\n/**\n * Record SQL statements as client spans for the database behind a service.\n * Drizzle's logger has no timing, so the hook sits on the driver: each\n * statement is timed where the driver runs it. Statements outside traced\n * requests are not recorded. Calling this again on the same client is a no-op.\n */\nexport function instrumentDatabase(db: unknown): void {\n const client = (db as { $client?: unknown } | undefined)?.$client;\n // postgres.js clients are callable functions, so accept both shapes.\n if (\n (typeof client !== \"object\" && typeof client !== \"function\") ||\n client === null\n ) {\n return;\n }\n const driver = client as Record<PropertyKey, unknown>;\n if (driver[DATABASE_INSTRUMENTED]) return;\n if (typeof driver.prepare === \"function\") {\n instrumentBunSqlite(driver as unknown as BunSqliteClient);\n } else if (typeof driver.unsafe === \"function\") {\n instrumentPostgres(driver as unknown as PostgresClient);\n } else {\n return;\n }\n driver[DATABASE_INSTRUMENTED] = true;\n}\n\nexport function instrumentFetch(): void {\n const original = globalThis.fetch as typeof fetch & {\n [FETCH_INSTRUMENTED]?: true;\n };\n if (original[FETCH_INSTRUMENTED]) return;\n // A Proxy keeps fetch's own properties, such as Bun's `fetch.preconnect`.\n const wrapped = new Proxy(original, {\n get: (target, key) =>\n key === FETCH_INSTRUMENTED ? true : Reflect.get(target, key),\n apply(target, self, args: Parameters<typeof fetch>) {\n const [input, init] = args;\n if (!trace.getActiveSpan()) return Reflect.apply(target, self, args);\n let url: URL;\n try {\n url = new URL(input instanceof Request ? input.url : String(input));\n } catch {\n return Reflect.apply(target, self, args);\n }\n const method = (\n init?.method ?? (input instanceof Request ? input.method : \"GET\")\n ).toUpperCase();\n const span = trace.getTracer(INSTRUMENTATION_SCOPE).startSpan(\n truncate(redactText(`${method} ${url.host}${url.pathname}`)),\n {\n kind: SpanKind.CLIENT,\n attributes: {\n [ATTR.httpMethod]: method,\n [ATTR.urlFull]: truncate(\n redactText(`${url.origin}${url.pathname}`),\n ),\n [ATTR.serverAddress]: url.hostname,\n },\n },\n context.active(),\n );\n const fail = (error: unknown) => {\n recordThrown(span, error);\n span.end();\n throw error;\n };\n let pending: Promise<Response>;\n try {\n pending = Reflect.apply(target, self, args);\n } catch (error) {\n return fail(error);\n }\n return pending.then((response) => {\n span.setAttribute(ATTR.httpStatus, response.status);\n if (response.status >= 400) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${response.status}`,\n });\n }\n span.end();\n return response;\n }, fail);\n },\n });\n globalThis.fetch = wrapped;\n}\n\ntype BunSqliteStatement = Record<\n (typeof SQLITE_STATEMENT_METHODS)[number],\n (...args: unknown[]) => unknown\n>;\n\ninterface BunSqliteClient {\n prepare: (sql: string) => BunSqliteStatement;\n}\n\nfunction instrumentBunSqlite(client: BunSqliteClient): void {\n const prepare = client.prepare.bind(client);\n client.prepare = (sql: string) => {\n const statement = prepare(sql);\n for (const method of SQLITE_STATEMENT_METHODS) {\n const original = statement[method];\n if (typeof original !== \"function\") continue;\n statement[method] = (...args: unknown[]) =>\n recordStatement(sql, \"sqlite\", () => original.apply(statement, args));\n }\n return statement;\n };\n}\n\ninterface PostgresQuery {\n then: (\n onFulfilled?: (value: unknown) => unknown,\n onRejected?: (reason: unknown) => unknown,\n ) => Promise<unknown>;\n}\n\ninterface PostgresClient {\n unsafe: (sql: string, ...rest: unknown[]) => PostgresQuery;\n}\n\n/**\n * postgres.js returns a query that runs when awaited, and `values()` returns\n * that same object, so overriding `then` on it times the whole round trip.\n */\nfunction instrumentPostgres(client: PostgresClient): void {\n const unsafe = client.unsafe.bind(client);\n client.unsafe = (sql: string, ...rest: unknown[]) => {\n const query = unsafe(sql, ...rest);\n if (!trace.getActiveSpan() || typeof query?.then !== \"function\") {\n return query;\n }\n const span = startStatementSpan(sql, \"postgresql\");\n let finished = false;\n const finish = (outcome: Outcome) => {\n if (finished) return;\n finished = true;\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n };\n const then = query.then.bind(query);\n // The query is already thenable; this wraps its own `then` to time the\n // round trip, so the no-thenable rule does not apply.\n // oxlint-disable-next-line unicorn/no-thenable\n query.then = (onFulfilled, onRejected) =>\n then(\n (value) => {\n finish({ failed: false, value });\n return onFulfilled ? onFulfilled(value) : value;\n },\n (error: unknown) => {\n finish({ failed: true, error });\n if (onRejected) return onRejected(error);\n throw error;\n },\n );\n return query;\n };\n}\n\nfunction recordStatement<T>(sql: string, system: string, fn: () => T): T {\n if (!trace.getActiveSpan()) return fn();\n return withSpan(\n statementName(sql),\n statementAttributes(sql, system),\n fn,\n SpanKind.CLIENT,\n );\n}\n\nfunction startStatementSpan(sql: string, system: string): Span {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startSpan(\n statementName(sql),\n { kind: SpanKind.CLIENT, attributes: statementAttributes(sql, system) },\n context.active(),\n );\n}\n\nfunction statementName(sql: string): string {\n return `SQL ${operationOf(sql)}`;\n}\n\nfunction statementAttributes(sql: string, system: string): Attributes {\n return {\n [ATTR.dbSystem]: system,\n [ATTR.dbOperation]: operationOf(sql),\n [ATTR.dbStatement]: truncate(sql, MAX_STATEMENT_LENGTH),\n };\n}\n\nfunction operationOf(sql: string): string {\n return sql.trim().split(/\\s+/, 1)[0]?.toUpperCase() || \"SQL\";\n}\n\nfunction settle<T>(fn: () => T, done: (outcome: Outcome) => void): T {\n let result: T;\n try {\n result = fn();\n } catch (error) {\n done({ failed: true, error });\n throw error;\n }\n if (isPromiseLike(result)) {\n return result.then(\n (value) => {\n done({ failed: false, value });\n return value;\n },\n (error: unknown) => {\n done({ failed: true, error });\n throw error;\n },\n ) as unknown as T;\n }\n done({ failed: false, value: result });\n return result;\n}\n\nfunction recordThrown(span: Span, error: unknown): void {\n if (!(error instanceof Error))\n span.recordException(redactText(String(error)));\n else if (!redacting()) span.recordException(error);\n else\n span.recordException({\n code: (error as { code?: string }).code,\n name: error.name,\n message: redactText(error.message),\n stack: error.stack && redactText(error.stack),\n });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncate(redactText(messageOf(error))),\n });\n}\n\nfunction responseStatus(value: unknown): number {\n const status = typeof value === \"number\" ? value : Number(value ?? 200);\n return Number.isInteger(status) ? status : 200;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n","import { ActionExecutionError, ValidationError, type Logger } from \"./types\";\nimport { recordFailure } from \"./telemetry\";\nimport type { WireError } from \"./protocol\";\nimport { redactDetails, redactText } from \"./sensitive\";\n\n/** The JSON body of a failed HTTP call. */\nexport interface ErrorEnvelope extends WireError {\n requestId: string;\n}\n\ntype ErrorContext = { logger: Pick<Logger, \"error\">; requestId: string };\n\n/** Preserve declared failures, log and wrap unexpected throws without exposing internals. */\nexport function normalizeActionError(\n err: unknown,\n { logger, requestId }: ErrorContext,\n): ActionExecutionError | ValidationError {\n if (err instanceof ActionExecutionError || err instanceof ValidationError)\n return err;\n logger.error(\"Unexpected action error\", { requestId }, err);\n const failure = new ActionExecutionError(\n \"INTERNAL_SERVER_ERROR\",\n \"Internal Server Error\",\n 500,\n undefined,\n { cause: err },\n );\n failure.name = \"InternalServerError\";\n return failure;\n}\n\n/**\n * Turn what an action threw into the JSON body of its HTTP response, and record\n * the failure on the active trace. Declared failures and validation errors keep\n * their code, status, and details; anything else is logged and answered as a\n * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.\n *\n * @param err - Whatever was thrown.\n * @param context - A `logger` with `error()`, and the `requestId` to put in the body.\n * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and\n * `details` or `errors` when there are any.\n */\nexport function toErrorResponse(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const envelope = redactAnsweredEnvelope(buildErrorEnvelope(err, context));\n recordFailure(err, envelope);\n return envelope;\n}\n\nfunction redactAnsweredEnvelope(envelope: ErrorEnvelope): ErrorEnvelope {\n envelope.message = redactText(envelope.message);\n if (envelope.details !== undefined)\n envelope.details = redactDetails(envelope.details);\n return envelope;\n}\n\nfunction buildErrorEnvelope(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const failure = normalizeActionError(err, context);\n if (\n failure.status >= 500 &&\n (err instanceof ActionExecutionError || err instanceof ValidationError)\n ) {\n context.logger.error(\n \"Server action error\",\n { requestId: context.requestId },\n err,\n );\n }\n if (failure instanceof ValidationError && failure.status >= 500) {\n return {\n name: failure.name,\n code: failure.code,\n message: failure.message,\n status: failure.status,\n requestId: context.requestId,\n };\n }\n return { ...failure.toJSON(), requestId: context.requestId };\n}\n","import {\n Kind,\n Type as TypeBox,\n TypeRegistry,\n type SchemaOptions,\n type TArray,\n type TSchema,\n type TUnsafe,\n type Static,\n} from \"@sinclair/typebox\";\nimport { TypeCompiler, type TypeCheck } from \"@sinclair/typebox/compiler\";\nimport type { ValidationErrorItem } from \"./types\";\nimport { Sensitive } from \"./sensitive\";\n\n/**\n * Any JSON value: null, boolean, number, string, or an array or object of\n * JSON values.\n */\nfunction Json(options?: SchemaOptions) {\n return TypeBox.Recursive(\n (This) =>\n TypeBox.Union([\n TypeBox.Null(),\n TypeBox.Boolean(),\n TypeBox.Number(),\n TypeBox.String(),\n TypeBox.Array(This),\n TypeBox.Record(TypeBox.String(), This),\n ]),\n options,\n );\n}\n\nexport interface FileOptions {\n /** The largest file accepted, in bytes. Also caps the request body before it is read. */\n maxSize?: number;\n /**\n * The content types accepted, such as `\"application/pdf\"` or `\"image/*\"`;\n * `\"*\\/*\"` accepts any. Over HTTP, Bun takes a file's type from the\n * extension of its file name, not from the part's `Content-Type`.\n */\n accept?: string[];\n description?: string;\n}\n\nfunction accepts(accept: string[] | undefined, type: string): boolean {\n if (!accept) return true;\n const given = type.split(\";\")[0]!.trim().toLowerCase();\n return accept.some((pattern) => {\n const wanted = pattern.toLowerCase();\n if (wanted === \"*/*\") return true;\n return wanted.endsWith(\"/*\")\n ? given.startsWith(wanted.slice(0, -1)) &&\n given.length > wanted.length - 1\n : given === wanted;\n });\n}\n\nTypeRegistry.Set<{ maxSize?: number; accept?: string[] }>(\n \"File\",\n (schema, value) =>\n value instanceof Blob &&\n !(value.size > (schema.maxSize ?? Infinity)) &&\n accepts(schema.accept, value.type),\n);\n\n/** A file from a `multipart/form-data` body: a `File` (a `Blob`), at most `maxSize` bytes, of a type in `accept`. */\nfunction File(options: FileOptions = {}): TUnsafe<File> {\n return TypeBox.Unsafe<File>({\n [Kind]: \"File\",\n type: \"string\",\n format: \"binary\",\n ...options,\n });\n}\n\n/** Several files under one form field. */\nfunction Files(\n options: FileOptions & { minItems?: number; maxItems?: number } = {},\n): TArray<TUnsafe<File>> {\n const { minItems, maxItems, ...file } = options;\n return TypeBox.Array(File(file), { minItems, maxItems });\n}\n\n/** TypeBox's `Type` plus Brick's `Json`, `File`, `Files` and `Sensitive`. */\n// TypeBox's `Type` is a module namespace at runtime, so its functions copy over.\nexport const Type = Object.assign({}, TypeBox, {\n Json,\n File,\n Files,\n Sensitive,\n});\nexport { Type as t };\nexport type { TSchema, Static };\n\nexport function fileFields(\n schema: unknown,\n): { key: string; maxBytes: number | undefined }[] {\n const fields = [];\n const properties = (schema as { properties?: Record<string, any> })\n ?.properties;\n for (const [key, prop] of Object.entries(properties ?? {})) {\n const file = prop[Kind] === \"File\" ? prop : prop.items;\n if (file?.[Kind] !== \"File\") continue;\n const count: number | undefined = file === prop ? 1 : prop.maxItems;\n const maxBytes =\n file.maxSize === undefined || count === undefined\n ? undefined\n : file.maxSize * count;\n fields.push({ key, maxBytes });\n }\n return fields;\n}\n\nconst compilerCache = new WeakMap<TSchema, TypeCheck<TSchema>>();\n\n/**\n * The compiled validator for a TypeBox schema. Compiling is slow and checking\n * is fast, so each schema is compiled once and kept for as long as the schema\n * object lives.\n *\n * @param schema - A TypeBox schema.\n * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.\n */\nexport function getCompiledCheck<T extends TSchema>(schema: T): TypeCheck<T> {\n let compiled = compilerCache.get(schema) as TypeCheck<T> | undefined;\n if (!compiled) {\n compiled = TypeCompiler.Compile(schema);\n compilerCache.set(schema, compiled);\n }\n return compiled;\n}\n\n/**\n * Check a value against a schema, the way actions check their input and output.\n *\n * @param schema - A TypeBox schema, or `undefined` to accept anything.\n * @param value - The value to check.\n * @returns `{ success: true, data }`, or `{ success: false, errors }` with a\n * `path`, `message` and `type` for each problem. The offending value is\n * left out so a rejected secret is never echoed or logged.\n */\nexport function validateWithSchema<T extends TSchema>(\n schema: T | undefined,\n value: unknown,\n):\n | { success: true; data: Static<T> }\n | { success: false; errors: ValidationErrorItem[] } {\n if (!schema) {\n return { success: true, data: value as Static<T> };\n }\n\n const check = getCompiledCheck(schema);\n if (check.Check(value)) {\n return { success: true, data: value as Static<T> };\n }\n\n const errors: ValidationErrorItem[] = [];\n for (const error of check.Errors(value)) {\n errors.push({\n path: error.path,\n message: error.message,\n type: error.type,\n });\n }\n\n return { success: false, errors };\n}\n","import { ATTR, GLOBAL_SYMBOL, SPAN } from \"./telemetry-names\";\nimport { format, formatWithOptions } from \"node:util\";\nimport { trace, type Span } from \"@opentelemetry/api\";\nimport type { Logger } from \"./types\";\nimport { redactText, redactValues, redacting } from \"./sensitive\";\n\ntype Level = keyof Logger;\n\n/**\n * Set by the CLI when a dashboard is collecting logs, in `brick dev` or in\n * `brick start` with the `dashboard` option. A shared symbol, not an option or\n * an export: the CLI and the app may each hold their own copy of this package,\n * and nothing but a dashboard turns it on.\n */\nconst CAPTURE = Symbol.for(GLOBAL_SYMBOL.logsCapture);\nconst MAX_MESSAGE_LENGTH = 4000;\n/**\n * Logs one span keeps. OpenTelemetry keeps 128 events per span by default,\n * exceptions among them, so a chatty action must not use them all up and\n * lose the stack trace of the error that ends it.\n */\nconst MAX_LOGS_PER_SPAN = 100;\n\nconst logged = new WeakMap<Span, number>();\n\n/**\n * Terminal formatting: colors and styles (`ESC [ … m`, and other CSI codes) and\n * titles or links (`ESC ] … BEL`). Libraries such as Better Auth color their\n * console output, which in a web page shows as stray characters.\n */\n// oxlint-disable no-control-regex\nconst ANSI =\n /\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\))/g;\n// oxlint-enable no-control-regex\n\nexport function stripAnsi(text: string): string {\n return text.includes(\"\\u001b\") ? text.replace(ANSI, \"\") : text;\n}\n\nconst REDACTED_COPY_NOT_PRINTABLE = \"[Unreadable]\";\n\nfunction formatRedacted(\n print: (...args: unknown[]) => string,\n args: unknown[],\n): string {\n let printed: string;\n try {\n printed = print(...redactValues(args));\n } catch {\n printed = REDACTED_COPY_NOT_PRINTABLE;\n }\n return redactText(printed);\n}\n\n/**\n * What `console.log` would print, without terminal colors, with objects cut off\n * at a sensible size.\n */\nfunction render(args: unknown[]): string {\n const text = formatRedacted(\n (...values) =>\n stripAnsi(\n formatWithOptions(\n {\n depth: 3,\n breakLength: 120,\n maxArrayLength: 50,\n maxStringLength: 1000,\n },\n ...values,\n ),\n ),\n args,\n );\n return text.length > MAX_MESSAGE_LENGTH\n ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…`\n : text;\n}\n\nfunction record(span: Span, level: Level, args: unknown[]): void {\n const count = (logged.get(span) ?? 0) + 1;\n logged.set(span, count);\n if (count > MAX_LOGS_PER_SPAN) {\n // Counted, so the dashboard can say how many it left out.\n span.setAttribute(ATTR.logsDropped, count - MAX_LOGS_PER_SPAN);\n return;\n }\n span.addEvent(SPAN.logEvent, {\n [ATTR.logLevel]: level,\n [ATTR.logMessage]: render(args),\n });\n}\n\n/**\n * Record a line on the running span, if a recording one is running. Returns\n * whether it did, so the caller prints only when it did not.\n */\nfunction recordActive(level: Level, args: unknown[]): boolean {\n const span = trace.getActiveSpan();\n if (!span?.isRecording()) return false;\n record(span, level, args);\n return true;\n}\n\n// The dev server's console capture calls this by name, for the same reason\n// `CAPTURE` is a shared symbol: it may hold a different copy of this package.\n(globalThis as Record<symbol, unknown>)[Symbol.for(GLOBAL_SYMBOL.logsRecord)] =\n recordActive;\n\n/**\n * A logger for actions, tools, and endpoints. While a dashboard is on, a line\n * logged while a request is being traced becomes an event on the span that is\n * running, which the dashboard shows with that request (and in its Logs tab);\n * it is not printed. Everywhere else, and for lines logged outside a request,\n * it prints to the console, prefixed by `prefix`: one for all levels, or one\n * per level.\n *\n * Capturing costs one context lookup and a span event per line, and nothing\n * is serialized for the dashboard until the span ends, so it is cheaper than\n * a console write. Lines are cut at 4,000 characters and a span keeps 100.\n */\nexport function createLogger(prefix: string | Record<Level, string>): Logger {\n const level =\n (name: Level, print: (...args: unknown[]) => void) =>\n (...args: unknown[]): void => {\n if (\n (globalThis as Record<symbol, unknown>)[CAPTURE] === true &&\n recordActive(name, args)\n )\n return;\n if (redacting()) args = [formatRedacted(format, args)];\n print(typeof prefix === \"string\" ? prefix : prefix[name], ...args);\n };\n return {\n info: level(\"info\", (...args) => console.log(...args)),\n warn: level(\"warn\", (...args) => console.warn(...args)),\n error: level(\"error\", (...args) => console.error(...args)),\n debug: level(\"debug\", (...args) => console.debug(...args)),\n };\n}\n\n/** The prefixes of loggers a caller did not supply. */\nexport const DEFAULT_LOG_PREFIXES: Record<Level, string> = {\n info: \"[INFO]\",\n warn: \"[WARN]\",\n error: \"[ERROR]\",\n debug: \"[DEBUG]\",\n};\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { GLOBAL_SYMBOL } from \"./telemetry-names\";\n\n/** The person `dashboard.auth.authorize` let in. */\nexport interface DashboardUser {\n id: string;\n name?: string;\n}\n\n/**\n * Who a request came from, when it reached the app through the dashboard's\n * `/app/*` proxy. `user` is missing when the dashboard let the request in\n * without one: by token, by `authorize` returning `true`, or with no `auth`.\n */\nexport interface DashboardIdentity {\n user?: DashboardUser;\n}\n\n/** The header the dashboard's `/app/*` proxy signs the identity into. */\nexport const DASHBOARD_IDENTITY_HEADER = \"x-brick-dashboard\";\n/** How `brick dev` hands the signing key to the app's process. */\nexport const DASHBOARD_KEY_ENV = \"BRICK_DASHBOARD_KEY\";\nconst SIGNATURE_TTL_MS = 60_000;\nconst KEY = Symbol.for(GLOBAL_SYMBOL.dashboardKey);\nconst global = globalThis as Record<symbol, string | undefined>;\nfunction hideKeyFromChildProcesses(): void {\n const handedOver = process.env[DASHBOARD_KEY_ENV];\n if (!handedOver) return;\n global[KEY] = handedOver;\n delete process.env[DASHBOARD_KEY_ENV];\n}\nhideKeyFromChildProcesses();\n\n/**\n * The key the dashboard signs identities with: random per process, or the one\n * `brick dev` or the Vite plugin handed the app.\n */\nexport function dashboardKey(): string {\n return (global[KEY] ??= randomBytes(32).toString(\"base64url\"));\n}\n\n// When each request reached the app, so a slow upload's body does not age its signature.\nconst arrivedAt = new WeakMap<Request, number>();\n\n/** Note when `request` arrived, before its body is read. */\nexport function markDashboardArrival(request: Request): void {\n arrivedAt.set(request, Date.now());\n}\n\nconst mac = (payload: string) =>\n createHmac(\"sha256\", dashboardKey()).update(payload).digest();\n\nconst sign = (claims: object, now: number): string => {\n const payload = Buffer.from(\n JSON.stringify({ ...claims, exp: now + SIGNATURE_TTL_MS }),\n ).toString(\"base64url\");\n return `${payload}.${mac(payload).toString(\"base64url\")}`;\n};\n\n/** The header value for an identity: `<base64url(json)>.<hmac>`. */\nexport function signDashboardIdentity(\n identity: DashboardIdentity,\n now = Date.now(),\n): string {\n return sign({ user: identity.user }, now);\n}\n\nfunction verifiedClaims(\n request: Request | undefined,\n): { user?: DashboardUser; scope?: unknown; write?: unknown } | undefined {\n const header = request?.headers.get(DASHBOARD_IDENTITY_HEADER);\n if (!header) return undefined;\n const dot = header.indexOf(\".\");\n if (dot < 0) return undefined;\n const payload = header.slice(0, dot);\n const given = Buffer.from(header.slice(dot + 1), \"base64url\");\n const expected = mac(payload);\n if (given.length !== expected.length || !timingSafeEqual(given, expected))\n return undefined;\n try {\n const claims = JSON.parse(\n Buffer.from(payload, \"base64url\").toString(\"utf8\"),\n );\n const now = (request && arrivedAt.get(request)) ?? Date.now();\n if (typeof claims?.exp !== \"number\" || claims.exp < now) return undefined;\n return claims;\n } catch {\n return undefined;\n }\n}\n\n/** A signature made for the MCP route carries a `scope`, and is not an identity here. */\nexport function dashboardIdentity(\n request: Request | undefined,\n): DashboardIdentity | undefined {\n const claims = verifiedClaims(request);\n if (!claims || claims.scope !== undefined) return undefined;\n return claims.user === undefined ? {} : { user: claims.user };\n}\n\n/** Who a call forwarded by the dashboard's `/mcp` is for, and whether tools that change data may run. */\nexport interface DashboardMcpCaller extends DashboardIdentity {\n write: boolean;\n}\n\n/**\n * The header value for a call the dashboard's `/mcp` forwards to the app. It is\n * scoped to the MCP route: the `/app` proxy never signs one, and a signature\n * made for `/app` is not accepted there.\n */\nexport function signDashboardMcp(\n caller: DashboardMcpCaller,\n now = Date.now(),\n): string {\n return sign({ user: caller.user, scope: \"mcp\", write: caller.write }, now);\n}\n\nexport function dashboardMcpCaller(\n request: Request | undefined,\n): DashboardMcpCaller | undefined {\n const claims = verifiedClaims(request);\n if (claims?.scope !== \"mcp\") return undefined;\n return {\n ...(claims.user === undefined ? {} : { user: claims.user }),\n write: claims.write === true,\n };\n}\n\n/**\n * The dashboard user a request came from, for an endpoint: the person\n * `dashboard.auth.authorize` let in, when the request arrived through the\n * dashboard's `/app/*` proxy. Undefined for any other request, and for one the\n * dashboard let in by token. Actions read it as `ctx.dashboard?.user`.\n */\nexport function dashboardUser(request: Request): DashboardUser | undefined {\n return dashboardIdentity(request)?.user;\n}\n","import type { Service } from \"./types\";\n\n/**\n * Who a call comes from, as the service's `identity` hook says. Brick treats\n * the strings as opaque: it compares and stores them, never interprets them.\n */\nexport interface Identity {\n /** Who: the rate-limit key and the audit actor. */\n id: string;\n /** A display name for the audit log. */\n label?: string;\n /** Which tenant: scopes file storage and is recorded in the audit log. */\n tenant?: string;\n}\n\nconst IDENTITY = Symbol.for(\"brickkit.identity\");\n\nexport function attachIdentity(\n ctx: Record<PropertyKey, unknown>,\n service: Service<any, any>,\n deps: Readonly<Record<string, unknown>>,\n): void {\n const hook = service.options.identity;\n if (typeof hook !== \"function\") return;\n let identity: Promise<Identity | null> | undefined;\n ctx[IDENTITY] = () =>\n (identity ??= Promise.resolve()\n .then(() => {\n const { [IDENTITY]: _own, ...withoutIdentity } = ctx;\n return hook({ ...withoutIdentity, deps } as any);\n })\n .then((value) => checked(service.name, value)));\n}\n\nfunction checked(service: string, value: unknown): Identity | null {\n if (value === null || value === undefined) return null;\n const { id, label, tenant } = value as Partial<Identity>;\n if (\n typeof id !== \"string\" ||\n !id ||\n (label !== undefined && typeof label !== \"string\") ||\n (tenant !== undefined && typeof tenant !== \"string\")\n )\n throw new Error(\n `Service \"${service}\": identity must return { id: string, label?: string, tenant?: string } with a non-empty id, null or undefined`,\n );\n return {\n id,\n ...(label !== undefined && { label }),\n ...(tenant !== undefined && { tenant }),\n };\n}\n\nexport function identityOf(ctx: object): Promise<Identity | null> {\n const resolve = (ctx as Record<PropertyKey, unknown>)[IDENTITY];\n return typeof resolve === \"function\" ? resolve() : Promise.resolve(null);\n}\n\nexport function hasIdentity(service: Service<any, any>): boolean {\n return typeof service.options.identity === \"function\";\n}\n","import type { BaseContext, PreparationContribution, Service } from \"./types\";\nimport type { AuditTable } from \"./audit\";\nimport type { OutboxTable } from \"./events/outbox\";\nimport type { ScheduleTable } from \"./schedules/table\";\nimport type { ServiceEvents } from \"./events/types\";\nimport type { EventRef } from \"./events/catalog\";\n\n/**\n * What core's own modules use of a service, beyond the public `Service`. Every\n * service `defineService` makes is one.\n */\nexport interface ServicePort<\n TDb = any,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> extends Service<TDb, TServiceContext> {\n readonly deps: Readonly<Record<string, unknown>>;\n /** Whether the service declares an event catalog. */\n readonly hasCatalog: boolean;\n /** `resolveContext`, for an action or socket a plugin install created: it sees `pluginDeps`. */\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n pluginDeps?: Readonly<Record<string, unknown>>,\n ): Promise<BaseContext<TDb> & TServiceContext>;\n setRecorder(recorder: ServiceEvents | undefined): void;\n getOutbox(): OutboxTable | undefined;\n getScheduleTable(): ScheduleTable | undefined;\n getAuditTable(): AuditTable | undefined;\n /** @throws When the event is not in the catalog or its payload does not match. */\n checkEvent(name: string, payload: unknown): void;\n /** Adds events to the catalog (a plugin's). */\n addEvents(refs: Readonly<Record<string, EventRef>>): void;\n registerTable(table: unknown): this;\n listPreparations(): PreparationContribution[];\n prepareContributions(): void;\n /** Records the declarations; the returned function puts them back (plugin rollback). */\n snapshot(): () => void;\n /** Marks the definitions changed, so cached architecture and OpenAPI are rebuilt. */\n touch(): void;\n}\n\n/** The port of a service: every `Service` is a `ServicePort`. */\nexport function portOf<TDb, TCtx extends Record<string, any>>(\n service: Service<TDb, TCtx>,\n): ServicePort<TDb, TCtx> {\n return service as ServicePort<TDb, TCtx>;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Service } from \"./types\";\nimport type { RawDeps } from \"./file-storage\";\nimport { portOf } from \"./service-port\";\n\n/** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */\nexport const PLUGIN_DEPS: unique symbol = Symbol.for(\"brickkit.plugin.deps\");\n\nexport function sharedAcrossCoreCopies<T>(key: string, create: () => T): T {\n const store = globalThis as any;\n return (store[Symbol.for(key)] ??= create());\n}\n\nconst depsBuiltByBrick = sharedAcrossCoreCopies(\n \"brickkit.deps.built\",\n () => new WeakSet<object>(),\n);\n\nexport function freezeAsBuiltDeps<T extends object>(deps: T): Readonly<T> {\n depsBuiltByBrick.add(Object.freeze(deps));\n return deps;\n}\n\nexport function depsOverride(\n callCtx: unknown,\n): Record<string, unknown> | undefined {\n const deps = (callCtx as { deps?: unknown } | undefined)?.deps;\n return deps && typeof deps === \"object\" && !depsBuiltByBrick.has(deps)\n ? (deps as Record<string, unknown>)\n : undefined;\n}\n\nconst running = new AsyncLocalStorage<Record<string, unknown>>();\n\n/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */\nexport function runWithDeps<T>(deps: Record<string, unknown>, fn: () => T): T {\n return running.run(deps, fn);\n}\n\nexport type ServiceDeps<S> =\n S extends Service<any, infer C, any>\n ? C extends { deps: infer D }\n ? Readonly<RawDeps<D>>\n : Readonly<Record<string, unknown>>\n : never;\n\n/**\n * The deps of a service, for code that has no `ctx`: listeners, schedules and\n * workflow steps. Actions, tools and socket handlers read `ctx.deps` instead.\n *\n * `useDeps(service)` returns that service's deps, typed from it, anywhere.\n * Without an argument it returns what the running listener, schedule or step\n * sees: in one a plugin added, the deps of that install; in the app's own, the\n * deps of all the app's services by name, for code that cannot import the\n * service (one built in a factory). A name two services give different values\n * has no single answer, so reading it throws.\n *\n * @param service - The service whose deps to return.\n * @returns The deps.\n * @throws Without `service`: when called outside a listener, schedule or\n * workflow step of a Brick app, or on reading a name two services give\n * different values.\n * @example\n * async function bookCarrier(orderId: string) {\n * \"use step\";\n * return useDeps(orders).carrier.book(orderId);\n * }\n */\nexport function useDeps<S extends Service<any, any, any>>(\n service: S,\n): ServiceDeps<S>;\nexport function useDeps<T = Record<string, unknown>>(): T;\nexport function useDeps(service?: Service<any, any, any>): unknown {\n if (service) return portOf(service).deps;\n const deps = running.getStore();\n if (!deps)\n throw new Error(\n \"useDeps() was called outside a Brick app: call it from a listener, a schedule or a workflow step (actions read ctx.deps), or pass the service: useDeps(service).\",\n );\n return deps;\n}\n\nfunction makeAmbiguous(\n deps: Record<string, unknown>,\n name: string,\n firstService: string | undefined,\n otherService: string,\n) {\n Object.defineProperty(deps, name, {\n enumerable: false,\n get() {\n throw new Error(\n `useDeps().${name} is ambiguous: services \"${firstService}\" and \"${otherService}\" both declare dep \"${name}\" with different values. Call useDeps(service) with the service you mean.`,\n );\n },\n });\n}\n\nexport function appDeps(\n services: readonly Service<any, any>[],\n): Record<string, unknown> {\n const deps: Record<string, unknown> = {};\n const owner = new Map<string, string>();\n for (const service of services)\n for (const [name, value] of Object.entries(portOf(service).deps)) {\n const seen = Object.getOwnPropertyDescriptor(deps, name);\n const first = owner.get(name);\n if (!seen) {\n owner.set(name, service.name);\n deps[name] = value;\n } else if (\"value\" in seen && seen.value !== value)\n makeAmbiguous(deps, name, first, service.name);\n }\n return freezeAsBuiltDeps(deps);\n}\n","import { fileURLToPath } from \"node:url\";\nimport { DuplicateNameError } from \"./types\";\n\n// The package root (src/ or dist/ is beneath it), so Brick's own frames are skipped.\nconst brickRoot = fileURLToPath(new URL(\"..\", import.meta.url));\n\n/**\n * The first `file:line` outside Brick on the current stack: where a name is\n * being defined. Best-effort: `undefined` when there is no stack.\n */\nexport function definitionSite(): string | undefined {\n // Plugins nest several Brick frames above the caller's.\n const limit = Error.stackTraceLimit;\n Error.stackTraceLimit = 50;\n const stack = new Error().stack;\n Error.stackTraceLimit = limit;\n for (const line of stack?.split(\"\\n\").slice(1) ?? []) {\n const match =\n /(?:\\(|at )(?:file:\\/\\/)?([^\\s()?]+)(?:\\?[^\\s():]*)?:(\\d+):\\d+\\)?$/.exec(\n line,\n );\n if (!match) continue;\n const [, file, row] = match;\n if (\n file!.startsWith(`${brickRoot}src/`) ||\n file!.startsWith(`${brickRoot}dist/`)\n )\n continue;\n return `${file}:${row}`;\n }\n return undefined;\n}\n\n/**\n * Records where `name` is defined. The same file defining it again (a dev\n * reload) replaces the old definition.\n *\n * @throws When a different file already defined `name`.\n */\nexport function claimName(\n sites: Map<string, string | undefined>,\n label: string,\n name: string,\n site: string | undefined,\n): void {\n const file = (at: string | undefined) => at?.replace(/:\\d+$/, \"\");\n if (sites.has(name) && file(sites.get(name)) !== file(site))\n throw new DuplicateNameError(\n `Brick: duplicate ${label}\\n ${sites.get(name) ?? \"unknown\"}\\n ${site ?? \"unknown\"}`,\n );\n sites.set(name, site);\n}\n","/**\n * Type-safe secrets & environment variables.\n *\n * Declare each secret once at module scope instead of scattering untyped\n * `process.env.FOO` reads:\n *\n * const port = defineSecret(\"PORT\").default(\"3333\").transform(Number).require();\n * const baseUrl = defineSecret(\"BASE_URL\").url().require();\n * const key = defineSecret(\"STRIPE_KEY\").validate((v) =>\n * v.startsWith(\"sk_\") || \"must start with sk_\"\n * ).require();\n *\n * Values resolve from the environment (Bun populates `process.env` from\n * `.env` locally; in prod the same env source applies — a future\n * `SecretSource` such as AWS can slot in without touching call sites).\n *\n * Resolution order per secret: test/session override → source (`process.env`\n * by default) → declared `default`. `resolveSecrets()` validates every\n * registered secret at boot and throws listing all missing required ones.\n */\n\nimport { definitionSite } from \"./definition-site\";\n\nexport interface SecretSource {\n get(name: string): string | undefined;\n}\n\n/** Default source: `process.env` (Bun loads `.env` into it automatically). */\nexport const envSource: SecretSource = {\n get: (name: string) => process.env[name],\n};\n\nexport interface SecretOptions {\n /** Fallback when the source has no value. Secrets without a default are required. */\n default?: string;\n}\n\n/** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */\nexport type SecretValidator<T> = (value: T) => void | boolean | string;\n\nconst registry = new Map<string, SecretRef<any>>();\nconst overrides = new Map<string, string>();\n/** Where each secret was first declared. */\nconst sites = new Map<string, string | undefined>();\n\nexport class SecretRef<T = string> {\n readonly name: string;\n readonly options: SecretOptions;\n private transformFn?: (raw: string) => T;\n private validators: SecretValidator<T>[] = [];\n\n constructor(name: string, options: SecretOptions = {}) {\n this.name = name;\n this.options = options;\n }\n\n /** True when a default was declared (i.e. the secret is optional). */\n get hasDefault(): boolean {\n return this.options.default !== undefined;\n }\n\n /** Fallback used when the source has no value. Makes the secret optional. */\n default(value: string): this {\n this.options.default = value;\n return this;\n }\n\n /**\n * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === \"true\"`).\n * Runs before validators; a throwing transform fails resolution.\n */\n transform<U>(fn: (raw: string) => U): SecretRef<U> {\n this.transformFn = fn as unknown as (raw: string) => T;\n return this as unknown as SecretRef<U>;\n }\n\n /** Run a custom check on the (transformed) value at every resolution. */\n validate(fn: SecretValidator<T>): this {\n this.validators.push(fn);\n return this;\n }\n\n /** Shorthand validator: value must parse as a URL. String refs only. */\n url(this: SecretRef<string>): SecretRef<string> {\n this.validators.push((v) => {\n try {\n new URL(v);\n } catch {\n return \"must be a valid URL\";\n }\n });\n return this;\n }\n\n private resolveRaw(source: SecretSource): string | undefined {\n return (\n overrides.get(this.name) ?? source.get(this.name) ?? this.options.default\n );\n }\n\n private coerce(raw: string): T {\n let value: T;\n if (this.transformFn) {\n try {\n value = this.transformFn(raw);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": transform failed (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n } else {\n value = raw as unknown as T;\n }\n for (const fn of this.validators) {\n let result: void | boolean | string;\n try {\n result = fn(value);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (result === false) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": validation failed`,\n );\n }\n if (typeof result === \"string\") {\n throw new Error(`Invalid value for secret \"${this.name}\": ${result}`);\n }\n }\n return value;\n }\n\n /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */\n value(source: SecretSource = envSource): T | undefined {\n const raw = this.resolveRaw(source);\n if (raw === undefined) return undefined;\n return this.coerce(raw);\n }\n\n /** Resolved value, or throws naming the missing/invalid secret. */\n require(source: SecretSource = envSource): T {\n const raw = this.resolveRaw(source);\n if (raw === undefined) {\n throw new Error(\n `Missing required secret \"${this.name}\": set it in .env (local) or the environment (prod)`,\n );\n }\n return this.coerce(raw);\n }\n\n /** True when a value would resolve (override, source, or default). */\n isSet(source: SecretSource = envSource): boolean {\n return this.resolveRaw(source) !== undefined;\n }\n}\n\n/**\n * Declare a secret. Calling it again for the name returns the same ref. From\n * the same line (a module evaluated again) it starts the declaration over, so\n * its builder calls replace the earlier ones instead of adding to them.\n */\nexport function defineSecret(\n name: string,\n options: SecretOptions = {},\n): SecretRef<string> {\n const site = definitionSite();\n const existing = registry.get(name);\n if (existing) {\n if (site !== undefined && sites.get(name) === site) {\n (existing as { options: SecretOptions }).options = options;\n existing[\"validators\"] = [];\n existing[\"transformFn\"] = undefined;\n }\n return existing;\n }\n sites.set(name, site);\n const ref = new SecretRef<string>(name, options);\n registry.set(name, ref);\n return ref;\n}\n\n/**\n * Validate every registered secret at boot. Throws a single error listing\n * all missing required secrets. Returns the resolved values.\n */\nexport function resolveSecrets(\n opts: { source?: SecretSource } = {},\n): Record<string, unknown> {\n const source = opts.source ?? envSource;\n const missing: string[] = [];\n const resolved: Record<string, unknown> = {};\n for (const ref of registry.values()) {\n const v = ref.value(source);\n if (v === undefined) missing.push(ref.name);\n else resolved[ref.name] = v;\n }\n if (missing.length > 0) {\n throw new Error(\n `Missing required secrets: ${missing.join(\", \")}. Set them in .env (local) or the environment (prod)`,\n );\n }\n return resolved;\n}\n\n/** Metadata for introspection (values never exposed — future dashboard use). */\nexport function listSecrets(\n opts: { source?: SecretSource } = {},\n): Array<{ name: string; hasDefault: boolean; isSet: boolean }> {\n const source = opts.source ?? envSource;\n return [...registry.values()].map((ref) => ({\n hasDefault: ref.hasDefault,\n isSet: ref.isSet(source),\n name: ref.name,\n }));\n}\n\n/** Test/session override for one secret (`undefined` clears the override). */\nexport function overrideSecret(name: string, value: string | undefined): void {\n if (value === undefined) overrides.delete(name);\n else overrides.set(name, value);\n}\n\n/** Clear registry and overrides. Test-only. */\nexport function resetSecrets(): void {\n registry.clear();\n overrides.clear();\n sites.clear();\n}\n","import {\n createHash,\n createHmac,\n randomBytes,\n timingSafeEqual,\n} from \"node:crypto\";\nimport { lstat, mkdir, readFile, realpath, rm } from \"node:fs/promises\";\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport { freezeAsBuiltDeps } from \"./deps\";\nimport { hasIdentity, identityOf } from \"./identity\";\nimport { SecretRef } from \"./secrets\";\nimport type { Service } from \"./types\";\n\n/** What `put` returns: the id to keep, and what was stored. */\nexport interface StoredFile {\n id: string;\n size: number;\n contentType: string;\n}\n\n/** File methods inside one tenant. Ids are the ones `put` returned; nothing takes a key, a path or a URL. */\nexport interface ScopedFiles {\n /** Stores the file under a new id Brick generates. `contentType` defaults to the file's own type. */\n put(file: Blob, options?: { contentType?: string }): Promise<StoredFile>;\n /** A short-lived signed link that downloads the file as an attachment. `expiresInMs` defaults to 5 minutes. */\n url(\n id: string,\n options?: { expiresInMs?: number; download?: string },\n ): Promise<string>;\n /** The file, or `undefined` when this tenant has none with that id. */\n get(id: string): Promise<Blob | undefined>;\n /** Removes the file; does nothing when this tenant has none with that id. */\n delete(id: string): Promise<void>;\n}\n\n/**\n * The handle of a file storage. In a call, `ctx.deps.<name>` is scoped to the\n * caller's tenant; outside one, name the tenant with `in(tenant)`.\n */\nexport interface FileStorage extends ScopedFiles {\n readonly kind: \"file\";\n /** The files of one tenant, for server code outside a request: a listener, a schedule, a webhook. */\n in(tenant: string): ScopedFiles;\n}\n\n/** A file storage as a call sees it in `ctx.deps`: the caller's tenant only, with no `in`. */\nexport interface CallFiles extends ScopedFiles {\n readonly kind: \"file\";\n}\n\n/** Deps as a call sees them: each file storage scoped to the caller's tenant. */\nexport type CallDeps<T> = { [K in keyof T]: CallDep<T[K]> };\ntype CallDep<V> = V extends FileStorage ? CallFiles : V;\n\nexport type RawDeps<T> = { [K in keyof T]: RawDep<T[K]> };\ntype RawDep<V> = V extends CallFiles ? FileStorage : V;\n\n/** A driver for file storage, such as `s3()`. It sees full keys; the handle builds them. */\nexport interface FileDriver {\n readonly kind: \"file\";\n /** Put in front of every key. */\n readonly prefix: string;\n /** The directory files are written under, in local mode. */\n readonly local?: string;\n /** Throws when the driver cannot work as configured; `brick()` calls it at startup. */\n check?(): void;\n write(key: string, file: Blob, contentType: string): Promise<void>;\n read(key: string): Promise<Blob | undefined>;\n remove(key: string): Promise<void>;\n /** A signed GET for the key, served with `contentDisposition`. */\n sign(\n key: string,\n expiresInMs: number,\n contentDisposition: string,\n ): Promise<string>;\n}\n\ntype Setting = string | SecretRef<string>;\n\n/** Options of the `s3()` storage driver. Settings left out come from Bun's `S3_*` and `AWS_*` environment variables. */\nexport interface S3StorageOptions {\n bucket?: string;\n /** Put in front of every key, such as `\"files/\"`. */\n prefix?: string;\n /** A directory: store files there instead of S3, for local development and tests. */\n local?: string;\n accessKeyId?: Setting;\n secretAccessKey?: Setting;\n sessionToken?: Setting;\n region?: Setting;\n /** An S3-compatible endpoint, such as R2 or MinIO. */\n endpoint?: Setting;\n}\n\nconst DEFAULT_EXPIRY_MS = 5 * 60_000;\n/** The longest a link may last: S3 refuses a presigned URL valid for longer. */\nconst MAX_EXPIRY_MS = 7 * 24 * 60 * 60_000;\nconst S3_READ_IDLE_TIMEOUT_MS = 30_000;\nexport const LOCAL_FILES_ROUTE = \"/_brick/files\";\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\nconst drivers: WeakMap<object, FileDriver> = ((globalThis as any)[\n Symbol.for(\"brickkit.storage.files\")\n] ??= new WeakMap());\n\nconst sha256 = (value: string) =>\n createHash(\"sha256\").update(value).digest(\"hex\");\n\nfunction tenantKey(tenant: unknown, local = false): string {\n if (\n typeof tenant !== \"string\" ||\n !tenant ||\n tenant === \".\" ||\n tenant === \"..\" ||\n !tenant.isWellFormed()\n )\n throw new Error(\n `File storage: the tenant must be a non-empty, well-formed string other than \".\" and \"..\", got ${JSON.stringify(tenant)}`,\n );\n return local ? sha256(tenant) : encodeURIComponent(tenant);\n}\n\nfunction attachment(download: string | undefined): string {\n if (!download) return \"attachment\";\n const ascii = download.replace(/[^\\x20-\\x7e]|[\"\\\\]/g, \"_\");\n return `attachment; filename=\"${ascii}\"; filename*=UTF-8''${encodeURIComponent(download)}`;\n}\n\nfunction scoped(\n driver: FileDriver,\n tenant: () => Promise<string>,\n): ScopedFiles {\n const folder = async () =>\n `${driver.prefix}${tenantKey(await tenant(), !!driver.local)}/`;\n const keyOf = async (id: string) => {\n const at = await folder();\n return typeof id === \"string\" && UUID.test(id) ? at + id : undefined;\n };\n return Object.freeze({\n put: async (file: Blob, options?: { contentType?: string }) => {\n if (!(file instanceof Blob))\n throw new TypeError(\"File storage: put needs a Blob or a File\");\n const at = await folder();\n const id = crypto.randomUUID();\n // Normalised as a Blob does (it adds a charset only to a lowercase type), so `put` returns what `get` gives back.\n const given = (options?.contentType || file.type).toLowerCase();\n const contentType =\n new Blob([], { type: given }).type || \"application/octet-stream\";\n await driver.write(at + id, file, contentType);\n return { id, size: file.size, contentType };\n },\n url: async (\n id: string,\n options: { expiresInMs?: number; download?: string } = {},\n ) => {\n const key = await keyOf(id);\n if (!key)\n throw new Error(`File storage: ${JSON.stringify(id)} is not a file id`);\n const expiresInMs = options.expiresInMs ?? DEFAULT_EXPIRY_MS;\n if (!Number.isSafeInteger(expiresInMs) || expiresInMs <= 0)\n throw new Error(\n `File storage: expiresInMs must be a positive integer, got ${expiresInMs}`,\n );\n if (expiresInMs > MAX_EXPIRY_MS)\n throw new Error(\n `File storage: expiresInMs must be at most 7 days (${MAX_EXPIRY_MS}), got ${expiresInMs}`,\n );\n return driver.sign(key, expiresInMs, attachment(options.download));\n },\n get: async (id: string) => {\n const key = await keyOf(id);\n return key ? driver.read(key) : undefined;\n },\n delete: async (id: string) => {\n const key = await keyOf(id);\n if (key) await driver.remove(key);\n },\n });\n}\n\nexport function fileStorage(driver: FileDriver): FileStorage {\n const outside = () =>\n Promise.reject(\n new Error(\n \"File storage: there is no caller here to take the tenant from. In an action read ctx.deps.<name>; elsewhere name the tenant: files.in(tenantId)\",\n ),\n );\n const handle: FileStorage = Object.freeze({\n kind: \"file\",\n in: (tenant: string) => {\n tenantKey(tenant);\n return scoped(driver, async () => tenant);\n },\n put: outside,\n url: outside,\n get: outside,\n delete: outside,\n });\n drivers.set(handle, driver);\n return handle;\n}\n\nconst fileNames = new WeakMap<object, string[]>();\nconst views = new WeakMap<object, { deps: object; ctx: object }>();\n\nexport function hasFilesView(ctx: { deps?: unknown }, deps: object): boolean {\n const view = views.get(ctx.deps as object);\n return view?.deps === deps && view.ctx === ctx;\n}\n\nexport function scopeFiles<T extends Readonly<Record<string, unknown>>>(\n deps: T,\n ctx: object,\n): T {\n let names = fileNames.get(deps);\n if (!names)\n fileNames.set(\n deps,\n (names = Object.keys(deps).filter((name) =>\n drivers.has(deps[name] as object),\n )),\n );\n if (!names.length) return deps;\n const tenant = async () => {\n const identity = await identityOf(ctx);\n if (!identity?.tenant)\n throw new Error(\n \"File storage: this call has no tenant. The service's identity hook must return { id, tenant } for callers that use files; outside a request use files.in(tenantId)\",\n );\n return identity.tenant;\n };\n const copy: Record<string, unknown> = { ...deps };\n for (const name of names) {\n const handle = deps[name] as FileStorage;\n const files: CallFiles = Object.freeze({\n kind: \"file\",\n ...scoped(drivers.get(handle)!, tenant),\n });\n copy[name] = files;\n }\n const view = freezeAsBuiltDeps(copy);\n views.set(view, { deps, ctx });\n return view as T;\n}\n\nexport function checkFileStorages(\n service: Service<any, any>,\n deps: readonly Readonly<Record<string, unknown>>[],\n): void {\n if (hasIdentity(service)) return;\n for (const values of deps) {\n const name = Object.keys(values).find((key) =>\n drivers.has(values[key] as object),\n );\n if (name)\n throw new Error(\n `Service \"${service.name}\" has file storage \"${name}\" in its deps or a plugin's but no identity hook. Files are kept per tenant: add identity: (ctx) => ({ id, tenant }) to the service.`,\n );\n }\n}\n\nconst warned = new WeakSet<FileDriver>();\n\nexport function localFileDirs(\n deps: readonly Readonly<Record<string, unknown>>[],\n): Set<string> {\n const dirs = new Set<string>();\n for (const values of deps)\n for (const value of Object.values(values)) {\n const driver = drivers.get(value as object);\n driver?.check?.();\n if (!driver?.local) continue;\n dirs.add(driver.local);\n if (process.env.NODE_ENV === \"production\" && !warned.has(driver)) {\n warned.add(driver);\n console.warn(\n `[Brick-TS] A file storage stores files in the local directory ${driver.local} while NODE_ENV is production. Set local only for development and tests.`,\n );\n }\n }\n return dirs;\n}\n\n/**\n * File storage in S3 or an S3-compatible store (R2, MinIO), through Bun's\n * built-in client. Nothing connects or reads credentials until the first call.\n * With `local`, files are written under that directory instead.\n *\n * @param options - `bucket`, `prefix`, `local`, and the credentials and\n * `endpoint` Bun's client takes, each a string or a `SecretRef`; left out,\n * Bun's `S3_*` and `AWS_*` environment variables apply.\n */\nexport function s3(options: S3StorageOptions = {}): FileDriver {\n const prefix = options.prefix ?? \"\";\n if (\n prefix.startsWith(\"/\") ||\n prefix.split(\"/\").some((part) => part === \".\" || part === \"..\")\n )\n throw new Error(\n `s3(): prefix must not start with \"/\" or hold \".\" or \"..\" segments, got ${JSON.stringify(prefix)}`,\n );\n if (options.local !== undefined)\n return localDriver(resolve(options.local), prefix);\n let client: Bun.S3Client | undefined;\n // Read here, not at import; passed to the client, which reads the environment only at process start.\n const bucket = () =>\n options.bucket || process.env.S3_BUCKET || process.env.AWS_BUCKET;\n // Without a bucket, Bun's client would take the key's first segment, the tenant, for one.\n const check = () => {\n if (!bucket())\n throw new Error(\n \"s3(): no bucket. Pass bucket, set S3_BUCKET or AWS_BUCKET, or set local for a directory.\",\n );\n };\n const open = () => {\n if (client) return client;\n check();\n const settings: Record<string, string> = { bucket: bucket()! };\n for (const name of [\n \"accessKeyId\",\n \"secretAccessKey\",\n \"sessionToken\",\n \"region\",\n \"endpoint\",\n ] as const) {\n const value = options[name];\n if (value !== undefined)\n settings[name] = value instanceof SecretRef ? value.require() : value;\n }\n return (client = new Bun.S3Client(settings));\n };\n const presign = (\n key: string,\n expiresInMs: number,\n contentDisposition?: string,\n ) =>\n open().presign(key, {\n method: \"GET\",\n expiresIn: Math.ceil(expiresInMs / 1000),\n ...(contentDisposition && { contentDisposition }),\n });\n const rethrowWithoutUrl = async <T>(\n operation: string,\n run: () => Promise<T>,\n ) => {\n try {\n return await run();\n } catch (error) {\n const code = (error as { code?: unknown }).code;\n throw new Error(\n `File storage: S3 failed ${operation} a file${typeof code === \"string\" ? ` (${code})` : \"\"}`,\n );\n }\n };\n return {\n kind: \"file\",\n prefix,\n check,\n write: async (key, file, contentType) => {\n const client = open();\n await rethrowWithoutUrl(\"writing\", () =>\n client.write(key, file, { type: contentType }),\n );\n },\n read: async (key) => {\n const url = presign(key, 60_000);\n const stalled = new AbortController();\n let idle: ReturnType<typeof setTimeout> | undefined;\n const stillMoving = () => {\n clearTimeout(idle);\n idle = setTimeout(() => stalled.abort(), S3_READ_IDLE_TIMEOUT_MS);\n };\n stillMoving();\n try {\n const response = await rethrowWithoutUrl(\"reading\", () =>\n fetch(url, { signal: stalled.signal }),\n );\n if (response.status === 404) return undefined;\n if (!response.ok)\n throw new Error(\n `File storage: S3 answered ${response.status} reading a file`,\n );\n return await rethrowWithoutUrl(\"reading\", async () => {\n const chunks: Uint8Array[] = [];\n for await (const chunk of response.body ?? []) {\n stillMoving();\n chunks.push(chunk);\n }\n return new Blob(chunks as BlobPart[], {\n type: response.headers.get(\"content-type\") ?? \"\",\n });\n });\n } finally {\n clearTimeout(idle);\n }\n },\n remove: async (key) => {\n const client = open();\n await rethrowWithoutUrl(\"deleting\", () => client.delete(key));\n },\n sign: async (key, expiresInMs, contentDisposition) =>\n presign(key, expiresInMs, contentDisposition),\n };\n}\n\nconst perProcessLinkKey: Buffer = ((globalThis as any)[\n Symbol.for(\"brickkit.storage.files.linkKey\")\n] ??= randomBytes(32));\nconst mac = (payload: string) =>\n createHmac(\"sha256\", perProcessLinkKey).update(payload).digest();\n\ninterface LinkClaims {\n dirDigest: string;\n key: string;\n expiresAt: number;\n disposition: string;\n}\n\nexport function signFileLink(claims: LinkClaims): string {\n const payload = Buffer.from(JSON.stringify(claims)).toString(\"base64url\");\n return `${payload}.${mac(payload).toString(\"base64url\")}`;\n}\n\nfunction verifyFileLink(token: string | null): LinkClaims | undefined {\n const dot = token?.indexOf(\".\") ?? -1;\n if (!token || dot < 0) return undefined;\n const payload = token.slice(0, dot);\n const given = Buffer.from(token.slice(dot + 1), \"base64url\");\n const expected = mac(payload);\n if (given.length !== expected.length || !timingSafeEqual(given, expected))\n return undefined;\n try {\n const claims = JSON.parse(Buffer.from(payload, \"base64url\").toString());\n return typeof claims.expiresAt === \"number\" && claims.expiresAt > Date.now()\n ? claims\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function localPath(\n dir: string,\n key: string,\n): Promise<string | undefined> {\n const folder = relative(dir, dirname(join(dir, key)));\n if (folder.split(sep).includes(\"..\")) return undefined;\n try {\n const [root, real] = await Promise.all([\n realpath(dir),\n realpath(join(dir, folder)),\n ]);\n return real === join(root, folder) ? join(real, basename(key)) : undefined;\n } catch (error) {\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as { code?: string }).code!))\n return undefined;\n throw error;\n }\n}\n\nconst isFile = (path: string) =>\n lstat(path).then(\n (stat) => stat.isFile(),\n (error) => {\n if ([\"ENOENT\", \"ENOTDIR\"].includes(error.code)) return false;\n throw error;\n },\n );\n\nasync function readLocal(dir: string, key: string): Promise<Blob | undefined> {\n const path = await localPath(dir, key);\n if (!path || !(await isFile(path)) || !(await isFile(`${path}.type`)))\n return undefined;\n const type = await readFile(`${path}.type`, \"utf8\");\n return new Blob([await readFile(path)], { type });\n}\n\nconst outsideDir = () =>\n new Error(\n \"File storage: the file's folder is not inside the local directory; refusing to follow a symlink\",\n );\n\nfunction localDriver(dir: string, prefix: string): FileDriver {\n return {\n kind: \"file\",\n prefix,\n local: dir,\n write: async (key, file, contentType) => {\n await mkdir(dirname(join(dir, key)), { recursive: true });\n const path = await localPath(dir, key);\n if (!path) throw outsideDir();\n await Bun.write(`${path}.type`, contentType);\n await Bun.write(path, file);\n },\n read: (key) => readLocal(dir, key),\n remove: async (key) => {\n const path = await localPath(dir, key);\n if (!path) return;\n await rm(path, { force: true });\n await rm(`${path}.type`, { force: true });\n },\n sign: async (key, expiresInMs, contentDisposition) =>\n `${LOCAL_FILES_ROUTE}?token=${signFileLink({ dirDigest: sha256(dir), key, expiresAt: Date.now() + expiresInMs, disposition: contentDisposition })}`,\n };\n}\n\nexport function localFilesRoute(dirs: ReadonlySet<string>) {\n const byDigest = new Map([...dirs].map((dir) => [sha256(dir), dir]));\n return async ({ request }: { request: Request }): Promise<Response> => {\n const claims = verifyFileLink(\n new URL(request.url).searchParams.get(\"token\"),\n );\n const dir = claims && byDigest.get(claims.dirDigest);\n if (!claims || !dir)\n return new Response(\"Invalid or expired link\", { status: 403 });\n const file = await readLocal(dir, claims.key);\n if (!file) return new Response(\"Not found\", { status: 404 });\n return new Response(file, {\n headers: {\n \"content-type\": file.type,\n \"content-disposition\": claims.disposition,\n \"x-content-type-options\": \"nosniff\",\n \"cache-control\": \"private, no-store\",\n },\n });\n };\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. */\nexport const 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 let failure: unknown;\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 timer.unref();\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 failure = undefined;\n connected(client);\n for (const wake of waiters.splice(0)) wake();\n },\n (error) => {\n failure = error;\n lost(client);\n },\n );\n };\n return {\n get(): RedisClient | undefined {\n start();\n return redis?.connected ? redis : undefined;\n },\n failure: () => failure,\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 { createHash } from \"node:crypto\";\nimport { fileStorage, type FileDriver, type FileStorage } from \"./file-storage\";\nimport { connection, REDIS_WAIT_MS } from \"./socket-redis\";\nimport { portOf } from \"./service-port\";\nimport type { Service } from \"./types\";\n\n/** What `increment` returns: the count after this hit, and when the counter expires. */\nexport interface Counter {\n count: number;\n expiresInMs: number;\n}\n\n/** What `putIfAbsent` returns: whether this call stored its value, and the value now stored. */\nexport interface PutIfAbsentResult {\n stored: boolean;\n value: string;\n}\n\n/** Key-value methods: values are strings, durations are milliseconds. */\ninterface KeyValueMethods {\n /** The value, or `null` when the key is missing or expired. */\n get(key: string): Promise<string | null>;\n /** Stores the value; without `ttlMs` it never expires. */\n put(key: string, value: string, ttlMs?: number): Promise<void>;\n /** Stores the value unless the key exists; says whether it did, and the value now stored. Atomic. */\n putIfAbsent(\n key: string,\n value: string,\n ttlMs: number,\n ): Promise<PutIfAbsentResult>;\n /** Adds 1 to a counter that expires `ttlMs` after its first hit. Atomic. Throws on a key that holds something other than an integer. */\n increment(key: string, ttlMs: number): Promise<Counter>;\n delete(key: string): Promise<void>;\n /** Closes the connection, if any. The next call opens a new one. */\n close(): Promise<void>;\n}\n\n/** A driver for key-value storage, such as `redis()` or `memory()`. It sees full keys. */\nexport interface KeyValueDriver extends KeyValueMethods {\n readonly kind: \"key-value\";\n /** Deletes the key only while it holds exactly `expected`; says whether it did. Atomic. */\n compareAndDelete(key: string, expected: string): Promise<boolean>;\n}\n\n/** Every kind of storage driver; `kind` decides the handle `defineStorage` returns. */\nexport type StorageDriver = KeyValueDriver | FileDriver;\n\n/** The handle of a key-value storage. App keys live apart from Brick's own. */\nexport interface KeyValueStorage extends KeyValueMethods {\n readonly kind: \"key-value\";\n}\n\nexport interface FrameworkStorage extends KeyValueStorage {\n compareAndDelete(key: string, expected: string): Promise<boolean>;\n}\n\n/** The handle `defineStorage` returns for a driver. */\nexport type StorageOf<D extends StorageDriver> = D extends KeyValueDriver\n ? KeyValueStorage\n : D extends FileDriver\n ? FileStorage\n : never;\n\n/** A storage could not be reached, or did not answer in time. Thrown by every call while it is down. A write that rejects with it may still have been applied. */\nexport class StorageUnavailableError extends Error {\n override readonly name = \"StorageUnavailableError\";\n static [Symbol.hasInstance](value: unknown): boolean {\n if (this !== StorageUnavailableError)\n return Function.prototype[Symbol.hasInstance].call(this, value);\n return value instanceof Error && value.name === \"StorageUnavailableError\";\n }\n}\n\nconst APP_PREFIX = \"app:\";\nconst BRICK_PREFIX = \"brick:storage:\";\n\n/** The framework side of each storage handle; global so a second core copy finds it. */\nconst frameworkSides: WeakMap<object, FrameworkStorage> = ((globalThis as any)[\n Symbol.for(\"brickkit.storage\")\n] ??= new WeakMap());\n\nconst users: WeakMap<object, number> = ((globalThis as any)[\n Symbol.for(\"brickkit.storage.users\")\n] ??= new WeakMap());\n\nfunction notACounter(key: string): Error {\n return new Error(`Storage: \"${key}\" does not hold a counter`);\n}\n\nfunction counterOverflow(key: string): Error {\n return new Error(`Storage: incrementing \"${key}\" would overflow`);\n}\n\nfunction ttl(ttlMs: number | undefined, required: boolean): void {\n if (ttlMs === undefined && !required) return;\n if (!Number.isSafeInteger(ttlMs) || ttlMs! <= 0)\n throw new Error(`Storage ttlMs must be a positive integer, got ${ttlMs}`);\n}\n\nexport function storageKey(feature: string, parts: unknown[]): string {\n return `${feature}:${JSON.stringify(\n parts.map((part) =>\n typeof part === \"string\" && part.length > 128\n ? { sha256: createHash(\"sha256\").update(part).digest(\"hex\") }\n : part,\n ),\n )}`;\n}\n\nfunction side(driver: KeyValueDriver, prefix: string) {\n return Object.freeze({\n kind: \"key-value\",\n get: async (key: string) => driver.get(prefix + key),\n put: async (key: string, value: string, ttlMs?: number) => {\n ttl(ttlMs, false);\n return driver.put(prefix + key, value, ttlMs);\n },\n putIfAbsent: async (key: string, value: string, ttlMs: number) => {\n ttl(ttlMs, true);\n return driver.putIfAbsent(prefix + key, value, ttlMs);\n },\n increment: async (key: string, ttlMs: number) => {\n ttl(ttlMs, true);\n return driver.increment(prefix + key, ttlMs);\n },\n delete: async (key: string) => driver.delete(prefix + key),\n close: async () => driver.close(),\n } as const);\n}\n\n/**\n * Declare a storage. The driver decides its kind: `redis()` and `memory()` make\n * key-value storage, `s3()` file storage kept per tenant. Pass it to a service\n * as a dep, and read it as `ctx.deps.<name>`. Nothing connects until the first call.\n *\n * @param options - `driver`: `redis({ url })`, or `memory()` for tests and local\n * development; `s3({ bucket, prefix, local })` for files.\n * @returns The handle. Key-value: `get`, `put`, `putIfAbsent`, `increment`,\n * `delete` and `close`. File: `put`, `url`, `get`, `delete` in the caller's\n * tenant, and `in(tenant)` outside a request.\n * @example\n * export const cache = defineStorage({ driver: redis({ url: process.env.REDIS_URL }) });\n * export const auth = defineService(\"auth\", { deps: { cache } });\n * // in an action\n * await ctx.deps.cache.put(`otp:${input.email}`, code, 5 * 60_000);\n */\nexport function defineStorage<D extends StorageDriver>(options: {\n driver: D;\n}): StorageOf<D> {\n const driver = options?.driver;\n if (driver?.kind === \"file\") return fileStorage(driver) as StorageOf<D>;\n if (driver?.kind !== \"key-value\")\n throw new Error(\n \"defineStorage needs a driver, such as redis(), memory() or s3()\",\n );\n const handle = side(driver, APP_PREFIX);\n frameworkSides.set(\n handle,\n Object.freeze({\n ...side(driver, BRICK_PREFIX),\n compareAndDelete: async (key: string, expected: string) =>\n driver.compareAndDelete(BRICK_PREFIX + key, expected),\n }),\n );\n return handle as StorageOf<D>;\n}\n\nexport function serviceStorage(\n service: Service<any, any>,\n deps: Readonly<Record<string, unknown>> = portOf(service).deps,\n): FrameworkStorage | undefined {\n // One handle under two names is one storage.\n const found = Object.entries(deps).filter(\n ([, value], index, all) =>\n frameworkSides.has(value as object) &&\n all.findIndex(([, other]) => other === value) === index,\n );\n if (found.length > 1)\n throw new Error(\n `Service \"${service.name}\" has two key-value storages in its deps, \"${found[0]![0]}\" and \"${found[1]![0]}\"; Brick needs one for its own keys. Keep one of them on this service.`,\n );\n return found[0] && frameworkSides.get(found[0][1] as object);\n}\n\nexport function useStorages(\n deps: readonly Readonly<Record<string, unknown>>[],\n): () => Promise<void> {\n const handles = new Set(\n deps.flatMap((values) =>\n Object.values(values).filter((value) =>\n frameworkSides.has(value as object),\n ),\n ) as KeyValueStorage[],\n );\n for (const handle of handles) users.set(handle, (users.get(handle) ?? 0) + 1);\n let released = false;\n return async () => {\n if (released) return;\n released = true;\n const unused = [...handles].filter((handle) => {\n const left = users.get(handle)! - 1;\n users.set(handle, left);\n return left === 0;\n });\n await Promise.all(unused.map((handle) => handle.close()));\n };\n}\n\n/** Options of the `redis()` storage driver. */\nexport interface RedisStorageOptions {\n /** Defaults to `REDIS_URL`, then `redis://localhost:6379`. */\n url?: string;\n /** Put in front of every key, Brick's own included, so two apps or environments can share one Redis database. */\n prefix?: string;\n}\n\nconst NOT_A_COUNTER = \"BRICK_NOT_A_COUNTER\";\nconst INCREMENT = `local n = redis.pcall('INCR', KEYS[1])\nif type(n) == 'table' and n.err then\n if string.find(n.err, '^WRONGTYPE') or string.find(n.err, 'not an integer') then return redis.error_reply('${NOT_A_COUNTER}') end\n return n\nend\nlocal t = redis.call('PTTL', KEYS[1])\nif t < 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) t = tonumber(ARGV[1]) end\nreturn {n, t}`;\nconst PUT_IF_ABSENT = `if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', ARGV[2]) then return {1, ARGV[1]} end\nreturn {0, redis.call('GET', KEYS[1])}`;\nconst COMPARE_AND_DELETE = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end\nreturn 0`;\nconst TIMED_OUT = Symbol(\"timed out\");\nconst UNAVAILABLE_REPLY =\n /^(LOADING|READONLY|OOM|BUSY|MASTERDOWN|CLUSTERDOWN|NOREPLICAS|MISCONF|TRYAGAIN)\\b/;\n\n/**\n * Key-value storage in Redis, through Bun's built-in client. Connects on first\n * use and reconnects by itself. While Redis is unreachable, calls reject with\n * `StorageUnavailableError`: the first after about a second, the rest at once.\n * A command Redis doesn't answer within a second rejects the same way, and the\n * connection is dropped so the next call opens a fresh one.\n *\n * @param options - `url`: defaults to `REDIS_URL`, then `redis://localhost:6379`.\n * `prefix`: put in front of every key, to share one Redis database between apps.\n */\nexport function redis(options: RedisStorageOptions = {}): KeyValueDriver {\n const prefix = options.prefix ?? \"\";\n let conn: ReturnType<typeof connection> | undefined;\n let down = false;\n const send = async (command: string, args: string[]): Promise<any> => {\n const current = (conn ??= connection(options.url, () => {\n down = false;\n }));\n if (!down) await current.opened(REDIS_WAIT_MS);\n const closedMeanwhile = () => conn !== current;\n const client = current.get();\n if (!client) {\n if (!closedMeanwhile()) down = true;\n throw new StorageUnavailableError(\"Storage: Redis is unreachable\", {\n cause: current.failure(),\n });\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n client.send(command, args),\n new Promise((_, reject) => {\n timer = setTimeout(reject, REDIS_WAIT_MS, TIMED_OUT);\n }),\n ]);\n } catch (error) {\n if (error === TIMED_OUT) {\n if (!closedMeanwhile()) {\n conn = undefined;\n down = false;\n }\n current.close();\n throw new StorageUnavailableError(\n `Storage: Redis did not answer within ${REDIS_WAIT_MS} ms`,\n );\n }\n if (client.connected) {\n if (UNAVAILABLE_REPLY.test(String((error as Error)?.message)))\n throw new StorageUnavailableError(\n `Storage: Redis cannot serve the command right now (${(error as Error).message})`,\n { cause: error },\n );\n throw error;\n }\n throw new StorageUnavailableError(\n \"Storage: the Redis connection was lost\",\n { cause: error },\n );\n } finally {\n clearTimeout(timer);\n }\n };\n return {\n kind: \"key-value\",\n get: (key) => send(\"GET\", [prefix + key]),\n put: async (key, value, ttlMs) => {\n const args = [prefix + key, value];\n await send(\n \"SET\",\n ttlMs === undefined ? args : [...args, \"PX\", String(ttlMs)],\n );\n },\n putIfAbsent: async (key, value, ttlMs) => {\n const [stored, now] = await send(\"EVAL\", [\n PUT_IF_ABSENT,\n \"1\",\n prefix + key,\n value,\n String(ttlMs),\n ]);\n return { stored: stored === 1, value: now };\n },\n increment: async (key, ttlMs) => {\n const [count, expiresInMs] = await send(\"EVAL\", [\n INCREMENT,\n \"1\",\n prefix + key,\n String(ttlMs),\n ]).catch((error) => {\n throw String(error?.message).includes(NOT_A_COUNTER)\n ? notACounter(key)\n : error;\n });\n return {\n count: Number(count),\n expiresInMs: Math.max(1, Number(expiresInMs)),\n };\n },\n delete: async (key) => {\n await send(\"DEL\", [prefix + key]);\n },\n compareAndDelete: async (key, expected) =>\n (await send(\"EVAL\", [\n COMPARE_AND_DELETE,\n \"1\",\n prefix + key,\n expected,\n ])) === 1,\n close: async () => {\n conn?.close();\n conn = undefined;\n down = false;\n },\n };\n}\n\n/**\n * Key-value storage in this process's memory, for tests and local development.\n * Lost on restart and not shared between processes.\n */\nexport function memory(): KeyValueDriver {\n const entries = new Map<string, { value: string; expiresAt?: number }>();\n const readEvictingExpired = (key: string) => {\n const entry = entries.get(key);\n if (entry?.expiresAt !== undefined && entry.expiresAt <= Date.now()) {\n entries.delete(key);\n return undefined;\n }\n return entry;\n };\n const expiry = (ttlMs?: number) =>\n ttlMs === undefined ? undefined : Date.now() + ttlMs;\n return {\n kind: \"key-value\",\n get: async (key) => readEvictingExpired(key)?.value ?? null,\n put: async (key, value, ttlMs) => {\n entries.set(key, { value, expiresAt: expiry(ttlMs) });\n },\n putIfAbsent: async (key, value, ttlMs) => {\n const entry = readEvictingExpired(key);\n if (entry) return { stored: false, value: entry.value };\n entries.set(key, { value, expiresAt: expiry(ttlMs) });\n return { stored: true, value };\n },\n increment: async (key, ttlMs) => {\n const entry = readEvictingExpired(key) ?? { value: \"0\" };\n // What Redis's INCR takes: a plain integer, no spaces, signs, exponents or leading zeros.\n const count = Number(entry.value) + 1;\n if (!/^(0|-?[1-9][0-9]*)$/.test(entry.value)) throw notACounter(key);\n if (!Number.isSafeInteger(count)) throw counterOverflow(key);\n const expiresAt = entry.expiresAt ?? Date.now() + ttlMs;\n entries.set(key, { value: String(count), expiresAt });\n return { count, expiresInMs: Math.max(1, expiresAt - Date.now()) };\n },\n delete: async (key) => {\n entries.delete(key);\n },\n compareAndDelete: async (key, expected) =>\n readEvictingExpired(key)?.value === expected && entries.delete(key),\n close: async () => {},\n };\n}\n","import {\n ActionExecutionError,\n type ActionContext,\n type Service,\n} from \"./types\";\nimport { hasIdentity, identityOf } from \"./identity\";\nimport { isIPv4, isIPv6 } from \"node:net\";\nimport {\n serviceStorage,\n storageKey,\n StorageUnavailableError,\n type Counter,\n type KeyValueStorage,\n} from \"./storage\";\n\n/**\n * A limit on how often an action runs: at most `max` calls per `windowMs`, per key.\n * A fixed window, counted in the service's key-value storage.\n */\nexport interface RateLimit<TInput = any, TCtx = ActionContext> {\n /**\n * Whose calls count together: `\"actor\"` (the service's `identity` id; an\n * anonymous caller counts by IP), `\"ip\"` (the client address; skipped when\n * there is none, as in-process), or a function of the validated input and\n * the context. A function that returns `null` or `undefined` skips this\n * limit for the call.\n */\n per:\n | \"actor\"\n | \"ip\"\n | ((args: { input: TInput; ctx: TCtx }) => string | null | undefined);\n /** Calls allowed per window. */\n max: number;\n /** The window's length in milliseconds. */\n windowMs: number;\n}\n\n/** Where an app finds the client address, given the request and the socket peer: a non-empty string, or `undefined` for none. */\nexport type ClientIp = (args: {\n request: Request;\n peer: string | undefined;\n}) => string | undefined;\n\ninterface AddressSource {\n clientIp?: ClientIp;\n server: () =>\n | { requestIP(request: Request): { address: string } | null }\n | null\n | undefined;\n}\nconst SOURCE = Symbol.for(\"brickkit.addressSource\");\nconst CLIENT_REQUEST = Symbol.for(\"brickkit.clientRequest\");\n\nexport function markAddressSource(\n request: Request,\n source: AddressSource,\n): void {\n (request as any)[SOURCE] = source;\n}\n\nexport function withClientIp(request: Request, clientIp: ClientIp): void {\n const app: AddressSource | undefined = (request as any)[SOURCE];\n markAddressSource(request, { clientIp, server: app?.server ?? noServer });\n}\nconst noServer = () => undefined;\n\nexport function clientRequestOf(ctx: object): Request | undefined {\n const request: any =\n (ctx as any)[CLIENT_REQUEST] ?? (ctx as { request?: Request }).request;\n return request?.[SOURCE] ? request : undefined;\n}\n\nexport function carryClientRequest(envelope: object, from: object): void {\n const request = clientRequestOf(from);\n if (request) (envelope as any)[CLIENT_REQUEST] = request;\n}\n\n/**\n * The client address of a call as rate limits count it, or `undefined` when it\n * has none: in-process without a request, or `app.handle` without `clientIp`.\n * An IPv4-mapped or NAT64 IPv6 address counts as its IPv4 address, any other\n * IPv6 address by its /64, and every spelling of one address the same. For a\n * custom `per` that combines it with another key.\n *\n * @throws When `clientIp` returns anything but a non-empty string or `undefined`.\n */\nexport function clientAddress(ctx: object): string | undefined {\n const request = clientRequestOf(ctx);\n if (!request) return undefined;\n const source: AddressSource = (request as any)[SOURCE];\n const peer = source.server()?.requestIP(request)?.address ?? undefined;\n const ip: unknown = source.clientIp\n ? source.clientIp({ request, peer })\n : peer;\n if (ip !== undefined && (typeof ip !== \"string\" || ip === \"\"))\n throw new Error(\n `clientIp must return a non-empty string, or undefined when there is no address; it returned ${ip === \"\" ? \"an empty string\" : ip instanceof Promise ? \"a promise (it must not be async)\" : String(ip)}`,\n );\n return ip === undefined ? undefined : addressKey(ip as string);\n}\n\nfunction addressKey(address: string): string {\n const ip = address.trim().toLowerCase().replace(/%.*$/, \"\");\n if (isIPv4(ip)) return ip;\n if (!isIPv6(ip)) return address;\n const [head = \"\", tail] = ip.split(\"::\");\n const split = (part: string | undefined) => (part ? part.split(\":\") : []);\n const left = split(head);\n const right = split(tail);\n const groups = (part: string[]) =>\n part.flatMap((group) => {\n if (!group.includes(\".\")) return [parseInt(group, 16)];\n const [a, b, c, d] = group.split(\".\").map(Number) as number[];\n return [(a! << 8) | b!, (c! << 8) | d!];\n });\n const l = groups(left);\n const r = groups(right);\n const all = [...l, ...Array(8 - l.length - r.length).fill(0), ...r];\n // Mapped (::ffff:a.b.c.d) and translated (64:ff9b::a.b.c.d, RFC 6052) IPv4.\n const head6 = all.slice(0, 6).join(\":\");\n if (head6 === \"0:0:0:0:0:65535\" || head6 === \"100:65435:0:0:0:0\")\n return [all[6]! >> 8, all[6]! & 255, all[7]! >> 8, all[7]! & 255].join(\".\");\n return `${all\n .slice(0, 4)\n .map((g) => g.toString(16))\n .join(\":\")}::/64`;\n}\n\nexport function rateLimitsOf(config: {\n name: string;\n rateLimit?: RateLimit | readonly RateLimit[];\n}): readonly RateLimit[] | undefined {\n const { rateLimit } = config;\n if (rateLimit === undefined) return undefined;\n const limits: readonly RateLimit[] = Array.isArray(rateLimit)\n ? rateLimit\n : [rateLimit as RateLimit];\n if (!limits.length)\n throw new Error(\n `Action '${config.name}': rateLimit is an empty list, which limits nothing. Give it at least one limit, or remove it.`,\n );\n for (const { per, max, windowMs } of limits)\n if (\n !(per === \"actor\" || per === \"ip\" || typeof per === \"function\") ||\n !Number.isSafeInteger(max) ||\n max < 1 ||\n !Number.isSafeInteger(windowMs) ||\n windowMs < 1\n )\n throw new Error(\n `Action '${config.name}': each rateLimit needs per (\"actor\", \"ip\" or a function) and max and windowMs as positive integers`,\n );\n return limits;\n}\n\nexport function checkRateLimits(\n service: Service<any, any>,\n action: { name: string; config: { name: string; rateLimit?: any } },\n deps: Readonly<Record<string, unknown>>,\n): void {\n const limits = rateLimitsOf(action.config);\n if (!limits) return;\n if (!storageOf(service, deps)) throw noStorage(service, action.name);\n if (limits.some((limit) => limit.per === \"actor\") && !hasIdentity(service))\n throw new Error(\n `Service \"${service.name}\": action '${action.name}' limits per \"actor\", but the service declares no identity. Add identity: (ctx) => ctx.user && { id: ctx.user.id } to defineService(\"${service.name}\", { ... }).`,\n );\n}\n\nfunction storageOf(\n service: Service<any, any>,\n deps: Readonly<Record<string, unknown>>,\n): KeyValueStorage | undefined {\n return serviceStorage(service, deps) ?? serviceStorage(service);\n}\n\nfunction noStorage(service: Service<any, any>, action: string): Error {\n return new Error(\n `Service \"${service.name}\": action '${action}' declares rateLimit, but the service has no key-value storage to count in. Add one: defineService(\"${service.name}\", { deps: { cache: defineStorage({ driver: redis() }) } }).`,\n );\n}\n\ninterface Fallback {\n active: boolean;\n counters: Map<string, { count: number; expiresAt: number }>;\n probeAt: number;\n healthySince?: number;\n sweepAt: number;\n}\nconst QUIET_MS = 10_000;\nconst PROBE_MS = 1_000;\nconst SWEEP_MS = 1_000;\nconst fallbacks = new WeakMap<KeyValueStorage, Fallback>();\n\nfunction countInMemory(\n fallback: Fallback,\n key: string,\n windowMs: number,\n now: number,\n): Counter {\n if (now >= fallback.sweepAt) sweep(fallback, now);\n let entry = fallback.counters.get(key);\n if (!entry || entry.expiresAt <= now)\n fallback.counters.set(\n key,\n (entry = { count: 0, expiresAt: now + windowMs }),\n );\n entry.count++;\n return {\n count: entry.count,\n expiresInMs: Math.max(1, entry.expiresAt - now),\n };\n}\n\nfunction sweep(fallback: Fallback, now: number): void {\n for (const [key, entry] of fallback.counters)\n if (entry.expiresAt <= now) fallback.counters.delete(key);\n fallback.sweepAt = now + SWEEP_MS;\n}\n\nconst isTimeToProbe = (fallback: Fallback, now: number): boolean =>\n now >= fallback.probeAt;\n\nconst hasBeenHealthyLongEnough = (fallback: Fallback, now: number): boolean =>\n fallback.healthySince !== undefined &&\n now - fallback.healthySince >= QUIET_MS;\n\nfunction enterFallback(fallback: Fallback, now: number, cause: Error): void {\n Object.assign(fallback, {\n active: true,\n probeAt: now + PROBE_MS,\n healthySince: undefined,\n });\n console.warn(\n `[Brick-TS] Rate limits: storage is unavailable (${cause.message}); counting in this process's memory until it is back.`,\n );\n}\n\nfunction leaveFallback(fallback: Fallback): void {\n fallback.active = false;\n console.warn(\n \"[Brick-TS] Rate limits: storage is back; counting there again.\",\n );\n}\n\nfunction probe(\n storage: KeyValueStorage,\n fallback: Fallback,\n key: string,\n windowMs: number,\n): void {\n const answered = () => {\n const now = Date.now();\n fallback.healthySince ??= now;\n if (fallback.active && hasBeenHealthyLongEnough(fallback, now))\n leaveFallback(fallback);\n };\n storage.increment(key, windowMs).then(answered, (error) => {\n if (error instanceof StorageUnavailableError)\n fallback.healthySince = undefined;\n else answered();\n });\n}\n\nasync function increment(\n storage: KeyValueStorage,\n key: string,\n windowMs: number,\n): Promise<Counter> {\n let fallback = fallbacks.get(storage);\n if (fallback) {\n const now = Date.now();\n if (fallback.active) {\n if (isTimeToProbe(fallback, now)) {\n fallback.probeAt = now + PROBE_MS;\n probe(storage, fallback, key, windowMs);\n }\n return countInMemory(fallback, key, windowMs, now);\n }\n if (now >= fallback.sweepAt) {\n sweep(fallback, now);\n if (!fallback.counters.size) fallbacks.delete(storage);\n }\n }\n try {\n return await storage.increment(key, windowMs);\n } catch (error) {\n if (!(error instanceof StorageUnavailableError)) throw error;\n const now = Date.now();\n fallback = fallbacks.get(storage);\n if (!fallback)\n fallbacks.set(\n storage,\n (fallback = {\n active: false,\n counters: new Map(),\n probeAt: 0,\n sweepAt: now + SWEEP_MS,\n }),\n );\n if (!fallback.active) enterFallback(fallback, now, error);\n return countInMemory(fallback, key, windowMs, now);\n }\n}\n\nasync function keyOf(\n limit: RateLimit,\n input: unknown,\n ctx: ActionContext,\n): Promise<string[] | undefined> {\n if (typeof limit.per === \"function\") {\n const key: unknown = limit.per({ input, ctx });\n if (typeof (key as { then?: unknown } | null)?.then === \"function\") {\n Promise.resolve(key).catch(() => {});\n throw new Error(\n \"rateLimit per must return a string, null or undefined; it returned a promise (it must not be async)\",\n );\n }\n return key == null ? undefined : [\"key\", String(key)];\n }\n if (limit.per === \"actor\") {\n const identity = await identityOf(ctx);\n if (identity) return [\"actor\", identity.id];\n }\n const ip = clientAddress(ctx);\n return ip === undefined ? undefined : [\"ip\", ip];\n}\n\nexport async function enforceRateLimits(\n service: Service<any, any> | undefined,\n kind: \"action\" | \"tool\",\n action: string,\n limits: readonly RateLimit[],\n input: unknown,\n ctx: ActionContext,\n): Promise<void> {\n if (!service)\n throw new Error(\n `Action '${action}' declares rateLimit, but it is not registered on a service`,\n );\n const storage = storageOf(service, ctx.deps as any);\n if (!storage) throw noStorage(service, action);\n for (const [index, limit] of limits.entries()) {\n const key = await keyOf(limit, input, ctx);\n if (!key) continue;\n const { count, expiresInMs } = await increment(\n storage,\n storageKey(\"rate-limit\", [service.name, kind, action, index, ...key]),\n limit.windowMs,\n );\n if (count > limit.max) {\n const retryAfterSeconds = Math.max(1, Math.ceil(expiresInMs / 1000));\n throw new ActionExecutionError(\n \"RATE_LIMITED\",\n `Too many calls to '${action}'; retry in ${retryAfterSeconds} s`,\n 429,\n { retryAfterSeconds },\n );\n }\n }\n}\n","import type { BaseContext, Logger, Service } from \"./types\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\nimport { dashboardIdentity } from \"./dashboard-identity\";\nimport { attachIdentity } from \"./identity\";\nimport { carryClientRequest } from \"./rate-limit\";\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nconst EMPTY = Object.freeze({});\nconst defaultLogger: Logger = createLogger(DEFAULT_LOG_PREFIXES);\n/** Random, so ids never repeat across restarts or processes. */\nconst newId = (kind: \"tr\" | \"req\") => `${kind}_${crypto.randomUUID()}`;\n\n/**\n * The trace and request ids of an HTTP request: the caller's `x-trace-id` and\n * `x-request-id` headers, else fresh ones. Both are echoed on the response.\n */\nexport function requestIds(\n headers: Record<string, string | undefined> | undefined,\n set: { headers?: Record<string, unknown> } | undefined,\n): { traceId: string; requestId: string } {\n const traceId = headers?.[\"x-trace-id\"] || newId(\"tr\");\n const requestId = headers?.[\"x-request-id\"] || newId(\"req\");\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n return { traceId, requestId };\n}\n\n/**\n * The framework fields of an action context: what the caller gave, the rest\n * defaulted. A missing trace or request id gets a fresh `tr_`/`req_` one.\n */\nexport function baseContext(\n fields: Partial<BaseContext> & { deps?: Readonly<Record<string, unknown>> },\n): BaseContext & { deps: Readonly<Record<string, unknown>> } {\n return {\n request: fields.request ?? DEFAULT_REQUEST,\n db: fields.db,\n logger: fields.logger ?? defaultLogger,\n traceId: fields.traceId ?? newId(\"tr\"),\n requestId: fields.requestId ?? newId(\"req\"),\n services: fields.services ?? EMPTY,\n metadata: fields.metadata ?? EMPTY,\n deps: fields.deps ?? EMPTY,\n dashboard: fields.dashboard ?? dashboardIdentity(fields.request),\n };\n}\n\ntype ContextEnvelope = Pick<\n BaseContext,\n \"caller\" | \"traceId\" | \"requestId\" | \"tenantId\" | \"dashboard\"\n> & { user?: unknown };\n\nexport function pickContextEnvelope(\n context?: Partial<BaseContext> & { user?: unknown },\n): Partial<ContextEnvelope> {\n if (!context) return {};\n const envelope: Partial<ContextEnvelope> = {};\n if (context.caller !== undefined) envelope.caller = context.caller;\n if (context.user !== undefined) envelope.user = context.user;\n if (context.traceId !== undefined) envelope.traceId = context.traceId;\n if (context.requestId !== undefined) envelope.requestId = context.requestId;\n if (context.tenantId !== undefined) envelope.tenantId = context.tenantId;\n // In process only: the identity was verified when the outer request arrived.\n if (context.dashboard !== undefined) envelope.dashboard = context.dashboard;\n carryClientRequest(envelope, context);\n return envelope;\n}\n\nconst RESOLVED = Symbol(\"resolved\");\nconst OWN_DEPS = Symbol(\"ownDeps\");\n\nexport function markResolved(\n ctx: object,\n service: Service<any, any>,\n ownDeps: Readonly<Record<string, unknown>>,\n): void {\n const marked = ctx as Record<PropertyKey, unknown>;\n marked[RESOLVED] = service;\n marked[OWN_DEPS] = ownDeps;\n attachIdentity(marked, service, ownDeps);\n}\n\nexport function resolvedDeps(\n ctx: unknown,\n service: Service<any, any>,\n): Readonly<Record<string, unknown>> | undefined {\n const marked = ctx as Record<PropertyKey, any> | undefined;\n return marked?.[RESOLVED] === service ? marked[OWN_DEPS] : undefined;\n}\n\nexport function serviceOf(ctx: object): Service<any, any> | undefined {\n return (ctx as Record<PropertyKey, any>)[RESOLVED];\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport { actionMeta } from \"./action-meta\";\nimport type {\n AuditConfig,\n Action,\n ActionErrorDefinition,\n ErrorBuilder,\n RateLimits,\n Service,\n} from \"./types\";\nimport { checkRateLimits } from \"./rate-limit\";\nimport { serviceStorage } from \"./storage\";\n\n/** What a verifier sees of a delivery. */\nexport interface WebhookRequest {\n /** The body exactly as it arrived. */\n rawBody: Uint8Array;\n headers: Headers;\n url: string;\n method: string;\n}\n\n/**\n * Decides whether the provider sent a delivery. `false`, or a throw, refuses it\n * (401); `true` accepts; `{ eventId }` accepts and names the event.\n * Set `suppliesEventId` on a verifier that always returns one, so a webhook\n * needs no `eventId` option.\n */\nexport type WebhookVerifier = ((\n request: WebhookRequest,\n) =>\n | boolean\n | { eventId: string | number }\n | Promise<boolean | { eventId: string | number }>) & {\n suppliesEventId?: true;\n /** Set on a verifier that signs the body (a GET has none, so it cannot serve one). */\n signsBody?: true;\n};\n\n/** What `service.webhook` takes. */\nexport interface WebhookConfig<\n TInput extends TSchema,\n TErrors extends Record<string, ActionErrorDefinition>,\n TContext,\n> {\n /** Its route is `<method> /api/<service>/<name>` (POST by default), as for an action. */\n name: string;\n description?: string;\n /** Relative to the service, as for an action. */\n path?: string;\n /** Default `\"POST\"`. With `\"GET\"` the input is the query string. */\n method?: \"POST\" | \"GET\";\n /** Runs first, on the raw body. Nothing else runs until it accepts. */\n verify: WebhookVerifier;\n /** The payload: JSON, or a form (`application/x-www-form-urlencoded`). Properties it does not declare are dropped. */\n input: TInput;\n /**\n * The delivery's id, so one sent twice runs once: a non-empty string or a\n * safe integer (`7` and `\"7\"` are one id); anything else, `undefined`\n * included, is no id. Not needed when the verifier supplies one.\n */\n eventId?: (args: {\n input: Static<TInput>;\n headers: Headers;\n url: string;\n method: string;\n }) => string | number | undefined | Promise<string | number | undefined>;\n /** `false` runs every delivery, with no check for repeats. Else `ttlMs` is how long a handled id is remembered (default 7 days). */\n replay?: false | { ttlMs?: number };\n /** Largest body accepted, in bytes (default 1 MiB). */\n maxBodyBytes?: number;\n rateLimit?: RateLimits<Static<TInput>, TContext>;\n /** The delivery's audit row when the service's database holds an audit table: written when the handler returns, not for a refused or repeated delivery or one whose handler throws. `false` leaves it out. */\n audit?: AuditConfig<Static<TInput>>;\n errors?: TErrors;\n tags?: string[];\n /** What the provider is answered: the return value, which may be a `Response`; `{ ok: true }` for nothing. */\n execute: (params: {\n input: Static<TInput>;\n ctx: TContext;\n error: ErrorBuilder<TErrors>;\n /** `undefined` when `replay` is `false` and the delivery has no id. */\n eventId: string | undefined;\n }) => unknown;\n}\n\nexport interface WebhookDefinition {\n readonly verify: WebhookVerifier;\n readonly eventId?: WebhookConfig<any, any, any>[\"eventId\"];\n readonly replay: false | { readonly ttlMs: number };\n readonly maxBodyBytes: number;\n}\n\nexport const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;\nexport const DEFAULT_REPLAY_TTL_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport function webhookOf(\n action: object | undefined,\n): WebhookDefinition | undefined {\n return action ? actionMeta(action).webhook : undefined;\n}\n\n/** Whether an action was declared with `service.webhook`. */\nexport function isWebhook(action: object): boolean {\n return webhookOf(action) !== undefined;\n}\n\nexport function defineWebhookMeta(\n service: string,\n config: WebhookConfig<any, any, any>,\n): WebhookDefinition {\n const where = `Service \"${service}\": webhook '${config?.name}'`;\n if (typeof config?.verify !== \"function\")\n throw new Error(\n `${where} needs verify: a verifier such as hmacSignature({ secret, header }), standardWebhooks({ secret }) or twilioSignature({ authToken, url }), or your own (request) => boolean. A webhook cannot run without one.`,\n );\n if (!config.input || typeof config.input !== \"object\")\n throw new Error(\n `${where} needs input: the schema of the payload, such as t.Object({ ... }).`,\n );\n if (config.method !== undefined && ![\"POST\", \"GET\"].includes(config.method))\n throw new Error(`${where}: method must be \"POST\" or \"GET\".`);\n if (config.method === \"GET\" && config.verify.signsBody)\n throw new Error(\n `${where}: method \"GET\" has no body, and this verifier signs the body, so it would accept one signature for every query. Use twilioSignature (it signs the URL) or a verifier of your own, or method \"POST\".`,\n );\n for (const option of [\"authorize\", \"output\"])\n if ((config as object as Record<string, unknown>)[option] !== undefined)\n throw new Error(\n `${where}: ${option} is not an option of a webhook, and would be ignored. verify is the check.`,\n );\n const { maxBodyBytes = DEFAULT_MAX_BODY_BYTES, replay } = config;\n if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1)\n throw new Error(`${where}: maxBodyBytes must be a positive integer.`);\n const ttlMs =\n replay === false ? undefined : (replay?.ttlMs ?? DEFAULT_REPLAY_TTL_MS);\n if (ttlMs !== undefined && (!Number.isSafeInteger(ttlMs) || ttlMs < 1))\n throw new Error(`${where}: replay.ttlMs must be a positive integer.`);\n return {\n verify: config.verify,\n eventId: config.eventId,\n replay: ttlMs === undefined ? false : { ttlMs },\n maxBodyBytes,\n };\n}\n\nexport function checkWebhook(\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n deps: Readonly<Record<string, unknown>>,\n): void {\n const webhook = webhookOf(action);\n if (!webhook) return;\n checkRateLimits(service, action, deps);\n if (webhook.replay === false) return;\n const where = `Service \"${service.name}\": webhook '${action.name}'`;\n if (!webhook.eventId && !webhook.verify.suppliesEventId)\n throw new Error(\n `${where} has no event id to tell deliveries apart by, so a delivery sent twice would run twice. Add eventId: ({ input }) => input.id, reading an id from a field of the signed payload (an id from a header the signature does not cover only removes accidental duplicates: anyone who captured a delivery can resend it with another id), use a verifier that supplies one (standardWebhooks), or set replay: false to run every delivery.`,\n );\n if (!serviceStorage(service))\n throw new Error(\n `${where} remembers the events it has handled, but the service has no key-value storage. Add one: defineService(\"${service.name}\", { deps: { cache: defineStorage({ driver: redis() }) } }), or set replay: false.`,\n );\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst sqliteQueues = new WeakMap<object, Promise<unknown>>();\n\ninterface OpenTransaction {\n /** The handles a nested call can pass to join this transaction. */\n handles: Set<unknown>;\n commits: (() => unknown)[];\n open: boolean;\n savepoints: number;\n}\nconst active = new AsyncLocalStorage<OpenTransaction>();\n\nfunction joined(db: unknown): OpenTransaction | undefined {\n const open = active.getStore();\n return open?.open && open.handles.has(db) ? open : undefined;\n}\n\nexport function isSqliteDatabase(db: any): boolean {\n return (\n typeof db?.$client?.prepare === \"function\" &&\n typeof db?.$client?.run === \"function\"\n );\n}\n\nfunction rollbackQuietly(db: any, statement = \"ROLLBACK\"): void {\n try {\n db.$client.run(statement);\n } catch {\n return;\n }\n}\n\nasync function nested<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const commits = open.commits.length;\n try {\n if (!isSqliteDatabase(db))\n // Drizzle runs a nested transaction as a savepoint.\n return await db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n const name = `brick_${++open.savepoints}`;\n db.$client.run(`SAVEPOINT ${name}`);\n try {\n const result = await fn(db);\n db.$client.run(`RELEASE ${name}`);\n return result;\n } catch (error) {\n rollbackQuietly(db, `ROLLBACK TO ${name}`);\n rollbackQuietly(db, `RELEASE ${name}`);\n throw error;\n }\n } catch (error) {\n // Work that was rolled back must not run its commit callbacks.\n open.commits.length = commits;\n throw error;\n }\n}\n\n/**\n * Run `fn` in a database transaction: everything it writes through the `tx` it is\n * given is committed together when it returns, or undone if it throws.\n *\n * Postgres uses a real transaction on one connection. SQLite has one connection\n * and a synchronous driver, which Drizzle's own `transaction` cannot use with an\n * async callback (it would commit before the callback finished). So transactions\n * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.\n * A write made elsewhere in the process during that time, outside this helper,\n * would join the transaction; use Postgres where that matters.\n *\n * A call made inside `fn` with the `tx` it was given (on SQLite, the database\n * itself) joins the open transaction as a savepoint instead of waiting for it: a\n * nested failure undoes only the nested work, and the outer transaction decides\n * the commit. Nested calls must run one at a time.\n *\n * @param db - A Drizzle database, from `service.getDb()`.\n * @param fn - Receives the transaction handle to run queries on.\n * @returns What `fn` returned.\n * @throws What `fn` threw, after rolling back.\n */\nexport async function runInTransaction<T>(\n db: any,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const outer = joined(db);\n if (outer) return nested(db, outer, fn);\n const open: OpenTransaction = {\n handles: new Set(),\n commits: [],\n open: true,\n savepoints: 0,\n };\n let result: T;\n try {\n result = await active.run(open, () => begin(db, open, fn));\n } finally {\n open.open = false;\n }\n for (const commit of open.commits) await commit();\n return result;\n}\n\nasync function begin<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n if (!isSqliteDatabase(db)) {\n return db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n }\n\n open.handles.add(db);\n const previous = sqliteQueues.get(db) ?? Promise.resolve();\n let release!: () => void;\n const turn = new Promise<void>((resolve) => {\n release = resolve;\n });\n sqliteQueues.set(\n db,\n previous.then(() => turn),\n );\n await previous;\n try {\n db.$client.run(\"BEGIN IMMEDIATE\");\n try {\n const result = await fn(db);\n db.$client.run(\"COMMIT\");\n return result;\n } catch (error) {\n rollbackQuietly(db);\n throw error;\n }\n } finally {\n release();\n }\n}\n\n/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */\nexport function inTransaction(db: unknown): boolean {\n return joined(db) !== undefined;\n}\n\n/**\n * Run `fn` once the transaction that `db` belongs to has committed, or now when\n * `db` is not in one opened by `runInTransaction`. It never runs when that\n * transaction, or the savepoint it was queued in, rolls back. An error it throws\n * reaches the caller of the outermost `runInTransaction`, after the commit.\n *\n * @param db - The handle the work ran on: a `tx`, or a database.\n * @param fn - The side effect, such as clearing a cache.\n */\nexport async function onTransactionCommit(\n db: unknown,\n fn: () => unknown,\n): Promise<void> {\n const open = joined(db);\n if (open) open.commits.push(fn);\n else await fn();\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n bigserial,\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\";\nimport { actionMeta } from \"./action-meta\";\nimport { serviceOf } from \"./context\";\nimport { sharedAcrossCoreCopies } from \"./deps\";\nimport {\n inTransaction,\n isSqliteDatabase,\n onTransactionCommit,\n runInTransaction,\n} from \"./events/transaction\";\nimport { identityOf } from \"./identity\";\nimport { actionMethod } from \"./routes\";\nimport { portOf, type ServicePort } from \"./service-port\";\nimport type { Action, ActionContext } from \"./types\";\n\nconst AUDIT = Symbol.for(\"brick.audit\");\n\nfunction sqliteAudit(name: string) {\n return sqliteTable(name, {\n seq: sqliteInteger(\"seq\").primaryKey({ autoIncrement: true }),\n id: sqliteText(\"id\").notNull().unique(),\n at: sqliteInteger(\"at\", { mode: \"timestamp_ms\" }).notNull(),\n service: sqliteText(\"service\").notNull(),\n action: sqliteText(\"action\").notNull(),\n resource: sqliteText(\"resource\"),\n recordId: sqliteText(\"record_id\"),\n actorId: sqliteText(\"actor_id\"),\n actorLabel: sqliteText(\"actor_label\"),\n tenant: sqliteText(\"tenant\"),\n traceId: sqliteText(\"trace_id\"),\n requestId: sqliteText(\"request_id\"),\n meta: sqliteText(\"meta\", { mode: \"json\" }),\n });\n}\n\nfunction postgresAudit(name: string) {\n return pgTable(name, {\n seq: bigserial(\"seq\", { mode: \"number\" }).primaryKey(),\n id: pgText(\"id\").notNull().unique(),\n at: timestamp(\"at\", { withTimezone: true }).notNull(),\n service: pgText(\"service\").notNull(),\n action: pgText(\"action\").notNull(),\n resource: pgText(\"resource\"),\n recordId: pgText(\"record_id\"),\n actorId: pgText(\"actor_id\"),\n actorLabel: pgText(\"actor_label\"),\n tenant: pgText(\"tenant\"),\n traceId: pgText(\"trace_id\"),\n requestId: pgText(\"request_id\"),\n meta: jsonb(\"meta\"),\n });\n}\n\n/** The audit table of a SQLite database. */\nexport type SQLiteAuditTable = ReturnType<typeof sqliteAudit>;\n/** The audit table of a Postgres database. */\nexport type PostgresAuditTable = ReturnType<typeof postgresAudit>;\n/** An audit table, made by `auditTable`. */\nexport type AuditTable = SQLiteAuditTable | PostgresAuditTable;\n\n/**\n * The audit table: one row per change, saying who made it, what ran and on\n * which record. A service whose database holds it records every create, update\n * and delete, every command, and every other action that is not a `GET`.\n * Brick only ever inserts into it; the docs give the trigger that makes the\n * database refuse anything else.\n *\n * Brick does not create tables for you. Put this in the schema of the database\n * and your migration tool (such as drizzle-kit) creates it. The service must\n * declare an `identity` hook: that is where the actor comes from.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_audit`.\n * @returns A Drizzle table, which you can also read with a resource of your own.\n * @example\n * import { auditTable, defineDatabase } from \"@brickkit/core\";\n *\n * export const auditLog = auditTable(\"postgres\");\n * export const database = defineDatabase({\n * engine: \"postgres\",\n * tables: { orders, auditLog },\n * });\n */\nexport function auditTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteAuditTable;\nexport function auditTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresAuditTable;\nexport function auditTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): AuditTable {\n const name = options.name ?? \"brick_audit\";\n const table = engine === \"sqlite\" ? sqliteAudit(name) : postgresAudit(name);\n Object.defineProperty(table, AUDIT, { value: { engine } });\n return table;\n}\n\n/** Whether a value is an audit table made by `auditTable`. */\nexport function isAuditTable(value: unknown): value is AuditTable {\n return typeof value === \"object\" && value !== null && AUDIT in value;\n}\n\ninterface AuditOptions {\n resource?: string;\n record?: (args: { input: any; result: any }) => unknown;\n}\n\nexport interface AuditStage {\n readonly service: ServicePort<any, any>;\n readonly table: AuditTable;\n readonly action: string;\n readonly recordsInOwnTransaction: boolean;\n readonly resource?: string;\n readonly record?: AuditOptions[\"record\"];\n}\n\nexport function auditStage(\n service: ServicePort<any, any>,\n action: Action<any, any, any, any>,\n): AuditStage | undefined {\n const table = service.getAuditTable();\n const config = action.config as { audit?: false | AuditOptions };\n if (!table || config.audit === false) return undefined;\n const { audit: mode, resourceAction } = actionMeta(action);\n if (mode === \"none\" || (!mode && actionMethod(action) === \"GET\"))\n return undefined;\n return {\n service,\n table,\n action: action.name,\n recordsInOwnTransaction: mode === \"inline\",\n resource: config.audit?.resource ?? resourceAction?.resource,\n record:\n config.audit?.record ??\n (resourceAction?.record ? ({ input }) => input.id : undefined),\n };\n}\n\ninterface Call {\n readonly audit: AuditStage;\n written: boolean;\n}\nconst calls = sharedAcrossCoreCopies(\n \"brickkit.audit.calls\",\n () => new AsyncLocalStorage<Call>(),\n);\n\nexport function runUnaudited<T>(run: () => T): T {\n return calls.getStore() ? calls.exit(run) : run();\n}\n\nexport interface Entry {\n action: string;\n resource?: string;\n recordId?: unknown;\n meta?: unknown;\n}\n\nfunction recordIdText(id: unknown): string | null {\n if (id === undefined || id === null) return null;\n if (typeof id === \"string\") return id;\n if (typeof id === \"number\" || typeof id === \"bigint\") return String(id);\n return JSON.stringify(id) ?? null;\n}\n\nasync function auditRow(\n ctx: { traceId?: string; requestId?: string },\n target: Pick<AuditStage, \"service\">,\n entry: Entry,\n) {\n const who = await identityOf(ctx);\n return {\n id: crypto.randomUUID(),\n at: new Date(),\n service: target.service.name,\n action: entry.action,\n resource: entry.resource ?? null,\n recordId: recordIdText(entry.recordId),\n actorId: who?.id ?? null,\n actorLabel: who?.label ?? null,\n tenant: who?.tenant ?? null,\n traceId: ctx.traceId ?? null,\n requestId: ctx.requestId ?? null,\n meta: entry.meta ?? null,\n };\n}\n\nfunction insertOutsideOtherRequestsTransactions<T>(\n db: any,\n fn: (handle: any) => Promise<T>,\n): Promise<T> {\n return isSqliteDatabase(db) && !inTransaction(db)\n ? runInTransaction(db, fn)\n : fn(db);\n}\n\nasync function writeAudit(\n handle: any,\n ctx: { traceId?: string; requestId?: string },\n target: Pick<AuditStage, \"service\" | \"table\">,\n entry: Entry,\n): Promise<void> {\n await handle.insert(target.table).values(await auditRow(ctx, target, entry));\n}\n\nfunction resolveActorBeforeAction(ctx: ActionContext) {\n return identityOf(ctx);\n}\n\nfunction buildRow(audit: AuditStage, ctx: ActionContext) {\n return auditRow(ctx, audit, {\n action: audit.action,\n resource: audit.resource,\n });\n}\n\nfunction setRecordIdOf(\n row: Awaited<ReturnType<typeof auditRow>>,\n audit: AuditStage,\n input: unknown,\n result: unknown,\n) {\n row.recordId = recordIdText(audit.record?.({ input, result }));\n}\n\nexport async function runAudited(\n audit: AuditStage,\n input: unknown,\n ctx: ActionContext,\n run: () => Promise<unknown>,\n): Promise<unknown> {\n await resolveActorBeforeAction(ctx);\n const call: Call = { audit, written: false };\n const result = await calls.run(call, run);\n if (!audit.recordsInOwnTransaction && !call.written) {\n let row: Awaited<ReturnType<typeof auditRow>> | undefined;\n try {\n row = await buildRow(audit, ctx);\n setRecordIdOf(row, audit, input, result);\n await insertOutsideOtherRequestsTransactions(ctx.db, (tx) =>\n tx.insert(audit.table).values(row),\n );\n } catch (error) {\n ctx.logger?.error?.(\n `audit: '${audit.action}' ran but its audit row was not written`,\n row,\n error,\n );\n }\n }\n return result;\n}\n\nexport function entryOf(\n audit: AuditStage,\n input: unknown,\n result: unknown,\n): Entry {\n return {\n action: audit.action,\n resource: audit.resource,\n recordId: audit.record?.({ input, result }),\n };\n}\n\nexport function inlineAudit(): AuditStage | undefined {\n const audit = calls.getStore()?.audit;\n return audit?.recordsInOwnTransaction ? audit : undefined;\n}\n\nexport function recordInline(\n audit: AuditStage,\n tx: unknown,\n ctx: ActionContext,\n entry: Entry,\n): Promise<void> {\n return writeAudit(tx, ctx, audit, entry);\n}\n\nfunction commitsWithBrickTransaction(tx: unknown, ctx: ActionContext) {\n return tx === ctx.db || inTransaction(tx);\n}\n\n/**\n * Record a change of your own from an action: for what Brick cannot see, or to\n * add `meta`. By default the row is inserted at once. Pass the `tx` of a\n * transaction you have open to commit it with your writes instead; once `tx`\n * commits it is the record of this call, and Brick does not add the automatic row.\n *\n * Brick copies no input or output into the log: `meta` holds what you pass.\n *\n * @param ctx - The action context: it names the service and the actor.\n * @param entry - `action` defaults to the running action's name, and is needed\n * in an action that is not itself recorded (a `GET`, `audit: false`).\n * `resource` and `recordId` say which record; `meta` is JSON of your choosing.\n * @param options - `tx`: an open transaction on the service's database.\n * @throws When `ctx` is not from an action of a service whose database holds an\n * audit table (a listener, a schedule or a workflow step has no such context),\n * or when `action` is missing.\n * @example\n * await runInTransaction(ctx.db, async (tx) => {\n * await tx.update(orders).set({ status: \"refunded\" }).where(eq(orders.id, input.orderId));\n * await recordAudit(ctx, { resource: \"order\", recordId: input.orderId, meta: { reason: input.reason } }, { tx });\n * });\n */\nexport async function recordAudit(\n ctx: ActionContext,\n entry: {\n action?: string;\n resource?: string;\n recordId?: string | number;\n meta?: unknown;\n },\n options: { tx?: unknown } = {},\n): Promise<void> {\n const service = serviceOf(ctx);\n const table = service && portOf(service).getAuditTable();\n if (!service || !table)\n throw new Error(\n \"recordAudit needs the ctx of an action of a service whose database holds an audit table\",\n );\n const call = calls.getStore();\n const action = entry.action ?? call?.audit.action;\n if (!action)\n throw new Error(\n \"recordAudit needs an action: it defaults to the running action only when that action is recorded\",\n );\n const target = { service: portOf(service), table };\n const named = { ...entry, action };\n if (options.tx === undefined)\n await insertOutsideOtherRequestsTransactions(ctx.db, (tx) =>\n writeAudit(tx, ctx, target, named),\n );\n else {\n await writeAudit(options.tx, ctx, target, named);\n if (call && commitsWithBrickTransaction(options.tx, ctx))\n await onTransactionCommit(options.tx, () => (call.written = true));\n }\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type Action,\n type ActionContext,\n type Logger,\n type ValidationErrorItem,\n} from \"../types\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport { toErrorResponse } from \"../error-response\";\nimport { recordWebhook } from \"../telemetry\";\nimport {\n serviceStorage,\n StorageUnavailableError,\n storageKey,\n type FrameworkStorage,\n} from \"../storage\";\nimport { webhookOf, type WebhookDefinition } from \"../webhook\";\nimport { baseContext, markResolved, requestIds } from \"../context\";\nimport { scopeFiles } from \"../file-storage\";\nimport type { ServicePort } from \"../service-port\";\nimport { enforceRateLimits, rateLimitsOf } from \"../rate-limit\";\nimport {\n auditStage,\n runAudited,\n runUnaudited,\n type AuditStage,\n} from \"../audit\";\nimport { withRedaction, type Sensitivity } from \"../sensitive\";\nimport type { Coercion, RouteIR } from \"./ir\";\n\n/*\n * The action pipeline, as stages: request ids → read input → validate →\n * rate limit → authorize → [audit] → execute → validate output → map error. `bindRoute` runs them\n * for an HTTP route; `action.execute` runs the same stages in-process.\n */\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\n/** @deprecated `brick build` no longer emits handler factories; see `bindCompiledApplication`. */\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\ninterface Checker {\n Check(value: unknown): boolean;\n Errors(value: unknown): Iterable<any>;\n}\n\n/** Everything one route needs to answer a request, worked out once at startup. */\nexport interface CompiledRoutePlan {\n readonly route: RouteIR;\n readonly service: ServicePort;\n readonly action: Action<any, any, any, any>;\n readonly execute: (params: any) => unknown;\n readonly authorize?: (params: any) => boolean | Promise<boolean>;\n readonly contextHook?: (baseCtx: any) => unknown;\n readonly inputChecker?: Checker;\n readonly outputChecker?: Checker;\n readonly sensitive?: Sensitivity;\n /** A plugin's check that runs before `inputChecker`. */\n readonly checkInput?: (input: unknown) => ValidationErrorItem[] | undefined;\n readonly errorBuilder: unknown;\n readonly logger: Logger;\n readonly cachedDb: unknown;\n /** The deps of the plugin install that created the action; else the service's. */\n readonly deps?: Readonly<Record<string, unknown>>;\n}\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true; // NOSONAR\n return false;\n}\n\n/** One source alone is the input as it is; several merge, later ones winning. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction coerceScalar(value: unknown, type: Coercion | undefined) {\n if (typeof value !== \"string\") return value;\n if (type === \"number\") {\n const number = Number(value);\n return Number.isNaN(number) ? value : number;\n }\n if (type === \"boolean\") {\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n }\n if (type === \"json\") {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n }\n return value;\n}\n\nfunction coerceQueryValue(\n value: unknown,\n { key, type, items }: RouteIR[\"coercions\"][number],\n request: Request | undefined,\n) {\n if (type !== \"array\") return coerceScalar(value, type);\n const values = request ? new URL(request.url).searchParams.getAll(key) : [];\n const list = values.length ? values : Array.isArray(value) ? value : [value];\n return list.map((item) => coerceScalar(item, items));\n}\n\nexport const BODY_TOO_LARGE = Symbol(\"brick.bodyTooLarge\");\n\nexport function bodyLimitParser(limit: number) {\n return ({ request }: { request: Request }) =>\n Number(request.headers.get(\"content-length\")) > limit\n ? BODY_TOO_LARGE\n : undefined;\n}\n\nexport function rawBodyParser(limit: number) {\n return async ({ request }: { request: Request }) => {\n if (Number(request.headers.get(\"content-length\")) > limit)\n return BODY_TOO_LARGE;\n const chunks: Uint8Array[] = [];\n let size = 0;\n if (request.body)\n for await (const chunk of request.body as AsyncIterable<Uint8Array>) {\n size += chunk.byteLength;\n if (size > limit) return BODY_TOO_LARGE;\n chunks.push(chunk);\n }\n return new Uint8Array(Buffer.concat(chunks));\n };\n}\n\n/** The action's input from the path, query and body, coerced by its schema. */\nexport function readInput(\n route: RouteIR,\n { params, body, query, request }: any,\n): unknown {\n if (body === BODY_TOO_LARGE)\n throw new ActionExecutionError(\n \"PAYLOAD_TOO_LARGE\",\n `Request body exceeds ${route.bodyLimit} bytes`,\n 413,\n );\n if (!route.input) return undefined;\n let coercedQuery = query;\n let coercedParams = params;\n let coercedBody = body;\n if (route.coercions.length) {\n if (query) {\n coercedQuery = { ...query };\n for (const coercion of route.coercions)\n if (query[coercion.key] !== undefined)\n coercedQuery[coercion.key] = coerceQueryValue(\n query[coercion.key],\n coercion,\n request,\n );\n }\n // Form fields arrive as strings, and a single file as itself, like query values.\n if (\n body &&\n request?.headers.get(\"content-type\")?.startsWith(\"multipart/form-data\")\n ) {\n coercedBody = { ...body };\n for (const coercion of route.coercions)\n if (body[coercion.key] !== undefined)\n coercedBody[coercion.key] = coerceQueryValue(\n body[coercion.key],\n coercion,\n undefined,\n );\n }\n for (const { key, type } of route.coercions) {\n if (type !== \"number\" || typeof params?.[key] !== \"string\") continue;\n const value = Number(params[key]);\n if (Number.isNaN(value)) continue;\n if (coercedParams === params) coercedParams = { ...params };\n coercedParams[key] = value;\n }\n }\n const input = route.readLike\n ? mergeInput(coercedQuery, coercedParams, coercedBody)\n : mergeInput(coercedParams, coercedBody, coercedQuery);\n return input === undefined &&\n (route.inputSchema as { type?: string } | undefined)?.type === \"object\"\n ? {}\n : input;\n}\n\n// Generic pre-validation nesting cap for parsed HTTP input. Compiled input\n// validators recurse, so unbounded nesting (e.g. a 20k-deep filter object)\n// would throw RangeError (HTTP 500) instead of failing validation with a\n// 400. The walk is iterative and far above legitimate depths (a max-depth\n// CRUD filter is ~45 levels of JSON).\nconst MAX_INPUT_DEPTH = 128;\nexport function inputTooDeep(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const stack: { node: unknown; depth: number }[] = [{ node: value, depth: 0 }];\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (depth > MAX_INPUT_DEPTH) return true;\n if (node && typeof node === \"object\") {\n const children = Array.isArray(node) ? node : Object.values(node);\n for (const child of children)\n if (child && typeof child === \"object\")\n stack.push({ node: child, depth: depth + 1 });\n }\n }\n return false;\n}\n\n/** The error for input (400) or output (500) that fails its schema. */\nexport function invalid(\n action: string,\n stage: \"input\" | \"output\",\n errors: ValidationErrorItem[],\n): ValidationError {\n return new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction validate(\n check: Checker,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n throw invalid(\n action,\n stage,\n Array.from(check.Errors(value), ({ path, message }) => ({ path, message })),\n );\n}\n\nfunction validateInput(\n check: Checker,\n input: unknown,\n action: string,\n checkInput: CompiledRoutePlan[\"checkInput\"],\n) {\n const errors = checkInput?.(input);\n if (errors) throw invalid(action, \"input\", errors);\n if (inputTooDeep(input))\n throw invalid(action, \"input\", [\n { path: \"\", message: \"Input exceeds maximum nesting depth\" },\n ]);\n validate(check, input, action, \"input\");\n}\n\n/** A refused `authorize`: 401 without a user, 403 with one. */\nexport function deny(action: string, user: unknown): never {\n throw new ActionExecutionError(\n user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${action}'`,\n user == null ? 401 : 403,\n );\n}\n\n/** Runs `authorize`, if any, and denies the call when it refuses. */\nasync function authorizeCall(\n authorize: ((params: any) => unknown) | undefined,\n ctx: { user?: unknown },\n input: unknown,\n action: string,\n): Promise<void> {\n if (authorize && !(await authorize({ ctx, input, user: ctx.user })))\n deny(action, ctx.user);\n}\n\n/** What a call runs once its context is ready. */\nexport interface Stages {\n readonly name: string;\n readonly dashboardOnly?: boolean;\n /** @throws The input's validation error. */\n readonly checkInput: (input: unknown) => void;\n readonly rateLimit?: (input: unknown, ctx: any) => Promise<void>;\n readonly authorize?: (params: any) => unknown;\n readonly audit?: AuditStage;\n readonly execute: (params: any) => unknown;\n readonly errorBuilder: unknown;\n /** @throws The output's validation error; else returns the output. */\n readonly checkOutput: (result: unknown) => unknown;\n readonly sensitive?: Sensitivity;\n}\n\n/** The stage order of every call, over HTTP and in-process: check input → rate limit → authorize → execute → check output. */\nexport async function runStages(\n stages: Stages,\n input: unknown,\n ctx: { user?: unknown; dashboard?: unknown },\n): Promise<unknown> {\n if (stages.dashboardOnly && !ctx.dashboard)\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Action '${stages.name}' is only for the dashboard`,\n 401,\n );\n stages.checkInput(input);\n stages.sensitive?.input(input);\n if (stages.rateLimit) await stages.rateLimit(input, ctx);\n await authorizeCall(stages.authorize, ctx, input, stages.name);\n const output = stages.audit\n ? await runAudited(stages.audit, input, ctx as ActionContext, async () =>\n stages.checkOutput(\n await stages.execute({ input, ctx, error: stages.errorBuilder }),\n ),\n )\n : stages.checkOutput(\n await runUnaudited(() =>\n stages.execute({ input, ctx, error: stages.errorBuilder }),\n ),\n );\n return stages.sensitive\n ? stages.sensitive.output(output, input, ctx)\n : output;\n}\n\nfunction mapError(\n err: unknown,\n set: any,\n options: { logger: Logger; requestId: string },\n) {\n const response = toErrorResponse(err, options);\n set.status = response.status;\n const retry = (\n response.details as { retryAfterSeconds?: unknown } | undefined\n )?.retryAfterSeconds;\n if (response.status === 429 && Number.isFinite(retry))\n set.headers[\"retry-after\"] = String(\n BigInt(Math.max(1, Math.ceil(retry as number))),\n );\n return response;\n}\n\nconst isThenable = (value: any): value is PromiseLike<unknown> =>\n value != null && typeof value.then === \"function\";\n\n/** The context of one HTTP request, with the trace and request id headers set. */\nfunction requestContext(\n plan: CompiledRoutePlan,\n { headers, request, set }: any,\n): ActionContext & { requestId: string } {\n const ctx = baseContext({\n ...requestIds(headers, set),\n request: request instanceof Request ? request : undefined,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n metadata: { headers },\n // resolveServiceContext's rule: the hook sees the service's deps; a plugin's action then gets its own.\n deps: plan.contextHook\n ? plan.service.deps\n : (plan.deps ?? plan.service.deps),\n });\n if (!plan.contextHook) resolveServiceDeps(ctx, plan);\n return ctx as ActionContext & { requestId: string };\n}\n\nconst HANDLED = \"handled\";\nconst IN_FLIGHT_CLAIM_MS = 5 * 60_000;\n\nconst eventIdFrom = (value: unknown): string | undefined =>\n Number.isSafeInteger(value)\n ? String(value)\n : typeof value === \"string\" && value\n ? value\n : undefined;\n\nconst refuse = (code: string, message: string, status: number) =>\n new ActionExecutionError(code, message, status);\n\nfunction fieldsOf(params: URLSearchParams): Record<string, unknown> {\n const grouped = new Map<string, string[]>();\n for (const [name, value] of params)\n grouped.set(name, [...(grouped.get(name) ?? []), value]);\n return Object.fromEntries(\n [...grouped].map(([name, values]) => [\n name,\n values.length > 1 ? values : values[0],\n ]),\n );\n}\n\nfunction webhookInput(route: RouteIR, request: Request, rawBody: Uint8Array) {\n const text = new TextDecoder().decode(rawBody);\n const form =\n route.method === \"GET\"\n ? new URL(request.url).searchParams\n : /^application\\/x-www-form-urlencoded/i.test(\n request.headers.get(\"content-type\") ?? \"\",\n )\n ? new URLSearchParams(text)\n : undefined;\n if (form) return readInput(route, { query: fieldsOf(form) });\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n throw invalid(route.action, \"input\", [\n { path: \"\", message: \"Body is not valid JSON\" },\n ]);\n }\n}\n\nfunction bindWebhook(plan: CompiledRoutePlan): CompiledHandler {\n const { execute } = plan;\n const name = plan.route.action;\n const webhook = webhookOf(plan.action)!;\n const limits = rateLimitsOf(plan.action.config);\n const audit = auditStage(plan.service, plan.action);\n const storage = webhook.replay ? serviceStorage(plan.service) : undefined;\n if (webhook.replay && !storage)\n throw new Error(\n `Webhook '${name}' remembers the events it has handled, but its service has no key-value storage`,\n );\n const brickWebhook = async (context: any) => {\n const delivery: Delivery = {\n plan,\n webhook,\n storage,\n limits,\n request: context.request,\n ctx: requestContext(plan, context),\n outcome: \"failed\",\n };\n try {\n rejectOversizedBody(delivery, context.body);\n const rawBody = rawBodyOf(context.body);\n await verifyDelivery(delivery, rawBody);\n const input = parseAndCheckInput(delivery, rawBody);\n plan.sensitive?.input(input);\n await resolveEventId(delivery, input);\n if ((await claimEvent(delivery)) === ALREADY_HANDLED)\n return { duplicate: true };\n\n let result: unknown;\n try {\n await resolveContext(delivery);\n await enforceWebhookRateLimits(delivery, input);\n const run = () =>\n execute({\n input,\n ctx: delivery.ctx,\n error: plan.errorBuilder,\n eventId: delivery.eventId,\n });\n result = audit\n ? await runAudited(audit, input, delivery.ctx, async () => run())\n : await runUnaudited(run);\n if (plan.sensitive && !(result instanceof Response))\n result = await plan.sensitive.output(result, input, delivery.ctx);\n } catch (error) {\n await releaseClaim(delivery);\n throw error;\n }\n await settleClaim(delivery, result);\n return result === undefined ? { ok: true } : result;\n } catch (err) {\n return mapError(err, context.set, delivery.ctx);\n } finally {\n recordWebhook(name, delivery.eventId, delivery.outcome);\n }\n };\n return plan.sensitive\n ? (context) => withRedaction(() => brickWebhook(context))\n : brickWebhook;\n}\n\ninterface Claim {\n readonly key: string;\n readonly mine: string;\n}\ninterface Delivery {\n readonly plan: CompiledRoutePlan;\n readonly webhook: WebhookDefinition;\n readonly storage: FrameworkStorage | undefined;\n readonly limits: ReturnType<typeof rateLimitsOf>;\n readonly request: Request;\n readonly ctx: ActionContext & { requestId: string };\n outcome: string;\n eventId?: string;\n claim?: Claim;\n}\n\nconst ALREADY_HANDLED = Symbol(\"alreadyHandled\");\n\nfunction rejectOversizedBody(delivery: Delivery, body: unknown) {\n if (body !== BODY_TOO_LARGE) return;\n delivery.outcome = \"too_large\";\n throw refuse(\n \"PAYLOAD_TOO_LARGE\",\n `Request body exceeds ${delivery.webhook.maxBodyBytes} bytes`,\n 413,\n );\n}\n\nconst rawBodyOf = (body: unknown) =>\n body instanceof Uint8Array ? body : new Uint8Array();\n\nfunction logVerifierThrowWithoutItsMessage(\n { plan, ctx }: Delivery,\n error: unknown,\n) {\n plan.logger.warn(\"A webhook verifier threw, so its delivery was refused\", {\n service: plan.service.name,\n webhook: plan.route.action,\n error: error instanceof Error ? error.constructor.name : typeof error,\n requestId: ctx.requestId,\n });\n}\n\nasync function verifyDelivery(delivery: Delivery, rawBody: Uint8Array) {\n const { webhook, request } = delivery;\n let verdict: unknown;\n try {\n verdict = await webhook.verify({\n rawBody,\n headers: request.headers,\n url: request.url,\n method: request.method,\n });\n } catch (error) {\n logVerifierThrowWithoutItsMessage(delivery, error);\n verdict = false;\n }\n const given = eventIdFrom((verdict as { eventId?: unknown } | null)?.eventId);\n if (verdict !== true && !given) {\n delivery.outcome = \"refused\";\n throw refuse(\"UNAUTHORIZED\", \"Webhook verification failed\", 401);\n }\n delivery.eventId = verdict === true ? undefined : given;\n}\n\nfunction parseAndCheckInput(delivery: Delivery, rawBody: Uint8Array) {\n const { plan, request } = delivery;\n const { route, inputChecker, checkInput } = plan;\n delivery.outcome = \"invalid\";\n let input = webhookInput(route, request, rawBody);\n if (inputChecker)\n validateInput(inputChecker, input, route.action, checkInput);\n input = Value.Clean(plan.action.config.input, input);\n delivery.outcome = \"failed\";\n return input;\n}\n\nasync function resolveEventId(delivery: Delivery, input: unknown) {\n const { webhook, request } = delivery;\n delivery.eventId ??= eventIdFrom(\n await webhook.eventId?.({\n input,\n headers: request.headers,\n url: request.url,\n method: request.method,\n }),\n );\n}\nasync function claimEvent(delivery: Delivery) {\n const { plan, storage, eventId } = delivery;\n if (!storage) return;\n if (!eventId) {\n delivery.outcome = \"no_event_id\";\n throw refuse(\"BAD_REQUEST\", \"The delivery has no event id\", 400);\n }\n const claim = (delivery.claim = {\n key: storageKey(\"webhook\", [plan.service.name, plan.route.action, eventId]),\n mine: `pending:${crypto.randomUUID()}`,\n });\n try {\n const claimed = await storage.putIfAbsent(\n claim.key,\n claim.mine,\n IN_FLIGHT_CLAIM_MS,\n );\n if (claimed.stored) return;\n if (claimed.value === HANDLED) {\n delivery.outcome = \"duplicate\";\n return ALREADY_HANDLED;\n }\n delivery.outcome = \"in_flight\";\n throw refuse(\n \"CONFLICT\",\n \"Another delivery of this event is being handled; retry later\",\n 409,\n );\n } catch (error) {\n if (!(error instanceof StorageUnavailableError)) throw error;\n releaseClaim(delivery);\n delivery.outcome = \"unavailable\";\n throw new ActionExecutionError(\n \"SERVICE_UNAVAILABLE\",\n \"Webhook storage is unavailable; retry later\",\n 503,\n undefined,\n { cause: error },\n );\n }\n}\n\nasync function resolveContext({ plan, ctx }: Delivery) {\n if (!plan.contextHook) return;\n const extra = await plan.contextHook(ctx);\n if (extra) Object.assign(ctx, extra);\n resolveServiceDeps(ctx, plan);\n}\n\nasync function enforceWebhookRateLimits(\n { plan, limits, ctx }: Delivery,\n input: unknown,\n) {\n if (limits)\n await enforceRateLimits(\n plan.service,\n \"action\",\n plan.route.action,\n limits,\n input,\n ctx,\n );\n}\nasync function releaseClaim({ storage, claim }: Delivery) {\n await storage?.compareAndDelete(claim!.key, claim!.mine).catch(() => {});\n}\nasync function settleClaim(delivery: Delivery, result: unknown) {\n const { plan, webhook, storage, claim, ctx } = delivery;\n const failed = result instanceof Response && result.status >= 400;\n if (storage && failed) await releaseClaim(delivery);\n else if (storage && webhook.replay)\n await storage\n .put(claim!.key, HANDLED, webhook.replay.ttlMs)\n .catch((error) =>\n plan.logger.warn(\n \"Webhook handled, but its id was not recorded; a retry may run it again\",\n { requestId: ctx.requestId },\n error,\n ),\n );\n delivery.outcome = failed ? \"failed\" : \"processed\";\n}\n\nfunction resolveServiceDeps(ctx: any, plan: CompiledRoutePlan) {\n markResolved(ctx, plan.service, plan.service.deps);\n ctx.deps = scopeFiles(plan.deps ?? plan.service.deps, ctx);\n}\n\n/** The HTTP handler of one route: the pipeline's stages, synchronous when no stage needs to wait. */\nexport function bindRoute(plan: CompiledRoutePlan): CompiledHandler {\n if (plan.route.kind === \"webhook\") return bindWebhook(plan);\n const {\n route,\n execute,\n contextHook,\n authorize,\n inputChecker,\n outputChecker,\n checkInput,\n errorBuilder,\n } = plan;\n const name = route.action;\n const limits = rateLimitsOf(plan.action.config);\n const audit = auditStage(plan.service, plan.action);\n const stages: Stages = {\n name,\n dashboardOnly: plan.action.config.dashboard === true,\n checkInput: (input) => {\n if (inputChecker) validateInput(inputChecker, input, name, checkInput);\n },\n rateLimit:\n limits &&\n ((input, ctx) =>\n enforceRateLimits(\n plan.service,\n (plan.action as { kind?: string }).kind === \"tool\"\n ? \"tool\"\n : \"action\",\n name,\n limits,\n input,\n ctx,\n )),\n authorize,\n audit,\n execute,\n errorBuilder,\n checkOutput: (result) => {\n if (outputChecker) validate(outputChecker, result, name, \"output\");\n return result;\n },\n sensitive: plan.sensitive,\n };\n if (\n contextHook ||\n authorize ||\n stages.dashboardOnly ||\n limits ||\n audit ||\n stages.sensitive\n ) {\n const brickAction = async (context: any) => {\n const ctx = requestContext(plan, context);\n try {\n const input = readInput(route, context);\n if (contextHook) {\n const extra = await contextHook(ctx);\n if (extra) Object.assign(ctx, extra);\n resolveServiceDeps(ctx, plan);\n }\n return await runStages(stages, input, ctx);\n } catch (err) {\n return mapError(err, context.set, ctx);\n }\n };\n return stages.sensitive\n ? (context) => withRedaction(() => brickAction(context))\n : brickAction;\n }\n // Nothing to wait for before `execute`: the same stages, without `authorize`, `rateLimit` or `audit`, synchronously.\n return function brickAction(context) {\n const ctx = requestContext(plan, context);\n try {\n const input = readInput(route, context);\n stages.checkInput(input);\n const result = execute({ input, ctx, error: errorBuilder });\n if (isThenable(result))\n return Promise.resolve(result)\n .then(stages.checkOutput)\n .catch((err) => mapError(err, context.set, ctx));\n return stages.checkOutput(result);\n } catch (err) {\n return mapError(err, context.set, ctx);\n }\n };\n}\n\n/** What `bindCompiledApplication`'s handler factories receive. */\nexport const compilerRuntime = Object.freeze({ bindRoute });\n","import type { TSchema } from \"@sinclair/typebox\";\nimport {\n type Action,\n type ActionConfigWithAuthorize,\n type ActionConfigWithoutAuthorize,\n type ActionContext,\n type ActionErrorDefinition,\n type ErrorBuilder,\n ActionExecutionError,\n} from \"./types\";\nimport { normalizeActionError } from \"./error-response\";\nimport { STANDARD_ERRORS } from \"./protocol\";\nimport { validateWithSchema } from \"./typebox\";\nimport { actionMeta } from \"./action-meta\";\nimport { baseContext } from \"./context\";\nimport { invalid, runStages, type Stages } from \"./compiler/runtime\";\nimport { enforceRateLimits, rateLimitsOf } from \"./rate-limit\";\nimport { auditStage, type AuditStage, type AuditTable } from \"./audit\";\nimport type { ServicePort } from \"./service-port\";\nimport { sensitivity, withRedaction } from \"./sensitive\";\n\n/**\n * The `error` helpers an action receives: one function per error code that\n * throws an `ActionExecutionError` with that code and status. The standard HTTP\n * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,\n * `RATE_LIMITED`, `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to\n * them or replace one.\n *\n * @param errorsDef - The action's `errors`: for each code, its `message` and\n * `status` (default 400).\n * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,\n * and always throw.\n */\nexport function buildErrorHelpers<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(errorsDef?: TErrors): ErrorBuilder<TErrors> {\n const helpers: Record<string, any> = {};\n // An action's own errors override the standard ones of the same code.\n for (const [code, def] of Object.entries({\n ...STANDARD_ERRORS,\n ...errorsDef,\n }) as [string, ActionErrorDefinition][])\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n throw new ActionExecutionError(\n code,\n overrideMessage || def.message,\n def.status || 400,\n details,\n options,\n );\n };\n\n return helpers as ErrorBuilder<TErrors>;\n}\n\n/** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */\nexport function errorsOf<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(action: { config: { errors?: TErrors } }): TErrors {\n return (action.config.errors ?? {}) as TErrors;\n}\n\n/**\n * Define an action: a typed, validated function that Brick serves over HTTP,\n * runs in-process, and exposes to the typed client and OpenAPI.\n *\n * A call runs in order: the input is validated against `input` (an invalid one\n * is a `VALIDATION_FAILED` error, HTTP 400); `authorize` runs, if there is one;\n * `execute` runs; and its result is validated against `output` (a mismatch is a\n * server error, HTTP 500). Throw `error.CODE(...)` from `execute` for a declared\n * failure or a standard one such as `error.NOT_FOUND()`. Any other thrown value\n * becomes `INTERNAL_SERVER_ERROR` (500), with the cause kept out of the response\n * and in the log.\n *\n * `authorize` returns `false` to refuse: the call fails with `UNAUTHORIZED`\n * (401) when there is no `ctx.user`, and `FORBIDDEN` (403) when there is one.\n * Where it is given, `execute` can rely on what it checked.\n *\n * @param config - `name`, `execute`, and optionally `description`, `input` and\n * `output` (TypeBox schemas), `errors`, `authorize`, `method` and `path` to\n * change the route (POST by default), `tags`, and `emits`.\n * @returns The action. Register it with `service.action(action)`; call it\n * directly with `action.run(input, ctx)`.\n * @example\n * import { defineAction, t } from \"@brickkit/core\";\n *\n * export const getPage = defineAction({\n * name: \"get\",\n * method: \"GET\",\n * input: t.Object({ id: t.String() }),\n * output: t.Object({ id: t.String(), title: t.String() }),\n * errors: { PAGE_GONE: { message: \"That page was removed\", status: 410 } },\n * authorize: ({ user }) => user != null,\n * execute: async ({ input, ctx, error }) => {\n * const page = await findPage(ctx.db, input.id);\n * if (!page) throw error.NOT_FOUND(\"No such page\");\n * return page;\n * },\n * });\n */\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction(config: any): any {\n const errorHelpers = buildErrorHelpers(config.errors);\n\n const actionFn = (async (params: { input?: any; ctx?: any }) => {\n return actionFn.execute(params);\n }) as any;\n\n Object.defineProperty(actionFn, \"name\", {\n value: config.name,\n configurable: true,\n });\n\n actionFn.config = config;\n actionFn.errorHelpers = errorHelpers;\n\n actionFn.validateInput = (input: unknown) => {\n const errors = actionMeta(actionFn).checkInput?.(input);\n return errors\n ? { success: false as const, errors }\n : validateWithSchema(config.input, input);\n };\n\n actionFn.validateOutput = (output: unknown) =>\n validateWithSchema(\n actionMeta(actionFn).runtimeOutput ?? config.output,\n output,\n );\n\n actionFn.run = async (input?: any, ctx?: any) => {\n return actionFn.execute({ input, ctx });\n };\n\n const limits = rateLimitsOf(config);\n const stages: Stages = {\n name: config.name,\n dashboardOnly: config.dashboard === true,\n checkInput: (input) => {\n if (!config.input) return;\n const checked = actionFn.validateInput(input);\n if (!checked.success) throw invalid(config.name, \"input\", checked.errors);\n },\n rateLimit:\n limits &&\n ((input, ctx) =>\n enforceRateLimits(\n actionMeta(actionFn).service,\n (actionFn as { kind?: string }).kind === \"tool\" ? \"tool\" : \"action\",\n config.name,\n limits,\n input,\n ctx,\n )),\n authorize: config.authorize,\n execute: config.execute,\n errorBuilder: errorHelpers,\n checkOutput: (result) => {\n if (!(actionMeta(actionFn).runtimeOutput ?? config.output)) return result;\n const checked = actionFn.validateOutput(result);\n if (!checked.success)\n throw invalid(config.name, \"output\", checked.errors);\n return result;\n },\n sensitive: sensitivity(config),\n };\n\n const auditStageOf = memoizedPerAuditTable(actionFn);\n const run = async (params: { input?: any; ctx?: any }) => {\n const meta = actionMeta(actionFn);\n // The registered service resolves the context once per request, and\n // recognizes one it already resolved.\n const ctx: any = meta.service\n ? await meta.service.resolveContext(params?.ctx, meta.deps?.values)\n : { ...baseContext(params?.ctx ?? {}), ...params?.ctx };\n try {\n const audit = auditStageOf(meta.service);\n return await runStages(\n audit ? { ...stages, audit } : stages,\n params?.input,\n ctx,\n );\n } catch (err) {\n throw normalizeActionError(err, ctx);\n }\n };\n actionFn.execute = stages.sensitive\n ? (params: { input?: any; ctx?: any }) => withRedaction(() => run(params))\n : run;\n\n return actionFn;\n}\n\nfunction memoizedPerAuditTable(action: Action<any, any, any, any>) {\n let memo:\n | { service?: unknown; table?: AuditTable; stage?: AuditStage }\n | undefined;\n return (service: ServicePort<any, any> | undefined) => {\n const table = service?.getAuditTable();\n if (memo && table === memo.table && service === memo.service)\n return memo.stage;\n const stage = service && auditStage(service, action);\n memo = { service, table, stage };\n return stage;\n };\n}\n","/** The HTTP methods an action, endpoint or plugin route can use. */\nexport const HTTP_METHODS = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"] as const;\nexport type HttpMethod = (typeof HTTP_METHODS)[number];\n","import {\n DuplicateNameError,\n type Action,\n type Resource,\n type Service,\n} from \"./types\";\nimport {\n PLUGIN_KIND,\n PLUGIN_COMMIT,\n type PluginEndpointContext,\n type PluginRouteMethod,\n type PluginRouteRegistrar,\n type PluginRoutes,\n type PluginRouteScope,\n PLUGIN_ROUTE_SCOPES,\n type ContextOf,\n type ResourcePlugin,\n type ResourcePluginContext,\n type ServicePlugin,\n type ServicePluginContext,\n} from \"./plugin-types\";\nimport { defineAction } from \"./action\";\nimport { actionMeta, type PluginRouteBinding } from \"./action-meta\";\nimport { kebabCase } from \"./kebab\";\nimport { DEFAULT_PREFIX, pathParamNames, pluginRoutePath } from \"./routes\";\nimport { HTTP_METHODS } from \"./http\";\nimport { sensitivity } from \"./sensitive\";\nimport { portOf } from \"./service-port\";\n\n/**\n * Define a plugin that installs onto a service with `service.use(plugin)`. Its\n * `setup` receives the service and a `routes` registrar for adding actions and\n * raw HTTP endpoints, and returns the typed API that `service.use` hands back.\n *\n * @param definition - A unique `name`, optional `routes` controls that let the\n * user move or switch off the plugin's routes, and `setup`, which must be\n * synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n * @example\n * import { defineServicePlugin, t } from \"@brickkit/core\";\n *\n * export const greeting = (salutation = \"Hello\") =>\n * defineServicePlugin({\n * name: \"example/greeting\",\n * setup({ routes }) {\n * const hello = routes.action({\n * name: \"hello\",\n * input: t.Object({ name: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `${salutation}, ${input.name}!`,\n * });\n * return { hello };\n * },\n * });\n *\n * const api = greeterService.use(greeting(\"Welcome\"));\n * await api.hello({ input: { name: \"Ada\" } });\n */\nexport function defineServicePlugin<\n S extends Service<any, any> = Service<any, any>,\n A = unknown,\n>(\n definition: Omit<ServicePlugin<S, A>, typeof PLUGIN_KIND> & {\n setup: (\n context: ServicePluginContext<S>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ServicePlugin<S, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [PLUGIN_KIND]: \"service\" as const,\n });\n}\n/**\n * Define a plugin that installs onto a resource (a table and its entity) with\n * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a\n * `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and\n * returns the typed API that `resource.use` hands back. `crud` is built this way.\n *\n * @param definition - A unique `name`, optional `routes` controls, and `setup`,\n * which must be synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n */\nexport function defineResourcePlugin<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n A extends object = object,\n>(\n definition: Omit<ResourcePlugin<S, R, A>, typeof PLUGIN_KIND> & {\n setup: (\n context: ResourcePluginContext<S, R>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ResourcePlugin<S, R, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [PLUGIN_KIND]: \"resource\" as const,\n });\n}\n\nexport function validateName(name: string) {\n if (!name || name.trim() !== name)\n throw new Error(\n \"Plugin and route names must be nonempty and have no surrounding whitespace\",\n );\n}\nfunction validatePath(path: string) {\n if (\n !path.startsWith(\"/\") ||\n path.includes(\"?\") ||\n path.includes(\"#\") ||\n path.includes(\"//\") ||\n path.split(\"/\").some((part) => part === \".\" || part === \"..\")\n ) {\n throw new Error(`Invalid plugin route path '${path}'`);\n }\n}\nfunction copyControls<S extends PluginRouteScope>(\n controls: PluginRoutes<S> | undefined,\n): PluginRoutes<S> | undefined {\n if (controls === undefined || controls === false) return controls;\n const result: Record<string, false | { path?: string; scope?: S }> =\n Object.create(null);\n for (const [name, value] of Object.entries(controls)) {\n validateName(name);\n if (value === false) {\n result[name] = false;\n continue;\n }\n if (value.path !== undefined) validatePath(value.path);\n if (value.scope !== undefined && !PLUGIN_ROUTE_SCOPES.includes(value.scope))\n throw new Error(`Invalid plugin route scope '${value.scope}'`);\n result[name] = Object.freeze({ ...value });\n }\n return Object.freeze(result);\n}\n\ntype Binding = PluginRouteBinding;\ninterface RawBinding extends Binding {\n handler: (context: PluginEndpointContext<any>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\ninterface Installation {\n descriptor: object;\n status: \"installing\" | \"installed\";\n api?: unknown;\n}\ninterface PluginState {\n hosts: Map<object, Map<string, Installation>>;\n actions: Map<Action<any, any, any, any>, Binding>;\n endpoints: RawBinding[];\n /** The URL segments under each resource that its plugins claim, and which plugin. */\n claims: Map<object, Map<string, string>>;\n}\nconst states = new WeakMap<object, PluginState>();\n\n/** Records the plugin state; the returned function puts all of it back (a failed install's rollback). */\nfunction snapshotState(state: PluginState): () => void {\n const copy = <V>(maps: Map<object, Map<string, V>>) =>\n new Map([...maps].map(([key, inner]) => [key, new Map(inner)]));\n const saved: PluginState = {\n hosts: copy(state.hosts),\n actions: new Map(state.actions),\n endpoints: [...state.endpoints],\n claims: copy(state.claims),\n };\n return () => {\n // Actions the failed install bound lose their route too.\n for (const action of state.actions.keys())\n if (!saved.actions.has(action)) delete actionMeta(action).route;\n Object.assign(state, saved);\n };\n}\nfunction stateOf(service: Service<any, any>): PluginState {\n let state = states.get(service);\n if (!state) {\n state = {\n hosts: new Map(),\n actions: new Map(),\n endpoints: [],\n claims: new Map(),\n };\n states.set(service, state);\n }\n return state;\n}\nexport function isInstallingPlugin(service: Service<any, any>): boolean {\n return [...(states.get(service)?.hosts.values() ?? [])].some(\n (installations) =>\n [...installations.values()].some((item) => item.status === \"installing\"),\n );\n}\n\n/**\n * The raw HTTP endpoints plugins registered on a service, ready to mount on the\n * application. Each handler resolves the service's context before it runs.\n *\n * @param service - The service plugins were installed on.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns The enabled endpoints: `path`, `method`, `handler`, and the\n * `summary`, `description`, and `tags` for OpenAPI.\n */\nexport function getPluginEndpoints(\n service: Service<any, any>,\n prefix = DEFAULT_PREFIX,\n) {\n return stateOf(service)\n .endpoints.filter((binding) => binding.enabled)\n .map((binding) => ({\n path: pluginRoutePath(binding, prefix),\n method: binding.method,\n service,\n plugin: binding.plugin,\n summary: binding.summary,\n description: binding.description,\n tags: binding.tags,\n handler: async (context: Omit<PluginEndpointContext, \"ctx\">) =>\n binding.handler({\n ...context,\n ctx: await service.resolveContext({ request: context.request }),\n }),\n }));\n}\n\n/** The plugin that claimed `segment` under `resource`, if one did. */\nexport function segmentClaimant(\n service: Service<any, any>,\n resource: object,\n segment: string,\n): string | undefined {\n return states.get(service)?.claims.get(resource)?.get(segment);\n}\n\n/** Descriptor identity is scoped to the service or resource installation host. */\nexport function installPlugin(\n service: Service<any, any>,\n resource: Resource<any, any, any> | undefined,\n descriptor: ServicePlugin<any, any> | ResourcePlugin<any, any, any>,\n) {\n if (service.isBuilt)\n throw new Error(\"Plugins must be installed before service build\");\n if (\n descriptor[PLUGIN_KIND] !== (resource ? \"resource\" : \"service\") &&\n descriptor[PLUGIN_KIND] !== \"plugin\"\n )\n throw new Error(\"Plugin does not support this installation host\");\n const state = stateOf(service);\n const host = resource ?? service;\n const existing = state.hosts.get(host)?.get(descriptor.name);\n if (existing) {\n if (existing.status === \"installing\")\n throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);\n if (existing.descriptor !== descriptor)\n throw new Error(\n `Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`,\n );\n return resource ?? existing.api;\n }\n const restoreService = portOf(service).snapshot();\n const restoreState = snapshotState(state);\n const installations =\n state.hosts.get(host) ?? new Map<string, Installation>();\n state.hosts.set(host, installations);\n installations.set(descriptor.name, { descriptor, status: \"installing\" });\n const names = new Set<string>();\n const commits: (() => void)[] = [];\n const ownedActions = new Set<Action<any, any, any, any>>();\n let active = true;\n const claim = (segment: string) => {\n if (!resource) throw new Error(\"Only resource plugins claim URL segments\");\n const claims = state.claims.get(resource) ?? new Map<string, string>();\n state.claims.set(resource, claims);\n if (claims.has(segment)) return;\n const taken = service.listActions().find((action) => {\n const info = actionMeta(action).resourceAction;\n return (\n info?.resource === resource.name && kebabCase(info.name) === segment\n );\n });\n if (taken)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${taken.name}\" in service \"${service.name}\": \"${segment}\" is a ${descriptor.name} route`,\n );\n claims.set(segment, descriptor.name);\n };\n const bindingFor = (config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: PluginRouteScope;\n }): Binding => {\n if (!active || service.isBuilt)\n throw new Error(\"Plugin routes can only be registered during setup\");\n validateName(config.name);\n validatePath(config.path);\n if (names.has(config.name))\n throw new DuplicateNameError(\n `Duplicate plugin route name '${config.name}'`,\n );\n names.add(config.name);\n const control =\n descriptor.routes === false ? false : descriptor.routes?.[config.name];\n const scope =\n (control && control.scope) ||\n config.scope ||\n (resource ? \"resource\" : \"service\");\n if (scope === \"resource\" && !resource)\n throw new Error(\"Service plugin routes cannot use resource scope\");\n if (!PLUGIN_ROUTE_SCOPES.includes(scope))\n throw new Error(`Invalid plugin route scope '${scope}'`);\n if (!HTTP_METHODS.includes(config.method))\n throw new Error(`Invalid plugin route method '${config.method}'`);\n const path = (control && control.path) || config.path;\n validatePath(path);\n const segment = path.split(\"/\")[1]!;\n if (scope === \"resource\" && segment && !segment.startsWith(\":\"))\n claim(segment);\n return {\n service: service.name,\n resource: resource?.name,\n plugin: descriptor.name,\n path,\n method: config.method,\n scope,\n enabled: control !== false,\n };\n };\n const routes: PluginRouteRegistrar<any> = {\n action(config: any) {\n const binding = bindingFor(config);\n for (const name of pathParamNames(binding.path)) {\n if (\n !config.input?.properties ||\n !Object.hasOwn(config.input.properties, name)\n )\n throw new Error(\n `Plugin action path parameter '${name}' must be declared in its input schema`,\n );\n }\n // Public contract name: resource/operation only (e.g. `page.list`).\n // The owning plugin stays in binding metadata (`plugin`) and on the\n // action (`plugin`/`resource`) so it never leaks into exported names,\n // OpenAPI, or client contracts.\n const name = `${resource ? `${resource.name}.` : \"\"}${config.name}`;\n if (service.getAction(name))\n throw new DuplicateNameError(\n `Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`,\n );\n const {\n scope: _scope,\n runtimeOutput,\n checkInput,\n ...actionConfig\n } = config;\n sensitivity({ ...actionConfig, name }, service.name);\n const action = defineAction({ ...actionConfig, name });\n Object.assign(actionMeta(action), {\n route: binding,\n runtimeOutput,\n checkInput,\n });\n service.action(action);\n ownedActions.add(action);\n state.actions.set(action, binding);\n return action;\n },\n endpoint(config) {\n const binding = bindingFor(config);\n state.endpoints.push({\n ...binding,\n handler: config.handler,\n summary: config.summary,\n description: config.description,\n tags: config.tags,\n });\n },\n claim,\n };\n try {\n const context = {\n service,\n ...(resource ? { resource } : {}),\n routes,\n [PLUGIN_COMMIT]: (commit: () => void) => commits.push(commit),\n };\n const api = resource\n ? (descriptor as ResourcePlugin<any, any, any>).setup(\n context as typeof context & { resource: Resource<any, any, any> },\n )\n : (descriptor as ServicePlugin<any, any>).setup(context);\n if (api && typeof api === \"object\" && \"then\" in api)\n throw new Error(\"Plugin setup must be synchronous\");\n if (\n descriptor.routes &&\n Object.keys(descriptor.routes).some((name) => !names.has(name))\n )\n throw new Error(\n `Plugin '${descriptor.name}' has an override for an unknown route`,\n );\n const walk = (value: unknown, path: string[], ancestors: Set<object>) => {\n if (typeof value === \"function\") {\n const binding = state.actions.get(value as Action<any, any, any, any>);\n if (binding && ownedActions.has(value as Action<any, any, any, any>)) {\n if (binding.clientPath)\n throw new Error(\"Plugin actions must have one returned API path\");\n binding.clientPath = resource\n ? [service.name, resource.name, ...path]\n : [service.name, ...path];\n }\n } else if (value && typeof value === \"object\" && !ancestors.has(value)) {\n const next = new Set(ancestors).add(value);\n for (const [key, child] of Object.entries(value))\n walk(child, [...path, key], next);\n }\n };\n walk(api, [], new Set());\n if (resource) {\n if (!api || typeof api !== \"object\" || Array.isArray(api))\n throw new Error(\"Resource plugins must return named API contributions\");\n for (const key of Object.keys(api)) {\n if (\n key in resource ||\n [\"__proto__\", \"prototype\", \"constructor\"].includes(key)\n )\n throw new Error(\n `Resource plugin contribution '${key}' collides with an existing property`,\n );\n }\n Object.assign(resource, api);\n }\n state.hosts.get(host)!.set(descriptor.name, {\n descriptor,\n status: \"installed\",\n api,\n });\n for (const commit of commits) commit();\n return resource ?? api;\n } catch (error) {\n restoreService();\n restoreState();\n throw error;\n } finally {\n active = false;\n }\n}\n/** Whether a plugin named `name` is installed on `host` (the service or a resource). */\nexport function hasPlugin(\n service: Service<any, any>,\n host: object,\n name: string,\n): boolean {\n return (\n states.get(service)?.hosts.get(host)?.get(name)?.status === \"installed\"\n );\n}\n/** Every descriptor installed on the service or its resources, in install order per host. */\nexport function installedPlugins(service: Service<any, any>): object[] {\n return [...(states.get(service)?.hosts.values() ?? [])].flatMap(\n (installations) =>\n [...installations.values()]\n .filter((item) => item.status === \"installed\")\n .map((item) => item.descriptor),\n );\n}\n","import { PLUGIN_DEPS } from \"./deps\";\nimport type { EventListener } from \"./events/types\";\nimport type {\n PluginInstallOptions,\n PluginInstance,\n PluginManifest,\n} from \"./define-plugin\";\nimport type { InstalledPlugin } from \"./plugin-types\";\n\nexport const INTERNALS = Symbol.for(\"brickkit.plugin.internals\");\ninterface Installation {\n scope: \"app\" | \"service\" | \"resource\";\n service?: string;\n resource?: string;\n}\nexport interface Internals {\n manifest: PluginManifest<any, any, any, any, any, any, any>;\n options: Record<string, unknown>;\n deps: Readonly<Record<string, unknown>>;\n install: PluginInstallOptions;\n dashboard?: string;\n installs: Installation[];\n /** When it was first installed, to run `app` parts in install order. */\n order?: number;\n}\n\nexport function isPluginInstance(value: unknown): value is PluginInstance {\n return (\n typeof value === \"object\" &&\n value !== null &&\n INTERNALS in (value as object)\n );\n}\nexport function pluginDepsOf(\n value: unknown,\n): Readonly<Record<string, unknown>> {\n return internalsOf(value)?.deps ?? {};\n}\nfunction internalsOf(value: unknown): Internals | undefined {\n return isPluginInstance(value)\n ? ((value as unknown as Record<symbol, Internals>)[INTERNALS] ?? undefined)\n : undefined;\n}\n\n/**\n * What `brick()` does with plugins: install those given in `plugins` on the\n * app, run every plugin's `app` part in install order, and return the\n * lifecycle, middleware and listeners they contributed.\n */\nexport function setupAppPlugins(\n installedOnServices: readonly object[],\n appPlugins: readonly unknown[],\n) {\n const instances = new Set<PluginInstance>();\n for (const descriptor of installedOnServices)\n if (isPluginInstance(descriptor)) instances.add(descriptor);\n const ordered = [...instances].sort(\n (a, b) => (internalsOf(a)!.order ?? 0) - (internalsOf(b)!.order ?? 0),\n );\n const onApp = new Set<string>();\n for (const plugin of appPlugins) {\n const internals = internalsOf(plugin);\n if (!internals)\n throw new Error(\n \"brick({ plugins }) takes instances from definePlugin(), such as audit()\",\n );\n const { manifest } = internals;\n if (!manifest.app || manifest.tables || manifest.events)\n throw new Error(\n `${manifest.name} cannot be installed on the app; ${\n manifest.resource ? \"use resource.use()\" : \"use service.use()\"\n }`,\n );\n for (const required of manifest.requires ?? [])\n if (!onApp.has(required))\n throw new Error(\n `${manifest.name} requires ${required}, installed in brick({ plugins }) before it`,\n );\n if (onApp.has(manifest.name))\n throw new Error(`Plugin ${manifest.name} is installed on the app twice`);\n // Its `app` part already runs from the service or resource install; running it again would double every hook.\n const installed = ordered.find(\n (other) => internalsOf(other)!.manifest.name === manifest.name,\n );\n if (installed)\n throw new Error(\n `Plugin ${manifest.name} is already installed with ${internalsOf(\n installed,\n )!\n .installs.map((install) =>\n install.scope === \"resource\"\n ? `${install.service}.${install.resource}.use()`\n : `${install.service}.use()`,\n )\n .join(\n \", \",\n )}, which runs its app part too; remove it from brick({ plugins })`,\n );\n onApp.add(manifest.name);\n if (!internals.installs.some((item) => item.scope === \"app\"))\n internals.installs.push({ scope: \"app\" });\n ordered.push(plugin as PluginInstance);\n }\n\n const lifecycles: Lifecycle[] = [];\n const middleware: ((context: any) => unknown)[] = [];\n const listeners: EventListener[] = [];\n const listed: InstalledPlugin[] = [];\n for (const plugin of ordered) {\n const { manifest, options, deps, installs, dashboard } =\n internalsOf(plugin)!;\n for (const install of installs)\n listed.push(\n Object.freeze({\n name: manifest.name,\n ...(manifest.brick ? { brick: manifest.brick } : {}),\n ...install,\n ...(dashboard ? { dashboard } : {}),\n }),\n );\n if (!manifest.app) continue;\n const lifecycle = { options, secrets: manifest.secrets ?? {}, deps };\n // A plugin's start and stop pair up, so stop runs only after its start did.\n const own = { start: [] as Function[], stop: [] as Function[] };\n manifest.app({\n ...lifecycle,\n on(event, handler) {\n if (event !== \"start\" && event !== \"stop\")\n throw new Error(`${manifest.name}: on() takes \"start\" or \"stop\"`);\n own[event].push(handler);\n },\n middleware(handler) {\n middleware.push(handler);\n },\n listeners(...items) {\n // `useDeps()` in a plugin's listener, and its workflow's steps, return the plugin's deps.\n listeners.push(\n ...items.map((listener) => ({ ...listener, [PLUGIN_DEPS]: deps })),\n );\n },\n });\n lifecycles.push({\n start: async () => {\n for (const handler of own.start) await handler(lifecycle);\n },\n stop: async () => {\n for (const handler of own.stop) await handler(lifecycle);\n },\n });\n }\n return {\n lifecycles,\n middleware,\n listeners,\n plugins: listed,\n deps: ordered.map((plugin) => internalsOf(plugin)!.deps),\n };\n}\n\ninterface Lifecycle {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\n/**\n * Start in install order. Stop what started, in reverse order; a start that\n * fails stops those before it and rethrows.\n */\nexport function pluginLifecycle(lifecycles: readonly Lifecycle[]) {\n let started: Promise<void> | undefined;\n const running: Lifecycle[] = [];\n const stopAll = async () => {\n const errors: unknown[] = [];\n for (const item of running.splice(0).reverse())\n try {\n await item.stop();\n } catch (error) {\n errors.push(error);\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length)\n throw new AggregateError(errors, \"Plugins failed to stop\");\n };\n return {\n start(): Promise<void> {\n return (started ??= (async () => {\n for (const item of lifecycles) {\n try {\n await item.start();\n } catch (error) {\n await stopAll().catch(() => undefined);\n started = undefined;\n throw error;\n }\n running.push(item);\n }\n })());\n },\n async stop(): Promise<void> {\n await started?.catch(() => undefined);\n started = undefined;\n await stopAll();\n },\n };\n}\n","import type { HttpMethod } from \"../http\";\nimport { DuplicateNameError, type Service, type Action } from \"../types\";\nimport { actionMeta } from \"../action-meta\";\nimport {\n DEFAULT_PREFIX,\n checkSegments,\n getActionRoute,\n inputSource,\n isReadLike,\n pathParamNames,\n routeKey,\n} from \"../routes\";\nimport { portOf } from \"../service-port\";\nimport { webhookOf } from \"../webhook\";\nimport { fileFields } from \"../typebox\";\nimport { marksKey } from \"../sensitive\";\n\nconst FORM_FIELDS_AND_FRAMING_BYTES = 1024 * 1024;\n\nexport type RouteMethod = HttpMethod;\n/** How a string from a query or form field becomes the schema's type; objects travel as JSON. */\nexport type Coercion = \"number\" | \"boolean\" | \"array\" | \"json\";\n\nfunction coercionOf(schema: any): Coercion | undefined {\n if (schema?.type === \"number\" || schema?.type === \"integer\") return \"number\";\n if (schema?.type === \"boolean\") return \"boolean\";\n if (schema?.type === \"array\") return \"array\";\n if (schema?.type === \"object\") return \"json\";\n return undefined;\n}\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n /** A `webhook` has a verified raw body; see `service.webhook`. */\n readonly kind: \"action\" | \"webhook\";\n /** The plugin that registered the action, if one did. */\n readonly plugin?: string;\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n /** Whether the server reads the query first (else path parameters, then body). */\n readonly readLike: boolean;\n /** Where callers send the input: the query (GET, DELETE) or the body. */\n readonly inputSource: \"query\" | \"body\";\n readonly coercions: readonly {\n readonly key: string;\n readonly type: Coercion;\n /** How each item of an `array` field is coerced. */\n readonly items?: Exclude<Coercion, \"array\">;\n }[];\n /** The most bytes a body may have: multipart bodies with `t.File` fields (by `Content-Length`), and a webhook's (counted as read). */\n readonly bodyLimit?: number;\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly preparations: readonly {\n service: string;\n name: string;\n metadata: unknown;\n }[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = DEFAULT_PREFIX,\n) {\n for (const service of services) service.build();\n return analyzeDeclaredApplication(services, prefix);\n}\n\n/** Inspect current declarations without closing service/plugin setup. */\nexport function analyzeDeclaredApplication(\n services: Service<any, any>[],\n prefix = DEFAULT_PREFIX,\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new DuplicateNameError(\n `Brick compiler: duplicate service '${service.name}'`,\n );\n names.add(service.name);\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<\n string,\n { name: string; plugin: boolean; webhook: boolean }\n >();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const route = describeRoute(service, action, method, path);\n const key = routeKey(method, path);\n const previous = registered.get(key);\n if (previous) {\n if (route.kind === \"webhook\" || previous.webhook)\n throw new DuplicateNameError(\n `Brick compiler: '${service.name}.${action.name}' and '${previous.name}' both claim '${method} ${path}', and a webhook cannot share its route`,\n );\n if (route.plugin || previous.plugin)\n throw new DuplicateNameError(\n `Brick compiler: duplicate plugin route '${method} ${path}'`,\n );\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (earlier service, then lower action name, wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, {\n name: `${service.name}.${action.name}`,\n plugin: Boolean(route.plugin),\n webhook: route.kind === \"webhook\",\n });\n routes.push(route);\n bindings.push({ service, action });\n };\n // Registration order follows module evaluation, which bundlers reorder (#107),\n // so routes are canonical: by route key, then service order, then action name.\n const candidates: [\n string,\n number,\n Service<any, any>,\n Action<any, any, any, any>,\n RouteMethod,\n string,\n ][] = [];\n for (const [index, service] of services.entries()) {\n checkSegments(service);\n for (const action of service.listActions()) {\n const route = getActionRoute(action, prefix);\n if (route === false) continue;\n candidates.push([\n routeKey(route.method, route.path),\n index,\n service,\n action,\n route.method,\n route.path,\n ]);\n }\n }\n candidates.sort(\n (a, b) =>\n compare(a[0], b[0]) || a[1] - b[1] || compare(a[3].name, b[3].name),\n );\n for (const [, , service, action, method, path] of candidates)\n add(service, action, method, path);\n const preparations = services.flatMap((service) =>\n portOf(service)\n .listPreparations()\n .map((contribution) => ({\n service: service.name,\n name: contribution.name,\n metadata: schemaSnapshot(contribution.describe?.()),\n }))\n .sort((a, b) => compare(a.name, b.name)),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n preparations,\n diagnostics,\n });\n return { ir, bindings };\n}\n\n/** Code-unit order, independent of locale. */\nconst compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);\n\n/** What the compiler records about one action route. */\nexport function describeRoute(\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n): RouteIR {\n for (const name of pathParamNames(path)) {\n if (marksKey(action.config.input, name))\n throw new Error(\n `Service '${service.name}' action '${action.name}': sensitive input field '/${name}' is a path parameter of '${method} ${path}', and request logs and traces record the path; take it in the request body instead`,\n );\n }\n const coercions: RouteIR[\"coercions\"][number][] = [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n const type = coercionOf(prop);\n if (!type) continue;\n const items = type === \"array\" ? coercionOf(prop.items) : undefined;\n coercions.push(\n items && items !== \"array\" ? { key, type, items } : { key, type },\n );\n }\n const plugin = actionMeta(action).route?.plugin;\n const files = fileFields(action.config.input);\n const webhook = webhookOf(action);\n const bodyLimit = webhook\n ? webhook.maxBodyBytes\n : files.length && files.every((field) => field.maxBytes !== undefined)\n ? files.reduce((sum, field) => sum + (field.maxBytes ?? 0), 0) +\n FORM_FIELDS_AND_FRAMING_BYTES\n : undefined;\n return {\n method,\n path,\n service: service.name,\n action: action.name,\n kind: webhook ? \"webhook\" : \"action\",\n ...(plugin ? { plugin } : {}),\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n readLike: isReadLike(method, action.name),\n inputSource: inputSource(method),\n coercions,\n ...(bodyLimit === undefined ? {} : { bodyLimit }),\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n };\n}\n","import type { Service, Action } from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { createLogger } from \"./logger\";\nimport { sensitivity } from \"./sensitive\";\nimport { actionMeta } from \"./action-meta\";\nimport { describeRoute, type RouteIR } from \"./compiler/ir\";\nimport { portOf } from \"./service-port\";\nimport { bindRoute, type CompiledRoutePlan } from \"./compiler/runtime\";\n\n/** The plan of an analyzed route: its callbacks, validators and logger. */\nexport function planRoute(\n route: RouteIR,\n service: Service,\n action: Action,\n): CompiledRoutePlan {\n const meta = actionMeta(action);\n const outputSchema = meta.runtimeOutput ?? action.config.output;\n return {\n route,\n service: portOf(service),\n action,\n execute: action.config.execute,\n authorize: action.config.authorize,\n contextHook: service.options.context,\n inputChecker: action.config.input\n ? (getCompiledCheck(action.config.input) as any)\n : undefined,\n outputChecker: outputSchema\n ? (getCompiledCheck(outputSchema) as any)\n : undefined,\n errorBuilder: action.errorHelpers,\n logger: createLogger(`[${service.name}:${action.name}]`),\n cachedDb: service.getDb(),\n checkInput: meta.checkInput,\n sensitive: sensitivity(action.config, service.name),\n deps: meta.deps?.values,\n };\n}\n\n/**\n * An Elysia handler for one action. Use it to mount an action on your own\n * Elysia app; `brick()` does it for you.\n *\n * @deprecated Serve actions with `brick()`, or bind every route at once with\n * `compileBrickApplication`.\n * @param service - The service the action belongs to.\n * @param action - The action.\n * @param routePath - The route's path.\n * @param method - The HTTP method (POST by default).\n * @returns A function from the Elysia context to the response.\n */\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n return bindRoute(\n planRoute(\n describeRoute(\n service,\n action,\n (method ?? \"POST\") as RouteIR[\"method\"],\n routePath,\n ),\n service,\n action,\n ),\n );\n}\n","import type { BrickApp } from \"./endpoints\";\n\n/**\n * Whether a value is an application made by `brick()`. It checks for the\n * methods and `definition` a `BrickApp` has, so it also recognizes one built by\n * another copy of the package.\n *\n * @param app - Anything, such as the default export of an entry file.\n * @returns `true` for a `BrickApp`, narrowing its type.\n */\nexport function isBrickApp(app: unknown): app is BrickApp {\n if (!app || typeof app !== \"object\") return false;\n return (\n \"endpoint\" in app &&\n typeof app.endpoint === \"function\" &&\n \"fetch\" in app &&\n typeof app.fetch === \"function\" &&\n \"listen\" in app &&\n typeof app.listen === \"function\" &&\n \"definition\" in app &&\n !!app.definition &&\n typeof app.definition === \"object\" &&\n \"services\" in app.definition &&\n Array.isArray(app.definition.services) &&\n \"prefix\" in app.definition &&\n typeof app.definition.prefix === \"string\"\n );\n}\n\n/**\n * Check that a module's default export is an application ready to be served,\n * for tools that load an entry file.\n *\n * @param app - The default export of an entry file.\n * @returns The app.\n * @throws When it is not a `BrickApp`, or it already called `.listen()`: the\n * entry must only build the app, and leave listening to the server bootstrap.\n */\nexport function requireBrickApp(app: unknown): BrickApp {\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n if (app.server)\n throw new Error(\n \"Brick: the app entry must not call .listen(); use a separate server bootstrap.\",\n );\n return app;\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport { validateWithSchema } from \"../typebox\";\nimport { sensitivePointer } from \"../sensitive\";\n\n/** A service's declared events: payload schema by event name. */\nexport type EventCatalog = Record<string, TSchema>;\n\n/**\n * One declared event, as `service.events.<name>`. Pass it to `defineListener({ on })`\n * for a typed payload, or to `emitEvent` for a checked one.\n */\nexport interface EventRef<TPayload = unknown> {\n /** The event name on the wire: `<service>.<event>`, such as `orders.shipped`. */\n readonly name: string;\n readonly service: string;\n readonly schema: TSchema;\n /** The plugin that declared it, for events a `definePlugin` adds. */\n readonly plugin?: string;\n /** Type-level only: the payload this event carries. */\n readonly __payload?: TPayload;\n}\n\n/** `service.events`: one `EventRef` per catalog entry. */\nexport type EventRefs<C extends EventCatalog> = {\n readonly [K in keyof C & string]: EventRef<Static<C[K]>>;\n};\n\n/** What a service with a catalog checks before recording an event. */\nexport interface EventChecker {\n readonly name: string;\n readonly events: Readonly<Record<string, EventRef>>;\n /** Whether the service has a catalog at all. */\n readonly hasCatalog: boolean;\n listResources(): readonly { name: string }[];\n}\n\nexport function isEventRef(value: unknown): value is EventRef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as EventRef).name === \"string\" &&\n typeof (value as EventRef).service === \"string\" &&\n typeof (value as EventRef).schema === \"object\"\n );\n}\n\n/** Build `service.events` from its catalog. */\nexport function eventRefs(\n service: string,\n catalog: EventCatalog | undefined,\n): Record<string, EventRef> {\n const refs: Record<string, EventRef> = Object.create(null);\n for (const [key, schema] of Object.entries(catalog ?? {})) {\n if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key))\n throw new Error(\n `Event \"${key}\" in service \"${service}\" must be a plain name such as shipped or itemAdded`,\n );\n if (!schema || typeof schema !== \"object\")\n throw new Error(\n `Event \"${service}.${key}\" needs a payload schema, such as t.Object({ ... })`,\n );\n const at = sensitivePointer(schema);\n if (at)\n throw new Error(\n `Event \"${service}.${key}\" payload marks '${at}' t.Sensitive, which event payloads do not support yet; carry an id and load the secret in the listener`,\n );\n refs[key] = Object.freeze({ name: `${service}.${key}`, service, schema });\n }\n return Object.freeze(refs);\n}\n\n/** @throws When the payload does not match the event's schema. */\nexport function checkPayload(ref: EventRef, payload: unknown): void {\n const result = validateWithSchema(ref.schema, payload);\n if (!result.success)\n throw new Error(\n `Event \"${ref.name}\" payload does not match its schema: ${result.errors\n .map((error) => `${error.path || \"/\"} ${error.message}`)\n .join(\"; \")}`,\n );\n}\n\n/** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */\nexport const CRUD_EVENT_OPERATIONS = [\"create\", \"update\", \"delete\"] as const;\nexport type CrudEventOperation = (typeof CRUD_EVENT_OPERATIONS)[number];\n\n/** The event a CRUD write records: `<resource>.<operation>`. */\nexport const crudEventName = (\n resource: string,\n operation: CrudEventOperation,\n): string => `${resource}.${operation}`;\n\n/** The `source` of a resource's events: `<service>.<resource>`. */\nexport const crudEventSource = (service: string, resource: string): string =>\n `${service}.${resource}`;\n\n/** Whether `name` is the CRUD event of one of `resources`. */\nexport function isCrudEvent(\n name: string,\n resources: readonly string[],\n): boolean {\n const dot = name.indexOf(\".\");\n return (\n dot > 0 &&\n (CRUD_EVENT_OPERATIONS as readonly string[]).includes(\n name.slice(dot + 1),\n ) &&\n resources.includes(name.slice(0, dot))\n );\n}\n\n/**\n * Check an event against the catalog of the service recording it. Without a\n * catalog any name goes. With one, the name must be `<service>.<event>` from it\n * (the payload is checked against its schema) or a CRUD event of one of the\n * service's resources (`<resource>.create|update|delete`).\n *\n * @throws When the name is not declared or the payload does not match.\n */\nexport function checkEvent(\n service: EventChecker,\n name: string,\n payload: unknown,\n): void {\n const prefix = `${service.name}.`;\n const ref = name.startsWith(prefix)\n ? service.events[name.slice(prefix.length)]\n : undefined;\n if (ref) return checkPayload(ref, payload);\n if (!service.hasCatalog) return;\n if (\n isCrudEvent(\n name,\n service.listResources().map((r) => r.name),\n )\n )\n return;\n throw new Error(\n `Event \"${name}\" is not in the event catalog of service \"${service.name}\" (declared: ${\n Object.values(service.events)\n .map((ref) => ref.name)\n .join(\", \") || \"none\"\n })`,\n );\n}\n","import { isEventRef, type EventRef } from \"./catalog\";\nimport { buildErrorHelpers } from \"../action\";\nimport { PLUGIN_DEPS } from \"../deps\";\nimport type { ActionErrorDefinition, ErrorBuilder } from \"../types\";\nimport type {\n EventDelivery,\n EventListener,\n EventWorkflow,\n ListenerFailure,\n RetryDecision,\n} from \"./types\";\n\ntype EventOn = EventRef<any> | readonly EventRef<any>[];\ntype PayloadOf<O> =\n O extends EventRef<infer P>\n ? P\n : O extends readonly EventRef<infer P>[]\n ? P\n : never;\n\ntype ListenerConfig<\n TPayload,\n TOn = string | readonly string[],\n TErrors extends Record<string, ActionErrorDefinition> = {},\n> = {\n name: string;\n on: TOn;\n maxAttempts?: number;\n /** Errors `run` may raise with `error.CODE()`. Spread `defineError(...)` results or `errorsOf(action)` here. */\n errors?: TErrors;\n /** Decides what a failure does next. Without it every failure retries until `maxAttempts`. */\n retry?: (error: ListenerFailure<TErrors>) => RetryDecision;\n} & (\n | {\n run: (\n delivery: EventDelivery<TPayload>,\n helpers: { error: ErrorBuilder<TErrors> },\n ) => void | Promise<void>;\n workflow?: never;\n }\n | { workflow: EventWorkflow<TPayload>; run?: never }\n);\n\n/**\n * Define a listener: code that runs for each event it listens for, after the write\n * that caused the event has been committed. Pass it to `brick({ events: {\n * listeners } })`.\n *\n * It either runs a handler (`run`) in the process that delivers events, or starts\n * a durable workflow (`workflow`) on the app's `events.world`. Delivery is at\n * least once. A handler that throws is retried later with a growing delay, then\n * parked as dead, so it can run again for the same event: use\n * `delivery.deliveryId` to make its work idempotent. A workflow needs no such\n * care: a delivery starts one run however often it is tried, and the workflow\n * retries its own steps.\n *\n * A listener can declare `errors`, as an action does, and raise them in `run` with\n * `error.CODE()`. `retry(error)` then picks `\"retry\"` or `\"dead\"` from the typed\n * `error.code`; anything not declared arrives as `{ code: \"UNKNOWN\", cause }`.\n *\n * @param config - `name` (unique; it is part of each delivery's id), `on` (a\n * declared event such as `orders.events.shipped`, which types the payload, or an\n * event name; or a list of either; a trailing `*` matches a prefix, as in\n * `user.*`), `run` or `workflow`, and optionally `maxAttempts`.\n * @returns The listener.\n * @throws When the name is empty or contains `:`, `on` is empty, or the listener\n * has both or neither of `run` and `workflow`.\n * @example\n * import { brick, defineListener } from \"@brickkit/core\";\n *\n * const welcome = defineListener({\n * name: \"welcome-email\",\n * on: \"user.create\",\n * run: async ({ payload, deliveryId }) => {\n * await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });\n * },\n * });\n *\n * export default brick({ services, events: { listeners: [welcome] } });\n * @example\n * // src/workflows/onboard.ts\n * export async function onboard(event: WorkflowEvent<CrudEventPayload>) {\n * \"use workflow\";\n * await sendWelcome(event.payload.row.email);\n * }\n *\n * defineListener({ name: \"onboard\", on: \"user.create\", workflow: onboard });\n * @example\n * // payload is { id: string; trackingId: string }, from the orders catalog.\n * defineListener({\n * name: \"notify-shipped\",\n * on: orders.events.shipped,\n * run: ({ payload }) => notify(payload.id, payload.trackingId),\n * });\n */\nexport function defineListener<\n const TOn extends EventOn,\n const TErrors extends Record<string, ActionErrorDefinition> = {},\n>(\n config: ListenerConfig<PayloadOf<TOn>, TOn, TErrors>,\n): EventListener<PayloadOf<TOn>>;\nexport function defineListener<\n TPayload = any,\n const TErrors extends Record<string, ActionErrorDefinition> = {},\n>(\n config: ListenerConfig<\n TPayload,\n string | EventRef<any> | readonly (string | EventRef<any>)[],\n TErrors\n >,\n): EventListener<TPayload>;\nexport function defineListener(\n config: ListenerConfig<any, unknown, any>,\n): EventListener {\n const on = (Array.isArray(config.on) ? config.on : [config.on]).map(\n (item: unknown) => (isEventRef(item) ? item.name : item),\n ) as string[];\n validateListener({ ...config, on } as EventListener);\n const helpers = buildErrorHelpers(config.errors);\n return Object.freeze({\n name: config.name,\n on: Object.freeze(on),\n ...(config.run !== undefined\n ? {\n run: ((delivery: EventDelivery) =>\n config.run!(delivery, { error: helpers })) as EventListener[\"run\"],\n }\n : {}),\n ...(config.errors ? { errors: config.errors } : {}),\n ...(config.retry ? { retry: config.retry } : {}),\n ...(config.workflow !== undefined ? { workflow: config.workflow } : {}),\n ...(config.maxAttempts !== undefined\n ? { maxAttempts: config.maxAttempts }\n : {}),\n });\n}\n\n/**\n * @throws When the name is empty or contains `:`, `on` is empty, `maxAttempts`\n * is not a positive integer, or the listener has both or neither of `run` and\n * `workflow`.\n */\nexport function validateListener(listener: EventListener): void {\n const { name, on, maxAttempts, run, workflow } = listener;\n if (typeof name !== \"string\" || !name)\n throw new Error(\"An event listener needs a name\");\n // A listener's name ends its delivery ids: see `deliveryId`.\n if (name.includes(\":\"))\n throw new Error(`Event listener name '${name}' must not contain ':'`);\n if (\n !Array.isArray(on) ||\n !on.length ||\n on.some((pattern) => !pattern || typeof pattern !== \"string\")\n )\n throw new Error(`Event listener '${name}' listens for nothing`);\n if (\n maxAttempts !== undefined &&\n (!Number.isInteger(maxAttempts) || maxAttempts < 1)\n )\n throw new Error(\n `Event listener '${name}': maxAttempts must be a positive integer`,\n );\n if (run !== undefined && workflow !== undefined)\n throw new Error(\n `Event listener '${name}' has both run and workflow; give it one`,\n );\n if (run === undefined && workflow === undefined)\n throw new Error(\n `Event listener '${name}' needs a run handler or a workflow`,\n );\n if (run !== undefined && typeof run !== \"function\")\n throw new Error(`Event listener '${name}': run must be a function`);\n if (workflow !== undefined && typeof workflow !== \"function\")\n throw new Error(\n `Event listener '${name}': workflow must be a function marked \"use workflow\"`,\n );\n}\n\n/** The deps a plugin's listener runs with, set by the plugin install; `undefined` for the app's own. */\nexport const listenerDeps = (listener: object) =>\n (listener as { [PLUGIN_DEPS]?: Record<string, unknown> })[PLUGIN_DEPS];\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { runWithDeps } from \"../deps\";\nimport { listenerDeps } from \"./listener\";\nimport type { Schedule, ScheduleRun } from \"../schedules/schedule\";\nimport type {\n EventDelivery,\n EventListener,\n EventsWorld,\n WorkflowEvent,\n WorkflowsOptions,\n} from \"./types\";\n\n/** The workflow bundle `buildWorkflows()` writes and the runtime reads: its directory under the project root, and its files. */\nexport const WORKFLOW_BUNDLE = {\n dir: \".well-known/workflow/v1\",\n flow: \"flow.mjs\",\n steps: \"__step_registrations.mjs\",\n webhook: \"webhook.mjs\",\n manifest: \"manifest.json\",\n} as const;\n/** From the Workflow SDK: the queue a workflow run goes to (`getQueueTopicPrefix(\"workflow\")` in `@workflow/world`), and the header a world names it in. */\nexport const WORKFLOW_QUEUE = {\n prefix: \"__wkf_workflow_\",\n header: \"x-vqs-queue-name\",\n} as const;\nconst STOPPED = \"The events were stopped, so workflows can no longer run\";\nconst NOT_BUILT =\n \"brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\";\n/** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */\nexport const WEBHOOK_ROUTE = `/${WORKFLOW_BUNDLE.dir}/webhook/*`;\n/** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */\nconst STEP_REGISTRY = Symbol.for(\"@workflow/core//registeredSteps\");\n\ninterface WorkflowSdk {\n start(\n workflow: unknown,\n args: unknown[],\n options: Record<string, unknown>,\n ): Promise<{ runId: string }>;\n setWorld(world: unknown): void;\n}\n\ninterface BundleManifest {\n steps?: Record<string, unknown>;\n workflows?: Record<string, Record<string, { workflowId?: string }>>;\n}\n\n/**\n * Where the workflow bundle is read from, and the project it is built from.\n *\n * @param options - The `events.workflows` option.\n * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the\n * builder finds the SDK from where it writes, and skips only this directory when it\n * looks for workflows.\n */\nexport function resolveWorkflowPaths(options: WorkflowsOptions = {}): {\n root: string;\n dir: string;\n} {\n const root = resolve(options.root ?? process.cwd());\n return { root, dir: shippedBundle ?? join(root, WORKFLOW_BUNDLE.dir) };\n}\n\n/** The bundle `brick build` shipped beside a compiled server, which reads it instead of building one. */\nlet shippedBundle: string | undefined;\n\n/** @internal Called by a compiled server before it loads its app. */\nexport function setShippedWorkflowBundle(dir: string): void {\n shippedBundle = resolve(dir);\n}\n\n/** Whether this process runs a compiled server that reads the bundle shipped beside it. */\nexport const isWorkflowBundleShipped = (): boolean =>\n shippedBundle !== undefined;\n\n/**\n * Runs workflow listeners: wires the world into the Workflow SDK, serves the\n * built bundle from this process, and starts one run for each delivery.\n *\n * Nothing is loaded until it is needed, so an app without workflow listeners\n * never imports the SDK.\n */\nexport class WorkflowRuntime {\n readonly root: string;\n private ready: Promise<WorkflowSdk> | undefined;\n private connected: Promise<WorkflowSdk> | undefined;\n private closed = false;\n\n constructor(\n readonly world: EventsWorld,\n options: WorkflowsOptions | undefined,\n /** The listeners and schedules that run workflows. */\n private readonly listeners: readonly {\n readonly name: string;\n readonly workflow?: unknown;\n }[],\n private readonly deps: Record<string, unknown> = {},\n ) {\n this.root = resolveWorkflowPaths(options).root;\n }\n\n /** Read when used, in case a bundler evaluates the app before the compiled server names its shipped bundle. */\n get dir(): string {\n return resolveWorkflowPaths({ root: this.root }).dir;\n }\n\n /** Begin loading the runtime now rather than at the first delivery. */\n warmUp(): void {\n this.ensure().catch((error) =>\n console.error(\n `[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n\n /**\n * Start the run for a delivery.\n *\n * The run is named after the delivery id, so a delivery that is tried again\n * finds the run it already started instead of starting another.\n *\n * @param listener - The workflow listener the delivery is for.\n * @param delivery - The delivery.\n */\n async startRun(\n listener: EventListener,\n delivery: EventDelivery,\n ): Promise<void> {\n const sdk = await this.ensure();\n const { attempt: _attempt, ...event } = delivery;\n await sdk.start(listener.workflow, [event satisfies WorkflowEvent], {\n world: this.world,\n runKey: delivery.deliveryId,\n runKeyTime: Date.parse(delivery.occurredAt),\n });\n }\n\n /**\n * Start the workflow of a schedule's run. The workflow run is named after\n * the run key, so a run that is tried again does not start another.\n */\n async startScheduled(schedule: Schedule, run: ScheduleRun): Promise<void> {\n const sdk = await this.ensure();\n const { attempt: _attempt, ...workflowRun } = run;\n await sdk.start(schedule.workflow, [workflowRun], {\n world: this.world,\n runKey: `schedule:${run.runKey}`,\n runKeyTime: Date.parse(run.slot),\n });\n }\n\n /**\n * Answer a request to a webhook a workflow created with `createWebhook`, by\n * resuming the workflow that waits on it. Needs the world but not the queue\n * consumer, so a process that only records events (`dispatch: false`) serves\n * webhooks too.\n *\n * @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.\n * @returns The response the bundle's webhook handler gives.\n */\n async handleWebhook(request: Request): Promise<Response> {\n await this.connect();\n const file = join(this.dir, WORKFLOW_BUNDLE.webhook);\n if (!existsSync(file))\n throw new Error(`No webhook bundle at ${file}. ${NOT_BUILT}`);\n const handlers = await import(pathToFileURL(file).href);\n const handler = handlers[request.method];\n if (typeof handler !== \"function\")\n return new Response(null, { status: 405 });\n return handler(request);\n }\n\n /** Stop the world. The runtime cannot be started again afterwards. */\n async close(): Promise<void> {\n this.closed = true;\n await this.ready?.catch(() => {});\n await this.connected?.catch(() => {});\n await this.world.close?.();\n }\n\n private ensure(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.ready ??= this.initialize().catch((error) => {\n this.ready = undefined;\n throw error;\n });\n return this.ready;\n }\n\n /** Load the SDK and give it the world: all a webhook needs. */\n private connect(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.connected ??= this.loadSdk()\n .then((sdk) => {\n sdk.setWorld(this.world);\n return sdk;\n })\n .catch((error) => {\n this.connected = undefined;\n throw error;\n });\n return this.connected;\n }\n\n private async initialize(): Promise<WorkflowSdk> {\n if (typeof this.world.createRunId !== \"function\")\n throw new Error(\n \"This world cannot name a run after its key, so an event delivered twice would start two runs. \" +\n \"Use the world from @brickkit/redis-world or @brickkit/bullmq-world.\",\n );\n const sdk = await this.connect();\n const flow = join(this.dir, WORKFLOW_BUNDLE.flow);\n if (!existsSync(flow))\n throw new Error(`No workflow bundle at ${flow}. ${NOT_BUILT}`);\n const manifest = this.readManifest();\n const depsOf = this.checkListeners(manifest);\n const bundle = await this.loadBundle(flow);\n if (typeof bundle.POST !== \"function\")\n throw new Error(`${flow} does not export a POST handler`);\n const post = bundle.POST;\n // Steps run inside this handler, so `useDeps()` in a step finds the deps of\n // the app, or of the plugin whose listener runs the workflow. The queue is\n // named after the workflow: `__wkf_workflow_<workflowId>`.\n this.world.registerHandler?.(WORKFLOW_QUEUE.prefix, (request: Request) => {\n const queue = request.headers.get(WORKFLOW_QUEUE.header) ?? \"\";\n const deps =\n depsOf.get(queue.slice(WORKFLOW_QUEUE.prefix.length)) ?? this.deps;\n return runWithDeps(deps, () => post(request));\n });\n await this.world.start?.();\n return sdk;\n }\n\n private async loadSdk(): Promise<WorkflowSdk> {\n // A compiled server may run where no SDK is installed: then the one beside its bundle.\n const from = [this.root, this.dir].map((dir) =>\n createRequire(join(dir, \"package.json\")),\n );\n const load = async (specifier: string) => {\n let path: string | undefined;\n for (const require of from)\n try {\n path ??= require.resolve(specifier);\n } catch {}\n if (!path) {\n throw new Error(\n `The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`,\n );\n }\n return import(pathToFileURL(path).href);\n };\n const [api, runtime] = await Promise.all([\n load(\"workflow/api\"),\n load(\"workflow/runtime\"),\n ]);\n return { start: api.start, setWorld: runtime.setWorld };\n }\n\n /**\n * The bundle holds its own copy of every step and registers them all when it\n * loads, replacing the ones the app registered. A copy has its own module state:\n * a step would find no database connection, no config, none of what the app set\n * up. So the app's steps are put back, and the bundle's copies serve only the\n * steps the app never loaded.\n */\n private async loadBundle(\n flow: string,\n ): Promise<{ POST?: (request: Request) => Promise<Response> }> {\n const registry = () =>\n (globalThis as Record<symbol, unknown>)[STEP_REGISTRY] as\n | Map<string, unknown>\n | undefined;\n const app = new Map(registry());\n const bundle = await import(pathToFileURL(flow).href);\n const registered = registry();\n if (registered) for (const [id, step] of app) registered.set(id, step);\n return bundle;\n }\n\n private readManifest(): BundleManifest | undefined {\n const path = join(this.dir, WORKFLOW_BUNDLE.manifest);\n if (!existsSync(path)) return undefined;\n return JSON.parse(readFileSync(path, \"utf8\")) as BundleManifest;\n }\n\n /**\n * A listener's workflow must carry the id the transform gives it, and the bundle\n * must know that id: a function that was never transformed, or a bundle built\n * before the workflow existed, would fail on its first delivery with a less\n * helpful message.\n *\n * @returns The deps each workflow's steps run with, by workflow id.\n * @throws When one workflow is run by listeners with different deps (an app\n * and a plugin, or two plugin installs): its steps could see only one set.\n */\n private checkListeners(\n manifest: BundleManifest | undefined,\n ): Map<string, Record<string, unknown>> {\n const depsOf = new Map<string, Record<string, unknown>>();\n const known = new Set<string>();\n for (const file of Object.values(manifest?.workflows ?? {}))\n for (const entry of Object.values(file))\n if (entry.workflowId) known.add(entry.workflowId);\n for (const listener of this.listeners) {\n const id = (listener.workflow as { workflowId?: unknown } | undefined)\n ?.workflowId;\n if (typeof id !== \"string\")\n throw new Error(\n `The workflow of listener '${listener.name}' was not transformed. ` +\n \"Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.\",\n );\n if (manifest && !known.has(id))\n throw new Error(\n `The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`,\n );\n const deps = listenerDeps(listener) ?? this.deps;\n if ((depsOf.get(id) ?? deps) !== deps)\n throw new Error(\n `Workflow '${id}' is run by listeners with different deps (listener '${listener.name}'); give each app or plugin install its own workflow.`,\n );\n depsOf.set(id, deps);\n }\n return depsOf;\n }\n}\n","import type { Service } from \"./types\";\nimport { planRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport {\n bindRoute,\n compilerRuntime,\n type CompiledHandler,\n type CompiledRoutePlan,\n type HandlerFactory,\n} from \"./compiler/runtime\";\nimport { requireBrickApp } from \"./app-entry\";\nimport { portOf } from \"./service-port\";\nimport { setShippedWorkflowBundle } from \"./events/workflows\";\n\n/** @throws When the services no longer analyze to `ir`, so the build is stale. */\nfunction analyzeMatching(services: Service<any, any>[], ir: BrickIR) {\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n return analyzed;\n}\n\n/**\n * Build artifact bootstrap: import the bundled app. It is not re-analyzed\n * against the IR: the bundle and its IR come from one build (#107).\n *\n * @param _ir Ignored; kept so existing callers still type-check.\n * @param options `workflows`: the workflow bundle `brick build` shipped beside\n * the server, read instead of `<root>/.well-known/workflow/v1`.\n */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n _ir?: BrickIR,\n options: { workflows?: string } = {},\n) {\n if (options.workflows) setShippedWorkflowBundle(options.workflows);\n return requireBrickApp((await load()).default);\n}\n\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type {\n CompiledHandler,\n CompiledRoutePlan,\n HandlerFactory,\n} from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n bind: (plan: CompiledRoutePlan, index: number) => CompiledHandler = bindRoute,\n): CompiledApplication {\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(planRoute(route, service, action));\n return Object.freeze({ ir: route, handler: bind(plan, index) });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n /** `\"generic\"` skips the plugins' preparations (no prewarm). */\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n if (options.mode !== \"generic\")\n for (const service of options.services)\n portOf(service).prepareContributions();\n return bindAnalyzed(ir, bindings);\n}\n\n/**\n * Build artifact binder: consumes emitted functions, with no runtime handler code generation.\n *\n * @deprecated `brick build` no longer emits handler factories; built servers\n * use `loadCompiledBrickApp`. Pass `compileBrickApplication(...)` as\n * `brick({ compilation })` instead.\n */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeMatching(services, ir);\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n for (const service of services) portOf(service).prepareContributions();\n return bindAnalyzed(ir, analyzed.bindings, (plan, index) =>\n factories[index]!(plan, compilerRuntime),\n );\n}\n","import type { InstalledPlugin } from \"./plugin-types\";\nimport type { Service, ArchitectureSchema } from \"./types\";\nimport type { RouteIR } from \"./compiler/ir\";\nimport { getActionRoute } from \"./routes\";\nimport type { EventsDefinition } from \"./events/hub\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport { claimName, definitionSite } from \"./definition-site\";\n\nexport interface ArchitectureApplication {\n services: readonly Service<any, any>[];\n routes: readonly RouteIR[];\n events?: EventsDefinition;\n sockets?: readonly (BrickSocketSchema & { service: string; path: string })[];\n plugins?: readonly InstalledPlugin[];\n}\n\nexport class ServiceRegistry {\n private _revision = 0;\n /** Definition revision for invalidating serialized architecture snapshots. */\n get revision(): number {\n return this._revision;\n }\n touch(): void {\n this._revision++;\n }\n\n private services = new Map<string, Service>();\n private sites = new Map<string, string | undefined>();\n\n /** @throws When a different file already registered a service with this name. */\n register(service: Service, site = definitionSite()): void {\n claimName(this.sites, `service \"${service.name}\"`, service.name, site);\n this.services.set(service.name, service);\n this.touch();\n }\n\n get(name: string): Service | undefined {\n return this.services.get(name);\n }\n\n has(name: string): boolean {\n return this.services.has(name);\n }\n\n list(): Service[] {\n return Array.from(this.services.values());\n }\n\n /**\n * The architecture of an app (`app.definition`): its mounted routes. Without\n * one, every registered service with its default routes under `/api`.\n */\n exportArchitecture(\n application?: ArchitectureApplication,\n ): ArchitectureSchema {\n return {\n version: \"1.0.0\",\n ...(application?.events ? { events: application.events } : {}),\n ...(application?.plugins?.length\n ? { plugins: [...application.plugins] }\n : {}),\n services: (application?.services ?? this.list()).map((service) => {\n const byAction = new Map(\n application\n ? application.routes\n .filter((route) => route.service === service.name)\n .map((route) => [route.action, route])\n : service.listActions().flatMap((action) => {\n const route = getActionRoute(action);\n return route ? [[action.name, route] as const] : [];\n }),\n );\n const schema = service.introspect();\n return {\n ...schema,\n ...(application?.sockets\n ? {\n sockets: application.sockets.filter(\n (socket) => socket.service === service.name,\n ),\n }\n : {}),\n actions: schema.actions.map((action) => {\n const route = byAction.get(action.name);\n return route\n ? { ...action, method: route.method, path: route.path }\n : action;\n }),\n };\n }),\n };\n }\n}\n\nlet globalRegistry = new ServiceRegistry();\n\n/**\n * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI\n * generator, `useService`, and the dashboard find services by name.\n *\n * @returns The current global registry.\n */\nexport function getGlobalRegistry(): ServiceRegistry {\n return globalRegistry;\n}\n\n/**\n * Start over with an empty global registry. For tests, which define the same\n * services again in each case; an application never needs it.\n */\nexport function resetGlobalRegistry(): void {\n globalRegistry = new ServiceRegistry();\n}\n","import type { Action, ActionAccessPolicy } from \"./types\";\nimport { actionMeta, type ActionAccessInfo } from \"./action-meta\";\n\nexport type { ActionAccessPolicy, ActionAccessInfo };\n\n/**\n * Record how an action is protected, for tools that cannot read it from the\n * configuration: plugins such as `crud` enforce access inside `execute`, so the\n * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard\n * read what is recorded here.\n *\n * @param action - The action to describe.\n * @param info - Whether it checks authorization and whether it scopes queries,\n * and the resulting policy.\n */\nexport function setActionAccess(action: object, info: ActionAccessInfo): void {\n actionMeta(action).access = {\n hasAuthorize: info.hasAuthorize,\n hasScope: info.hasScope,\n policy: info.policy,\n };\n}\n\n/**\n * How an action is protected: `\"public\"` when nothing checks the caller,\n * `\"authorized\"` when an `authorize` does, and `\"scoped\"` when the action also\n * limits what rows the caller can reach. It reads what a plugin recorded with\n * `setActionAccess`, else the action's own `authorize`, and keeps the policy\n * consistent with the flags.\n *\n * @param action - An action, or any object a plugin described.\n * @returns `hasAuthorize`, `hasScope`, and `policy`.\n */\nexport function getActionAccess(action: Action | object): ActionAccessInfo {\n const meta = actionMeta(action).access;\n const configAuthorize =\n typeof (action as Partial<Action>).config?.authorize === \"function\";\n if (!meta) {\n return {\n hasAuthorize: configAuthorize,\n hasScope: false,\n policy: configAuthorize ? \"authorized\" : \"public\",\n };\n }\n const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);\n const hasScope = Boolean(meta.hasScope);\n let policy: ActionAccessPolicy =\n meta.policy ??\n (hasAuthorize ? (hasScope ? \"scoped\" : \"authorized\") : \"public\");\n // Normalize conflicting metadata so the policy always agrees with the\n // effective flags (e.g. metadata stamped \"public\" on an action that also\n // declares config.authorize must not report policy \"public\").\n if (policy === \"public\" && hasAuthorize)\n policy = hasScope ? \"scoped\" : \"authorized\";\n else if (policy !== \"public\" && !hasAuthorize) policy = \"public\";\n else if (policy === \"scoped\" && !hasScope) policy = \"authorized\";\n return { hasAuthorize, hasScope, policy };\n}\n\n/**\n * Say how the audit log records an action a plugin owns: `\"inline\"` when the\n * plugin writes in its own transaction and records the write there with a\n * host hook, `\"none\"` when it never writes. Without this, an action that is not\n * a `GET` is recorded after it runs, as a plain action is.\n */\nexport function setActionAudit(action: object, mode: \"inline\" | \"none\"): void {\n actionMeta(action).audit = mode;\n}\n","import type { EventRef } from \"./events/catalog\";\nimport {\n DEFAULT_PREFIX,\n actionOwners,\n pathParamNames,\n toOpenApiPath,\n} from \"./routes\";\nimport { analyzeDeclaredApplication } from \"./compiler/ir\";\nimport { getActionAccess } from \"./access\";\nimport { rateLimitsOf } from \"./rate-limit\";\nimport { webhookOf } from \"./webhook\";\nimport { fileFields } from \"./typebox\";\nimport { writeOnly } from \"./sensitive\";\nimport { getGlobalRegistry } from \"./registry\";\nimport type { Service, ActionErrorDefinition } from \"./types\";\n\n/** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */\nexport const OPENAPI_DEFAULTS = Object.freeze({\n title: \"Brick-TS API Mesh\",\n version: \"1.0.0\",\n path: \"/openapi.json\",\n});\n\nexport interface OpenApiGeneratorOptions {\n title?: string;\n version?: string;\n description?: string;\n prefix?: string;\n services?: Service<any, any>[];\n}\n\nfunction isAnchor(\n node: unknown,\n): node is { $id: string } & Record<string, any> {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$id === \"string\"\n );\n}\n\nfunction isBareRef(node: unknown): node is { $ref: string } {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$ref === \"string\" &&\n !(node as { $ref: string }).$ref.startsWith(\"#\")\n );\n}\n\nfunction toComponentKey(id: string): string {\n return id.replace(/[^A-Za-z0-9.\\-_]+/g, \"_\");\n}\n\n/**\n * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors\n * (`{ $id: \"T0\", ..., { $ref: \"T0\" } }`). OpenAPI interprets a bare `$ref`\n * as an external file reference, so downstream tooling tries to load a\n * file named `T0` and fails. Hoist every anchored subschema into\n * `#/components/schemas/` and rewrite the refs to local pointers.\n * First definition wins when one `$id` is declared twice.\n */\nfunction hoistAnchoredSchemas(spec: Record<string, any>): void {\n const anchored = new Map<string, any>();\n\n const collect = (node: any): any => {\n if (Array.isArray(node)) return node.map(collect);\n if (typeof node !== \"object\" || node === null) return node;\n if (isAnchor(node)) {\n const id = node.$id;\n const { $id: _dropped, ...rest } = node;\n const collected = collect(rest);\n if (!anchored.has(id)) anchored.set(id, collected);\n return { $ref: `#/components/schemas/${toComponentKey(id)}` };\n }\n for (const key of Object.keys(node)) {\n node[key] = collect(node[key]);\n }\n return node;\n };\n\n const rewrite = (node: any): void => {\n if (Array.isArray(node)) {\n for (const child of node) rewrite(child);\n return;\n }\n if (typeof node !== \"object\" || node === null) return;\n if (isBareRef(node)) {\n node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;\n }\n for (const key of Object.keys(node)) rewrite(node[key]);\n };\n\n collect(spec);\n\n const components = (spec.components ??= {}) as Record<string, any>;\n const schemas = (components.schemas ??= {}) as Record<string, any>;\n for (const [id, schema] of anchored) {\n schemas[toComponentKey(id)] = schema;\n }\n\n // Second pass covers refs inside the hoisted copies themselves\n // (e.g. the self-recursive JSON-value schema).\n rewrite(spec);\n}\n\n/**\n * Build the OpenAPI 3.1 document for the services: one path per action route,\n * with request and response schemas from the actions' TypeBox schemas, their\n * declared errors, tags by service, and a bearer security scheme where any\n * action needs authorization. Declared events are listed under `x-brick-events`,\n * by wire name, with their service and payload schema.\n *\n * `brick()` calls this for `/openapi.json`; call it yourself to write the\n * document to a file or feed another tool.\n *\n * @param options - `title`, `version`, and `description` for the `info` block,\n * `prefix` (default `/api`), and the `services` to describe (the global\n * registry's by default).\n * @returns The document as a plain object.\n */\nexport function generateOpenApiSpec(\n options: OpenApiGeneratorOptions = {},\n): Record<string, any> {\n const title = options.title ?? OPENAPI_DEFAULTS.title;\n const version = options.version ?? OPENAPI_DEFAULTS.version;\n const description =\n options.description ??\n \"Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.\";\n const prefix = options.prefix ?? DEFAULT_PREFIX;\n\n const services = options.services ?? getGlobalRegistry().list();\n\n const paths: Record<string, any> = {};\n const tags = new Map<string, string>();\n let hasAnyAuthorizedAction = false;\n\n // The routes the server mounts: shadowed ones are left out, as the router leaves them out.\n const { ir, bindings } = analyzeDeclaredApplication([...services], prefix);\n for (const service of services) {\n tags.set(service.name, `Actions exposed by '${service.name}' service`);\n\n for (const [index, route] of ir.routes.entries()) {\n if (route.service !== service.name) continue;\n const { action } = bindings[index]!;\n const routePath = route.path;\n const method = route.method.toLowerCase();\n const pathParams = pathParamNames(routePath);\n const actionPath = toOpenApiPath(routePath);\n if (!paths[actionPath]) paths[actionPath] = {};\n\n const { plugin, resource } = actionOwners(action);\n // Resource routes group under `service · resource`.\n const group = resource ? `${service.name} · ${resource}` : service.name;\n if (resource)\n tags.set(\n group,\n `Routes of resource '${resource}' in service '${service.name}'`,\n );\n\n const webhook = webhookOf(action);\n const hasAuth = getActionAccess(action).hasAuthorize;\n if (hasAuth) {\n hasAnyAuthorizedAction = true;\n }\n\n const responses: Record<string, any> = {};\n\n if (action.config.output) {\n responses[\"200\"] = {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: action.config.output,\n },\n },\n };\n } else {\n responses[\"200\"] = {\n description: \"Successful response\",\n };\n }\n\n const errorAlternatives = new Set<string>();\n const addError = (\n code: string,\n status: number,\n message: string,\n details?: unknown,\n ) => {\n const key = `${status}:${code}`;\n if (errorAlternatives.has(key)) return;\n errorAlternatives.add(key);\n const schema = {\n allOf: [\n { $ref: \"#/components/schemas/ErrorEnvelope\" },\n {\n type: \"object\",\n properties: {\n code: { const: code },\n status: { const: status },\n ...(details ? { details } : {}),\n },\n },\n ],\n };\n const existing = responses[String(status)];\n if (existing) {\n existing.description += \"; \" + message;\n existing.content[\"application/json\"].schema.oneOf.push(schema);\n } else {\n responses[String(status)] = {\n description: message,\n content: { \"application/json\": { schema: { oneOf: [schema] } } },\n };\n }\n };\n if (action.config.input)\n addError(\"VALIDATION_FAILED\", 400, \"Validation error\");\n if (hasAuth) {\n addError(\"UNAUTHORIZED\", 401, \"Authentication required\");\n addError(\"FORBIDDEN\", 403, \"Access denied\");\n }\n if (webhook) {\n addError(\"UNAUTHORIZED\", 401, \"Webhook verification failed\");\n addError(\n \"PAYLOAD_TOO_LARGE\",\n 413,\n `Body over ${webhook.maxBodyBytes} bytes`,\n );\n if (webhook.replay) {\n addError(\n \"CONFLICT\",\n 409,\n \"Another delivery of this event is being handled; retry later\",\n );\n addError(\n \"SERVICE_UNAVAILABLE\",\n 503,\n \"Webhook storage is unavailable; retry later\",\n );\n }\n }\n if ((action.config as { dashboard?: boolean }).dashboard === true)\n addError(\"UNAUTHORIZED\", 401, \"Only for the dashboard\");\n if (rateLimitsOf(action.config)) {\n addError(\n \"RATE_LIMITED\",\n 429,\n \"Too many calls; retry after Retry-After seconds\",\n {\n type: \"object\",\n properties: { retryAfterSeconds: { type: \"integer\", minimum: 1 } },\n required: [\"retryAfterSeconds\"],\n },\n );\n responses[\"429\"].headers = {\n \"Retry-After\": {\n description: \"Seconds until the window resets\",\n schema: { type: \"integer\", minimum: 1 },\n },\n };\n }\n if (action.config.errors) {\n for (const [code, errorDef] of Object.entries(action.config.errors)) {\n const def = errorDef as ActionErrorDefinition;\n addError(code, def.status || 400, def.message || code, def.details);\n }\n }\n addError(\"INTERNAL_SERVER_ERROR\", 500, \"Internal server error\");\n if (action.config.output)\n addError(\"VALIDATION_FAILED\", 500, \"Output validation error\");\n\n const operation: Record<string, any> = {\n operationId: `${service.name}_${action.name}_${method}`,\n summary: `${service.name}.${action.name}`,\n description:\n action.config.description ??\n `Execute action '${action.name}' on service '${service.name}'`,\n tags: [...new Set([group, ...(action.config.tags ?? [])])],\n ...(webhook ? { \"x-brick-webhook\": true } : {}),\n ...(plugin ? { \"x-brick-plugin\": plugin } : {}),\n ...(resource ? { \"x-brick-resource\": resource } : {}),\n responses,\n };\n\n const inputSchema = writeOnly(action.config.input);\n const properties = inputSchema?.properties ?? {};\n const parameters: any[] = [...new Set(pathParams)].map((key) => ({\n name: key,\n in: \"path\",\n required: true,\n schema: properties[key] ?? { type: \"string\" },\n }));\n if (route.inputSource === \"query\") {\n for (const [key, schema] of Object.entries(properties)) {\n if (pathParams.includes(key)) continue;\n parameters.push({\n name: key,\n in: \"query\",\n required: inputSchema?.required?.includes(key) ?? false,\n schema,\n });\n }\n } else if (inputSchema) {\n const bodySchema =\n pathParams.length && inputSchema.properties\n ? {\n ...inputSchema,\n properties: Object.fromEntries(\n Object.entries(properties).filter(\n ([key]) => !pathParams.includes(key),\n ),\n ),\n required: (inputSchema.required ?? []).filter(\n (key: string) => !pathParams.includes(key),\n ),\n }\n : inputSchema;\n operation.requestBody = {\n required: true,\n content: {\n [fileFields(inputSchema).length\n ? \"multipart/form-data\"\n : \"application/json\"]: { schema: bodySchema },\n ...(webhook\n ? { \"application/x-www-form-urlencoded\": { schema: bodySchema } }\n : {}),\n },\n };\n }\n if (parameters.length) operation.parameters = parameters;\n if (hasAuth) operation.security = [{ bearerAuth: [] }];\n paths[actionPath][method] = operation;\n }\n }\n\n const spec: Record<string, any> = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n description,\n },\n paths,\n tags: Array.from(tags, ([name, description]) => ({ name, description })),\n };\n\n spec.components = {\n schemas: {\n ErrorEnvelope: {\n type: \"object\",\n required: [\"name\", \"code\", \"message\", \"status\", \"requestId\"],\n properties: {\n name: { type: \"string\" },\n code: { type: \"string\" },\n message: { type: \"string\" },\n status: { type: \"integer\" },\n requestId: { type: \"string\" },\n details: {},\n errors: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"path\", \"message\"],\n properties: {\n path: { type: \"string\" },\n message: { type: \"string\" },\n },\n },\n },\n },\n },\n },\n };\n if (hasAnyAuthorizedAction) {\n Object.assign(spec.components, {\n securitySchemes: {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n description: \"Enter your Bearer authentication token\",\n },\n },\n });\n }\n\n const events = Object.fromEntries(\n services.flatMap((service) =>\n Object.values(\n (service as { events?: Record<string, EventRef> }).events ?? {},\n ).map((ref) => [\n ref.name,\n {\n service: service.name,\n payload: ref.schema,\n ...(ref.plugin ? { \"x-brick-plugin\": ref.plugin } : {}),\n },\n ]),\n ),\n );\n if (Object.keys(events).length) spec[\"x-brick-events\"] = events;\n\n // Operations reference live TypeBox schemas. Rewrite only the serialized\n // document so OpenAPI pointers cannot corrupt runtime validation schemas.\n const document: Record<string, any> = JSON.parse(JSON.stringify(spec));\n hoistAnchoredSchemas(document);\n\n return document;\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface RequestLoggingOptions {\n enabled?: boolean;\n logger?: (msg: string) => void;\n}\n\nfunction formatLog(\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number,\n): string {\n return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n}\n\n/**\n * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError\n * while `set.status` may still hold the 200 default when onError runs).\n */\nfunction thrownStatus(error: unknown): number | undefined {\n if (typeof error === \"object\" && error !== null && \"status\" in error) {\n const status: unknown = error.status;\n if (typeof status === \"number\") return status;\n }\n return undefined;\n}\n\n/**\n * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.\n * Timing is tracked per-Request via a WeakMap. The onError hook only logs and\n * returns undefined so existing error mapping is preserved.\n *\n * Hooks are registered with the \"global\" scope so they propagate to the\n * parent app when mounted via `app.use(...)` — Elysia scopes plain instance\n * hooks to the plugin's own routes. Timing is captured in beforeHandle\n * because request hooks are not propagated from a\n * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().\n */\nexport function requestLoggingPlugin(opts: RequestLoggingOptions = {}): Elysia {\n const plugin = new Elysia();\n const enabled = opts.enabled ?? true;\n if (!enabled) return plugin;\n const logger = opts.logger ?? console.log;\n const startedAt = new WeakMap<object, number>();\n\n const markStarted = ({ request }: Pick<Context, \"request\">): void => {\n startedAt.set(request, Date.now());\n };\n\n const logSuccess = ({\n request,\n set,\n responseValue,\n }: Pick<Context, \"request\" | \"set\"> & { responseValue?: unknown }): void => {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n // A raw route's Response carries its own status; `set.status` stays 200.\n const status =\n responseValue instanceof Response\n ? responseValue.status\n : (set.status ?? 200);\n logger(formatLog(request.method, path, status, Date.now() - start));\n };\n\n const logError = ({\n request,\n set,\n error,\n }: Pick<Context, \"request\" | \"set\"> & { error?: unknown }): undefined => {\n if (request) {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n const status = thrownStatus(error) ?? set.status ?? 500;\n logger(formatLog(request.method, path, status, Date.now() - start));\n }\n return undefined;\n };\n\n plugin.onBeforeHandle(\"global\", markStarted);\n plugin.onAfterHandle(\"global\", logSuccess);\n plugin.onError(\"global\", logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\nimport { OPENAPI_DEFAULTS } from \"./openapi\";\n\n/** An OpenAPI document as plain JSON. */\nexport type OpenApiDocument = Record<string, unknown>;\n\n/** An extra OpenAPI document for the API reference, such as Better Auth's. */\nexport interface ReferenceDocument {\n /** Name in the reference's list of documents. */\n title: string;\n /** The document, or a function returning it; called each time the app starts. */\n document:\n | OpenApiDocument\n | (() => OpenApiDocument | Promise<OpenApiDocument>);\n}\n\n/** A named OpenAPI document ready to render. */\nexport interface ApiDocument {\n title: string;\n document: OpenApiDocument;\n}\n\n/** Developer documentation for the `brick dev` dashboard. */\nexport interface DocumentationOptions {\n /**\n * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the\n * app entry, as it reads in the file that sets it.\n */\n dir: string;\n /**\n * Module whose exports are React components for MDX, added to the built-in\n * ones; a relative path starts where `dir` does. A default export or a\n * `components` export holds the name-to-component map. The dashboard bundles\n * it, so it may import anything the project has.\n */\n components?: string;\n}\n\nexport interface ReferenceOptions {\n /** Also serve a standalone Scalar page here. Without a path, no page is served. */\n path?: string;\n title?: string;\n specUrl?: string;\n /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */\n documents?: ReferenceDocument[];\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/**\n * Standalone Elysia plugin serving GET <path> with the Scalar HTML page.\n *\n * @deprecated Use `brick({ reference: true })` or `reference: { path }`.\n */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? OPENAPI_DEFAULTS.title;\n const specUrl = opts.specUrl ?? OPENAPI_DEFAULTS.path;\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/**\n * Mounts the Scalar reference route onto an existing app.\n *\n * @deprecated Use `brick({ reference: true })` or `reference: { path }`.\n */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","import type { DashboardUser } from \"./dashboard-identity\";\n\n/** Who may open the dashboard that `brick start` serves for monitoring. */\nexport interface DashboardAuth {\n /**\n * Secrets that let a request in. A browser asks for one in its sign-in\n * prompt (any user name, the secret as the password), and monitors and\n * scripts send `Authorization: Bearer <secret>`. Give several to rotate one\n * while the other still works. Each is at least 16 characters long;\n * `openssl rand -base64 32` makes a good one.\n */\n token?: string | readonly string[];\n /**\n * Your own check, to sign people in with the auth the app already has: read\n * a session cookie, verify a Better Auth or Clerk session, look at a header\n * a proxy adds. It receives the request (method, URL, and headers; no body)\n * and returns `true` to let it in, `false` to refuse it with 401, or a\n * `Response` to send instead, such as a redirect to your login page. If it\n * throws or takes longer than five seconds, the request is refused with 503.\n *\n * Return `{ user: { id, name } }` to let it in and say who it is: requests\n * the dashboard's pages send to the app through `/app/*` carry that user,\n * signed, which the app reads with `ctx.dashboard?.user` in an action or\n * `dashboardUser(request)` in an endpoint.\n *\n * A request is let in when it carries a valid `token`, or when this\n * returns `true`; give both to let monitors in by token and people in by\n * sign-in.\n */\n authorize?: (\n request: Request,\n ) =>\n | boolean\n | Response\n | { user: DashboardUser }\n | Promise<boolean | Response | { user: DashboardUser }>;\n}\n\n/**\n * The monitoring dashboard `brick start` serves beside the app, on a port of\n * its own: live requests, logs, errors, and the shape of the service, so it\n * stays reachable when the app's own routes are not. `brick dev` has its own\n * dashboard, set by command line options, and ignores this.\n *\n * Setting it turns on `telemetry`, since the dashboard shows what is traced.\n * While it is on, `ctx.logger` and `console` lines written during a request\n * go to the dashboard instead of the console.\n */\nexport interface DashboardOptions {\n /** Default 9400. */\n port?: number;\n /**\n * The address to listen on. Default `127.0.0.1`, reachable only from the same\n * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard\n * will not start on any other address without it.\n */\n host?: string;\n auth?: DashboardAuth;\n /**\n * Days of finished requests to keep on disk, in `.brick/` of the working\n * folder. Default 0: only what happened since the process started, which is\n * lost when it restarts. Needs a folder that outlives the container.\n */\n historyDays?: number;\n /**\n * Show the Schedules and Workflows views, which `brick dev` always has: each\n * schedule's next run and last runs, and the workflow inspector with every\n * run's steps. Default false, because they do more than monitor: a signed-in\n * user (one `auth.authorize` returned as `{ user }`) can run a schedule now,\n * cancel or replay a run, and resume a hook. Anyone else the dashboard lets\n * in (by token, or by `authorize` returning `true`) can only look.\n */\n inspector?: boolean;\n /**\n * Let a coding agent (Claude Code, Cursor, Codex) read the dashboard's data\n * over MCP at `/mcp`, while it debugs: requests, traces, logs, errors and the\n * app's architecture. Default false; `brick dev` always has it, since it only\n * listens on this machine. Its own tools only read, even for a signed-in\n * user, and it passes the same checks as the rest of the dashboard: the agent sends\n * `Authorization: Bearer <token>` with one of `auth.token`.\n *\n * What the agent reads goes to its model provider: request paths and\n * messages, log lines (which can hold what your users typed), error stacks,\n * and span attributes such as SQL text. Turn it on only for a dashboard\n * whose data you are willing to send there.\n *\n * It also serves the app's own tools marked `dashboard: true` (see\n * `service.tool`), next to the dashboard's. A tool that is not marked\n * `readOnlyHint: true` can change data, and is offered only to a signed-in\n * user (one `auth.authorize` returned as `{ user }`).\n */\n mcp?: boolean;\n}\n\n/**\n * Where the app answers MCP for the dashboard's `/mcp`: its tools marked\n * `dashboard: true`. Only a request signed by the dashboard gets in.\n */\nexport const DASHBOARD_MCP_ROUTE = \"/_brick/dashboard/mcp\";\n\n/** The dashboard's own MCP tools. A `dashboard: true` tool may not take one of these names. */\nexport const DASHBOARD_MCP_TOOLS = [\n \"summary\",\n \"list_requests\",\n \"get_trace\",\n \"list_errors\",\n \"app_overview\",\n \"search_logs\",\n \"list_reloads\",\n \"list_schedules\",\n \"list_runs\",\n \"get_run\",\n \"get_openapi\",\n \"list_docs\",\n \"read_doc\",\n] as const;\n\nconst MIN_TOKEN_LENGTH = 16;\n\n/**\n * Check what `brick()` was given, and freeze it. The secrets sit behind a getter\n * that is not enumerable, so logging or serializing the application definition\n * does not print them.\n */\nexport function normalizeDashboard(\n options: DashboardOptions | undefined,\n): DashboardOptions | undefined {\n if (options === undefined) return undefined;\n const { port, host, auth, historyDays, inspector, mcp } = options;\n if (\n port !== undefined &&\n (!Number.isInteger(port) || port < 1 || port > 65535)\n )\n throw new Error(\n `Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`,\n );\n if (host !== undefined && (typeof host !== \"string\" || host.trim() === \"\"))\n throw new Error(\n \"Brick: dashboard host must be an address, such as '0.0.0.0'.\",\n );\n if (\n historyDays !== undefined &&\n (!Number.isInteger(historyDays) || historyDays < 0)\n )\n throw new Error(\n `Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`,\n );\n if (inspector !== undefined && typeof inspector !== \"boolean\")\n throw new Error(\"Brick: dashboard inspector must be true or false.\");\n if (mcp !== undefined && typeof mcp !== \"boolean\")\n throw new Error(\"Brick: dashboard mcp must be true or false.\");\n const normalized: DashboardOptions = {\n ...(port !== undefined ? { port } : {}),\n ...(host !== undefined ? { host: host.trim() } : {}),\n ...(historyDays !== undefined ? { historyDays } : {}),\n ...(inspector !== undefined ? { inspector } : {}),\n ...(mcp !== undefined ? { mcp } : {}),\n };\n if (auth !== undefined) {\n const tokens =\n auth.token === undefined\n ? undefined\n : typeof auth.token === \"string\"\n ? [auth.token]\n : [...auth.token];\n if (\n tokens?.some(\n (token) => typeof token !== \"string\" || token.length < MIN_TOKEN_LENGTH,\n )\n )\n throw new Error(\n `Brick: a dashboard token must be at least ${MIN_TOKEN_LENGTH} characters. Try: openssl rand -base64 32`,\n );\n if (auth.authorize !== undefined && typeof auth.authorize !== \"function\")\n throw new Error(\"Brick: dashboard authorize must be a function.\");\n if ((tokens === undefined || tokens.length === 0) && !auth.authorize)\n throw new Error(\n \"Brick: dashboard auth needs a token or an authorize function.\",\n );\n const secrets = Object.freeze({\n ...(tokens ? { token: Object.freeze(tokens) } : {}),\n ...(auth.authorize ? { authorize: auth.authorize } : {}),\n });\n // A getter, so inspecting the object (Bun prints hidden fields too) shows\n // `[Getter]` and not the secrets.\n Object.defineProperty(normalized, \"auth\", {\n enumerable: false,\n get: () => secrets,\n });\n }\n return Object.freeze(normalized);\n}\n","import {\n DuplicateNameError,\n type ActionContext,\n type Service,\n type Tool,\n type ToolAnnotations,\n} from \"./types\";\nimport { withClientIp, type ClientIp } from \"./rate-limit\";\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 }`.\nexport const 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 * Where the client address is, for a tool's `rateLimit: { per: \"ip\" }`, as\n * `brick({ clientIp })`. Mounted on a Brick app, the handler already uses\n * the app's; this one replaces it.\n */\n clientIp?: ClientIp;\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 if (options.clientIp) withClientIp(request, options.clientIp);\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","import type { HttpMethod } from \"./http\";\nimport type { RouteIR } from \"./compiler/ir\";\nimport type { Elysia } from \"elysia\";\nimport type { Logger, Service } from \"./types\";\nimport type { DatabaseHandle } from \"./db/define\";\nimport type { ApiDocument, DocumentationOptions } from \"./docs\";\nimport type { DashboardOptions } from \"./dashboard\";\nimport type { EventsDefinition, EventsHub } from \"./events/hub\";\nimport { toErrorResponse } from \"./error-response\";\nimport { pathParamNames, toOpenApiPath } from \"./routes\";\nimport { createLogger } from \"./logger\";\nimport { requestIds } from \"./context\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport type { InstalledPlugin } from \"./plugin-types\";\n\nexport type EndpointMethod = HttpMethod;\n\n/** The logger handed to endpoint handlers (the same one actions get). */\nexport type EndpointLogger = Logger;\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n /** The plugin that contributed it; OpenAPI labels it `x-brick-plugin`. */\n plugin?: string;\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb();\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n const tag = `endpoint:${def.method} ${def.path}`;\n const logger = createLogger(`[${tag}]`);\n return async ({ params, body, query, headers, request, set }: any) => {\n const { traceId, requestId } = requestIds(headers, set);\n\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger,\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err) {\n const failure =\n !(\n err instanceof ActionExecutionError || err instanceof ValidationError\n ) &&\n err !== null &&\n typeof err === \"object\" &&\n \"status\" in err &&\n typeof err.status === \"number\" &&\n Number.isInteger(err.status) &&\n err.status >= 400 &&\n err.status < 500\n ? new ActionExecutionError(\n \"HTTP_ERROR\",\n \"message\" in err && typeof err.message === \"string\"\n ? err.message\n : \"Endpoint error\",\n err.status,\n undefined,\n { cause: err },\n )\n : err;\n const response = toErrorResponse(failure, {\n logger: ctx.logger,\n requestId,\n });\n set.status = response.status;\n return response;\n }\n };\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(def.plugin ? { \"x-brick-plugin\": def.plugin } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Service definitions, prefix, and telemetry setting chosen at construction. */\n readonly definition: {\n readonly routes: readonly RouteIR[];\n readonly sockets: readonly (BrickSocketSchema & {\n service: string;\n path: string;\n })[];\n readonly services: readonly Service<any, any>[];\n readonly prefix: string;\n readonly telemetry: boolean;\n readonly documentation?: DocumentationOptions;\n /** What `brick start` serves for monitoring; its `auth` is not enumerable. */\n readonly dashboard?: DashboardOptions;\n /** The listeners and settings of `events`, as plain data. */\n readonly events?: EventsDefinition;\n /** Every `definePlugin` installation, in install order. */\n readonly plugins?: readonly InstalledPlugin[];\n };\n /**\n * Run the plugins' `on(\"start\")` handlers in install order, once. `listen`\n * calls it; `brick dev` and `brick start` await it before serving. `stop()`\n * runs their `on(\"stop\")` handlers in reverse order.\n */\n start(): Promise<void>;\n /**\n * Start the plugins, listen on `port`, then start event delivery. What\n * `brick dev`, `brick start` and a built server run.\n */\n serve(options: { port: number }): Promise<BrickApp>;\n /**\n * Stop event delivery (finishing deliveries in flight), then the server, then\n * the plugins. `closeActiveConnections` is passed to `stop()`.\n */\n shutdown(closeActiveConnections?: boolean): Promise<void>;\n /**\n * The events of this app, when `events` is set: start and stop delivery, drain\n * what is due, and see or retry what is parked. `brick dev` and `brick start`\n * start it for you.\n */\n readonly events?: EventsHub;\n /** Register a raw endpoint (a plain route, not an action). */\n endpoint(def: EndpointDefinition): void;\n /**\n * The OpenAPI documents behind the dashboard's APIs view: this app's own\n * unless `docs` is false, then those from `reference.documents`.\n */\n referenceDocuments(): Promise<ApiDocument[]>;\n /** This app's OpenAPI document, as `/openapi.json` serves it (also when `docs` is false). */\n openApiDocument(): Record<string, any>;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","const ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nexport function newEventId(now: number = Date.now()): string {\n let time = \"\";\n let remaining = now;\n for (let index = 0; index < 10; index++) {\n time = ALPHABET[remaining % 32] + time;\n remaining = Math.floor(remaining / 32);\n }\n let random = \"\";\n for (const byte of crypto.getRandomValues(new Uint8Array(16))) {\n random += ALPHABET[byte % 32];\n }\n return `evt_${time}${random}`;\n}\n\n/**\n * A delivery's id: `<event id>:<listener>`, which is why a listener name cannot\n * contain `:`.\n */\nexport const deliveryId = (eventId: string, listener: string) =>\n `${eventId}:${listener}`;\n","import {\n bigserial,\n index as pgIndex,\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp,\n} from \"drizzle-orm/pg-core\";\nimport {\n index as sqliteIndex,\n integer as sqliteInteger,\n sqliteTable,\n text as sqliteText,\n} from \"drizzle-orm/sqlite-core\";\nimport { deliveryId } from \"./id\";\nimport type { EventDelivery, EventEnvelope } from \"./types\";\n\nconst OUTBOX = Symbol.for(\"brick.outbox\");\n\nexport const OUTBOX_STATUSES = [\n \"pending\",\n \"claimed\",\n \"delivered\",\n \"dead\",\n] as const;\n/** What the outbox rows are in, by state. */\nexport type OutboxStatus = (typeof OUTBOX_STATUSES)[number];\n\nfunction sqliteOutbox(name: string) {\n const timestampMs = (column: string) =>\n sqliteInteger(column, { mode: \"timestamp_ms\" });\n return sqliteTable(\n name,\n {\n seq: sqliteInteger(\"seq\").primaryKey({ autoIncrement: true }),\n id: sqliteText(\"id\").notNull().unique(),\n eventId: sqliteText(\"event_id\").notNull(),\n listener: sqliteText(\"listener\").notNull(),\n name: sqliteText(\"name\").notNull(),\n payload: sqliteText(\"payload\", { mode: \"json\" }).notNull(),\n traceId: sqliteText(\"trace_id\"),\n source: sqliteText(\"source\"),\n occurredAt: timestampMs(\"occurred_at\").notNull(),\n status: sqliteText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: sqliteInteger(\"attempts\").notNull().default(0),\n lastError: sqliteText(\"last_error\"),\n availableAt: timestampMs(\"available_at\").notNull(),\n claimedAt: timestampMs(\"claimed_at\"),\n deliveredAt: timestampMs(\"delivered_at\"),\n },\n (table) => [\n sqliteIndex(`${name}_due`).on(table.status, table.availableAt),\n sqliteIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\nfunction postgresOutbox(name: string) {\n const at = (column: string) => timestamp(column, { withTimezone: true });\n return pgTable(\n name,\n {\n seq: bigserial(\"seq\", { mode: \"number\" }).primaryKey(),\n id: pgText(\"id\").notNull().unique(),\n eventId: pgText(\"event_id\").notNull(),\n listener: pgText(\"listener\").notNull(),\n name: pgText(\"name\").notNull(),\n payload: jsonb(\"payload\").notNull(),\n traceId: pgText(\"trace_id\"),\n source: pgText(\"source\"),\n occurredAt: at(\"occurred_at\").notNull(),\n status: pgText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: pgInteger(\"attempts\").notNull().default(0),\n lastError: pgText(\"last_error\"),\n availableAt: at(\"available_at\").notNull(),\n claimedAt: at(\"claimed_at\"),\n deliveredAt: at(\"delivered_at\"),\n },\n (table) => [\n pgIndex(`${name}_due`).on(table.status, table.availableAt),\n pgIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\n/** The outbox table of a SQLite database. */\nexport type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;\n/** The outbox table of a Postgres database. */\nexport type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;\n/** An outbox table, made by `outboxTable`. */\nexport type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;\n\n/**\n * The outbox table: where recorded events wait, one row per listener, until they\n * are delivered. A write and the events it causes are inserted in one transaction,\n * so an event is neither lost when the process dies after the write nor sent for a\n * write that was rolled back.\n *\n * Brick does not create tables for you. Put this in the schema of the database\n * whose writes emit events, and your migration tool (such as drizzle-kit) creates\n * it. A service whose database holds the table records events; one without it does\n * not.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_outbox`.\n * @returns A Drizzle table.\n * @example\n * import { defineDatabase, outboxTable } from \"@brickkit/core\";\n *\n * export const outbox = outboxTable(\"postgres\");\n * export const database = defineDatabase({\n * engine: \"postgres\",\n * tables: { users, outbox },\n * });\n */\nexport function outboxTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteOutboxTable;\nexport function outboxTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresOutboxTable;\nexport function outboxTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): OutboxTable {\n const name = options.name ?? \"brick_outbox\";\n const table = engine === \"sqlite\" ? sqliteOutbox(name) : postgresOutbox(name);\n Object.defineProperty(table, OUTBOX, { value: { engine } });\n return table;\n}\n\n/**\n * Whether a value is an outbox table made by `outboxTable`.\n *\n * @param value - Anything.\n * @returns `true` for an outbox table, narrowing its type.\n */\nexport function isOutboxTable(value: unknown): value is OutboxTable {\n return typeof value === \"object\" && value !== null && OUTBOX in value;\n}\n\nexport type OutboxRow = OutboxTable[\"$inferSelect\"];\n\n/** The rows that record an event: one per listener, due now. */\nexport function outboxRows(\n event: Omit<EventEnvelope, \"occurredAt\"> & { occurredAt: Date },\n listeners: readonly string[],\n) {\n return listeners.map((listener) => ({\n id: deliveryId(event.id, listener),\n eventId: event.id,\n listener,\n name: event.name,\n payload: event.payload,\n traceId: event.traceId ?? null,\n source: event.source ?? null,\n occurredAt: event.occurredAt,\n status: \"pending\" as const,\n attempts: 0,\n availableAt: event.occurredAt,\n }));\n}\n\n/** The delivery a row of `outboxRows` is. */\nexport function deliveryOf(row: OutboxRow): EventDelivery {\n return {\n id: row.eventId,\n name: row.name,\n payload: row.payload,\n occurredAt: row.occurredAt.toISOString(),\n ...(row.traceId ? { traceId: row.traceId } : {}),\n ...(row.source ? { source: row.source } : {}),\n listener: row.listener,\n deliveryId: row.id,\n attempt: row.attempts,\n };\n}\n\nexport function outboxEngine(table: OutboxTable): \"sqlite\" | \"postgres\" {\n return (\n table as unknown as Record<symbol, { engine: \"sqlite\" | \"postgres\" }>\n )[OUTBOX].engine;\n}\n","import { and, asc, eq, inArray, lt, lte, or, sql } from \"drizzle-orm\";\nimport {\n deliveryOf,\n OUTBOX_STATUSES,\n outboxEngine,\n type OutboxRow,\n type OutboxStatus,\n type OutboxTable,\n} from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type { Deliverable } from \"./hub\";\nimport { ActionExecutionError } from \"../types\";\nimport type { DispatchOptions } from \"./types\";\n\nfunction resolveDispatchOptions(\n options: DispatchOptions,\n): Required<DispatchOptions> {\n return {\n timer: options.timer ?? true,\n intervalMs: options.intervalMs ?? 1_000,\n batchSize: options.batchSize ?? 50,\n maxAttempts: options.maxAttempts ?? 8,\n claimTimeoutMs: options.claimTimeoutMs ?? 60_000,\n maxBackoffMs: options.maxBackoffMs ?? 300_000,\n retainDeliveredMs: options.retainDeliveredMs ?? 86_400_000,\n };\n}\n\n/** How many outbox rows are in each state. */\nexport type OutboxCounts = Record<OutboxStatus, number>;\n\nconst PURGE_INTERVAL_MS = 60_000;\n\n/** Listeners whose `retry` threw, logged once each. */\nconst brokenRetry = new WeakSet<Deliverable>();\n\n/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as \"retry\", and is logged once. */\nfunction decideRetry(\n name: string,\n listener: Deliverable,\n error: unknown,\n): \"retry\" | \"dead\" {\n if (!listener.retry) return \"retry\";\n try {\n return listener.retry(\n error instanceof ActionExecutionError && listener.errors?.[error.code]\n ? { code: error.code, message: error.message, details: error.details }\n : {\n code: \"UNKNOWN\",\n message: error instanceof Error ? error.message : String(error),\n cause: error,\n },\n );\n } catch (thrown) {\n if (!brokenRetry.has(listener)) {\n brokenRetry.add(listener);\n console.error(\n `[Brick-TS events] Listener '${name}': its retry() threw, so the failure is retried. Later throws are not logged.`,\n thrown,\n );\n }\n return \"retry\";\n }\n}\n\nexport function backoffMs(attempt: number, maxBackoffMs: number): number {\n return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);\n}\n\n/**\n * Delivers the events recorded in one outbox table to the app's listeners.\n *\n * It claims a batch of due rows, runs each listener, and marks the row delivered.\n * A listener that throws is retried later with a growing delay, and parked as\n * dead after its attempts run out. Several dispatchers can share a table: on\n * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not\n * finished within `claimTimeoutMs` (the process died) is taken by another.\n * Delivery is at least once, so a listener should tolerate running twice for the\n * same `deliveryId`.\n */\nexport class Dispatcher {\n private readonly engine: \"sqlite\" | \"postgres\";\n private readonly options: Required<DispatchOptions>;\n private readonly inFlight = new Set<Promise<void>>();\n private timer?: ReturnType<typeof setInterval>;\n private tickQueue?: Promise<number>;\n private lastPurge = 0;\n\n constructor(\n private readonly db: any,\n private readonly table: OutboxTable,\n private readonly listeners: (name: string) => Deliverable | undefined,\n options: DispatchOptions = {},\n ) {\n this.engine = outboxEngine(table);\n this.options = resolveDispatchOptions(options);\n }\n\n /** Start looking for due deliveries on a timer. Does nothing if it already is. */\n start(): void {\n if (this.timer || !this.options.timer) return;\n this.timer = setInterval(() => void this.tick(), this.options.intervalMs);\n this.timer.unref?.();\n void this.tick();\n }\n\n /** Stop the timer and wait for the deliveries that are running to finish. */\n async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n await this.tickQueue;\n await Promise.allSettled(this.inFlight);\n }\n\n /** Look for work soon, without waiting for the timer. Safe to call often. */\n notify(): void {\n if (!this.timer) return;\n setTimeout(() => void this.tick(), 0).unref?.();\n }\n\n /** Claim what is due and run it, once. @returns How many deliveries it started. */\n private tick(): Promise<number> {\n this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(\n () => this.claimAndRun(),\n () => this.claimAndRun(),\n );\n return this.tickQueue;\n }\n\n /**\n * Deliver everything that is due now and wait until those deliveries are done.\n * Deliveries that fail and are rescheduled are not waited for again.\n *\n * @returns How many deliveries it ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (;;) {\n const started = await this.tick();\n await Promise.allSettled(this.inFlight);\n if (started === 0) return total;\n total += started;\n }\n }\n\n async counts(): Promise<OutboxCounts> {\n const t = this.table as any;\n const rows: { status: OutboxStatus; count: number }[] = await this.db\n .select({ status: t.status, count: sql<number>`count(*)` })\n .from(t)\n .groupBy(t.status);\n const counts = Object.fromEntries(\n OUTBOX_STATUSES.map((status) => [status, 0]),\n ) as OutboxCounts;\n for (const row of rows) counts[row.status] = Number(row.count);\n return counts;\n }\n\n /**\n * Put parked deliveries back in line, with their attempts reset.\n *\n * @param deliveryId - One delivery to retry. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n const t = this.table as any;\n const rows: { id: string }[] = await this.db\n .update(t)\n .set({ status: \"pending\", attempts: 0, availableAt: new Date() })\n .where(\n deliveryId\n ? and(eq(t.status, \"dead\"), eq(t.id, deliveryId))\n : eq(t.status, \"dead\"),\n )\n .returning({ id: t.id });\n if (rows.length) this.notify();\n return rows.length;\n }\n\n private async claimAndRun(): Promise<number> {\n try {\n const room = this.options.batchSize - this.inFlight.size;\n if (room <= 0) return 0;\n const rows = await this.claim(room);\n for (const row of rows) {\n const run = this.deliver(row).finally(() => {\n this.inFlight.delete(run);\n });\n this.inFlight.add(run);\n }\n await this.purgeDelivered();\n return rows.length;\n } catch (error) {\n this.logError(error);\n return 0;\n }\n }\n\n private async claim(limit: number): Promise<OutboxRow[]> {\n const t = this.table as any;\n const now = new Date();\n const stale = new Date(now.getTime() - this.options.claimTimeoutMs);\n const due = or(\n and(eq(t.status, \"pending\"), lte(t.availableAt, now)),\n and(eq(t.status, \"claimed\"), lt(t.claimedAt, stale)),\n );\n const claimIn = async (tx: any): Promise<OutboxRow[]> => {\n let select = tx\n .select()\n .from(t)\n .where(due)\n .orderBy(asc(t.seq))\n .limit(limit);\n if (this.engine === \"postgres\")\n select = select.for(\"update\", { skipLocked: true });\n const picked: OutboxRow[] = await select;\n if (!picked.length) return [];\n await tx\n .update(t)\n .set({\n status: \"claimed\",\n claimedAt: now,\n attempts: sql`${t.attempts} + 1`,\n })\n .where(\n inArray(\n t.seq,\n picked.map((row) => row.seq),\n ),\n );\n return picked.map((row) => ({ ...row, attempts: row.attempts + 1 }));\n };\n return this.engine === \"postgres\"\n ? this.db.transaction(claimIn)\n : runInTransaction(this.db, claimIn);\n }\n\n private async deliver(row: OutboxRow): Promise<void> {\n const listener = this.listeners(row.listener);\n if (!listener) {\n await this.park(row, `No listener named '${row.listener}' is registered`);\n return;\n }\n try {\n await listener.run(deliveryOf(row));\n } catch (error) {\n await this.fail(\n row,\n error,\n listener.maxAttempts ?? this.options.maxAttempts,\n decideRetry(row.listener, listener, error),\n );\n return;\n }\n await this.markDelivered(row);\n }\n\n private async markDelivered(row: OutboxRow): Promise<void> {\n const t = this.table as any;\n try {\n if (this.options.retainDeliveredMs === 0)\n await this.db.delete(t).where(eq(t.seq, row.seq));\n else\n await this.db\n .update(t)\n .set({\n status: \"delivered\",\n deliveredAt: new Date(),\n lastError: null,\n })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.logError(error);\n }\n }\n\n private async fail(\n row: OutboxRow,\n error: unknown,\n maxAttempts: number,\n decision: \"retry\" | \"dead\",\n ): Promise<void> {\n const message = error instanceof Error ? error.message : String(error);\n if (decision === \"dead\" || row.attempts >= maxAttempts) {\n await this.park(row, message);\n return;\n }\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({\n status: \"pending\",\n lastError: message,\n claimedAt: null,\n availableAt: new Date(\n Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs),\n ),\n })\n .where(eq(t.seq, row.seq));\n } catch (writeError) {\n this.logError(writeError);\n }\n }\n\n private async park(row: OutboxRow, message: string): Promise<void> {\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({ status: \"dead\", lastError: message, claimedAt: null })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.logError(error);\n }\n }\n\n private logError(error: unknown): void {\n console.error(\"[Brick-TS events]\", error);\n }\n\n private async purgeDelivered(): Promise<void> {\n const keep = this.options.retainDeliveredMs;\n const now = Date.now();\n if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;\n this.lastPurge = now;\n const t = this.table as any;\n await this.db\n .delete(t)\n .where(\n and(eq(t.status, \"delivered\"), lt(t.deliveredAt, new Date(now - keep))),\n );\n }\n}\n","/*\n * Cron expressions and intervals, without dependencies.\n *\n * A cron expression has five fields (minute hour day-of-month month\n * day-of-week) or six, with seconds first. Fields take `*`, numbers, ranges\n * (`1-5`), steps (`*\\/15`, `0-30/10`, `5/10`), lists (`1,15`) and the names\n * `jan`-`dec` and `sun`-`sat`; day-of-week 7 is Sunday too. As in Vixie cron,\n * when both day fields are restricted a day matching either one matches. The\n * macros `@yearly`, `@monthly`, `@weekly`, `@daily` and `@hourly` work too.\n *\n * Times are wall-clock times in an IANA time zone. A time that does not exist\n * (it falls in the hour a DST change skips) runs when the clocks jump, shifted\n * by the gap; a time that happens twice (the hour a DST change repeats) runs\n * once, the first time.\n */\n\n/** A parsed cron expression: the allowed values of each field. */\nexport interface CronExpression {\n readonly source: string;\n readonly seconds: ReadonlySet<number>;\n readonly minutes: ReadonlySet<number>;\n readonly hours: ReadonlySet<number>;\n readonly days: ReadonlySet<number>;\n readonly months: ReadonlySet<number>;\n /** 0 is Sunday. */\n readonly weekdays: ReadonlySet<number>;\n /** Both day fields are restricted: a day matches when either does. */\n readonly eitherDay: boolean;\n}\n\nconst MACROS: Record<string, string> = {\n \"@yearly\": \"0 0 1 1 *\",\n \"@annually\": \"0 0 1 1 *\",\n \"@monthly\": \"0 0 1 * *\",\n \"@weekly\": \"0 0 * * 0\",\n \"@daily\": \"0 0 * * *\",\n \"@midnight\": \"0 0 * * *\",\n \"@hourly\": \"0 * * * *\",\n};\n\nconst MONTH_NAMES = \"jan feb mar apr may jun jul aug sep oct nov dec\".split(\n \" \",\n);\nconst DAY_NAMES = \"sun mon tue wed thu fri sat\".split(\" \");\n\nfunction parseField(\n field: string,\n min: number,\n max: number,\n names: string[] = [],\n nameBase = 0,\n): { values: Set<number>; star: boolean } {\n const value = (text: string): number => {\n const named = names.indexOf(text.toLowerCase());\n if (named >= 0) return named + nameBase;\n if (!/^\\d+$/.test(text)) throw new Error(`'${text}' is not a number`);\n const number = Number(text);\n if (number < min || number > max)\n throw new Error(`${number} is outside ${min}-${max}`);\n return number;\n };\n const values = new Set<number>();\n for (const part of field.split(\",\")) {\n const [range, stepText, extra] = part.split(\"/\");\n if (extra !== undefined || !range)\n throw new Error(`'${part}' is not a valid field`);\n const step = stepText === undefined ? 1 : Number(stepText);\n if (!Number.isInteger(step) || step < 1)\n throw new Error(`'${stepText}' is not a valid step`);\n let from: number;\n let to: number;\n if (range === \"*\") [from, to] = [min, max];\n else if (range.includes(\"-\")) {\n const [a, b, extra] = range.split(\"-\");\n if (extra !== undefined)\n throw new Error(`'${range}' is not a valid range`);\n [from, to] = [value(a!), value(b!)];\n if (from > to) throw new Error(`'${range}' runs backwards`);\n } else {\n from = value(range);\n // `5/10` means from 5 to the end, every 10.\n to = stepText === undefined ? from : max;\n }\n for (let v = from; v <= to; v += step) values.add(v);\n }\n // As in Vixie cron, `*/2` still counts as unrestricted for the day rule.\n return { values, star: field.startsWith(\"*\") || field.startsWith(\"?\") };\n}\n\n/**\n * Parse a cron expression.\n *\n * @throws When the expression is malformed.\n */\nexport function parseCron(expression: string): CronExpression {\n const source = expression.trim();\n const fields = (MACROS[source.toLowerCase()] ?? source).split(/\\s+/);\n if (fields.length === 5) fields.unshift(\"0\");\n if (fields.length !== 6)\n throw new Error(\n `Cron expression '${expression}' needs 5 fields (minute hour day month weekday), or 6 with seconds first`,\n );\n const [sec, min, hour, day, month, weekday] = fields as [\n string,\n string,\n string,\n string,\n string,\n string,\n ];\n try {\n const days = parseField(day.replace(\"?\", \"*\"), 1, 31);\n const weekdays = parseField(weekday.replace(\"?\", \"*\"), 0, 7, DAY_NAMES);\n if (weekdays.values.delete(7)) weekdays.values.add(0);\n return {\n source,\n seconds: parseField(sec, 0, 59).values,\n minutes: parseField(min, 0, 59).values,\n hours: parseField(hour, 0, 23).values,\n days: days.values,\n months: parseField(month, 1, 12, MONTH_NAMES, 1).values,\n weekdays: weekdays.values,\n eitherDay: !days.star && !weekdays.star,\n };\n } catch (error) {\n throw new Error(\n `Cron expression '${expression}': ${(error as Error).message}`,\n );\n }\n}\n\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\n/**\n * @throws When `timeZone` is not an IANA time zone this runtime knows.\n */\nexport function checkTimeZone(timeZone: string): void {\n formatter(timeZone);\n}\n\nfunction formatter(timeZone: string): Intl.DateTimeFormat {\n let found = formatters.get(timeZone);\n if (!found) {\n try {\n found = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n });\n } catch {\n throw new Error(`Unknown time zone '${timeZone}'`);\n }\n formatters.set(timeZone, found);\n }\n return found;\n}\n\n/** The wall-clock time at `instant` in `timeZone`, as if it were UTC (whole seconds). */\nfunction wallClock(instant: number, timeZone: string): number {\n const parts: Record<string, number> = {};\n for (const part of formatter(timeZone).formatToParts(instant))\n if (part.type !== \"literal\") parts[part.type] = Number(part.value);\n return Date.UTC(\n parts.year!,\n parts.month! - 1,\n parts.day!,\n parts.hour!,\n parts.minute!,\n parts.second!,\n );\n}\n\nconst DAY_MS = 86_400_000;\n\n/** The offset of `timeZone` from UTC at `instant`, in milliseconds. */\nconst offsetAt = (instant: number, timeZone: string) =>\n wallClock(instant, timeZone) - Math.floor(instant / 1000) * 1000;\n\n/**\n * The first instant whose wall-clock time in `timeZone` is `wall`, or, when\n * a DST change skips `wall`, the instant the clocks jump past it, shifted by\n * the gap.\n */\nfunction instantOf(wall: number, timeZone: string): number {\n const before = wall - offsetAt(wall - DAY_MS, timeZone);\n const after = wall - offsetAt(wall + DAY_MS, timeZone);\n const valid = [before, after].filter(\n (instant) => wallClock(instant, timeZone) === wall,\n );\n return valid.length ? Math.min(...valid) : before;\n}\n\nfunction dayMatches(cron: CronExpression, date: Date): boolean {\n const day = cron.days.has(date.getUTCDate());\n const weekday = cron.weekdays.has(date.getUTCDay());\n return cron.eitherDay ? day || weekday : day && weekday;\n}\n\n/** The first wall-clock time at or after `wall` that the expression matches, or undefined within eight years. */\nfunction nextWall(cron: CronExpression, wall: number): number | undefined {\n const d = new Date(wall);\n const limit = d.getUTCFullYear() + 8;\n while (d.getUTCFullYear() <= limit) {\n if (!cron.months.has(d.getUTCMonth() + 1)) {\n d.setUTCMonth(d.getUTCMonth() + 1, 1);\n d.setUTCHours(0, 0, 0);\n } else if (!dayMatches(cron, d)) {\n d.setUTCDate(d.getUTCDate() + 1);\n d.setUTCHours(0, 0, 0);\n } else if (!cron.hours.has(d.getUTCHours())) {\n d.setUTCHours(d.getUTCHours() + 1, 0, 0);\n } else if (!cron.minutes.has(d.getUTCMinutes())) {\n d.setUTCMinutes(d.getUTCMinutes() + 1, 0);\n } else if (!cron.seconds.has(d.getUTCSeconds())) {\n d.setUTCSeconds(d.getUTCSeconds() + 1);\n } else return d.getTime();\n }\n return undefined;\n}\n\n/**\n * The first time after `after` that the expression fires in `timeZone`.\n *\n * @returns The instant, or `undefined` when it never fires (`0 0 31 2 *`).\n */\nexport function nextCron(\n cron: CronExpression,\n after: Date,\n timeZone = \"UTC\",\n): Date | undefined {\n const from = after.getTime();\n // Whole seconds: the next one strictly after `from`.\n let wall = wallClock(from, timeZone) + 1000;\n for (;;) {\n const found = nextWall(cron, wall);\n if (found === undefined) return undefined;\n const instant = instantOf(found, timeZone);\n // A repeated hour: its wall times already ran the first time round.\n if (instant > from) return new Date(instant);\n wall = found + 1000;\n }\n}\n\n/** A century: well inside what a `Date` can hold after any due time. */\nconst MAX_DURATION_MS = 100 * 366 * DAY_MS;\n\nconst UNITS: Record<string, number> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 3_600_000,\n d: DAY_MS,\n};\n\n/**\n * A duration in milliseconds: a number of milliseconds, or text such as\n * `\"90s\"`, `\"15m\"`, `\"6h\"`, `\"1d\"` or `\"1h30m\"`.\n *\n * @throws When it is not a positive duration (or zero, with `allowZero`), or\n * is longer than a century.\n */\nexport function parseDuration(\n duration: string | number,\n options: { allowZero?: boolean } = {},\n): number {\n let ms = 0;\n if (typeof duration === \"number\") ms = duration;\n else {\n const text = duration.replace(/\\s+/g, \"\");\n const pattern = /(\\d+(?:\\.\\d+)?)(ms|s|m|h|d)/gy;\n let match: RegExpExecArray | null;\n let read = 0;\n while ((match = pattern.exec(text))) {\n ms += Number(match[1]) * UNITS[match[2]!]!;\n read = pattern.lastIndex;\n }\n if (!text || read !== text.length) ms = NaN;\n }\n const rounded = Math.round(ms);\n if (\n !Number.isFinite(rounded) ||\n rounded < (options.allowZero ? 0 : 1) ||\n rounded > MAX_DURATION_MS\n )\n throw new Error(\n `'${duration}' is not a duration: use milliseconds or text such as \"15m\", \"6h\" or \"1h30m\"`,\n );\n return rounded;\n}\n","import {\n checkTimeZone,\n nextCron,\n parseCron,\n parseDuration,\n type CronExpression,\n} from \"./cron\";\n\n/** What a schedule's `run` receives: which run this is. */\nexport interface ScheduleRun {\n /** The schedule's name. */\n schedule: string;\n /**\n * When this run was due, as an ISO timestamp: the cron time, the end of the\n * interval, or the moment someone triggered it. Retries of a failed run keep it.\n */\n slot: string;\n /** `manual` when started with `schedules.trigger(name)` or `brick schedules run`. */\n trigger: \"schedule\" | \"manual\";\n /** 1 on the first try, 2 on the first retry, and so on. */\n attempt: number;\n /** `<schedule>:<slot>`: the same on every retry, for idempotency keys. */\n runKey: string;\n}\n\n/** What a schedule's workflow receives: the run, without `attempt` (a run starts one workflow however often it is tried). */\nexport type ScheduleWorkflowRun = Omit<ScheduleRun, \"attempt\">;\n\n/** A function marked `\"use workflow\"`, started once per run of the schedule it is given to. */\nexport type ScheduleWorkflow = (run: ScheduleWorkflowRun) => Promise<unknown>;\n\ntype When =\n | {\n /**\n * A cron expression: `\"0 2 * * *\"` is 02:00 every day. Five fields, or six\n * with seconds first; `@daily` and the other macros work too.\n */\n cron: string;\n /** The IANA time zone `cron` is read in, such as `\"Europe/Berlin\"`. Default `\"UTC\"`. */\n timeZone?: string;\n every?: never;\n }\n | {\n /**\n * Run again this long after the last successful run finished: `\"6h\"`,\n * `\"15m\"`, `\"1h30m\"`, or milliseconds. The first run is due as soon as a\n * process starts the schedules.\n */\n every: string | number;\n cron?: never;\n timeZone?: never;\n };\n\n/** What `defineSchedule` takes. */\nexport type ScheduleConfig = When & {\n /** Unique among the app's schedules, and the key its state is stored under: renaming it starts it afresh. */\n name: string;\n /**\n * A due time that passed while no process ran the schedules (or one more\n * than a minute late): `\"once\"` (the default) runs it once, however many\n * were missed; `\"skip\"` skips it and waits for the next.\n */\n catchUp?: \"once\" | \"skip\";\n /** Tries per due time, the first included. Default 3. */\n maxAttempts?: number;\n /** The wait before the first retry, doubling on each retry after it; 0 retries at once. Default `\"1m\"`. */\n backoff?: string | number;\n /** A random delay of up to this much, added to every due time, so many processes or apps do not all start at once. */\n jitter?: string | number;\n /** `false` keeps the schedule from running on its own; `trigger` still runs it. Default `true`. */\n enabled?: boolean;\n} & (\n | {\n /** Runs in the process that claims the due time. Throwing retries it. */\n run: (run: ScheduleRun) => void | Promise<void>;\n workflow?: never;\n }\n | {\n /**\n * A durable workflow started for each due time, on the app's\n * `events.world`. The run counts as done once the workflow started; the\n * workflow retries its own steps.\n */\n workflow: ScheduleWorkflow;\n run?: never;\n }\n );\n\n/** A schedule, made by `defineSchedule`. */\nexport interface Schedule {\n readonly name: string;\n readonly cron?: CronExpression;\n readonly timeZone?: string;\n /** The interval, in milliseconds. */\n readonly every?: number;\n readonly catchUp: \"once\" | \"skip\";\n readonly maxAttempts: number;\n readonly backoffMs: number;\n readonly jitterMs: number;\n readonly enabled: boolean;\n readonly run?: (run: ScheduleRun) => void | Promise<void>;\n readonly workflow?: ScheduleWorkflow;\n /** What decides the due times, as stored with them: a change makes the next one be worked out again. */\n readonly spec: string;\n}\n\n/**\n * Define a schedule: code that runs at set times, in one process among all\n * those that run the app. Pass it to `brick({ events: { schedules } })`.\n *\n * It runs either on a `cron` expression, at fixed wall-clock times in a time\n * zone, or `every` so long, counted from the end of the last successful run.\n * State lives in the app's `scheduleTable()`, so a due time runs once however\n * many processes there are, and a restart or deploy carries on where it\n * stopped. A due time counts as done only once its run succeeds: a run that\n * throws is retried with a growing delay, and one whose process died is taken\n * over by another process. A run is never started while the last one is still\n * running; due times that pass in the meantime are skipped.\n *\n * @param config - `name`, `cron` (and `timeZone`) or `every`, `run` or\n * `workflow`, and optionally `catchUp`, `maxAttempts`, `backoff`, `jitter` and\n * `enabled`.\n * @returns The schedule.\n * @throws When the name is empty or contains `:`, the cron expression or time\n * zone is invalid, or the schedule has both or neither of `cron` and `every`,\n * or of `run` and `workflow`.\n * @example\n * import { brick, defineSchedule } from \"@brickkit/core\";\n *\n * const backup = defineSchedule({\n * name: \"db-backup\",\n * cron: \"0 *\\/6 * * *\",\n * timeZone: \"Europe/Berlin\",\n * run: () => backupDatabase(),\n * });\n *\n * export default brick({ services, events: { schedules: [backup] } });\n */\nexport function defineSchedule(config: ScheduleConfig): Schedule {\n const { name } = config;\n if (typeof name !== \"string\" || !name)\n throw new Error(\"A schedule needs a name\");\n if (name.includes(\":\"))\n throw new Error(`Schedule name '${name}' must not contain ':'`);\n const fail = (message: string): never => {\n throw new Error(`Schedule '${name}': ${message}`);\n };\n const attempt = <T>(fn: () => T): T => {\n try {\n return fn();\n } catch (error) {\n return fail((error as Error).message);\n }\n };\n /** A duration that may also be 0: none. */\n const optionalDuration = (\n value: string | number | undefined,\n fallback: number,\n ) =>\n value === undefined\n ? fallback\n : attempt(() => parseDuration(value, { allowZero: true }));\n if ((config.cron === undefined) === (config.every === undefined))\n fail(\"give it a cron expression or an interval (every), not both\");\n if ((config.run === undefined) === (config.workflow === undefined))\n fail(\"give it a run handler or a workflow, not both\");\n if (config.run !== undefined && typeof config.run !== \"function\")\n fail(\"run must be a function\");\n if (config.workflow !== undefined && typeof config.workflow !== \"function\")\n fail('workflow must be a function marked \"use workflow\"');\n const maxAttempts = config.maxAttempts ?? 3;\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1)\n fail(\"maxAttempts must be a positive integer\");\n if (\n config.catchUp !== undefined &&\n ![\"once\", \"skip\"].includes(config.catchUp)\n )\n fail('catchUp must be \"once\" or \"skip\"');\n let when: Pick<Schedule, \"cron\" | \"timeZone\" | \"every\" | \"spec\">;\n if (config.cron !== undefined) {\n const timeZone = config.timeZone ?? \"UTC\";\n const cron = attempt(() => parseCron(config.cron!));\n attempt(() => checkTimeZone(timeZone));\n if (!nextCron(cron, new Date(), timeZone))\n fail(`cron expression '${config.cron}' never fires`);\n when = { cron, timeZone, spec: `cron ${cron.source} ${timeZone}` };\n } else {\n const every = attempt(() => parseDuration(config.every!));\n when = { every, spec: `every ${every}` };\n }\n return Object.freeze({\n name,\n ...when,\n catchUp: config.catchUp ?? \"once\",\n maxAttempts,\n backoffMs: optionalDuration(config.backoff, 60_000),\n jitterMs: optionalDuration(config.jitter, 0),\n enabled: config.enabled ?? true,\n ...(config.run ? { run: config.run } : {}),\n ...(config.workflow ? { workflow: config.workflow } : {}),\n });\n}\n\n/**\n * The first due time of `schedule` after `after`, before jitter: the next\n * cron time, or `after` plus the interval. `undefined` when the cron\n * expression fires no more.\n */\nexport function nextDue(schedule: Schedule, after: Date): Date | undefined {\n return schedule.cron\n ? nextCron(schedule.cron, after, schedule.timeZone)\n : new Date(after.getTime() + schedule.every!);\n}\n","import { and, eq, inArray, isNull, lt, lte, or, sql } from \"drizzle-orm\";\nimport { isSqliteDatabase } from \"../events/transaction\";\nimport { nextDue, type Schedule, type ScheduleRun } from \"./schedule\";\nimport type { ScheduleRow, ScheduleRunRecord, ScheduleTable } from \"./table\";\n\n/** A due time this late, on its first try, counts as missed for `catchUp: \"skip\"`. */\nconst MISSED_AFTER_MS = 60_000;\n/** Runs kept per schedule. */\nconst KEEP_RUNS = 20;\nconst ABANDONED = \"The process running it stopped before it finished\";\n\n/** A schedule as `schedules.list()` reports it. */\nexport interface ScheduleState {\n name: string;\n kind: \"handler\" | \"workflow\";\n cron?: string;\n timeZone?: string;\n /** The interval, in milliseconds. */\n every?: number;\n enabled: boolean;\n /** When it is next due (a retry included), as an ISO timestamp; `null` before a process first started the schedules. */\n nextRunAt: string | null;\n /** Whether a process is running it now. */\n running: boolean;\n /** Tries of the current due time so far. */\n attempts: number;\n lastSuccessAt: string | null;\n /** The last runs, newest first. */\n runs: ScheduleRunRecord[];\n}\n\nexport interface SchedulerOptions {\n /** Look for due schedules on a timer. */\n timer: boolean;\n intervalMs: number;\n /** How long a run may go without a heartbeat before another process takes it over. */\n claimTimeoutMs: number;\n}\n\n/**\n * Runs an app's schedules from one schedule table, shared by every process\n * that runs the app.\n *\n * Each schedule has one row. A process claims a due row with a conditional\n * update (due, and not held by a live claim), so one process wins each due\n * time, on Postgres and SQLite alike. While it runs, the process renews its\n * claim; a process that dies stops renewing, and after `claimTimeoutMs`\n * another process takes the due time over. On Postgres claims are timed by\n * the database's clock, so hosts whose clocks disagree still agree on them. Only success (or giving up after\n * `maxAttempts`) moves the row to the next due time.\n */\nexport class Scheduler {\n private readonly byName: Map<string, Schedule>;\n private readonly inFlight = new Map<string, Promise<void>>();\n private timer?: ReturnType<typeof setInterval>;\n private tickQueue?: Promise<number>;\n private synced?: Promise<void>;\n private readonly postgres: boolean;\n\n constructor(\n private readonly db: any,\n private readonly table: ScheduleTable,\n schedules: readonly Schedule[],\n private readonly runner: (\n schedule: Schedule,\n run: ScheduleRun,\n ) => Promise<void>,\n private readonly options: SchedulerOptions,\n ) {\n this.byName = new Map(schedules.map((s) => [s.name, s]));\n this.postgres = !isSqliteDatabase(db);\n }\n\n start(): void {\n if (this.timer || !this.options.timer) return;\n this.timer = setInterval(() => void this.tick(), this.options.intervalMs);\n this.timer.unref?.();\n void this.tick();\n }\n\n /** Stop the timer and wait for the runs in progress. */\n async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n await this.tickQueue;\n await Promise.allSettled(this.inFlight.values());\n }\n\n /**\n * Run what is due now and wait for it. Retries that are not due yet are not\n * waited for. For tests and for workers driven by hand.\n *\n * @returns How many runs it started.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (;;) {\n const started = await this.tick();\n await Promise.allSettled(this.inFlight.values());\n if (started === 0) return total;\n total += started;\n }\n }\n\n /** Every schedule with its state. */\n async list(now = new Date()): Promise<ScheduleState[]> {\n const t = this.table as any;\n const rows: ScheduleRow[] = await this.db.select().from(t);\n const byName = new Map(rows.map((row) => [row.name, row]));\n return [...this.byName.values()].map((schedule) => {\n const row = byName.get(schedule.name);\n return {\n name: schedule.name,\n kind: schedule.workflow ? \"workflow\" : \"handler\",\n ...(schedule.cron\n ? { cron: schedule.cron.source, timeZone: schedule.timeZone }\n : { every: schedule.every }),\n enabled: schedule.enabled,\n nextRunAt: row ? row.nextAt.toISOString() : null,\n running: Boolean(row?.runId && row.leaseUntil && row.leaseUntil > now),\n attempts: row?.runId ? row.attempts : (row?.attempts ?? 0),\n lastSuccessAt: row?.lastSuccessAt?.toISOString() ?? null,\n runs: row?.runs ?? [],\n };\n });\n }\n\n /**\n * Make a schedule due now, as a manual run. Whichever process runs the\n * schedules picks it up; this one at once if it does.\n *\n * @returns `false` when the schedule is running now.\n * @throws When no schedule has that name.\n */\n async trigger(name: string): Promise<boolean> {\n if (!this.byName.has(name)) throw new Error(`No schedule named '${name}'`);\n await this.sync();\n const now = new Date();\n const set = await this.reset(name, now, {\n slot: now,\n nextAt: now,\n attempts: 0,\n trigger: \"manual\",\n });\n if (!set) return false;\n if (this.timer) setTimeout(() => void this.tick(), 0).unref?.();\n return true;\n }\n\n /**\n * Set a schedule's row afresh, unless a live claim holds it. A claim whose\n * process died is recorded first, as a failed run of its own due time.\n *\n * @returns Whether the row was set.\n */\n private async reset(\n name: string,\n now: Date,\n values: Partial<ScheduleRow>,\n ): Promise<boolean> {\n const t = this.table as any;\n const [row]: ScheduleRow[] = await this.db\n .select()\n .from(t)\n .where(eq(t.name, name));\n if (!row) return false;\n const updated = await this.db\n .update(t)\n .set({\n ...values,\n runId: null,\n startedAt: null,\n leaseUntil: null,\n // Only the holder of a claim writes the runs, and this one is dead.\n ...(row.runId\n ? {\n runs: [\n this.record(row, row.startedAt!, \"failed\", ABANDONED),\n ...row.runs,\n ].slice(0, KEEP_RUNS),\n }\n : {}),\n })\n // Unless its claim is live, or another process claimed it meanwhile.\n .where(and(eq(t.name, name), this.unchanged(row.runId), this.free(now)))\n .returning({ name: t.name });\n return updated.length > 0;\n }\n\n /** Not held by a live claim. */\n private free(now: Date) {\n const t = this.table as any;\n return or(isNull(t.runId), lt(t.leaseUntil, this.clock(now)));\n }\n\n /** Still held by the claim `runId`, or by none when it is null. */\n private unchanged(runId: string | null) {\n const t = this.table as any;\n return runId ? eq(t.runId, runId) : isNull(t.runId);\n }\n\n /** Now, for claims: the database's clock on Postgres, this host's on SQLite (one host). */\n private clock(now: Date) {\n return this.postgres ? sql`now()` : now;\n }\n\n /** When a claim made or renewed now runs out. */\n private leaseFrom(now: Date) {\n const ms = this.options.claimTimeoutMs;\n return this.postgres\n ? sql`now() + make_interval(secs => ${ms / 1000})`\n : new Date(now.getTime() + ms);\n }\n\n /** A row due at the schedule's first time from now: an interval at once, a cron schedule at its next time. */\n private fresh(schedule: Schedule, now: Date) {\n const slot = schedule.cron ? nextDue(schedule, now) : now;\n return (\n slot && {\n spec: schedule.spec,\n slot,\n nextAt: this.jittered(schedule, slot),\n attempts: 0,\n trigger: \"schedule\" as const,\n }\n );\n }\n\n /**\n * Give each schedule its row, and work its next due time out again when what\n * decides it changed (an edited cron expression). Once per scheduler.\n */\n private sync(): Promise<void> {\n this.synced ??= this.writeRows().catch((error) => {\n this.synced = undefined;\n throw error;\n });\n return this.synced;\n }\n\n private async writeRows(): Promise<void> {\n const t = this.table as any;\n const now = new Date();\n for (const schedule of this.byName.values()) {\n const fresh = this.fresh(schedule, now);\n if (!fresh) continue;\n await this.db\n .insert(t)\n .values({ name: schedule.name, runs: [], ...fresh })\n .onConflictDoNothing();\n const [row]: Pick<ScheduleRow, \"spec\">[] = await this.db\n .select({ spec: t.spec })\n .from(t)\n .where(eq(t.name, schedule.name));\n if (row && row.spec !== schedule.spec)\n await this.reset(schedule.name, now, fresh);\n }\n }\n\n private tick(): Promise<number> {\n this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(\n () => this.claimAndRun(),\n () => this.claimAndRun(),\n );\n return this.tickQueue;\n }\n\n private async claimAndRun(): Promise<number> {\n try {\n await this.sync();\n const t = this.table as any;\n const now = new Date();\n const due: Pick<\n ScheduleRow,\n \"name\" | \"spec\" | \"trigger\" | \"runId\" | \"startedAt\"\n >[] = await this.db\n .select({\n name: t.name,\n spec: t.spec,\n trigger: t.trigger,\n runId: t.runId,\n startedAt: t.startedAt,\n })\n .from(t)\n .where(\n and(\n inArray(t.name, [...this.byName.keys()]),\n lte(t.nextAt, now),\n this.free(now),\n ),\n );\n let started = 0;\n for (const candidate of due) {\n const schedule = this.byName.get(candidate.name)!;\n if (this.inFlight.has(schedule.name)) continue;\n if (!schedule.enabled && candidate.trigger !== \"manual\") continue;\n // Another version of the app wrote it (a rolling deploy): this\n // process's definition decides when it is due.\n if (candidate.spec !== schedule.spec) {\n const fresh = this.fresh(schedule, now);\n if (fresh) await this.reset(schedule.name, now, fresh);\n continue;\n }\n const runId = crypto.randomUUID();\n const [row]: ScheduleRow[] = await this.db\n .update(t)\n .set({\n runId,\n startedAt: now,\n leaseUntil: this.leaseFrom(now),\n // Counted at the claim, so a try whose process dies still counts.\n attempts: sql`${t.attempts} + 1`,\n })\n .where(\n and(\n eq(t.name, schedule.name),\n lte(t.nextAt, now),\n this.free(now),\n // As read: the abandoned try recorded below is that claim's.\n this.unchanged(candidate.runId),\n ),\n )\n .returning();\n if (!row) continue; // Another process won it, or changed it.\n started++;\n const run = this.execute(\n schedule,\n row,\n candidate.runId === null ? undefined : candidate.startedAt!,\n )\n .catch((error) => this.logError(error))\n .finally(() => this.inFlight.delete(schedule.name));\n this.inFlight.set(schedule.name, run);\n }\n return started;\n } catch (error) {\n this.logError(error);\n return 0;\n }\n }\n\n private async execute(\n schedule: Schedule,\n row: ScheduleRow,\n /** When the last try started, when its process stopped before it finished. */\n abandonedAt: Date | undefined,\n ): Promise<void> {\n const runs = [...row.runs];\n const startedAt = row.startedAt!;\n const attempt = row.attempts;\n if (abandonedAt)\n runs.unshift(\n this.record(\n { ...row, attempts: attempt - 1 },\n abandonedAt,\n \"failed\",\n ABANDONED,\n ),\n );\n const now = () => new Date();\n if (\n attempt === 1 &&\n row.trigger === \"schedule\" &&\n // An overdue interval has no later time to wait for.\n schedule.cron &&\n schedule.catchUp === \"skip\" &&\n startedAt.getTime() - row.nextAt.getTime() > MISSED_AFTER_MS\n ) {\n runs.unshift(this.record(row, startedAt, \"skipped\"));\n return this.advance(schedule, row, runs, now(), false);\n }\n if (attempt > schedule.maxAttempts)\n return this.advance(schedule, row, runs, now(), false);\n const heartbeat = setInterval(\n () => void this.renew(row).catch((error) => this.logError(error)),\n Math.max(10, Math.floor(this.options.claimTimeoutMs / 3)),\n );\n heartbeat.unref?.();\n const slot = row.slot.toISOString();\n try {\n await this.runner(schedule, {\n schedule: schedule.name,\n slot,\n trigger: row.trigger,\n attempt,\n runKey: `${schedule.name}:${slot}`,\n });\n } catch (error) {\n clearInterval(heartbeat);\n const message = error instanceof Error ? error.message : String(error);\n runs.unshift(this.record(row, startedAt, \"failed\", message));\n return this.retry(schedule, row, runs, now());\n }\n clearInterval(heartbeat);\n runs.unshift(this.record(row, startedAt, \"succeeded\"));\n return this.advance(schedule, row, runs, now(), true);\n }\n\n private async renew(row: ScheduleRow): Promise<void> {\n const t = this.table as any;\n const updated = await this.db\n .update(t)\n .set({\n leaseUntil: this.leaseFrom(new Date()),\n })\n .where(and(eq(t.name, row.name), eq(t.runId, row.runId)))\n .returning({ name: t.name });\n if (!updated.length)\n console.warn(\n `[Brick-TS schedules] Schedule '${row.name}' lost its claim while running; another process may run it too.`,\n );\n }\n\n /** After a failure: try the same due time again later, unless the tries ran out or the next due time comes first. */\n private async retry(\n schedule: Schedule,\n row: ScheduleRow,\n runs: ScheduleRunRecord[],\n now: Date,\n ): Promise<void> {\n const retryAt = new Date(\n now.getTime() + schedule.backoffMs * 2 ** (row.attempts - 1),\n );\n const next = schedule.cron ? nextDue(schedule, now) : undefined;\n if (row.attempts >= schedule.maxAttempts || (next && next <= retryAt))\n return this.advance(schedule, row, runs, now, false);\n await this.release(row, { nextAt: retryAt, runs });\n }\n\n /** Done with this due time: on to the next one. */\n private async advance(\n schedule: Schedule,\n row: ScheduleRow,\n runs: ScheduleRunRecord[],\n now: Date,\n succeeded: boolean,\n ): Promise<void> {\n // Due times that passed during the run are skipped: runs never overlap.\n const slot = nextDue(schedule, now);\n await this.release(row, {\n spec: schedule.spec,\n ...(slot\n ? { slot, nextAt: this.jittered(schedule, slot) }\n : // A cron expression that fires no more: park it far ahead.\n { nextAt: new Date(8.64e15) }),\n attempts: 0,\n trigger: \"schedule\",\n runs,\n ...(succeeded ? { lastSuccessAt: now } : {}),\n });\n }\n\n private async release(\n row: ScheduleRow,\n values: Partial<ScheduleRow>,\n ): Promise<void> {\n const t = this.table as any;\n const updated = await this.db\n .update(t)\n .set({\n ...values,\n runs: values.runs?.slice(0, KEEP_RUNS),\n runId: null,\n leaseUntil: null,\n })\n .where(and(eq(t.name, row.name), eq(t.runId, row.runId)))\n .returning({ name: t.name });\n if (!updated.length)\n console.warn(\n `[Brick-TS schedules] Schedule '${row.name}': another process took the run over, so this outcome is not recorded.`,\n );\n }\n\n private record(\n row: ScheduleRow,\n startedAt: Date,\n outcome: ScheduleRunRecord[\"outcome\"],\n error?: string,\n ): ScheduleRunRecord {\n return {\n slot: row.slot.toISOString(),\n trigger: row.trigger,\n attempt: row.attempts,\n startedAt: startedAt.toISOString(),\n finishedAt: new Date().toISOString(),\n outcome,\n ...(error !== undefined ? { error } : {}),\n };\n }\n\n private jittered(schedule: Schedule, slot: Date): Date {\n return schedule.jitterMs\n ? new Date(slot.getTime() + Math.floor(Math.random() * schedule.jitterMs))\n : slot;\n }\n\n private logError(error: unknown): void {\n console.error(\"[Brick-TS schedules]\", error);\n }\n}\n","import { GLOBAL_SYMBOL } from \"../telemetry-names\";\nimport { Dispatcher, type OutboxCounts } from \"./dispatcher\";\nimport { newEventId } from \"./id\";\nimport { listenerDeps, validateListener } from \"./listener\";\nimport { outboxRows, OUTBOX_STATUSES, type OutboxTable } from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type {\n DispatchOptions,\n EventDelivery,\n EventListener,\n EventRecorder,\n EventsOptions,\n EventsWorld,\n ServiceEvents,\n} from \"./types\";\nimport { isWorkflowBundleShipped, WorkflowRuntime } from \"./workflows\";\nimport { runWithDeps } from \"../deps\";\nimport { portOf, type ServicePort } from \"../service-port\";\nimport { DuplicateNameError, type Service } from \"../types\";\nimport type { Schedule } from \"../schedules/schedule\";\nimport { Scheduler, type ScheduleState } from \"../schedules/scheduler\";\nimport type { ScheduleTable } from \"../schedules/table\";\nimport { outsideRedaction } from \"../sensitive\";\n\nexport function matchesEvent(pattern: string, name: string): boolean {\n if (pattern === \"*\") return true;\n if (pattern.endsWith(\"*\")) return name.startsWith(pattern.slice(0, -1));\n return pattern === name;\n}\n\n/** The service of each database that records events, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */\nexport const recordingServices = new WeakMap<object, ServicePort>();\n\n// Shared by name: the CLI that stops the hubs may hold another copy of this package.\nconst startedHubs = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(GLOBAL_SYMBOL.eventsStarted)\n] ??= new Set()) as Set<Pick<EventsHub, \"stop\">>;\n\n/**\n * Stop every events hub started in this process, by any copy of `@brickkit/core`,\n * and wait for their deliveries. A hub that fails to stop does not cut the wait\n * for the others: the first failure is thrown once every hub is done.\n */\nexport async function stopAllEvents(): Promise<void> {\n const results = await Promise.allSettled(\n [...startedHubs].map((hub) => hub.stop()),\n );\n const failed = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (failed) throw failed.reason;\n}\n\n/**\n * What an app's `events` option describes, as plain data. It goes in the app\n * definition, which is sent to the dev dashboard, so it holds no functions.\n */\nexport interface EventsDefinition {\n listeners: { name: string; on: string[]; kind: \"handler\" | \"workflow\" }[];\n dispatch: boolean;\n /** Names of the services whose writes record events. */\n recorders: string[];\n /** The app's schedules; absent when it has none. */\n schedules?: {\n name: string;\n kind: \"handler\" | \"workflow\";\n cron?: string;\n timeZone?: string;\n every?: number;\n enabled: boolean;\n }[];\n}\n\n/** What `app.events.schedules` offers: see and trigger the app's schedules. */\nexport interface ScheduleControl {\n /** Every schedule, with when it is next due and its last runs. */\n list(): Promise<ScheduleState[]>;\n /**\n * Run a schedule now, once, in whichever process runs the schedules. It\n * works with `enabled: false` too.\n *\n * @returns `false` when the schedule is running now, so nothing was started.\n * @throws When no schedule has that name.\n */\n trigger(name: string): Promise<boolean>;\n /** Run what is due now, and wait for it. For tests and workers driven by hand. @returns How many runs started. */\n drain(): Promise<number>;\n}\n\n/** What the dispatcher runs for a delivery. */\nexport interface Deliverable {\n readonly maxAttempts?: number;\n readonly errors?: EventListener[\"errors\"];\n readonly retry?: EventListener[\"retry\"];\n run(delivery: EventDelivery): void | Promise<void>;\n}\n\n/**\n * The events of one app: who listens, where events are recorded, and the\n * dispatchers that deliver them. `brick({ events })` makes one and puts it on\n * `app.events`.\n */\nexport class EventsHub {\n private readonly byName = new Map<string, EventListener>();\n private readonly dispatchers = new Map<OutboxTable, Dispatcher>();\n private readonly deliverables = new Map<string, Deliverable>();\n private readonly dispatchOptions: DispatchOptions | false;\n private readonly runtime: WorkflowRuntime | undefined;\n private readonly recorderNames: string[] = [];\n private readonly scheduleList: Schedule[] = [];\n private scheduler: Scheduler | undefined;\n private started = false;\n private stopping: Promise<void> | undefined;\n\n /**\n * @param options - The `events` option.\n * @param deps - The deps of the app's services, which `useDeps()` returns in\n * its listeners, schedules and workflow steps.\n */\n constructor(\n options: EventsOptions,\n private readonly deps: Record<string, unknown> = {},\n ) {\n for (const listener of options.listeners ?? []) {\n validateListener(listener);\n if (this.byName.has(listener.name))\n throw new DuplicateNameError(\n `Duplicate event listener '${listener.name}'`,\n );\n this.byName.set(listener.name, listener);\n }\n const scheduleNames = new Set<string>();\n for (const schedule of options.schedules ?? []) {\n if (scheduleNames.has(schedule.name))\n throw new DuplicateNameError(`Duplicate schedule '${schedule.name}'`);\n scheduleNames.add(schedule.name);\n this.scheduleList.push(schedule);\n }\n const workflowListeners = [\n ...this.byName.values(),\n ...this.scheduleList,\n ].filter((listener) => listener.workflow);\n if (workflowListeners.length) {\n if (!options.world)\n throw new Error(\n `${\"on\" in workflowListeners[0]! ? \"Event listener\" : \"Schedule\"} '${workflowListeners[0]!.name}' runs a workflow, so events needs a world: ` +\n \"brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.\",\n );\n this.runtime = new WorkflowRuntime(\n options.world,\n options.workflows,\n workflowListeners,\n deps,\n );\n }\n this.dispatchOptions =\n options.dispatch === false\n ? false\n : options.dispatch === true || options.dispatch === undefined\n ? {}\n : options.dispatch;\n }\n\n /**\n * Give each service whose database holds an outbox table a recorder, and a\n * dispatcher for that table. Call it before the first request: a service has no\n * recorder until then.\n *\n * @param services - The app's services.\n * @returns The hub, for chaining.\n */\n attach(services: readonly Service<any, any>[]): this {\n for (const service of services.map(portOf)) {\n const table = service.getOutbox();\n if (!table) continue;\n this.recorderNames.push(service.name);\n service.setRecorder(\n this.bind(table, (name, payload) => service.checkEvent(name, payload)),\n );\n const db = service.getDb();\n if (db && typeof db === \"object\") recordingServices.set(db, service);\n if (!this.dispatchers.has(table))\n this.dispatchers.set(\n table,\n new Dispatcher(\n db,\n table,\n (name) => this.deliverable(name),\n this.dispatchOptions || {},\n ),\n );\n }\n if (this.scheduleList.length) this.attachSchedules(services);\n if (this.recorderNames.length === 0 && this.byName.size > 0) {\n console.warn(\n \"[Brick-TS] events are configured, but no service database has an outbox table. \" +\n \"Add outboxTable() to a database's tables so its writes can record events.\",\n );\n }\n return this;\n }\n\n matching(name: string): EventListener[] {\n const found: EventListener[] = [];\n for (const listener of this.byName.values())\n if (listener.on.some((pattern) => matchesEvent(pattern, name)))\n found.push(listener);\n return found;\n }\n\n describe(): EventsDefinition {\n return {\n listeners: [...this.byName.values()].map((listener) => ({\n name: listener.name,\n on: [...listener.on],\n kind: listener.workflow ? (\"workflow\" as const) : (\"handler\" as const),\n })),\n dispatch: this.dispatchOptions !== false,\n recorders: [...this.recorderNames],\n ...(this.scheduleList.length\n ? {\n schedules: this.scheduleList.map((schedule) => ({\n name: schedule.name,\n kind: schedule.workflow\n ? (\"workflow\" as const)\n : (\"handler\" as const),\n ...(schedule.cron\n ? { cron: schedule.cron.source, timeZone: schedule.timeZone }\n : { every: schedule.every }),\n enabled: schedule.enabled,\n })),\n }\n : {}),\n };\n }\n\n /** The app's schedules, when it has any. Running them follows `start()` and `stop()`. */\n get schedules(): ScheduleControl | undefined {\n const scheduler = this.scheduler;\n return (\n scheduler && {\n list: () => scheduler.list(),\n trigger: (name) => scheduler.trigger(name),\n drain: () => scheduler.drain(),\n }\n );\n }\n\n /**\n * Find the one schedule table among the services' databases.\n *\n * @throws When none holds one, or more than one does: a schedule must have\n * one place where its state lives.\n */\n private attachSchedules(services: readonly Service<any, any>[]): void {\n const found = new Map<ScheduleTable, unknown>();\n for (const service of services.map(portOf)) {\n const table = service.getScheduleTable();\n if (table && !found.has(table)) found.set(table, service.getDb());\n }\n if (found.size !== 1)\n throw new Error(\n found.size\n ? \"Brick: schedules need exactly one scheduleTable(), but several databases hold one.\"\n : \"Brick: schedules keep their state in a scheduleTable(), and no service database holds one. Add scheduleTable() to a database's tables.\",\n );\n const [[table, db]] = [...found];\n const options = this.dispatchOptions || {};\n this.scheduler = new Scheduler(\n db,\n table,\n this.scheduleList,\n (schedule, run) =>\n schedule.workflow\n ? this.runtime!.startScheduled(schedule, run)\n : runWithDeps(this.deps, async () => schedule.run!(run)),\n {\n timer: options.timer ?? true,\n intervalMs: options.intervalMs ?? 1_000,\n claimTimeoutMs: options.claimTimeoutMs ?? 60_000,\n },\n );\n }\n\n /**\n * Where the workflow bundle is read from, the project it is built from, and\n * the world the workflows run on. Only set when a listener runs a workflow.\n * The CLI builds the bundle there before events start, and shows the world's\n * runs in the dev dashboard. `shipped`: a compiled server reads the bundle\n * `brick build` shipped beside it, so there is nothing to build.\n */\n get workflows():\n | { root: string; dir: string; world: EventsWorld; shipped: boolean }\n | undefined {\n return (\n this.runtime && {\n root: this.runtime.root,\n dir: this.runtime.dir,\n world: this.runtime.world,\n shipped: isWorkflowBundleShipped(),\n }\n );\n }\n\n /**\n * Resume the workflow that waits on a webhook. The server mounts this on the\n * route the Workflow SDK puts in webhook URLs.\n */\n webhook(request: Request): Promise<Response> {\n if (!this.runtime)\n throw new Error(\"No listener of this app runs a workflow\");\n return this.runtime.handleWebhook(request);\n }\n\n /**\n * Start delivering recorded events from this process, and start the world that\n * runs workflow listeners. Does nothing if this process only records events\n * (`dispatch: false`), already started, or a stop is still waiting.\n */\n start(): void {\n // A process being stopped exits when the stop is done, and would drop what\n // this start claims. A startup that finishes late, or a commit, lands here.\n if (this.dispatchOptions === false || this.started || this.stopping) return;\n this.started = true;\n startedHubs.add(this);\n this.runtime?.warmUp();\n for (const dispatcher of this.dispatchers.values()) dispatcher.start();\n this.scheduler?.start();\n }\n\n /**\n * Stop delivering, wait for the deliveries that are running, and close the\n * world. A world cannot be started again, so workflow listeners stop for good.\n * A stop that arrives while another runs waits for that one.\n */\n stop(): Promise<void> {\n return (this.stopping ??= this.shutDown().finally(() => {\n // Removed only when done, so a stop-all waits for a stop already running.\n this.stopping = undefined;\n startedHubs.delete(this);\n }));\n }\n\n private async shutDown(): Promise<void> {\n this.started = false;\n await Promise.all([\n ...[...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()),\n this.scheduler?.stop(),\n ]);\n await this.runtime?.close();\n }\n\n /**\n * Deliver everything that is due now and wait for it. For tests and for\n * workers that drive delivery themselves.\n *\n * @returns How many deliveries ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.drain();\n return total;\n }\n\n /** How many rows are in each state, across the app's outbox tables. */\n async counts(): Promise<OutboxCounts> {\n const total = Object.fromEntries(\n OUTBOX_STATUSES.map((status) => [status, 0]),\n ) as OutboxCounts;\n for (const dispatcher of this.dispatchers.values()) {\n const counts = await dispatcher.counts();\n for (const status of OUTBOX_STATUSES) total[status] += counts[status];\n }\n return total;\n }\n\n /**\n * Put parked deliveries back in line.\n *\n * @param deliveryId - One delivery. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.retryDead(deliveryId);\n return total;\n }\n\n private deliverable(name: string): Deliverable | undefined {\n const listener = this.byName.get(name);\n if (!listener) return undefined;\n let found = this.deliverables.get(name);\n if (!found) {\n const { run, workflow, maxAttempts, errors, retry } = listener;\n const deps = listenerDeps(listener) ?? this.deps;\n found = {\n ...(errors ? { errors } : {}),\n ...(retry ? { retry } : {}),\n ...(maxAttempts !== undefined ? { maxAttempts } : {}),\n run: workflow\n ? (delivery) => this.runtime!.startRun(listener, delivery)\n : (delivery) => runWithDeps(deps, () => run!(delivery)),\n };\n this.deliverables.set(name, found);\n }\n return found;\n }\n\n private bind(\n table: OutboxTable,\n check: (name: string, payload: unknown) => void,\n ): ServiceEvents {\n const startAndNotify = () =>\n outsideRedaction(() => {\n this.start();\n this.dispatchers.get(table)?.notify();\n });\n const insert = async (\n tx: any,\n context: { traceId?: string; source?: string },\n name: string,\n payload: unknown,\n ): Promise<boolean> => {\n check(name, payload);\n const listeners = this.matching(name);\n if (!listeners.length) return false;\n await tx.insert(table as any).values(\n outboxRows(\n {\n id: newEventId(),\n name,\n payload,\n occurredAt: new Date(),\n ...context,\n },\n listeners.map((listener) => listener.name),\n ),\n );\n return true;\n };\n return {\n wants: (name) => this.matching(name).length > 0,\n transaction: async (db, context, fn) => {\n let recorded = false;\n const result = await runInTransaction(db, async (tx) => {\n const record: EventRecorder = async (name, payload) => {\n if (await insert(tx, context, name, payload)) recorded = true;\n };\n return fn(tx, record);\n });\n if (recorded) startAndNotify();\n return result;\n },\n record: async (tx, context, name, payload) => {\n await insert(tx, context, name, payload);\n },\n };\n }\n}\n","/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */\nexport function publicOrigin(request: Request): string {\n // Browsers cannot set X-Forwarded-* on a WebSocket handshake, so a cross-site page cannot forge a match.\n const forwarded = (name: string) =>\n request.headers.get(name)?.split(\",\")[0]?.trim() || undefined;\n const url = new URL(request.url);\n const proto = forwarded(\"x-forwarded-proto\");\n return `${proto ? `${proto}:` : url.protocol}//${forwarded(\"x-forwarded-host\") ?? url.host}`;\n}\n\n/**\n * Which origins may call the app: an exact origin (`\"https://app.example.com\"`),\n * a list of them, or a predicate. `true` allows only the app's own origin.\n */\nexport type CorsOrigin =\n | true\n | string\n | readonly string[]\n | ((origin: string, request: Request) => boolean);\n\n/** `brick({ cors })`: an origin rule, or the rule plus `credentials`. */\nexport type CorsOptions =\n | CorsOrigin\n | {\n /** Default `true`: the app's own origin only. */\n origin?: CorsOrigin;\n /** Send `Access-Control-Allow-Credentials: true` to allowed origins (cookies, auth headers). */\n credentials?: boolean;\n };\n\nconst METHODS = \"GET, POST, PUT, PATCH, DELETE\";\n\n/**\n * A request hook that adds CORS headers for allowed origins and answers\n * preflights. An origin that doesn't match gets no `Access-Control-Allow-Origin`,\n * so the browser blocks it; origins are compared exactly and never reflected\n * unless the rule allows them.\n */\nexport function corsHook(cors: CorsOptions) {\n const { origin = true, credentials = false } =\n typeof cors === \"object\" && !Array.isArray(cors)\n ? (cors as Exclude<CorsOptions, CorsOrigin>)\n : { origin: cors as CorsOrigin };\n const list =\n typeof origin === \"string\"\n ? [origin]\n : Array.isArray(origin)\n ? (origin as readonly string[])\n : undefined;\n if (list?.includes(\"*\"))\n throw new Error(\n 'Brick: cors origin \"*\" is not supported. List the origins, or pass a predicate.',\n );\n const allows = (from: string, request: Request) =>\n origin === true\n ? from === publicOrigin(request)\n : typeof origin === \"function\"\n ? origin(from, request) === true\n : list!.includes(from);\n\n return ({\n request,\n set,\n }: {\n request: Request;\n set: { headers: Record<string, unknown> };\n }) => {\n const from = request.headers.get(\"origin\");\n if (from === null) return;\n const headers: Record<string, string> = { vary: \"Origin\" };\n if (allows(from, request)) {\n headers[\"access-control-allow-origin\"] = from;\n if (credentials) headers[\"access-control-allow-credentials\"] = \"true\";\n headers[\"access-control-expose-headers\"] = \"Retry-After\";\n }\n const preflight =\n request.method === \"OPTIONS\" &&\n request.headers.has(\"access-control-request-method\");\n if (!preflight) {\n Object.assign(set.headers, headers);\n return;\n }\n if (headers[\"access-control-allow-origin\"]) {\n headers[\"access-control-allow-methods\"] = METHODS;\n const requested = request.headers.get(\"access-control-request-headers\");\n if (requested) headers[\"access-control-allow-headers\"] = requested;\n }\n return new Response(null, { status: 204, headers });\n };\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { Elysia } from \"elysia\";\nimport { websocket } from \"elysia/websocket\";\nimport { createLogger } from \"./logger\";\nimport { kebabCase } from \"./kebab\";\nimport { joinRoute, ownerPath } from \"./routes\";\nimport { buildErrorHelpers } from \"./action\";\nimport {\n ActionExecutionError,\n type ActionErrorDefinition,\n type BaseContext,\n} from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { inTransaction, onTransactionCommit } from \"./events/transaction\";\nimport { serializeSocketSchema } from \"./socket-schema\";\nimport {\n byteLength,\n encodeFrame,\n isControlEvent,\n isSocketEnvelope,\n isSocketRoom,\n isSocketSeq,\n replayFrame,\n replayHeadroom,\n signSeq,\n splitSeq,\n SOCKET_BUFFER_BYTES,\n SOCKET_BUFFER_MESSAGES,\n STANDARD_ERRORS,\n SOCKET_CLOSE,\n SOCKET_CONTROL,\n SOCKET_MAX_BYTES,\n SOCKET_PROTOCOL,\n SOCKET_SIGNATURE_LENGTH,\n SOCKET_TOKEN_PROTOCOL,\n} from \"./protocol\";\nimport { publicOrigin } from \"./cors\";\nimport { sensitivePointer } from \"./sensitive\";\nimport type {\n BrickSocketConfig,\n BrickSocketSender,\n SocketBroker,\n SocketBrokerMessage,\n SocketEmitArgs,\n SocketPayloads,\n SocketSchemas,\n RegisteredSocket,\n SocketSender,\n SocketSession,\n} from \"./socket-types\";\n\nexport type { RegisteredSocket };\n\nclass SocketDenied extends Error {}\n\n/** Validates and serializes one output message, rechecking what survives JSON. */\nfunction outputFrame(\n output: SocketSchemas,\n event: string,\n data: unknown,\n): string {\n const schema = Object.hasOwn(output, event) ? output[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new Error(\"Invalid socket output\");\n const frame = encodeFrame(event, data);\n if (byteLength(frame) > SOCKET_MAX_BYTES)\n throw new Error(\"Socket output too large\");\n if (!getCompiledCheck(schema).Check(JSON.parse(frame).data))\n throw new Error(\"Socket output is not JSON-compatible\");\n return frame;\n}\n\n/** Delivers within this process. The default broker of every app. */\nexport function localBroker(): SocketBroker {\n const topics = new Map<string, Set<(message: SocketBrokerMessage) => void>>();\n // Replay history: one rising counter per process, prefixed with its start so a restart reads as a gap.\n const epoch = Date.now();\n let counter = 0;\n /** Rooms dropped from `kept` once idle, at counter values up to this. */\n let swept = 0;\n const kept = new Map<\n string,\n {\n entries: { n: number; at: number; message: SocketBrokerMessage }[];\n /** The highest n no longer kept. */\n trimmed: number;\n maxAgeMs: number;\n }\n >();\n const prune = (names: Iterable<string>) => {\n for (const topic of names) {\n const room = kept.get(topic);\n if (!room) continue;\n const oldest = Date.now() - room.maxAgeMs;\n while (room.entries[0] && room.entries[0].at < oldest)\n room.trimmed = room.entries.shift()!.n;\n if (!room.entries.length) {\n kept.delete(topic);\n swept = counter;\n }\n }\n };\n return {\n publish(message, replay) {\n if (message.type === \"emit\" && replay) {\n const n = ++counter;\n message = { ...message, seq: `${epoch}-${n}` };\n const room = kept.get(message.topic) ?? {\n entries: [],\n trimmed: 0,\n maxAgeMs: replay.maxAgeMs,\n };\n kept.set(message.topic, room);\n room.entries.push({ n, at: Date.now(), message });\n if (room.entries.length > replay.keep)\n room.trimmed = room.entries.shift()!.n;\n // shortcut: idle rooms are swept every 1000 emits, not on a timer; fine while emits keep coming.\n if (n % 1000 === 0) prune([...kept.keys()]);\n }\n for (const deliver of topics.get(message.topic) ?? []) deliver(message);\n },\n head: () => `${epoch}-${counter}`,\n history(topic, since) {\n const [from, n] = since.split(\"-\").map(Number) as [number, number];\n if (from !== epoch || n > counter) return undefined;\n prune([topic]);\n const room = kept.get(topic);\n if (!room) return n >= swept ? [] : undefined;\n if (n < room.trimmed) return undefined;\n return room.entries\n .filter((entry) => entry.n > n)\n .map((entry) => entry.message);\n },\n subscribe(topic, deliver) {\n const listeners = topics.get(topic) ?? new Set();\n listeners.add(deliver);\n topics.set(topic, listeners);\n return () => {\n listeners.delete(deliver);\n if (!listeners.size) topics.delete(topic);\n };\n },\n };\n}\n\nexport function defineServiceSocket<\n I extends SocketSchemas,\n O extends SocketSchemas,\n Ctx extends BaseContext,\n E extends Record<string, ActionErrorDefinition> = {},\n>(\n service: string,\n config: BrickSocketConfig<I, O, Ctx, E>,\n resolve: (request: Request) => Promise<Ctx>,\n): RegisteredSocket {\n if (\n !config.name ||\n config.name.split(\".\").some((part) => !/^[a-zA-Z_][\\w-]*$/.test(part))\n )\n throw new Error(\"Invalid socket name\");\n if (\n config.path !== undefined &&\n (!config.path.startsWith(\"/\") ||\n /[?#*]/.test(config.path) ||\n config.path.split(\"/\").some((segment) => segment.startsWith(\":\")))\n )\n throw new Error(\n \"Socket path must be a static route (relative to its service) without a query or fragment\",\n );\n const input = Object.freeze({ ...config.input });\n const output = Object.freeze({ ...config.output });\n const handlers = { ...config.handlers };\n if (\n Object.keys(input).length !== Object.keys(handlers).length ||\n Object.keys(input).some(\n (key) =>\n !Object.hasOwn(handlers, key) || typeof handlers[key] !== \"function\",\n )\n )\n throw new Error(\"Every socket input event needs exactly one handler\");\n if ([...Object.keys(input), ...Object.keys(output)].some(isControlEvent))\n throw new Error(\"Socket event names starting with $ are reserved\");\n const maxRooms = config.maxRooms ?? 100;\n if (!Number.isInteger(maxRooms) || maxRooms < 1)\n throw new Error(\"Socket maxRooms must be a positive integer\");\n const replay = config.replay && { ...config.replay };\n if (\n replay &&\n !(\n Number.isInteger(replay.keep) &&\n replay.keep > 0 &&\n replay.maxAgeMs > 0 &&\n Number.isFinite(replay.maxAgeMs)\n )\n )\n throw new Error(\n \"Socket replay needs a positive integer keep and a positive finite maxAgeMs\",\n );\n for (const [path, schema] of [\n ...Object.entries(input).map(([k, v]) => [`input.${k}`, v] as const),\n ...Object.entries(output).map(([k, v]) => [`output.${k}`, v] as const),\n ]) {\n serializeSocketSchema(schema, path);\n getCompiledCheck(schema);\n const at = sensitivePointer(schema);\n if (at)\n throw new Error(\n `Service '${service}' socket '${config.name}': ${path} marks '${at}' t.Sensitive, which sockets do not support yet; keep the secret out of socket messages`,\n );\n }\n const typed = (socket: SocketSender): BrickSocketSender<SocketPayloads<O>> =>\n socket;\n const error = buildErrorHelpers(config.errors);\n const context = async (request: Request) => {\n const ctx = await resolve(request);\n if (config.authorize && !(await config.authorize({ ctx })))\n throw new SocketDenied();\n return ctx;\n };\n const topicPrefix = `${service}.${config.name}:`;\n const topic = (room: string) => {\n if (!isSocketRoom(room)) throw new Error(`Invalid socket room: ${room}`);\n return topicPrefix + room;\n };\n const brokers = new Set<SocketBroker>();\n const publish = (messages: SocketBrokerMessage[], after: unknown) => {\n const send = () => {\n for (const broker of brokers)\n for (const message of messages) broker.publish(message, replay);\n };\n if (after === undefined) return send();\n if (!inTransaction(after))\n throw new Error(\n \"Socket emit { after: tx } needs a tx from runInTransaction(db, (tx) => ...); a plain db.transaction() is not tracked, so the emit could be sent for a write that rolls back\",\n );\n void onTransactionCommit(after, send);\n };\n return {\n schema: {\n name: config.name,\n path: config.path,\n description: config.description,\n input: Object.keys(input),\n output: Object.keys(output),\n hasAuthorize: !!config.authorize,\n },\n input,\n output,\n ...(config.errors ? { errors: { ...config.errors } } : {}),\n allowedOrigins: config.allowedOrigins\n ? [...config.allowedOrigins]\n : undefined,\n allowMissingOrigin: config.allowMissingOrigin,\n maxRooms,\n replay,\n brokers,\n topicPrefix,\n topic,\n handle: {\n name: config.name,\n emit(rooms, ...[event, payload, options]: SocketEmitArgs<any>) {\n const unique = [\n ...new Set(typeof rooms === \"string\" ? [rooms] : rooms),\n ];\n const topics = unique.map(topic);\n const frame = outputFrame(output, event, payload);\n // Room and sequence are added to each replayed frame on delivery.\n if (\n replay &&\n unique.some(\n (room) =>\n byteLength(frame) + replayHeadroom(room) > SOCKET_MAX_BYTES,\n )\n )\n throw new Error(\"Socket output too large\");\n publish(\n topics.map((topic) => ({ type: \"emit\", topic, frame })),\n options?.after,\n );\n },\n kick(room, options = {}) {\n publish(\n [\n {\n type: \"kick\",\n topic: topic(room),\n ...(options.also !== undefined\n ? { also: topic(options.also) }\n : {}),\n ...(options.reason !== undefined\n ? { reason: String(options.reason) }\n : {}),\n },\n ],\n undefined,\n );\n },\n },\n async connect(request) {\n const initial = await context(request);\n const rooms = [\n ...new Set(config.rooms ? await config.rooms({ ctx: initial }) : []),\n ];\n rooms.forEach(topic);\n if (rooms.length > maxRooms) throw new Error(\"Too many socket rooms\");\n return {\n rooms,\n async open(socket) {\n await config.open?.({ ctx: initial, socket: typed(socket) });\n },\n async message(event, data, socket) {\n const schema = Object.hasOwn(input, event) ? input[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new SocketDenied();\n const ctx = await context(request);\n if (!socket.isOpen) return;\n // The schema and event were checked together before dispatch.\n const handler = handlers[event as keyof I];\n await handler({\n input: data as SocketPayloads<I>[keyof I],\n ctx,\n socket: typed(socket),\n error,\n });\n },\n async join(room) {\n const ctx = await context(request);\n return !!config.join && (await config.join({ ctx, room }));\n },\n async close(socket, code, reason) {\n await config.close?.({\n ctx: initial,\n socket: typed(socket),\n code,\n reason,\n });\n },\n };\n },\n };\n}\n\n/** `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */\nexport function socketPath(\n prefix: string,\n service: string,\n socket: RegisteredSocket,\n): string {\n return joinRoute(\n ownerPath(prefix, service),\n socket.schema.path ?? `/${kebabCase(socket.schema.name)}`,\n );\n}\n\nconst protocols = (request: Request) =>\n (request.headers.get(\"sec-websocket-protocol\") ?? \"\")\n .split(\",\")\n .map((protocol) => protocol.trim())\n .filter(Boolean);\n\n/** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */\nfunction tokenRequest(request: Request): {\n token: boolean;\n request: Request;\n} {\n const offered = protocols(request);\n const token = offered\n .find((protocol) => protocol.startsWith(SOCKET_TOKEN_PROTOCOL))\n ?.slice(SOCKET_TOKEN_PROTOCOL.length);\n if (!token) return { token: false, request };\n const headers = new Headers(request.headers);\n headers.set(\"authorization\", `Bearer ${token}`);\n const rest = offered.filter(\n (protocol) => !protocol.startsWith(SOCKET_TOKEN_PROTOCOL),\n );\n if (rest.length) headers.set(\"sec-websocket-protocol\", rest.join(\", \"));\n else headers.delete(\"sec-websocket-protocol\");\n return {\n token: true,\n request: new Request(request.url, { method: request.method, headers }),\n };\n}\n\n/** Each connection owns its queue and service session. */\nexport function mountSockets(\n app: Elysia,\n sockets: { service: string; path: string; definition: RegisteredSocket }[],\n broker: SocketBroker,\n secret?: string,\n): void {\n if (secret === \"\") throw new Error(\"Brick: sockets.secret can't be empty\");\n // A sequence is signed for its room, so a client resumes only a room it was sent that sequence in.\n const key = secret ?? randomBytes(32);\n const signature = (topic: string, seq: string) =>\n createHmac(\"sha256\", key)\n .update(`${topic}\\n${seq}`)\n .digest(\"base64url\")\n .slice(0, SOCKET_SIGNATURE_LENGTH);\n const sign = (topic: string, seq: string) =>\n signSeq(seq, signature(topic, seq));\n const verify = (topic: string, signed: string) => {\n const [seq, sig] = splitSeq(signed);\n return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq)))\n ? seq\n : undefined;\n };\n if (\n sockets.some(({ definition }) => definition.replay) &&\n !(broker.head && broker.history)\n )\n throw new Error(\"Brick: the socket broker does not support replay\");\n for (const { definition } of sockets) definition.brokers.add(broker);\n app.onStop(async () => {\n for (const { definition } of sockets) definition.brokers.delete(broker);\n await broker.close?.();\n });\n if (!sockets.length) return;\n app.use(\n websocket({\n maxPayloadLength: SOCKET_MAX_BYTES,\n backpressureLimit: SOCKET_BUFFER_BYTES,\n closeOnBackpressureLimit: true,\n }),\n );\n for (const { service, path, definition } of sockets) {\n const logger = createLogger(\n `[Brick socket ${service}.${definition.schema.name}]`,\n );\n const sessions = new WeakMap<Request, SocketSession>();\n type Peer = {\n request: Request;\n send(data: string): number;\n close(code?: number, reason?: string): void;\n subscribe(topic: string): void;\n unsubscribe(topic: string): void;\n isSubscribed(topic: string): boolean;\n readonly readyState: number;\n };\n type Connection = {\n ws: Peer;\n session: SocketSession;\n sender: SocketSender;\n tail: Promise<void>;\n pending: number;\n bytes: number;\n closed: boolean;\n /** Every room topic the connection is in. */\n rooms: Set<string>;\n /** The topics the client joined, which it may leave. */\n requested: Set<string>;\n };\n const connections = new WeakMap<Request, Connection>();\n const roomOf = (topic: string) =>\n topic.slice(definition.topicPrefix.length);\n const holders = new Map<\n string,\n { connections: Set<Connection>; unsubscribe: () => void }\n >();\n const control = (ws: Peer, event: string, data: unknown) => {\n if (ws.readyState === 1) ws.send(encodeFrame(event, data));\n };\n /** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */\n const enter = async (\n connection: Connection,\n topic: string,\n live = true,\n ) => {\n if (connection.rooms.has(topic)) return;\n connection.rooms.add(topic);\n if (live) connection.ws.subscribe(topic);\n let holder = holders.get(topic);\n if (!holder) {\n holder = {\n connections: new Set(),\n unsubscribe: () => {},\n };\n holders.set(topic, holder);\n holder.unsubscribe = broker.subscribe(topic, deliver);\n }\n holder.connections.add(connection);\n await broker.ready?.(topic).catch(() => {});\n };\n const exit = (connection: Connection, topic: string) => {\n if (!connection.rooms.delete(topic)) return;\n connection.requested.delete(topic);\n if (connection.ws.readyState === 1) connection.ws.unsubscribe(topic);\n const holder = holders.get(topic);\n if (!holder?.connections.delete(connection) || holder.connections.size)\n return;\n holders.delete(topic);\n holder.unsubscribe();\n };\n const frameOf = (message: SocketBrokerMessage & { type: \"emit\" }) =>\n message.seq === undefined\n ? message.frame\n : replayFrame(\n message.frame,\n roomOf(message.topic),\n sign(message.topic, message.seq),\n );\n const deliver = (message: SocketBrokerMessage) => {\n if (message.type === \"emit\") {\n app.server?.publish(message.topic, frameOf(message));\n return;\n }\n for (const connection of holders.get(message.topic)?.connections ?? []) {\n if (message.also && !connection.ws.isSubscribed(message.also)) continue;\n exit(connection, message.topic);\n control(connection.ws, SOCKET_CONTROL.left, {\n room: roomOf(message.topic),\n ...(message.reason !== undefined ? { reason: message.reason } : {}),\n });\n }\n };\n /** `$join` and `$leave`, acknowledged with the same event. */\n const room = async (\n connection: Connection,\n event: string,\n data: unknown,\n ) => {\n const fields = (data && typeof data === \"object\" ? data : {}) as Record<\n string,\n unknown\n >;\n const { room: name, since } = fields;\n if (!isSocketRoom(name) || (since !== undefined && !isSocketSeq(since)))\n throw new SocketDenied();\n const topic = definition.topic(name);\n if (event === SOCKET_CONTROL.leave) {\n if (connection.requested.has(topic)) exit(connection, topic);\n control(connection.ws, SOCKET_CONTROL.leave, { room: name });\n return;\n }\n const isOpen = () => !connection.closed && connection.ws.readyState === 1;\n const ok =\n connection.rooms.has(topic) ||\n (connection.rooms.size < definition.maxRooms &&\n (await connection.session.join(name)));\n if (!isOpen()) return;\n const replay = definition.replay;\n let seq: string | undefined;\n if (ok && !connection.rooms.has(topic)) {\n const entered = enter(connection, topic, !replay);\n connection.requested.add(topic);\n await entered;\n if (replay && connection.rooms.has(topic)) {\n // Held in this process before reading history, so later emits are either in it or arrive live.\n // A since not signed for this room gets no history, only $gap.\n const start =\n since === undefined\n ? await broker.head!(topic)\n : verify(topic, since);\n const missed =\n start === undefined\n ? undefined\n : await broker.history!(topic, start, replay);\n const restart = missed ? undefined : await broker.head!(topic);\n if (!isOpen()) return;\n if (connection.rooms.has(topic)) {\n connection.ws.subscribe(topic);\n if (since === undefined) seq = sign(topic, start!);\n for (const message of missed ?? [])\n if (message.type === \"emit\") connection.ws.send(frameOf(message));\n if (restart !== undefined)\n control(connection.ws, SOCKET_CONTROL.gap, {\n room: name,\n seq: sign(topic, restart),\n });\n }\n }\n }\n // A kick while joining wins.\n control(connection.ws, SOCKET_CONTROL.join, {\n room: name,\n ok: ok && connection.rooms.has(topic),\n ...(seq !== undefined ? { seq } : {}),\n });\n };\n // The codes a handler can raise with `error.CODE()`: declared plus standard.\n const raisable = { ...STANDARD_ERRORS, ...definition.errors };\n const fail = (ws: Peer, error: unknown) => {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n if (ws.readyState !== 1) return;\n ws.close(\n error instanceof SocketDenied\n ? SOCKET_CLOSE.policy\n : SOCKET_CLOSE.serverError,\n error instanceof SocketDenied\n ? \"Message refused\"\n : \"Socket handler failed\",\n );\n };\n app.ws(path, {\n async beforeHandle({ request }) {\n if (sessions.has(request)) return;\n const { token, request: resolved } = tokenRequest(request);\n const origin = request.headers.get(\"origin\");\n if (\n origin\n ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(\n origin,\n )\n : // Without cookies a missing Origin is no hijacking risk.\n !(definition.allowMissingOrigin ?? token)\n )\n return new Response(\"Socket origin refused\", { status: 403 });\n try {\n sessions.set(request, await definition.connect(resolved));\n } catch (error) {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n return new Response(\"Socket connection refused\", {\n status: error instanceof SocketDenied ? 403 : 500,\n });\n }\n },\n upgrade: ({ request }: { request: Request }) =>\n protocols(request).includes(SOCKET_PROTOCOL)\n ? { \"Sec-WebSocket-Protocol\": SOCKET_PROTOCOL }\n : undefined,\n async open(ws) {\n const session = sessions.get(ws.request);\n if (!session) {\n ws.close(SOCKET_CLOSE.serverError, \"Missing socket session\");\n return;\n }\n const sender: SocketSender = {\n get isOpen() {\n return !state.closed && ws.readyState === 1;\n },\n close() {\n ws.close(SOCKET_CLOSE.normal, \"\");\n },\n send(event, data) {\n if (!sender.isOpen) throw new Error(\"Socket is closed\");\n const result = ws.send(outputFrame(definition.output, event, data));\n if (result === 0) {\n ws.close(SOCKET_CLOSE.tryAgainLater, \"Socket buffer full\");\n throw new Error(\"Socket buffer full\");\n }\n },\n };\n const state: Connection = {\n ws,\n session,\n sender,\n tail: Promise.resolve(),\n pending: 0,\n bytes: 0,\n closed: false,\n rooms: new Set(),\n requested: new Set(),\n };\n connections.set(ws.request, state);\n try {\n await Promise.all(\n session.rooms.map((room) => enter(state, definition.topic(room))),\n );\n await session.open(sender);\n } catch (error) {\n fail(ws, error);\n }\n },\n message(ws, value: unknown) {\n const state = connections.get(ws.request);\n if (!state || state.closed || ws.readyState !== 1) return;\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n ws.close(SOCKET_CLOSE.unsupportedData, \"Only JSON text is supported\");\n return;\n }\n if (typeof value === \"string\") {\n ws.close(SOCKET_CLOSE.invalidPayload, \"Expected JSON envelope\");\n return;\n }\n if (!isSocketEnvelope(value)) {\n ws.close(SOCKET_CLOSE.policy, \"Invalid socket envelope\");\n return;\n }\n const size = byteLength(JSON.stringify(value));\n if (size > SOCKET_MAX_BYTES) {\n ws.close(SOCKET_CLOSE.tooLarge, \"Message too large\");\n return;\n }\n if (\n state.pending >= SOCKET_BUFFER_MESSAGES ||\n state.bytes + size > SOCKET_BUFFER_BYTES\n ) {\n ws.close(SOCKET_CLOSE.tryAgainLater, \"Socket queue full\");\n return;\n }\n state.pending++;\n state.bytes += size;\n state.tail = state.tail\n .then(async () => {\n if (state.closed || ws.readyState !== 1) return;\n if (\n value.event === SOCKET_CONTROL.join ||\n value.event === SOCKET_CONTROL.leave\n )\n await room(state, value.event, value.data);\n else\n await state.session.message(\n value.event,\n value.data,\n state.sender,\n );\n })\n .catch((error: unknown) => {\n // A declared error answers a handler message; the connection stays\n // open. A failed $join or $leave, or an error with an undeclared\n // code (from a nested action, say), is logged and closes it, which\n // also rejects the client's pending joins.\n if (\n error instanceof ActionExecutionError &&\n !state.closed &&\n value.event !== SOCKET_CONTROL.join &&\n value.event !== SOCKET_CONTROL.leave &&\n Object.hasOwn(raisable, error.code)\n )\n try {\n const frame = encodeFrame(SOCKET_CONTROL.error, {\n event: value.event,\n ...error.toJSON(),\n });\n if (byteLength(frame) > SOCKET_MAX_BYTES)\n throw new Error(\"Socket error too large\", { cause: error });\n if (ws.readyState === 1) ws.send(frame);\n return;\n } catch (unsent) {\n return fail(ws, unsent);\n }\n fail(ws, error);\n })\n .finally(() => {\n state.pending--;\n state.bytes -= size;\n });\n // Brick owns the queue. Returning the tail here makes native close wait on application work.\n },\n async close(ws, code = 1006, reason = \"\") {\n const state = connections.get(ws.request);\n sessions.delete(ws.request);\n if (!state || state.closed) return;\n state.closed = true;\n for (const topic of state.rooms) exit(state, topic);\n try {\n await state.session.close(state.sender, code, reason);\n } catch (error) {\n logger.error({\n error,\n service,\n socket: definition.schema.name,\n phase: \"cleanup\",\n });\n }\n connections.delete(ws.request);\n },\n });\n }\n}\n","import { ATTR, SPAN } from \"./telemetry-names\";\nimport type { HttpMethod } from \"./http\";\nimport { Elysia } from \"elysia\";\nimport {\n compileBrickApplication,\n type CompiledApplication,\n type RouteIR,\n} from \"./compiler\";\nimport { DuplicateNameError, type Service, type Tool } from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getPluginEndpoints, installedPlugins } from \"./plugin\";\nimport { pluginDepsOf, pluginLifecycle, setupAppPlugins } from \"./plugin-app\";\nimport type { PluginInstance } from \"./define-plugin\";\nimport { OPENAPI_DEFAULTS, generateOpenApiSpec } from \"./openapi\";\nimport { resolveSecrets, type SecretSource } from \"./secrets\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n type ApiDocument,\n type DocumentationOptions,\n type OpenApiDocument,\n type ReferenceOptions,\n} from \"./docs\";\nimport {\n DASHBOARD_MCP_ROUTE,\n DASHBOARD_MCP_TOOLS,\n normalizeDashboard,\n type DashboardOptions,\n} from \"./dashboard\";\nimport {\n createMcpHandler,\n createMcpRegistry,\n type McpRegistry,\n type McpToolDefinition,\n} from \"./mcp\";\nimport { dashboardMcpCaller, markDashboardArrival } from \"./dashboard-identity\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\nimport {\n instrumentDatabase,\n instrumentFetch,\n traceHttpRequest,\n withSpan,\n} from \"./telemetry\";\nimport { EventsHub } from \"./events/hub\";\nimport { appDeps } from \"./deps\";\nimport { WEBHOOK_ROUTE } from \"./events/workflows\";\nimport type { EventsOptions } from \"./events/types\";\nimport { localBroker, mountSockets, socketPath } from \"./socket\";\nimport { DEFAULT_PREFIX, routeKey } from \"./routes\";\nimport type { SocketBroker } from \"./socket-types\";\nimport { corsHook, type CorsOptions } from \"./cors\";\nimport { useStorages } from \"./storage\";\nimport {\n checkFileStorages,\n LOCAL_FILES_ROUTE,\n localFileDirs,\n localFilesRoute,\n} from \"./file-storage\";\nimport { portOf } from \"./service-port\";\nimport { bodyLimitParser, rawBodyParser } from \"./compiler/runtime\";\nimport { markAddressSource, type ClientIp } from \"./rate-limit\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Run the plugins' preparations (such as CRUD's prepared queries) at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n /**\n * `true` serves a Scalar page at /reference. Options serve one only with a\n * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.\n */\n reference?: boolean | ReferenceOptions; // default false\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (plain routes, not actions), mounted at startup. */\n endpoints?: EndpointDefinition[];\n /**\n * Record request, action, and RPC spans with OpenTelemetry (default false).\n * Spans go to the globally registered tracer provider; without one they are\n * no-ops. `brick dev` shows them in its dashboard.\n */\n telemetry?: boolean;\n /**\n * Developer documentation for the `brick dev` dashboard (its Docs tab): a\n * folder of `.md`/`.mdx` pages in Fumadocs' layout, with frontmatter and\n * `meta.json` for ordering. A string is the folder. Relative paths start at\n * the folder of the app entry, as they read in the file that sets them (from\n * `src/app.ts`, `\"../docs\"` is `docs/` at the project root). Needs\n * `fumadocs-core` and `@mdx-js/mdx` installed.\n */\n documentation?: string | DocumentationOptions;\n /**\n * Monitoring dashboard for `brick start`, on a port of its own and behind\n * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.\n */\n dashboard?: DashboardOptions;\n /**\n * Record events in the same database transaction as the writes that cause them,\n * and deliver them to listeners after the commit. Generated CRUD writes emit\n * `<resource>.create`, `<resource>.update` and `<resource>.delete`. A service\n * records events once its database holds an `outboxTable()`. Reads emit nothing,\n * and an app without this option behaves exactly as before. See `EventsOptions`.\n */\n events?: EventsOptions;\n /**\n * Socket fan-out. `broker` carries emits and kicks between processes\n * (default: this process only). See `redisBroker`. The app closes it on stop.\n * `secret` signs replay sequences; give every process the same one so a\n * client can resume on any of them (default: random per process).\n */\n sockets?: { broker?: SocketBroker; secret?: string };\n /**\n * App-wide plugins from `definePlugin`, in install order: their `app` part\n * adds start/stop lifecycle, middleware and listeners. Plugins installed with\n * `service.use()` or `resource.use()` take part too, before these.\n */\n plugins?: readonly PluginInstance<any, any>[];\n /**\n * CORS for browser callers on other origins. `true` allows the app's own\n * origin; a string, list or predicate names the allowed origins, compared\n * exactly. `{ origin, credentials }` adds `credentials: true` for cookies.\n * Other origins get no `Access-Control-Allow-Origin`. Preflights are answered.\n */\n cors?: false | CorsOptions;\n /**\n * Where the client address is, for `rateLimit: { per: \"ip\" }`. By default it\n * is the socket peer; behind a proxy, read the header your proxy sets. Brick\n * never reads `X-Forwarded-For` or any other header itself.\n *\n * @example\n * clientIp: ({ request, peer }) => request.headers.get(\"fly-client-ip\") ?? peer,\n */\n clientIp?: ClientIp;\n}\n\n/**\n * Create the HTTP application: an Elysia app that serves every service's\n * actions (and the tools that opt in with `http: true`) as routes, with\n * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,\n * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.\n *\n * Services come from the global registry unless `services` is given. The app\n * does not listen by itself: export it from your entry file, where `brick dev`,\n * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your\n * own server bootstrap.\n *\n * @param options - `prefix` for action routes (default `/api`), `services`,\n * `title`, `version`, and `description` for the OpenAPI document, `docs` and the\n * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,\n * `telemetry`, `documentation`, and `dashboard`. See `CreateServerOptions`.\n * @returns The app, with `definition` (its services, prefix, and routes),\n * `endpoint()` to add raw routes, and `listEndpoints()` to list them.\n * @throws When a required secret is missing, `documentation` or `dashboard`\n * is invalid, or `deps` is passed (it moved to `defineService({ deps })`).\n * @example\n * import { brick } from \"@brickkit/core\";\n * import { pagesService } from \"./services/pages\";\n *\n * export default brick({\n * services: [pagesService],\n * title: \"Pages API\",\n * telemetry: true,\n * });\n */\nexport function brick(options: CreateServerOptions = {}): BrickApp {\n if (\"deps\" in options)\n throw new Error(\n \"Brick: brick({ deps }) was removed in 0.16. Move each value into the service that uses it: defineService(name, { deps: { ... } }).\",\n );\n const prefix =\n options.prefix ?? options.compilation?.ir.prefix ?? DEFAULT_PREFIX;\n const title = options.title ?? OPENAPI_DEFAULTS.title;\n const version = options.version ?? OPENAPI_DEFAULTS.version;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? OPENAPI_DEFAULTS.path;\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n const dashboard = normalizeDashboard(options.dashboard);\n // The dashboard shows what is traced, so having one means tracing.\n const telemetry = options.telemetry === true || dashboard !== undefined;\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n const plugins = setupAppPlugins(\n services.flatMap((service) => installedPlugins(service)),\n options.plugins ?? [],\n );\n const addressSource = {\n clientIp: options.clientIp,\n server: () => app.server,\n };\n // CORS first, so preflights are answered and its headers reach responses\n // from middleware, which skips the later lifecycle hooks.\n app.onRequest(({ request }) => {\n markDashboardArrival(request);\n markAddressSource(request, addressSource);\n });\n if (options.cors) app.onRequest(corsHook(options.cors));\n for (const handler of plugins.middleware) app.onRequest(handler);\n\n // Mounted and registered in one call, so actions and sockets can't shadow them.\n const registeredRoutes = new Map<string, boolean>();\n const webhookRoutes = new Map<string, string>();\n const builtIn = (path: string, handler: any) => {\n app.get(path, handler);\n registeredRoutes.set(routeKey(\"GET\", path), false);\n };\n\n builtIn(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false)\n app.use(\n requestLoggingPlugin(requestLogging === true ? {} : requestLogging),\n );\n\n // Scalar API reference page (opt-in): `reference: true`, or options with a path.\n const reference = options.reference ?? false;\n const referenceOptions: ReferenceOptions =\n typeof reference === \"object\" ? reference : {};\n const referencePath =\n reference === true ? \"/reference\" : referenceOptions.path;\n if (referencePath !== undefined) {\n builtIn(\n referencePath,\n htmlResponse(\n scalarDocsHTML(\n referenceOptions.specUrl ?? openApiPath,\n referenceOptions.title ?? title,\n ),\n ),\n );\n }\n\n const byName = new Map<string, unknown>();\n for (const service of services) {\n if ((byName.get(service.name) ?? service) !== service)\n throw new DuplicateNameError(\n `Brick: duplicate service \"${service.name}\" in brick()`,\n );\n byName.set(service.name, service);\n }\n const eventsOptions = plugins.listeners.length\n ? {\n ...options.events,\n listeners: [...(options.events?.listeners ?? []), ...plugins.listeners],\n }\n : options.events;\n const events = eventsOptions\n ? new EventsHub(eventsOptions, appDeps(services)).attach(services)\n : undefined;\n if (events?.workflows)\n app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));\n if (telemetry) {\n for (const service of services) instrumentDatabase(service.getDb());\n instrumentFetch();\n }\n\n // Close declarations before anything reads them.\n for (const service of services) service.build();\n for (const service of services)\n checkFileStorages(service, [\n portOf(service).deps,\n ...installedPlugins(service).map(pluginDepsOf),\n ]);\n const localDirs = localFileDirs([\n ...services.map((service) => portOf(service).deps),\n ...plugins.deps,\n ]);\n if (localDirs.size) builtIn(LOCAL_FILES_ROUTE, localFilesRoute(localDirs));\n\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n const paths = { ...spec.paths };\n for (const [path, operations] of Object.entries(\n endpointPaths(endpointDefs),\n ))\n paths[path] = { ...paths[path], ...operations };\n return { ...spec, paths };\n };\n\n if (enableDocs) {\n builtIn(\n openApiPath,\n cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n ),\n );\n builtIn(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n builtIn(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n }\n // Built from `definition`, below.\n builtIn(\"/_brick/services\", (context: any) => architecture(context));\n\n const dashboardTools: Tool<any, any, any, any>[] = [];\n const dashboardToolService = new Map<string, string>();\n for (const service of services)\n for (const tool of service.listTools()) {\n if (tool.config.dashboard !== true) continue;\n if ((DASHBOARD_MCP_TOOLS as readonly string[]).includes(tool.name))\n throw new DuplicateNameError(\n `Brick: the tool '${tool.name}' is marked dashboard: true, but the dashboard's MCP endpoint has a tool of that name. Rename yours.`,\n );\n const other = dashboardToolService.get(tool.name);\n if (other !== undefined)\n throw new DuplicateNameError(\n `Brick: the services '${other}' and '${service.name}' both have a tool '${tool.name}' marked dashboard: true. The dashboard's MCP endpoint needs one name per tool, so rename one of them.`,\n );\n dashboardToolService.set(tool.name, service.name);\n dashboardTools.push(tool);\n }\n const toolRegistry = createMcpRegistry({ tools: dashboardTools });\n const readsOnly = (tool: McpToolDefinition) =>\n tool.annotations.readOnlyHint === true;\n const forCaller = (write: boolean): McpRegistry => ({\n listTools: () =>\n toolRegistry.listTools().filter((tool) => write || readsOnly(tool)),\n callTool(name, args, ctx) {\n const tool = toolRegistry.listTools().find((item) => item.name === name);\n if (tool && !write && !readsOnly(tool))\n throw new Error(\n `${name} can change data, so only a signed-in user may call it: dashboard.auth.authorize must return { user }. A token, or authorize returning true, can only read.`,\n );\n return toolRegistry.callTool(name, args, ctx);\n },\n });\n const mcpHandlers = [false, true].map((write) =>\n createMcpHandler({\n registry: forCaller(write),\n serverInfo: { name: title, version },\n }),\n );\n app.post(DASHBOARD_MCP_ROUTE, ({ request }) => {\n const caller = dashboardMcpCaller(request);\n return caller\n ? mcpHandlers[caller.write ? 1 : 0]!(request, {\n dashboard: caller.user ? { user: caller.user } : {},\n })\n : new Response(\"Unauthorized\", { status: 401 });\n });\n registeredRoutes.set(routeKey(\"POST\", DASHBOARD_MCP_ROUTE), false);\n\n const sockets = services.flatMap((service) =>\n service.listSockets().map((definition) => ({\n service: service.name,\n path: socketPath(prefix, service.name, definition),\n definition,\n })),\n );\n const socketRoutes = new Set<string>();\n for (const socket of sockets) {\n const key = routeKey(\"GET\", socket.path);\n if (registeredRoutes.has(key) || socketRoutes.has(key))\n throw new DuplicateNameError(\n `Brick: duplicate socket route '${socket.path}'`,\n );\n socketRoutes.add(key);\n }\n const mountRoute = (\n method: HttpMethod,\n path: string,\n handler: any,\n plugin = false,\n hook?: object,\n webhook?: string,\n ) => {\n const key = routeKey(method, path);\n if (socketRoutes.has(key))\n throw new DuplicateNameError(\n `Brick: route '${method} ${path}' conflicts with a socket`,\n );\n if (registeredRoutes.has(key)) {\n const other = webhook ?? webhookRoutes.get(key);\n if (other)\n throw new DuplicateNameError(\n `Brick: route '${method} ${path}' is claimed by webhook '${other}' and by another route; a webhook cannot share its route`,\n );\n if (plugin || registeredRoutes.get(key))\n throw new DuplicateNameError(\n `Brick: duplicate plugin route '${method} ${path}'`,\n );\n return false;\n }\n if (hook) app.route(method, path, hook, handler);\n else app.route(method, path, handler);\n registeredRoutes.set(key, plugin);\n if (webhook) webhookRoutes.set(key, webhook);\n return true;\n };\n\n const mountEndpoint = (def: EndpointDefinition, plugin = false) => {\n const handler = createEndpointHandler(def, services);\n mountRoute(\n def.method,\n def.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, def.method, def.path, () =>\n handler(context),\n )\n : handler,\n plugin,\n );\n endpointDefs.push(def);\n endpointRevision++;\n };\n\n for (const service of services) {\n for (const def of getPluginEndpoints(service, prefix))\n mountEndpoint(def, true);\n }\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n brickApp.openApiDocument = buildSpec;\n brickApp.referenceDocuments = async () => {\n const documents: ApiDocument[] = enableDocs\n ? [{ title, document: buildSpec() as unknown as OpenApiDocument }]\n : [];\n for (const extra of referenceOptions.documents ?? []) {\n try {\n const document =\n typeof extra.document === \"function\"\n ? await extra.document()\n : extra.document;\n documents.push({ title: extra.title, document });\n } catch (error) {\n console.warn(\n `[Brick-TS] Skipping the \"${extra.title}\" API document: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return documents;\n };\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n const mountedRoutes: RouteIR[] = [];\n for (const route of compilation.routes) {\n const { handler } = route;\n const invoke = (context: any) => {\n const result = telemetry\n ? withSpan(\n `${SPAN.actionPrefix}${route.ir.service}.${route.ir.action}`,\n {\n [ATTR.service]: route.ir.service,\n [ATTR.action]: route.ir.action,\n },\n () => handler(context),\n )\n : handler(context);\n return result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ? Promise.resolve(result).then(jsonActionResult)\n : jsonActionResult(result);\n };\n const mounted = mountRoute(\n route.ir.method,\n route.ir.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, route.ir.method, route.ir.path, () =>\n invoke(context),\n )\n : invoke,\n Boolean(route.ir.plugin),\n route.ir.kind === \"webhook\"\n ? { parse: rawBodyParser(route.ir.bodyLimit!) }\n : route.ir.bodyLimit\n ? { parse: bodyLimitParser(route.ir.bodyLimit) }\n : undefined,\n route.ir.kind === \"webhook\"\n ? `${route.ir.service}.${route.ir.action}`\n : undefined,\n );\n if (mounted) mountedRoutes.push(route.ir);\n }\n\n mountSockets(\n app,\n sockets,\n options.sockets?.broker ?? localBroker(),\n options.sockets?.secret,\n );\n const definition = Object.freeze({\n services: Object.freeze([...services]),\n prefix,\n routes: Object.freeze(mountedRoutes),\n sockets: Object.freeze(\n sockets.map(({ service, path, definition }) => ({\n ...definition.schema,\n service,\n path,\n })),\n ),\n telemetry,\n documentation: normalizeDocumentation(options.documentation),\n dashboard,\n ...(events ? { events: events.describe() } : {}),\n plugins: Object.freeze(plugins.plugins),\n });\n Object.defineProperty(brickApp, \"definition\", { value: definition });\n Object.defineProperty(brickApp, \"events\", { value: events });\n // Plugin lifecycle: start before serving, stop after the server stops.\n const lifecycle = pluginLifecycle(plugins.lifecycles);\n const releaseStorages = useStorages([\n ...services.map((service) => portOf(service).deps),\n ...plugins.deps,\n ]);\n const listen = app.listen.bind(app);\n const stop = app.stop.bind(app);\n Object.defineProperty(brickApp, \"start\", { value: lifecycle.start });\n // One rule with serve(): an app whose plugins fail to start does not serve.\n // listen() is synchronous, so it stops the server it already opened.\n brickApp.listen = ((...args: Parameters<typeof listen>) => {\n lifecycle.start().catch((error) => {\n console.error(\"[Brick-TS] A plugin failed to start:\", error);\n return Promise.resolve(stop(true))\n .finally(releaseStorages)\n .catch((stopError) =>\n console.error(\n \"[Brick-TS] Stopping after a failed plugin start failed:\",\n stopError,\n ),\n );\n });\n return listen(...args);\n }) as typeof brickApp.listen;\n brickApp.stop = (async (closeActiveConnections?: boolean) => {\n try {\n await stop(closeActiveConnections);\n } finally {\n try {\n await lifecycle.stop();\n } finally {\n await releaseStorages();\n }\n }\n }) as typeof brickApp.stop;\n Object.defineProperty(brickApp, \"serve\", {\n value: async ({ port }: { port: number }) => {\n await lifecycle.start();\n listen(port);\n events?.start();\n return brickApp;\n },\n });\n Object.defineProperty(brickApp, \"shutdown\", {\n value: async (closeActiveConnections?: boolean) => {\n await events?.stop();\n await brickApp.stop(closeActiveConnections);\n },\n });\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n const architecture = cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(definition),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n );\n\n return brickApp;\n}\n\nfunction normalizeDocumentation(\n documentation: string | DocumentationOptions | undefined,\n): DocumentationOptions | undefined {\n if (documentation === undefined) return undefined;\n const options =\n typeof documentation === \"string\" ? { dir: documentation } : documentation;\n if (typeof options.dir !== \"string\" || options.dir === \"\")\n throw new Error(\"Brick: documentation needs a folder, such as './docs'.\");\n return Object.freeze({\n dir: options.dir,\n ...(options.components ? { components: options.components } : {}),\n });\n}\n\nfunction jsonActionResult(value: unknown): unknown {\n return value === null\n ? new Response(\"null\", { headers: { \"content-type\": \"application/json\" } })\n : value;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;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A2B,EACxD,CAAC;AACH;;AAGA,SAAS,gBACP,OACA,UACA;CACA,IAAI,CAAC,OAAO,WAAW,SAAS;CAChC,IAAI,OAAO,KAAK,UAAU,MAAM,CAAC;CACjC,QAAQ,EAAE,UAAyD;EACjE,MAAM,CAAC,cAAc,kBAAkB,SAAS;EAChD,IAAI,iBAAiB,SAAS,mBAAmB,SAAS;GACxD,OAAO,KAAK,UAAU,MAAM,CAAC;GAC7B,QAAQ;GACR,UAAU;EACZ;EACA,IAAI,QAAQ,kBAAkB;EAC9B,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"server.js","names":["warned","TypeBox","mac","sqliteInteger","sqliteText","pgText","sqliteInteger","sqliteText","sqliteIndex","pgText","pgInteger","pgIndex"],"sources":["../../src/plugin-types.ts","../../src/sensitive.ts","../../src/telemetry.ts","../../src/error-response.ts","../../src/typebox.ts","../../src/logger.ts","../../src/dashboard-identity.ts","../../src/identity.ts","../../src/service-port.ts","../../src/deps.ts","../../src/definition-site.ts","../../src/secrets.ts","../../src/file-storage.ts","../../src/socket-redis.ts","../../src/storage.ts","../../src/rate-limit.ts","../../src/context.ts","../../src/webhook.ts","../../src/events/transaction.ts","../../src/audit.ts","../../src/compiler/runtime.ts","../../src/action.ts","../../src/http.ts","../../src/plugin.ts","../../src/plugin-app.ts","../../src/compiler/ir.ts","../../src/action-handler.ts","../../src/app-entry.ts","../../src/events/catalog.ts","../../src/events/listener.ts","../../src/events/workflows.ts","../../src/compiler.ts","../../src/registry.ts","../../src/access.ts","../../src/openapi.ts","../../src/request-logger.ts","../../src/docs.ts","../../src/dashboard.ts","../../src/mcp.ts","../../src/endpoints.ts","../../src/events/id.ts","../../src/events/outbox.ts","../../src/events/dispatcher.ts","../../src/schedules/cron.ts","../../src/schedules/schedule.ts","../../src/schedules/scheduler.ts","../../src/events/hub.ts","../../src/cors.ts","../../src/socket.ts","../../src/server.ts"],"sourcesContent":["import type { HttpMethod } from \"./http\";\nimport type { TSchema } from \"@sinclair/typebox\";\nimport type { PluginInstance } from \"./define-plugin\";\nimport type { PluginActionChecks } from \"./action-meta\";\nimport type {\n Action,\n ActionConfigWithAuthorize,\n ActionConfigWithoutAuthorize,\n ActionContext,\n ActionErrorDefinition,\n BaseContext,\n Resource,\n Service,\n} from \"./types\";\n\nexport type PluginRouteMethod = HttpMethod;\n/** Where a plugin route mounts: under the app prefix, its service, or its resource. */\nexport const PLUGIN_ROUTE_SCOPES = [\"app\", \"service\", \"resource\"] as const;\nexport type PluginRouteScope = (typeof PLUGIN_ROUTE_SCOPES)[number];\nexport type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =\n | false\n | Readonly<Record<string, false | { path?: string; scope?: S }>>;\n\nexport type ContextOf<S> =\n S extends Service<infer D, infer C> ? BaseContext<D> & C : never;\n\nexport interface PluginEndpointContext<\n C extends ActionContext = ActionContext,\n> {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n set: { status?: number; headers: Record<string, string> };\n ctx: C;\n}\n\nexport interface PluginRouteRegistrar<\n C extends ActionContext = ActionContext,\n S extends PluginRouteScope = PluginRouteScope,\n> {\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<I, O, E, C> &\n PluginActionChecks & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<I, O, E, C> &\n PluginActionChecks & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n endpoint(config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n }): void;\n /**\n * Reserve a URL segment under the resource, so no resource action takes it,\n * for a route the plugin may add later. Resource-scoped routes claim their\n * first segment themselves.\n */\n claim(segment: string): void;\n}\n\nexport interface ServicePluginContext<\n S extends Service<any, any> = Service<any, any>,\n> {\n service: S;\n routes: PluginRouteRegistrar<ContextOf<S>, \"app\" | \"service\">;\n}\nexport interface ResourcePluginContext<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n> {\n service: S;\n resource: R;\n routes: PluginRouteRegistrar<ContextOf<S>>;\n}\n\n/** Plugins may specialize their returned API for the installation host. */\nexport interface ResourcePluginTypes {\n readonly table: unknown;\n readonly context: unknown;\n readonly resource: unknown;\n readonly api: object;\n}\nexport type ResourcePluginAPI<P, T, C, R = unknown> = P extends {\n readonly types: infer H extends ResourcePluginTypes;\n}\n ? (H & {\n readonly table: T;\n readonly context: C;\n readonly resource: R;\n })[\"api\"]\n : P extends PluginInstance<infer A extends object, any>\n ? A\n : P extends ResourcePlugin<any, any, infer A>\n ? A\n : never;\n\n/** Which host a plugin descriptor installs on. Process-global, so descriptors survive a second core copy. */\nexport const PLUGIN_KIND: unique symbol = Symbol.for(\"brickkit.plugin.kind\");\n/**\n * The setup context's slot where a `definePlugin` setup hands over what to do\n * once its install succeeds; a failed install drops it.\n */\nexport const PLUGIN_COMMIT: unique symbol = Symbol.for(\n \"brickkit.plugin.commit\",\n);\nexport interface ServicePlugin<S extends Service<any, any>, A> {\n readonly [PLUGIN_KIND]: \"service\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes<\"app\" | \"service\">;\n readonly setup: (context: ServicePluginContext<S>) => A;\n}\nexport interface ResourcePlugin<\n S extends Service<any, any>,\n R extends Resource<any, any, any>,\n A extends object,\n> {\n readonly [PLUGIN_KIND]: \"resource\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes;\n readonly setup: (context: ResourcePluginContext<S, R>) => A;\n}\n\n/** A plugin as `app.definition.plugins` lists it. */\nexport interface InstalledPlugin {\n readonly name: string;\n readonly brick?: string;\n readonly scope: \"app\" | \"service\" | \"resource\";\n readonly service?: string;\n readonly resource?: string;\n /** The plugin's dashboard extension, an absolute path. */\n readonly dashboard?: string;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { inspect } from \"node:util\";\nimport type { TSchema } from \"@sinclair/typebox\";\n\nconst SENSITIVE = Symbol.for(\"brickkit.sensitive\");\n\n/** The schema, unchanged in type and validation, marked sensitive. */\nexport function Sensitive<T extends TSchema>(schema: T): T {\n return { ...schema, [SENSITIVE]: true };\n}\n\nexport const isSensitive = (schema: any): boolean =>\n schema?.[SENSITIVE] === true;\n\ntype Segment = string | null | { except: string[] };\n\ninterface SensitivePath {\n segments: Segment[];\n optional: boolean;\n}\n\ninterface Analysis {\n paths: SensitivePath[];\n publics: { segments: Segment[]; required: boolean }[];\n ref?: string;\n hidden?: string;\n}\n\ninterface Walk extends Analysis {\n markedIds: Set<string>;\n loops: Map<string, string>;\n external?: string;\n}\n\nconst analyses = new WeakMap<object, Analysis>();\n\nfunction analyze(schema: unknown): Analysis {\n if (!schema || typeof schema !== \"object\") return { paths: [], publics: [] };\n let analysis = analyses.get(schema);\n if (!analysis) {\n const walk: Walk = {\n paths: [],\n publics: [],\n markedIds: new Set(),\n loops: new Map(),\n };\n collect(schema, [], false, [], walk);\n analysis = {\n paths: walk.paths,\n publics: walk.publics,\n hidden: walk.hidden,\n };\n if (walk.paths.length || walk.hidden)\n analysis.ref =\n walk.external ??\n [...walk.markedIds].map((id) => walk.loops.get(id)).find(Boolean);\n analyses.set(schema, analysis);\n }\n return analysis;\n}\n\nexport function sensitivePaths(schema: unknown): SensitivePath[] {\n return analyze(schema).paths;\n}\n\nconst holdsMark = (node: unknown, seen = new Set<unknown>()): boolean => {\n if (!node || typeof node !== \"object\" || seen.has(node)) return false;\n seen.add(node);\n return (\n isSensitive(node) ||\n Object.values(node).some((child) => holdsMark(child, seen))\n );\n};\n\nfunction collect(\n schema: any,\n segments: Segment[],\n optional: boolean,\n ids: string[],\n walk: Walk,\n): void {\n if (!schema || typeof schema !== \"object\") return;\n if (isSensitive(schema)) {\n walk.paths.push({ segments, optional });\n for (const id of ids) walk.markedIds.add(id);\n return;\n }\n if (typeof schema.$ref === \"string\") {\n if (!ids.includes(schema.$ref)) walk.external ??= pointer(segments);\n else if (!walk.loops.has(schema.$ref))\n walk.loops.set(schema.$ref, pointer(segments));\n }\n if (typeof schema.$id === \"string\") ids = [...ids, schema.$id];\n const list = schema.type === \"array\" && !Array.isArray(schema.items);\n for (const key of Object.keys(schema))\n if (\n !WALKED.has(key) ||\n (key === \"items\" && !list && !Array.isArray(schema.items))\n )\n if (holdsMark(schema[key])) walk.hidden ??= pointer([...segments, key]);\n const branchesSharingOnePath = [\n ...(schema.anyOf ?? []),\n ...(schema.allOf ?? []),\n ...(schema.oneOf ?? []),\n ];\n for (const branch of branchesSharingOnePath)\n collect(branch, segments, optional, ids, walk);\n const declared = Object.keys(schema.properties ?? {});\n const required = new Set<string>(schema.required ?? []);\n const removable = !(\n schema.minProperties >\n declared.filter(\n (key) => required.has(key) && !isSensitive(schema.properties[key]),\n ).length\n );\n for (const key of declared) {\n const child = schema.properties[key];\n if (!isSensitive(child))\n walk.publics.push({\n segments: [...segments, key],\n required: required.has(key),\n });\n collect(\n child,\n [...segments, key],\n removable && !required.has(key),\n ids,\n walk,\n );\n }\n for (const child of Object.values(schema.patternProperties ?? {}))\n collect(child, [...segments, null], removable, ids, walk);\n if (\n schema.additionalProperties &&\n typeof schema.additionalProperties === \"object\"\n )\n collect(\n schema.additionalProperties,\n [...segments, declared.length ? { except: declared } : null],\n removable,\n ids,\n walk,\n );\n const before = walk.paths.length;\n const items: [unknown, Segment][] = Array.isArray(schema.items)\n ? schema.items.map((child: unknown, index: number) => [\n child,\n String(index),\n ])\n : list\n ? [[schema.items, null]]\n : [];\n for (const [child, segment] of items) {\n if (!isSensitive(child))\n walk.publics.push({ segments: [...segments, segment], required: true });\n collect(child, [...segments, segment], false, ids, walk);\n }\n if (schema.uniqueItems)\n for (const path of walk.paths.slice(before)) path.optional = false;\n}\n\nconst WALKED = new Set([\n \"anyOf\",\n \"allOf\",\n \"oneOf\",\n \"properties\",\n \"patternProperties\",\n \"additionalProperties\",\n \"items\",\n]);\n\nconst admits = (segment: Segment, key: string): boolean =>\n segment === null ||\n (typeof segment === \"string\"\n ? segment === key\n : !segment.except.includes(key));\n\nconst overlap = (a: Segment, b: Segment): boolean =>\n typeof a === \"string\"\n ? admits(b, a)\n : typeof b === \"string\"\n ? admits(a, b)\n : true;\n\nexport const marksKey = (schema: unknown, key: string): boolean =>\n sensitivePaths(schema).some(\n ({ segments: [first] }) => first === undefined || admits(first, key),\n );\n\n/** Whether any part of a schema is marked sensitive. */\nexport function hasSensitive(schema: unknown): boolean {\n const { paths, hidden } = analyze(schema);\n return paths.length > 0 || hidden !== undefined;\n}\n\nexport function writeOnly<T>(schema: T): T {\n if (!hasSensitive(schema)) return schema;\n const visit = (node: any): any => {\n if (Array.isArray(node)) return node.map(visit);\n if (!node || typeof node !== \"object\") return node;\n const copy = { ...node };\n for (const key of Object.keys(copy)) copy[key] = visit(copy[key]);\n if (isSensitive(node)) copy.writeOnly = true;\n return copy;\n };\n return visit(schema);\n}\n\nconst pointer = (segments: Segment[]) =>\n segments.map((key) => `/${typeof key === \"string\" ? key : \"*\"}`).join(\"\") ||\n \"/\";\n\nexport function sensitivePointer(schema: unknown): string | undefined {\n const { paths, hidden } = analyze(schema);\n return paths[0] ? pointer(paths[0].segments) : hidden;\n}\n\nconst escape = (key: string) => key.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n\nconst keysAt = (value: object, segment: Segment): string[] =>\n segment === null\n ? Object.keys(value)\n : typeof segment === \"object\"\n ? Object.keys(value).filter((key) => !segment.except.includes(key))\n : Object.hasOwn(value, segment)\n ? [segment]\n : [];\n\nfunction* found(\n value: any,\n segments: Segment[],\n index = 0,\n at = \"\",\n): Generator<[parent: any, key: string, field: string]> {\n if (value === null || typeof value !== \"object\") return;\n for (const key of keysAt(value, segments[index]!)) {\n const field = `${at}/${escape(key)}`;\n if (index === segments.length - 1) yield [value, key, field];\n else yield* found(value[key], segments, index + 1, field);\n }\n}\n\nfunction omit(\n value: any,\n segments: Segment[],\n hidden: Set<string>,\n index = 0,\n at = \"\",\n): unknown {\n if (value === null || typeof value !== \"object\") return value;\n let copy: any;\n for (const key of keysAt(value, segments[index]!)) {\n const field = `${at}/${escape(key)}`;\n if (index === segments.length - 1) {\n if (!hidden.has(field)) continue;\n copy ??= Array.isArray(value) ? [...value] : { ...value };\n delete copy[key];\n } else {\n const next = omit(value[key], segments, hidden, index + 1, field);\n if (next === value[key]) continue;\n copy ??= Array.isArray(value) ? [...value] : { ...value };\n copy[key] = next;\n }\n }\n return copy ?? value;\n}\n\nexport type Reveal<TInput = unknown, TContext = any> =\n | boolean\n | ((args: {\n field: string;\n input: TInput;\n ctx: TContext;\n }) => boolean | Promise<boolean>);\n\nexport interface Sensitivity {\n input(input: unknown): void;\n output(output: unknown, input: unknown, ctx: unknown): Promise<unknown>;\n}\n\nexport function sensitivity(\n config: {\n name: string;\n input?: unknown;\n output?: unknown;\n reveal?: Reveal<any>;\n },\n service?: string,\n): Sensitivity | undefined {\n const input = analyze(config.input);\n const output = analyze(config.output);\n const inputs = input.paths;\n const outputs = output.paths;\n if (!hasSensitive(config.input) && !hasSensitive(config.output))\n return undefined;\n const owner = service\n ? `Service '${service}' action '${config.name}'`\n : `Action '${config.name}'`;\n for (const [kind, { ref, hidden }] of [\n [\"input\", input],\n [\"output\", output],\n ] as const) {\n if (ref !== undefined)\n throw new Error(\n `${owner}: the ${kind} schema marks a field t.Sensitive and has a $ref at '${ref}' (t.Recursive, t.Module or t.Ref), which sensitive fields do not follow; move the secret out of the recursive or referenced schema`,\n );\n if (hidden !== undefined)\n throw new Error(\n `${owner}: the ${kind} schema marks a field t.Sensitive under '${hidden}', which sensitive fields do not follow; mark it in properties, items, records or union branches`,\n );\n }\n const { reveal = false } = config;\n if (reveal !== true)\n for (const path of outputs) {\n const at = pointer(path.segments);\n if (!path.optional)\n throw new Error(\n `${owner}: sensitive output field '${at}' is removed unless \\`reveal\\` allows it, so the schema must let it be absent: make it t.Optional in every union or intersect branch, not an array item, a record value or a property under minProperties, nor inside a uniqueItems array (or set \\`reveal: true\\`)`,\n );\n const exact = JSON.stringify(path.segments);\n const hit = output.publics.find(\n ({ segments, required }) =>\n segments.length === path.segments.length &&\n segments.every((segment, index) =>\n overlap(segment, path.segments[index]!),\n ) &&\n (required || JSON.stringify(segments) !== exact),\n );\n if (hit)\n throw new Error(\n `${owner}: sensitive output field '${at}' is removed unless \\`reveal\\` allows it, and that path also matches the unmarked field '${pointer(hit.segments)}', which would be removed with it; give the secret a name of its own (or set \\`reveal: true\\`)`,\n );\n }\n const values = (value: unknown, paths: SensitivePath[]) => {\n const all: unknown[] = [];\n for (const { segments } of paths)\n if (!segments.length) all.push(value);\n else\n for (const [parent, key] of found(value, segments))\n all.push(parent[key]);\n return all;\n };\n return {\n input(input) {\n for (const value of values(input, inputs)) redact(value);\n },\n async output(output, input, ctx) {\n for (const value of values(output, outputs)) redact(value);\n if (reveal === true) return output;\n let result = output;\n for (const { segments } of outputs) {\n const hidden = new Set<string>();\n for (const [, , field] of found(output, segments))\n if (\n typeof reveal !== \"function\" ||\n (await reveal({ field, input, ctx })) !== true\n )\n hidden.add(field);\n if (hidden.size) result = omit(result, segments, hidden);\n }\n return result;\n },\n };\n}\n\nconst MIN_REDACTED_LENGTH = 8;\nconst MIN_REDACTED_DIGITS = 4;\nconst MAX_REDACTED_VALUES = 10_000;\nconst MAX_WALKED_ENTRIES = 100;\nconst REDACTED = \"[REDACTED]\";\nconst WITHHELD = \"[REDACTED: too many sensitive values in this call]\";\n\ninterface Redactions {\n values: Set<string>;\n count: number;\n sorted?: string[];\n full?: boolean;\n}\n\nconst redactions = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(\"brickkit.redactions\")\n] ??= new AsyncLocalStorage<Redactions>()) as AsyncLocalStorage<Redactions>;\n\nlet warned = false;\n\nfunction add(set: Redactions, value: string): void {\n if (set.values.has(value)) return;\n if (set.count >= MAX_REDACTED_VALUES) {\n if (!warned)\n console.warn(\n `[brick] A call's redaction set reached ${MAX_REDACTED_VALUES} values, so its log lines are now withheld. A timer or task started inside a call with t.Sensitive fields joins that call's set; bound an input's sensitive records and arrays with maxProperties or maxItems.`,\n );\n warned = true;\n set.full = true;\n return;\n }\n set.count++;\n set.values.add(value);\n set.values.add(JSON.stringify(value).slice(1, -1));\n set.sorted = undefined;\n}\n\nconst longNumber = (value: number | bigint) =>\n String(value).replace(/\\D/g, \"\").length >= MIN_REDACTED_DIGITS;\n\n/**\n * Keep a secret out of what Brick logs and traces for the rest of the running\n * call: the logger, the span recorder and error responses replace it with\n * `[REDACTED]`. Call it as soon as `execute` loads a secret, before it can be\n * logged. It takes each string and number in the value, as a `t.Sensitive`\n * field's value is taken: booleans, and numbers under 4 digits, are left out.\n * Outside a call with `t.Sensitive` fields it does nothing.\n */\nexport function redact(value: unknown): void {\n const set = redactions.getStore();\n if (set) register(set, value, new Set());\n}\n\nfunction register(set: Redactions, value: unknown, seen: Set<object>): void {\n if (typeof value === \"string\") {\n if (value) add(set, value);\n } else if (typeof value === \"number\" || typeof value === \"bigint\") {\n if (longNumber(value)) add(set, String(value));\n } else if (value && typeof value === \"object\" && !seen.has(value)) {\n seen.add(value);\n for (const child of Object.values(value)) register(set, child, seen);\n }\n}\n\nexport function redacting(): boolean {\n const set = redactions.getStore();\n return !!set && (set.full || set.values.size > 0);\n}\n\nexport function redactText(text: string): string;\nexport function redactText(text: unknown): unknown;\nexport function redactText(text: unknown): unknown {\n const set = redactions.getStore();\n if (!set || typeof text !== \"string\") return text;\n if (set.full) return WITHHELD;\n set.sorted ??= [...set.values]\n .filter((value) => value.length >= MIN_REDACTED_LENGTH)\n .sort((a, b) => b.length - a.length);\n let redacted: string = text;\n for (const value of set.sorted)\n if (redacted.includes(value))\n redacted = redacted.split(value).join(REDACTED);\n return redacted;\n}\n\nfunction redactLeaf(set: Redactions, value: unknown): unknown {\n if (typeof value === \"string\")\n return set.values.has(value) ? REDACTED : redactText(value);\n if (typeof value === \"number\" || typeof value === \"bigint\")\n return longNumber(value) && set.values.has(String(value))\n ? REDACTED\n : value;\n return value;\n}\n\nconst LEAF_DEPTH = 5;\n\nfunction publicFieldsCopy(\n original: object,\n props: [PropertyKey, unknown][],\n): object {\n const copy = Object.create(Object.getPrototypeOf(original));\n for (const [key, next] of props)\n Object.defineProperty(copy, key, {\n value: next,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return copy;\n}\n\nexport function redactValues<T>(value: T): T {\n const set = redactions.getStore();\n if (!set || (!set.full && !set.values.size)) return value;\n const walking = new Set<object>();\n const done = new Map<object, unknown>();\n const visit = (value: any, depth: number): any => {\n if (typeof value === \"function\")\n return Object.keys(value).length ? \"[Function]\" : value;\n if (!value || typeof value !== \"object\") return redactLeaf(set, value);\n if (value instanceof Date) return value;\n if (walking.has(value)) return \"[Circular]\";\n if (done.has(value)) return done.get(value);\n if (depth > LEAF_DEPTH) return \"[Object]\";\n walking.add(value);\n let copy: unknown;\n try {\n copy = inside(value, depth);\n } catch {\n copy = \"[Unreadable]\";\n }\n walking.delete(value);\n done.set(value, copy);\n return copy;\n };\n const entries = (value: Iterable<unknown>, size: number, depth: number) => {\n const items: unknown[] = [];\n for (const item of value) {\n if (items.length === MAX_WALKED_ENTRIES) break;\n items.push(item);\n }\n const next = items.map((item) =>\n visit(item, value instanceof Map ? depth : depth + 1),\n );\n const more = size - items.length;\n const changed = more > 0 || next.some((item, i) => item !== items[i]);\n return { next, more, changed };\n };\n const inside = (value: object, depth: number): unknown => {\n if (Array.isArray(value)) {\n const { next, more, changed } = entries(value, value.length, depth);\n if (more) next.push(`... ${more} more items not shown`);\n return changed || Object.keys(value).length !== value.length\n ? next\n : value;\n }\n if (value instanceof Map || value instanceof Set) {\n const { next, more, changed } = entries(value, value.size, depth);\n if (!changed) return value;\n if (value instanceof Set) {\n if (more) next.push(`... ${more} more items not shown`);\n return new Set(next);\n }\n const map = new Map(next as [unknown, unknown][]);\n if (more) map.set(\"...\", `${more} more entries not shown`);\n return map;\n }\n if (value instanceof Error) {\n let text = redactText(\n String(value.stack || `${value.name}: ${value.message}`),\n );\n if (Object.keys(value).length)\n text += ` ${inspect(visit({ ...value }, depth + 1), { depth: 2 })}`;\n if (value.cause !== undefined) {\n const cause = visit(value.cause, depth + 1);\n text += `\\n [cause]: ${typeof cause === \"string\" ? cause : inspect(cause, { depth: 2 })}`;\n }\n return text;\n }\n const tag = Object.prototype.toString.call(value);\n if (tag !== \"[object Object]\") return `[${tag.slice(8, -1)}]`;\n const descriptors = Object.getOwnPropertyDescriptors(value);\n let changed = false;\n const props: [PropertyKey, unknown][] = [];\n for (const key of Reflect.ownKeys(descriptors)) {\n const descriptor = descriptors[key as any]!;\n if (!descriptor.enumerable) continue;\n const name = typeof key === \"string\" ? redactLeaf(set, key) : key;\n const next =\n \"value\" in descriptor ? visit(descriptor.value, depth + 1) : \"[Getter]\";\n if (name !== key || next !== descriptor.value) changed = true;\n props.push([name as PropertyKey, next]);\n }\n return changed ? publicFieldsCopy(value, props) : value;\n };\n return visit(value, 0);\n}\n\nexport function redactDetails(details: unknown): unknown {\n const set = redactions.getStore();\n if (!set || details === undefined || (!set.full && !set.values.size))\n return details;\n if (set.full) return WITHHELD;\n try {\n const text = JSON.stringify(details);\n if (text === undefined) return details;\n const copy = JSON.parse(text, (_key, value) =>\n value && typeof value === \"object\" && !Array.isArray(value)\n ? Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n redactLeaf(set, key),\n child,\n ]),\n )\n : redactLeaf(set, value),\n );\n return JSON.stringify(copy) === text ? details : copy;\n } catch {\n return REDACTED;\n }\n}\n\nexport const outsideRedaction = <T>(fn: () => T): T => redactions.exit(fn);\n\n/** Set a property of an error, unless it is read-only (a `DOMException`, a frozen error). */\nfunction assign(target: any, key: string, value: unknown): void {\n try {\n target[key] = value;\n } catch {}\n}\n\nconst ESCAPED_ERROR_FIELDS = new Set([\"message\", \"stack\", \"cause\", \"details\"]);\nconst MAX_CAUSE_DEPTH = 8;\n\n/** `err`, redacted in place along its cause chain, for whoever logs it outside the call. */\nfunction redactEscaped(err: unknown): unknown {\n if (!(err instanceof Error)) return redactValues(err);\n let e: any = err;\n for (let n = 0; n < MAX_CAUSE_DEPTH; n++) {\n assign(e, \"message\", redactText(e.message));\n if (e.stack) assign(e, \"stack\", redactText(e.stack));\n if (\"details\" in e) assign(e, \"details\", redactDetails(e.details));\n for (const [key, descriptor] of Object.entries(\n Object.getOwnPropertyDescriptors(e),\n ))\n if (\n descriptor.enumerable &&\n \"value\" in descriptor &&\n !ESCAPED_ERROR_FIELDS.has(key)\n )\n assign(e, key, redactValues(descriptor.value));\n if (!(e.cause instanceof Error)) {\n if (e.cause !== undefined) assign(e, \"cause\", redactValues(e.cause));\n break;\n }\n e = e.cause;\n }\n return err;\n}\n\nexport async function withRedaction<T>(fn: () => Promise<T>): Promise<T> {\n if (redactions.getStore()) return fn();\n const set: Redactions = { values: new Set(), count: 0 };\n try {\n return await redactions.run(set, fn);\n } catch (err) {\n throw redactions.run(set, () => redactEscaped(err));\n }\n}\n","import { ATTR } from \"./telemetry-names\";\nimport { redactText, redacting } from \"./sensitive\";\nimport {\n context,\n isSpanContextValid,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n type Attributes,\n type Span,\n} from \"@opentelemetry/api\";\n\nconst INSTRUMENTATION_SCOPE = \"@brickkit/core\";\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STATEMENT_LENGTH = 2000;\nconst DATABASE_INSTRUMENTED = Symbol.for(\"brickkit.telemetry.database\");\nconst FETCH_INSTRUMENTED = Symbol.for(\"brickkit.telemetry.fetch\");\nconst SQLITE_STATEMENT_METHODS = [\"all\", \"get\", \"run\", \"values\"] as const;\n\ntype Outcome =\n | { failed: false; value: unknown }\n | { failed: true; error: unknown };\n\n/** Run `fn` as a child of the active span, ending the span when its result settles. */\nexport function withSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n kind: SpanKind = SpanKind.INTERNAL,\n): T {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(name, { kind, attributes }, (span) =>\n settle(fn, (outcome) => {\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n }),\n );\n}\n\n/**\n * Add a child span for an in-process call, but only inside a request that is\n * already traced. Calls made outside instrumented requests run unchanged.\n */\nexport function withCallSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n): T {\n return inTrace() ? withSpan(name, attributes, fn) : fn();\n}\n\n/**\n * Whether a child span would join a trace: the active span is recording and\n * has a valid context. A non-recording span, such as one from a tracer that\n * never got the registered provider, would make each child a root trace.\n */\nfunction inTrace(): boolean {\n const span = trace.getActiveSpan();\n return (\n Boolean(span?.isRecording()) && isSpanContextValid(span!.spanContext())\n );\n}\n\n/**\n * Run one try of a schedule as a root span, `schedule <name>`, so the SQL,\n * fetch calls and log lines of the run share its trace. Never a child of\n * whatever context started the tick, such as the request that triggered it.\n */\nexport function traceScheduleRun<T>(\n run: { schedule: string; trigger: string; attempt: number; slot: string },\n fn: () => Promise<T>,\n): Promise<T> {\n return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(\n `schedule ${run.schedule}`,\n {\n root: true,\n attributes: {\n [ATTR.schedule]: run.schedule,\n [ATTR.scheduleTrigger]: run.trigger,\n [ATTR.scheduleAttempt]: run.attempt,\n [ATTR.scheduleSlot]: run.slot,\n },\n },\n (span) =>\n settle(fn, (outcome) => {\n span.setAttribute(\n ATTR.scheduleOutcome,\n outcome.failed ? \"failed\" : \"succeeded\",\n );\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n }),\n );\n}\n\ninterface HttpContext {\n request?: Request;\n headers?: Record<string, string | undefined>;\n set?: { status?: unknown; headers?: Record<string, unknown> };\n}\n\n/** What a raw route handler receives from `traceRoute`. Read the body from `request`. */\nexport interface RawRouteContext {\n request: Request;\n headers: Record<string, string | undefined>;\n set: { status?: unknown; headers?: Record<string, unknown> };\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n}\n\n/**\n * Wrap a raw route handler so each of its requests gets a server span. Use it\n * for routes registered directly on the app, outside actions and endpoints,\n * such as auth or webhook routes. Spans are recorded whenever a tracer provider\n * is registered; `brick({ telemetry })` does not apply to these routes.\n *\n * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia\n * decides what to parse from the handler's destructuring, and forwarding the\n * whole context would parse the body and leave `request.json()` with nothing.\n */\nexport function traceRoute<T>(\n route: string,\n handler: (context: RawRouteContext) => T,\n): (context: RawRouteContext) => T {\n return ({ request, headers, set, params, query }) =>\n traceHttpRequest({ request, headers, set }, request.method, route, () =>\n handler({ request, headers, set, params, query }),\n );\n}\n\n/**\n * Wrap one HTTP request in a server span. The span continues the caller's\n * trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the\n * request id Brick returns is the span's trace id, so clients can find the\n * request in the dashboard.\n */\nexport function traceHttpRequest<T>(\n request: HttpContext,\n method: string,\n route: string,\n fn: () => T,\n): T {\n const attributes: Attributes = {\n [ATTR.httpMethod]: method,\n [ATTR.httpRoute]: route,\n };\n if (request.request) {\n attributes[ATTR.urlPath] = new URL(request.request.url).pathname;\n }\n const headers = request.headers ?? {};\n const parent = propagation.extract(context.active(), headers);\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(\n `${method} ${route}`,\n { kind: SpanKind.SERVER, attributes },\n parent,\n (span) => {\n if (!headers[\"x-trace-id\"]) {\n headers[\"x-trace-id\"] = span.spanContext().traceId;\n }\n const outgoing: Record<string, string> = {};\n propagation.inject(context.active(), outgoing);\n if (request.set?.headers) Object.assign(request.set.headers, outgoing);\n return settle(fn, (outcome) => {\n // Raw handlers often return a Response, whose status Elysia's `set` never sees.\n const status = outcome.failed\n ? 500\n : outcome.value instanceof Response\n ? outcome.value.status\n : responseStatus(request.set?.status);\n if (outcome.failed) recordThrown(span, outcome.error);\n span.setAttribute(ATTR.httpStatus, status);\n const traceId = headers[\"x-trace-id\"];\n if (traceId) span.setAttribute(ATTR.traceId, traceId);\n if (status >= 500) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${status}`,\n });\n }\n span.end();\n });\n },\n );\n}\n\n/**\n * Attach a handled failure to the active span. Brick returns these as\n * responses rather than throwing, so only server faults (5xx) mark the span\n * as errored; client errors keep their code as an attribute.\n */\nexport function recordFailure(\n error: unknown,\n failure: { status: number; code: string; message: string },\n): void {\n const span = trace.getActiveSpan();\n if (!span) return;\n span.setAttributes({\n [ATTR.errorCode]: failure.code,\n [ATTR.errorStatus]: failure.status,\n [ATTR.errorMessage]: truncate(failure.message),\n });\n if (failure.status >= 500) recordThrown(span, error);\n}\n\nexport function recordWebhook(\n name: string,\n eventId: string | undefined,\n outcome: string,\n): void {\n trace.getActiveSpan()?.setAttributes({\n [ATTR.webhook]: name,\n ...(eventId === undefined ? {} : { [ATTR.webhookEventId]: eventId }),\n [ATTR.webhookOutcome]: outcome,\n });\n}\n\n/**\n * Record SQL statements as client spans for the database behind a service.\n * Drizzle's logger has no timing, so the hook sits on the driver: each\n * statement is timed where the driver runs it. Statements outside traced\n * requests are not recorded. Calling this again on the same client is a no-op.\n */\nexport function instrumentDatabase(db: unknown): void {\n const client = (db as { $client?: unknown } | undefined)?.$client;\n // postgres.js clients are callable functions, so accept both shapes.\n if (\n (typeof client !== \"object\" && typeof client !== \"function\") ||\n client === null\n ) {\n return;\n }\n const driver = client as Record<PropertyKey, unknown>;\n if (driver[DATABASE_INSTRUMENTED]) return;\n if (typeof driver.prepare === \"function\") {\n instrumentBunSqlite(driver as unknown as BunSqliteClient);\n } else if (typeof driver.unsafe === \"function\") {\n instrumentPostgres(driver as unknown as PostgresClient);\n } else {\n return;\n }\n driver[DATABASE_INSTRUMENTED] = true;\n}\n\nexport function instrumentFetch(): void {\n const original = globalThis.fetch as typeof fetch & {\n [FETCH_INSTRUMENTED]?: true;\n };\n if (original[FETCH_INSTRUMENTED]) return;\n // A Proxy keeps fetch's own properties, such as Bun's `fetch.preconnect`.\n const wrapped = new Proxy(original, {\n get: (target, key) =>\n key === FETCH_INSTRUMENTED ? true : Reflect.get(target, key),\n apply(target, self, args: Parameters<typeof fetch>) {\n const [input, init] = args;\n if (!inTrace()) return Reflect.apply(target, self, args);\n let url: URL;\n try {\n url = new URL(input instanceof Request ? input.url : String(input));\n } catch {\n return Reflect.apply(target, self, args);\n }\n const method = (\n init?.method ?? (input instanceof Request ? input.method : \"GET\")\n ).toUpperCase();\n const span = trace.getTracer(INSTRUMENTATION_SCOPE).startSpan(\n truncate(redactText(`${method} ${url.host}${url.pathname}`)),\n {\n kind: SpanKind.CLIENT,\n attributes: {\n [ATTR.httpMethod]: method,\n [ATTR.urlFull]: truncate(\n redactText(`${url.origin}${url.pathname}`),\n ),\n [ATTR.serverAddress]: url.hostname,\n },\n },\n context.active(),\n );\n const fail = (error: unknown) => {\n recordThrown(span, error);\n span.end();\n throw error;\n };\n let pending: Promise<Response>;\n try {\n pending = Reflect.apply(target, self, args);\n } catch (error) {\n return fail(error);\n }\n return pending.then((response) => {\n span.setAttribute(ATTR.httpStatus, response.status);\n if (response.status >= 400) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${response.status}`,\n });\n }\n span.end();\n return response;\n }, fail);\n },\n });\n globalThis.fetch = wrapped;\n}\n\ntype BunSqliteStatement = Record<\n (typeof SQLITE_STATEMENT_METHODS)[number],\n (...args: unknown[]) => unknown\n>;\n\ninterface BunSqliteClient {\n prepare: (sql: string) => BunSqliteStatement;\n}\n\nfunction instrumentBunSqlite(client: BunSqliteClient): void {\n const prepare = client.prepare.bind(client);\n client.prepare = (sql: string) => {\n const statement = prepare(sql);\n for (const method of SQLITE_STATEMENT_METHODS) {\n const original = statement[method];\n if (typeof original !== \"function\") continue;\n statement[method] = (...args: unknown[]) =>\n recordStatement(sql, \"sqlite\", () => original.apply(statement, args));\n }\n return statement;\n };\n}\n\ninterface PostgresQuery {\n then: (\n onFulfilled?: (value: unknown) => unknown,\n onRejected?: (reason: unknown) => unknown,\n ) => Promise<unknown>;\n}\n\ninterface PostgresClient {\n unsafe: (sql: string, ...rest: unknown[]) => PostgresQuery;\n}\n\n/**\n * postgres.js returns a query that runs when awaited, and `values()` returns\n * that same object, so overriding `then` on it times the whole round trip.\n */\nfunction instrumentPostgres(client: PostgresClient): void {\n const unsafe = client.unsafe.bind(client);\n client.unsafe = (sql: string, ...rest: unknown[]) => {\n const query = unsafe(sql, ...rest);\n if (!inTrace() || typeof query?.then !== \"function\") {\n return query;\n }\n const span = startStatementSpan(sql, \"postgresql\");\n let finished = false;\n const finish = (outcome: Outcome) => {\n if (finished) return;\n finished = true;\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n };\n const then = query.then.bind(query);\n // The query is already thenable; this wraps its own `then` to time the\n // round trip, so the no-thenable rule does not apply.\n // oxlint-disable-next-line unicorn/no-thenable\n query.then = (onFulfilled, onRejected) =>\n then(\n (value) => {\n finish({ failed: false, value });\n return onFulfilled ? onFulfilled(value) : value;\n },\n (error: unknown) => {\n finish({ failed: true, error });\n if (onRejected) return onRejected(error);\n throw error;\n },\n );\n return query;\n };\n}\n\nfunction recordStatement<T>(sql: string, system: string, fn: () => T): T {\n if (!inTrace()) return fn();\n return withSpan(\n statementName(sql),\n statementAttributes(sql, system),\n fn,\n SpanKind.CLIENT,\n );\n}\n\nfunction startStatementSpan(sql: string, system: string): Span {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startSpan(\n statementName(sql),\n { kind: SpanKind.CLIENT, attributes: statementAttributes(sql, system) },\n context.active(),\n );\n}\n\nfunction statementName(sql: string): string {\n return `SQL ${operationOf(sql)}`;\n}\n\nfunction statementAttributes(sql: string, system: string): Attributes {\n return {\n [ATTR.dbSystem]: system,\n [ATTR.dbOperation]: operationOf(sql),\n [ATTR.dbStatement]: truncate(sql, MAX_STATEMENT_LENGTH),\n };\n}\n\nfunction operationOf(sql: string): string {\n return sql.trim().split(/\\s+/, 1)[0]?.toUpperCase() || \"SQL\";\n}\n\nfunction settle<T>(fn: () => T, done: (outcome: Outcome) => void): T {\n let result: T;\n try {\n result = fn();\n } catch (error) {\n done({ failed: true, error });\n throw error;\n }\n if (isPromiseLike(result)) {\n return result.then(\n (value) => {\n done({ failed: false, value });\n return value;\n },\n (error: unknown) => {\n done({ failed: true, error });\n throw error;\n },\n ) as unknown as T;\n }\n done({ failed: false, value: result });\n return result;\n}\n\nfunction recordThrown(span: Span, error: unknown): void {\n if (!(error instanceof Error))\n span.recordException(redactText(String(error)));\n else if (!redacting()) span.recordException(error);\n else\n span.recordException({\n code: (error as { code?: string }).code,\n name: error.name,\n message: redactText(error.message),\n stack: error.stack && redactText(error.stack),\n });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncate(redactText(messageOf(error))),\n });\n}\n\nfunction responseStatus(value: unknown): number {\n const status = typeof value === \"number\" ? value : Number(value ?? 200);\n return Number.isInteger(status) ? status : 200;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n","import { ActionExecutionError, ValidationError, type Logger } from \"./types\";\nimport { recordFailure } from \"./telemetry\";\nimport type { WireError } from \"./protocol\";\nimport { redactDetails, redactText } from \"./sensitive\";\n\n/** The JSON body of a failed HTTP call. */\nexport interface ErrorEnvelope extends WireError {\n requestId: string;\n}\n\ntype ErrorContext = { logger: Pick<Logger, \"error\">; requestId: string };\n\n/** Preserve declared failures, log and wrap unexpected throws without exposing internals. */\nexport function normalizeActionError(\n err: unknown,\n { logger, requestId }: ErrorContext,\n): ActionExecutionError | ValidationError {\n if (err instanceof ActionExecutionError || err instanceof ValidationError)\n return err;\n logger.error(\"Unexpected action error\", { requestId }, err);\n const failure = new ActionExecutionError(\n \"INTERNAL_SERVER_ERROR\",\n \"Internal Server Error\",\n 500,\n undefined,\n { cause: err },\n );\n failure.name = \"InternalServerError\";\n return failure;\n}\n\n/**\n * Turn what an action threw into the JSON body of its HTTP response, and record\n * the failure on the active trace. Declared failures and validation errors keep\n * their code, status, and details; anything else is logged and answered as a\n * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.\n *\n * @param err - Whatever was thrown.\n * @param context - A `logger` with `error()`, and the `requestId` to put in the body.\n * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and\n * `details` or `errors` when there are any.\n */\nexport function toErrorResponse(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const envelope = redactAnsweredEnvelope(buildErrorEnvelope(err, context));\n recordFailure(err, envelope);\n return envelope;\n}\n\nfunction redactAnsweredEnvelope(envelope: ErrorEnvelope): ErrorEnvelope {\n envelope.message = redactText(envelope.message);\n if (envelope.details !== undefined)\n envelope.details = redactDetails(envelope.details);\n return envelope;\n}\n\nfunction buildErrorEnvelope(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const failure = normalizeActionError(err, context);\n if (\n failure.status >= 500 &&\n (err instanceof ActionExecutionError || err instanceof ValidationError)\n ) {\n context.logger.error(\n \"Server action error\",\n { requestId: context.requestId },\n err,\n );\n }\n if (failure instanceof ValidationError && failure.status >= 500) {\n return {\n name: failure.name,\n code: failure.code,\n message: failure.message,\n status: failure.status,\n requestId: context.requestId,\n };\n }\n return { ...failure.toJSON(), requestId: context.requestId };\n}\n","import {\n Kind,\n Type as TypeBox,\n TypeRegistry,\n type SchemaOptions,\n type TArray,\n type TSchema,\n type TUnsafe,\n type Static,\n} from \"@sinclair/typebox\";\nimport { TypeCompiler, type TypeCheck } from \"@sinclair/typebox/compiler\";\nimport type { ValidationErrorItem } from \"./types\";\nimport { Sensitive } from \"./sensitive\";\n\n/**\n * Any JSON value: null, boolean, number, string, or an array or object of\n * JSON values.\n */\nfunction Json(options?: SchemaOptions) {\n return TypeBox.Recursive(\n (This) =>\n TypeBox.Union([\n TypeBox.Null(),\n TypeBox.Boolean(),\n TypeBox.Number(),\n TypeBox.String(),\n TypeBox.Array(This),\n TypeBox.Record(TypeBox.String(), This),\n ]),\n options,\n );\n}\n\nexport interface FileOptions {\n /** The largest file accepted, in bytes. Also caps the request body before it is read. */\n maxSize?: number;\n /**\n * The content types accepted, such as `\"application/pdf\"` or `\"image/*\"`;\n * `\"*\\/*\"` accepts any. Over HTTP, Bun takes a file's type from the\n * extension of its file name, not from the part's `Content-Type`.\n */\n accept?: string[];\n description?: string;\n}\n\nfunction accepts(accept: string[] | undefined, type: string): boolean {\n if (!accept) return true;\n const given = type.split(\";\")[0]!.trim().toLowerCase();\n return accept.some((pattern) => {\n const wanted = pattern.toLowerCase();\n if (wanted === \"*/*\") return true;\n return wanted.endsWith(\"/*\")\n ? given.startsWith(wanted.slice(0, -1)) &&\n given.length > wanted.length - 1\n : given === wanted;\n });\n}\n\nTypeRegistry.Set<{ maxSize?: number; accept?: string[] }>(\n \"File\",\n (schema, value) =>\n value instanceof Blob &&\n !(value.size > (schema.maxSize ?? Infinity)) &&\n accepts(schema.accept, value.type),\n);\n\n/** A file from a `multipart/form-data` body: a `File` (a `Blob`), at most `maxSize` bytes, of a type in `accept`. */\nfunction File(options: FileOptions = {}): TUnsafe<File> {\n return TypeBox.Unsafe<File>({\n [Kind]: \"File\",\n type: \"string\",\n format: \"binary\",\n ...options,\n });\n}\n\n/** Several files under one form field. */\nfunction Files(\n options: FileOptions & { minItems?: number; maxItems?: number } = {},\n): TArray<TUnsafe<File>> {\n const { minItems, maxItems, ...file } = options;\n return TypeBox.Array(File(file), { minItems, maxItems });\n}\n\n/** TypeBox's `Type` plus Brick's `Json`, `File`, `Files` and `Sensitive`. */\n// TypeBox's `Type` is a module namespace at runtime, so its functions copy over.\nexport const Type = Object.assign({}, TypeBox, {\n Json,\n File,\n Files,\n Sensitive,\n});\nexport { Type as t };\nexport type { TSchema, Static };\n\nexport function fileFields(\n schema: unknown,\n): { key: string; maxBytes: number | undefined }[] {\n const fields = [];\n const properties = (schema as { properties?: Record<string, any> })\n ?.properties;\n for (const [key, prop] of Object.entries(properties ?? {})) {\n const file = prop[Kind] === \"File\" ? prop : prop.items;\n if (file?.[Kind] !== \"File\") continue;\n const count: number | undefined = file === prop ? 1 : prop.maxItems;\n const maxBytes =\n file.maxSize === undefined || count === undefined\n ? undefined\n : file.maxSize * count;\n fields.push({ key, maxBytes });\n }\n return fields;\n}\n\nconst compilerCache = new WeakMap<TSchema, TypeCheck<TSchema>>();\n\n/**\n * The compiled validator for a TypeBox schema. Compiling is slow and checking\n * is fast, so each schema is compiled once and kept for as long as the schema\n * object lives.\n *\n * @param schema - A TypeBox schema.\n * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.\n */\nexport function getCompiledCheck<T extends TSchema>(schema: T): TypeCheck<T> {\n let compiled = compilerCache.get(schema) as TypeCheck<T> | undefined;\n if (!compiled) {\n compiled = TypeCompiler.Compile(schema);\n compilerCache.set(schema, compiled);\n }\n return compiled;\n}\n\n/**\n * Check a value against a schema, the way actions check their input and output.\n *\n * @param schema - A TypeBox schema, or `undefined` to accept anything.\n * @param value - The value to check.\n * @returns `{ success: true, data }`, or `{ success: false, errors }` with a\n * `path`, `message` and `type` for each problem. The offending value is\n * left out so a rejected secret is never echoed or logged.\n */\nexport function validateWithSchema<T extends TSchema>(\n schema: T | undefined,\n value: unknown,\n):\n | { success: true; data: Static<T> }\n | { success: false; errors: ValidationErrorItem[] } {\n if (!schema) {\n return { success: true, data: value as Static<T> };\n }\n\n const check = getCompiledCheck(schema);\n if (check.Check(value)) {\n return { success: true, data: value as Static<T> };\n }\n\n const errors: ValidationErrorItem[] = [];\n for (const error of check.Errors(value)) {\n errors.push({\n path: error.path,\n message: error.message,\n type: error.type,\n });\n }\n\n return { success: false, errors };\n}\n","import { ATTR, GLOBAL_SYMBOL, SPAN } from \"./telemetry-names\";\nimport { format, formatWithOptions } from \"node:util\";\nimport { trace, type Span } from \"@opentelemetry/api\";\nimport type { Logger } from \"./types\";\nimport { redactText, redactValues, redacting } from \"./sensitive\";\n\ntype Level = keyof Logger;\n\n/**\n * Set by the CLI when a dashboard is collecting logs, in `brick dev` or in\n * `brick start` with the `dashboard` option. A shared symbol, not an option or\n * an export: the CLI and the app may each hold their own copy of this package,\n * and nothing but a dashboard turns it on.\n */\nconst CAPTURE = Symbol.for(GLOBAL_SYMBOL.logsCapture);\nconst MAX_MESSAGE_LENGTH = 4000;\n/**\n * Logs one span keeps. OpenTelemetry keeps 128 events per span by default,\n * exceptions among them, so a chatty action must not use them all up and\n * lose the stack trace of the error that ends it.\n */\nconst MAX_LOGS_PER_SPAN = 100;\n\nconst logged = new WeakMap<Span, number>();\n\n/**\n * Terminal formatting: colors and styles (`ESC [ … m`, and other CSI codes) and\n * titles or links (`ESC ] … BEL`). Libraries such as Better Auth color their\n * console output, which in a web page shows as stray characters.\n */\n// oxlint-disable no-control-regex\nconst ANSI =\n /\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\))/g;\n// oxlint-enable no-control-regex\n\nexport function stripAnsi(text: string): string {\n return text.includes(\"\\u001b\") ? text.replace(ANSI, \"\") : text;\n}\n\nconst REDACTED_COPY_NOT_PRINTABLE = \"[Unreadable]\";\n\nfunction formatRedacted(\n print: (...args: unknown[]) => string,\n args: unknown[],\n): string {\n let printed: string;\n try {\n printed = print(...redactValues(args));\n } catch {\n printed = REDACTED_COPY_NOT_PRINTABLE;\n }\n return redactText(printed);\n}\n\n/**\n * What `console.log` would print, without terminal colors, with objects cut off\n * at a sensible size.\n */\nfunction render(args: unknown[]): string {\n const text = formatRedacted(\n (...values) =>\n stripAnsi(\n formatWithOptions(\n {\n depth: 3,\n breakLength: 120,\n maxArrayLength: 50,\n maxStringLength: 1000,\n },\n ...values,\n ),\n ),\n args,\n );\n return text.length > MAX_MESSAGE_LENGTH\n ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…`\n : text;\n}\n\nfunction record(span: Span, level: Level, args: unknown[]): void {\n const count = (logged.get(span) ?? 0) + 1;\n logged.set(span, count);\n if (count > MAX_LOGS_PER_SPAN) {\n // Counted, so the dashboard can say how many it left out.\n span.setAttribute(ATTR.logsDropped, count - MAX_LOGS_PER_SPAN);\n return;\n }\n span.addEvent(SPAN.logEvent, {\n [ATTR.logLevel]: level,\n [ATTR.logMessage]: render(args),\n });\n}\n\n/**\n * Record a line on the running span, if a recording one is running. Returns\n * whether it did, so the caller prints only when it did not.\n */\nfunction recordActive(level: Level, args: unknown[]): boolean {\n const span = trace.getActiveSpan();\n if (!span?.isRecording()) return false;\n record(span, level, args);\n return true;\n}\n\n// The dev server's console capture calls this by name, for the same reason\n// `CAPTURE` is a shared symbol: it may hold a different copy of this package.\n(globalThis as Record<symbol, unknown>)[Symbol.for(GLOBAL_SYMBOL.logsRecord)] =\n recordActive;\n\n/**\n * A logger for actions, tools, and endpoints. While a dashboard is on, a line\n * logged while a request is being traced becomes an event on the span that is\n * running, which the dashboard shows with that request (and in its Logs tab);\n * it is not printed. Everywhere else, and for lines logged outside a request,\n * it prints to the console, prefixed by `prefix`: one for all levels, or one\n * per level.\n *\n * Capturing costs one context lookup and a span event per line, and nothing\n * is serialized for the dashboard until the span ends, so it is cheaper than\n * a console write. Lines are cut at 4,000 characters and a span keeps 100.\n */\nexport function createLogger(prefix: string | Record<Level, string>): Logger {\n const level =\n (name: Level, print: (...args: unknown[]) => void) =>\n (...args: unknown[]): void => {\n if (\n (globalThis as Record<symbol, unknown>)[CAPTURE] === true &&\n recordActive(name, args)\n )\n return;\n if (redacting()) args = [formatRedacted(format, args)];\n print(typeof prefix === \"string\" ? prefix : prefix[name], ...args);\n };\n return {\n info: level(\"info\", (...args) => console.log(...args)),\n warn: level(\"warn\", (...args) => console.warn(...args)),\n error: level(\"error\", (...args) => console.error(...args)),\n debug: level(\"debug\", (...args) => console.debug(...args)),\n };\n}\n\n/** The prefixes of loggers a caller did not supply. */\nexport const DEFAULT_LOG_PREFIXES: Record<Level, string> = {\n info: \"[INFO]\",\n warn: \"[WARN]\",\n error: \"[ERROR]\",\n debug: \"[DEBUG]\",\n};\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { GLOBAL_SYMBOL } from \"./telemetry-names\";\n\n/** The person `dashboard.auth.authorize` let in. */\nexport interface DashboardUser {\n id: string;\n name?: string;\n}\n\n/**\n * Who a request came from, when it reached the app through the dashboard's\n * `/app/*` proxy. `user` is missing when the dashboard let the request in\n * without one: by token, by `authorize` returning `true`, or with no `auth`.\n */\nexport interface DashboardIdentity {\n user?: DashboardUser;\n}\n\n/** The header the dashboard's `/app/*` proxy signs the identity into. */\nexport const DASHBOARD_IDENTITY_HEADER = \"x-brick-dashboard\";\n/** How `brick dev` hands the signing key to the app's process. */\nexport const DASHBOARD_KEY_ENV = \"BRICK_DASHBOARD_KEY\";\nconst SIGNATURE_TTL_MS = 60_000;\nconst KEY = Symbol.for(GLOBAL_SYMBOL.dashboardKey);\nconst global = globalThis as Record<symbol, string | undefined>;\nfunction hideKeyFromChildProcesses(): void {\n const handedOver = process.env[DASHBOARD_KEY_ENV];\n if (!handedOver) return;\n global[KEY] = handedOver;\n delete process.env[DASHBOARD_KEY_ENV];\n}\nhideKeyFromChildProcesses();\n\n/**\n * The key the dashboard signs identities with: random per process, or the one\n * `brick dev` or the Vite plugin handed the app.\n */\nexport function dashboardKey(): string {\n return (global[KEY] ??= randomBytes(32).toString(\"base64url\"));\n}\n\n// When each request reached the app, so a slow upload's body does not age its signature.\nconst arrivedAt = new WeakMap<Request, number>();\n\n/** Note when `request` arrived, before its body is read. */\nexport function markDashboardArrival(request: Request): void {\n arrivedAt.set(request, Date.now());\n}\n\nconst mac = (payload: string) =>\n createHmac(\"sha256\", dashboardKey()).update(payload).digest();\n\nconst sign = (claims: object, now: number): string => {\n const payload = Buffer.from(\n JSON.stringify({ ...claims, exp: now + SIGNATURE_TTL_MS }),\n ).toString(\"base64url\");\n return `${payload}.${mac(payload).toString(\"base64url\")}`;\n};\n\n/** The header value for an identity: `<base64url(json)>.<hmac>`. */\nexport function signDashboardIdentity(\n identity: DashboardIdentity,\n now = Date.now(),\n): string {\n return sign({ user: identity.user }, now);\n}\n\nfunction verifiedClaims(\n request: Request | undefined,\n): { user?: DashboardUser; scope?: unknown; write?: unknown } | undefined {\n const header = request?.headers.get(DASHBOARD_IDENTITY_HEADER);\n if (!header) return undefined;\n const dot = header.indexOf(\".\");\n if (dot < 0) return undefined;\n const payload = header.slice(0, dot);\n const given = Buffer.from(header.slice(dot + 1), \"base64url\");\n const expected = mac(payload);\n if (given.length !== expected.length || !timingSafeEqual(given, expected))\n return undefined;\n try {\n const claims = JSON.parse(\n Buffer.from(payload, \"base64url\").toString(\"utf8\"),\n );\n const now = (request && arrivedAt.get(request)) ?? Date.now();\n if (typeof claims?.exp !== \"number\" || claims.exp < now) return undefined;\n return claims;\n } catch {\n return undefined;\n }\n}\n\n/** A signature made for the MCP route carries a `scope`, and is not an identity here. */\nexport function dashboardIdentity(\n request: Request | undefined,\n): DashboardIdentity | undefined {\n const claims = verifiedClaims(request);\n if (!claims || claims.scope !== undefined) return undefined;\n return claims.user === undefined ? {} : { user: claims.user };\n}\n\n/** Who a call forwarded by the dashboard's `/mcp` is for, and whether tools that change data may run. */\nexport interface DashboardMcpCaller extends DashboardIdentity {\n write: boolean;\n}\n\n/**\n * The header value for a call the dashboard's `/mcp` forwards to the app. It is\n * scoped to the MCP route: the `/app` proxy never signs one, and a signature\n * made for `/app` is not accepted there.\n */\nexport function signDashboardMcp(\n caller: DashboardMcpCaller,\n now = Date.now(),\n): string {\n return sign({ user: caller.user, scope: \"mcp\", write: caller.write }, now);\n}\n\nexport function dashboardMcpCaller(\n request: Request | undefined,\n): DashboardMcpCaller | undefined {\n const claims = verifiedClaims(request);\n if (claims?.scope !== \"mcp\") return undefined;\n return {\n ...(claims.user === undefined ? {} : { user: claims.user }),\n write: claims.write === true,\n };\n}\n\n/**\n * The dashboard user a request came from, for an endpoint: the person\n * `dashboard.auth.authorize` let in, when the request arrived through the\n * dashboard's `/app/*` proxy. Undefined for any other request, and for one the\n * dashboard let in by token. Actions read it as `ctx.dashboard?.user`.\n */\nexport function dashboardUser(request: Request): DashboardUser | undefined {\n return dashboardIdentity(request)?.user;\n}\n","import type { Service } from \"./types\";\n\n/**\n * Who a call comes from, as the service's `identity` hook says. Brick treats\n * the strings as opaque: it compares and stores them, never interprets them.\n */\nexport interface Identity {\n /** Who: the rate-limit key and the audit actor. */\n id: string;\n /** A display name for the audit log. */\n label?: string;\n /** Which tenant: scopes file storage and is recorded in the audit log. */\n tenant?: string;\n}\n\nconst IDENTITY = Symbol.for(\"brickkit.identity\");\n\nexport function attachIdentity(\n ctx: Record<PropertyKey, unknown>,\n service: Service<any, any>,\n deps: Readonly<Record<string, unknown>>,\n): void {\n const hook = service.options.identity;\n if (typeof hook !== \"function\") return;\n let identity: Promise<Identity | null> | undefined;\n ctx[IDENTITY] = () =>\n (identity ??= Promise.resolve()\n .then(() => {\n const { [IDENTITY]: _own, ...withoutIdentity } = ctx;\n return hook({ ...withoutIdentity, deps } as any);\n })\n .then((value) => checked(service.name, value)));\n}\n\nfunction checked(service: string, value: unknown): Identity | null {\n if (value === null || value === undefined) return null;\n const { id, label, tenant } = value as Partial<Identity>;\n if (\n typeof id !== \"string\" ||\n !id ||\n (label !== undefined && typeof label !== \"string\") ||\n (tenant !== undefined && typeof tenant !== \"string\")\n )\n throw new Error(\n `Service \"${service}\": identity must return { id: string, label?: string, tenant?: string } with a non-empty id, null or undefined`,\n );\n return {\n id,\n ...(label !== undefined && { label }),\n ...(tenant !== undefined && { tenant }),\n };\n}\n\nexport function identityOf(ctx: object): Promise<Identity | null> {\n const resolve = (ctx as Record<PropertyKey, unknown>)[IDENTITY];\n return typeof resolve === \"function\" ? resolve() : Promise.resolve(null);\n}\n\nexport function hasIdentity(service: Service<any, any>): boolean {\n return typeof service.options.identity === \"function\";\n}\n","import type { BaseContext, PreparationContribution, Service } from \"./types\";\nimport type { AuditTable } from \"./audit\";\nimport type { OutboxTable } from \"./events/outbox\";\nimport type { ScheduleTable } from \"./schedules/table\";\nimport type { ServiceEvents } from \"./events/types\";\nimport type { EventRef } from \"./events/catalog\";\n\n/**\n * What core's own modules use of a service, beyond the public `Service`. Every\n * service `defineService` makes is one.\n */\nexport interface ServicePort<\n TDb = any,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> extends Service<TDb, TServiceContext> {\n readonly deps: Readonly<Record<string, unknown>>;\n /** Whether the service declares an event catalog. */\n readonly hasCatalog: boolean;\n /** `resolveContext`, for an action or socket a plugin install created: it sees `pluginDeps`. */\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n pluginDeps?: Readonly<Record<string, unknown>>,\n ): Promise<BaseContext<TDb> & TServiceContext>;\n setRecorder(recorder: ServiceEvents | undefined): void;\n getOutbox(): OutboxTable | undefined;\n getScheduleTable(): ScheduleTable | undefined;\n getAuditTable(): AuditTable | undefined;\n /** @throws When the event is not in the catalog or its payload does not match. */\n checkEvent(name: string, payload: unknown): void;\n /** Adds events to the catalog (a plugin's). */\n addEvents(refs: Readonly<Record<string, EventRef>>): void;\n registerTable(table: unknown): this;\n listPreparations(): PreparationContribution[];\n prepareContributions(): void;\n /** Records the declarations; the returned function puts them back (plugin rollback). */\n snapshot(): () => void;\n /** Marks the definitions changed, so cached architecture and OpenAPI are rebuilt. */\n touch(): void;\n}\n\n/** The port of a service: every `Service` is a `ServicePort`. */\nexport function portOf<TDb, TCtx extends Record<string, any>>(\n service: Service<TDb, TCtx>,\n): ServicePort<TDb, TCtx> {\n return service as ServicePort<TDb, TCtx>;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Service } from \"./types\";\nimport type { RawDeps } from \"./file-storage\";\nimport { portOf } from \"./service-port\";\n\n/** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */\nexport const PLUGIN_DEPS: unique symbol = Symbol.for(\"brickkit.plugin.deps\");\n\nexport function sharedAcrossCoreCopies<T>(key: string, create: () => T): T {\n const store = globalThis as any;\n return (store[Symbol.for(key)] ??= create());\n}\n\nconst depsBuiltByBrick = sharedAcrossCoreCopies(\n \"brickkit.deps.built\",\n () => new WeakSet<object>(),\n);\n\nexport function freezeAsBuiltDeps<T extends object>(deps: T): Readonly<T> {\n depsBuiltByBrick.add(Object.freeze(deps));\n return deps;\n}\n\nexport function depsOverride(\n callCtx: unknown,\n): Record<string, unknown> | undefined {\n const deps = (callCtx as { deps?: unknown } | undefined)?.deps;\n return deps && typeof deps === \"object\" && !depsBuiltByBrick.has(deps)\n ? (deps as Record<string, unknown>)\n : undefined;\n}\n\nconst running = new AsyncLocalStorage<Record<string, unknown>>();\n\n/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */\nexport function runWithDeps<T>(deps: Record<string, unknown>, fn: () => T): T {\n return running.run(deps, fn);\n}\n\nexport type ServiceDeps<S> =\n S extends Service<any, infer C, any>\n ? C extends { deps: infer D }\n ? Readonly<RawDeps<D>>\n : Readonly<Record<string, unknown>>\n : never;\n\n/**\n * The deps of a service, for code that has no `ctx`: listeners, schedules and\n * workflow steps. Actions, tools and socket handlers read `ctx.deps` instead.\n *\n * `useDeps(service)` returns that service's deps, typed from it, anywhere.\n * Without an argument it returns what the running listener, schedule or step\n * sees: in one a plugin added, the deps of that install; in the app's own, the\n * deps of all the app's services by name, for code that cannot import the\n * service (one built in a factory). A name two services give different values\n * has no single answer, so reading it throws.\n *\n * @param service - The service whose deps to return.\n * @returns The deps.\n * @throws Without `service`: when called outside a listener, schedule or\n * workflow step of a Brick app, or on reading a name two services give\n * different values.\n * @example\n * async function bookCarrier(orderId: string) {\n * \"use step\";\n * return useDeps(orders).carrier.book(orderId);\n * }\n */\nexport function useDeps<S extends Service<any, any, any>>(\n service: S,\n): ServiceDeps<S>;\nexport function useDeps<T = Record<string, unknown>>(): T;\nexport function useDeps(service?: Service<any, any, any>): unknown {\n if (service) return portOf(service).deps;\n const deps = running.getStore();\n if (!deps)\n throw new Error(\n \"useDeps() was called outside a Brick app: call it from a listener, a schedule or a workflow step (actions read ctx.deps), or pass the service: useDeps(service).\",\n );\n return deps;\n}\n\nfunction makeAmbiguous(\n deps: Record<string, unknown>,\n name: string,\n firstService: string | undefined,\n otherService: string,\n) {\n Object.defineProperty(deps, name, {\n enumerable: false,\n get() {\n throw new Error(\n `useDeps().${name} is ambiguous: services \"${firstService}\" and \"${otherService}\" both declare dep \"${name}\" with different values. Call useDeps(service) with the service you mean.`,\n );\n },\n });\n}\n\nexport function appDeps(\n services: readonly Service<any, any>[],\n): Record<string, unknown> {\n const deps: Record<string, unknown> = {};\n const owner = new Map<string, string>();\n for (const service of services)\n for (const [name, value] of Object.entries(portOf(service).deps)) {\n const seen = Object.getOwnPropertyDescriptor(deps, name);\n const first = owner.get(name);\n if (!seen) {\n owner.set(name, service.name);\n deps[name] = value;\n } else if (\"value\" in seen && seen.value !== value)\n makeAmbiguous(deps, name, first, service.name);\n }\n return freezeAsBuiltDeps(deps);\n}\n","import { fileURLToPath } from \"node:url\";\nimport { DuplicateNameError } from \"./types\";\n\n// The package root (src/ or dist/ is beneath it), so Brick's own frames are skipped.\nconst brickRoot = fileURLToPath(new URL(\"..\", import.meta.url));\n\n/**\n * The first `file:line` outside Brick on the current stack: where a name is\n * being defined. Best-effort: `undefined` when there is no stack.\n */\nexport function definitionSite(): string | undefined {\n // Plugins nest several Brick frames above the caller's.\n const limit = Error.stackTraceLimit;\n Error.stackTraceLimit = 50;\n const stack = new Error().stack;\n Error.stackTraceLimit = limit;\n for (const line of stack?.split(\"\\n\").slice(1) ?? []) {\n const match =\n /(?:\\(|at )(?:file:\\/\\/)?([^\\s()?]+)(?:\\?[^\\s():]*)?:(\\d+):\\d+\\)?$/.exec(\n line,\n );\n if (!match) continue;\n const [, file, row] = match;\n if (\n file!.startsWith(`${brickRoot}src/`) ||\n file!.startsWith(`${brickRoot}dist/`)\n )\n continue;\n return `${file}:${row}`;\n }\n return undefined;\n}\n\n/**\n * Records where `name` is defined. The same file defining it again (a dev\n * reload) replaces the old definition.\n *\n * @throws When a different file already defined `name`.\n */\nexport function claimName(\n sites: Map<string, string | undefined>,\n label: string,\n name: string,\n site: string | undefined,\n): void {\n const file = (at: string | undefined) => at?.replace(/:\\d+$/, \"\");\n if (sites.has(name) && file(sites.get(name)) !== file(site))\n throw new DuplicateNameError(\n `Brick: duplicate ${label}\\n ${sites.get(name) ?? \"unknown\"}\\n ${site ?? \"unknown\"}`,\n );\n sites.set(name, site);\n}\n","/**\n * Type-safe secrets & environment variables.\n *\n * Declare each secret once at module scope instead of scattering untyped\n * `process.env.FOO` reads:\n *\n * const port = defineSecret(\"PORT\").default(\"3333\").transform(Number).require();\n * const baseUrl = defineSecret(\"BASE_URL\").url().require();\n * const key = defineSecret(\"STRIPE_KEY\").validate((v) =>\n * v.startsWith(\"sk_\") || \"must start with sk_\"\n * ).require();\n *\n * Values resolve from the environment (Bun populates `process.env` from\n * `.env` locally; in prod the same env source applies — a future\n * `SecretSource` such as AWS can slot in without touching call sites).\n *\n * Resolution order per secret: test/session override → source (`process.env`\n * by default) → declared `default`. `resolveSecrets()` validates every\n * registered secret at boot and throws listing all missing required ones.\n */\n\nimport { definitionSite } from \"./definition-site\";\n\nexport interface SecretSource {\n get(name: string): string | undefined;\n}\n\n/** Default source: `process.env` (Bun loads `.env` into it automatically). */\nexport const envSource: SecretSource = {\n get: (name: string) => process.env[name],\n};\n\nexport interface SecretOptions {\n /** Fallback when the source has no value. Secrets without a default are required. */\n default?: string;\n}\n\n/** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */\nexport type SecretValidator<T> = (value: T) => void | boolean | string;\n\nconst registry = new Map<string, SecretRef<any>>();\nconst overrides = new Map<string, string>();\n/** Where each secret was first declared. */\nconst sites = new Map<string, string | undefined>();\n\nexport class SecretRef<T = string> {\n readonly name: string;\n readonly options: SecretOptions;\n private transformFn?: (raw: string) => T;\n private validators: SecretValidator<T>[] = [];\n\n constructor(name: string, options: SecretOptions = {}) {\n this.name = name;\n this.options = options;\n }\n\n /** True when a default was declared (i.e. the secret is optional). */\n get hasDefault(): boolean {\n return this.options.default !== undefined;\n }\n\n /** Fallback used when the source has no value. Makes the secret optional. */\n default(value: string): this {\n this.options.default = value;\n return this;\n }\n\n /**\n * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === \"true\"`).\n * Runs before validators; a throwing transform fails resolution.\n */\n transform<U>(fn: (raw: string) => U): SecretRef<U> {\n this.transformFn = fn as unknown as (raw: string) => T;\n return this as unknown as SecretRef<U>;\n }\n\n /** Run a custom check on the (transformed) value at every resolution. */\n validate(fn: SecretValidator<T>): this {\n this.validators.push(fn);\n return this;\n }\n\n /** Shorthand validator: value must parse as a URL. String refs only. */\n url(this: SecretRef<string>): SecretRef<string> {\n this.validators.push((v) => {\n try {\n new URL(v);\n } catch {\n return \"must be a valid URL\";\n }\n });\n return this;\n }\n\n private resolveRaw(source: SecretSource): string | undefined {\n return (\n overrides.get(this.name) ?? source.get(this.name) ?? this.options.default\n );\n }\n\n private coerce(raw: string): T {\n let value: T;\n if (this.transformFn) {\n try {\n value = this.transformFn(raw);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": transform failed (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n } else {\n value = raw as unknown as T;\n }\n for (const fn of this.validators) {\n let result: void | boolean | string;\n try {\n result = fn(value);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (result === false) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": validation failed`,\n );\n }\n if (typeof result === \"string\") {\n throw new Error(`Invalid value for secret \"${this.name}\": ${result}`);\n }\n }\n return value;\n }\n\n /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */\n value(source: SecretSource = envSource): T | undefined {\n const raw = this.resolveRaw(source);\n if (raw === undefined) return undefined;\n return this.coerce(raw);\n }\n\n /** Resolved value, or throws naming the missing/invalid secret. */\n require(source: SecretSource = envSource): T {\n const raw = this.resolveRaw(source);\n if (raw === undefined) {\n throw new Error(\n `Missing required secret \"${this.name}\": set it in .env (local) or the environment (prod)`,\n );\n }\n return this.coerce(raw);\n }\n\n /** True when a value would resolve (override, source, or default). */\n isSet(source: SecretSource = envSource): boolean {\n return this.resolveRaw(source) !== undefined;\n }\n}\n\n/**\n * Declare a secret. Calling it again for the name returns the same ref. From\n * the same line (a module evaluated again) it starts the declaration over, so\n * its builder calls replace the earlier ones instead of adding to them.\n */\nexport function defineSecret(\n name: string,\n options: SecretOptions = {},\n): SecretRef<string> {\n const site = definitionSite();\n const existing = registry.get(name);\n if (existing) {\n if (site !== undefined && sites.get(name) === site) {\n (existing as { options: SecretOptions }).options = options;\n existing[\"validators\"] = [];\n existing[\"transformFn\"] = undefined;\n }\n return existing;\n }\n sites.set(name, site);\n const ref = new SecretRef<string>(name, options);\n registry.set(name, ref);\n return ref;\n}\n\n/**\n * Validate every registered secret at boot. Throws a single error listing\n * all missing required secrets. Returns the resolved values.\n */\nexport function resolveSecrets(\n opts: { source?: SecretSource } = {},\n): Record<string, unknown> {\n const source = opts.source ?? envSource;\n const missing: string[] = [];\n const resolved: Record<string, unknown> = {};\n for (const ref of registry.values()) {\n const v = ref.value(source);\n if (v === undefined) missing.push(ref.name);\n else resolved[ref.name] = v;\n }\n if (missing.length > 0) {\n throw new Error(\n `Missing required secrets: ${missing.join(\", \")}. Set them in .env (local) or the environment (prod)`,\n );\n }\n return resolved;\n}\n\n/** Metadata for introspection (values never exposed — future dashboard use). */\nexport function listSecrets(\n opts: { source?: SecretSource } = {},\n): Array<{ name: string; hasDefault: boolean; isSet: boolean }> {\n const source = opts.source ?? envSource;\n return [...registry.values()].map((ref) => ({\n hasDefault: ref.hasDefault,\n isSet: ref.isSet(source),\n name: ref.name,\n }));\n}\n\n/** Test/session override for one secret (`undefined` clears the override). */\nexport function overrideSecret(name: string, value: string | undefined): void {\n if (value === undefined) overrides.delete(name);\n else overrides.set(name, value);\n}\n\n/** Clear registry and overrides. Test-only. */\nexport function resetSecrets(): void {\n registry.clear();\n overrides.clear();\n sites.clear();\n}\n","import {\n createHash,\n createHmac,\n randomBytes,\n timingSafeEqual,\n} from \"node:crypto\";\nimport { lstat, mkdir, readFile, realpath, rm } from \"node:fs/promises\";\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport { freezeAsBuiltDeps } from \"./deps\";\nimport { hasIdentity, identityOf } from \"./identity\";\nimport { SecretRef } from \"./secrets\";\nimport type { Service } from \"./types\";\n\n/** What `put` returns: the id to keep, and what was stored. */\nexport interface StoredFile {\n id: string;\n size: number;\n contentType: string;\n}\n\n/** File methods inside one tenant. Ids are the ones `put` returned; nothing takes a key, a path or a URL. */\nexport interface ScopedFiles {\n /** Stores the file under a new id Brick generates. `contentType` defaults to the file's own type. */\n put(file: Blob, options?: { contentType?: string }): Promise<StoredFile>;\n /** A short-lived signed link that downloads the file as an attachment. `expiresInMs` defaults to 5 minutes. */\n url(\n id: string,\n options?: { expiresInMs?: number; download?: string },\n ): Promise<string>;\n /** The file, or `undefined` when this tenant has none with that id. */\n get(id: string): Promise<Blob | undefined>;\n /** Removes the file; does nothing when this tenant has none with that id. */\n delete(id: string): Promise<void>;\n}\n\n/**\n * The handle of a file storage. In a call, `ctx.deps.<name>` is scoped to the\n * caller's tenant; outside one, name the tenant with `in(tenant)`.\n */\nexport interface FileStorage extends ScopedFiles {\n readonly kind: \"file\";\n /** The files of one tenant, for server code outside a request: a listener, a schedule, a webhook. */\n in(tenant: string): ScopedFiles;\n}\n\n/** A file storage as a call sees it in `ctx.deps`: the caller's tenant only, with no `in`. */\nexport interface CallFiles extends ScopedFiles {\n readonly kind: \"file\";\n}\n\n/** Deps as a call sees them: each file storage scoped to the caller's tenant. */\nexport type CallDeps<T> = { [K in keyof T]: CallDep<T[K]> };\ntype CallDep<V> = V extends FileStorage ? CallFiles : V;\n\nexport type RawDeps<T> = { [K in keyof T]: RawDep<T[K]> };\ntype RawDep<V> = V extends CallFiles ? FileStorage : V;\n\n/** A driver for file storage, such as `s3()`. It sees full keys; the handle builds them. */\nexport interface FileDriver {\n readonly kind: \"file\";\n /** Put in front of every key. */\n readonly prefix: string;\n /** The directory files are written under, in local mode. */\n readonly local?: string;\n /** Throws when the driver cannot work as configured; `brick()` calls it at startup. */\n check?(): void;\n write(key: string, file: Blob, contentType: string): Promise<void>;\n read(key: string): Promise<Blob | undefined>;\n remove(key: string): Promise<void>;\n /** A signed GET for the key, served with `contentDisposition`. */\n sign(\n key: string,\n expiresInMs: number,\n contentDisposition: string,\n ): Promise<string>;\n}\n\ntype Setting = string | SecretRef<string>;\n\n/** Options of the `s3()` storage driver. Settings left out come from Bun's `S3_*` and `AWS_*` environment variables. */\nexport interface S3StorageOptions {\n bucket?: string;\n /** Put in front of every key, such as `\"files/\"`. */\n prefix?: string;\n /** A directory: store files there instead of S3, for local development and tests. */\n local?: string;\n accessKeyId?: Setting;\n secretAccessKey?: Setting;\n sessionToken?: Setting;\n region?: Setting;\n /** An S3-compatible endpoint, such as R2 or MinIO. */\n endpoint?: Setting;\n}\n\nconst DEFAULT_EXPIRY_MS = 5 * 60_000;\n/** The longest a link may last: S3 refuses a presigned URL valid for longer. */\nconst MAX_EXPIRY_MS = 7 * 24 * 60 * 60_000;\nconst S3_READ_IDLE_TIMEOUT_MS = 30_000;\nexport const LOCAL_FILES_ROUTE = \"/_brick/files\";\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\nconst drivers: WeakMap<object, FileDriver> = ((globalThis as any)[\n Symbol.for(\"brickkit.storage.files\")\n] ??= new WeakMap());\n\nconst sha256 = (value: string) =>\n createHash(\"sha256\").update(value).digest(\"hex\");\n\nfunction tenantKey(tenant: unknown, local = false): string {\n if (\n typeof tenant !== \"string\" ||\n !tenant ||\n tenant === \".\" ||\n tenant === \"..\" ||\n !tenant.isWellFormed()\n )\n throw new Error(\n `File storage: the tenant must be a non-empty, well-formed string other than \".\" and \"..\", got ${JSON.stringify(tenant)}`,\n );\n return local ? sha256(tenant) : encodeURIComponent(tenant);\n}\n\nfunction attachment(download: string | undefined): string {\n if (!download) return \"attachment\";\n const ascii = download.replace(/[^\\x20-\\x7e]|[\"\\\\]/g, \"_\");\n return `attachment; filename=\"${ascii}\"; filename*=UTF-8''${encodeURIComponent(download)}`;\n}\n\nfunction scoped(\n driver: FileDriver,\n tenant: () => Promise<string>,\n): ScopedFiles {\n const folder = async () =>\n `${driver.prefix}${tenantKey(await tenant(), !!driver.local)}/`;\n const keyOf = async (id: string) => {\n const at = await folder();\n return typeof id === \"string\" && UUID.test(id) ? at + id : undefined;\n };\n return Object.freeze({\n put: async (file: Blob, options?: { contentType?: string }) => {\n if (!(file instanceof Blob))\n throw new TypeError(\"File storage: put needs a Blob or a File\");\n const at = await folder();\n const id = crypto.randomUUID();\n // Normalised as a Blob does (it adds a charset only to a lowercase type), so `put` returns what `get` gives back.\n const given = (options?.contentType || file.type).toLowerCase();\n const contentType =\n new Blob([], { type: given }).type || \"application/octet-stream\";\n await driver.write(at + id, file, contentType);\n return { id, size: file.size, contentType };\n },\n url: async (\n id: string,\n options: { expiresInMs?: number; download?: string } = {},\n ) => {\n const key = await keyOf(id);\n if (!key)\n throw new Error(`File storage: ${JSON.stringify(id)} is not a file id`);\n const expiresInMs = options.expiresInMs ?? DEFAULT_EXPIRY_MS;\n if (!Number.isSafeInteger(expiresInMs) || expiresInMs <= 0)\n throw new Error(\n `File storage: expiresInMs must be a positive integer, got ${expiresInMs}`,\n );\n if (expiresInMs > MAX_EXPIRY_MS)\n throw new Error(\n `File storage: expiresInMs must be at most 7 days (${MAX_EXPIRY_MS}), got ${expiresInMs}`,\n );\n return driver.sign(key, expiresInMs, attachment(options.download));\n },\n get: async (id: string) => {\n const key = await keyOf(id);\n return key ? driver.read(key) : undefined;\n },\n delete: async (id: string) => {\n const key = await keyOf(id);\n if (key) await driver.remove(key);\n },\n });\n}\n\nexport function fileStorage(driver: FileDriver): FileStorage {\n const outside = () =>\n Promise.reject(\n new Error(\n \"File storage: there is no caller here to take the tenant from. In an action read ctx.deps.<name>; elsewhere name the tenant: files.in(tenantId)\",\n ),\n );\n const handle: FileStorage = Object.freeze({\n kind: \"file\",\n in: (tenant: string) => {\n tenantKey(tenant);\n return scoped(driver, async () => tenant);\n },\n put: outside,\n url: outside,\n get: outside,\n delete: outside,\n });\n drivers.set(handle, driver);\n return handle;\n}\n\nconst fileNames = new WeakMap<object, string[]>();\nconst views = new WeakMap<object, { deps: object; ctx: object }>();\n\nexport function hasFilesView(ctx: { deps?: unknown }, deps: object): boolean {\n const view = views.get(ctx.deps as object);\n return view?.deps === deps && view.ctx === ctx;\n}\n\nexport function scopeFiles<T extends Readonly<Record<string, unknown>>>(\n deps: T,\n ctx: object,\n): T {\n let names = fileNames.get(deps);\n if (!names)\n fileNames.set(\n deps,\n (names = Object.keys(deps).filter((name) =>\n drivers.has(deps[name] as object),\n )),\n );\n if (!names.length) return deps;\n const tenant = async () => {\n const identity = await identityOf(ctx);\n if (!identity?.tenant)\n throw new Error(\n \"File storage: this call has no tenant. The service's identity hook must return { id, tenant } for callers that use files; outside a request use files.in(tenantId)\",\n );\n return identity.tenant;\n };\n const copy: Record<string, unknown> = { ...deps };\n for (const name of names) {\n const handle = deps[name] as FileStorage;\n const files: CallFiles = Object.freeze({\n kind: \"file\",\n ...scoped(drivers.get(handle)!, tenant),\n });\n copy[name] = files;\n }\n const view = freezeAsBuiltDeps(copy);\n views.set(view, { deps, ctx });\n return view as T;\n}\n\nexport function checkFileStorages(\n service: Service<any, any>,\n deps: readonly Readonly<Record<string, unknown>>[],\n): void {\n if (hasIdentity(service)) return;\n for (const values of deps) {\n const name = Object.keys(values).find((key) =>\n drivers.has(values[key] as object),\n );\n if (name)\n throw new Error(\n `Service \"${service.name}\" has file storage \"${name}\" in its deps or a plugin's but no identity hook. Files are kept per tenant: add identity: (ctx) => ({ id, tenant }) to the service.`,\n );\n }\n}\n\nconst warned = new WeakSet<FileDriver>();\n\nexport function localFileDirs(\n deps: readonly Readonly<Record<string, unknown>>[],\n): Set<string> {\n const dirs = new Set<string>();\n for (const values of deps)\n for (const value of Object.values(values)) {\n const driver = drivers.get(value as object);\n driver?.check?.();\n if (!driver?.local) continue;\n dirs.add(driver.local);\n if (process.env.NODE_ENV === \"production\" && !warned.has(driver)) {\n warned.add(driver);\n console.warn(\n `[Brick-TS] A file storage stores files in the local directory ${driver.local} while NODE_ENV is production. Set local only for development and tests.`,\n );\n }\n }\n return dirs;\n}\n\n/**\n * File storage in S3 or an S3-compatible store (R2, MinIO), through Bun's\n * built-in client. Nothing connects or reads credentials until the first call.\n * With `local`, files are written under that directory instead.\n *\n * @param options - `bucket`, `prefix`, `local`, and the credentials and\n * `endpoint` Bun's client takes, each a string or a `SecretRef`; left out,\n * Bun's `S3_*` and `AWS_*` environment variables apply.\n */\nexport function s3(options: S3StorageOptions = {}): FileDriver {\n const prefix = options.prefix ?? \"\";\n if (\n prefix.startsWith(\"/\") ||\n prefix.split(\"/\").some((part) => part === \".\" || part === \"..\")\n )\n throw new Error(\n `s3(): prefix must not start with \"/\" or hold \".\" or \"..\" segments, got ${JSON.stringify(prefix)}`,\n );\n if (options.local !== undefined)\n return localDriver(resolve(options.local), prefix);\n let client: Bun.S3Client | undefined;\n // Read here, not at import; passed to the client, which reads the environment only at process start.\n const bucket = () =>\n options.bucket || process.env.S3_BUCKET || process.env.AWS_BUCKET;\n // Without a bucket, Bun's client would take the key's first segment, the tenant, for one.\n const check = () => {\n if (!bucket())\n throw new Error(\n \"s3(): no bucket. Pass bucket, set S3_BUCKET or AWS_BUCKET, or set local for a directory.\",\n );\n };\n const open = () => {\n if (client) return client;\n check();\n const settings: Record<string, string> = { bucket: bucket()! };\n for (const name of [\n \"accessKeyId\",\n \"secretAccessKey\",\n \"sessionToken\",\n \"region\",\n \"endpoint\",\n ] as const) {\n const value = options[name];\n if (value !== undefined)\n settings[name] = value instanceof SecretRef ? value.require() : value;\n }\n return (client = new Bun.S3Client(settings));\n };\n const presign = (\n key: string,\n expiresInMs: number,\n contentDisposition?: string,\n ) =>\n open().presign(key, {\n method: \"GET\",\n expiresIn: Math.ceil(expiresInMs / 1000),\n ...(contentDisposition && { contentDisposition }),\n });\n const rethrowWithoutUrl = async <T>(\n operation: string,\n run: () => Promise<T>,\n ) => {\n try {\n return await run();\n } catch (error) {\n const code = (error as { code?: unknown }).code;\n throw new Error(\n `File storage: S3 failed ${operation} a file${typeof code === \"string\" ? ` (${code})` : \"\"}`,\n );\n }\n };\n return {\n kind: \"file\",\n prefix,\n check,\n write: async (key, file, contentType) => {\n const client = open();\n await rethrowWithoutUrl(\"writing\", () =>\n client.write(key, file, { type: contentType }),\n );\n },\n read: async (key) => {\n const url = presign(key, 60_000);\n const stalled = new AbortController();\n let idle: ReturnType<typeof setTimeout> | undefined;\n const stillMoving = () => {\n clearTimeout(idle);\n idle = setTimeout(() => stalled.abort(), S3_READ_IDLE_TIMEOUT_MS);\n };\n stillMoving();\n try {\n const response = await rethrowWithoutUrl(\"reading\", () =>\n fetch(url, { signal: stalled.signal }),\n );\n if (response.status === 404) return undefined;\n if (!response.ok)\n throw new Error(\n `File storage: S3 answered ${response.status} reading a file`,\n );\n return await rethrowWithoutUrl(\"reading\", async () => {\n const chunks: Uint8Array[] = [];\n for await (const chunk of response.body ?? []) {\n stillMoving();\n chunks.push(chunk);\n }\n return new Blob(chunks as BlobPart[], {\n type: response.headers.get(\"content-type\") ?? \"\",\n });\n });\n } finally {\n clearTimeout(idle);\n }\n },\n remove: async (key) => {\n const client = open();\n await rethrowWithoutUrl(\"deleting\", () => client.delete(key));\n },\n sign: async (key, expiresInMs, contentDisposition) =>\n presign(key, expiresInMs, contentDisposition),\n };\n}\n\nconst perProcessLinkKey: Buffer = ((globalThis as any)[\n Symbol.for(\"brickkit.storage.files.linkKey\")\n] ??= randomBytes(32));\nconst mac = (payload: string) =>\n createHmac(\"sha256\", perProcessLinkKey).update(payload).digest();\n\ninterface LinkClaims {\n dirDigest: string;\n key: string;\n expiresAt: number;\n disposition: string;\n}\n\nexport function signFileLink(claims: LinkClaims): string {\n const payload = Buffer.from(JSON.stringify(claims)).toString(\"base64url\");\n return `${payload}.${mac(payload).toString(\"base64url\")}`;\n}\n\nfunction verifyFileLink(token: string | null): LinkClaims | undefined {\n const dot = token?.indexOf(\".\") ?? -1;\n if (!token || dot < 0) return undefined;\n const payload = token.slice(0, dot);\n const given = Buffer.from(token.slice(dot + 1), \"base64url\");\n const expected = mac(payload);\n if (given.length !== expected.length || !timingSafeEqual(given, expected))\n return undefined;\n try {\n const claims = JSON.parse(Buffer.from(payload, \"base64url\").toString());\n return typeof claims.expiresAt === \"number\" && claims.expiresAt > Date.now()\n ? claims\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function localPath(\n dir: string,\n key: string,\n): Promise<string | undefined> {\n const folder = relative(dir, dirname(join(dir, key)));\n if (folder.split(sep).includes(\"..\")) return undefined;\n try {\n const [root, real] = await Promise.all([\n realpath(dir),\n realpath(join(dir, folder)),\n ]);\n return real === join(root, folder) ? join(real, basename(key)) : undefined;\n } catch (error) {\n if ([\"ENOENT\", \"ENOTDIR\"].includes((error as { code?: string }).code!))\n return undefined;\n throw error;\n }\n}\n\nconst isFile = (path: string) =>\n lstat(path).then(\n (stat) => stat.isFile(),\n (error) => {\n if ([\"ENOENT\", \"ENOTDIR\"].includes(error.code)) return false;\n throw error;\n },\n );\n\nasync function readLocal(dir: string, key: string): Promise<Blob | undefined> {\n const path = await localPath(dir, key);\n if (!path || !(await isFile(path)) || !(await isFile(`${path}.type`)))\n return undefined;\n const type = await readFile(`${path}.type`, \"utf8\");\n return new Blob([await readFile(path)], { type });\n}\n\nconst outsideDir = () =>\n new Error(\n \"File storage: the file's folder is not inside the local directory; refusing to follow a symlink\",\n );\n\nfunction localDriver(dir: string, prefix: string): FileDriver {\n return {\n kind: \"file\",\n prefix,\n local: dir,\n write: async (key, file, contentType) => {\n await mkdir(dirname(join(dir, key)), { recursive: true });\n const path = await localPath(dir, key);\n if (!path) throw outsideDir();\n await Bun.write(`${path}.type`, contentType);\n await Bun.write(path, file);\n },\n read: (key) => readLocal(dir, key),\n remove: async (key) => {\n const path = await localPath(dir, key);\n if (!path) return;\n await rm(path, { force: true });\n await rm(`${path}.type`, { force: true });\n },\n sign: async (key, expiresInMs, contentDisposition) =>\n `${LOCAL_FILES_ROUTE}?token=${signFileLink({ dirDigest: sha256(dir), key, expiresAt: Date.now() + expiresInMs, disposition: contentDisposition })}`,\n };\n}\n\nexport function localFilesRoute(dirs: ReadonlySet<string>) {\n const byDigest = new Map([...dirs].map((dir) => [sha256(dir), dir]));\n return async ({ request }: { request: Request }): Promise<Response> => {\n const claims = verifyFileLink(\n new URL(request.url).searchParams.get(\"token\"),\n );\n const dir = claims && byDigest.get(claims.dirDigest);\n if (!claims || !dir)\n return new Response(\"Invalid or expired link\", { status: 403 });\n const file = await readLocal(dir, claims.key);\n if (!file) return new Response(\"Not found\", { status: 404 });\n return new Response(file, {\n headers: {\n \"content-type\": file.type,\n \"content-disposition\": claims.disposition,\n \"x-content-type-options\": \"nosniff\",\n \"cache-control\": \"private, no-store\",\n },\n });\n };\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. */\nexport const 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 let failure: unknown;\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 timer.unref();\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 failure = undefined;\n connected(client);\n for (const wake of waiters.splice(0)) wake();\n },\n (error) => {\n failure = error;\n lost(client);\n },\n );\n };\n return {\n get(): RedisClient | undefined {\n start();\n return redis?.connected ? redis : undefined;\n },\n failure: () => failure,\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 { createHash } from \"node:crypto\";\nimport { fileStorage, type FileDriver, type FileStorage } from \"./file-storage\";\nimport { connection, REDIS_WAIT_MS } from \"./socket-redis\";\nimport { portOf } from \"./service-port\";\nimport type { Service } from \"./types\";\n\n/** What `increment` returns: the count after this hit, and when the counter expires. */\nexport interface Counter {\n count: number;\n expiresInMs: number;\n}\n\n/** What `putIfAbsent` returns: whether this call stored its value, and the value now stored. */\nexport interface PutIfAbsentResult {\n stored: boolean;\n value: string;\n}\n\n/** Key-value methods: values are strings, durations are milliseconds. */\ninterface KeyValueMethods {\n /** The value, or `null` when the key is missing or expired. */\n get(key: string): Promise<string | null>;\n /** Stores the value; without `ttlMs` it never expires. */\n put(key: string, value: string, ttlMs?: number): Promise<void>;\n /** Stores the value unless the key exists; says whether it did, and the value now stored. Atomic. */\n putIfAbsent(\n key: string,\n value: string,\n ttlMs: number,\n ): Promise<PutIfAbsentResult>;\n /** Adds 1 to a counter that expires `ttlMs` after its first hit. Atomic. Throws on a key that holds something other than an integer. */\n increment(key: string, ttlMs: number): Promise<Counter>;\n delete(key: string): Promise<void>;\n /** Closes the connection, if any. The next call opens a new one. */\n close(): Promise<void>;\n}\n\n/** A driver for key-value storage, such as `redis()` or `memory()`. It sees full keys. */\nexport interface KeyValueDriver extends KeyValueMethods {\n readonly kind: \"key-value\";\n /** Deletes the key only while it holds exactly `expected`; says whether it did. Atomic. */\n compareAndDelete(key: string, expected: string): Promise<boolean>;\n}\n\n/** Every kind of storage driver; `kind` decides the handle `defineStorage` returns. */\nexport type StorageDriver = KeyValueDriver | FileDriver;\n\n/** The handle of a key-value storage. App keys live apart from Brick's own. */\nexport interface KeyValueStorage extends KeyValueMethods {\n readonly kind: \"key-value\";\n}\n\nexport interface FrameworkStorage extends KeyValueStorage {\n compareAndDelete(key: string, expected: string): Promise<boolean>;\n}\n\n/** The handle `defineStorage` returns for a driver. */\nexport type StorageOf<D extends StorageDriver> = D extends KeyValueDriver\n ? KeyValueStorage\n : D extends FileDriver\n ? FileStorage\n : never;\n\n/** A storage could not be reached, or did not answer in time. Thrown by every call while it is down. A write that rejects with it may still have been applied. */\nexport class StorageUnavailableError extends Error {\n override readonly name = \"StorageUnavailableError\";\n static [Symbol.hasInstance](value: unknown): boolean {\n if (this !== StorageUnavailableError)\n return Function.prototype[Symbol.hasInstance].call(this, value);\n return value instanceof Error && value.name === \"StorageUnavailableError\";\n }\n}\n\nconst APP_PREFIX = \"app:\";\nconst BRICK_PREFIX = \"brick:storage:\";\n\n/** The framework side of each storage handle; global so a second core copy finds it. */\nconst frameworkSides: WeakMap<object, FrameworkStorage> = ((globalThis as any)[\n Symbol.for(\"brickkit.storage\")\n] ??= new WeakMap());\n\nconst users: WeakMap<object, number> = ((globalThis as any)[\n Symbol.for(\"brickkit.storage.users\")\n] ??= new WeakMap());\n\nfunction notACounter(key: string): Error {\n return new Error(`Storage: \"${key}\" does not hold a counter`);\n}\n\nfunction counterOverflow(key: string): Error {\n return new Error(`Storage: incrementing \"${key}\" would overflow`);\n}\n\nfunction ttl(ttlMs: number | undefined, required: boolean): void {\n if (ttlMs === undefined && !required) return;\n if (!Number.isSafeInteger(ttlMs) || ttlMs! <= 0)\n throw new Error(`Storage ttlMs must be a positive integer, got ${ttlMs}`);\n}\n\nexport function storageKey(feature: string, parts: unknown[]): string {\n return `${feature}:${JSON.stringify(\n parts.map((part) =>\n typeof part === \"string\" && part.length > 128\n ? { sha256: createHash(\"sha256\").update(part).digest(\"hex\") }\n : part,\n ),\n )}`;\n}\n\nfunction side(driver: KeyValueDriver, prefix: string) {\n return Object.freeze({\n kind: \"key-value\",\n get: async (key: string) => driver.get(prefix + key),\n put: async (key: string, value: string, ttlMs?: number) => {\n ttl(ttlMs, false);\n return driver.put(prefix + key, value, ttlMs);\n },\n putIfAbsent: async (key: string, value: string, ttlMs: number) => {\n ttl(ttlMs, true);\n return driver.putIfAbsent(prefix + key, value, ttlMs);\n },\n increment: async (key: string, ttlMs: number) => {\n ttl(ttlMs, true);\n return driver.increment(prefix + key, ttlMs);\n },\n delete: async (key: string) => driver.delete(prefix + key),\n close: async () => driver.close(),\n } as const);\n}\n\n/**\n * Declare a storage. The driver decides its kind: `redis()` and `memory()` make\n * key-value storage, `s3()` file storage kept per tenant. Pass it to a service\n * as a dep, and read it as `ctx.deps.<name>`. Nothing connects until the first call.\n *\n * @param options - `driver`: `redis({ url })`, or `memory()` for tests and local\n * development; `s3({ bucket, prefix, local })` for files.\n * @returns The handle. Key-value: `get`, `put`, `putIfAbsent`, `increment`,\n * `delete` and `close`. File: `put`, `url`, `get`, `delete` in the caller's\n * tenant, and `in(tenant)` outside a request.\n * @example\n * export const cache = defineStorage({ driver: redis({ url: process.env.REDIS_URL }) });\n * export const auth = defineService(\"auth\", { deps: { cache } });\n * // in an action\n * await ctx.deps.cache.put(`otp:${input.email}`, code, 5 * 60_000);\n */\nexport function defineStorage<D extends StorageDriver>(options: {\n driver: D;\n}): StorageOf<D> {\n const driver = options?.driver;\n if (driver?.kind === \"file\") return fileStorage(driver) as StorageOf<D>;\n if (driver?.kind !== \"key-value\")\n throw new Error(\n \"defineStorage needs a driver, such as redis(), memory() or s3()\",\n );\n const handle = side(driver, APP_PREFIX);\n frameworkSides.set(\n handle,\n Object.freeze({\n ...side(driver, BRICK_PREFIX),\n compareAndDelete: async (key: string, expected: string) =>\n driver.compareAndDelete(BRICK_PREFIX + key, expected),\n }),\n );\n return handle as StorageOf<D>;\n}\n\nexport function serviceStorage(\n service: Service<any, any>,\n deps: Readonly<Record<string, unknown>> = portOf(service).deps,\n): FrameworkStorage | undefined {\n // One handle under two names is one storage.\n const found = Object.entries(deps).filter(\n ([, value], index, all) =>\n frameworkSides.has(value as object) &&\n all.findIndex(([, other]) => other === value) === index,\n );\n if (found.length > 1)\n throw new Error(\n `Service \"${service.name}\" has two key-value storages in its deps, \"${found[0]![0]}\" and \"${found[1]![0]}\"; Brick needs one for its own keys. Keep one of them on this service.`,\n );\n return found[0] && frameworkSides.get(found[0][1] as object);\n}\n\nexport function useStorages(\n deps: readonly Readonly<Record<string, unknown>>[],\n): () => Promise<void> {\n const handles = new Set(\n deps.flatMap((values) =>\n Object.values(values).filter((value) =>\n frameworkSides.has(value as object),\n ),\n ) as KeyValueStorage[],\n );\n for (const handle of handles) users.set(handle, (users.get(handle) ?? 0) + 1);\n let released = false;\n return async () => {\n if (released) return;\n released = true;\n const unused = [...handles].filter((handle) => {\n const left = users.get(handle)! - 1;\n users.set(handle, left);\n return left === 0;\n });\n await Promise.all(unused.map((handle) => handle.close()));\n };\n}\n\n/** Options of the `redis()` storage driver. */\nexport interface RedisStorageOptions {\n /** Defaults to `REDIS_URL`, then `redis://localhost:6379`. */\n url?: string;\n /** Put in front of every key, Brick's own included, so two apps or environments can share one Redis database. */\n prefix?: string;\n}\n\nconst NOT_A_COUNTER = \"BRICK_NOT_A_COUNTER\";\nconst INCREMENT = `local n = redis.pcall('INCR', KEYS[1])\nif type(n) == 'table' and n.err then\n if string.find(n.err, '^WRONGTYPE') or string.find(n.err, 'not an integer') then return redis.error_reply('${NOT_A_COUNTER}') end\n return n\nend\nlocal t = redis.call('PTTL', KEYS[1])\nif t < 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) t = tonumber(ARGV[1]) end\nreturn {n, t}`;\nconst PUT_IF_ABSENT = `if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', ARGV[2]) then return {1, ARGV[1]} end\nreturn {0, redis.call('GET', KEYS[1])}`;\nconst COMPARE_AND_DELETE = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end\nreturn 0`;\nconst TIMED_OUT = Symbol(\"timed out\");\nconst UNAVAILABLE_REPLY =\n /^(LOADING|READONLY|OOM|BUSY|MASTERDOWN|CLUSTERDOWN|NOREPLICAS|MISCONF|TRYAGAIN)\\b/;\n\n/**\n * Key-value storage in Redis, through Bun's built-in client. Connects on first\n * use and reconnects by itself. While Redis is unreachable, calls reject with\n * `StorageUnavailableError`: the first after about a second, the rest at once.\n * A command Redis doesn't answer within a second rejects the same way, and the\n * connection is dropped so the next call opens a fresh one.\n *\n * @param options - `url`: defaults to `REDIS_URL`, then `redis://localhost:6379`.\n * `prefix`: put in front of every key, to share one Redis database between apps.\n */\nexport function redis(options: RedisStorageOptions = {}): KeyValueDriver {\n const prefix = options.prefix ?? \"\";\n let conn: ReturnType<typeof connection> | undefined;\n let down = false;\n const send = async (command: string, args: string[]): Promise<any> => {\n const current = (conn ??= connection(options.url, () => {\n down = false;\n }));\n if (!down) await current.opened(REDIS_WAIT_MS);\n const closedMeanwhile = () => conn !== current;\n const client = current.get();\n if (!client) {\n if (!closedMeanwhile()) down = true;\n throw new StorageUnavailableError(\"Storage: Redis is unreachable\", {\n cause: current.failure(),\n });\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n client.send(command, args),\n new Promise((_, reject) => {\n timer = setTimeout(reject, REDIS_WAIT_MS, TIMED_OUT);\n }),\n ]);\n } catch (error) {\n if (error === TIMED_OUT) {\n if (!closedMeanwhile()) {\n conn = undefined;\n down = false;\n }\n current.close();\n throw new StorageUnavailableError(\n `Storage: Redis did not answer within ${REDIS_WAIT_MS} ms`,\n );\n }\n if (client.connected) {\n if (UNAVAILABLE_REPLY.test(String((error as Error)?.message)))\n throw new StorageUnavailableError(\n `Storage: Redis cannot serve the command right now (${(error as Error).message})`,\n { cause: error },\n );\n throw error;\n }\n throw new StorageUnavailableError(\n \"Storage: the Redis connection was lost\",\n { cause: error },\n );\n } finally {\n clearTimeout(timer);\n }\n };\n return {\n kind: \"key-value\",\n get: (key) => send(\"GET\", [prefix + key]),\n put: async (key, value, ttlMs) => {\n const args = [prefix + key, value];\n await send(\n \"SET\",\n ttlMs === undefined ? args : [...args, \"PX\", String(ttlMs)],\n );\n },\n putIfAbsent: async (key, value, ttlMs) => {\n const [stored, now] = await send(\"EVAL\", [\n PUT_IF_ABSENT,\n \"1\",\n prefix + key,\n value,\n String(ttlMs),\n ]);\n return { stored: stored === 1, value: now };\n },\n increment: async (key, ttlMs) => {\n const [count, expiresInMs] = await send(\"EVAL\", [\n INCREMENT,\n \"1\",\n prefix + key,\n String(ttlMs),\n ]).catch((error) => {\n throw String(error?.message).includes(NOT_A_COUNTER)\n ? notACounter(key)\n : error;\n });\n return {\n count: Number(count),\n expiresInMs: Math.max(1, Number(expiresInMs)),\n };\n },\n delete: async (key) => {\n await send(\"DEL\", [prefix + key]);\n },\n compareAndDelete: async (key, expected) =>\n (await send(\"EVAL\", [\n COMPARE_AND_DELETE,\n \"1\",\n prefix + key,\n expected,\n ])) === 1,\n close: async () => {\n conn?.close();\n conn = undefined;\n down = false;\n },\n };\n}\n\n/**\n * Key-value storage in this process's memory, for tests and local development.\n * Lost on restart and not shared between processes.\n */\nexport function memory(): KeyValueDriver {\n const entries = new Map<string, { value: string; expiresAt?: number }>();\n const readEvictingExpired = (key: string) => {\n const entry = entries.get(key);\n if (entry?.expiresAt !== undefined && entry.expiresAt <= Date.now()) {\n entries.delete(key);\n return undefined;\n }\n return entry;\n };\n const expiry = (ttlMs?: number) =>\n ttlMs === undefined ? undefined : Date.now() + ttlMs;\n return {\n kind: \"key-value\",\n get: async (key) => readEvictingExpired(key)?.value ?? null,\n put: async (key, value, ttlMs) => {\n entries.set(key, { value, expiresAt: expiry(ttlMs) });\n },\n putIfAbsent: async (key, value, ttlMs) => {\n const entry = readEvictingExpired(key);\n if (entry) return { stored: false, value: entry.value };\n entries.set(key, { value, expiresAt: expiry(ttlMs) });\n return { stored: true, value };\n },\n increment: async (key, ttlMs) => {\n const entry = readEvictingExpired(key) ?? { value: \"0\" };\n // What Redis's INCR takes: a plain integer, no spaces, signs, exponents or leading zeros.\n const count = Number(entry.value) + 1;\n if (!/^(0|-?[1-9][0-9]*)$/.test(entry.value)) throw notACounter(key);\n if (!Number.isSafeInteger(count)) throw counterOverflow(key);\n const expiresAt = entry.expiresAt ?? Date.now() + ttlMs;\n entries.set(key, { value: String(count), expiresAt });\n return { count, expiresInMs: Math.max(1, expiresAt - Date.now()) };\n },\n delete: async (key) => {\n entries.delete(key);\n },\n compareAndDelete: async (key, expected) =>\n readEvictingExpired(key)?.value === expected && entries.delete(key),\n close: async () => {},\n };\n}\n","import {\n ActionExecutionError,\n type ActionContext,\n type Service,\n} from \"./types\";\nimport { hasIdentity, identityOf } from \"./identity\";\nimport { isIPv4, isIPv6 } from \"node:net\";\nimport {\n serviceStorage,\n storageKey,\n StorageUnavailableError,\n type Counter,\n type KeyValueStorage,\n} from \"./storage\";\n\n/**\n * A limit on how often an action runs: at most `max` calls per `windowMs`, per key.\n * A fixed window, counted in the service's key-value storage.\n */\nexport interface RateLimit<TInput = any, TCtx = ActionContext> {\n /**\n * Whose calls count together: `\"actor\"` (the service's `identity` id; an\n * anonymous caller counts by IP), `\"ip\"` (the client address; skipped when\n * there is none, as in-process), or a function of the validated input and\n * the context. A function that returns `null` or `undefined` skips this\n * limit for the call.\n */\n per:\n | \"actor\"\n | \"ip\"\n | ((args: { input: TInput; ctx: TCtx }) => string | null | undefined);\n /** Calls allowed per window. */\n max: number;\n /** The window's length in milliseconds. */\n windowMs: number;\n}\n\n/** Where an app finds the client address, given the request and the socket peer: a non-empty string, or `undefined` for none. */\nexport type ClientIp = (args: {\n request: Request;\n peer: string | undefined;\n}) => string | undefined;\n\ninterface AddressSource {\n clientIp?: ClientIp;\n server: () =>\n | { requestIP(request: Request): { address: string } | null }\n | null\n | undefined;\n}\nconst SOURCE = Symbol.for(\"brickkit.addressSource\");\nconst CLIENT_REQUEST = Symbol.for(\"brickkit.clientRequest\");\n\nexport function markAddressSource(\n request: Request,\n source: AddressSource,\n): void {\n (request as any)[SOURCE] = source;\n}\n\nexport function withClientIp(request: Request, clientIp: ClientIp): void {\n const app: AddressSource | undefined = (request as any)[SOURCE];\n markAddressSource(request, { clientIp, server: app?.server ?? noServer });\n}\nconst noServer = () => undefined;\n\nexport function clientRequestOf(ctx: object): Request | undefined {\n const request: any =\n (ctx as any)[CLIENT_REQUEST] ?? (ctx as { request?: Request }).request;\n return request?.[SOURCE] ? request : undefined;\n}\n\nexport function carryClientRequest(envelope: object, from: object): void {\n const request = clientRequestOf(from);\n if (request) (envelope as any)[CLIENT_REQUEST] = request;\n}\n\n/**\n * The client address of a call as rate limits count it, or `undefined` when it\n * has none: in-process without a request, or `app.handle` without `clientIp`.\n * An IPv4-mapped or NAT64 IPv6 address counts as its IPv4 address, any other\n * IPv6 address by its /64, and every spelling of one address the same. For a\n * custom `per` that combines it with another key.\n *\n * @throws When `clientIp` returns anything but a non-empty string or `undefined`.\n */\nexport function clientAddress(ctx: object): string | undefined {\n const request = clientRequestOf(ctx);\n if (!request) return undefined;\n const source: AddressSource = (request as any)[SOURCE];\n const peer = source.server()?.requestIP(request)?.address ?? undefined;\n const ip: unknown = source.clientIp\n ? source.clientIp({ request, peer })\n : peer;\n if (ip !== undefined && (typeof ip !== \"string\" || ip === \"\"))\n throw new Error(\n `clientIp must return a non-empty string, or undefined when there is no address; it returned ${ip === \"\" ? \"an empty string\" : ip instanceof Promise ? \"a promise (it must not be async)\" : String(ip)}`,\n );\n return ip === undefined ? undefined : addressKey(ip as string);\n}\n\nfunction addressKey(address: string): string {\n const ip = address.trim().toLowerCase().replace(/%.*$/, \"\");\n if (isIPv4(ip)) return ip;\n if (!isIPv6(ip)) return address;\n const [head = \"\", tail] = ip.split(\"::\");\n const split = (part: string | undefined) => (part ? part.split(\":\") : []);\n const left = split(head);\n const right = split(tail);\n const groups = (part: string[]) =>\n part.flatMap((group) => {\n if (!group.includes(\".\")) return [parseInt(group, 16)];\n const [a, b, c, d] = group.split(\".\").map(Number) as number[];\n return [(a! << 8) | b!, (c! << 8) | d!];\n });\n const l = groups(left);\n const r = groups(right);\n const all = [...l, ...Array(8 - l.length - r.length).fill(0), ...r];\n // Mapped (::ffff:a.b.c.d) and translated (64:ff9b::a.b.c.d, RFC 6052) IPv4.\n const head6 = all.slice(0, 6).join(\":\");\n if (head6 === \"0:0:0:0:0:65535\" || head6 === \"100:65435:0:0:0:0\")\n return [all[6]! >> 8, all[6]! & 255, all[7]! >> 8, all[7]! & 255].join(\".\");\n return `${all\n .slice(0, 4)\n .map((g) => g.toString(16))\n .join(\":\")}::/64`;\n}\n\nexport function rateLimitsOf(config: {\n name: string;\n rateLimit?: RateLimit | readonly RateLimit[];\n}): readonly RateLimit[] | undefined {\n const { rateLimit } = config;\n if (rateLimit === undefined) return undefined;\n const limits: readonly RateLimit[] = Array.isArray(rateLimit)\n ? rateLimit\n : [rateLimit as RateLimit];\n if (!limits.length)\n throw new Error(\n `Action '${config.name}': rateLimit is an empty list, which limits nothing. Give it at least one limit, or remove it.`,\n );\n for (const { per, max, windowMs } of limits)\n if (\n !(per === \"actor\" || per === \"ip\" || typeof per === \"function\") ||\n !Number.isSafeInteger(max) ||\n max < 1 ||\n !Number.isSafeInteger(windowMs) ||\n windowMs < 1\n )\n throw new Error(\n `Action '${config.name}': each rateLimit needs per (\"actor\", \"ip\" or a function) and max and windowMs as positive integers`,\n );\n return limits;\n}\n\nexport function checkRateLimits(\n service: Service<any, any>,\n action: { name: string; config: { name: string; rateLimit?: any } },\n deps: Readonly<Record<string, unknown>>,\n): void {\n const limits = rateLimitsOf(action.config);\n if (!limits) return;\n if (!storageOf(service, deps)) throw noStorage(service, action.name);\n if (limits.some((limit) => limit.per === \"actor\") && !hasIdentity(service))\n throw new Error(\n `Service \"${service.name}\": action '${action.name}' limits per \"actor\", but the service declares no identity. Add identity: (ctx) => ctx.user && { id: ctx.user.id } to defineService(\"${service.name}\", { ... }).`,\n );\n}\n\nfunction storageOf(\n service: Service<any, any>,\n deps: Readonly<Record<string, unknown>>,\n): KeyValueStorage | undefined {\n return serviceStorage(service, deps) ?? serviceStorage(service);\n}\n\nfunction noStorage(service: Service<any, any>, action: string): Error {\n return new Error(\n `Service \"${service.name}\": action '${action}' declares rateLimit, but the service has no key-value storage to count in. Add one: defineService(\"${service.name}\", { deps: { cache: defineStorage({ driver: redis() }) } }).`,\n );\n}\n\ninterface Fallback {\n active: boolean;\n counters: Map<string, { count: number; expiresAt: number }>;\n probeAt: number;\n healthySince?: number;\n sweepAt: number;\n}\nconst QUIET_MS = 10_000;\nconst PROBE_MS = 1_000;\nconst SWEEP_MS = 1_000;\nconst fallbacks = new WeakMap<KeyValueStorage, Fallback>();\n\nfunction countInMemory(\n fallback: Fallback,\n key: string,\n windowMs: number,\n now: number,\n): Counter {\n if (now >= fallback.sweepAt) sweep(fallback, now);\n let entry = fallback.counters.get(key);\n if (!entry || entry.expiresAt <= now)\n fallback.counters.set(\n key,\n (entry = { count: 0, expiresAt: now + windowMs }),\n );\n entry.count++;\n return {\n count: entry.count,\n expiresInMs: Math.max(1, entry.expiresAt - now),\n };\n}\n\nfunction sweep(fallback: Fallback, now: number): void {\n for (const [key, entry] of fallback.counters)\n if (entry.expiresAt <= now) fallback.counters.delete(key);\n fallback.sweepAt = now + SWEEP_MS;\n}\n\nconst isTimeToProbe = (fallback: Fallback, now: number): boolean =>\n now >= fallback.probeAt;\n\nconst hasBeenHealthyLongEnough = (fallback: Fallback, now: number): boolean =>\n fallback.healthySince !== undefined &&\n now - fallback.healthySince >= QUIET_MS;\n\nfunction enterFallback(fallback: Fallback, now: number, cause: Error): void {\n Object.assign(fallback, {\n active: true,\n probeAt: now + PROBE_MS,\n healthySince: undefined,\n });\n console.warn(\n `[Brick-TS] Rate limits: storage is unavailable (${cause.message}); counting in this process's memory until it is back.`,\n );\n}\n\nfunction leaveFallback(fallback: Fallback): void {\n fallback.active = false;\n console.warn(\n \"[Brick-TS] Rate limits: storage is back; counting there again.\",\n );\n}\n\nfunction probe(\n storage: KeyValueStorage,\n fallback: Fallback,\n key: string,\n windowMs: number,\n): void {\n const answered = () => {\n const now = Date.now();\n fallback.healthySince ??= now;\n if (fallback.active && hasBeenHealthyLongEnough(fallback, now))\n leaveFallback(fallback);\n };\n storage.increment(key, windowMs).then(answered, (error) => {\n if (error instanceof StorageUnavailableError)\n fallback.healthySince = undefined;\n else answered();\n });\n}\n\nasync function increment(\n storage: KeyValueStorage,\n key: string,\n windowMs: number,\n): Promise<Counter> {\n let fallback = fallbacks.get(storage);\n if (fallback) {\n const now = Date.now();\n if (fallback.active) {\n if (isTimeToProbe(fallback, now)) {\n fallback.probeAt = now + PROBE_MS;\n probe(storage, fallback, key, windowMs);\n }\n return countInMemory(fallback, key, windowMs, now);\n }\n if (now >= fallback.sweepAt) {\n sweep(fallback, now);\n if (!fallback.counters.size) fallbacks.delete(storage);\n }\n }\n try {\n return await storage.increment(key, windowMs);\n } catch (error) {\n if (!(error instanceof StorageUnavailableError)) throw error;\n const now = Date.now();\n fallback = fallbacks.get(storage);\n if (!fallback)\n fallbacks.set(\n storage,\n (fallback = {\n active: false,\n counters: new Map(),\n probeAt: 0,\n sweepAt: now + SWEEP_MS,\n }),\n );\n if (!fallback.active) enterFallback(fallback, now, error);\n return countInMemory(fallback, key, windowMs, now);\n }\n}\n\nasync function keyOf(\n limit: RateLimit,\n input: unknown,\n ctx: ActionContext,\n): Promise<string[] | undefined> {\n if (typeof limit.per === \"function\") {\n const key: unknown = limit.per({ input, ctx });\n if (typeof (key as { then?: unknown } | null)?.then === \"function\") {\n Promise.resolve(key).catch(() => {});\n throw new Error(\n \"rateLimit per must return a string, null or undefined; it returned a promise (it must not be async)\",\n );\n }\n return key == null ? undefined : [\"key\", String(key)];\n }\n if (limit.per === \"actor\") {\n const identity = await identityOf(ctx);\n if (identity) return [\"actor\", identity.id];\n }\n const ip = clientAddress(ctx);\n return ip === undefined ? undefined : [\"ip\", ip];\n}\n\nexport async function enforceRateLimits(\n service: Service<any, any> | undefined,\n kind: \"action\" | \"tool\",\n action: string,\n limits: readonly RateLimit[],\n input: unknown,\n ctx: ActionContext,\n): Promise<void> {\n if (!service)\n throw new Error(\n `Action '${action}' declares rateLimit, but it is not registered on a service`,\n );\n const storage = storageOf(service, ctx.deps as any);\n if (!storage) throw noStorage(service, action);\n for (const [index, limit] of limits.entries()) {\n const key = await keyOf(limit, input, ctx);\n if (!key) continue;\n const { count, expiresInMs } = await increment(\n storage,\n storageKey(\"rate-limit\", [service.name, kind, action, index, ...key]),\n limit.windowMs,\n );\n if (count > limit.max) {\n const retryAfterSeconds = Math.max(1, Math.ceil(expiresInMs / 1000));\n throw new ActionExecutionError(\n \"RATE_LIMITED\",\n `Too many calls to '${action}'; retry in ${retryAfterSeconds} s`,\n 429,\n { retryAfterSeconds },\n );\n }\n }\n}\n","import type { BaseContext, Logger, Service } from \"./types\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\nimport { dashboardIdentity } from \"./dashboard-identity\";\nimport { attachIdentity } from \"./identity\";\nimport { carryClientRequest } from \"./rate-limit\";\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nconst EMPTY = Object.freeze({});\nconst defaultLogger: Logger = createLogger(DEFAULT_LOG_PREFIXES);\n/** Random, so ids never repeat across restarts or processes. */\nconst newId = (kind: \"tr\" | \"req\") => `${kind}_${crypto.randomUUID()}`;\n\n/**\n * The trace and request ids of an HTTP request: the caller's `x-trace-id` and\n * `x-request-id` headers, else fresh ones. Both are echoed on the response.\n */\nexport function requestIds(\n headers: Record<string, string | undefined> | undefined,\n set: { headers?: Record<string, unknown> } | undefined,\n): { traceId: string; requestId: string } {\n const traceId = headers?.[\"x-trace-id\"] || newId(\"tr\");\n const requestId = headers?.[\"x-request-id\"] || newId(\"req\");\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n return { traceId, requestId };\n}\n\n/**\n * The framework fields of an action context: what the caller gave, the rest\n * defaulted. A missing trace or request id gets a fresh `tr_`/`req_` one.\n */\nexport function baseContext(\n fields: Partial<BaseContext> & { deps?: Readonly<Record<string, unknown>> },\n): BaseContext & { deps: Readonly<Record<string, unknown>> } {\n return {\n request: fields.request ?? DEFAULT_REQUEST,\n db: fields.db,\n logger: fields.logger ?? defaultLogger,\n traceId: fields.traceId ?? newId(\"tr\"),\n requestId: fields.requestId ?? newId(\"req\"),\n services: fields.services ?? EMPTY,\n metadata: fields.metadata ?? EMPTY,\n deps: fields.deps ?? EMPTY,\n dashboard: fields.dashboard ?? dashboardIdentity(fields.request),\n };\n}\n\ntype ContextEnvelope = Pick<\n BaseContext,\n \"caller\" | \"traceId\" | \"requestId\" | \"tenantId\" | \"dashboard\"\n> & { user?: unknown };\n\nexport function pickContextEnvelope(\n context?: Partial<BaseContext> & { user?: unknown },\n): Partial<ContextEnvelope> {\n if (!context) return {};\n const envelope: Partial<ContextEnvelope> = {};\n if (context.caller !== undefined) envelope.caller = context.caller;\n if (context.user !== undefined) envelope.user = context.user;\n if (context.traceId !== undefined) envelope.traceId = context.traceId;\n if (context.requestId !== undefined) envelope.requestId = context.requestId;\n if (context.tenantId !== undefined) envelope.tenantId = context.tenantId;\n // In process only: the identity was verified when the outer request arrived.\n if (context.dashboard !== undefined) envelope.dashboard = context.dashboard;\n carryClientRequest(envelope, context);\n return envelope;\n}\n\nconst RESOLVED = Symbol(\"resolved\");\nconst OWN_DEPS = Symbol(\"ownDeps\");\n\nexport function markResolved(\n ctx: object,\n service: Service<any, any>,\n ownDeps: Readonly<Record<string, unknown>>,\n): void {\n const marked = ctx as Record<PropertyKey, unknown>;\n marked[RESOLVED] = service;\n marked[OWN_DEPS] = ownDeps;\n attachIdentity(marked, service, ownDeps);\n}\n\nexport function resolvedDeps(\n ctx: unknown,\n service: Service<any, any>,\n): Readonly<Record<string, unknown>> | undefined {\n const marked = ctx as Record<PropertyKey, any> | undefined;\n return marked?.[RESOLVED] === service ? marked[OWN_DEPS] : undefined;\n}\n\nexport function serviceOf(ctx: object): Service<any, any> | undefined {\n return (ctx as Record<PropertyKey, any>)[RESOLVED];\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport { actionMeta } from \"./action-meta\";\nimport type {\n AuditConfig,\n Action,\n ActionErrorDefinition,\n ErrorBuilder,\n RateLimits,\n Service,\n} from \"./types\";\nimport { checkRateLimits } from \"./rate-limit\";\nimport { serviceStorage } from \"./storage\";\n\n/** What a verifier sees of a delivery. */\nexport interface WebhookRequest {\n /** The body exactly as it arrived. */\n rawBody: Uint8Array;\n headers: Headers;\n url: string;\n method: string;\n}\n\n/**\n * Decides whether the provider sent a delivery. `false`, or a throw, refuses it\n * (401); `true` accepts; `{ eventId }` accepts and names the event.\n * Set `suppliesEventId` on a verifier that always returns one, so a webhook\n * needs no `eventId` option.\n */\nexport type WebhookVerifier = ((\n request: WebhookRequest,\n) =>\n | boolean\n | { eventId: string | number }\n | Promise<boolean | { eventId: string | number }>) & {\n suppliesEventId?: true;\n /** Set on a verifier that signs the body (a GET has none, so it cannot serve one). */\n signsBody?: true;\n};\n\n/** What `service.webhook` takes. */\nexport interface WebhookConfig<\n TInput extends TSchema,\n TErrors extends Record<string, ActionErrorDefinition>,\n TContext,\n> {\n /** Its route is `<method> /api/<service>/<name>` (POST by default), as for an action. */\n name: string;\n description?: string;\n /** Relative to the service, as for an action. */\n path?: string;\n /** Default `\"POST\"`. With `\"GET\"` the input is the query string. */\n method?: \"POST\" | \"GET\";\n /** Runs first, on the raw body. Nothing else runs until it accepts. */\n verify: WebhookVerifier;\n /** The payload: JSON, or a form (`application/x-www-form-urlencoded`). Properties it does not declare are dropped. */\n input: TInput;\n /**\n * The delivery's id, so one sent twice runs once: a non-empty string or a\n * safe integer (`7` and `\"7\"` are one id); anything else, `undefined`\n * included, is no id. Not needed when the verifier supplies one.\n */\n eventId?: (args: {\n input: Static<TInput>;\n headers: Headers;\n url: string;\n method: string;\n }) => string | number | undefined | Promise<string | number | undefined>;\n /** `false` runs every delivery, with no check for repeats. Else `ttlMs` is how long a handled id is remembered (default 7 days). */\n replay?: false | { ttlMs?: number };\n /** Largest body accepted, in bytes (default 1 MiB). */\n maxBodyBytes?: number;\n rateLimit?: RateLimits<Static<TInput>, TContext>;\n /** The delivery's audit row when the service's database holds an audit table: written when the handler returns, not for a refused or repeated delivery or one whose handler throws. `false` leaves it out. */\n audit?: AuditConfig<Static<TInput>>;\n errors?: TErrors;\n tags?: string[];\n /** What the provider is answered: the return value, which may be a `Response`; `{ ok: true }` for nothing. */\n execute: (params: {\n input: Static<TInput>;\n ctx: TContext;\n error: ErrorBuilder<TErrors>;\n /** `undefined` when `replay` is `false` and the delivery has no id. */\n eventId: string | undefined;\n }) => unknown;\n}\n\nexport interface WebhookDefinition {\n readonly verify: WebhookVerifier;\n readonly eventId?: WebhookConfig<any, any, any>[\"eventId\"];\n readonly replay: false | { readonly ttlMs: number };\n readonly maxBodyBytes: number;\n}\n\nexport const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;\nexport const DEFAULT_REPLAY_TTL_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport function webhookOf(\n action: object | undefined,\n): WebhookDefinition | undefined {\n return action ? actionMeta(action).webhook : undefined;\n}\n\n/** Whether an action was declared with `service.webhook`. */\nexport function isWebhook(action: object): boolean {\n return webhookOf(action) !== undefined;\n}\n\nexport function defineWebhookMeta(\n service: string,\n config: WebhookConfig<any, any, any>,\n): WebhookDefinition {\n const where = `Service \"${service}\": webhook '${config?.name}'`;\n if (typeof config?.verify !== \"function\")\n throw new Error(\n `${where} needs verify: a verifier such as hmacSignature({ secret, header }), standardWebhooks({ secret }) or twilioSignature({ authToken, url }), or your own (request) => boolean. A webhook cannot run without one.`,\n );\n if (!config.input || typeof config.input !== \"object\")\n throw new Error(\n `${where} needs input: the schema of the payload, such as t.Object({ ... }).`,\n );\n if (config.method !== undefined && ![\"POST\", \"GET\"].includes(config.method))\n throw new Error(`${where}: method must be \"POST\" or \"GET\".`);\n if (config.method === \"GET\" && config.verify.signsBody)\n throw new Error(\n `${where}: method \"GET\" has no body, and this verifier signs the body, so it would accept one signature for every query. Use twilioSignature (it signs the URL) or a verifier of your own, or method \"POST\".`,\n );\n for (const option of [\"authorize\", \"output\"])\n if ((config as object as Record<string, unknown>)[option] !== undefined)\n throw new Error(\n `${where}: ${option} is not an option of a webhook, and would be ignored. verify is the check.`,\n );\n const { maxBodyBytes = DEFAULT_MAX_BODY_BYTES, replay } = config;\n if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1)\n throw new Error(`${where}: maxBodyBytes must be a positive integer.`);\n const ttlMs =\n replay === false ? undefined : (replay?.ttlMs ?? DEFAULT_REPLAY_TTL_MS);\n if (ttlMs !== undefined && (!Number.isSafeInteger(ttlMs) || ttlMs < 1))\n throw new Error(`${where}: replay.ttlMs must be a positive integer.`);\n return {\n verify: config.verify,\n eventId: config.eventId,\n replay: ttlMs === undefined ? false : { ttlMs },\n maxBodyBytes,\n };\n}\n\nexport function checkWebhook(\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n deps: Readonly<Record<string, unknown>>,\n): void {\n const webhook = webhookOf(action);\n if (!webhook) return;\n checkRateLimits(service, action, deps);\n if (webhook.replay === false) return;\n const where = `Service \"${service.name}\": webhook '${action.name}'`;\n if (!webhook.eventId && !webhook.verify.suppliesEventId)\n throw new Error(\n `${where} has no event id to tell deliveries apart by, so a delivery sent twice would run twice. Add eventId: ({ input }) => input.id, reading an id from a field of the signed payload (an id from a header the signature does not cover only removes accidental duplicates: anyone who captured a delivery can resend it with another id), use a verifier that supplies one (standardWebhooks), or set replay: false to run every delivery.`,\n );\n if (!serviceStorage(service))\n throw new Error(\n `${where} remembers the events it has handled, but the service has no key-value storage. Add one: defineService(\"${service.name}\", { deps: { cache: defineStorage({ driver: redis() }) } }), or set replay: false.`,\n );\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst sqliteQueues = new WeakMap<object, Promise<unknown>>();\n\ninterface OpenTransaction {\n /** The handles a nested call can pass to join this transaction. */\n handles: Set<unknown>;\n commits: (() => unknown)[];\n open: boolean;\n savepoints: number;\n}\nconst active = new AsyncLocalStorage<OpenTransaction>();\n\nfunction joined(db: unknown): OpenTransaction | undefined {\n const open = active.getStore();\n return open?.open && open.handles.has(db) ? open : undefined;\n}\n\nexport function isSqliteDatabase(db: any): boolean {\n return (\n typeof db?.$client?.prepare === \"function\" &&\n typeof db?.$client?.run === \"function\"\n );\n}\n\nfunction rollbackQuietly(db: any, statement = \"ROLLBACK\"): void {\n try {\n db.$client.run(statement);\n } catch {\n return;\n }\n}\n\nasync function nested<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const commits = open.commits.length;\n try {\n if (!isSqliteDatabase(db))\n // Drizzle runs a nested transaction as a savepoint.\n return await db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n const name = `brick_${++open.savepoints}`;\n db.$client.run(`SAVEPOINT ${name}`);\n try {\n const result = await fn(db);\n db.$client.run(`RELEASE ${name}`);\n return result;\n } catch (error) {\n rollbackQuietly(db, `ROLLBACK TO ${name}`);\n rollbackQuietly(db, `RELEASE ${name}`);\n throw error;\n }\n } catch (error) {\n // Work that was rolled back must not run its commit callbacks.\n open.commits.length = commits;\n throw error;\n }\n}\n\n/**\n * Run `fn` in a database transaction: everything it writes through the `tx` it is\n * given is committed together when it returns, or undone if it throws.\n *\n * Postgres uses a real transaction on one connection. SQLite has one connection\n * and a synchronous driver, which Drizzle's own `transaction` cannot use with an\n * async callback (it would commit before the callback finished). So transactions\n * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.\n * A write made elsewhere in the process during that time, outside this helper,\n * would join the transaction; use Postgres where that matters.\n *\n * A call made inside `fn` with the `tx` it was given (on SQLite, the database\n * itself) joins the open transaction as a savepoint instead of waiting for it: a\n * nested failure undoes only the nested work, and the outer transaction decides\n * the commit. Nested calls must run one at a time.\n *\n * @param db - A Drizzle database, from `service.getDb()`.\n * @param fn - Receives the transaction handle to run queries on.\n * @returns What `fn` returned.\n * @throws What `fn` threw, after rolling back.\n */\nexport async function runInTransaction<T>(\n db: any,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const outer = joined(db);\n if (outer) return nested(db, outer, fn);\n const open: OpenTransaction = {\n handles: new Set(),\n commits: [],\n open: true,\n savepoints: 0,\n };\n let result: T;\n try {\n result = await active.run(open, () => begin(db, open, fn));\n } finally {\n open.open = false;\n }\n for (const commit of open.commits) await commit();\n return result;\n}\n\nasync function begin<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n if (!isSqliteDatabase(db)) {\n return db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n }\n\n open.handles.add(db);\n const previous = sqliteQueues.get(db) ?? Promise.resolve();\n let release!: () => void;\n const turn = new Promise<void>((resolve) => {\n release = resolve;\n });\n sqliteQueues.set(\n db,\n previous.then(() => turn),\n );\n await previous;\n try {\n db.$client.run(\"BEGIN IMMEDIATE\");\n try {\n const result = await fn(db);\n db.$client.run(\"COMMIT\");\n return result;\n } catch (error) {\n rollbackQuietly(db);\n throw error;\n }\n } finally {\n release();\n }\n}\n\n/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */\nexport function inTransaction(db: unknown): boolean {\n return joined(db) !== undefined;\n}\n\n/**\n * Run `fn` once the transaction that `db` belongs to has committed, or now when\n * `db` is not in one opened by `runInTransaction`. It never runs when that\n * transaction, or the savepoint it was queued in, rolls back. An error it throws\n * reaches the caller of the outermost `runInTransaction`, after the commit.\n *\n * @param db - The handle the work ran on: a `tx`, or a database.\n * @param fn - The side effect, such as clearing a cache.\n */\nexport async function onTransactionCommit(\n db: unknown,\n fn: () => unknown,\n): Promise<void> {\n const open = joined(db);\n if (open) open.commits.push(fn);\n else await fn();\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n bigserial,\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\";\nimport { actionMeta } from \"./action-meta\";\nimport { serviceOf } from \"./context\";\nimport { sharedAcrossCoreCopies } from \"./deps\";\nimport {\n inTransaction,\n isSqliteDatabase,\n onTransactionCommit,\n runInTransaction,\n} from \"./events/transaction\";\nimport { identityOf } from \"./identity\";\nimport { actionMethod } from \"./routes\";\nimport { portOf, type ServicePort } from \"./service-port\";\nimport type { Action, ActionContext } from \"./types\";\n\nconst AUDIT = Symbol.for(\"brick.audit\");\n\nfunction sqliteAudit(name: string) {\n return sqliteTable(name, {\n seq: sqliteInteger(\"seq\").primaryKey({ autoIncrement: true }),\n id: sqliteText(\"id\").notNull().unique(),\n at: sqliteInteger(\"at\", { mode: \"timestamp_ms\" }).notNull(),\n service: sqliteText(\"service\").notNull(),\n action: sqliteText(\"action\").notNull(),\n resource: sqliteText(\"resource\"),\n recordId: sqliteText(\"record_id\"),\n actorId: sqliteText(\"actor_id\"),\n actorLabel: sqliteText(\"actor_label\"),\n tenant: sqliteText(\"tenant\"),\n traceId: sqliteText(\"trace_id\"),\n requestId: sqliteText(\"request_id\"),\n meta: sqliteText(\"meta\", { mode: \"json\" }),\n });\n}\n\nfunction postgresAudit(name: string) {\n return pgTable(name, {\n seq: bigserial(\"seq\", { mode: \"number\" }).primaryKey(),\n id: pgText(\"id\").notNull().unique(),\n at: timestamp(\"at\", { withTimezone: true }).notNull(),\n service: pgText(\"service\").notNull(),\n action: pgText(\"action\").notNull(),\n resource: pgText(\"resource\"),\n recordId: pgText(\"record_id\"),\n actorId: pgText(\"actor_id\"),\n actorLabel: pgText(\"actor_label\"),\n tenant: pgText(\"tenant\"),\n traceId: pgText(\"trace_id\"),\n requestId: pgText(\"request_id\"),\n meta: jsonb(\"meta\"),\n });\n}\n\n/** The audit table of a SQLite database. */\nexport type SQLiteAuditTable = ReturnType<typeof sqliteAudit>;\n/** The audit table of a Postgres database. */\nexport type PostgresAuditTable = ReturnType<typeof postgresAudit>;\n/** An audit table, made by `auditTable`. */\nexport type AuditTable = SQLiteAuditTable | PostgresAuditTable;\n\n/**\n * The audit table: one row per change, saying who made it, what ran and on\n * which record. A service whose database holds it records every create, update\n * and delete, every command, and every other action that is not a `GET`.\n * Brick only ever inserts into it; the docs give the trigger that makes the\n * database refuse anything else.\n *\n * Brick does not create tables for you. Put this in the schema of the database\n * and your migration tool (such as drizzle-kit) creates it. The service must\n * declare an `identity` hook: that is where the actor comes from.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_audit`.\n * @returns A Drizzle table, which you can also read with a resource of your own.\n * @example\n * import { auditTable, defineDatabase } from \"@brickkit/core\";\n *\n * export const auditLog = auditTable(\"postgres\");\n * export const database = defineDatabase({\n * engine: \"postgres\",\n * tables: { orders, auditLog },\n * });\n */\nexport function auditTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteAuditTable;\nexport function auditTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresAuditTable;\nexport function auditTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): AuditTable {\n const name = options.name ?? \"brick_audit\";\n const table = engine === \"sqlite\" ? sqliteAudit(name) : postgresAudit(name);\n Object.defineProperty(table, AUDIT, { value: { engine } });\n return table;\n}\n\n/** Whether a value is an audit table made by `auditTable`. */\nexport function isAuditTable(value: unknown): value is AuditTable {\n return typeof value === \"object\" && value !== null && AUDIT in value;\n}\n\ninterface AuditOptions {\n resource?: string;\n record?: (args: { input: any; result: any }) => unknown;\n}\n\nexport interface AuditStage {\n readonly service: ServicePort<any, any>;\n readonly table: AuditTable;\n readonly action: string;\n readonly recordsInOwnTransaction: boolean;\n readonly resource?: string;\n readonly record?: AuditOptions[\"record\"];\n}\n\nexport function auditStage(\n service: ServicePort<any, any>,\n action: Action<any, any, any, any>,\n): AuditStage | undefined {\n const table = service.getAuditTable();\n const config = action.config as { audit?: false | AuditOptions };\n if (!table || config.audit === false) return undefined;\n const { audit: mode, resourceAction } = actionMeta(action);\n if (mode === \"none\" || (!mode && actionMethod(action) === \"GET\"))\n return undefined;\n return {\n service,\n table,\n action: action.name,\n recordsInOwnTransaction: mode === \"inline\",\n resource: config.audit?.resource ?? resourceAction?.resource,\n record:\n config.audit?.record ??\n (resourceAction?.record ? ({ input }) => input.id : undefined),\n };\n}\n\ninterface Call {\n readonly audit: AuditStage;\n written: boolean;\n}\nconst calls = sharedAcrossCoreCopies(\n \"brickkit.audit.calls\",\n () => new AsyncLocalStorage<Call>(),\n);\n\nexport function runUnaudited<T>(run: () => T): T {\n return calls.getStore() ? calls.exit(run) : run();\n}\n\nexport interface Entry {\n action: string;\n resource?: string;\n recordId?: unknown;\n meta?: unknown;\n}\n\nfunction recordIdText(id: unknown): string | null {\n if (id === undefined || id === null) return null;\n if (typeof id === \"string\") return id;\n if (typeof id === \"number\" || typeof id === \"bigint\") return String(id);\n return JSON.stringify(id) ?? null;\n}\n\nasync function auditRow(\n ctx: { traceId?: string; requestId?: string },\n target: Pick<AuditStage, \"service\">,\n entry: Entry,\n) {\n const who = await identityOf(ctx);\n return {\n id: crypto.randomUUID(),\n at: new Date(),\n service: target.service.name,\n action: entry.action,\n resource: entry.resource ?? null,\n recordId: recordIdText(entry.recordId),\n actorId: who?.id ?? null,\n actorLabel: who?.label ?? null,\n tenant: who?.tenant ?? null,\n traceId: ctx.traceId ?? null,\n requestId: ctx.requestId ?? null,\n meta: entry.meta ?? null,\n };\n}\n\nfunction insertOutsideOtherRequestsTransactions<T>(\n db: any,\n fn: (handle: any) => Promise<T>,\n): Promise<T> {\n return isSqliteDatabase(db) && !inTransaction(db)\n ? runInTransaction(db, fn)\n : fn(db);\n}\n\nasync function writeAudit(\n handle: any,\n ctx: { traceId?: string; requestId?: string },\n target: Pick<AuditStage, \"service\" | \"table\">,\n entry: Entry,\n): Promise<void> {\n await handle.insert(target.table).values(await auditRow(ctx, target, entry));\n}\n\nfunction resolveActorBeforeAction(ctx: ActionContext) {\n return identityOf(ctx);\n}\n\nfunction buildRow(audit: AuditStage, ctx: ActionContext) {\n return auditRow(ctx, audit, {\n action: audit.action,\n resource: audit.resource,\n });\n}\n\nfunction setRecordIdOf(\n row: Awaited<ReturnType<typeof auditRow>>,\n audit: AuditStage,\n input: unknown,\n result: unknown,\n) {\n row.recordId = recordIdText(audit.record?.({ input, result }));\n}\n\nexport async function runAudited(\n audit: AuditStage,\n input: unknown,\n ctx: ActionContext,\n run: () => Promise<unknown>,\n): Promise<unknown> {\n await resolveActorBeforeAction(ctx);\n const call: Call = { audit, written: false };\n const result = await calls.run(call, run);\n if (!audit.recordsInOwnTransaction && !call.written) {\n let row: Awaited<ReturnType<typeof auditRow>> | undefined;\n try {\n row = await buildRow(audit, ctx);\n setRecordIdOf(row, audit, input, result);\n await insertOutsideOtherRequestsTransactions(ctx.db, (tx) =>\n tx.insert(audit.table).values(row),\n );\n } catch (error) {\n ctx.logger?.error?.(\n `audit: '${audit.action}' ran but its audit row was not written`,\n row,\n error,\n );\n }\n }\n return result;\n}\n\nexport function entryOf(\n audit: AuditStage,\n input: unknown,\n result: unknown,\n): Entry {\n return {\n action: audit.action,\n resource: audit.resource,\n recordId: audit.record?.({ input, result }),\n };\n}\n\nexport function inlineAudit(): AuditStage | undefined {\n const audit = calls.getStore()?.audit;\n return audit?.recordsInOwnTransaction ? audit : undefined;\n}\n\nexport function recordInline(\n audit: AuditStage,\n tx: unknown,\n ctx: ActionContext,\n entry: Entry,\n): Promise<void> {\n return writeAudit(tx, ctx, audit, entry);\n}\n\nfunction commitsWithBrickTransaction(tx: unknown, ctx: ActionContext) {\n return tx === ctx.db || inTransaction(tx);\n}\n\n/**\n * Record a change of your own from an action: for what Brick cannot see, or to\n * add `meta`. By default the row is inserted at once. Pass the `tx` of a\n * transaction you have open to commit it with your writes instead; once `tx`\n * commits it is the record of this call, and Brick does not add the automatic row.\n *\n * Brick copies no input or output into the log: `meta` holds what you pass.\n *\n * @param ctx - The action context: it names the service and the actor.\n * @param entry - `action` defaults to the running action's name, and is needed\n * in an action that is not itself recorded (a `GET`, `audit: false`).\n * `resource` and `recordId` say which record; `meta` is JSON of your choosing.\n * @param options - `tx`: an open transaction on the service's database.\n * @throws When `ctx` is not from an action of a service whose database holds an\n * audit table (a listener, a schedule or a workflow step has no such context),\n * or when `action` is missing.\n * @example\n * await runInTransaction(ctx.db, async (tx) => {\n * await tx.update(orders).set({ status: \"refunded\" }).where(eq(orders.id, input.orderId));\n * await recordAudit(ctx, { resource: \"order\", recordId: input.orderId, meta: { reason: input.reason } }, { tx });\n * });\n */\nexport async function recordAudit(\n ctx: ActionContext,\n entry: {\n action?: string;\n resource?: string;\n recordId?: string | number;\n meta?: unknown;\n },\n options: { tx?: unknown } = {},\n): Promise<void> {\n const service = serviceOf(ctx);\n const table = service && portOf(service).getAuditTable();\n if (!service || !table)\n throw new Error(\n \"recordAudit needs the ctx of an action of a service whose database holds an audit table\",\n );\n const call = calls.getStore();\n const action = entry.action ?? call?.audit.action;\n if (!action)\n throw new Error(\n \"recordAudit needs an action: it defaults to the running action only when that action is recorded\",\n );\n const target = { service: portOf(service), table };\n const named = { ...entry, action };\n if (options.tx === undefined)\n await insertOutsideOtherRequestsTransactions(ctx.db, (tx) =>\n writeAudit(tx, ctx, target, named),\n );\n else {\n await writeAudit(options.tx, ctx, target, named);\n if (call && commitsWithBrickTransaction(options.tx, ctx))\n await onTransactionCommit(options.tx, () => (call.written = true));\n }\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type Action,\n type ActionContext,\n type Logger,\n type ValidationErrorItem,\n} from \"../types\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport { toErrorResponse } from \"../error-response\";\nimport { recordWebhook } from \"../telemetry\";\nimport {\n serviceStorage,\n StorageUnavailableError,\n storageKey,\n type FrameworkStorage,\n} from \"../storage\";\nimport { webhookOf, type WebhookDefinition } from \"../webhook\";\nimport { baseContext, markResolved, requestIds } from \"../context\";\nimport { scopeFiles } from \"../file-storage\";\nimport type { ServicePort } from \"../service-port\";\nimport { enforceRateLimits, rateLimitsOf } from \"../rate-limit\";\nimport {\n auditStage,\n runAudited,\n runUnaudited,\n type AuditStage,\n} from \"../audit\";\nimport { withRedaction, type Sensitivity } from \"../sensitive\";\nimport type { Coercion, RouteIR } from \"./ir\";\n\n/*\n * The action pipeline, as stages: request ids → read input → validate →\n * rate limit → authorize → [audit] → execute → validate output → map error. `bindRoute` runs them\n * for an HTTP route; `action.execute` runs the same stages in-process.\n */\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\n/** @deprecated `brick build` no longer emits handler factories; see `bindCompiledApplication`. */\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\ninterface Checker {\n Check(value: unknown): boolean;\n Errors(value: unknown): Iterable<any>;\n}\n\n/** Everything one route needs to answer a request, worked out once at startup. */\nexport interface CompiledRoutePlan {\n readonly route: RouteIR;\n readonly service: ServicePort;\n readonly action: Action<any, any, any, any>;\n readonly execute: (params: any) => unknown;\n readonly authorize?: (params: any) => boolean | Promise<boolean>;\n readonly contextHook?: (baseCtx: any) => unknown;\n readonly inputChecker?: Checker;\n readonly outputChecker?: Checker;\n readonly sensitive?: Sensitivity;\n /** A plugin's check that runs before `inputChecker`. */\n readonly checkInput?: (input: unknown) => ValidationErrorItem[] | undefined;\n readonly errorBuilder: unknown;\n readonly logger: Logger;\n readonly cachedDb: unknown;\n /** The deps of the plugin install that created the action; else the service's. */\n readonly deps?: Readonly<Record<string, unknown>>;\n}\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true; // NOSONAR\n return false;\n}\n\n/** One source alone is the input as it is; several merge, later ones winning. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction coerceScalar(value: unknown, type: Coercion | undefined) {\n if (typeof value !== \"string\") return value;\n if (type === \"number\") {\n const number = Number(value);\n return Number.isNaN(number) ? value : number;\n }\n if (type === \"boolean\") {\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n }\n if (type === \"json\") {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n }\n return value;\n}\n\nfunction coerceQueryValue(\n value: unknown,\n { key, type, items }: RouteIR[\"coercions\"][number],\n request: Request | undefined,\n) {\n if (type !== \"array\") return coerceScalar(value, type);\n const values = request ? new URL(request.url).searchParams.getAll(key) : [];\n const list = values.length ? values : Array.isArray(value) ? value : [value];\n return list.map((item) => coerceScalar(item, items));\n}\n\nexport const BODY_TOO_LARGE = Symbol(\"brick.bodyTooLarge\");\n\nexport function bodyLimitParser(limit: number) {\n return ({ request }: { request: Request }) =>\n Number(request.headers.get(\"content-length\")) > limit\n ? BODY_TOO_LARGE\n : undefined;\n}\n\nexport function rawBodyParser(limit: number) {\n return async ({ request }: { request: Request }) => {\n if (Number(request.headers.get(\"content-length\")) > limit)\n return BODY_TOO_LARGE;\n const chunks: Uint8Array[] = [];\n let size = 0;\n if (request.body)\n for await (const chunk of request.body as AsyncIterable<Uint8Array>) {\n size += chunk.byteLength;\n if (size > limit) return BODY_TOO_LARGE;\n chunks.push(chunk);\n }\n return new Uint8Array(Buffer.concat(chunks));\n };\n}\n\n/** The action's input from the path, query and body, coerced by its schema. */\nexport function readInput(\n route: RouteIR,\n { params, body, query, request }: any,\n): unknown {\n if (body === BODY_TOO_LARGE)\n throw new ActionExecutionError(\n \"PAYLOAD_TOO_LARGE\",\n `Request body exceeds ${route.bodyLimit} bytes`,\n 413,\n );\n if (!route.input) return undefined;\n let coercedQuery = query;\n let coercedParams = params;\n let coercedBody = body;\n if (route.coercions.length) {\n if (query) {\n coercedQuery = { ...query };\n for (const coercion of route.coercions)\n if (query[coercion.key] !== undefined)\n coercedQuery[coercion.key] = coerceQueryValue(\n query[coercion.key],\n coercion,\n request,\n );\n }\n // Form fields arrive as strings, and a single file as itself, like query values.\n if (\n body &&\n request?.headers.get(\"content-type\")?.startsWith(\"multipart/form-data\")\n ) {\n coercedBody = { ...body };\n for (const coercion of route.coercions)\n if (body[coercion.key] !== undefined)\n coercedBody[coercion.key] = coerceQueryValue(\n body[coercion.key],\n coercion,\n undefined,\n );\n }\n for (const { key, type } of route.coercions) {\n if (type !== \"number\" || typeof params?.[key] !== \"string\") continue;\n const value = Number(params[key]);\n if (Number.isNaN(value)) continue;\n if (coercedParams === params) coercedParams = { ...params };\n coercedParams[key] = value;\n }\n }\n const input = route.readLike\n ? mergeInput(coercedQuery, coercedParams, coercedBody)\n : mergeInput(coercedParams, coercedBody, coercedQuery);\n return input === undefined &&\n (route.inputSchema as { type?: string } | undefined)?.type === \"object\"\n ? {}\n : input;\n}\n\n// Generic pre-validation nesting cap for parsed HTTP input. Compiled input\n// validators recurse, so unbounded nesting (e.g. a 20k-deep filter object)\n// would throw RangeError (HTTP 500) instead of failing validation with a\n// 400. The walk is iterative and far above legitimate depths (a max-depth\n// CRUD filter is ~45 levels of JSON).\nconst MAX_INPUT_DEPTH = 128;\nexport function inputTooDeep(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const stack: { node: unknown; depth: number }[] = [{ node: value, depth: 0 }];\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (depth > MAX_INPUT_DEPTH) return true;\n if (node && typeof node === \"object\") {\n const children = Array.isArray(node) ? node : Object.values(node);\n for (const child of children)\n if (child && typeof child === \"object\")\n stack.push({ node: child, depth: depth + 1 });\n }\n }\n return false;\n}\n\n/** The error for input (400) or output (500) that fails its schema. */\nexport function invalid(\n action: string,\n stage: \"input\" | \"output\",\n errors: ValidationErrorItem[],\n): ValidationError {\n return new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction validate(\n check: Checker,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n throw invalid(\n action,\n stage,\n Array.from(check.Errors(value), ({ path, message }) => ({ path, message })),\n );\n}\n\nfunction validateInput(\n check: Checker,\n input: unknown,\n action: string,\n checkInput: CompiledRoutePlan[\"checkInput\"],\n) {\n const errors = checkInput?.(input);\n if (errors) throw invalid(action, \"input\", errors);\n if (inputTooDeep(input))\n throw invalid(action, \"input\", [\n { path: \"\", message: \"Input exceeds maximum nesting depth\" },\n ]);\n validate(check, input, action, \"input\");\n}\n\n/** A refused `authorize`: 401 without a user, 403 with one. */\nexport function deny(action: string, user: unknown): never {\n throw new ActionExecutionError(\n user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${action}'`,\n user == null ? 401 : 403,\n );\n}\n\n/** Runs `authorize`, if any, and denies the call when it refuses. */\nasync function authorizeCall(\n authorize: ((params: any) => unknown) | undefined,\n ctx: { user?: unknown },\n input: unknown,\n action: string,\n): Promise<void> {\n if (authorize && !(await authorize({ ctx, input, user: ctx.user })))\n deny(action, ctx.user);\n}\n\n/** What a call runs once its context is ready. */\nexport interface Stages {\n readonly name: string;\n readonly dashboardOnly?: boolean;\n /** @throws The input's validation error. */\n readonly checkInput: (input: unknown) => void;\n readonly rateLimit?: (input: unknown, ctx: any) => Promise<void>;\n readonly authorize?: (params: any) => unknown;\n readonly audit?: AuditStage;\n readonly execute: (params: any) => unknown;\n readonly errorBuilder: unknown;\n /** @throws The output's validation error; else returns the output. */\n readonly checkOutput: (result: unknown) => unknown;\n readonly sensitive?: Sensitivity;\n}\n\n/** The stage order of every call, over HTTP and in-process: check input → rate limit → authorize → execute → check output. */\nexport async function runStages(\n stages: Stages,\n input: unknown,\n ctx: { user?: unknown; dashboard?: unknown },\n): Promise<unknown> {\n if (stages.dashboardOnly && !ctx.dashboard)\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Action '${stages.name}' is only for the dashboard`,\n 401,\n );\n stages.checkInput(input);\n stages.sensitive?.input(input);\n if (stages.rateLimit) await stages.rateLimit(input, ctx);\n await authorizeCall(stages.authorize, ctx, input, stages.name);\n const output = stages.audit\n ? await runAudited(stages.audit, input, ctx as ActionContext, async () =>\n stages.checkOutput(\n await stages.execute({ input, ctx, error: stages.errorBuilder }),\n ),\n )\n : stages.checkOutput(\n await runUnaudited(() =>\n stages.execute({ input, ctx, error: stages.errorBuilder }),\n ),\n );\n return stages.sensitive\n ? stages.sensitive.output(output, input, ctx)\n : output;\n}\n\nfunction mapError(\n err: unknown,\n set: any,\n options: { logger: Logger; requestId: string },\n) {\n const response = toErrorResponse(err, options);\n set.status = response.status;\n const retry = (\n response.details as { retryAfterSeconds?: unknown } | undefined\n )?.retryAfterSeconds;\n if (response.status === 429 && Number.isFinite(retry))\n set.headers[\"retry-after\"] = String(\n BigInt(Math.max(1, Math.ceil(retry as number))),\n );\n return response;\n}\n\nconst isThenable = (value: any): value is PromiseLike<unknown> =>\n value != null && typeof value.then === \"function\";\n\n/** The context of one HTTP request, with the trace and request id headers set. */\nfunction requestContext(\n plan: CompiledRoutePlan,\n { headers, request, set }: any,\n): ActionContext & { requestId: string } {\n const ctx = baseContext({\n ...requestIds(headers, set),\n request: request instanceof Request ? request : undefined,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n metadata: { headers },\n // resolveServiceContext's rule: the hook sees the service's deps; a plugin's action then gets its own.\n deps: plan.contextHook\n ? plan.service.deps\n : (plan.deps ?? plan.service.deps),\n });\n if (!plan.contextHook) resolveServiceDeps(ctx, plan);\n return ctx as ActionContext & { requestId: string };\n}\n\nconst HANDLED = \"handled\";\nconst IN_FLIGHT_CLAIM_MS = 5 * 60_000;\n\nconst eventIdFrom = (value: unknown): string | undefined =>\n Number.isSafeInteger(value)\n ? String(value)\n : typeof value === \"string\" && value\n ? value\n : undefined;\n\nconst refuse = (code: string, message: string, status: number) =>\n new ActionExecutionError(code, message, status);\n\nfunction fieldsOf(params: URLSearchParams): Record<string, unknown> {\n const grouped = new Map<string, string[]>();\n for (const [name, value] of params)\n grouped.set(name, [...(grouped.get(name) ?? []), value]);\n return Object.fromEntries(\n [...grouped].map(([name, values]) => [\n name,\n values.length > 1 ? values : values[0],\n ]),\n );\n}\n\nfunction webhookInput(route: RouteIR, request: Request, rawBody: Uint8Array) {\n const text = new TextDecoder().decode(rawBody);\n const form =\n route.method === \"GET\"\n ? new URL(request.url).searchParams\n : /^application\\/x-www-form-urlencoded/i.test(\n request.headers.get(\"content-type\") ?? \"\",\n )\n ? new URLSearchParams(text)\n : undefined;\n if (form) return readInput(route, { query: fieldsOf(form) });\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n throw invalid(route.action, \"input\", [\n { path: \"\", message: \"Body is not valid JSON\" },\n ]);\n }\n}\n\nfunction bindWebhook(plan: CompiledRoutePlan): CompiledHandler {\n const { execute } = plan;\n const name = plan.route.action;\n const webhook = webhookOf(plan.action)!;\n const limits = rateLimitsOf(plan.action.config);\n const audit = auditStage(plan.service, plan.action);\n const storage = webhook.replay ? serviceStorage(plan.service) : undefined;\n if (webhook.replay && !storage)\n throw new Error(\n `Webhook '${name}' remembers the events it has handled, but its service has no key-value storage`,\n );\n const brickWebhook = async (context: any) => {\n const delivery: Delivery = {\n plan,\n webhook,\n storage,\n limits,\n request: context.request,\n ctx: requestContext(plan, context),\n outcome: \"failed\",\n };\n try {\n rejectOversizedBody(delivery, context.body);\n const rawBody = rawBodyOf(context.body);\n await verifyDelivery(delivery, rawBody);\n const input = parseAndCheckInput(delivery, rawBody);\n plan.sensitive?.input(input);\n await resolveEventId(delivery, input);\n if ((await claimEvent(delivery)) === ALREADY_HANDLED)\n return { duplicate: true };\n\n let result: unknown;\n try {\n await resolveContext(delivery);\n await enforceWebhookRateLimits(delivery, input);\n const run = () =>\n execute({\n input,\n ctx: delivery.ctx,\n error: plan.errorBuilder,\n eventId: delivery.eventId,\n });\n result = audit\n ? await runAudited(audit, input, delivery.ctx, async () => run())\n : await runUnaudited(run);\n if (plan.sensitive && !(result instanceof Response))\n result = await plan.sensitive.output(result, input, delivery.ctx);\n } catch (error) {\n await releaseClaim(delivery);\n throw error;\n }\n await settleClaim(delivery, result);\n return result === undefined ? { ok: true } : result;\n } catch (err) {\n return mapError(err, context.set, delivery.ctx);\n } finally {\n recordWebhook(name, delivery.eventId, delivery.outcome);\n }\n };\n return plan.sensitive\n ? (context) => withRedaction(() => brickWebhook(context))\n : brickWebhook;\n}\n\ninterface Claim {\n readonly key: string;\n readonly mine: string;\n}\ninterface Delivery {\n readonly plan: CompiledRoutePlan;\n readonly webhook: WebhookDefinition;\n readonly storage: FrameworkStorage | undefined;\n readonly limits: ReturnType<typeof rateLimitsOf>;\n readonly request: Request;\n readonly ctx: ActionContext & { requestId: string };\n outcome: string;\n eventId?: string;\n claim?: Claim;\n}\n\nconst ALREADY_HANDLED = Symbol(\"alreadyHandled\");\n\nfunction rejectOversizedBody(delivery: Delivery, body: unknown) {\n if (body !== BODY_TOO_LARGE) return;\n delivery.outcome = \"too_large\";\n throw refuse(\n \"PAYLOAD_TOO_LARGE\",\n `Request body exceeds ${delivery.webhook.maxBodyBytes} bytes`,\n 413,\n );\n}\n\nconst rawBodyOf = (body: unknown) =>\n body instanceof Uint8Array ? body : new Uint8Array();\n\nfunction logVerifierThrowWithoutItsMessage(\n { plan, ctx }: Delivery,\n error: unknown,\n) {\n plan.logger.warn(\"A webhook verifier threw, so its delivery was refused\", {\n service: plan.service.name,\n webhook: plan.route.action,\n error: error instanceof Error ? error.constructor.name : typeof error,\n requestId: ctx.requestId,\n });\n}\n\nasync function verifyDelivery(delivery: Delivery, rawBody: Uint8Array) {\n const { webhook, request } = delivery;\n let verdict: unknown;\n try {\n verdict = await webhook.verify({\n rawBody,\n headers: request.headers,\n url: request.url,\n method: request.method,\n });\n } catch (error) {\n logVerifierThrowWithoutItsMessage(delivery, error);\n verdict = false;\n }\n const given = eventIdFrom((verdict as { eventId?: unknown } | null)?.eventId);\n if (verdict !== true && !given) {\n delivery.outcome = \"refused\";\n throw refuse(\"UNAUTHORIZED\", \"Webhook verification failed\", 401);\n }\n delivery.eventId = verdict === true ? undefined : given;\n}\n\nfunction parseAndCheckInput(delivery: Delivery, rawBody: Uint8Array) {\n const { plan, request } = delivery;\n const { route, inputChecker, checkInput } = plan;\n delivery.outcome = \"invalid\";\n let input = webhookInput(route, request, rawBody);\n if (inputChecker)\n validateInput(inputChecker, input, route.action, checkInput);\n input = Value.Clean(plan.action.config.input, input);\n delivery.outcome = \"failed\";\n return input;\n}\n\nasync function resolveEventId(delivery: Delivery, input: unknown) {\n const { webhook, request } = delivery;\n delivery.eventId ??= eventIdFrom(\n await webhook.eventId?.({\n input,\n headers: request.headers,\n url: request.url,\n method: request.method,\n }),\n );\n}\nasync function claimEvent(delivery: Delivery) {\n const { plan, storage, eventId } = delivery;\n if (!storage) return;\n if (!eventId) {\n delivery.outcome = \"no_event_id\";\n throw refuse(\"BAD_REQUEST\", \"The delivery has no event id\", 400);\n }\n const claim = (delivery.claim = {\n key: storageKey(\"webhook\", [plan.service.name, plan.route.action, eventId]),\n mine: `pending:${crypto.randomUUID()}`,\n });\n try {\n const claimed = await storage.putIfAbsent(\n claim.key,\n claim.mine,\n IN_FLIGHT_CLAIM_MS,\n );\n if (claimed.stored) return;\n if (claimed.value === HANDLED) {\n delivery.outcome = \"duplicate\";\n return ALREADY_HANDLED;\n }\n delivery.outcome = \"in_flight\";\n throw refuse(\n \"CONFLICT\",\n \"Another delivery of this event is being handled; retry later\",\n 409,\n );\n } catch (error) {\n if (!(error instanceof StorageUnavailableError)) throw error;\n releaseClaim(delivery);\n delivery.outcome = \"unavailable\";\n throw new ActionExecutionError(\n \"SERVICE_UNAVAILABLE\",\n \"Webhook storage is unavailable; retry later\",\n 503,\n undefined,\n { cause: error },\n );\n }\n}\n\nasync function resolveContext({ plan, ctx }: Delivery) {\n if (!plan.contextHook) return;\n const extra = await plan.contextHook(ctx);\n if (extra) Object.assign(ctx, extra);\n resolveServiceDeps(ctx, plan);\n}\n\nasync function enforceWebhookRateLimits(\n { plan, limits, ctx }: Delivery,\n input: unknown,\n) {\n if (limits)\n await enforceRateLimits(\n plan.service,\n \"action\",\n plan.route.action,\n limits,\n input,\n ctx,\n );\n}\nasync function releaseClaim({ storage, claim }: Delivery) {\n await storage?.compareAndDelete(claim!.key, claim!.mine).catch(() => {});\n}\nasync function settleClaim(delivery: Delivery, result: unknown) {\n const { plan, webhook, storage, claim, ctx } = delivery;\n const failed = result instanceof Response && result.status >= 400;\n if (storage && failed) await releaseClaim(delivery);\n else if (storage && webhook.replay)\n await storage\n .put(claim!.key, HANDLED, webhook.replay.ttlMs)\n .catch((error) =>\n plan.logger.warn(\n \"Webhook handled, but its id was not recorded; a retry may run it again\",\n { requestId: ctx.requestId },\n error,\n ),\n );\n delivery.outcome = failed ? \"failed\" : \"processed\";\n}\n\nfunction resolveServiceDeps(ctx: any, plan: CompiledRoutePlan) {\n markResolved(ctx, plan.service, plan.service.deps);\n ctx.deps = scopeFiles(plan.deps ?? plan.service.deps, ctx);\n}\n\n/** The HTTP handler of one route: the pipeline's stages, synchronous when no stage needs to wait. */\nexport function bindRoute(plan: CompiledRoutePlan): CompiledHandler {\n if (plan.route.kind === \"webhook\") return bindWebhook(plan);\n const {\n route,\n execute,\n contextHook,\n authorize,\n inputChecker,\n outputChecker,\n checkInput,\n errorBuilder,\n } = plan;\n const name = route.action;\n const limits = rateLimitsOf(plan.action.config);\n const audit = auditStage(plan.service, plan.action);\n const stages: Stages = {\n name,\n dashboardOnly: plan.action.config.dashboard === true,\n checkInput: (input) => {\n if (inputChecker) validateInput(inputChecker, input, name, checkInput);\n },\n rateLimit:\n limits &&\n ((input, ctx) =>\n enforceRateLimits(\n plan.service,\n (plan.action as { kind?: string }).kind === \"tool\"\n ? \"tool\"\n : \"action\",\n name,\n limits,\n input,\n ctx,\n )),\n authorize,\n audit,\n execute,\n errorBuilder,\n checkOutput: (result) => {\n if (outputChecker) validate(outputChecker, result, name, \"output\");\n return result;\n },\n sensitive: plan.sensitive,\n };\n if (\n contextHook ||\n authorize ||\n stages.dashboardOnly ||\n limits ||\n audit ||\n stages.sensitive\n ) {\n const brickAction = async (context: any) => {\n const ctx = requestContext(plan, context);\n try {\n const input = readInput(route, context);\n if (contextHook) {\n const extra = await contextHook(ctx);\n if (extra) Object.assign(ctx, extra);\n resolveServiceDeps(ctx, plan);\n }\n return await runStages(stages, input, ctx);\n } catch (err) {\n return mapError(err, context.set, ctx);\n }\n };\n return stages.sensitive\n ? (context) => withRedaction(() => brickAction(context))\n : brickAction;\n }\n // Nothing to wait for before `execute`: the same stages, without `authorize`, `rateLimit` or `audit`, synchronously.\n return function brickAction(context) {\n const ctx = requestContext(plan, context);\n try {\n const input = readInput(route, context);\n stages.checkInput(input);\n const result = execute({ input, ctx, error: errorBuilder });\n if (isThenable(result))\n return Promise.resolve(result)\n .then(stages.checkOutput)\n .catch((err) => mapError(err, context.set, ctx));\n return stages.checkOutput(result);\n } catch (err) {\n return mapError(err, context.set, ctx);\n }\n };\n}\n\n/** What `bindCompiledApplication`'s handler factories receive. */\nexport const compilerRuntime = Object.freeze({ bindRoute });\n","import type { TSchema } from \"@sinclair/typebox\";\nimport {\n type Action,\n type ActionConfigWithAuthorize,\n type ActionConfigWithoutAuthorize,\n type ActionContext,\n type ActionErrorDefinition,\n type ErrorBuilder,\n ActionExecutionError,\n} from \"./types\";\nimport { normalizeActionError } from \"./error-response\";\nimport { STANDARD_ERRORS } from \"./protocol\";\nimport { validateWithSchema } from \"./typebox\";\nimport { actionMeta } from \"./action-meta\";\nimport { baseContext } from \"./context\";\nimport { invalid, runStages, type Stages } from \"./compiler/runtime\";\nimport { enforceRateLimits, rateLimitsOf } from \"./rate-limit\";\nimport { auditStage, type AuditStage, type AuditTable } from \"./audit\";\nimport type { ServicePort } from \"./service-port\";\nimport { sensitivity, withRedaction } from \"./sensitive\";\n\n/**\n * The `error` helpers an action receives: one function per error code that\n * throws an `ActionExecutionError` with that code and status. The standard HTTP\n * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,\n * `RATE_LIMITED`, `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to\n * them or replace one.\n *\n * @param errorsDef - The action's `errors`: for each code, its `message` and\n * `status` (default 400).\n * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,\n * and always throw.\n */\nexport function buildErrorHelpers<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(errorsDef?: TErrors): ErrorBuilder<TErrors> {\n const helpers: Record<string, any> = {};\n // An action's own errors override the standard ones of the same code.\n for (const [code, def] of Object.entries({\n ...STANDARD_ERRORS,\n ...errorsDef,\n }) as [string, ActionErrorDefinition][])\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n throw new ActionExecutionError(\n code,\n overrideMessage || def.message,\n def.status || 400,\n details,\n options,\n );\n };\n\n return helpers as ErrorBuilder<TErrors>;\n}\n\n/** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */\nexport function errorsOf<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(action: { config: { errors?: TErrors } }): TErrors {\n return (action.config.errors ?? {}) as TErrors;\n}\n\n/**\n * Define an action: a typed, validated function that Brick serves over HTTP,\n * runs in-process, and exposes to the typed client and OpenAPI.\n *\n * A call runs in order: the input is validated against `input` (an invalid one\n * is a `VALIDATION_FAILED` error, HTTP 400); `authorize` runs, if there is one;\n * `execute` runs; and its result is validated against `output` (a mismatch is a\n * server error, HTTP 500). Throw `error.CODE(...)` from `execute` for a declared\n * failure or a standard one such as `error.NOT_FOUND()`. Any other thrown value\n * becomes `INTERNAL_SERVER_ERROR` (500), with the cause kept out of the response\n * and in the log.\n *\n * `authorize` returns `false` to refuse: the call fails with `UNAUTHORIZED`\n * (401) when there is no `ctx.user`, and `FORBIDDEN` (403) when there is one.\n * Where it is given, `execute` can rely on what it checked.\n *\n * @param config - `name`, `execute`, and optionally `description`, `input` and\n * `output` (TypeBox schemas), `errors`, `authorize`, `method` and `path` to\n * change the route (POST by default), `tags`, and `emits`.\n * @returns The action. Register it with `service.action(action)`; call it\n * directly with `action.run(input, ctx)`.\n * @example\n * import { defineAction, t } from \"@brickkit/core\";\n *\n * export const getPage = defineAction({\n * name: \"get\",\n * method: \"GET\",\n * input: t.Object({ id: t.String() }),\n * output: t.Object({ id: t.String(), title: t.String() }),\n * errors: { PAGE_GONE: { message: \"That page was removed\", status: 410 } },\n * authorize: ({ user }) => user != null,\n * execute: async ({ input, ctx, error }) => {\n * const page = await findPage(ctx.db, input.id);\n * if (!page) throw error.NOT_FOUND(\"No such page\");\n * return page;\n * },\n * });\n */\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction(config: any): any {\n const errorHelpers = buildErrorHelpers(config.errors);\n\n const actionFn = (async (params: { input?: any; ctx?: any }) => {\n return actionFn.execute(params);\n }) as any;\n\n Object.defineProperty(actionFn, \"name\", {\n value: config.name,\n configurable: true,\n });\n\n actionFn.config = config;\n actionFn.errorHelpers = errorHelpers;\n\n actionFn.validateInput = (input: unknown) => {\n const errors = actionMeta(actionFn).checkInput?.(input);\n return errors\n ? { success: false as const, errors }\n : validateWithSchema(config.input, input);\n };\n\n actionFn.validateOutput = (output: unknown) =>\n validateWithSchema(\n actionMeta(actionFn).runtimeOutput ?? config.output,\n output,\n );\n\n actionFn.run = async (input?: any, ctx?: any) => {\n return actionFn.execute({ input, ctx });\n };\n\n const limits = rateLimitsOf(config);\n const stages: Stages = {\n name: config.name,\n dashboardOnly: config.dashboard === true,\n checkInput: (input) => {\n if (!config.input) return;\n const checked = actionFn.validateInput(input);\n if (!checked.success) throw invalid(config.name, \"input\", checked.errors);\n },\n rateLimit:\n limits &&\n ((input, ctx) =>\n enforceRateLimits(\n actionMeta(actionFn).service,\n (actionFn as { kind?: string }).kind === \"tool\" ? \"tool\" : \"action\",\n config.name,\n limits,\n input,\n ctx,\n )),\n authorize: config.authorize,\n execute: config.execute,\n errorBuilder: errorHelpers,\n checkOutput: (result) => {\n if (!(actionMeta(actionFn).runtimeOutput ?? config.output)) return result;\n const checked = actionFn.validateOutput(result);\n if (!checked.success)\n throw invalid(config.name, \"output\", checked.errors);\n return result;\n },\n sensitive: sensitivity(config),\n };\n\n const auditStageOf = memoizedPerAuditTable(actionFn);\n const run = async (params: { input?: any; ctx?: any }) => {\n const meta = actionMeta(actionFn);\n // The registered service resolves the context once per request, and\n // recognizes one it already resolved.\n const ctx: any = meta.service\n ? await meta.service.resolveContext(params?.ctx, meta.deps?.values)\n : { ...baseContext(params?.ctx ?? {}), ...params?.ctx };\n try {\n const audit = auditStageOf(meta.service);\n return await runStages(\n audit ? { ...stages, audit } : stages,\n params?.input,\n ctx,\n );\n } catch (err) {\n throw normalizeActionError(err, ctx);\n }\n };\n actionFn.execute = stages.sensitive\n ? (params: { input?: any; ctx?: any }) => withRedaction(() => run(params))\n : run;\n\n return actionFn;\n}\n\nfunction memoizedPerAuditTable(action: Action<any, any, any, any>) {\n let memo:\n | { service?: unknown; table?: AuditTable; stage?: AuditStage }\n | undefined;\n return (service: ServicePort<any, any> | undefined) => {\n const table = service?.getAuditTable();\n if (memo && table === memo.table && service === memo.service)\n return memo.stage;\n const stage = service && auditStage(service, action);\n memo = { service, table, stage };\n return stage;\n };\n}\n","/** The HTTP methods an action, endpoint or plugin route can use. */\nexport const HTTP_METHODS = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"] as const;\nexport type HttpMethod = (typeof HTTP_METHODS)[number];\n","import {\n DuplicateNameError,\n type Action,\n type Resource,\n type Service,\n} from \"./types\";\nimport {\n PLUGIN_KIND,\n PLUGIN_COMMIT,\n type PluginEndpointContext,\n type PluginRouteMethod,\n type PluginRouteRegistrar,\n type PluginRoutes,\n type PluginRouteScope,\n PLUGIN_ROUTE_SCOPES,\n type ContextOf,\n type ResourcePlugin,\n type ResourcePluginContext,\n type ServicePlugin,\n type ServicePluginContext,\n} from \"./plugin-types\";\nimport { defineAction } from \"./action\";\nimport { actionMeta, type PluginRouteBinding } from \"./action-meta\";\nimport { kebabCase } from \"./kebab\";\nimport { DEFAULT_PREFIX, pathParamNames, pluginRoutePath } from \"./routes\";\nimport { HTTP_METHODS } from \"./http\";\nimport { sensitivity } from \"./sensitive\";\nimport { portOf } from \"./service-port\";\n\n/**\n * Define a plugin that installs onto a service with `service.use(plugin)`. Its\n * `setup` receives the service and a `routes` registrar for adding actions and\n * raw HTTP endpoints, and returns the typed API that `service.use` hands back.\n *\n * @param definition - A unique `name`, optional `routes` controls that let the\n * user move or switch off the plugin's routes, and `setup`, which must be\n * synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n * @example\n * import { defineServicePlugin, t } from \"@brickkit/core\";\n *\n * export const greeting = (salutation = \"Hello\") =>\n * defineServicePlugin({\n * name: \"example/greeting\",\n * setup({ routes }) {\n * const hello = routes.action({\n * name: \"hello\",\n * input: t.Object({ name: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `${salutation}, ${input.name}!`,\n * });\n * return { hello };\n * },\n * });\n *\n * const api = greeterService.use(greeting(\"Welcome\"));\n * await api.hello({ input: { name: \"Ada\" } });\n */\nexport function defineServicePlugin<\n S extends Service<any, any> = Service<any, any>,\n A = unknown,\n>(\n definition: Omit<ServicePlugin<S, A>, typeof PLUGIN_KIND> & {\n setup: (\n context: ServicePluginContext<S>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ServicePlugin<S, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [PLUGIN_KIND]: \"service\" as const,\n });\n}\n/**\n * Define a plugin that installs onto a resource (a table and its entity) with\n * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a\n * `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and\n * returns the typed API that `resource.use` hands back. `crud` is built this way.\n *\n * @param definition - A unique `name`, optional `routes` controls, and `setup`,\n * which must be synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n */\nexport function defineResourcePlugin<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n A extends object = object,\n>(\n definition: Omit<ResourcePlugin<S, R, A>, typeof PLUGIN_KIND> & {\n setup: (\n context: ResourcePluginContext<S, R>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ResourcePlugin<S, R, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [PLUGIN_KIND]: \"resource\" as const,\n });\n}\n\nexport function validateName(name: string) {\n if (!name || name.trim() !== name)\n throw new Error(\n \"Plugin and route names must be nonempty and have no surrounding whitespace\",\n );\n}\nfunction validatePath(path: string) {\n if (\n !path.startsWith(\"/\") ||\n path.includes(\"?\") ||\n path.includes(\"#\") ||\n path.includes(\"//\") ||\n path.split(\"/\").some((part) => part === \".\" || part === \"..\")\n ) {\n throw new Error(`Invalid plugin route path '${path}'`);\n }\n}\nfunction copyControls<S extends PluginRouteScope>(\n controls: PluginRoutes<S> | undefined,\n): PluginRoutes<S> | undefined {\n if (controls === undefined || controls === false) return controls;\n const result: Record<string, false | { path?: string; scope?: S }> =\n Object.create(null);\n for (const [name, value] of Object.entries(controls)) {\n validateName(name);\n if (value === false) {\n result[name] = false;\n continue;\n }\n if (value.path !== undefined) validatePath(value.path);\n if (value.scope !== undefined && !PLUGIN_ROUTE_SCOPES.includes(value.scope))\n throw new Error(`Invalid plugin route scope '${value.scope}'`);\n result[name] = Object.freeze({ ...value });\n }\n return Object.freeze(result);\n}\n\ntype Binding = PluginRouteBinding;\ninterface RawBinding extends Binding {\n handler: (context: PluginEndpointContext<any>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\ninterface Installation {\n descriptor: object;\n status: \"installing\" | \"installed\";\n api?: unknown;\n}\ninterface PluginState {\n hosts: Map<object, Map<string, Installation>>;\n actions: Map<Action<any, any, any, any>, Binding>;\n endpoints: RawBinding[];\n /** The URL segments under each resource that its plugins claim, and which plugin. */\n claims: Map<object, Map<string, string>>;\n}\nconst states = new WeakMap<object, PluginState>();\n\n/** Records the plugin state; the returned function puts all of it back (a failed install's rollback). */\nfunction snapshotState(state: PluginState): () => void {\n const copy = <V>(maps: Map<object, Map<string, V>>) =>\n new Map([...maps].map(([key, inner]) => [key, new Map(inner)]));\n const saved: PluginState = {\n hosts: copy(state.hosts),\n actions: new Map(state.actions),\n endpoints: [...state.endpoints],\n claims: copy(state.claims),\n };\n return () => {\n // Actions the failed install bound lose their route too.\n for (const action of state.actions.keys())\n if (!saved.actions.has(action)) delete actionMeta(action).route;\n Object.assign(state, saved);\n };\n}\nfunction stateOf(service: Service<any, any>): PluginState {\n let state = states.get(service);\n if (!state) {\n state = {\n hosts: new Map(),\n actions: new Map(),\n endpoints: [],\n claims: new Map(),\n };\n states.set(service, state);\n }\n return state;\n}\nexport function isInstallingPlugin(service: Service<any, any>): boolean {\n return [...(states.get(service)?.hosts.values() ?? [])].some(\n (installations) =>\n [...installations.values()].some((item) => item.status === \"installing\"),\n );\n}\n\n/**\n * The raw HTTP endpoints plugins registered on a service, ready to mount on the\n * application. Each handler resolves the service's context before it runs.\n *\n * @param service - The service plugins were installed on.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns The enabled endpoints: `path`, `method`, `handler`, and the\n * `summary`, `description`, and `tags` for OpenAPI.\n */\nexport function getPluginEndpoints(\n service: Service<any, any>,\n prefix = DEFAULT_PREFIX,\n) {\n return stateOf(service)\n .endpoints.filter((binding) => binding.enabled)\n .map((binding) => ({\n path: pluginRoutePath(binding, prefix),\n method: binding.method,\n service,\n plugin: binding.plugin,\n summary: binding.summary,\n description: binding.description,\n tags: binding.tags,\n handler: async (context: Omit<PluginEndpointContext, \"ctx\">) =>\n binding.handler({\n ...context,\n ctx: await service.resolveContext({ request: context.request }),\n }),\n }));\n}\n\n/** The plugin that claimed `segment` under `resource`, if one did. */\nexport function segmentClaimant(\n service: Service<any, any>,\n resource: object,\n segment: string,\n): string | undefined {\n return states.get(service)?.claims.get(resource)?.get(segment);\n}\n\n/** Descriptor identity is scoped to the service or resource installation host. */\nexport function installPlugin(\n service: Service<any, any>,\n resource: Resource<any, any, any> | undefined,\n descriptor: ServicePlugin<any, any> | ResourcePlugin<any, any, any>,\n) {\n if (service.isBuilt)\n throw new Error(\"Plugins must be installed before service build\");\n if (\n descriptor[PLUGIN_KIND] !== (resource ? \"resource\" : \"service\") &&\n descriptor[PLUGIN_KIND] !== \"plugin\"\n )\n throw new Error(\"Plugin does not support this installation host\");\n const state = stateOf(service);\n const host = resource ?? service;\n const existing = state.hosts.get(host)?.get(descriptor.name);\n if (existing) {\n if (existing.status === \"installing\")\n throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);\n if (existing.descriptor !== descriptor)\n throw new Error(\n `Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`,\n );\n return resource ?? existing.api;\n }\n const restoreService = portOf(service).snapshot();\n const restoreState = snapshotState(state);\n const installations =\n state.hosts.get(host) ?? new Map<string, Installation>();\n state.hosts.set(host, installations);\n installations.set(descriptor.name, { descriptor, status: \"installing\" });\n const names = new Set<string>();\n const commits: (() => void)[] = [];\n const ownedActions = new Set<Action<any, any, any, any>>();\n let active = true;\n const claim = (segment: string) => {\n if (!resource) throw new Error(\"Only resource plugins claim URL segments\");\n const claims = state.claims.get(resource) ?? new Map<string, string>();\n state.claims.set(resource, claims);\n if (claims.has(segment)) return;\n const taken = service.listActions().find((action) => {\n const info = actionMeta(action).resourceAction;\n return (\n info?.resource === resource.name && kebabCase(info.name) === segment\n );\n });\n if (taken)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${taken.name}\" in service \"${service.name}\": \"${segment}\" is a ${descriptor.name} route`,\n );\n claims.set(segment, descriptor.name);\n };\n const bindingFor = (config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: PluginRouteScope;\n }): Binding => {\n if (!active || service.isBuilt)\n throw new Error(\"Plugin routes can only be registered during setup\");\n validateName(config.name);\n validatePath(config.path);\n if (names.has(config.name))\n throw new DuplicateNameError(\n `Duplicate plugin route name '${config.name}'`,\n );\n names.add(config.name);\n const control =\n descriptor.routes === false ? false : descriptor.routes?.[config.name];\n const scope =\n (control && control.scope) ||\n config.scope ||\n (resource ? \"resource\" : \"service\");\n if (scope === \"resource\" && !resource)\n throw new Error(\"Service plugin routes cannot use resource scope\");\n if (!PLUGIN_ROUTE_SCOPES.includes(scope))\n throw new Error(`Invalid plugin route scope '${scope}'`);\n if (!HTTP_METHODS.includes(config.method))\n throw new Error(`Invalid plugin route method '${config.method}'`);\n const path = (control && control.path) || config.path;\n validatePath(path);\n const segment = path.split(\"/\")[1]!;\n if (scope === \"resource\" && segment && !segment.startsWith(\":\"))\n claim(segment);\n return {\n service: service.name,\n resource: resource?.name,\n plugin: descriptor.name,\n path,\n method: config.method,\n scope,\n enabled: control !== false,\n };\n };\n const routes: PluginRouteRegistrar<any> = {\n action(config: any) {\n const binding = bindingFor(config);\n for (const name of pathParamNames(binding.path)) {\n if (\n !config.input?.properties ||\n !Object.hasOwn(config.input.properties, name)\n )\n throw new Error(\n `Plugin action path parameter '${name}' must be declared in its input schema`,\n );\n }\n // Public contract name: resource/operation only (e.g. `page.list`).\n // The owning plugin stays in binding metadata (`plugin`) and on the\n // action (`plugin`/`resource`) so it never leaks into exported names,\n // OpenAPI, or client contracts.\n const name = `${resource ? `${resource.name}.` : \"\"}${config.name}`;\n if (service.getAction(name))\n throw new DuplicateNameError(\n `Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`,\n );\n const {\n scope: _scope,\n runtimeOutput,\n checkInput,\n ...actionConfig\n } = config;\n sensitivity({ ...actionConfig, name }, service.name);\n const action = defineAction({ ...actionConfig, name });\n Object.assign(actionMeta(action), {\n route: binding,\n runtimeOutput,\n checkInput,\n });\n service.action(action);\n ownedActions.add(action);\n state.actions.set(action, binding);\n return action;\n },\n endpoint(config) {\n const binding = bindingFor(config);\n state.endpoints.push({\n ...binding,\n handler: config.handler,\n summary: config.summary,\n description: config.description,\n tags: config.tags,\n });\n },\n claim,\n };\n try {\n const context = {\n service,\n ...(resource ? { resource } : {}),\n routes,\n [PLUGIN_COMMIT]: (commit: () => void) => commits.push(commit),\n };\n const api = resource\n ? (descriptor as ResourcePlugin<any, any, any>).setup(\n context as typeof context & { resource: Resource<any, any, any> },\n )\n : (descriptor as ServicePlugin<any, any>).setup(context);\n if (api && typeof api === \"object\" && \"then\" in api)\n throw new Error(\"Plugin setup must be synchronous\");\n if (\n descriptor.routes &&\n Object.keys(descriptor.routes).some((name) => !names.has(name))\n )\n throw new Error(\n `Plugin '${descriptor.name}' has an override for an unknown route`,\n );\n const walk = (value: unknown, path: string[], ancestors: Set<object>) => {\n if (typeof value === \"function\") {\n const binding = state.actions.get(value as Action<any, any, any, any>);\n if (binding && ownedActions.has(value as Action<any, any, any, any>)) {\n if (binding.clientPath)\n throw new Error(\"Plugin actions must have one returned API path\");\n binding.clientPath = resource\n ? [service.name, resource.name, ...path]\n : [service.name, ...path];\n }\n } else if (value && typeof value === \"object\" && !ancestors.has(value)) {\n const next = new Set(ancestors).add(value);\n for (const [key, child] of Object.entries(value))\n walk(child, [...path, key], next);\n }\n };\n walk(api, [], new Set());\n if (resource) {\n if (!api || typeof api !== \"object\" || Array.isArray(api))\n throw new Error(\"Resource plugins must return named API contributions\");\n for (const key of Object.keys(api)) {\n if (\n key in resource ||\n [\"__proto__\", \"prototype\", \"constructor\"].includes(key)\n )\n throw new Error(\n `Resource plugin contribution '${key}' collides with an existing property`,\n );\n }\n Object.assign(resource, api);\n }\n state.hosts.get(host)!.set(descriptor.name, {\n descriptor,\n status: \"installed\",\n api,\n });\n for (const commit of commits) commit();\n return resource ?? api;\n } catch (error) {\n restoreService();\n restoreState();\n throw error;\n } finally {\n active = false;\n }\n}\n/** Whether a plugin named `name` is installed on `host` (the service or a resource). */\nexport function hasPlugin(\n service: Service<any, any>,\n host: object,\n name: string,\n): boolean {\n return (\n states.get(service)?.hosts.get(host)?.get(name)?.status === \"installed\"\n );\n}\n/** Every descriptor installed on the service or its resources, in install order per host. */\nexport function installedPlugins(service: Service<any, any>): object[] {\n return [...(states.get(service)?.hosts.values() ?? [])].flatMap(\n (installations) =>\n [...installations.values()]\n .filter((item) => item.status === \"installed\")\n .map((item) => item.descriptor),\n );\n}\n","import { PLUGIN_DEPS } from \"./deps\";\nimport type { EventListener } from \"./events/types\";\nimport type {\n PluginInstallOptions,\n PluginInstance,\n PluginManifest,\n} from \"./define-plugin\";\nimport type { InstalledPlugin } from \"./plugin-types\";\n\nexport const INTERNALS = Symbol.for(\"brickkit.plugin.internals\");\ninterface Installation {\n scope: \"app\" | \"service\" | \"resource\";\n service?: string;\n resource?: string;\n}\nexport interface Internals {\n manifest: PluginManifest<any, any, any, any, any, any, any>;\n options: Record<string, unknown>;\n deps: Readonly<Record<string, unknown>>;\n install: PluginInstallOptions;\n dashboard?: string;\n installs: Installation[];\n /** When it was first installed, to run `app` parts in install order. */\n order?: number;\n}\n\nexport function isPluginInstance(value: unknown): value is PluginInstance {\n return (\n typeof value === \"object\" &&\n value !== null &&\n INTERNALS in (value as object)\n );\n}\nexport function pluginDepsOf(\n value: unknown,\n): Readonly<Record<string, unknown>> {\n return internalsOf(value)?.deps ?? {};\n}\nfunction internalsOf(value: unknown): Internals | undefined {\n return isPluginInstance(value)\n ? ((value as unknown as Record<symbol, Internals>)[INTERNALS] ?? undefined)\n : undefined;\n}\n\n/**\n * What `brick()` does with plugins: install those given in `plugins` on the\n * app, run every plugin's `app` part in install order, and return the\n * lifecycle, middleware and listeners they contributed.\n */\nexport function setupAppPlugins(\n installedOnServices: readonly object[],\n appPlugins: readonly unknown[],\n) {\n const instances = new Set<PluginInstance>();\n for (const descriptor of installedOnServices)\n if (isPluginInstance(descriptor)) instances.add(descriptor);\n const ordered = [...instances].sort(\n (a, b) => (internalsOf(a)!.order ?? 0) - (internalsOf(b)!.order ?? 0),\n );\n const onApp = new Set<string>();\n for (const plugin of appPlugins) {\n const internals = internalsOf(plugin);\n if (!internals)\n throw new Error(\n \"brick({ plugins }) takes instances from definePlugin(), such as audit()\",\n );\n const { manifest } = internals;\n if (!manifest.app || manifest.tables || manifest.events)\n throw new Error(\n `${manifest.name} cannot be installed on the app; ${\n manifest.resource ? \"use resource.use()\" : \"use service.use()\"\n }`,\n );\n for (const required of manifest.requires ?? [])\n if (!onApp.has(required))\n throw new Error(\n `${manifest.name} requires ${required}, installed in brick({ plugins }) before it`,\n );\n if (onApp.has(manifest.name))\n throw new Error(`Plugin ${manifest.name} is installed on the app twice`);\n // Its `app` part already runs from the service or resource install; running it again would double every hook.\n const installed = ordered.find(\n (other) => internalsOf(other)!.manifest.name === manifest.name,\n );\n if (installed)\n throw new Error(\n `Plugin ${manifest.name} is already installed with ${internalsOf(\n installed,\n )!\n .installs.map((install) =>\n install.scope === \"resource\"\n ? `${install.service}.${install.resource}.use()`\n : `${install.service}.use()`,\n )\n .join(\n \", \",\n )}, which runs its app part too; remove it from brick({ plugins })`,\n );\n onApp.add(manifest.name);\n if (!internals.installs.some((item) => item.scope === \"app\"))\n internals.installs.push({ scope: \"app\" });\n ordered.push(plugin as PluginInstance);\n }\n\n const lifecycles: Lifecycle[] = [];\n const middleware: ((context: any) => unknown)[] = [];\n const listeners: EventListener[] = [];\n const listed: InstalledPlugin[] = [];\n for (const plugin of ordered) {\n const { manifest, options, deps, installs, dashboard } =\n internalsOf(plugin)!;\n for (const install of installs)\n listed.push(\n Object.freeze({\n name: manifest.name,\n ...(manifest.brick ? { brick: manifest.brick } : {}),\n ...install,\n ...(dashboard ? { dashboard } : {}),\n }),\n );\n if (!manifest.app) continue;\n const lifecycle = { options, secrets: manifest.secrets ?? {}, deps };\n // A plugin's start and stop pair up, so stop runs only after its start did.\n const own = { start: [] as Function[], stop: [] as Function[] };\n manifest.app({\n ...lifecycle,\n on(event, handler) {\n if (event !== \"start\" && event !== \"stop\")\n throw new Error(`${manifest.name}: on() takes \"start\" or \"stop\"`);\n own[event].push(handler);\n },\n middleware(handler) {\n middleware.push(handler);\n },\n listeners(...items) {\n // `useDeps()` in a plugin's listener, and its workflow's steps, return the plugin's deps.\n listeners.push(\n ...items.map((listener) => ({ ...listener, [PLUGIN_DEPS]: deps })),\n );\n },\n });\n lifecycles.push({\n start: async () => {\n for (const handler of own.start) await handler(lifecycle);\n },\n stop: async () => {\n for (const handler of own.stop) await handler(lifecycle);\n },\n });\n }\n return {\n lifecycles,\n middleware,\n listeners,\n plugins: listed,\n deps: ordered.map((plugin) => internalsOf(plugin)!.deps),\n };\n}\n\ninterface Lifecycle {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\n/**\n * Start in install order. Stop what started, in reverse order; a start that\n * fails stops those before it and rethrows.\n */\nexport function pluginLifecycle(lifecycles: readonly Lifecycle[]) {\n let started: Promise<void> | undefined;\n const running: Lifecycle[] = [];\n const stopAll = async () => {\n const errors: unknown[] = [];\n for (const item of running.splice(0).reverse())\n try {\n await item.stop();\n } catch (error) {\n errors.push(error);\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length)\n throw new AggregateError(errors, \"Plugins failed to stop\");\n };\n return {\n start(): Promise<void> {\n return (started ??= (async () => {\n for (const item of lifecycles) {\n try {\n await item.start();\n } catch (error) {\n await stopAll().catch(() => undefined);\n started = undefined;\n throw error;\n }\n running.push(item);\n }\n })());\n },\n async stop(): Promise<void> {\n await started?.catch(() => undefined);\n started = undefined;\n await stopAll();\n },\n };\n}\n","import type { HttpMethod } from \"../http\";\nimport { DuplicateNameError, type Service, type Action } from \"../types\";\nimport { actionMeta } from \"../action-meta\";\nimport {\n DEFAULT_PREFIX,\n checkSegments,\n getActionRoute,\n inputSource,\n isReadLike,\n pathParamNames,\n routeKey,\n} from \"../routes\";\nimport { portOf } from \"../service-port\";\nimport { webhookOf } from \"../webhook\";\nimport { fileFields } from \"../typebox\";\nimport { marksKey } from \"../sensitive\";\n\nconst FORM_FIELDS_AND_FRAMING_BYTES = 1024 * 1024;\n\nexport type RouteMethod = HttpMethod;\n/** How a string from a query or form field becomes the schema's type; objects travel as JSON. */\nexport type Coercion = \"number\" | \"boolean\" | \"array\" | \"json\";\n\nfunction coercionOf(schema: any): Coercion | undefined {\n if (schema?.type === \"number\" || schema?.type === \"integer\") return \"number\";\n if (schema?.type === \"boolean\") return \"boolean\";\n if (schema?.type === \"array\") return \"array\";\n if (schema?.type === \"object\") return \"json\";\n return undefined;\n}\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n /** A `webhook` has a verified raw body; see `service.webhook`. */\n readonly kind: \"action\" | \"webhook\";\n /** The plugin that registered the action, if one did. */\n readonly plugin?: string;\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n /** Whether the server reads the query first (else path parameters, then body). */\n readonly readLike: boolean;\n /** Where callers send the input: the query (GET, DELETE) or the body. */\n readonly inputSource: \"query\" | \"body\";\n readonly coercions: readonly {\n readonly key: string;\n readonly type: Coercion;\n /** How each item of an `array` field is coerced. */\n readonly items?: Exclude<Coercion, \"array\">;\n }[];\n /** The most bytes a body may have: multipart bodies with `t.File` fields (by `Content-Length`), and a webhook's (counted as read). */\n readonly bodyLimit?: number;\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly preparations: readonly {\n service: string;\n name: string;\n metadata: unknown;\n }[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = DEFAULT_PREFIX,\n) {\n for (const service of services) service.build();\n return analyzeDeclaredApplication(services, prefix);\n}\n\n/** Inspect current declarations without closing service/plugin setup. */\nexport function analyzeDeclaredApplication(\n services: Service<any, any>[],\n prefix = DEFAULT_PREFIX,\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new DuplicateNameError(\n `Brick compiler: duplicate service '${service.name}'`,\n );\n names.add(service.name);\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<\n string,\n { name: string; plugin: boolean; webhook: boolean }\n >();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const route = describeRoute(service, action, method, path);\n const key = routeKey(method, path);\n const previous = registered.get(key);\n if (previous) {\n if (route.kind === \"webhook\" || previous.webhook)\n throw new DuplicateNameError(\n `Brick compiler: '${service.name}.${action.name}' and '${previous.name}' both claim '${method} ${path}', and a webhook cannot share its route`,\n );\n if (route.plugin || previous.plugin)\n throw new DuplicateNameError(\n `Brick compiler: duplicate plugin route '${method} ${path}'`,\n );\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (earlier service, then lower action name, wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, {\n name: `${service.name}.${action.name}`,\n plugin: Boolean(route.plugin),\n webhook: route.kind === \"webhook\",\n });\n routes.push(route);\n bindings.push({ service, action });\n };\n // Registration order follows module evaluation, which bundlers reorder (#107),\n // so routes are canonical: by route key, then service order, then action name.\n const candidates: [\n string,\n number,\n Service<any, any>,\n Action<any, any, any, any>,\n RouteMethod,\n string,\n ][] = [];\n for (const [index, service] of services.entries()) {\n checkSegments(service);\n for (const action of service.listActions()) {\n const route = getActionRoute(action, prefix);\n if (route === false) continue;\n candidates.push([\n routeKey(route.method, route.path),\n index,\n service,\n action,\n route.method,\n route.path,\n ]);\n }\n }\n candidates.sort(\n (a, b) =>\n compare(a[0], b[0]) || a[1] - b[1] || compare(a[3].name, b[3].name),\n );\n for (const [, , service, action, method, path] of candidates)\n add(service, action, method, path);\n const preparations = services.flatMap((service) =>\n portOf(service)\n .listPreparations()\n .map((contribution) => ({\n service: service.name,\n name: contribution.name,\n metadata: schemaSnapshot(contribution.describe?.()),\n }))\n .sort((a, b) => compare(a.name, b.name)),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n preparations,\n diagnostics,\n });\n return { ir, bindings };\n}\n\n/** Code-unit order, independent of locale. */\nconst compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);\n\n/** What the compiler records about one action route. */\nexport function describeRoute(\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n): RouteIR {\n for (const name of pathParamNames(path)) {\n if (marksKey(action.config.input, name))\n throw new Error(\n `Service '${service.name}' action '${action.name}': sensitive input field '/${name}' is a path parameter of '${method} ${path}', and request logs and traces record the path; take it in the request body instead`,\n );\n }\n const coercions: RouteIR[\"coercions\"][number][] = [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n const type = coercionOf(prop);\n if (!type) continue;\n const items = type === \"array\" ? coercionOf(prop.items) : undefined;\n coercions.push(\n items && items !== \"array\" ? { key, type, items } : { key, type },\n );\n }\n const plugin = actionMeta(action).route?.plugin;\n const files = fileFields(action.config.input);\n const webhook = webhookOf(action);\n const bodyLimit = webhook\n ? webhook.maxBodyBytes\n : files.length && files.every((field) => field.maxBytes !== undefined)\n ? files.reduce((sum, field) => sum + (field.maxBytes ?? 0), 0) +\n FORM_FIELDS_AND_FRAMING_BYTES\n : undefined;\n return {\n method,\n path,\n service: service.name,\n action: action.name,\n kind: webhook ? \"webhook\" : \"action\",\n ...(plugin ? { plugin } : {}),\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n readLike: isReadLike(method, action.name),\n inputSource: inputSource(method),\n coercions,\n ...(bodyLimit === undefined ? {} : { bodyLimit }),\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n };\n}\n","import type { Service, Action } from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { createLogger } from \"./logger\";\nimport { sensitivity } from \"./sensitive\";\nimport { actionMeta } from \"./action-meta\";\nimport { describeRoute, type RouteIR } from \"./compiler/ir\";\nimport { portOf } from \"./service-port\";\nimport { bindRoute, type CompiledRoutePlan } from \"./compiler/runtime\";\n\n/** The plan of an analyzed route: its callbacks, validators and logger. */\nexport function planRoute(\n route: RouteIR,\n service: Service,\n action: Action,\n): CompiledRoutePlan {\n const meta = actionMeta(action);\n const outputSchema = meta.runtimeOutput ?? action.config.output;\n return {\n route,\n service: portOf(service),\n action,\n execute: action.config.execute,\n authorize: action.config.authorize,\n contextHook: service.options.context,\n inputChecker: action.config.input\n ? (getCompiledCheck(action.config.input) as any)\n : undefined,\n outputChecker: outputSchema\n ? (getCompiledCheck(outputSchema) as any)\n : undefined,\n errorBuilder: action.errorHelpers,\n logger: createLogger(`[${service.name}:${action.name}]`),\n cachedDb: service.getDb(),\n checkInput: meta.checkInput,\n sensitive: sensitivity(action.config, service.name),\n deps: meta.deps?.values,\n };\n}\n\n/**\n * An Elysia handler for one action. Use it to mount an action on your own\n * Elysia app; `brick()` does it for you.\n *\n * @deprecated Serve actions with `brick()`, or bind every route at once with\n * `compileBrickApplication`.\n * @param service - The service the action belongs to.\n * @param action - The action.\n * @param routePath - The route's path.\n * @param method - The HTTP method (POST by default).\n * @returns A function from the Elysia context to the response.\n */\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n return bindRoute(\n planRoute(\n describeRoute(\n service,\n action,\n (method ?? \"POST\") as RouteIR[\"method\"],\n routePath,\n ),\n service,\n action,\n ),\n );\n}\n","import type { BrickApp } from \"./endpoints\";\n\n/**\n * Whether a value is an application made by `brick()`. It checks for the\n * methods and `definition` a `BrickApp` has, so it also recognizes one built by\n * another copy of the package.\n *\n * @param app - Anything, such as the default export of an entry file.\n * @returns `true` for a `BrickApp`, narrowing its type.\n */\nexport function isBrickApp(app: unknown): app is BrickApp {\n if (!app || typeof app !== \"object\") return false;\n return (\n \"endpoint\" in app &&\n typeof app.endpoint === \"function\" &&\n \"fetch\" in app &&\n typeof app.fetch === \"function\" &&\n \"listen\" in app &&\n typeof app.listen === \"function\" &&\n \"definition\" in app &&\n !!app.definition &&\n typeof app.definition === \"object\" &&\n \"services\" in app.definition &&\n Array.isArray(app.definition.services) &&\n \"prefix\" in app.definition &&\n typeof app.definition.prefix === \"string\"\n );\n}\n\n/**\n * Check that a module's default export is an application ready to be served,\n * for tools that load an entry file.\n *\n * @param app - The default export of an entry file.\n * @returns The app.\n * @throws When it is not a `BrickApp`, or it already called `.listen()`: the\n * entry must only build the app, and leave listening to the server bootstrap.\n */\nexport function requireBrickApp(app: unknown): BrickApp {\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n if (app.server)\n throw new Error(\n \"Brick: the app entry must not call .listen(); use a separate server bootstrap.\",\n );\n return app;\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport { validateWithSchema } from \"../typebox\";\nimport { sensitivePointer } from \"../sensitive\";\n\n/** A service's declared events: payload schema by event name. */\nexport type EventCatalog = Record<string, TSchema>;\n\n/**\n * One declared event, as `service.events.<name>`. Pass it to `defineListener({ on })`\n * for a typed payload, or to `emitEvent` for a checked one.\n */\nexport interface EventRef<TPayload = unknown> {\n /** The event name on the wire: `<service>.<event>`, such as `orders.shipped`. */\n readonly name: string;\n readonly service: string;\n readonly schema: TSchema;\n /** The plugin that declared it, for events a `definePlugin` adds. */\n readonly plugin?: string;\n /** Type-level only: the payload this event carries. */\n readonly __payload?: TPayload;\n}\n\n/** `service.events`: one `EventRef` per catalog entry. */\nexport type EventRefs<C extends EventCatalog> = {\n readonly [K in keyof C & string]: EventRef<Static<C[K]>>;\n};\n\n/** What a service with a catalog checks before recording an event. */\nexport interface EventChecker {\n readonly name: string;\n readonly events: Readonly<Record<string, EventRef>>;\n /** Whether the service has a catalog at all. */\n readonly hasCatalog: boolean;\n listResources(): readonly { name: string }[];\n}\n\nexport function isEventRef(value: unknown): value is EventRef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as EventRef).name === \"string\" &&\n typeof (value as EventRef).service === \"string\" &&\n typeof (value as EventRef).schema === \"object\"\n );\n}\n\n/** Build `service.events` from its catalog. */\nexport function eventRefs(\n service: string,\n catalog: EventCatalog | undefined,\n): Record<string, EventRef> {\n const refs: Record<string, EventRef> = Object.create(null);\n for (const [key, schema] of Object.entries(catalog ?? {})) {\n if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key))\n throw new Error(\n `Event \"${key}\" in service \"${service}\" must be a plain name such as shipped or itemAdded`,\n );\n if (!schema || typeof schema !== \"object\")\n throw new Error(\n `Event \"${service}.${key}\" needs a payload schema, such as t.Object({ ... })`,\n );\n const at = sensitivePointer(schema);\n if (at)\n throw new Error(\n `Event \"${service}.${key}\" payload marks '${at}' t.Sensitive, which event payloads do not support yet; carry an id and load the secret in the listener`,\n );\n refs[key] = Object.freeze({ name: `${service}.${key}`, service, schema });\n }\n return Object.freeze(refs);\n}\n\n/** @throws When the payload does not match the event's schema. */\nexport function checkPayload(ref: EventRef, payload: unknown): void {\n const result = validateWithSchema(ref.schema, payload);\n if (!result.success)\n throw new Error(\n `Event \"${ref.name}\" payload does not match its schema: ${result.errors\n .map((error) => `${error.path || \"/\"} ${error.message}`)\n .join(\"; \")}`,\n );\n}\n\n/** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */\nexport const CRUD_EVENT_OPERATIONS = [\"create\", \"update\", \"delete\"] as const;\nexport type CrudEventOperation = (typeof CRUD_EVENT_OPERATIONS)[number];\n\n/** The event a CRUD write records: `<resource>.<operation>`. */\nexport const crudEventName = (\n resource: string,\n operation: CrudEventOperation,\n): string => `${resource}.${operation}`;\n\n/** The `source` of a resource's events: `<service>.<resource>`. */\nexport const crudEventSource = (service: string, resource: string): string =>\n `${service}.${resource}`;\n\n/** Whether `name` is the CRUD event of one of `resources`. */\nexport function isCrudEvent(\n name: string,\n resources: readonly string[],\n): boolean {\n const dot = name.indexOf(\".\");\n return (\n dot > 0 &&\n (CRUD_EVENT_OPERATIONS as readonly string[]).includes(\n name.slice(dot + 1),\n ) &&\n resources.includes(name.slice(0, dot))\n );\n}\n\n/**\n * Check an event against the catalog of the service recording it. Without a\n * catalog any name goes. With one, the name must be `<service>.<event>` from it\n * (the payload is checked against its schema) or a CRUD event of one of the\n * service's resources (`<resource>.create|update|delete`).\n *\n * @throws When the name is not declared or the payload does not match.\n */\nexport function checkEvent(\n service: EventChecker,\n name: string,\n payload: unknown,\n): void {\n const prefix = `${service.name}.`;\n const ref = name.startsWith(prefix)\n ? service.events[name.slice(prefix.length)]\n : undefined;\n if (ref) return checkPayload(ref, payload);\n if (!service.hasCatalog) return;\n if (\n isCrudEvent(\n name,\n service.listResources().map((r) => r.name),\n )\n )\n return;\n throw new Error(\n `Event \"${name}\" is not in the event catalog of service \"${service.name}\" (declared: ${\n Object.values(service.events)\n .map((ref) => ref.name)\n .join(\", \") || \"none\"\n })`,\n );\n}\n","import { isEventRef, type EventRef } from \"./catalog\";\nimport { buildErrorHelpers } from \"../action\";\nimport { PLUGIN_DEPS } from \"../deps\";\nimport type { ActionErrorDefinition, ErrorBuilder } from \"../types\";\nimport type {\n EventDelivery,\n EventListener,\n EventWorkflow,\n ListenerFailure,\n RetryDecision,\n} from \"./types\";\n\ntype EventOn = EventRef<any> | readonly EventRef<any>[];\ntype PayloadOf<O> =\n O extends EventRef<infer P>\n ? P\n : O extends readonly EventRef<infer P>[]\n ? P\n : never;\n\ntype ListenerConfig<\n TPayload,\n TOn = string | readonly string[],\n TErrors extends Record<string, ActionErrorDefinition> = {},\n> = {\n name: string;\n on: TOn;\n maxAttempts?: number;\n /** Errors `run` may raise with `error.CODE()`. Spread `defineError(...)` results or `errorsOf(action)` here. */\n errors?: TErrors;\n /** Decides what a failure does next. Without it every failure retries until `maxAttempts`. */\n retry?: (error: ListenerFailure<TErrors>) => RetryDecision;\n} & (\n | {\n run: (\n delivery: EventDelivery<TPayload>,\n helpers: { error: ErrorBuilder<TErrors> },\n ) => void | Promise<void>;\n workflow?: never;\n }\n | { workflow: EventWorkflow<TPayload>; run?: never }\n);\n\n/**\n * Define a listener: code that runs for each event it listens for, after the write\n * that caused the event has been committed. Pass it to `brick({ events: {\n * listeners } })`.\n *\n * It either runs a handler (`run`) in the process that delivers events, or starts\n * a durable workflow (`workflow`) on the app's `events.world`. Delivery is at\n * least once. A handler that throws is retried later with a growing delay, then\n * parked as dead, so it can run again for the same event: use\n * `delivery.deliveryId` to make its work idempotent. A workflow needs no such\n * care: a delivery starts one run however often it is tried, and the workflow\n * retries its own steps.\n *\n * A listener can declare `errors`, as an action does, and raise them in `run` with\n * `error.CODE()`. `retry(error)` then picks `\"retry\"` or `\"dead\"` from the typed\n * `error.code`; anything not declared arrives as `{ code: \"UNKNOWN\", cause }`.\n *\n * @param config - `name` (unique; it is part of each delivery's id), `on` (a\n * declared event such as `orders.events.shipped`, which types the payload, or an\n * event name; or a list of either; a trailing `*` matches a prefix, as in\n * `user.*`), `run` or `workflow`, and optionally `maxAttempts`.\n * @returns The listener.\n * @throws When the name is empty or contains `:`, `on` is empty, or the listener\n * has both or neither of `run` and `workflow`.\n * @example\n * import { brick, defineListener } from \"@brickkit/core\";\n *\n * const welcome = defineListener({\n * name: \"welcome-email\",\n * on: \"user.create\",\n * run: async ({ payload, deliveryId }) => {\n * await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });\n * },\n * });\n *\n * export default brick({ services, events: { listeners: [welcome] } });\n * @example\n * // src/workflows/onboard.ts\n * export async function onboard(event: WorkflowEvent<CrudEventPayload>) {\n * \"use workflow\";\n * await sendWelcome(event.payload.row.email);\n * }\n *\n * defineListener({ name: \"onboard\", on: \"user.create\", workflow: onboard });\n * @example\n * // payload is { id: string; trackingId: string }, from the orders catalog.\n * defineListener({\n * name: \"notify-shipped\",\n * on: orders.events.shipped,\n * run: ({ payload }) => notify(payload.id, payload.trackingId),\n * });\n */\nexport function defineListener<\n const TOn extends EventOn,\n const TErrors extends Record<string, ActionErrorDefinition> = {},\n>(\n config: ListenerConfig<PayloadOf<TOn>, TOn, TErrors>,\n): EventListener<PayloadOf<TOn>>;\nexport function defineListener<\n TPayload = any,\n const TErrors extends Record<string, ActionErrorDefinition> = {},\n>(\n config: ListenerConfig<\n TPayload,\n string | EventRef<any> | readonly (string | EventRef<any>)[],\n TErrors\n >,\n): EventListener<TPayload>;\nexport function defineListener(\n config: ListenerConfig<any, unknown, any>,\n): EventListener {\n const on = (Array.isArray(config.on) ? config.on : [config.on]).map(\n (item: unknown) => (isEventRef(item) ? item.name : item),\n ) as string[];\n validateListener({ ...config, on } as EventListener);\n const helpers = buildErrorHelpers(config.errors);\n return Object.freeze({\n name: config.name,\n on: Object.freeze(on),\n ...(config.run !== undefined\n ? {\n run: ((delivery: EventDelivery) =>\n config.run!(delivery, { error: helpers })) as EventListener[\"run\"],\n }\n : {}),\n ...(config.errors ? { errors: config.errors } : {}),\n ...(config.retry ? { retry: config.retry } : {}),\n ...(config.workflow !== undefined ? { workflow: config.workflow } : {}),\n ...(config.maxAttempts !== undefined\n ? { maxAttempts: config.maxAttempts }\n : {}),\n });\n}\n\n/**\n * @throws When the name is empty or contains `:`, `on` is empty, `maxAttempts`\n * is not a positive integer, or the listener has both or neither of `run` and\n * `workflow`.\n */\nexport function validateListener(listener: EventListener): void {\n const { name, on, maxAttempts, run, workflow } = listener;\n if (typeof name !== \"string\" || !name)\n throw new Error(\"An event listener needs a name\");\n // A listener's name ends its delivery ids: see `deliveryId`.\n if (name.includes(\":\"))\n throw new Error(`Event listener name '${name}' must not contain ':'`);\n if (\n !Array.isArray(on) ||\n !on.length ||\n on.some((pattern) => !pattern || typeof pattern !== \"string\")\n )\n throw new Error(`Event listener '${name}' listens for nothing`);\n if (\n maxAttempts !== undefined &&\n (!Number.isInteger(maxAttempts) || maxAttempts < 1)\n )\n throw new Error(\n `Event listener '${name}': maxAttempts must be a positive integer`,\n );\n if (run !== undefined && workflow !== undefined)\n throw new Error(\n `Event listener '${name}' has both run and workflow; give it one`,\n );\n if (run === undefined && workflow === undefined)\n throw new Error(\n `Event listener '${name}' needs a run handler or a workflow`,\n );\n if (run !== undefined && typeof run !== \"function\")\n throw new Error(`Event listener '${name}': run must be a function`);\n if (workflow !== undefined && typeof workflow !== \"function\")\n throw new Error(\n `Event listener '${name}': workflow must be a function marked \"use workflow\"`,\n );\n}\n\n/** The deps a plugin's listener runs with, set by the plugin install; `undefined` for the app's own. */\nexport const listenerDeps = (listener: object) =>\n (listener as { [PLUGIN_DEPS]?: Record<string, unknown> })[PLUGIN_DEPS];\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { runWithDeps } from \"../deps\";\nimport { listenerDeps } from \"./listener\";\nimport type { Schedule, ScheduleRun } from \"../schedules/schedule\";\nimport type {\n EventDelivery,\n EventListener,\n EventsWorld,\n WorkflowEvent,\n WorkflowsOptions,\n} from \"./types\";\n\n/** The workflow bundle `buildWorkflows()` writes and the runtime reads: its directory under the project root, and its files. */\nexport const WORKFLOW_BUNDLE = {\n dir: \".well-known/workflow/v1\",\n flow: \"flow.mjs\",\n steps: \"__step_registrations.mjs\",\n webhook: \"webhook.mjs\",\n manifest: \"manifest.json\",\n} as const;\n/** From the Workflow SDK: the queue a workflow run goes to (`getQueueTopicPrefix(\"workflow\")` in `@workflow/world`), and the header a world names it in. */\nexport const WORKFLOW_QUEUE = {\n prefix: \"__wkf_workflow_\",\n header: \"x-vqs-queue-name\",\n} as const;\nconst STOPPED = \"The events were stopped, so workflows can no longer run\";\nconst NOT_BUILT =\n \"brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\";\n/** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */\nexport const WEBHOOK_ROUTE = `/${WORKFLOW_BUNDLE.dir}/webhook/*`;\n/** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */\nconst STEP_REGISTRY = Symbol.for(\"@workflow/core//registeredSteps\");\n\ninterface WorkflowSdk {\n start(\n workflow: unknown,\n args: unknown[],\n options: Record<string, unknown>,\n ): Promise<{ runId: string }>;\n setWorld(world: unknown): void;\n}\n\ninterface BundleManifest {\n steps?: Record<string, unknown>;\n workflows?: Record<string, Record<string, { workflowId?: string }>>;\n}\n\n/**\n * Where the workflow bundle is read from, and the project it is built from.\n *\n * @param options - The `events.workflows` option.\n * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the\n * builder finds the SDK from where it writes, and skips only this directory when it\n * looks for workflows.\n */\nexport function resolveWorkflowPaths(options: WorkflowsOptions = {}): {\n root: string;\n dir: string;\n} {\n const root = resolve(options.root ?? process.cwd());\n return { root, dir: shippedBundle ?? join(root, WORKFLOW_BUNDLE.dir) };\n}\n\n/** The bundle `brick build` shipped beside a compiled server, which reads it instead of building one. */\nlet shippedBundle: string | undefined;\n\n/** @internal Called by a compiled server before it loads its app. */\nexport function setShippedWorkflowBundle(dir: string): void {\n shippedBundle = resolve(dir);\n}\n\n/** Whether this process runs a compiled server that reads the bundle shipped beside it. */\nexport const isWorkflowBundleShipped = (): boolean =>\n shippedBundle !== undefined;\n\n/**\n * Runs workflow listeners: wires the world into the Workflow SDK, serves the\n * built bundle from this process, and starts one run for each delivery.\n *\n * Nothing is loaded until it is needed, so an app without workflow listeners\n * never imports the SDK.\n */\nexport class WorkflowRuntime {\n readonly root: string;\n private ready: Promise<WorkflowSdk> | undefined;\n private connected: Promise<WorkflowSdk> | undefined;\n private closed = false;\n\n constructor(\n readonly world: EventsWorld,\n options: WorkflowsOptions | undefined,\n /** The listeners and schedules that run workflows. */\n private readonly listeners: readonly {\n readonly name: string;\n readonly workflow?: unknown;\n }[],\n private readonly deps: Record<string, unknown> = {},\n ) {\n this.root = resolveWorkflowPaths(options).root;\n }\n\n /** Read when used, in case a bundler evaluates the app before the compiled server names its shipped bundle. */\n get dir(): string {\n return resolveWorkflowPaths({ root: this.root }).dir;\n }\n\n /** Begin loading the runtime now rather than at the first delivery. */\n warmUp(): void {\n this.ensure().catch((error) =>\n console.error(\n `[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n\n /**\n * Start the run for a delivery.\n *\n * The run is named after the delivery id, so a delivery that is tried again\n * finds the run it already started instead of starting another.\n *\n * @param listener - The workflow listener the delivery is for.\n * @param delivery - The delivery.\n */\n async startRun(\n listener: EventListener,\n delivery: EventDelivery,\n ): Promise<void> {\n const sdk = await this.ensure();\n const { attempt: _attempt, ...event } = delivery;\n await sdk.start(listener.workflow, [event satisfies WorkflowEvent], {\n world: this.world,\n runKey: delivery.deliveryId,\n runKeyTime: Date.parse(delivery.occurredAt),\n });\n }\n\n /**\n * Start the workflow of a schedule's run. The workflow run is named after\n * the run key, so a run that is tried again does not start another.\n */\n async startScheduled(schedule: Schedule, run: ScheduleRun): Promise<void> {\n const sdk = await this.ensure();\n const { attempt: _attempt, ...workflowRun } = run;\n await sdk.start(schedule.workflow, [workflowRun], {\n world: this.world,\n runKey: `schedule:${run.runKey}`,\n runKeyTime: Date.parse(run.slot),\n });\n }\n\n /**\n * Answer a request to a webhook a workflow created with `createWebhook`, by\n * resuming the workflow that waits on it. Needs the world but not the queue\n * consumer, so a process that only records events (`dispatch: false`) serves\n * webhooks too.\n *\n * @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.\n * @returns The response the bundle's webhook handler gives.\n */\n async handleWebhook(request: Request): Promise<Response> {\n await this.connect();\n const file = join(this.dir, WORKFLOW_BUNDLE.webhook);\n if (!existsSync(file))\n throw new Error(`No webhook bundle at ${file}. ${NOT_BUILT}`);\n const handlers = await import(pathToFileURL(file).href);\n const handler = handlers[request.method];\n if (typeof handler !== \"function\")\n return new Response(null, { status: 405 });\n return handler(request);\n }\n\n /** Stop the world. The runtime cannot be started again afterwards. */\n async close(): Promise<void> {\n this.closed = true;\n await this.ready?.catch(() => {});\n await this.connected?.catch(() => {});\n await this.world.close?.();\n }\n\n private ensure(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.ready ??= this.initialize().catch((error) => {\n this.ready = undefined;\n throw error;\n });\n return this.ready;\n }\n\n /** Load the SDK and give it the world: all a webhook needs. */\n private connect(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.connected ??= this.loadSdk()\n .then((sdk) => {\n sdk.setWorld(this.world);\n return sdk;\n })\n .catch((error) => {\n this.connected = undefined;\n throw error;\n });\n return this.connected;\n }\n\n private async initialize(): Promise<WorkflowSdk> {\n if (typeof this.world.createRunId !== \"function\")\n throw new Error(\n \"This world cannot name a run after its key, so an event delivered twice would start two runs. \" +\n \"Use the world from @brickkit/redis-world or @brickkit/bullmq-world.\",\n );\n const sdk = await this.connect();\n const flow = join(this.dir, WORKFLOW_BUNDLE.flow);\n if (!existsSync(flow))\n throw new Error(`No workflow bundle at ${flow}. ${NOT_BUILT}`);\n const manifest = this.readManifest();\n const depsOf = this.checkListeners(manifest);\n const bundle = await this.loadBundle(flow);\n if (typeof bundle.POST !== \"function\")\n throw new Error(`${flow} does not export a POST handler`);\n const post = bundle.POST;\n // Steps run inside this handler, so `useDeps()` in a step finds the deps of\n // the app, or of the plugin whose listener runs the workflow. The queue is\n // named after the workflow: `__wkf_workflow_<workflowId>`.\n this.world.registerHandler?.(WORKFLOW_QUEUE.prefix, (request: Request) => {\n const queue = request.headers.get(WORKFLOW_QUEUE.header) ?? \"\";\n const deps =\n depsOf.get(queue.slice(WORKFLOW_QUEUE.prefix.length)) ?? this.deps;\n return runWithDeps(deps, () => post(request));\n });\n await this.world.start?.();\n return sdk;\n }\n\n private async loadSdk(): Promise<WorkflowSdk> {\n // A compiled server may run where no SDK is installed: then the one beside its bundle.\n const from = [this.root, this.dir].map((dir) =>\n createRequire(join(dir, \"package.json\")),\n );\n const load = async (specifier: string) => {\n let path: string | undefined;\n for (const require of from)\n try {\n path ??= require.resolve(specifier);\n } catch {}\n if (!path) {\n throw new Error(\n `The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`,\n );\n }\n return import(pathToFileURL(path).href);\n };\n const [api, runtime] = await Promise.all([\n load(\"workflow/api\"),\n load(\"workflow/runtime\"),\n ]);\n return { start: api.start, setWorld: runtime.setWorld };\n }\n\n /**\n * The bundle holds its own copy of every step and registers them all when it\n * loads, replacing the ones the app registered. A copy has its own module state:\n * a step would find no database connection, no config, none of what the app set\n * up. So the app's steps are put back, and the bundle's copies serve only the\n * steps the app never loaded.\n */\n private async loadBundle(\n flow: string,\n ): Promise<{ POST?: (request: Request) => Promise<Response> }> {\n const registry = () =>\n (globalThis as Record<symbol, unknown>)[STEP_REGISTRY] as\n | Map<string, unknown>\n | undefined;\n const app = new Map(registry());\n const bundle = await import(pathToFileURL(flow).href);\n const registered = registry();\n if (registered) for (const [id, step] of app) registered.set(id, step);\n return bundle;\n }\n\n private readManifest(): BundleManifest | undefined {\n const path = join(this.dir, WORKFLOW_BUNDLE.manifest);\n if (!existsSync(path)) return undefined;\n return JSON.parse(readFileSync(path, \"utf8\")) as BundleManifest;\n }\n\n /**\n * A listener's workflow must carry the id the transform gives it, and the bundle\n * must know that id: a function that was never transformed, or a bundle built\n * before the workflow existed, would fail on its first delivery with a less\n * helpful message.\n *\n * @returns The deps each workflow's steps run with, by workflow id.\n * @throws When one workflow is run by listeners with different deps (an app\n * and a plugin, or two plugin installs): its steps could see only one set.\n */\n private checkListeners(\n manifest: BundleManifest | undefined,\n ): Map<string, Record<string, unknown>> {\n const depsOf = new Map<string, Record<string, unknown>>();\n const known = new Set<string>();\n for (const file of Object.values(manifest?.workflows ?? {}))\n for (const entry of Object.values(file))\n if (entry.workflowId) known.add(entry.workflowId);\n for (const listener of this.listeners) {\n const id = (listener.workflow as { workflowId?: unknown } | undefined)\n ?.workflowId;\n if (typeof id !== \"string\")\n throw new Error(\n `The workflow of listener '${listener.name}' was not transformed. ` +\n \"Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.\",\n );\n if (manifest && !known.has(id))\n throw new Error(\n `The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`,\n );\n const deps = listenerDeps(listener) ?? this.deps;\n if ((depsOf.get(id) ?? deps) !== deps)\n throw new Error(\n `Workflow '${id}' is run by listeners with different deps (listener '${listener.name}'); give each app or plugin install its own workflow.`,\n );\n depsOf.set(id, deps);\n }\n return depsOf;\n }\n}\n","import type { Service } from \"./types\";\nimport { planRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport {\n bindRoute,\n compilerRuntime,\n type CompiledHandler,\n type CompiledRoutePlan,\n type HandlerFactory,\n} from \"./compiler/runtime\";\nimport { requireBrickApp } from \"./app-entry\";\nimport { portOf } from \"./service-port\";\nimport { setShippedWorkflowBundle } from \"./events/workflows\";\n\n/** @throws When the services no longer analyze to `ir`, so the build is stale. */\nfunction analyzeMatching(services: Service<any, any>[], ir: BrickIR) {\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n return analyzed;\n}\n\n/**\n * Build artifact bootstrap: import the bundled app. It is not re-analyzed\n * against the IR: the bundle and its IR come from one build (#107).\n *\n * @param _ir Ignored; kept so existing callers still type-check.\n * @param options `workflows`: the workflow bundle `brick build` shipped beside\n * the server, read instead of `<root>/.well-known/workflow/v1`.\n */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n _ir?: BrickIR,\n options: { workflows?: string } = {},\n) {\n if (options.workflows) setShippedWorkflowBundle(options.workflows);\n return requireBrickApp((await load()).default);\n}\n\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type {\n CompiledHandler,\n CompiledRoutePlan,\n HandlerFactory,\n} from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n bind: (plan: CompiledRoutePlan, index: number) => CompiledHandler = bindRoute,\n): CompiledApplication {\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(planRoute(route, service, action));\n return Object.freeze({ ir: route, handler: bind(plan, index) });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n /** `\"generic\"` skips the plugins' preparations (no prewarm). */\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n if (options.mode !== \"generic\")\n for (const service of options.services)\n portOf(service).prepareContributions();\n return bindAnalyzed(ir, bindings);\n}\n\n/**\n * Build artifact binder: consumes emitted functions, with no runtime handler code generation.\n *\n * @deprecated `brick build` no longer emits handler factories; built servers\n * use `loadCompiledBrickApp`. Pass `compileBrickApplication(...)` as\n * `brick({ compilation })` instead.\n */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeMatching(services, ir);\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n for (const service of services) portOf(service).prepareContributions();\n return bindAnalyzed(ir, analyzed.bindings, (plan, index) =>\n factories[index]!(plan, compilerRuntime),\n );\n}\n","import type { InstalledPlugin } from \"./plugin-types\";\nimport type { Service, ArchitectureSchema } from \"./types\";\nimport type { RouteIR } from \"./compiler/ir\";\nimport { getActionRoute } from \"./routes\";\nimport type { EventsDefinition } from \"./events/hub\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport { claimName, definitionSite } from \"./definition-site\";\n\nexport interface ArchitectureApplication {\n services: readonly Service<any, any>[];\n routes: readonly RouteIR[];\n events?: EventsDefinition;\n sockets?: readonly (BrickSocketSchema & { service: string; path: string })[];\n plugins?: readonly InstalledPlugin[];\n}\n\nexport class ServiceRegistry {\n private _revision = 0;\n /** Definition revision for invalidating serialized architecture snapshots. */\n get revision(): number {\n return this._revision;\n }\n touch(): void {\n this._revision++;\n }\n\n private services = new Map<string, Service>();\n private sites = new Map<string, string | undefined>();\n\n /** @throws When a different file already registered a service with this name. */\n register(service: Service, site = definitionSite()): void {\n claimName(this.sites, `service \"${service.name}\"`, service.name, site);\n this.services.set(service.name, service);\n this.touch();\n }\n\n get(name: string): Service | undefined {\n return this.services.get(name);\n }\n\n has(name: string): boolean {\n return this.services.has(name);\n }\n\n list(): Service[] {\n return Array.from(this.services.values());\n }\n\n /**\n * The architecture of an app (`app.definition`): its mounted routes. Without\n * one, every registered service with its default routes under `/api`.\n */\n exportArchitecture(\n application?: ArchitectureApplication,\n ): ArchitectureSchema {\n return {\n version: \"1.0.0\",\n ...(application?.events ? { events: application.events } : {}),\n ...(application?.plugins?.length\n ? { plugins: [...application.plugins] }\n : {}),\n services: (application?.services ?? this.list()).map((service) => {\n const byAction = new Map(\n application\n ? application.routes\n .filter((route) => route.service === service.name)\n .map((route) => [route.action, route])\n : service.listActions().flatMap((action) => {\n const route = getActionRoute(action);\n return route ? [[action.name, route] as const] : [];\n }),\n );\n const schema = service.introspect();\n return {\n ...schema,\n ...(application?.sockets\n ? {\n sockets: application.sockets.filter(\n (socket) => socket.service === service.name,\n ),\n }\n : {}),\n actions: schema.actions.map((action) => {\n const route = byAction.get(action.name);\n return route\n ? { ...action, method: route.method, path: route.path }\n : action;\n }),\n };\n }),\n };\n }\n}\n\nlet globalRegistry = new ServiceRegistry();\n\n/**\n * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI\n * generator, `useService`, and the dashboard find services by name.\n *\n * @returns The current global registry.\n */\nexport function getGlobalRegistry(): ServiceRegistry {\n return globalRegistry;\n}\n\n/**\n * Start over with an empty global registry. For tests, which define the same\n * services again in each case; an application never needs it.\n */\nexport function resetGlobalRegistry(): void {\n globalRegistry = new ServiceRegistry();\n}\n","import type { Action, ActionAccessPolicy } from \"./types\";\nimport { actionMeta, type ActionAccessInfo } from \"./action-meta\";\n\nexport type { ActionAccessPolicy, ActionAccessInfo };\n\n/**\n * Record how an action is protected, for tools that cannot read it from the\n * configuration: plugins such as `crud` enforce access inside `execute`, so the\n * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard\n * read what is recorded here.\n *\n * @param action - The action to describe.\n * @param info - Whether it checks authorization and whether it scopes queries,\n * and the resulting policy.\n */\nexport function setActionAccess(action: object, info: ActionAccessInfo): void {\n actionMeta(action).access = {\n hasAuthorize: info.hasAuthorize,\n hasScope: info.hasScope,\n policy: info.policy,\n };\n}\n\n/**\n * How an action is protected: `\"public\"` when nothing checks the caller,\n * `\"authorized\"` when an `authorize` does, and `\"scoped\"` when the action also\n * limits what rows the caller can reach. It reads what a plugin recorded with\n * `setActionAccess`, else the action's own `authorize`, and keeps the policy\n * consistent with the flags.\n *\n * @param action - An action, or any object a plugin described.\n * @returns `hasAuthorize`, `hasScope`, and `policy`.\n */\nexport function getActionAccess(action: Action | object): ActionAccessInfo {\n const meta = actionMeta(action).access;\n const configAuthorize =\n typeof (action as Partial<Action>).config?.authorize === \"function\";\n if (!meta) {\n return {\n hasAuthorize: configAuthorize,\n hasScope: false,\n policy: configAuthorize ? \"authorized\" : \"public\",\n };\n }\n const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);\n const hasScope = Boolean(meta.hasScope);\n let policy: ActionAccessPolicy =\n meta.policy ??\n (hasAuthorize ? (hasScope ? \"scoped\" : \"authorized\") : \"public\");\n // Normalize conflicting metadata so the policy always agrees with the\n // effective flags (e.g. metadata stamped \"public\" on an action that also\n // declares config.authorize must not report policy \"public\").\n if (policy === \"public\" && hasAuthorize)\n policy = hasScope ? \"scoped\" : \"authorized\";\n else if (policy !== \"public\" && !hasAuthorize) policy = \"public\";\n else if (policy === \"scoped\" && !hasScope) policy = \"authorized\";\n return { hasAuthorize, hasScope, policy };\n}\n\n/**\n * Say how the audit log records an action a plugin owns: `\"inline\"` when the\n * plugin writes in its own transaction and records the write there with a\n * host hook, `\"none\"` when it never writes. Without this, an action that is not\n * a `GET` is recorded after it runs, as a plain action is.\n */\nexport function setActionAudit(action: object, mode: \"inline\" | \"none\"): void {\n actionMeta(action).audit = mode;\n}\n","import type { EventRef } from \"./events/catalog\";\nimport {\n DEFAULT_PREFIX,\n actionOwners,\n pathParamNames,\n toOpenApiPath,\n} from \"./routes\";\nimport { analyzeDeclaredApplication } from \"./compiler/ir\";\nimport { getActionAccess } from \"./access\";\nimport { rateLimitsOf } from \"./rate-limit\";\nimport { webhookOf } from \"./webhook\";\nimport { fileFields } from \"./typebox\";\nimport { writeOnly } from \"./sensitive\";\nimport { getGlobalRegistry } from \"./registry\";\nimport type { Service, ActionErrorDefinition } from \"./types\";\n\n/** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */\nexport const OPENAPI_DEFAULTS = Object.freeze({\n title: \"Brick-TS API Mesh\",\n version: \"1.0.0\",\n path: \"/openapi.json\",\n});\n\nexport interface OpenApiGeneratorOptions {\n title?: string;\n version?: string;\n description?: string;\n prefix?: string;\n services?: Service<any, any>[];\n}\n\nfunction isAnchor(\n node: unknown,\n): node is { $id: string } & Record<string, any> {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$id === \"string\"\n );\n}\n\nfunction isBareRef(node: unknown): node is { $ref: string } {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$ref === \"string\" &&\n !(node as { $ref: string }).$ref.startsWith(\"#\")\n );\n}\n\nfunction toComponentKey(id: string): string {\n return id.replace(/[^A-Za-z0-9.\\-_]+/g, \"_\");\n}\n\n/**\n * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors\n * (`{ $id: \"T0\", ..., { $ref: \"T0\" } }`). OpenAPI interprets a bare `$ref`\n * as an external file reference, so downstream tooling tries to load a\n * file named `T0` and fails. Hoist every anchored subschema into\n * `#/components/schemas/` and rewrite the refs to local pointers.\n * First definition wins when one `$id` is declared twice.\n */\nfunction hoistAnchoredSchemas(spec: Record<string, any>): void {\n const anchored = new Map<string, any>();\n\n const collect = (node: any): any => {\n if (Array.isArray(node)) return node.map(collect);\n if (typeof node !== \"object\" || node === null) return node;\n if (isAnchor(node)) {\n const id = node.$id;\n const { $id: _dropped, ...rest } = node;\n const collected = collect(rest);\n if (!anchored.has(id)) anchored.set(id, collected);\n return { $ref: `#/components/schemas/${toComponentKey(id)}` };\n }\n for (const key of Object.keys(node)) {\n node[key] = collect(node[key]);\n }\n return node;\n };\n\n const rewrite = (node: any): void => {\n if (Array.isArray(node)) {\n for (const child of node) rewrite(child);\n return;\n }\n if (typeof node !== \"object\" || node === null) return;\n if (isBareRef(node)) {\n node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;\n }\n for (const key of Object.keys(node)) rewrite(node[key]);\n };\n\n collect(spec);\n\n const components = (spec.components ??= {}) as Record<string, any>;\n const schemas = (components.schemas ??= {}) as Record<string, any>;\n for (const [id, schema] of anchored) {\n schemas[toComponentKey(id)] = schema;\n }\n\n // Second pass covers refs inside the hoisted copies themselves\n // (e.g. the self-recursive JSON-value schema).\n rewrite(spec);\n}\n\n/**\n * Build the OpenAPI 3.1 document for the services: one path per action route,\n * with request and response schemas from the actions' TypeBox schemas, their\n * declared errors, tags by service, and a bearer security scheme where any\n * action needs authorization. Declared events are listed under `x-brick-events`,\n * by wire name, with their service and payload schema.\n *\n * `brick()` calls this for `/openapi.json`; call it yourself to write the\n * document to a file or feed another tool.\n *\n * @param options - `title`, `version`, and `description` for the `info` block,\n * `prefix` (default `/api`), and the `services` to describe (the global\n * registry's by default).\n * @returns The document as a plain object.\n */\nexport function generateOpenApiSpec(\n options: OpenApiGeneratorOptions = {},\n): Record<string, any> {\n const title = options.title ?? OPENAPI_DEFAULTS.title;\n const version = options.version ?? OPENAPI_DEFAULTS.version;\n const description =\n options.description ??\n \"Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.\";\n const prefix = options.prefix ?? DEFAULT_PREFIX;\n\n const services = options.services ?? getGlobalRegistry().list();\n\n const paths: Record<string, any> = {};\n const tags = new Map<string, string>();\n let hasAnyAuthorizedAction = false;\n\n // The routes the server mounts: shadowed ones are left out, as the router leaves them out.\n const { ir, bindings } = analyzeDeclaredApplication([...services], prefix);\n for (const service of services) {\n tags.set(service.name, `Actions exposed by '${service.name}' service`);\n\n for (const [index, route] of ir.routes.entries()) {\n if (route.service !== service.name) continue;\n const { action } = bindings[index]!;\n const routePath = route.path;\n const method = route.method.toLowerCase();\n const pathParams = pathParamNames(routePath);\n const actionPath = toOpenApiPath(routePath);\n if (!paths[actionPath]) paths[actionPath] = {};\n\n const { plugin, resource } = actionOwners(action);\n // Resource routes group under `service · resource`.\n const group = resource ? `${service.name} · ${resource}` : service.name;\n if (resource)\n tags.set(\n group,\n `Routes of resource '${resource}' in service '${service.name}'`,\n );\n\n const webhook = webhookOf(action);\n const hasAuth = getActionAccess(action).hasAuthorize;\n if (hasAuth) {\n hasAnyAuthorizedAction = true;\n }\n\n const responses: Record<string, any> = {};\n\n if (action.config.output) {\n responses[\"200\"] = {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: action.config.output,\n },\n },\n };\n } else {\n responses[\"200\"] = {\n description: \"Successful response\",\n };\n }\n\n const errorAlternatives = new Set<string>();\n const addError = (\n code: string,\n status: number,\n message: string,\n details?: unknown,\n ) => {\n const key = `${status}:${code}`;\n if (errorAlternatives.has(key)) return;\n errorAlternatives.add(key);\n const schema = {\n allOf: [\n { $ref: \"#/components/schemas/ErrorEnvelope\" },\n {\n type: \"object\",\n properties: {\n code: { const: code },\n status: { const: status },\n ...(details ? { details } : {}),\n },\n },\n ],\n };\n const existing = responses[String(status)];\n if (existing) {\n existing.description += \"; \" + message;\n existing.content[\"application/json\"].schema.oneOf.push(schema);\n } else {\n responses[String(status)] = {\n description: message,\n content: { \"application/json\": { schema: { oneOf: [schema] } } },\n };\n }\n };\n if (action.config.input)\n addError(\"VALIDATION_FAILED\", 400, \"Validation error\");\n if (hasAuth) {\n addError(\"UNAUTHORIZED\", 401, \"Authentication required\");\n addError(\"FORBIDDEN\", 403, \"Access denied\");\n }\n if (webhook) {\n addError(\"UNAUTHORIZED\", 401, \"Webhook verification failed\");\n addError(\n \"PAYLOAD_TOO_LARGE\",\n 413,\n `Body over ${webhook.maxBodyBytes} bytes`,\n );\n if (webhook.replay) {\n addError(\n \"CONFLICT\",\n 409,\n \"Another delivery of this event is being handled; retry later\",\n );\n addError(\n \"SERVICE_UNAVAILABLE\",\n 503,\n \"Webhook storage is unavailable; retry later\",\n );\n }\n }\n if ((action.config as { dashboard?: boolean }).dashboard === true)\n addError(\"UNAUTHORIZED\", 401, \"Only for the dashboard\");\n if (rateLimitsOf(action.config)) {\n addError(\n \"RATE_LIMITED\",\n 429,\n \"Too many calls; retry after Retry-After seconds\",\n {\n type: \"object\",\n properties: { retryAfterSeconds: { type: \"integer\", minimum: 1 } },\n required: [\"retryAfterSeconds\"],\n },\n );\n responses[\"429\"].headers = {\n \"Retry-After\": {\n description: \"Seconds until the window resets\",\n schema: { type: \"integer\", minimum: 1 },\n },\n };\n }\n if (action.config.errors) {\n for (const [code, errorDef] of Object.entries(action.config.errors)) {\n const def = errorDef as ActionErrorDefinition;\n addError(code, def.status || 400, def.message || code, def.details);\n }\n }\n addError(\"INTERNAL_SERVER_ERROR\", 500, \"Internal server error\");\n if (action.config.output)\n addError(\"VALIDATION_FAILED\", 500, \"Output validation error\");\n\n const operation: Record<string, any> = {\n operationId: `${service.name}_${action.name}_${method}`,\n summary: `${service.name}.${action.name}`,\n description:\n action.config.description ??\n `Execute action '${action.name}' on service '${service.name}'`,\n tags: [...new Set([group, ...(action.config.tags ?? [])])],\n ...(webhook ? { \"x-brick-webhook\": true } : {}),\n ...(plugin ? { \"x-brick-plugin\": plugin } : {}),\n ...(resource ? { \"x-brick-resource\": resource } : {}),\n responses,\n };\n\n const inputSchema = writeOnly(action.config.input);\n const properties = inputSchema?.properties ?? {};\n const parameters: any[] = [...new Set(pathParams)].map((key) => ({\n name: key,\n in: \"path\",\n required: true,\n schema: properties[key] ?? { type: \"string\" },\n }));\n if (route.inputSource === \"query\") {\n for (const [key, schema] of Object.entries(properties)) {\n if (pathParams.includes(key)) continue;\n parameters.push({\n name: key,\n in: \"query\",\n required: inputSchema?.required?.includes(key) ?? false,\n schema,\n });\n }\n } else if (inputSchema) {\n const bodySchema =\n pathParams.length && inputSchema.properties\n ? {\n ...inputSchema,\n properties: Object.fromEntries(\n Object.entries(properties).filter(\n ([key]) => !pathParams.includes(key),\n ),\n ),\n required: (inputSchema.required ?? []).filter(\n (key: string) => !pathParams.includes(key),\n ),\n }\n : inputSchema;\n operation.requestBody = {\n required: true,\n content: {\n [fileFields(inputSchema).length\n ? \"multipart/form-data\"\n : \"application/json\"]: { schema: bodySchema },\n ...(webhook\n ? { \"application/x-www-form-urlencoded\": { schema: bodySchema } }\n : {}),\n },\n };\n }\n if (parameters.length) operation.parameters = parameters;\n if (hasAuth) operation.security = [{ bearerAuth: [] }];\n paths[actionPath][method] = operation;\n }\n }\n\n const spec: Record<string, any> = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n description,\n },\n paths,\n tags: Array.from(tags, ([name, description]) => ({ name, description })),\n };\n\n spec.components = {\n schemas: {\n ErrorEnvelope: {\n type: \"object\",\n required: [\"name\", \"code\", \"message\", \"status\", \"requestId\"],\n properties: {\n name: { type: \"string\" },\n code: { type: \"string\" },\n message: { type: \"string\" },\n status: { type: \"integer\" },\n requestId: { type: \"string\" },\n details: {},\n errors: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"path\", \"message\"],\n properties: {\n path: { type: \"string\" },\n message: { type: \"string\" },\n },\n },\n },\n },\n },\n },\n };\n if (hasAnyAuthorizedAction) {\n Object.assign(spec.components, {\n securitySchemes: {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n description: \"Enter your Bearer authentication token\",\n },\n },\n });\n }\n\n const events = Object.fromEntries(\n services.flatMap((service) =>\n Object.values(\n (service as { events?: Record<string, EventRef> }).events ?? {},\n ).map((ref) => [\n ref.name,\n {\n service: service.name,\n payload: ref.schema,\n ...(ref.plugin ? { \"x-brick-plugin\": ref.plugin } : {}),\n },\n ]),\n ),\n );\n if (Object.keys(events).length) spec[\"x-brick-events\"] = events;\n\n // Operations reference live TypeBox schemas. Rewrite only the serialized\n // document so OpenAPI pointers cannot corrupt runtime validation schemas.\n const document: Record<string, any> = JSON.parse(JSON.stringify(spec));\n hoistAnchoredSchemas(document);\n\n return document;\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface RequestLoggingOptions {\n enabled?: boolean;\n logger?: (msg: string) => void;\n}\n\nfunction formatLog(\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number,\n): string {\n return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n}\n\n/**\n * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError\n * while `set.status` may still hold the 200 default when onError runs).\n */\nfunction thrownStatus(error: unknown): number | undefined {\n if (typeof error === \"object\" && error !== null && \"status\" in error) {\n const status: unknown = error.status;\n if (typeof status === \"number\") return status;\n }\n return undefined;\n}\n\n/**\n * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.\n * Timing is tracked per-Request via a WeakMap. The onError hook only logs and\n * returns undefined so existing error mapping is preserved.\n *\n * Hooks are registered with the \"global\" scope so they propagate to the\n * parent app when mounted via `app.use(...)` — Elysia scopes plain instance\n * hooks to the plugin's own routes. Timing is captured in beforeHandle\n * because request hooks are not propagated from a\n * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().\n */\nexport function requestLoggingPlugin(opts: RequestLoggingOptions = {}): Elysia {\n const plugin = new Elysia();\n const enabled = opts.enabled ?? true;\n if (!enabled) return plugin;\n const logger = opts.logger ?? console.log;\n const startedAt = new WeakMap<object, number>();\n\n const markStarted = ({ request }: Pick<Context, \"request\">): void => {\n startedAt.set(request, Date.now());\n };\n\n const logSuccess = ({\n request,\n set,\n responseValue,\n }: Pick<Context, \"request\" | \"set\"> & { responseValue?: unknown }): void => {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n // A raw route's Response carries its own status; `set.status` stays 200.\n const status =\n responseValue instanceof Response\n ? responseValue.status\n : (set.status ?? 200);\n logger(formatLog(request.method, path, status, Date.now() - start));\n };\n\n const logError = ({\n request,\n set,\n error,\n }: Pick<Context, \"request\" | \"set\"> & { error?: unknown }): undefined => {\n if (request) {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n const status = thrownStatus(error) ?? set.status ?? 500;\n logger(formatLog(request.method, path, status, Date.now() - start));\n }\n return undefined;\n };\n\n plugin.onBeforeHandle(\"global\", markStarted);\n plugin.onAfterHandle(\"global\", logSuccess);\n plugin.onError(\"global\", logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\nimport { OPENAPI_DEFAULTS } from \"./openapi\";\n\n/** An OpenAPI document as plain JSON. */\nexport type OpenApiDocument = Record<string, unknown>;\n\n/** An extra OpenAPI document for the API reference, such as Better Auth's. */\nexport interface ReferenceDocument {\n /** Name in the reference's list of documents. */\n title: string;\n /** The document, or a function returning it; called each time the app starts. */\n document:\n | OpenApiDocument\n | (() => OpenApiDocument | Promise<OpenApiDocument>);\n}\n\n/** A named OpenAPI document ready to render. */\nexport interface ApiDocument {\n title: string;\n document: OpenApiDocument;\n}\n\n/** Developer documentation for the `brick dev` dashboard. */\nexport interface DocumentationOptions {\n /**\n * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the\n * app entry, as it reads in the file that sets it.\n */\n dir: string;\n /**\n * Module whose exports are React components for MDX, added to the built-in\n * ones; a relative path starts where `dir` does. A default export or a\n * `components` export holds the name-to-component map. The dashboard bundles\n * it, so it may import anything the project has.\n */\n components?: string;\n}\n\nexport interface ReferenceOptions {\n /** Also serve a standalone Scalar page here. Without a path, no page is served. */\n path?: string;\n title?: string;\n specUrl?: string;\n /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */\n documents?: ReferenceDocument[];\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/**\n * Standalone Elysia plugin serving GET <path> with the Scalar HTML page.\n *\n * @deprecated Use `brick({ reference: true })` or `reference: { path }`.\n */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? OPENAPI_DEFAULTS.title;\n const specUrl = opts.specUrl ?? OPENAPI_DEFAULTS.path;\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/**\n * Mounts the Scalar reference route onto an existing app.\n *\n * @deprecated Use `brick({ reference: true })` or `reference: { path }`.\n */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","import type { DashboardUser } from \"./dashboard-identity\";\n\n/** Who may open the dashboard that `brick start` serves for monitoring. */\nexport interface DashboardAuth {\n /**\n * Secrets that let a request in. A browser asks for one in its sign-in\n * prompt (any user name, the secret as the password), and monitors and\n * scripts send `Authorization: Bearer <secret>`. Give several to rotate one\n * while the other still works. Each is at least 16 characters long;\n * `openssl rand -base64 32` makes a good one.\n */\n token?: string | readonly string[];\n /**\n * Your own check, to sign people in with the auth the app already has: read\n * a session cookie, verify a Better Auth or Clerk session, look at a header\n * a proxy adds. It receives the request (method, URL, and headers; no body)\n * and returns `true` to let it in, `false` to refuse it with 401, or a\n * `Response` to send instead, such as a redirect to your login page. If it\n * throws or takes longer than five seconds, the request is refused with 503.\n *\n * Return `{ user: { id, name } }` to let it in and say who it is: requests\n * the dashboard's pages send to the app through `/app/*` carry that user,\n * signed, which the app reads with `ctx.dashboard?.user` in an action or\n * `dashboardUser(request)` in an endpoint.\n *\n * A request is let in when it carries a valid `token`, or when this\n * returns `true`; give both to let monitors in by token and people in by\n * sign-in.\n */\n authorize?: (\n request: Request,\n ) =>\n | boolean\n | Response\n | { user: DashboardUser }\n | Promise<boolean | Response | { user: DashboardUser }>;\n}\n\n/**\n * The monitoring dashboard `brick start` serves beside the app, on a port of\n * its own: live requests, logs, errors, and the shape of the service, so it\n * stays reachable when the app's own routes are not. `brick dev` has its own\n * dashboard, set by command line options, and ignores this.\n *\n * Setting it turns on `telemetry`, since the dashboard shows what is traced.\n * While it is on, `ctx.logger` and `console` lines written during a request\n * go to the dashboard instead of the console.\n */\nexport interface DashboardOptions {\n /** Default 9400. */\n port?: number;\n /**\n * The address to listen on. Default `127.0.0.1`, reachable only from the same\n * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard\n * will not start on any other address without it.\n */\n host?: string;\n auth?: DashboardAuth;\n /**\n * Days of finished requests to keep on disk, in `.brick/` of the working\n * folder. Default 0: only what happened since the process started, which is\n * lost when it restarts. Needs a folder that outlives the container.\n */\n historyDays?: number;\n /**\n * Show the Schedules and Workflows views, which `brick dev` always has: each\n * schedule's next run and last runs, and the workflow inspector with every\n * run's steps. Default false, because they do more than monitor: a signed-in\n * user (one `auth.authorize` returned as `{ user }`) can run a schedule now,\n * cancel or replay a run, and resume a hook. Anyone else the dashboard lets\n * in (by token, or by `authorize` returning `true`) can only look.\n */\n inspector?: boolean;\n /**\n * Let a coding agent (Claude Code, Cursor, Codex) read the dashboard's data\n * over MCP at `/mcp`, while it debugs: requests, traces, logs, errors and the\n * app's architecture. Default false; `brick dev` always has it, since it only\n * listens on this machine. Its own tools only read, even for a signed-in\n * user, and it passes the same checks as the rest of the dashboard: the agent sends\n * `Authorization: Bearer <token>` with one of `auth.token`.\n *\n * What the agent reads goes to its model provider: request paths and\n * messages, log lines (which can hold what your users typed), error stacks,\n * and span attributes such as SQL text. Turn it on only for a dashboard\n * whose data you are willing to send there.\n *\n * It also serves the app's own tools marked `dashboard: true` (see\n * `service.tool`), next to the dashboard's. A tool that is not marked\n * `readOnlyHint: true` can change data, and is offered only to a signed-in\n * user (one `auth.authorize` returned as `{ user }`).\n */\n mcp?: boolean;\n}\n\n/**\n * Where the app answers MCP for the dashboard's `/mcp`: its tools marked\n * `dashboard: true`. Only a request signed by the dashboard gets in.\n */\nexport const DASHBOARD_MCP_ROUTE = \"/_brick/dashboard/mcp\";\n\n/** The dashboard's own MCP tools. A `dashboard: true` tool may not take one of these names. */\nexport const DASHBOARD_MCP_TOOLS = [\n \"summary\",\n \"list_requests\",\n \"get_trace\",\n \"list_errors\",\n \"app_overview\",\n \"search_logs\",\n \"list_reloads\",\n \"list_schedules\",\n \"list_runs\",\n \"get_run\",\n \"get_openapi\",\n \"list_docs\",\n \"read_doc\",\n] as const;\n\nconst MIN_TOKEN_LENGTH = 16;\n\n/**\n * Check what `brick()` was given, and freeze it. The secrets sit behind a getter\n * that is not enumerable, so logging or serializing the application definition\n * does not print them.\n */\nexport function normalizeDashboard(\n options: DashboardOptions | undefined,\n): DashboardOptions | undefined {\n if (options === undefined) return undefined;\n const { port, host, auth, historyDays, inspector, mcp } = options;\n if (\n port !== undefined &&\n (!Number.isInteger(port) || port < 1 || port > 65535)\n )\n throw new Error(\n `Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`,\n );\n if (host !== undefined && (typeof host !== \"string\" || host.trim() === \"\"))\n throw new Error(\n \"Brick: dashboard host must be an address, such as '0.0.0.0'.\",\n );\n if (\n historyDays !== undefined &&\n (!Number.isInteger(historyDays) || historyDays < 0)\n )\n throw new Error(\n `Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`,\n );\n if (inspector !== undefined && typeof inspector !== \"boolean\")\n throw new Error(\"Brick: dashboard inspector must be true or false.\");\n if (mcp !== undefined && typeof mcp !== \"boolean\")\n throw new Error(\"Brick: dashboard mcp must be true or false.\");\n const normalized: DashboardOptions = {\n ...(port !== undefined ? { port } : {}),\n ...(host !== undefined ? { host: host.trim() } : {}),\n ...(historyDays !== undefined ? { historyDays } : {}),\n ...(inspector !== undefined ? { inspector } : {}),\n ...(mcp !== undefined ? { mcp } : {}),\n };\n if (auth !== undefined) {\n const tokens =\n auth.token === undefined\n ? undefined\n : typeof auth.token === \"string\"\n ? [auth.token]\n : [...auth.token];\n if (\n tokens?.some(\n (token) => typeof token !== \"string\" || token.length < MIN_TOKEN_LENGTH,\n )\n )\n throw new Error(\n `Brick: a dashboard token must be at least ${MIN_TOKEN_LENGTH} characters. Try: openssl rand -base64 32`,\n );\n if (auth.authorize !== undefined && typeof auth.authorize !== \"function\")\n throw new Error(\"Brick: dashboard authorize must be a function.\");\n if ((tokens === undefined || tokens.length === 0) && !auth.authorize)\n throw new Error(\n \"Brick: dashboard auth needs a token or an authorize function.\",\n );\n const secrets = Object.freeze({\n ...(tokens ? { token: Object.freeze(tokens) } : {}),\n ...(auth.authorize ? { authorize: auth.authorize } : {}),\n });\n // A getter, so inspecting the object (Bun prints hidden fields too) shows\n // `[Getter]` and not the secrets.\n Object.defineProperty(normalized, \"auth\", {\n enumerable: false,\n get: () => secrets,\n });\n }\n return Object.freeze(normalized);\n}\n","import {\n DuplicateNameError,\n type ActionContext,\n type Service,\n type Tool,\n type ToolAnnotations,\n} from \"./types\";\nimport { withClientIp, type ClientIp } from \"./rate-limit\";\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 }`.\nexport const 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 * Where the client address is, for a tool's `rateLimit: { per: \"ip\" }`, as\n * `brick({ clientIp })`. Mounted on a Brick app, the handler already uses\n * the app's; this one replaces it.\n */\n clientIp?: ClientIp;\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 if (options.clientIp) withClientIp(request, options.clientIp);\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","import type { HttpMethod } from \"./http\";\nimport type { RouteIR } from \"./compiler/ir\";\nimport type { Elysia } from \"elysia\";\nimport type { Logger, Service } from \"./types\";\nimport type { DatabaseHandle } from \"./db/define\";\nimport type { ApiDocument, DocumentationOptions } from \"./docs\";\nimport type { DashboardOptions } from \"./dashboard\";\nimport type { EventsDefinition, EventsHub } from \"./events/hub\";\nimport { toErrorResponse } from \"./error-response\";\nimport { pathParamNames, toOpenApiPath } from \"./routes\";\nimport { createLogger } from \"./logger\";\nimport { requestIds } from \"./context\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport type { InstalledPlugin } from \"./plugin-types\";\n\nexport type EndpointMethod = HttpMethod;\n\n/** The logger handed to endpoint handlers (the same one actions get). */\nexport type EndpointLogger = Logger;\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n /** The plugin that contributed it; OpenAPI labels it `x-brick-plugin`. */\n plugin?: string;\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb();\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n const tag = `endpoint:${def.method} ${def.path}`;\n const logger = createLogger(`[${tag}]`);\n return async ({ params, body, query, headers, request, set }: any) => {\n const { traceId, requestId } = requestIds(headers, set);\n\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger,\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err) {\n const failure =\n !(\n err instanceof ActionExecutionError || err instanceof ValidationError\n ) &&\n err !== null &&\n typeof err === \"object\" &&\n \"status\" in err &&\n typeof err.status === \"number\" &&\n Number.isInteger(err.status) &&\n err.status >= 400 &&\n err.status < 500\n ? new ActionExecutionError(\n \"HTTP_ERROR\",\n \"message\" in err && typeof err.message === \"string\"\n ? err.message\n : \"Endpoint error\",\n err.status,\n undefined,\n { cause: err },\n )\n : err;\n const response = toErrorResponse(failure, {\n logger: ctx.logger,\n requestId,\n });\n set.status = response.status;\n return response;\n }\n };\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(def.plugin ? { \"x-brick-plugin\": def.plugin } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Service definitions, prefix, and telemetry setting chosen at construction. */\n readonly definition: {\n readonly routes: readonly RouteIR[];\n readonly sockets: readonly (BrickSocketSchema & {\n service: string;\n path: string;\n })[];\n readonly services: readonly Service<any, any>[];\n readonly prefix: string;\n readonly telemetry: boolean;\n readonly documentation?: DocumentationOptions;\n /** What `brick start` serves for monitoring; its `auth` is not enumerable. */\n readonly dashboard?: DashboardOptions;\n /** The listeners and settings of `events`, as plain data. */\n readonly events?: EventsDefinition;\n /** Every `definePlugin` installation, in install order. */\n readonly plugins?: readonly InstalledPlugin[];\n };\n /**\n * Run the plugins' `on(\"start\")` handlers in install order, once. `listen`\n * calls it; `brick dev` and `brick start` await it before serving. `stop()`\n * runs their `on(\"stop\")` handlers in reverse order.\n */\n start(): Promise<void>;\n /**\n * Start the plugins, listen on `port`, then start event delivery. What\n * `brick dev`, `brick start` and a built server run.\n */\n serve(options: { port: number }): Promise<BrickApp>;\n /**\n * Stop event delivery (finishing deliveries in flight), then the server, then\n * the plugins. `closeActiveConnections` is passed to `stop()`.\n */\n shutdown(closeActiveConnections?: boolean): Promise<void>;\n /**\n * The events of this app, when `events` is set: start and stop delivery, drain\n * what is due, and see or retry what is parked. `brick dev` and `brick start`\n * start it for you.\n */\n readonly events?: EventsHub;\n /** Register a raw endpoint (a plain route, not an action). */\n endpoint(def: EndpointDefinition): void;\n /**\n * The OpenAPI documents behind the dashboard's APIs view: this app's own\n * unless `docs` is false, then those from `reference.documents`.\n */\n referenceDocuments(): Promise<ApiDocument[]>;\n /** This app's OpenAPI document, as `/openapi.json` serves it (also when `docs` is false). */\n openApiDocument(): Record<string, any>;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","const ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nexport function newEventId(now: number = Date.now()): string {\n let time = \"\";\n let remaining = now;\n for (let index = 0; index < 10; index++) {\n time = ALPHABET[remaining % 32] + time;\n remaining = Math.floor(remaining / 32);\n }\n let random = \"\";\n for (const byte of crypto.getRandomValues(new Uint8Array(16))) {\n random += ALPHABET[byte % 32];\n }\n return `evt_${time}${random}`;\n}\n\n/**\n * A delivery's id: `<event id>:<listener>`, which is why a listener name cannot\n * contain `:`.\n */\nexport const deliveryId = (eventId: string, listener: string) =>\n `${eventId}:${listener}`;\n","import {\n bigserial,\n index as pgIndex,\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp,\n} from \"drizzle-orm/pg-core\";\nimport {\n index as sqliteIndex,\n integer as sqliteInteger,\n sqliteTable,\n text as sqliteText,\n} from \"drizzle-orm/sqlite-core\";\nimport { deliveryId } from \"./id\";\nimport type { EventDelivery, EventEnvelope } from \"./types\";\n\nconst OUTBOX = Symbol.for(\"brick.outbox\");\n\nexport const OUTBOX_STATUSES = [\n \"pending\",\n \"claimed\",\n \"delivered\",\n \"dead\",\n] as const;\n/** What the outbox rows are in, by state. */\nexport type OutboxStatus = (typeof OUTBOX_STATUSES)[number];\n\nfunction sqliteOutbox(name: string) {\n const timestampMs = (column: string) =>\n sqliteInteger(column, { mode: \"timestamp_ms\" });\n return sqliteTable(\n name,\n {\n seq: sqliteInteger(\"seq\").primaryKey({ autoIncrement: true }),\n id: sqliteText(\"id\").notNull().unique(),\n eventId: sqliteText(\"event_id\").notNull(),\n listener: sqliteText(\"listener\").notNull(),\n name: sqliteText(\"name\").notNull(),\n payload: sqliteText(\"payload\", { mode: \"json\" }).notNull(),\n traceId: sqliteText(\"trace_id\"),\n source: sqliteText(\"source\"),\n occurredAt: timestampMs(\"occurred_at\").notNull(),\n status: sqliteText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: sqliteInteger(\"attempts\").notNull().default(0),\n lastError: sqliteText(\"last_error\"),\n availableAt: timestampMs(\"available_at\").notNull(),\n claimedAt: timestampMs(\"claimed_at\"),\n deliveredAt: timestampMs(\"delivered_at\"),\n },\n (table) => [\n sqliteIndex(`${name}_due`).on(table.status, table.availableAt),\n sqliteIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\nfunction postgresOutbox(name: string) {\n const at = (column: string) => timestamp(column, { withTimezone: true });\n return pgTable(\n name,\n {\n seq: bigserial(\"seq\", { mode: \"number\" }).primaryKey(),\n id: pgText(\"id\").notNull().unique(),\n eventId: pgText(\"event_id\").notNull(),\n listener: pgText(\"listener\").notNull(),\n name: pgText(\"name\").notNull(),\n payload: jsonb(\"payload\").notNull(),\n traceId: pgText(\"trace_id\"),\n source: pgText(\"source\"),\n occurredAt: at(\"occurred_at\").notNull(),\n status: pgText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: pgInteger(\"attempts\").notNull().default(0),\n lastError: pgText(\"last_error\"),\n availableAt: at(\"available_at\").notNull(),\n claimedAt: at(\"claimed_at\"),\n deliveredAt: at(\"delivered_at\"),\n },\n (table) => [\n pgIndex(`${name}_due`).on(table.status, table.availableAt),\n pgIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\n/** The outbox table of a SQLite database. */\nexport type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;\n/** The outbox table of a Postgres database. */\nexport type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;\n/** An outbox table, made by `outboxTable`. */\nexport type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;\n\n/**\n * The outbox table: where recorded events wait, one row per listener, until they\n * are delivered. A write and the events it causes are inserted in one transaction,\n * so an event is neither lost when the process dies after the write nor sent for a\n * write that was rolled back.\n *\n * Brick does not create tables for you. Put this in the schema of the database\n * whose writes emit events, and your migration tool (such as drizzle-kit) creates\n * it. A service whose database holds the table records events; one without it does\n * not.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_outbox`.\n * @returns A Drizzle table.\n * @example\n * import { defineDatabase, outboxTable } from \"@brickkit/core\";\n *\n * export const outbox = outboxTable(\"postgres\");\n * export const database = defineDatabase({\n * engine: \"postgres\",\n * tables: { users, outbox },\n * });\n */\nexport function outboxTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteOutboxTable;\nexport function outboxTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresOutboxTable;\nexport function outboxTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): OutboxTable {\n const name = options.name ?? \"brick_outbox\";\n const table = engine === \"sqlite\" ? sqliteOutbox(name) : postgresOutbox(name);\n Object.defineProperty(table, OUTBOX, { value: { engine } });\n return table;\n}\n\n/**\n * Whether a value is an outbox table made by `outboxTable`.\n *\n * @param value - Anything.\n * @returns `true` for an outbox table, narrowing its type.\n */\nexport function isOutboxTable(value: unknown): value is OutboxTable {\n return typeof value === \"object\" && value !== null && OUTBOX in value;\n}\n\nexport type OutboxRow = OutboxTable[\"$inferSelect\"];\n\n/** The rows that record an event: one per listener, due now. */\nexport function outboxRows(\n event: Omit<EventEnvelope, \"occurredAt\"> & { occurredAt: Date },\n listeners: readonly string[],\n) {\n return listeners.map((listener) => ({\n id: deliveryId(event.id, listener),\n eventId: event.id,\n listener,\n name: event.name,\n payload: event.payload,\n traceId: event.traceId ?? null,\n source: event.source ?? null,\n occurredAt: event.occurredAt,\n status: \"pending\" as const,\n attempts: 0,\n availableAt: event.occurredAt,\n }));\n}\n\n/** The delivery a row of `outboxRows` is. */\nexport function deliveryOf(row: OutboxRow): EventDelivery {\n return {\n id: row.eventId,\n name: row.name,\n payload: row.payload,\n occurredAt: row.occurredAt.toISOString(),\n ...(row.traceId ? { traceId: row.traceId } : {}),\n ...(row.source ? { source: row.source } : {}),\n listener: row.listener,\n deliveryId: row.id,\n attempt: row.attempts,\n };\n}\n\nexport function outboxEngine(table: OutboxTable): \"sqlite\" | \"postgres\" {\n return (\n table as unknown as Record<symbol, { engine: \"sqlite\" | \"postgres\" }>\n )[OUTBOX].engine;\n}\n","import { and, asc, eq, inArray, lt, lte, or, sql } from \"drizzle-orm\";\nimport {\n deliveryOf,\n OUTBOX_STATUSES,\n outboxEngine,\n type OutboxRow,\n type OutboxStatus,\n type OutboxTable,\n} from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type { Deliverable } from \"./hub\";\nimport { ActionExecutionError } from \"../types\";\nimport type { DispatchOptions } from \"./types\";\n\nfunction resolveDispatchOptions(\n options: DispatchOptions,\n): Required<DispatchOptions> {\n return {\n timer: options.timer ?? true,\n intervalMs: options.intervalMs ?? 1_000,\n batchSize: options.batchSize ?? 50,\n maxAttempts: options.maxAttempts ?? 8,\n claimTimeoutMs: options.claimTimeoutMs ?? 60_000,\n maxBackoffMs: options.maxBackoffMs ?? 300_000,\n retainDeliveredMs: options.retainDeliveredMs ?? 86_400_000,\n };\n}\n\n/** How many outbox rows are in each state. */\nexport type OutboxCounts = Record<OutboxStatus, number>;\n\nconst PURGE_INTERVAL_MS = 60_000;\n\n/** Listeners whose `retry` threw, logged once each. */\nconst brokenRetry = new WeakSet<Deliverable>();\n\n/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as \"retry\", and is logged once. */\nfunction decideRetry(\n name: string,\n listener: Deliverable,\n error: unknown,\n): \"retry\" | \"dead\" {\n if (!listener.retry) return \"retry\";\n try {\n return listener.retry(\n error instanceof ActionExecutionError && listener.errors?.[error.code]\n ? { code: error.code, message: error.message, details: error.details }\n : {\n code: \"UNKNOWN\",\n message: error instanceof Error ? error.message : String(error),\n cause: error,\n },\n );\n } catch (thrown) {\n if (!brokenRetry.has(listener)) {\n brokenRetry.add(listener);\n console.error(\n `[Brick-TS events] Listener '${name}': its retry() threw, so the failure is retried. Later throws are not logged.`,\n thrown,\n );\n }\n return \"retry\";\n }\n}\n\nexport function backoffMs(attempt: number, maxBackoffMs: number): number {\n return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);\n}\n\n/**\n * Delivers the events recorded in one outbox table to the app's listeners.\n *\n * It claims a batch of due rows, runs each listener, and marks the row delivered.\n * A listener that throws is retried later with a growing delay, and parked as\n * dead after its attempts run out. Several dispatchers can share a table: on\n * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not\n * finished within `claimTimeoutMs` (the process died) is taken by another.\n * Delivery is at least once, so a listener should tolerate running twice for the\n * same `deliveryId`.\n */\nexport class Dispatcher {\n private readonly engine: \"sqlite\" | \"postgres\";\n private readonly options: Required<DispatchOptions>;\n private readonly inFlight = new Set<Promise<void>>();\n private timer?: ReturnType<typeof setInterval>;\n private tickQueue?: Promise<number>;\n private lastPurge = 0;\n\n constructor(\n private readonly db: any,\n private readonly table: OutboxTable,\n private readonly listeners: (name: string) => Deliverable | undefined,\n options: DispatchOptions = {},\n ) {\n this.engine = outboxEngine(table);\n this.options = resolveDispatchOptions(options);\n }\n\n /** Start looking for due deliveries on a timer. Does nothing if it already is. */\n start(): void {\n if (this.timer || !this.options.timer) return;\n this.timer = setInterval(() => void this.tick(), this.options.intervalMs);\n this.timer.unref?.();\n void this.tick();\n }\n\n /** Stop the timer and wait for the deliveries that are running to finish. */\n async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n await this.tickQueue;\n await Promise.allSettled(this.inFlight);\n }\n\n /** Look for work soon, without waiting for the timer. Safe to call often. */\n notify(): void {\n if (!this.timer) return;\n setTimeout(() => void this.tick(), 0).unref?.();\n }\n\n /** Claim what is due and run it, once. @returns How many deliveries it started. */\n private tick(): Promise<number> {\n this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(\n () => this.claimAndRun(),\n () => this.claimAndRun(),\n );\n return this.tickQueue;\n }\n\n /**\n * Deliver everything that is due now and wait until those deliveries are done.\n * Deliveries that fail and are rescheduled are not waited for again.\n *\n * @returns How many deliveries it ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (;;) {\n const started = await this.tick();\n await Promise.allSettled(this.inFlight);\n if (started === 0) return total;\n total += started;\n }\n }\n\n async counts(): Promise<OutboxCounts> {\n const t = this.table as any;\n const rows: { status: OutboxStatus; count: number }[] = await this.db\n .select({ status: t.status, count: sql<number>`count(*)` })\n .from(t)\n .groupBy(t.status);\n const counts = Object.fromEntries(\n OUTBOX_STATUSES.map((status) => [status, 0]),\n ) as OutboxCounts;\n for (const row of rows) counts[row.status] = Number(row.count);\n return counts;\n }\n\n /**\n * Put parked deliveries back in line, with their attempts reset.\n *\n * @param deliveryId - One delivery to retry. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n const t = this.table as any;\n const rows: { id: string }[] = await this.db\n .update(t)\n .set({ status: \"pending\", attempts: 0, availableAt: new Date() })\n .where(\n deliveryId\n ? and(eq(t.status, \"dead\"), eq(t.id, deliveryId))\n : eq(t.status, \"dead\"),\n )\n .returning({ id: t.id });\n if (rows.length) this.notify();\n return rows.length;\n }\n\n private async claimAndRun(): Promise<number> {\n try {\n const room = this.options.batchSize - this.inFlight.size;\n if (room <= 0) return 0;\n const rows = await this.claim(room);\n for (const row of rows) {\n const run = this.deliver(row).finally(() => {\n this.inFlight.delete(run);\n });\n this.inFlight.add(run);\n }\n await this.purgeDelivered();\n return rows.length;\n } catch (error) {\n this.logError(error);\n return 0;\n }\n }\n\n private async claim(limit: number): Promise<OutboxRow[]> {\n const t = this.table as any;\n const now = new Date();\n const stale = new Date(now.getTime() - this.options.claimTimeoutMs);\n const due = or(\n and(eq(t.status, \"pending\"), lte(t.availableAt, now)),\n and(eq(t.status, \"claimed\"), lt(t.claimedAt, stale)),\n );\n const claimIn = async (tx: any): Promise<OutboxRow[]> => {\n let select = tx\n .select()\n .from(t)\n .where(due)\n .orderBy(asc(t.seq))\n .limit(limit);\n if (this.engine === \"postgres\")\n select = select.for(\"update\", { skipLocked: true });\n const picked: OutboxRow[] = await select;\n if (!picked.length) return [];\n await tx\n .update(t)\n .set({\n status: \"claimed\",\n claimedAt: now,\n attempts: sql`${t.attempts} + 1`,\n })\n .where(\n inArray(\n t.seq,\n picked.map((row) => row.seq),\n ),\n );\n return picked.map((row) => ({ ...row, attempts: row.attempts + 1 }));\n };\n return this.engine === \"postgres\"\n ? this.db.transaction(claimIn)\n : runInTransaction(this.db, claimIn);\n }\n\n private async deliver(row: OutboxRow): Promise<void> {\n const listener = this.listeners(row.listener);\n if (!listener) {\n await this.park(row, `No listener named '${row.listener}' is registered`);\n return;\n }\n try {\n await listener.run(deliveryOf(row));\n } catch (error) {\n await this.fail(\n row,\n error,\n listener.maxAttempts ?? this.options.maxAttempts,\n decideRetry(row.listener, listener, error),\n );\n return;\n }\n await this.markDelivered(row);\n }\n\n private async markDelivered(row: OutboxRow): Promise<void> {\n const t = this.table as any;\n try {\n if (this.options.retainDeliveredMs === 0)\n await this.db.delete(t).where(eq(t.seq, row.seq));\n else\n await this.db\n .update(t)\n .set({\n status: \"delivered\",\n deliveredAt: new Date(),\n lastError: null,\n })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.logError(error);\n }\n }\n\n private async fail(\n row: OutboxRow,\n error: unknown,\n maxAttempts: number,\n decision: \"retry\" | \"dead\",\n ): Promise<void> {\n const message = error instanceof Error ? error.message : String(error);\n if (decision === \"dead\" || row.attempts >= maxAttempts) {\n await this.park(row, message);\n return;\n }\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({\n status: \"pending\",\n lastError: message,\n claimedAt: null,\n availableAt: new Date(\n Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs),\n ),\n })\n .where(eq(t.seq, row.seq));\n } catch (writeError) {\n this.logError(writeError);\n }\n }\n\n private async park(row: OutboxRow, message: string): Promise<void> {\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({ status: \"dead\", lastError: message, claimedAt: null })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.logError(error);\n }\n }\n\n private logError(error: unknown): void {\n console.error(\"[Brick-TS events]\", error);\n }\n\n private async purgeDelivered(): Promise<void> {\n const keep = this.options.retainDeliveredMs;\n const now = Date.now();\n if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;\n this.lastPurge = now;\n const t = this.table as any;\n await this.db\n .delete(t)\n .where(\n and(eq(t.status, \"delivered\"), lt(t.deliveredAt, new Date(now - keep))),\n );\n }\n}\n","/*\n * Cron expressions and intervals, without dependencies.\n *\n * A cron expression has five fields (minute hour day-of-month month\n * day-of-week) or six, with seconds first. Fields take `*`, numbers, ranges\n * (`1-5`), steps (`*\\/15`, `0-30/10`, `5/10`), lists (`1,15`) and the names\n * `jan`-`dec` and `sun`-`sat`; day-of-week 7 is Sunday too. As in Vixie cron,\n * when both day fields are restricted a day matching either one matches. The\n * macros `@yearly`, `@monthly`, `@weekly`, `@daily` and `@hourly` work too.\n *\n * Times are wall-clock times in an IANA time zone. A time that does not exist\n * (it falls in the hour a DST change skips) runs when the clocks jump, shifted\n * by the gap; a time that happens twice (the hour a DST change repeats) runs\n * once, the first time.\n */\n\n/** A parsed cron expression: the allowed values of each field. */\nexport interface CronExpression {\n readonly source: string;\n readonly seconds: ReadonlySet<number>;\n readonly minutes: ReadonlySet<number>;\n readonly hours: ReadonlySet<number>;\n readonly days: ReadonlySet<number>;\n readonly months: ReadonlySet<number>;\n /** 0 is Sunday. */\n readonly weekdays: ReadonlySet<number>;\n /** Both day fields are restricted: a day matches when either does. */\n readonly eitherDay: boolean;\n}\n\nconst MACROS: Record<string, string> = {\n \"@yearly\": \"0 0 1 1 *\",\n \"@annually\": \"0 0 1 1 *\",\n \"@monthly\": \"0 0 1 * *\",\n \"@weekly\": \"0 0 * * 0\",\n \"@daily\": \"0 0 * * *\",\n \"@midnight\": \"0 0 * * *\",\n \"@hourly\": \"0 * * * *\",\n};\n\nconst MONTH_NAMES = \"jan feb mar apr may jun jul aug sep oct nov dec\".split(\n \" \",\n);\nconst DAY_NAMES = \"sun mon tue wed thu fri sat\".split(\" \");\n\nfunction parseField(\n field: string,\n min: number,\n max: number,\n names: string[] = [],\n nameBase = 0,\n): { values: Set<number>; star: boolean } {\n const value = (text: string): number => {\n const named = names.indexOf(text.toLowerCase());\n if (named >= 0) return named + nameBase;\n if (!/^\\d+$/.test(text)) throw new Error(`'${text}' is not a number`);\n const number = Number(text);\n if (number < min || number > max)\n throw new Error(`${number} is outside ${min}-${max}`);\n return number;\n };\n const values = new Set<number>();\n for (const part of field.split(\",\")) {\n const [range, stepText, extra] = part.split(\"/\");\n if (extra !== undefined || !range)\n throw new Error(`'${part}' is not a valid field`);\n const step = stepText === undefined ? 1 : Number(stepText);\n if (!Number.isInteger(step) || step < 1)\n throw new Error(`'${stepText}' is not a valid step`);\n let from: number;\n let to: number;\n if (range === \"*\") [from, to] = [min, max];\n else if (range.includes(\"-\")) {\n const [a, b, extra] = range.split(\"-\");\n if (extra !== undefined)\n throw new Error(`'${range}' is not a valid range`);\n [from, to] = [value(a!), value(b!)];\n if (from > to) throw new Error(`'${range}' runs backwards`);\n } else {\n from = value(range);\n // `5/10` means from 5 to the end, every 10.\n to = stepText === undefined ? from : max;\n }\n for (let v = from; v <= to; v += step) values.add(v);\n }\n // As in Vixie cron, `*/2` still counts as unrestricted for the day rule.\n return { values, star: field.startsWith(\"*\") || field.startsWith(\"?\") };\n}\n\n/**\n * Parse a cron expression.\n *\n * @throws When the expression is malformed.\n */\nexport function parseCron(expression: string): CronExpression {\n const source = expression.trim();\n const fields = (MACROS[source.toLowerCase()] ?? source).split(/\\s+/);\n if (fields.length === 5) fields.unshift(\"0\");\n if (fields.length !== 6)\n throw new Error(\n `Cron expression '${expression}' needs 5 fields (minute hour day month weekday), or 6 with seconds first`,\n );\n const [sec, min, hour, day, month, weekday] = fields as [\n string,\n string,\n string,\n string,\n string,\n string,\n ];\n try {\n const days = parseField(day.replace(\"?\", \"*\"), 1, 31);\n const weekdays = parseField(weekday.replace(\"?\", \"*\"), 0, 7, DAY_NAMES);\n if (weekdays.values.delete(7)) weekdays.values.add(0);\n return {\n source,\n seconds: parseField(sec, 0, 59).values,\n minutes: parseField(min, 0, 59).values,\n hours: parseField(hour, 0, 23).values,\n days: days.values,\n months: parseField(month, 1, 12, MONTH_NAMES, 1).values,\n weekdays: weekdays.values,\n eitherDay: !days.star && !weekdays.star,\n };\n } catch (error) {\n throw new Error(\n `Cron expression '${expression}': ${(error as Error).message}`,\n );\n }\n}\n\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\n/**\n * @throws When `timeZone` is not an IANA time zone this runtime knows.\n */\nexport function checkTimeZone(timeZone: string): void {\n formatter(timeZone);\n}\n\nfunction formatter(timeZone: string): Intl.DateTimeFormat {\n let found = formatters.get(timeZone);\n if (!found) {\n try {\n found = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n });\n } catch {\n throw new Error(`Unknown time zone '${timeZone}'`);\n }\n formatters.set(timeZone, found);\n }\n return found;\n}\n\n/** The wall-clock time at `instant` in `timeZone`, as if it were UTC (whole seconds). */\nfunction wallClock(instant: number, timeZone: string): number {\n const parts: Record<string, number> = {};\n for (const part of formatter(timeZone).formatToParts(instant))\n if (part.type !== \"literal\") parts[part.type] = Number(part.value);\n return Date.UTC(\n parts.year!,\n parts.month! - 1,\n parts.day!,\n parts.hour!,\n parts.minute!,\n parts.second!,\n );\n}\n\nconst DAY_MS = 86_400_000;\n\n/** The offset of `timeZone` from UTC at `instant`, in milliseconds. */\nconst offsetAt = (instant: number, timeZone: string) =>\n wallClock(instant, timeZone) - Math.floor(instant / 1000) * 1000;\n\n/**\n * The first instant whose wall-clock time in `timeZone` is `wall`, or, when\n * a DST change skips `wall`, the instant the clocks jump past it, shifted by\n * the gap.\n */\nfunction instantOf(wall: number, timeZone: string): number {\n const before = wall - offsetAt(wall - DAY_MS, timeZone);\n const after = wall - offsetAt(wall + DAY_MS, timeZone);\n const valid = [before, after].filter(\n (instant) => wallClock(instant, timeZone) === wall,\n );\n return valid.length ? Math.min(...valid) : before;\n}\n\nfunction dayMatches(cron: CronExpression, date: Date): boolean {\n const day = cron.days.has(date.getUTCDate());\n const weekday = cron.weekdays.has(date.getUTCDay());\n return cron.eitherDay ? day || weekday : day && weekday;\n}\n\n/** The first wall-clock time at or after `wall` that the expression matches, or undefined within eight years. */\nfunction nextWall(cron: CronExpression, wall: number): number | undefined {\n const d = new Date(wall);\n const limit = d.getUTCFullYear() + 8;\n while (d.getUTCFullYear() <= limit) {\n if (!cron.months.has(d.getUTCMonth() + 1)) {\n d.setUTCMonth(d.getUTCMonth() + 1, 1);\n d.setUTCHours(0, 0, 0);\n } else if (!dayMatches(cron, d)) {\n d.setUTCDate(d.getUTCDate() + 1);\n d.setUTCHours(0, 0, 0);\n } else if (!cron.hours.has(d.getUTCHours())) {\n d.setUTCHours(d.getUTCHours() + 1, 0, 0);\n } else if (!cron.minutes.has(d.getUTCMinutes())) {\n d.setUTCMinutes(d.getUTCMinutes() + 1, 0);\n } else if (!cron.seconds.has(d.getUTCSeconds())) {\n d.setUTCSeconds(d.getUTCSeconds() + 1);\n } else return d.getTime();\n }\n return undefined;\n}\n\n/**\n * The first time after `after` that the expression fires in `timeZone`.\n *\n * @returns The instant, or `undefined` when it never fires (`0 0 31 2 *`).\n */\nexport function nextCron(\n cron: CronExpression,\n after: Date,\n timeZone = \"UTC\",\n): Date | undefined {\n const from = after.getTime();\n // Whole seconds: the next one strictly after `from`.\n let wall = wallClock(from, timeZone) + 1000;\n for (;;) {\n const found = nextWall(cron, wall);\n if (found === undefined) return undefined;\n const instant = instantOf(found, timeZone);\n // A repeated hour: its wall times already ran the first time round.\n if (instant > from) return new Date(instant);\n wall = found + 1000;\n }\n}\n\n/** A century: well inside what a `Date` can hold after any due time. */\nconst MAX_DURATION_MS = 100 * 366 * DAY_MS;\n\nconst UNITS: Record<string, number> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 3_600_000,\n d: DAY_MS,\n};\n\n/**\n * A duration in milliseconds: a number of milliseconds, or text such as\n * `\"90s\"`, `\"15m\"`, `\"6h\"`, `\"1d\"` or `\"1h30m\"`.\n *\n * @throws When it is not a positive duration (or zero, with `allowZero`), or\n * is longer than a century.\n */\nexport function parseDuration(\n duration: string | number,\n options: { allowZero?: boolean } = {},\n): number {\n let ms = 0;\n if (typeof duration === \"number\") ms = duration;\n else {\n const text = duration.replace(/\\s+/g, \"\");\n const pattern = /(\\d+(?:\\.\\d+)?)(ms|s|m|h|d)/gy;\n let match: RegExpExecArray | null;\n let read = 0;\n while ((match = pattern.exec(text))) {\n ms += Number(match[1]) * UNITS[match[2]!]!;\n read = pattern.lastIndex;\n }\n if (!text || read !== text.length) ms = NaN;\n }\n const rounded = Math.round(ms);\n if (\n !Number.isFinite(rounded) ||\n rounded < (options.allowZero ? 0 : 1) ||\n rounded > MAX_DURATION_MS\n )\n throw new Error(\n `'${duration}' is not a duration: use milliseconds or text such as \"15m\", \"6h\" or \"1h30m\"`,\n );\n return rounded;\n}\n","import {\n checkTimeZone,\n nextCron,\n parseCron,\n parseDuration,\n type CronExpression,\n} from \"./cron\";\n\n/** What a schedule's `run` receives: which run this is. */\nexport interface ScheduleRun {\n /** The schedule's name. */\n schedule: string;\n /**\n * When this run was due, as an ISO timestamp: the cron time, the end of the\n * interval, or the moment someone triggered it. Retries of a failed run keep it.\n */\n slot: string;\n /** `manual` when started with `schedules.trigger(name)` or `brick schedules run`. */\n trigger: \"schedule\" | \"manual\";\n /** 1 on the first try, 2 on the first retry, and so on. */\n attempt: number;\n /** `<schedule>:<slot>`: the same on every retry, for idempotency keys. */\n runKey: string;\n}\n\n/** What a schedule's workflow receives: the run, without `attempt` (a run starts one workflow however often it is tried). */\nexport type ScheduleWorkflowRun = Omit<ScheduleRun, \"attempt\">;\n\n/** A function marked `\"use workflow\"`, started once per run of the schedule it is given to. */\nexport type ScheduleWorkflow = (run: ScheduleWorkflowRun) => Promise<unknown>;\n\ntype When =\n | {\n /**\n * A cron expression: `\"0 2 * * *\"` is 02:00 every day. Five fields, or six\n * with seconds first; `@daily` and the other macros work too.\n */\n cron: string;\n /** The IANA time zone `cron` is read in, such as `\"Europe/Berlin\"`. Default `\"UTC\"`. */\n timeZone?: string;\n every?: never;\n }\n | {\n /**\n * Run again this long after the last successful run finished: `\"6h\"`,\n * `\"15m\"`, `\"1h30m\"`, or milliseconds. The first run is due as soon as a\n * process starts the schedules.\n */\n every: string | number;\n cron?: never;\n timeZone?: never;\n };\n\n/** What `defineSchedule` takes. */\nexport type ScheduleConfig = When & {\n /** Unique among the app's schedules, and the key its state is stored under: renaming it starts it afresh. */\n name: string;\n /**\n * A due time that passed while no process ran the schedules (or one more\n * than a minute late): `\"once\"` (the default) runs it once, however many\n * were missed; `\"skip\"` skips it and waits for the next.\n */\n catchUp?: \"once\" | \"skip\";\n /** Tries per due time, the first included. Default 3. */\n maxAttempts?: number;\n /** The wait before the first retry, doubling on each retry after it; 0 retries at once. Default `\"1m\"`. */\n backoff?: string | number;\n /** A random delay of up to this much, added to every due time, so many processes or apps do not all start at once. */\n jitter?: string | number;\n /** `false` keeps the schedule from running on its own; `trigger` still runs it. Default `true`. */\n enabled?: boolean;\n} & (\n | {\n /** Runs in the process that claims the due time. Throwing retries it. */\n run: (run: ScheduleRun) => void | Promise<void>;\n workflow?: never;\n }\n | {\n /**\n * A durable workflow started for each due time, on the app's\n * `events.world`. The run counts as done once the workflow started; the\n * workflow retries its own steps.\n */\n workflow: ScheduleWorkflow;\n run?: never;\n }\n );\n\n/** A schedule, made by `defineSchedule`. */\nexport interface Schedule {\n readonly name: string;\n readonly cron?: CronExpression;\n readonly timeZone?: string;\n /** The interval, in milliseconds. */\n readonly every?: number;\n readonly catchUp: \"once\" | \"skip\";\n readonly maxAttempts: number;\n readonly backoffMs: number;\n readonly jitterMs: number;\n readonly enabled: boolean;\n readonly run?: (run: ScheduleRun) => void | Promise<void>;\n readonly workflow?: ScheduleWorkflow;\n /** What decides the due times, as stored with them: a change makes the next one be worked out again. */\n readonly spec: string;\n}\n\n/**\n * Define a schedule: code that runs at set times, in one process among all\n * those that run the app. Pass it to `brick({ events: { schedules } })`.\n *\n * It runs either on a `cron` expression, at fixed wall-clock times in a time\n * zone, or `every` so long, counted from the end of the last successful run.\n * State lives in the app's `scheduleTable()`, so a due time runs once however\n * many processes there are, and a restart or deploy carries on where it\n * stopped. A due time counts as done only once its run succeeds: a run that\n * throws is retried with a growing delay, and one whose process died is taken\n * over by another process. A run is never started while the last one is still\n * running; due times that pass in the meantime are skipped.\n *\n * @param config - `name`, `cron` (and `timeZone`) or `every`, `run` or\n * `workflow`, and optionally `catchUp`, `maxAttempts`, `backoff`, `jitter` and\n * `enabled`.\n * @returns The schedule.\n * @throws When the name is empty or contains `:`, the cron expression or time\n * zone is invalid, or the schedule has both or neither of `cron` and `every`,\n * or of `run` and `workflow`.\n * @example\n * import { brick, defineSchedule } from \"@brickkit/core\";\n *\n * const backup = defineSchedule({\n * name: \"db-backup\",\n * cron: \"0 *\\/6 * * *\",\n * timeZone: \"Europe/Berlin\",\n * run: () => backupDatabase(),\n * });\n *\n * export default brick({ services, events: { schedules: [backup] } });\n */\nexport function defineSchedule(config: ScheduleConfig): Schedule {\n const { name } = config;\n if (typeof name !== \"string\" || !name)\n throw new Error(\"A schedule needs a name\");\n if (name.includes(\":\"))\n throw new Error(`Schedule name '${name}' must not contain ':'`);\n const fail = (message: string): never => {\n throw new Error(`Schedule '${name}': ${message}`);\n };\n const attempt = <T>(fn: () => T): T => {\n try {\n return fn();\n } catch (error) {\n return fail((error as Error).message);\n }\n };\n /** A duration that may also be 0: none. */\n const optionalDuration = (\n value: string | number | undefined,\n fallback: number,\n ) =>\n value === undefined\n ? fallback\n : attempt(() => parseDuration(value, { allowZero: true }));\n if ((config.cron === undefined) === (config.every === undefined))\n fail(\"give it a cron expression or an interval (every), not both\");\n if ((config.run === undefined) === (config.workflow === undefined))\n fail(\"give it a run handler or a workflow, not both\");\n if (config.run !== undefined && typeof config.run !== \"function\")\n fail(\"run must be a function\");\n if (config.workflow !== undefined && typeof config.workflow !== \"function\")\n fail('workflow must be a function marked \"use workflow\"');\n const maxAttempts = config.maxAttempts ?? 3;\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1)\n fail(\"maxAttempts must be a positive integer\");\n if (\n config.catchUp !== undefined &&\n ![\"once\", \"skip\"].includes(config.catchUp)\n )\n fail('catchUp must be \"once\" or \"skip\"');\n let when: Pick<Schedule, \"cron\" | \"timeZone\" | \"every\" | \"spec\">;\n if (config.cron !== undefined) {\n const timeZone = config.timeZone ?? \"UTC\";\n const cron = attempt(() => parseCron(config.cron!));\n attempt(() => checkTimeZone(timeZone));\n if (!nextCron(cron, new Date(), timeZone))\n fail(`cron expression '${config.cron}' never fires`);\n when = { cron, timeZone, spec: `cron ${cron.source} ${timeZone}` };\n } else {\n const every = attempt(() => parseDuration(config.every!));\n when = { every, spec: `every ${every}` };\n }\n return Object.freeze({\n name,\n ...when,\n catchUp: config.catchUp ?? \"once\",\n maxAttempts,\n backoffMs: optionalDuration(config.backoff, 60_000),\n jitterMs: optionalDuration(config.jitter, 0),\n enabled: config.enabled ?? true,\n ...(config.run ? { run: config.run } : {}),\n ...(config.workflow ? { workflow: config.workflow } : {}),\n });\n}\n\n/**\n * The first due time of `schedule` after `after`, before jitter: the next\n * cron time, or `after` plus the interval. `undefined` when the cron\n * expression fires no more.\n */\nexport function nextDue(schedule: Schedule, after: Date): Date | undefined {\n return schedule.cron\n ? nextCron(schedule.cron, after, schedule.timeZone)\n : new Date(after.getTime() + schedule.every!);\n}\n","import { and, eq, inArray, isNull, lt, lte, or, sql } from \"drizzle-orm\";\nimport { isSqliteDatabase } from \"../events/transaction\";\nimport { nextDue, type Schedule, type ScheduleRun } from \"./schedule\";\nimport type { ScheduleRow, ScheduleRunRecord, ScheduleTable } from \"./table\";\n\n/** A due time this late, on its first try, counts as missed for `catchUp: \"skip\"`. */\nconst MISSED_AFTER_MS = 60_000;\n/** Runs kept per schedule. */\nconst KEEP_RUNS = 20;\nconst ABANDONED = \"The process running it stopped before it finished\";\n\n/** A schedule as `schedules.list()` reports it. */\nexport interface ScheduleState {\n name: string;\n kind: \"handler\" | \"workflow\";\n cron?: string;\n timeZone?: string;\n /** The interval, in milliseconds. */\n every?: number;\n enabled: boolean;\n /** When it is next due (a retry included), as an ISO timestamp; `null` before a process first started the schedules. */\n nextRunAt: string | null;\n /** Whether a process is running it now. */\n running: boolean;\n /** Tries of the current due time so far. */\n attempts: number;\n lastSuccessAt: string | null;\n /** The last runs, newest first. */\n runs: ScheduleRunRecord[];\n}\n\nexport interface SchedulerOptions {\n /** Look for due schedules on a timer. */\n timer: boolean;\n intervalMs: number;\n /** How long a run may go without a heartbeat before another process takes it over. */\n claimTimeoutMs: number;\n}\n\n/**\n * Runs an app's schedules from one schedule table, shared by every process\n * that runs the app.\n *\n * Each schedule has one row. A process claims a due row with a conditional\n * update (due, and not held by a live claim), so one process wins each due\n * time, on Postgres and SQLite alike. While it runs, the process renews its\n * claim; a process that dies stops renewing, and after `claimTimeoutMs`\n * another process takes the due time over. On Postgres claims are timed by\n * the database's clock, so hosts whose clocks disagree still agree on them. Only success (or giving up after\n * `maxAttempts`) moves the row to the next due time.\n */\nexport class Scheduler {\n private readonly byName: Map<string, Schedule>;\n private readonly inFlight = new Map<string, Promise<void>>();\n private timer?: ReturnType<typeof setInterval>;\n private tickQueue?: Promise<number>;\n private synced?: Promise<void>;\n private readonly postgres: boolean;\n\n constructor(\n private readonly db: any,\n private readonly table: ScheduleTable,\n schedules: readonly Schedule[],\n private readonly runner: (\n schedule: Schedule,\n run: ScheduleRun,\n ) => Promise<void>,\n private readonly options: SchedulerOptions,\n ) {\n this.byName = new Map(schedules.map((s) => [s.name, s]));\n this.postgres = !isSqliteDatabase(db);\n }\n\n start(): void {\n if (this.timer || !this.options.timer) return;\n this.timer = setInterval(() => void this.tick(), this.options.intervalMs);\n this.timer.unref?.();\n void this.tick();\n }\n\n /** Stop the timer and wait for the runs in progress. */\n async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n await this.tickQueue;\n await Promise.allSettled(this.inFlight.values());\n }\n\n /**\n * Run what is due now and wait for it. Retries that are not due yet are not\n * waited for. For tests and for workers driven by hand.\n *\n * @returns How many runs it started.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (;;) {\n const started = await this.tick();\n await Promise.allSettled(this.inFlight.values());\n if (started === 0) return total;\n total += started;\n }\n }\n\n /** Every schedule with its state. */\n async list(now = new Date()): Promise<ScheduleState[]> {\n const t = this.table as any;\n const rows: ScheduleRow[] = await this.db.select().from(t);\n const byName = new Map(rows.map((row) => [row.name, row]));\n return [...this.byName.values()].map((schedule) => {\n const row = byName.get(schedule.name);\n return {\n name: schedule.name,\n kind: schedule.workflow ? \"workflow\" : \"handler\",\n ...(schedule.cron\n ? { cron: schedule.cron.source, timeZone: schedule.timeZone }\n : { every: schedule.every }),\n enabled: schedule.enabled,\n nextRunAt: row ? row.nextAt.toISOString() : null,\n running: Boolean(row?.runId && row.leaseUntil && row.leaseUntil > now),\n attempts: row?.runId ? row.attempts : (row?.attempts ?? 0),\n lastSuccessAt: row?.lastSuccessAt?.toISOString() ?? null,\n runs: row?.runs ?? [],\n };\n });\n }\n\n /**\n * Make a schedule due now, as a manual run. Whichever process runs the\n * schedules picks it up; this one at once if it does.\n *\n * @returns `false` when the schedule is running now.\n * @throws When no schedule has that name.\n */\n async trigger(name: string): Promise<boolean> {\n if (!this.byName.has(name)) throw new Error(`No schedule named '${name}'`);\n await this.sync();\n const now = new Date();\n const set = await this.reset(name, now, {\n slot: now,\n nextAt: now,\n attempts: 0,\n trigger: \"manual\",\n });\n if (!set) return false;\n if (this.timer) setTimeout(() => void this.tick(), 0).unref?.();\n return true;\n }\n\n /**\n * Set a schedule's row afresh, unless a live claim holds it. A claim whose\n * process died is recorded first, as a failed run of its own due time.\n *\n * @returns Whether the row was set.\n */\n private async reset(\n name: string,\n now: Date,\n values: Partial<ScheduleRow>,\n ): Promise<boolean> {\n const t = this.table as any;\n const [row]: ScheduleRow[] = await this.db\n .select()\n .from(t)\n .where(eq(t.name, name));\n if (!row) return false;\n const updated = await this.db\n .update(t)\n .set({\n ...values,\n runId: null,\n startedAt: null,\n leaseUntil: null,\n // Only the holder of a claim writes the runs, and this one is dead.\n ...(row.runId\n ? {\n runs: [\n this.record(row, row.startedAt!, \"failed\", ABANDONED),\n ...row.runs,\n ].slice(0, KEEP_RUNS),\n }\n : {}),\n })\n // Unless its claim is live, or another process claimed it meanwhile.\n .where(and(eq(t.name, name), this.unchanged(row.runId), this.free(now)))\n .returning({ name: t.name });\n return updated.length > 0;\n }\n\n /** Not held by a live claim. */\n private free(now: Date) {\n const t = this.table as any;\n return or(isNull(t.runId), lt(t.leaseUntil, this.clock(now)));\n }\n\n /** Still held by the claim `runId`, or by none when it is null. */\n private unchanged(runId: string | null) {\n const t = this.table as any;\n return runId ? eq(t.runId, runId) : isNull(t.runId);\n }\n\n /** Now, for claims: the database's clock on Postgres, this host's on SQLite (one host). */\n private clock(now: Date) {\n return this.postgres ? sql`now()` : now;\n }\n\n /** When a claim made or renewed now runs out. */\n private leaseFrom(now: Date) {\n const ms = this.options.claimTimeoutMs;\n return this.postgres\n ? sql`now() + make_interval(secs => ${ms / 1000})`\n : new Date(now.getTime() + ms);\n }\n\n /** A row due at the schedule's first time from now: an interval at once, a cron schedule at its next time. */\n private fresh(schedule: Schedule, now: Date) {\n const slot = schedule.cron ? nextDue(schedule, now) : now;\n return (\n slot && {\n spec: schedule.spec,\n slot,\n nextAt: this.jittered(schedule, slot),\n attempts: 0,\n trigger: \"schedule\" as const,\n }\n );\n }\n\n /**\n * Give each schedule its row, and work its next due time out again when what\n * decides it changed (an edited cron expression). Once per scheduler.\n */\n private sync(): Promise<void> {\n this.synced ??= this.writeRows().catch((error) => {\n this.synced = undefined;\n throw error;\n });\n return this.synced;\n }\n\n private async writeRows(): Promise<void> {\n const t = this.table as any;\n const now = new Date();\n for (const schedule of this.byName.values()) {\n const fresh = this.fresh(schedule, now);\n if (!fresh) continue;\n await this.db\n .insert(t)\n .values({ name: schedule.name, runs: [], ...fresh })\n .onConflictDoNothing();\n const [row]: Pick<ScheduleRow, \"spec\">[] = await this.db\n .select({ spec: t.spec })\n .from(t)\n .where(eq(t.name, schedule.name));\n if (row && row.spec !== schedule.spec)\n await this.reset(schedule.name, now, fresh);\n }\n }\n\n private tick(): Promise<number> {\n this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(\n () => this.claimAndRun(),\n () => this.claimAndRun(),\n );\n return this.tickQueue;\n }\n\n private async claimAndRun(): Promise<number> {\n try {\n await this.sync();\n const t = this.table as any;\n const now = new Date();\n const due: Pick<\n ScheduleRow,\n \"name\" | \"spec\" | \"trigger\" | \"runId\" | \"startedAt\"\n >[] = await this.db\n .select({\n name: t.name,\n spec: t.spec,\n trigger: t.trigger,\n runId: t.runId,\n startedAt: t.startedAt,\n })\n .from(t)\n .where(\n and(\n inArray(t.name, [...this.byName.keys()]),\n lte(t.nextAt, now),\n this.free(now),\n ),\n );\n let started = 0;\n for (const candidate of due) {\n const schedule = this.byName.get(candidate.name)!;\n if (this.inFlight.has(schedule.name)) continue;\n if (!schedule.enabled && candidate.trigger !== \"manual\") continue;\n // Another version of the app wrote it (a rolling deploy): this\n // process's definition decides when it is due.\n if (candidate.spec !== schedule.spec) {\n const fresh = this.fresh(schedule, now);\n if (fresh) await this.reset(schedule.name, now, fresh);\n continue;\n }\n const runId = crypto.randomUUID();\n const [row]: ScheduleRow[] = await this.db\n .update(t)\n .set({\n runId,\n startedAt: now,\n leaseUntil: this.leaseFrom(now),\n // Counted at the claim, so a try whose process dies still counts.\n attempts: sql`${t.attempts} + 1`,\n })\n .where(\n and(\n eq(t.name, schedule.name),\n lte(t.nextAt, now),\n this.free(now),\n // As read: the abandoned try recorded below is that claim's.\n this.unchanged(candidate.runId),\n ),\n )\n .returning();\n if (!row) continue; // Another process won it, or changed it.\n started++;\n const run = this.execute(\n schedule,\n row,\n candidate.runId === null ? undefined : candidate.startedAt!,\n )\n .catch((error) => this.logError(error))\n .finally(() => this.inFlight.delete(schedule.name));\n this.inFlight.set(schedule.name, run);\n }\n return started;\n } catch (error) {\n this.logError(error);\n return 0;\n }\n }\n\n private async execute(\n schedule: Schedule,\n row: ScheduleRow,\n /** When the last try started, when its process stopped before it finished. */\n abandonedAt: Date | undefined,\n ): Promise<void> {\n const runs = [...row.runs];\n const startedAt = row.startedAt!;\n const attempt = row.attempts;\n if (abandonedAt)\n runs.unshift(\n this.record(\n { ...row, attempts: attempt - 1 },\n abandonedAt,\n \"failed\",\n ABANDONED,\n ),\n );\n const now = () => new Date();\n if (\n attempt === 1 &&\n row.trigger === \"schedule\" &&\n // An overdue interval has no later time to wait for.\n schedule.cron &&\n schedule.catchUp === \"skip\" &&\n startedAt.getTime() - row.nextAt.getTime() > MISSED_AFTER_MS\n ) {\n runs.unshift(this.record(row, startedAt, \"skipped\"));\n return this.advance(schedule, row, runs, now(), false);\n }\n if (attempt > schedule.maxAttempts)\n return this.advance(schedule, row, runs, now(), false);\n const heartbeat = setInterval(\n () => void this.renew(row).catch((error) => this.logError(error)),\n Math.max(10, Math.floor(this.options.claimTimeoutMs / 3)),\n );\n heartbeat.unref?.();\n const slot = row.slot.toISOString();\n try {\n await this.runner(schedule, {\n schedule: schedule.name,\n slot,\n trigger: row.trigger,\n attempt,\n runKey: `${schedule.name}:${slot}`,\n });\n } catch (error) {\n clearInterval(heartbeat);\n const message = error instanceof Error ? error.message : String(error);\n runs.unshift(this.record(row, startedAt, \"failed\", message));\n return this.retry(schedule, row, runs, now());\n }\n clearInterval(heartbeat);\n runs.unshift(this.record(row, startedAt, \"succeeded\"));\n return this.advance(schedule, row, runs, now(), true);\n }\n\n private async renew(row: ScheduleRow): Promise<void> {\n const t = this.table as any;\n const updated = await this.db\n .update(t)\n .set({\n leaseUntil: this.leaseFrom(new Date()),\n })\n .where(and(eq(t.name, row.name), eq(t.runId, row.runId)))\n .returning({ name: t.name });\n if (!updated.length)\n console.warn(\n `[Brick-TS schedules] Schedule '${row.name}' lost its claim while running; another process may run it too.`,\n );\n }\n\n /** After a failure: try the same due time again later, unless the tries ran out or the next due time comes first. */\n private async retry(\n schedule: Schedule,\n row: ScheduleRow,\n runs: ScheduleRunRecord[],\n now: Date,\n ): Promise<void> {\n const retryAt = new Date(\n now.getTime() + schedule.backoffMs * 2 ** (row.attempts - 1),\n );\n const next = schedule.cron ? nextDue(schedule, now) : undefined;\n if (row.attempts >= schedule.maxAttempts || (next && next <= retryAt))\n return this.advance(schedule, row, runs, now, false);\n await this.release(row, { nextAt: retryAt, runs });\n }\n\n /** Done with this due time: on to the next one. */\n private async advance(\n schedule: Schedule,\n row: ScheduleRow,\n runs: ScheduleRunRecord[],\n now: Date,\n succeeded: boolean,\n ): Promise<void> {\n // Due times that passed during the run are skipped: runs never overlap.\n const slot = nextDue(schedule, now);\n await this.release(row, {\n spec: schedule.spec,\n ...(slot\n ? { slot, nextAt: this.jittered(schedule, slot) }\n : // A cron expression that fires no more: park it far ahead.\n { nextAt: new Date(8.64e15) }),\n attempts: 0,\n trigger: \"schedule\",\n runs,\n ...(succeeded ? { lastSuccessAt: now } : {}),\n });\n }\n\n private async release(\n row: ScheduleRow,\n values: Partial<ScheduleRow>,\n ): Promise<void> {\n const t = this.table as any;\n const updated = await this.db\n .update(t)\n .set({\n ...values,\n runs: values.runs?.slice(0, KEEP_RUNS),\n runId: null,\n leaseUntil: null,\n })\n .where(and(eq(t.name, row.name), eq(t.runId, row.runId)))\n .returning({ name: t.name });\n if (!updated.length)\n console.warn(\n `[Brick-TS schedules] Schedule '${row.name}': another process took the run over, so this outcome is not recorded.`,\n );\n }\n\n private record(\n row: ScheduleRow,\n startedAt: Date,\n outcome: ScheduleRunRecord[\"outcome\"],\n error?: string,\n ): ScheduleRunRecord {\n return {\n slot: row.slot.toISOString(),\n trigger: row.trigger,\n attempt: row.attempts,\n startedAt: startedAt.toISOString(),\n finishedAt: new Date().toISOString(),\n outcome,\n ...(error !== undefined ? { error } : {}),\n };\n }\n\n private jittered(schedule: Schedule, slot: Date): Date {\n return schedule.jitterMs\n ? new Date(slot.getTime() + Math.floor(Math.random() * schedule.jitterMs))\n : slot;\n }\n\n private logError(error: unknown): void {\n console.error(\"[Brick-TS schedules]\", error);\n }\n}\n","import { traceScheduleRun } from \"../telemetry\";\nimport { GLOBAL_SYMBOL } from \"../telemetry-names\";\nimport { Dispatcher, type OutboxCounts } from \"./dispatcher\";\nimport { newEventId } from \"./id\";\nimport { listenerDeps, validateListener } from \"./listener\";\nimport { outboxRows, OUTBOX_STATUSES, type OutboxTable } from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type {\n DispatchOptions,\n EventDelivery,\n EventListener,\n EventRecorder,\n EventsOptions,\n EventsWorld,\n ServiceEvents,\n} from \"./types\";\nimport { isWorkflowBundleShipped, WorkflowRuntime } from \"./workflows\";\nimport { runWithDeps } from \"../deps\";\nimport { portOf, type ServicePort } from \"../service-port\";\nimport { DuplicateNameError, type Service } from \"../types\";\nimport type { Schedule } from \"../schedules/schedule\";\nimport { Scheduler, type ScheduleState } from \"../schedules/scheduler\";\nimport type { ScheduleTable } from \"../schedules/table\";\nimport { outsideRedaction } from \"../sensitive\";\n\nexport function matchesEvent(pattern: string, name: string): boolean {\n if (pattern === \"*\") return true;\n if (pattern.endsWith(\"*\")) return name.startsWith(pattern.slice(0, -1));\n return pattern === name;\n}\n\n/** The service of each database that records events, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */\nexport const recordingServices = new WeakMap<object, ServicePort>();\n\n// Shared by name: the CLI that stops the hubs may hold another copy of this package.\nconst startedHubs = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(GLOBAL_SYMBOL.eventsStarted)\n] ??= new Set()) as Set<Pick<EventsHub, \"stop\">>;\n\n/**\n * Stop every events hub started in this process, by any copy of `@brickkit/core`,\n * and wait for their deliveries. A hub that fails to stop does not cut the wait\n * for the others: the first failure is thrown once every hub is done.\n */\nexport async function stopAllEvents(): Promise<void> {\n const results = await Promise.allSettled(\n [...startedHubs].map((hub) => hub.stop()),\n );\n const failed = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (failed) throw failed.reason;\n}\n\n/**\n * What an app's `events` option describes, as plain data. It goes in the app\n * definition, which is sent to the dev dashboard, so it holds no functions.\n */\nexport interface EventsDefinition {\n listeners: { name: string; on: string[]; kind: \"handler\" | \"workflow\" }[];\n dispatch: boolean;\n /** Names of the services whose writes record events. */\n recorders: string[];\n /** The app's schedules; absent when it has none. */\n schedules?: {\n name: string;\n kind: \"handler\" | \"workflow\";\n cron?: string;\n timeZone?: string;\n every?: number;\n enabled: boolean;\n }[];\n}\n\n/** What `app.events.schedules` offers: see and trigger the app's schedules. */\nexport interface ScheduleControl {\n /** Every schedule, with when it is next due and its last runs. */\n list(): Promise<ScheduleState[]>;\n /**\n * Run a schedule now, once, in whichever process runs the schedules. It\n * works with `enabled: false` too.\n *\n * @returns `false` when the schedule is running now, so nothing was started.\n * @throws When no schedule has that name.\n */\n trigger(name: string): Promise<boolean>;\n /** Run what is due now, and wait for it. For tests and workers driven by hand. @returns How many runs started. */\n drain(): Promise<number>;\n}\n\n/** What the dispatcher runs for a delivery. */\nexport interface Deliverable {\n readonly maxAttempts?: number;\n readonly errors?: EventListener[\"errors\"];\n readonly retry?: EventListener[\"retry\"];\n run(delivery: EventDelivery): void | Promise<void>;\n}\n\n/**\n * The events of one app: who listens, where events are recorded, and the\n * dispatchers that deliver them. `brick({ events })` makes one and puts it on\n * `app.events`.\n */\nexport class EventsHub {\n private readonly byName = new Map<string, EventListener>();\n private readonly dispatchers = new Map<OutboxTable, Dispatcher>();\n private readonly deliverables = new Map<string, Deliverable>();\n private readonly dispatchOptions: DispatchOptions | false;\n private readonly runtime: WorkflowRuntime | undefined;\n private readonly recorderNames: string[] = [];\n private readonly scheduleList: Schedule[] = [];\n private scheduler: Scheduler | undefined;\n private started = false;\n private stopping: Promise<void> | undefined;\n\n /**\n * @param options - The `events` option.\n * @param deps - The deps of the app's services, which `useDeps()` returns in\n * its listeners, schedules and workflow steps.\n * @param telemetry - Trace each schedule run, as `brick({ telemetry })` does requests.\n */\n constructor(\n options: EventsOptions,\n private readonly deps: Record<string, unknown> = {},\n private readonly telemetry = false,\n ) {\n for (const listener of options.listeners ?? []) {\n validateListener(listener);\n if (this.byName.has(listener.name))\n throw new DuplicateNameError(\n `Duplicate event listener '${listener.name}'`,\n );\n this.byName.set(listener.name, listener);\n }\n const scheduleNames = new Set<string>();\n for (const schedule of options.schedules ?? []) {\n if (scheduleNames.has(schedule.name))\n throw new DuplicateNameError(`Duplicate schedule '${schedule.name}'`);\n scheduleNames.add(schedule.name);\n this.scheduleList.push(schedule);\n }\n const workflowListeners = [\n ...this.byName.values(),\n ...this.scheduleList,\n ].filter((listener) => listener.workflow);\n if (workflowListeners.length) {\n if (!options.world)\n throw new Error(\n `${\"on\" in workflowListeners[0]! ? \"Event listener\" : \"Schedule\"} '${workflowListeners[0]!.name}' runs a workflow, so events needs a world: ` +\n \"brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.\",\n );\n this.runtime = new WorkflowRuntime(\n options.world,\n options.workflows,\n workflowListeners,\n deps,\n );\n }\n this.dispatchOptions =\n options.dispatch === false\n ? false\n : options.dispatch === true || options.dispatch === undefined\n ? {}\n : options.dispatch;\n }\n\n /**\n * Give each service whose database holds an outbox table a recorder, and a\n * dispatcher for that table. Call it before the first request: a service has no\n * recorder until then.\n *\n * @param services - The app's services.\n * @returns The hub, for chaining.\n */\n attach(services: readonly Service<any, any>[]): this {\n for (const service of services.map(portOf)) {\n const table = service.getOutbox();\n if (!table) continue;\n this.recorderNames.push(service.name);\n service.setRecorder(\n this.bind(table, (name, payload) => service.checkEvent(name, payload)),\n );\n const db = service.getDb();\n if (db && typeof db === \"object\") recordingServices.set(db, service);\n if (!this.dispatchers.has(table))\n this.dispatchers.set(\n table,\n new Dispatcher(\n db,\n table,\n (name) => this.deliverable(name),\n this.dispatchOptions || {},\n ),\n );\n }\n if (this.scheduleList.length) this.attachSchedules(services);\n if (this.recorderNames.length === 0 && this.byName.size > 0) {\n console.warn(\n \"[Brick-TS] events are configured, but no service database has an outbox table. \" +\n \"Add outboxTable() to a database's tables so its writes can record events.\",\n );\n }\n return this;\n }\n\n matching(name: string): EventListener[] {\n const found: EventListener[] = [];\n for (const listener of this.byName.values())\n if (listener.on.some((pattern) => matchesEvent(pattern, name)))\n found.push(listener);\n return found;\n }\n\n describe(): EventsDefinition {\n return {\n listeners: [...this.byName.values()].map((listener) => ({\n name: listener.name,\n on: [...listener.on],\n kind: listener.workflow ? (\"workflow\" as const) : (\"handler\" as const),\n })),\n dispatch: this.dispatchOptions !== false,\n recorders: [...this.recorderNames],\n ...(this.scheduleList.length\n ? {\n schedules: this.scheduleList.map((schedule) => ({\n name: schedule.name,\n kind: schedule.workflow\n ? (\"workflow\" as const)\n : (\"handler\" as const),\n ...(schedule.cron\n ? { cron: schedule.cron.source, timeZone: schedule.timeZone }\n : { every: schedule.every }),\n enabled: schedule.enabled,\n })),\n }\n : {}),\n };\n }\n\n /** The app's schedules, when it has any. Running them follows `start()` and `stop()`. */\n get schedules(): ScheduleControl | undefined {\n const scheduler = this.scheduler;\n return (\n scheduler && {\n list: () => scheduler.list(),\n trigger: (name) => scheduler.trigger(name),\n drain: () => scheduler.drain(),\n }\n );\n }\n\n /**\n * Find the one schedule table among the services' databases.\n *\n * @throws When none holds one, or more than one does: a schedule must have\n * one place where its state lives.\n */\n private attachSchedules(services: readonly Service<any, any>[]): void {\n const found = new Map<ScheduleTable, unknown>();\n for (const service of services.map(portOf)) {\n const table = service.getScheduleTable();\n if (table && !found.has(table)) found.set(table, service.getDb());\n }\n if (found.size !== 1)\n throw new Error(\n found.size\n ? \"Brick: schedules need exactly one scheduleTable(), but several databases hold one.\"\n : \"Brick: schedules keep their state in a scheduleTable(), and no service database holds one. Add scheduleTable() to a database's tables.\",\n );\n const [[table, db]] = [...found];\n const options = this.dispatchOptions || {};\n this.scheduler = new Scheduler(\n db,\n table,\n this.scheduleList,\n (schedule, run) => {\n const start = () =>\n schedule.workflow\n ? this.runtime!.startScheduled(schedule, run)\n : runWithDeps(this.deps, async () => schedule.run!(run));\n return this.telemetry ? traceScheduleRun(run, start) : start();\n },\n {\n timer: options.timer ?? true,\n intervalMs: options.intervalMs ?? 1_000,\n claimTimeoutMs: options.claimTimeoutMs ?? 60_000,\n },\n );\n }\n\n /**\n * Where the workflow bundle is read from, the project it is built from, and\n * the world the workflows run on. Only set when a listener runs a workflow.\n * The CLI builds the bundle there before events start, and shows the world's\n * runs in the dev dashboard. `shipped`: a compiled server reads the bundle\n * `brick build` shipped beside it, so there is nothing to build.\n */\n get workflows():\n | { root: string; dir: string; world: EventsWorld; shipped: boolean }\n | undefined {\n return (\n this.runtime && {\n root: this.runtime.root,\n dir: this.runtime.dir,\n world: this.runtime.world,\n shipped: isWorkflowBundleShipped(),\n }\n );\n }\n\n /**\n * Resume the workflow that waits on a webhook. The server mounts this on the\n * route the Workflow SDK puts in webhook URLs.\n */\n webhook(request: Request): Promise<Response> {\n if (!this.runtime)\n throw new Error(\"No listener of this app runs a workflow\");\n return this.runtime.handleWebhook(request);\n }\n\n /**\n * Start delivering recorded events from this process, and start the world that\n * runs workflow listeners. Does nothing if this process only records events\n * (`dispatch: false`), already started, or a stop is still waiting.\n */\n start(): void {\n // A process being stopped exits when the stop is done, and would drop what\n // this start claims. A startup that finishes late, or a commit, lands here.\n if (this.dispatchOptions === false || this.started || this.stopping) return;\n this.started = true;\n startedHubs.add(this);\n this.runtime?.warmUp();\n for (const dispatcher of this.dispatchers.values()) dispatcher.start();\n this.scheduler?.start();\n }\n\n /**\n * Stop delivering, wait for the deliveries that are running, and close the\n * world. A world cannot be started again, so workflow listeners stop for good.\n * A stop that arrives while another runs waits for that one.\n */\n stop(): Promise<void> {\n return (this.stopping ??= this.shutDown().finally(() => {\n // Removed only when done, so a stop-all waits for a stop already running.\n this.stopping = undefined;\n startedHubs.delete(this);\n }));\n }\n\n private async shutDown(): Promise<void> {\n this.started = false;\n await Promise.all([\n ...[...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()),\n this.scheduler?.stop(),\n ]);\n await this.runtime?.close();\n }\n\n /**\n * Deliver everything that is due now and wait for it. For tests and for\n * workers that drive delivery themselves.\n *\n * @returns How many deliveries ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.drain();\n return total;\n }\n\n /** How many rows are in each state, across the app's outbox tables. */\n async counts(): Promise<OutboxCounts> {\n const total = Object.fromEntries(\n OUTBOX_STATUSES.map((status) => [status, 0]),\n ) as OutboxCounts;\n for (const dispatcher of this.dispatchers.values()) {\n const counts = await dispatcher.counts();\n for (const status of OUTBOX_STATUSES) total[status] += counts[status];\n }\n return total;\n }\n\n /**\n * Put parked deliveries back in line.\n *\n * @param deliveryId - One delivery. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.retryDead(deliveryId);\n return total;\n }\n\n private deliverable(name: string): Deliverable | undefined {\n const listener = this.byName.get(name);\n if (!listener) return undefined;\n let found = this.deliverables.get(name);\n if (!found) {\n const { run, workflow, maxAttempts, errors, retry } = listener;\n const deps = listenerDeps(listener) ?? this.deps;\n found = {\n ...(errors ? { errors } : {}),\n ...(retry ? { retry } : {}),\n ...(maxAttempts !== undefined ? { maxAttempts } : {}),\n run: workflow\n ? (delivery) => this.runtime!.startRun(listener, delivery)\n : (delivery) => runWithDeps(deps, () => run!(delivery)),\n };\n this.deliverables.set(name, found);\n }\n return found;\n }\n\n private bind(\n table: OutboxTable,\n check: (name: string, payload: unknown) => void,\n ): ServiceEvents {\n const startAndNotify = () =>\n outsideRedaction(() => {\n this.start();\n this.dispatchers.get(table)?.notify();\n });\n const insert = async (\n tx: any,\n context: { traceId?: string; source?: string },\n name: string,\n payload: unknown,\n ): Promise<boolean> => {\n check(name, payload);\n const listeners = this.matching(name);\n if (!listeners.length) return false;\n await tx.insert(table as any).values(\n outboxRows(\n {\n id: newEventId(),\n name,\n payload,\n occurredAt: new Date(),\n ...context,\n },\n listeners.map((listener) => listener.name),\n ),\n );\n return true;\n };\n return {\n wants: (name) => this.matching(name).length > 0,\n transaction: async (db, context, fn) => {\n let recorded = false;\n const result = await runInTransaction(db, async (tx) => {\n const record: EventRecorder = async (name, payload) => {\n if (await insert(tx, context, name, payload)) recorded = true;\n };\n return fn(tx, record);\n });\n if (recorded) startAndNotify();\n return result;\n },\n record: async (tx, context, name, payload) => {\n await insert(tx, context, name, payload);\n },\n };\n }\n}\n","/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */\nexport function publicOrigin(request: Request): string {\n // Browsers cannot set X-Forwarded-* on a WebSocket handshake, so a cross-site page cannot forge a match.\n const forwarded = (name: string) =>\n request.headers.get(name)?.split(\",\")[0]?.trim() || undefined;\n const url = new URL(request.url);\n const proto = forwarded(\"x-forwarded-proto\");\n return `${proto ? `${proto}:` : url.protocol}//${forwarded(\"x-forwarded-host\") ?? url.host}`;\n}\n\n/**\n * Which origins may call the app: an exact origin (`\"https://app.example.com\"`),\n * a list of them, or a predicate. `true` allows only the app's own origin.\n */\nexport type CorsOrigin =\n | true\n | string\n | readonly string[]\n | ((origin: string, request: Request) => boolean);\n\n/** `brick({ cors })`: an origin rule, or the rule plus `credentials`. */\nexport type CorsOptions =\n | CorsOrigin\n | {\n /** Default `true`: the app's own origin only. */\n origin?: CorsOrigin;\n /** Send `Access-Control-Allow-Credentials: true` to allowed origins (cookies, auth headers). */\n credentials?: boolean;\n };\n\nconst METHODS = \"GET, POST, PUT, PATCH, DELETE\";\n\n/**\n * A request hook that adds CORS headers for allowed origins and answers\n * preflights. An origin that doesn't match gets no `Access-Control-Allow-Origin`,\n * so the browser blocks it; origins are compared exactly and never reflected\n * unless the rule allows them.\n */\nexport function corsHook(cors: CorsOptions) {\n const { origin = true, credentials = false } =\n typeof cors === \"object\" && !Array.isArray(cors)\n ? (cors as Exclude<CorsOptions, CorsOrigin>)\n : { origin: cors as CorsOrigin };\n const list =\n typeof origin === \"string\"\n ? [origin]\n : Array.isArray(origin)\n ? (origin as readonly string[])\n : undefined;\n if (list?.includes(\"*\"))\n throw new Error(\n 'Brick: cors origin \"*\" is not supported. List the origins, or pass a predicate.',\n );\n const allows = (from: string, request: Request) =>\n origin === true\n ? from === publicOrigin(request)\n : typeof origin === \"function\"\n ? origin(from, request) === true\n : list!.includes(from);\n\n return ({\n request,\n set,\n }: {\n request: Request;\n set: { headers: Record<string, unknown> };\n }) => {\n const from = request.headers.get(\"origin\");\n if (from === null) return;\n const headers: Record<string, string> = { vary: \"Origin\" };\n if (allows(from, request)) {\n headers[\"access-control-allow-origin\"] = from;\n if (credentials) headers[\"access-control-allow-credentials\"] = \"true\";\n headers[\"access-control-expose-headers\"] = \"Retry-After\";\n }\n const preflight =\n request.method === \"OPTIONS\" &&\n request.headers.has(\"access-control-request-method\");\n if (!preflight) {\n Object.assign(set.headers, headers);\n return;\n }\n if (headers[\"access-control-allow-origin\"]) {\n headers[\"access-control-allow-methods\"] = METHODS;\n const requested = request.headers.get(\"access-control-request-headers\");\n if (requested) headers[\"access-control-allow-headers\"] = requested;\n }\n return new Response(null, { status: 204, headers });\n };\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { Elysia } from \"elysia\";\nimport { websocket } from \"elysia/websocket\";\nimport { createLogger } from \"./logger\";\nimport { kebabCase } from \"./kebab\";\nimport { joinRoute, ownerPath } from \"./routes\";\nimport { buildErrorHelpers } from \"./action\";\nimport {\n ActionExecutionError,\n type ActionErrorDefinition,\n type BaseContext,\n} from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { inTransaction, onTransactionCommit } from \"./events/transaction\";\nimport { serializeSocketSchema } from \"./socket-schema\";\nimport {\n byteLength,\n encodeFrame,\n isControlEvent,\n isSocketEnvelope,\n isSocketRoom,\n isSocketSeq,\n replayFrame,\n replayHeadroom,\n signSeq,\n splitSeq,\n SOCKET_BUFFER_BYTES,\n SOCKET_BUFFER_MESSAGES,\n STANDARD_ERRORS,\n SOCKET_CLOSE,\n SOCKET_CONTROL,\n SOCKET_MAX_BYTES,\n SOCKET_PROTOCOL,\n SOCKET_SIGNATURE_LENGTH,\n SOCKET_TOKEN_PROTOCOL,\n} from \"./protocol\";\nimport { publicOrigin } from \"./cors\";\nimport { sensitivePointer } from \"./sensitive\";\nimport type {\n BrickSocketConfig,\n BrickSocketSender,\n SocketBroker,\n SocketBrokerMessage,\n SocketEmitArgs,\n SocketPayloads,\n SocketSchemas,\n RegisteredSocket,\n SocketSender,\n SocketSession,\n} from \"./socket-types\";\n\nexport type { RegisteredSocket };\n\nclass SocketDenied extends Error {}\n\n/** Validates and serializes one output message, rechecking what survives JSON. */\nfunction outputFrame(\n output: SocketSchemas,\n event: string,\n data: unknown,\n): string {\n const schema = Object.hasOwn(output, event) ? output[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new Error(\"Invalid socket output\");\n const frame = encodeFrame(event, data);\n if (byteLength(frame) > SOCKET_MAX_BYTES)\n throw new Error(\"Socket output too large\");\n if (!getCompiledCheck(schema).Check(JSON.parse(frame).data))\n throw new Error(\"Socket output is not JSON-compatible\");\n return frame;\n}\n\n/** Delivers within this process. The default broker of every app. */\nexport function localBroker(): SocketBroker {\n const topics = new Map<string, Set<(message: SocketBrokerMessage) => void>>();\n // Replay history: one rising counter per process, prefixed with its start so a restart reads as a gap.\n const epoch = Date.now();\n let counter = 0;\n /** Rooms dropped from `kept` once idle, at counter values up to this. */\n let swept = 0;\n const kept = new Map<\n string,\n {\n entries: { n: number; at: number; message: SocketBrokerMessage }[];\n /** The highest n no longer kept. */\n trimmed: number;\n maxAgeMs: number;\n }\n >();\n const prune = (names: Iterable<string>) => {\n for (const topic of names) {\n const room = kept.get(topic);\n if (!room) continue;\n const oldest = Date.now() - room.maxAgeMs;\n while (room.entries[0] && room.entries[0].at < oldest)\n room.trimmed = room.entries.shift()!.n;\n if (!room.entries.length) {\n kept.delete(topic);\n swept = counter;\n }\n }\n };\n return {\n publish(message, replay) {\n if (message.type === \"emit\" && replay) {\n const n = ++counter;\n message = { ...message, seq: `${epoch}-${n}` };\n const room = kept.get(message.topic) ?? {\n entries: [],\n trimmed: 0,\n maxAgeMs: replay.maxAgeMs,\n };\n kept.set(message.topic, room);\n room.entries.push({ n, at: Date.now(), message });\n if (room.entries.length > replay.keep)\n room.trimmed = room.entries.shift()!.n;\n // shortcut: idle rooms are swept every 1000 emits, not on a timer; fine while emits keep coming.\n if (n % 1000 === 0) prune([...kept.keys()]);\n }\n for (const deliver of topics.get(message.topic) ?? []) deliver(message);\n },\n head: () => `${epoch}-${counter}`,\n history(topic, since) {\n const [from, n] = since.split(\"-\").map(Number) as [number, number];\n if (from !== epoch || n > counter) return undefined;\n prune([topic]);\n const room = kept.get(topic);\n if (!room) return n >= swept ? [] : undefined;\n if (n < room.trimmed) return undefined;\n return room.entries\n .filter((entry) => entry.n > n)\n .map((entry) => entry.message);\n },\n subscribe(topic, deliver) {\n const listeners = topics.get(topic) ?? new Set();\n listeners.add(deliver);\n topics.set(topic, listeners);\n return () => {\n listeners.delete(deliver);\n if (!listeners.size) topics.delete(topic);\n };\n },\n };\n}\n\nexport function defineServiceSocket<\n I extends SocketSchemas,\n O extends SocketSchemas,\n Ctx extends BaseContext,\n E extends Record<string, ActionErrorDefinition> = {},\n>(\n service: string,\n config: BrickSocketConfig<I, O, Ctx, E>,\n resolve: (request: Request) => Promise<Ctx>,\n): RegisteredSocket {\n if (\n !config.name ||\n config.name.split(\".\").some((part) => !/^[a-zA-Z_][\\w-]*$/.test(part))\n )\n throw new Error(\"Invalid socket name\");\n if (\n config.path !== undefined &&\n (!config.path.startsWith(\"/\") ||\n /[?#*]/.test(config.path) ||\n config.path.split(\"/\").some((segment) => segment.startsWith(\":\")))\n )\n throw new Error(\n \"Socket path must be a static route (relative to its service) without a query or fragment\",\n );\n const input = Object.freeze({ ...config.input });\n const output = Object.freeze({ ...config.output });\n const handlers = { ...config.handlers };\n if (\n Object.keys(input).length !== Object.keys(handlers).length ||\n Object.keys(input).some(\n (key) =>\n !Object.hasOwn(handlers, key) || typeof handlers[key] !== \"function\",\n )\n )\n throw new Error(\"Every socket input event needs exactly one handler\");\n if ([...Object.keys(input), ...Object.keys(output)].some(isControlEvent))\n throw new Error(\"Socket event names starting with $ are reserved\");\n const maxRooms = config.maxRooms ?? 100;\n if (!Number.isInteger(maxRooms) || maxRooms < 1)\n throw new Error(\"Socket maxRooms must be a positive integer\");\n const replay = config.replay && { ...config.replay };\n if (\n replay &&\n !(\n Number.isInteger(replay.keep) &&\n replay.keep > 0 &&\n replay.maxAgeMs > 0 &&\n Number.isFinite(replay.maxAgeMs)\n )\n )\n throw new Error(\n \"Socket replay needs a positive integer keep and a positive finite maxAgeMs\",\n );\n for (const [path, schema] of [\n ...Object.entries(input).map(([k, v]) => [`input.${k}`, v] as const),\n ...Object.entries(output).map(([k, v]) => [`output.${k}`, v] as const),\n ]) {\n serializeSocketSchema(schema, path);\n getCompiledCheck(schema);\n const at = sensitivePointer(schema);\n if (at)\n throw new Error(\n `Service '${service}' socket '${config.name}': ${path} marks '${at}' t.Sensitive, which sockets do not support yet; keep the secret out of socket messages`,\n );\n }\n const typed = (socket: SocketSender): BrickSocketSender<SocketPayloads<O>> =>\n socket;\n const error = buildErrorHelpers(config.errors);\n const context = async (request: Request) => {\n const ctx = await resolve(request);\n if (config.authorize && !(await config.authorize({ ctx })))\n throw new SocketDenied();\n return ctx;\n };\n const topicPrefix = `${service}.${config.name}:`;\n const topic = (room: string) => {\n if (!isSocketRoom(room)) throw new Error(`Invalid socket room: ${room}`);\n return topicPrefix + room;\n };\n const brokers = new Set<SocketBroker>();\n const publish = (messages: SocketBrokerMessage[], after: unknown) => {\n const send = () => {\n for (const broker of brokers)\n for (const message of messages) broker.publish(message, replay);\n };\n if (after === undefined) return send();\n if (!inTransaction(after))\n throw new Error(\n \"Socket emit { after: tx } needs a tx from runInTransaction(db, (tx) => ...); a plain db.transaction() is not tracked, so the emit could be sent for a write that rolls back\",\n );\n void onTransactionCommit(after, send);\n };\n return {\n schema: {\n name: config.name,\n path: config.path,\n description: config.description,\n input: Object.keys(input),\n output: Object.keys(output),\n hasAuthorize: !!config.authorize,\n },\n input,\n output,\n ...(config.errors ? { errors: { ...config.errors } } : {}),\n allowedOrigins: config.allowedOrigins\n ? [...config.allowedOrigins]\n : undefined,\n allowMissingOrigin: config.allowMissingOrigin,\n maxRooms,\n replay,\n brokers,\n topicPrefix,\n topic,\n handle: {\n name: config.name,\n emit(rooms, ...[event, payload, options]: SocketEmitArgs<any>) {\n const unique = [\n ...new Set(typeof rooms === \"string\" ? [rooms] : rooms),\n ];\n const topics = unique.map(topic);\n const frame = outputFrame(output, event, payload);\n // Room and sequence are added to each replayed frame on delivery.\n if (\n replay &&\n unique.some(\n (room) =>\n byteLength(frame) + replayHeadroom(room) > SOCKET_MAX_BYTES,\n )\n )\n throw new Error(\"Socket output too large\");\n publish(\n topics.map((topic) => ({ type: \"emit\", topic, frame })),\n options?.after,\n );\n },\n kick(room, options = {}) {\n publish(\n [\n {\n type: \"kick\",\n topic: topic(room),\n ...(options.also !== undefined\n ? { also: topic(options.also) }\n : {}),\n ...(options.reason !== undefined\n ? { reason: String(options.reason) }\n : {}),\n },\n ],\n undefined,\n );\n },\n },\n async connect(request) {\n const initial = await context(request);\n const rooms = [\n ...new Set(config.rooms ? await config.rooms({ ctx: initial }) : []),\n ];\n rooms.forEach(topic);\n if (rooms.length > maxRooms) throw new Error(\"Too many socket rooms\");\n return {\n rooms,\n async open(socket) {\n await config.open?.({ ctx: initial, socket: typed(socket) });\n },\n async message(event, data, socket) {\n const schema = Object.hasOwn(input, event) ? input[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new SocketDenied();\n const ctx = await context(request);\n if (!socket.isOpen) return;\n // The schema and event were checked together before dispatch.\n const handler = handlers[event as keyof I];\n await handler({\n input: data as SocketPayloads<I>[keyof I],\n ctx,\n socket: typed(socket),\n error,\n });\n },\n async join(room) {\n const ctx = await context(request);\n return !!config.join && (await config.join({ ctx, room }));\n },\n async close(socket, code, reason) {\n await config.close?.({\n ctx: initial,\n socket: typed(socket),\n code,\n reason,\n });\n },\n };\n },\n };\n}\n\n/** `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */\nexport function socketPath(\n prefix: string,\n service: string,\n socket: RegisteredSocket,\n): string {\n return joinRoute(\n ownerPath(prefix, service),\n socket.schema.path ?? `/${kebabCase(socket.schema.name)}`,\n );\n}\n\nconst protocols = (request: Request) =>\n (request.headers.get(\"sec-websocket-protocol\") ?? \"\")\n .split(\",\")\n .map((protocol) => protocol.trim())\n .filter(Boolean);\n\n/** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */\nfunction tokenRequest(request: Request): {\n token: boolean;\n request: Request;\n} {\n const offered = protocols(request);\n const token = offered\n .find((protocol) => protocol.startsWith(SOCKET_TOKEN_PROTOCOL))\n ?.slice(SOCKET_TOKEN_PROTOCOL.length);\n if (!token) return { token: false, request };\n const headers = new Headers(request.headers);\n headers.set(\"authorization\", `Bearer ${token}`);\n const rest = offered.filter(\n (protocol) => !protocol.startsWith(SOCKET_TOKEN_PROTOCOL),\n );\n if (rest.length) headers.set(\"sec-websocket-protocol\", rest.join(\", \"));\n else headers.delete(\"sec-websocket-protocol\");\n return {\n token: true,\n request: new Request(request.url, { method: request.method, headers }),\n };\n}\n\n/** Each connection owns its queue and service session. */\nexport function mountSockets(\n app: Elysia,\n sockets: { service: string; path: string; definition: RegisteredSocket }[],\n broker: SocketBroker,\n secret?: string,\n): void {\n if (secret === \"\") throw new Error(\"Brick: sockets.secret can't be empty\");\n // A sequence is signed for its room, so a client resumes only a room it was sent that sequence in.\n const key = secret ?? randomBytes(32);\n const signature = (topic: string, seq: string) =>\n createHmac(\"sha256\", key)\n .update(`${topic}\\n${seq}`)\n .digest(\"base64url\")\n .slice(0, SOCKET_SIGNATURE_LENGTH);\n const sign = (topic: string, seq: string) =>\n signSeq(seq, signature(topic, seq));\n const verify = (topic: string, signed: string) => {\n const [seq, sig] = splitSeq(signed);\n return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq)))\n ? seq\n : undefined;\n };\n if (\n sockets.some(({ definition }) => definition.replay) &&\n !(broker.head && broker.history)\n )\n throw new Error(\"Brick: the socket broker does not support replay\");\n for (const { definition } of sockets) definition.brokers.add(broker);\n app.onStop(async () => {\n for (const { definition } of sockets) definition.brokers.delete(broker);\n await broker.close?.();\n });\n if (!sockets.length) return;\n app.use(\n websocket({\n maxPayloadLength: SOCKET_MAX_BYTES,\n backpressureLimit: SOCKET_BUFFER_BYTES,\n closeOnBackpressureLimit: true,\n }),\n );\n for (const { service, path, definition } of sockets) {\n const logger = createLogger(\n `[Brick socket ${service}.${definition.schema.name}]`,\n );\n const sessions = new WeakMap<Request, SocketSession>();\n type Peer = {\n request: Request;\n send(data: string): number;\n close(code?: number, reason?: string): void;\n subscribe(topic: string): void;\n unsubscribe(topic: string): void;\n isSubscribed(topic: string): boolean;\n readonly readyState: number;\n };\n type Connection = {\n ws: Peer;\n session: SocketSession;\n sender: SocketSender;\n tail: Promise<void>;\n pending: number;\n bytes: number;\n closed: boolean;\n /** Every room topic the connection is in. */\n rooms: Set<string>;\n /** The topics the client joined, which it may leave. */\n requested: Set<string>;\n };\n const connections = new WeakMap<Request, Connection>();\n const roomOf = (topic: string) =>\n topic.slice(definition.topicPrefix.length);\n const holders = new Map<\n string,\n { connections: Set<Connection>; unsubscribe: () => void }\n >();\n const control = (ws: Peer, event: string, data: unknown) => {\n if (ws.readyState === 1) ws.send(encodeFrame(event, data));\n };\n /** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */\n const enter = async (\n connection: Connection,\n topic: string,\n live = true,\n ) => {\n if (connection.rooms.has(topic)) return;\n connection.rooms.add(topic);\n if (live) connection.ws.subscribe(topic);\n let holder = holders.get(topic);\n if (!holder) {\n holder = {\n connections: new Set(),\n unsubscribe: () => {},\n };\n holders.set(topic, holder);\n holder.unsubscribe = broker.subscribe(topic, deliver);\n }\n holder.connections.add(connection);\n await broker.ready?.(topic).catch(() => {});\n };\n const exit = (connection: Connection, topic: string) => {\n if (!connection.rooms.delete(topic)) return;\n connection.requested.delete(topic);\n if (connection.ws.readyState === 1) connection.ws.unsubscribe(topic);\n const holder = holders.get(topic);\n if (!holder?.connections.delete(connection) || holder.connections.size)\n return;\n holders.delete(topic);\n holder.unsubscribe();\n };\n const frameOf = (message: SocketBrokerMessage & { type: \"emit\" }) =>\n message.seq === undefined\n ? message.frame\n : replayFrame(\n message.frame,\n roomOf(message.topic),\n sign(message.topic, message.seq),\n );\n const deliver = (message: SocketBrokerMessage) => {\n if (message.type === \"emit\") {\n app.server?.publish(message.topic, frameOf(message));\n return;\n }\n for (const connection of holders.get(message.topic)?.connections ?? []) {\n if (message.also && !connection.ws.isSubscribed(message.also)) continue;\n exit(connection, message.topic);\n control(connection.ws, SOCKET_CONTROL.left, {\n room: roomOf(message.topic),\n ...(message.reason !== undefined ? { reason: message.reason } : {}),\n });\n }\n };\n /** `$join` and `$leave`, acknowledged with the same event. */\n const room = async (\n connection: Connection,\n event: string,\n data: unknown,\n ) => {\n const fields = (data && typeof data === \"object\" ? data : {}) as Record<\n string,\n unknown\n >;\n const { room: name, since } = fields;\n if (!isSocketRoom(name) || (since !== undefined && !isSocketSeq(since)))\n throw new SocketDenied();\n const topic = definition.topic(name);\n if (event === SOCKET_CONTROL.leave) {\n if (connection.requested.has(topic)) exit(connection, topic);\n control(connection.ws, SOCKET_CONTROL.leave, { room: name });\n return;\n }\n const isOpen = () => !connection.closed && connection.ws.readyState === 1;\n const ok =\n connection.rooms.has(topic) ||\n (connection.rooms.size < definition.maxRooms &&\n (await connection.session.join(name)));\n if (!isOpen()) return;\n const replay = definition.replay;\n let seq: string | undefined;\n if (ok && !connection.rooms.has(topic)) {\n const entered = enter(connection, topic, !replay);\n connection.requested.add(topic);\n await entered;\n if (replay && connection.rooms.has(topic)) {\n // Held in this process before reading history, so later emits are either in it or arrive live.\n // A since not signed for this room gets no history, only $gap.\n const start =\n since === undefined\n ? await broker.head!(topic)\n : verify(topic, since);\n const missed =\n start === undefined\n ? undefined\n : await broker.history!(topic, start, replay);\n const restart = missed ? undefined : await broker.head!(topic);\n if (!isOpen()) return;\n if (connection.rooms.has(topic)) {\n connection.ws.subscribe(topic);\n if (since === undefined) seq = sign(topic, start!);\n for (const message of missed ?? [])\n if (message.type === \"emit\") connection.ws.send(frameOf(message));\n if (restart !== undefined)\n control(connection.ws, SOCKET_CONTROL.gap, {\n room: name,\n seq: sign(topic, restart),\n });\n }\n }\n }\n // A kick while joining wins.\n control(connection.ws, SOCKET_CONTROL.join, {\n room: name,\n ok: ok && connection.rooms.has(topic),\n ...(seq !== undefined ? { seq } : {}),\n });\n };\n // The codes a handler can raise with `error.CODE()`: declared plus standard.\n const raisable = { ...STANDARD_ERRORS, ...definition.errors };\n const fail = (ws: Peer, error: unknown) => {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n if (ws.readyState !== 1) return;\n ws.close(\n error instanceof SocketDenied\n ? SOCKET_CLOSE.policy\n : SOCKET_CLOSE.serverError,\n error instanceof SocketDenied\n ? \"Message refused\"\n : \"Socket handler failed\",\n );\n };\n app.ws(path, {\n async beforeHandle({ request }) {\n if (sessions.has(request)) return;\n const { token, request: resolved } = tokenRequest(request);\n const origin = request.headers.get(\"origin\");\n if (\n origin\n ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(\n origin,\n )\n : // Without cookies a missing Origin is no hijacking risk.\n !(definition.allowMissingOrigin ?? token)\n )\n return new Response(\"Socket origin refused\", { status: 403 });\n try {\n sessions.set(request, await definition.connect(resolved));\n } catch (error) {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n return new Response(\"Socket connection refused\", {\n status: error instanceof SocketDenied ? 403 : 500,\n });\n }\n },\n upgrade: ({ request }: { request: Request }) =>\n protocols(request).includes(SOCKET_PROTOCOL)\n ? { \"Sec-WebSocket-Protocol\": SOCKET_PROTOCOL }\n : undefined,\n async open(ws) {\n const session = sessions.get(ws.request);\n if (!session) {\n ws.close(SOCKET_CLOSE.serverError, \"Missing socket session\");\n return;\n }\n const sender: SocketSender = {\n get isOpen() {\n return !state.closed && ws.readyState === 1;\n },\n close() {\n ws.close(SOCKET_CLOSE.normal, \"\");\n },\n send(event, data) {\n if (!sender.isOpen) throw new Error(\"Socket is closed\");\n const result = ws.send(outputFrame(definition.output, event, data));\n if (result === 0) {\n ws.close(SOCKET_CLOSE.tryAgainLater, \"Socket buffer full\");\n throw new Error(\"Socket buffer full\");\n }\n },\n };\n const state: Connection = {\n ws,\n session,\n sender,\n tail: Promise.resolve(),\n pending: 0,\n bytes: 0,\n closed: false,\n rooms: new Set(),\n requested: new Set(),\n };\n connections.set(ws.request, state);\n try {\n await Promise.all(\n session.rooms.map((room) => enter(state, definition.topic(room))),\n );\n await session.open(sender);\n } catch (error) {\n fail(ws, error);\n }\n },\n message(ws, value: unknown) {\n const state = connections.get(ws.request);\n if (!state || state.closed || ws.readyState !== 1) return;\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n ws.close(SOCKET_CLOSE.unsupportedData, \"Only JSON text is supported\");\n return;\n }\n if (typeof value === \"string\") {\n ws.close(SOCKET_CLOSE.invalidPayload, \"Expected JSON envelope\");\n return;\n }\n if (!isSocketEnvelope(value)) {\n ws.close(SOCKET_CLOSE.policy, \"Invalid socket envelope\");\n return;\n }\n const size = byteLength(JSON.stringify(value));\n if (size > SOCKET_MAX_BYTES) {\n ws.close(SOCKET_CLOSE.tooLarge, \"Message too large\");\n return;\n }\n if (\n state.pending >= SOCKET_BUFFER_MESSAGES ||\n state.bytes + size > SOCKET_BUFFER_BYTES\n ) {\n ws.close(SOCKET_CLOSE.tryAgainLater, \"Socket queue full\");\n return;\n }\n state.pending++;\n state.bytes += size;\n state.tail = state.tail\n .then(async () => {\n if (state.closed || ws.readyState !== 1) return;\n if (\n value.event === SOCKET_CONTROL.join ||\n value.event === SOCKET_CONTROL.leave\n )\n await room(state, value.event, value.data);\n else\n await state.session.message(\n value.event,\n value.data,\n state.sender,\n );\n })\n .catch((error: unknown) => {\n // A declared error answers a handler message; the connection stays\n // open. A failed $join or $leave, or an error with an undeclared\n // code (from a nested action, say), is logged and closes it, which\n // also rejects the client's pending joins.\n if (\n error instanceof ActionExecutionError &&\n !state.closed &&\n value.event !== SOCKET_CONTROL.join &&\n value.event !== SOCKET_CONTROL.leave &&\n Object.hasOwn(raisable, error.code)\n )\n try {\n const frame = encodeFrame(SOCKET_CONTROL.error, {\n event: value.event,\n ...error.toJSON(),\n });\n if (byteLength(frame) > SOCKET_MAX_BYTES)\n throw new Error(\"Socket error too large\", { cause: error });\n if (ws.readyState === 1) ws.send(frame);\n return;\n } catch (unsent) {\n return fail(ws, unsent);\n }\n fail(ws, error);\n })\n .finally(() => {\n state.pending--;\n state.bytes -= size;\n });\n // Brick owns the queue. Returning the tail here makes native close wait on application work.\n },\n async close(ws, code = 1006, reason = \"\") {\n const state = connections.get(ws.request);\n sessions.delete(ws.request);\n if (!state || state.closed) return;\n state.closed = true;\n for (const topic of state.rooms) exit(state, topic);\n try {\n await state.session.close(state.sender, code, reason);\n } catch (error) {\n logger.error({\n error,\n service,\n socket: definition.schema.name,\n phase: \"cleanup\",\n });\n }\n connections.delete(ws.request);\n },\n });\n }\n}\n","import { ATTR, SPAN } from \"./telemetry-names\";\nimport type { HttpMethod } from \"./http\";\nimport { Elysia } from \"elysia\";\nimport {\n compileBrickApplication,\n type CompiledApplication,\n type RouteIR,\n} from \"./compiler\";\nimport { DuplicateNameError, type Service, type Tool } from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getPluginEndpoints, installedPlugins } from \"./plugin\";\nimport { pluginDepsOf, pluginLifecycle, setupAppPlugins } from \"./plugin-app\";\nimport type { PluginInstance } from \"./define-plugin\";\nimport { OPENAPI_DEFAULTS, generateOpenApiSpec } from \"./openapi\";\nimport { resolveSecrets, type SecretSource } from \"./secrets\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n type ApiDocument,\n type DocumentationOptions,\n type OpenApiDocument,\n type ReferenceOptions,\n} from \"./docs\";\nimport {\n DASHBOARD_MCP_ROUTE,\n DASHBOARD_MCP_TOOLS,\n normalizeDashboard,\n type DashboardOptions,\n} from \"./dashboard\";\nimport {\n createMcpHandler,\n createMcpRegistry,\n type McpRegistry,\n type McpToolDefinition,\n} from \"./mcp\";\nimport { dashboardMcpCaller, markDashboardArrival } from \"./dashboard-identity\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\nimport {\n instrumentDatabase,\n instrumentFetch,\n traceHttpRequest,\n withSpan,\n} from \"./telemetry\";\nimport { EventsHub } from \"./events/hub\";\nimport { appDeps } from \"./deps\";\nimport { WEBHOOK_ROUTE } from \"./events/workflows\";\nimport type { EventsOptions } from \"./events/types\";\nimport { localBroker, mountSockets, socketPath } from \"./socket\";\nimport { DEFAULT_PREFIX, routeKey } from \"./routes\";\nimport type { SocketBroker } from \"./socket-types\";\nimport { corsHook, type CorsOptions } from \"./cors\";\nimport { useStorages } from \"./storage\";\nimport {\n checkFileStorages,\n LOCAL_FILES_ROUTE,\n localFileDirs,\n localFilesRoute,\n} from \"./file-storage\";\nimport { portOf } from \"./service-port\";\nimport { bodyLimitParser, rawBodyParser } from \"./compiler/runtime\";\nimport { markAddressSource, type ClientIp } from \"./rate-limit\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Run the plugins' preparations (such as CRUD's prepared queries) at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n /**\n * `true` serves a Scalar page at /reference. Options serve one only with a\n * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.\n */\n reference?: boolean | ReferenceOptions; // default false\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (plain routes, not actions), mounted at startup. */\n endpoints?: EndpointDefinition[];\n /**\n * Record request, action, and RPC spans with OpenTelemetry (default false).\n * Spans go to the globally registered tracer provider; without one they are\n * no-ops. `brick dev` shows them in its dashboard.\n */\n telemetry?: boolean;\n /**\n * Developer documentation for the `brick dev` dashboard (its Docs tab): a\n * folder of `.md`/`.mdx` pages in Fumadocs' layout, with frontmatter and\n * `meta.json` for ordering. A string is the folder. Relative paths start at\n * the folder of the app entry, as they read in the file that sets them (from\n * `src/app.ts`, `\"../docs\"` is `docs/` at the project root). Needs\n * `fumadocs-core` and `@mdx-js/mdx` installed.\n */\n documentation?: string | DocumentationOptions;\n /**\n * Monitoring dashboard for `brick start`, on a port of its own and behind\n * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.\n */\n dashboard?: DashboardOptions;\n /**\n * Record events in the same database transaction as the writes that cause them,\n * and deliver them to listeners after the commit. Generated CRUD writes emit\n * `<resource>.create`, `<resource>.update` and `<resource>.delete`. A service\n * records events once its database holds an `outboxTable()`. Reads emit nothing,\n * and an app without this option behaves exactly as before. See `EventsOptions`.\n */\n events?: EventsOptions;\n /**\n * Socket fan-out. `broker` carries emits and kicks between processes\n * (default: this process only). See `redisBroker`. The app closes it on stop.\n * `secret` signs replay sequences; give every process the same one so a\n * client can resume on any of them (default: random per process).\n */\n sockets?: { broker?: SocketBroker; secret?: string };\n /**\n * App-wide plugins from `definePlugin`, in install order: their `app` part\n * adds start/stop lifecycle, middleware and listeners. Plugins installed with\n * `service.use()` or `resource.use()` take part too, before these.\n */\n plugins?: readonly PluginInstance<any, any>[];\n /**\n * CORS for browser callers on other origins. `true` allows the app's own\n * origin; a string, list or predicate names the allowed origins, compared\n * exactly. `{ origin, credentials }` adds `credentials: true` for cookies.\n * Other origins get no `Access-Control-Allow-Origin`. Preflights are answered.\n */\n cors?: false | CorsOptions;\n /**\n * Where the client address is, for `rateLimit: { per: \"ip\" }`. By default it\n * is the socket peer; behind a proxy, read the header your proxy sets. Brick\n * never reads `X-Forwarded-For` or any other header itself.\n *\n * @example\n * clientIp: ({ request, peer }) => request.headers.get(\"fly-client-ip\") ?? peer,\n */\n clientIp?: ClientIp;\n}\n\n/**\n * Create the HTTP application: an Elysia app that serves every service's\n * actions (and the tools that opt in with `http: true`) as routes, with\n * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,\n * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.\n *\n * Services come from the global registry unless `services` is given. The app\n * does not listen by itself: export it from your entry file, where `brick dev`,\n * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your\n * own server bootstrap.\n *\n * @param options - `prefix` for action routes (default `/api`), `services`,\n * `title`, `version`, and `description` for the OpenAPI document, `docs` and the\n * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,\n * `telemetry`, `documentation`, and `dashboard`. See `CreateServerOptions`.\n * @returns The app, with `definition` (its services, prefix, and routes),\n * `endpoint()` to add raw routes, and `listEndpoints()` to list them.\n * @throws When a required secret is missing, `documentation` or `dashboard`\n * is invalid, or `deps` is passed (it moved to `defineService({ deps })`).\n * @example\n * import { brick } from \"@brickkit/core\";\n * import { pagesService } from \"./services/pages\";\n *\n * export default brick({\n * services: [pagesService],\n * title: \"Pages API\",\n * telemetry: true,\n * });\n */\nexport function brick(options: CreateServerOptions = {}): BrickApp {\n if (\"deps\" in options)\n throw new Error(\n \"Brick: brick({ deps }) was removed in 0.16. Move each value into the service that uses it: defineService(name, { deps: { ... } }).\",\n );\n const prefix =\n options.prefix ?? options.compilation?.ir.prefix ?? DEFAULT_PREFIX;\n const title = options.title ?? OPENAPI_DEFAULTS.title;\n const version = options.version ?? OPENAPI_DEFAULTS.version;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? OPENAPI_DEFAULTS.path;\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n const dashboard = normalizeDashboard(options.dashboard);\n // The dashboard shows what is traced, so having one means tracing.\n const telemetry = options.telemetry === true || dashboard !== undefined;\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n const plugins = setupAppPlugins(\n services.flatMap((service) => installedPlugins(service)),\n options.plugins ?? [],\n );\n const addressSource = {\n clientIp: options.clientIp,\n server: () => app.server,\n };\n // CORS first, so preflights are answered and its headers reach responses\n // from middleware, which skips the later lifecycle hooks.\n app.onRequest(({ request }) => {\n markDashboardArrival(request);\n markAddressSource(request, addressSource);\n });\n if (options.cors) app.onRequest(corsHook(options.cors));\n for (const handler of plugins.middleware) app.onRequest(handler);\n\n // Mounted and registered in one call, so actions and sockets can't shadow them.\n const registeredRoutes = new Map<string, boolean>();\n const webhookRoutes = new Map<string, string>();\n const builtIn = (path: string, handler: any) => {\n app.get(path, handler);\n registeredRoutes.set(routeKey(\"GET\", path), false);\n };\n\n builtIn(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false)\n app.use(\n requestLoggingPlugin(requestLogging === true ? {} : requestLogging),\n );\n\n // Scalar API reference page (opt-in): `reference: true`, or options with a path.\n const reference = options.reference ?? false;\n const referenceOptions: ReferenceOptions =\n typeof reference === \"object\" ? reference : {};\n const referencePath =\n reference === true ? \"/reference\" : referenceOptions.path;\n if (referencePath !== undefined) {\n builtIn(\n referencePath,\n htmlResponse(\n scalarDocsHTML(\n referenceOptions.specUrl ?? openApiPath,\n referenceOptions.title ?? title,\n ),\n ),\n );\n }\n\n const byName = new Map<string, unknown>();\n for (const service of services) {\n if ((byName.get(service.name) ?? service) !== service)\n throw new DuplicateNameError(\n `Brick: duplicate service \"${service.name}\" in brick()`,\n );\n byName.set(service.name, service);\n }\n const eventsOptions = plugins.listeners.length\n ? {\n ...options.events,\n listeners: [...(options.events?.listeners ?? []), ...plugins.listeners],\n }\n : options.events;\n const events = eventsOptions\n ? new EventsHub(eventsOptions, appDeps(services), telemetry).attach(\n services,\n )\n : undefined;\n if (events?.workflows)\n app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));\n if (telemetry) {\n for (const service of services) instrumentDatabase(service.getDb());\n instrumentFetch();\n }\n\n // Close declarations before anything reads them.\n for (const service of services) service.build();\n for (const service of services)\n checkFileStorages(service, [\n portOf(service).deps,\n ...installedPlugins(service).map(pluginDepsOf),\n ]);\n const localDirs = localFileDirs([\n ...services.map((service) => portOf(service).deps),\n ...plugins.deps,\n ]);\n if (localDirs.size) builtIn(LOCAL_FILES_ROUTE, localFilesRoute(localDirs));\n\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n const paths = { ...spec.paths };\n for (const [path, operations] of Object.entries(\n endpointPaths(endpointDefs),\n ))\n paths[path] = { ...paths[path], ...operations };\n return { ...spec, paths };\n };\n\n if (enableDocs) {\n builtIn(\n openApiPath,\n cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n ),\n );\n builtIn(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n builtIn(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n }\n // Built from `definition`, below.\n builtIn(\"/_brick/services\", (context: any) => architecture(context));\n\n const dashboardTools: Tool<any, any, any, any>[] = [];\n const dashboardToolService = new Map<string, string>();\n for (const service of services)\n for (const tool of service.listTools()) {\n if (tool.config.dashboard !== true) continue;\n if ((DASHBOARD_MCP_TOOLS as readonly string[]).includes(tool.name))\n throw new DuplicateNameError(\n `Brick: the tool '${tool.name}' is marked dashboard: true, but the dashboard's MCP endpoint has a tool of that name. Rename yours.`,\n );\n const other = dashboardToolService.get(tool.name);\n if (other !== undefined)\n throw new DuplicateNameError(\n `Brick: the services '${other}' and '${service.name}' both have a tool '${tool.name}' marked dashboard: true. The dashboard's MCP endpoint needs one name per tool, so rename one of them.`,\n );\n dashboardToolService.set(tool.name, service.name);\n dashboardTools.push(tool);\n }\n const toolRegistry = createMcpRegistry({ tools: dashboardTools });\n const readsOnly = (tool: McpToolDefinition) =>\n tool.annotations.readOnlyHint === true;\n const forCaller = (write: boolean): McpRegistry => ({\n listTools: () =>\n toolRegistry.listTools().filter((tool) => write || readsOnly(tool)),\n callTool(name, args, ctx) {\n const tool = toolRegistry.listTools().find((item) => item.name === name);\n if (tool && !write && !readsOnly(tool))\n throw new Error(\n `${name} can change data, so only a signed-in user may call it: dashboard.auth.authorize must return { user }. A token, or authorize returning true, can only read.`,\n );\n return toolRegistry.callTool(name, args, ctx);\n },\n });\n const mcpHandlers = [false, true].map((write) =>\n createMcpHandler({\n registry: forCaller(write),\n serverInfo: { name: title, version },\n }),\n );\n app.post(DASHBOARD_MCP_ROUTE, ({ request }) => {\n const caller = dashboardMcpCaller(request);\n return caller\n ? mcpHandlers[caller.write ? 1 : 0]!(request, {\n dashboard: caller.user ? { user: caller.user } : {},\n })\n : new Response(\"Unauthorized\", { status: 401 });\n });\n registeredRoutes.set(routeKey(\"POST\", DASHBOARD_MCP_ROUTE), false);\n\n const sockets = services.flatMap((service) =>\n service.listSockets().map((definition) => ({\n service: service.name,\n path: socketPath(prefix, service.name, definition),\n definition,\n })),\n );\n const socketRoutes = new Set<string>();\n for (const socket of sockets) {\n const key = routeKey(\"GET\", socket.path);\n if (registeredRoutes.has(key) || socketRoutes.has(key))\n throw new DuplicateNameError(\n `Brick: duplicate socket route '${socket.path}'`,\n );\n socketRoutes.add(key);\n }\n const mountRoute = (\n method: HttpMethod,\n path: string,\n handler: any,\n plugin = false,\n hook?: object,\n webhook?: string,\n ) => {\n const key = routeKey(method, path);\n if (socketRoutes.has(key))\n throw new DuplicateNameError(\n `Brick: route '${method} ${path}' conflicts with a socket`,\n );\n if (registeredRoutes.has(key)) {\n const other = webhook ?? webhookRoutes.get(key);\n if (other)\n throw new DuplicateNameError(\n `Brick: route '${method} ${path}' is claimed by webhook '${other}' and by another route; a webhook cannot share its route`,\n );\n if (plugin || registeredRoutes.get(key))\n throw new DuplicateNameError(\n `Brick: duplicate plugin route '${method} ${path}'`,\n );\n return false;\n }\n if (hook) app.route(method, path, hook, handler);\n else app.route(method, path, handler);\n registeredRoutes.set(key, plugin);\n if (webhook) webhookRoutes.set(key, webhook);\n return true;\n };\n\n const mountEndpoint = (def: EndpointDefinition, plugin = false) => {\n const handler = createEndpointHandler(def, services);\n mountRoute(\n def.method,\n def.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, def.method, def.path, () =>\n handler(context),\n )\n : handler,\n plugin,\n );\n endpointDefs.push(def);\n endpointRevision++;\n };\n\n for (const service of services) {\n for (const def of getPluginEndpoints(service, prefix))\n mountEndpoint(def, true);\n }\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n brickApp.openApiDocument = buildSpec;\n brickApp.referenceDocuments = async () => {\n const documents: ApiDocument[] = enableDocs\n ? [{ title, document: buildSpec() as unknown as OpenApiDocument }]\n : [];\n for (const extra of referenceOptions.documents ?? []) {\n try {\n const document =\n typeof extra.document === \"function\"\n ? await extra.document()\n : extra.document;\n documents.push({ title: extra.title, document });\n } catch (error) {\n console.warn(\n `[Brick-TS] Skipping the \"${extra.title}\" API document: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return documents;\n };\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n const mountedRoutes: RouteIR[] = [];\n for (const route of compilation.routes) {\n const { handler } = route;\n const invoke = (context: any) => {\n const result = telemetry\n ? withSpan(\n `${SPAN.actionPrefix}${route.ir.service}.${route.ir.action}`,\n {\n [ATTR.service]: route.ir.service,\n [ATTR.action]: route.ir.action,\n },\n () => handler(context),\n )\n : handler(context);\n return result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ? Promise.resolve(result).then(jsonActionResult)\n : jsonActionResult(result);\n };\n const mounted = mountRoute(\n route.ir.method,\n route.ir.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, route.ir.method, route.ir.path, () =>\n invoke(context),\n )\n : invoke,\n Boolean(route.ir.plugin),\n route.ir.kind === \"webhook\"\n ? { parse: rawBodyParser(route.ir.bodyLimit!) }\n : route.ir.bodyLimit\n ? { parse: bodyLimitParser(route.ir.bodyLimit) }\n : undefined,\n route.ir.kind === \"webhook\"\n ? `${route.ir.service}.${route.ir.action}`\n : undefined,\n );\n if (mounted) mountedRoutes.push(route.ir);\n }\n\n mountSockets(\n app,\n sockets,\n options.sockets?.broker ?? localBroker(),\n options.sockets?.secret,\n );\n const definition = Object.freeze({\n services: Object.freeze([...services]),\n prefix,\n routes: Object.freeze(mountedRoutes),\n sockets: Object.freeze(\n sockets.map(({ service, path, definition }) => ({\n ...definition.schema,\n service,\n path,\n })),\n ),\n telemetry,\n documentation: normalizeDocumentation(options.documentation),\n dashboard,\n ...(events ? { events: events.describe() } : {}),\n plugins: Object.freeze(plugins.plugins),\n });\n Object.defineProperty(brickApp, \"definition\", { value: definition });\n Object.defineProperty(brickApp, \"events\", { value: events });\n // Plugin lifecycle: start before serving, stop after the server stops.\n const lifecycle = pluginLifecycle(plugins.lifecycles);\n const releaseStorages = useStorages([\n ...services.map((service) => portOf(service).deps),\n ...plugins.deps,\n ]);\n const listen = app.listen.bind(app);\n const stop = app.stop.bind(app);\n Object.defineProperty(brickApp, \"start\", { value: lifecycle.start });\n // One rule with serve(): an app whose plugins fail to start does not serve.\n // listen() is synchronous, so it stops the server it already opened.\n brickApp.listen = ((...args: Parameters<typeof listen>) => {\n lifecycle.start().catch((error) => {\n console.error(\"[Brick-TS] A plugin failed to start:\", error);\n return Promise.resolve(stop(true))\n .finally(releaseStorages)\n .catch((stopError) =>\n console.error(\n \"[Brick-TS] Stopping after a failed plugin start failed:\",\n stopError,\n ),\n );\n });\n return listen(...args);\n }) as typeof brickApp.listen;\n brickApp.stop = (async (closeActiveConnections?: boolean) => {\n try {\n await stop(closeActiveConnections);\n } finally {\n try {\n await lifecycle.stop();\n } finally {\n await releaseStorages();\n }\n }\n }) as typeof brickApp.stop;\n Object.defineProperty(brickApp, \"serve\", {\n value: async ({ port }: { port: number }) => {\n await lifecycle.start();\n listen(port);\n events?.start();\n return brickApp;\n },\n });\n Object.defineProperty(brickApp, \"shutdown\", {\n value: async (closeActiveConnections?: boolean) => {\n await events?.stop();\n await brickApp.stop(closeActiveConnections);\n },\n });\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n const architecture = cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(definition),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n );\n\n return brickApp;\n}\n\nfunction normalizeDocumentation(\n documentation: string | DocumentationOptions | undefined,\n): DocumentationOptions | undefined {\n if (documentation === undefined) return undefined;\n const options =\n typeof documentation === \"string\" ? { dir: documentation } : documentation;\n if (typeof options.dir !== \"string\" || options.dir === \"\")\n throw new Error(\"Brick: documentation needs a folder, such as './docs'.\");\n return Object.freeze({\n dir: options.dir,\n ...(options.components ? { components: options.components } : {}),\n });\n}\n\nfunction jsonActionResult(value: unknown): unknown {\n return value === null\n ? new Response(\"null\", { headers: { \"content-type\": \"application/json\" } })\n : value;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiBA,MAAa,sBAAsB;CAAC;CAAO;CAAW;AAAU;;AA8GhE,MAAa,cAA6B,OAAO,IAAI,sBAAsB;;;;;AAK3E,MAAa,gBAA+B,OAAO,IACjD,wBACF;;AClIA,MAAM,YAAY,OAAO,IAAI,oBAAoB;;AAGj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