@brickkit/effect 0.16.0-beta.11 → 0.16.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-BU2vMdOO.js","names":["built","logged","mac","sqliteInteger","sqliteText","pgText","MARK","isPlainObject","warned","pointer","collect","register","invalid","idSchema","jsonSchema","internalsOf","internalsOf","sqliteInteger","sqliteText","pgText","pgInteger","logError","Every","sqliteInteger","sqliteText","sqliteIndex","pgText","pgInteger","pgIndex","WorkflowEngine","Workflow","columnIdSchema","pgText","sqliteText","integer","Workflow","WorkflowEngine","invalid"],"sources":["../src/errors.ts","../src/action-meta.ts","../src/telemetry-names.ts","../src/dashboard-identity.ts","../src/telemetry.ts","../src/context.ts","../src/actor.ts","../src/audit.ts","../src/file-schema.ts","../src/deps.ts","../src/definition-site.ts","../src/secrets.ts","../src/storage-errors.ts","../src/file-storage.ts","../src/storage.ts","../src/rate-limit.ts","../src/omit-undefined.ts","../src/sensitive.ts","../src/validation-issues.ts","../src/action.ts","../src/crud/codec.ts","../src/access.ts","../src/routes.ts","../src/architecture.ts","../src/registry.ts","../src/plugin-types.ts","../src/service-internals.ts","../src/plugin.ts","../src/docs.ts","../src/request-logger.ts","../src/openapi.ts","../src/events/catalog.ts","../src/events/transaction.ts","../src/socket-protocol.ts","../src/socket-schema.ts","../src/socket.ts","../src/raw-socket.ts","../src/events/query.ts","../src/events/unref.ts","../src/schedules/cron.ts","../src/schedules/schedule.ts","../src/schedules/table.ts","../src/schedules/scheduler.ts","../src/events/id.ts","../src/events/outbox.ts","../src/events/dispatcher.ts","../src/events/workflow.ts","../src/events/listener.ts","../src/events/hub.ts","../src/resource.ts","../src/contract.ts","../src/cors.ts","../src/response-hooks.ts","../src/dashboard.ts","../src/mcp.ts","../src/endpoints.ts","../src/plugin-app.ts","../src/socket-server.ts","../src/workflow-store.ts","../src/workflows.ts","../src/workflow-world.ts","../src/server.ts"],"sourcesContent":["import { Cause, Data, Effect } from \"effect\";\n\n/** The codes every action can raise, with their status and default message. The same as `@brickkit/core`. */\nexport const STANDARD_ERRORS = {\n BAD_REQUEST: { status: 400, message: \"Bad Request\" },\n UNAUTHORIZED: { status: 401, message: \"Unauthorized\" },\n FORBIDDEN: { status: 403, message: \"Forbidden\" },\n NOT_FOUND: { status: 404, message: \"Not Found\" },\n CONFLICT: { status: 409, message: \"Conflict\" },\n RATE_LIMITED: { status: 429, message: \"Too Many Requests\" },\n INTERNAL_SERVER_ERROR: { status: 500, message: \"Internal Server Error\" },\n} as const;\n\nexport type StandardErrorCode = keyof typeof STANDARD_ERRORS;\n\n/** A declared failure of an action: a `code`, an HTTP `status`, and optional `details`. */\nexport class BrickError extends Data.TaggedError(\"BrickError\")<{\n readonly code: string;\n readonly message: string;\n readonly status: number;\n readonly details?: unknown;\n /** The error this one stands for, kept for the log: core's error with its own `cause`. */\n readonly cause?: unknown;\n}> {}\n\n/** One reason an input or output failed its schema: a JSON pointer to the field, and a message that never carries the rejected value. */\nexport interface ValidationIssue {\n readonly path: string;\n readonly message: string;\n}\n\n/** The input (400) or output (500) of an action did not match its schema. */\nexport class ValidationError extends Data.TaggedError(\"ValidationError\")<{\n readonly message: string;\n readonly status: number;\n readonly errors: ReadonlyArray<ValidationIssue>;\n /** The error this one stands for, kept for the log. */\n readonly cause?: unknown;\n}> {\n readonly code = \"VALIDATION_FAILED\";\n}\n\n/** Two declarations claim one name or URL segment. */\nexport class DuplicateNameError extends Error {\n override readonly name = \"DuplicateNameError\";\n}\n\n/** An error as JSON: the body of a failed HTTP call, as `@brickkit/core`'s client decodes it. */\nexport interface WireError {\n name: string;\n code: string;\n message: string;\n status: number;\n details?: unknown;\n errors?: ValidationIssue[];\n}\n\n/** `WireError` plus the id of the request, the body of every failed HTTP call. */\nexport interface ErrorEnvelope extends WireError {\n requestId: string;\n}\n\n/** Where unexpected failures are logged, and the id of the request they are logged for. */\nexport interface FailureContext {\n readonly logger: { error: (...args: any[]) => void };\n readonly requestId?: string | undefined;\n}\n\ntype Failure = BrickError | ValidationError;\n\n/**\n * Whether `value` is an error of core's class `name`, or of a subclass: core's\n * `instanceof`, without importing core (a second copy of core has its own\n * classes). Core sets `name` in its constructors, which a minifier cannot\n * rename, so that settles it for an `Error`. A class name does not survive\n * minification, so the prototype chain is only the fallback for a subclass that\n * sets its own `name`.\n */\nconst inheritsFrom = (value: object, name: string): boolean => {\n if (value instanceof Error && value.name === name) return true;\n for (\n let at = Object.getPrototypeOf(value);\n at;\n at = Object.getPrototypeOf(at)\n )\n if (Object.hasOwn(at, \"constructor\") && at.constructor?.name === name)\n return true;\n return false;\n};\n\nconst isHttpStatus = (status: unknown): status is number =>\n Number.isInteger(status) &&\n (status as number) >= 400 &&\n (status as number) < 600;\n\nconst isIssue = (item: unknown): item is ValidationIssue & { type?: number } =>\n item !== null &&\n typeof item === \"object\" &&\n typeof (item as ValidationIssue).path === \"string\" &&\n typeof (item as ValidationIssue).message === \"string\";\n\n/** The `name` of the core error a failure stands for, as core answers the error's `name`. */\nconst names = new WeakMap<Failure, string>();\n\nfunction named<F extends Failure>(failure: F, core: object): F {\n const { name } = core as { name?: unknown };\n if (typeof name === \"string\") names.set(failure, name);\n return failure;\n}\n\n/**\n * The failure `value` stands for, or `undefined`. Besides this package's own\n * errors it takes an error of `@brickkit/core`, which core answers with its code,\n * status and details wherever it came from: an `ActionExecutionError` (or a\n * subclass of it) with a string `code` and `message` and a 4xx or 5xx `status`,\n * and a `ValidationError` with its `errors`. Core checks the class and nothing\n * else, so any other value that carries a `status` (an Elysia or third-party\n * error, a plain `Error`) is not one.\n */\nexport function asFailure(value: unknown): Failure | undefined {\n if (value instanceof BrickError || value instanceof ValidationError)\n return value;\n if (value === null || typeof value !== \"object\") return undefined;\n const { code, message, status, details, errors } = value as Record<\n string,\n unknown\n >;\n if (typeof message !== \"string\" || !isHttpStatus(status)) return undefined;\n if (inheritsFrom(value, \"ActionExecutionError\") && typeof code === \"string\")\n return named(\n new BrickError({ code, message, status, details, cause: value }),\n value,\n );\n if (\n inheritsFrom(value, \"ValidationError\") &&\n code === \"VALIDATION_FAILED\" &&\n Array.isArray(errors) &&\n errors.every(isIssue)\n )\n return named(\n new ValidationError({\n cause: value,\n message,\n status,\n errors: errors.map(({ path, message, type }) => ({\n path,\n message,\n ...(typeof type === \"number\" && { type }),\n })),\n }),\n value,\n );\n return undefined;\n}\n\n/** The first failure in `cause`, typed or a defect, that `asFailure` recognises. */\nexport function failureOfCause(\n cause: Cause.Cause<unknown>,\n): Failure | undefined {\n for (const reason of cause.reasons) {\n const failure = asFailure(\n Cause.isFailReason(reason)\n ? reason.error\n : Cause.isDieReason(reason)\n ? reason.defect\n : undefined,\n );\n if (failure) return failure;\n }\n return undefined;\n}\n\n/** The 500s `toFailure` built: named `InternalServerError`, as core names its own. */\nconst built = new WeakSet<Failure>();\n\n/** The 5xx failures already logged, so they are logged once. */\nconst logged = new WeakSet<Failure>();\n\n/**\n * A copy of `failure` with other `message` and `details`, which is the same\n * failure as far as its name and its logging go. The copy leaves out the\n * `cause`: it was logged with `failure`, and holds what the caller redacted.\n */\nexport function redactedCopy<F extends BrickError | ValidationError>(\n failure: F,\n { message, details }: { message: string; details: unknown },\n): F {\n // As core does, a validation failure's message is redacted and its issues are kept; the cause is left out, since it holds the secret.\n const copy = (\n failure instanceof ValidationError\n ? new ValidationError({\n message,\n status: failure.status,\n errors: failure.errors,\n })\n : new BrickError({\n code: (failure as BrickError).code,\n status: failure.status,\n message,\n details,\n })\n ) as F;\n const name = names.get(failure);\n if (name !== undefined) names.set(copy, name);\n if (built.has(failure)) built.add(copy);\n if (logged.has(failure)) logged.add(copy);\n return copy;\n}\n\n/**\n * `prefixed` stands for `failure` with a longer message. Core logs the error a nested action passes through\n * once, when it is answered, and the one it built after an unexpected throw twice, so only the first\n * carries its log over.\n */\nexport function prefixedFailure(\n failure: BrickError,\n prefixed: BrickError,\n): BrickError {\n if (logged.has(failure) && !built.has(failure)) logged.add(prefixed);\n return prefixed;\n}\n\n/** Logs a recognised failure with status 500 or more, as core does, once. */\nfunction logServerFailure(\n failure: Failure,\n cause: Cause.Cause<unknown>,\n { logger, requestId }: FailureContext,\n): void {\n if (failure.status < 500 || logged.has(failure)) return;\n logged.add(failure);\n logger.error(\"Server action error\", { requestId }, Cause.pretty(cause));\n}\n\n/** A failure as JSON. A failed output check (status 500) leaves out its `errors`, which describe internals. */\nexport function toWireError(error: Failure): WireError {\n if (error instanceof ValidationError)\n return {\n name: names.get(error) ?? \"ValidationError\",\n code: error.code,\n message: error.message,\n status: error.status,\n ...(error.status < 500 && { errors: [...error.errors] }),\n };\n return {\n name:\n names.get(error) ??\n (built.has(error) ? \"InternalServerError\" : \"ActionExecutionError\"),\n code: error.code,\n message: error.message,\n status: error.status,\n details: error.details,\n };\n}\n\n/**\n * The failure a cause stands for: a declared one, or a core error (see\n * `asFailure`), is kept; anything else (an unknown failure or a defect) is logged and becomes `INTERNAL_SERVER_ERROR`\n * (500), with the cause kept out of the result.\n */\nexport function toFailure(\n cause: Cause.Cause<unknown>,\n { logger, requestId }: FailureContext,\n): Failure {\n const known = failureOfCause(cause);\n if (known) {\n // Logged here, with the caller's logger, which may redact; `toErrorResponse` has none.\n logServerFailure(known, cause, { logger, requestId });\n return known;\n }\n logger.error(\"Unexpected action error\", { requestId }, Cause.pretty(cause));\n const failure = new BrickError({\n ...STANDARD_ERRORS.INTERNAL_SERVER_ERROR,\n code: \"INTERNAL_SERVER_ERROR\",\n // For `brick({ onError })`; the answer never carries it.\n cause: Cause.squash(cause),\n });\n built.add(failure);\n logged.add(failure);\n return failure;\n}\n\n/** Turns whatever fails in `self` into a declared failure, except interruption. */\nexport const normalizeFailures =\n (context: FailureContext) =>\n <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, Failure, R> =>\n Effect.catchCause(self, (cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause as Cause.Cause<never>)\n : Effect.fail(toFailure(cause, context)),\n );\n\n/**\n * The JSON body of a failed HTTP call. Declared failures and validation errors\n * keep 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 */\nexport function toErrorResponse(\n cause: Cause.Cause<unknown>,\n context: FailureContext,\n): ErrorEnvelope {\n const known = failureOfCause(cause);\n if (known) logServerFailure(known, cause, context);\n const failure = known ?? toFailure(cause, context);\n return { ...toWireError(failure), requestId: context.requestId ?? \"\" };\n}\n","import type { HttpMethod } from \"./action\";\n\n/** Where a plugin mounted one of its actions. */\nexport interface PluginRouteBinding {\n /** The plugin's name (`@brickkit/crud`). Kept apart from the action's public name. */\n plugin: string;\n service: string;\n resource?: string | undefined;\n path: string;\n method: HttpMethod;\n scope: \"app\" | \"service\" | \"resource\";\n enabled: boolean;\n /** The action's path in the plugin's returned API, for the typed client. */\n clientPath?: string[];\n}\n\n/** How an action is protected: nothing checks the caller, `authorize` does, or it also limits the rows. */\nexport type ActionAccessPolicy = \"public\" | \"authorized\" | \"scoped\";\n\n/** What `getActionAccess` says of an action. */\nexport interface ActionAccessInfo {\n hasAuthorize: boolean;\n hasScope: boolean;\n policy: ActionAccessPolicy;\n}\n\n/** What a resource knows of an action it owns (`resource.action`, `resource.command`). */\nexport interface ResourceActionInfo {\n /** The resource's name. */\n readonly resource: string;\n /** The name the action was declared with, without the resource: `ship`. */\n readonly name: string;\n /** Whether it works on one record (`/:id/<name>`). */\n readonly record: boolean;\n /** Which rows a record action may load, when its resource has no `crud`. */\n readonly access?: unknown;\n}\n\n/** What Brick knows about an action besides its config. */\nexport interface ActionMeta {\n /** Set when a resource declared the action with `resource.action` or `resource.command`. */\n resourceAction?: ResourceActionInfo;\n /** Set when a plugin registered the action. */\n route?: PluginRouteBinding;\n /** How the action is protected, when a plugin checks access inside `execute`. */\n access?: ActionAccessInfo;\n /** How the audit log records the action, when a plugin says so with `setActionAudit`. */\n audit?: \"inline\" | \"none\";\n /** The deps of the plugin install that created the action, and when they were bound. */\n deps?: { values: Readonly<Record<string, unknown>>; at: number };\n}\n\n/** The slot of an action's `ActionMeta`. Process-global, so a second copy of this package reads what the first wrote. */\nexport const ACTION_META: unique symbol = Symbol.for(\n \"brickkit.effect.action.meta\",\n);\n\n/** An action's metadata, created empty on first use. */\nexport function actionMeta(action: object): ActionMeta {\n return ((action as { [ACTION_META]?: ActionMeta })[ACTION_META] ??= {});\n}\n","// Names Brick writes into traces and onto globalThis, read by the CLI and its\n// dashboard page. Browser-safe: constants only.\n\nexport const SPAN = {\n /** `action <service>.<action>` */\n actionPrefix: \"action \",\n /** `rpc <service>.<action>` */\n rpcPrefix: \"rpc \",\n /** `socket <service>.<name>`: a raw socket connection, from upgrade to close. */\n socketPrefix: \"socket \",\n exceptionEvent: \"exception\",\n /** The span event a `ctx.logger` line becomes. */\n logEvent: \"log\",\n} as const;\n\nexport const ATTR = {\n httpMethod: \"http.request.method\",\n httpRoute: \"http.route\",\n httpStatus: \"http.response.status_code\",\n urlPath: \"url.path\",\n /** An outbound request's scheme, host and path. Never the query, credentials, headers or body. */\n urlFull: \"url.full\",\n serverAddress: \"server.address\",\n service: \"brick.service\",\n action: \"brick.action\",\n /** A webhook delivery: the webhook's name, its event id and what became of it. Never the body or the signature. */\n webhook: \"brick.webhook\",\n webhookEventId: \"brick.webhook.event_id\",\n webhookOutcome: \"brick.webhook.outcome\",\n /** A schedule run: the schedule's name, what started it, which try, its due time and how it ended. */\n schedule: \"brick.schedule\",\n scheduleTrigger: \"brick.schedule.trigger\",\n scheduleAttempt: \"brick.schedule.attempt\",\n scheduleSlot: \"brick.schedule.slot\",\n scheduleOutcome: \"brick.schedule.outcome\",\n /** A raw socket connection: its route name, id, frames and bytes received, and close code. */\n socketName: \"brick.socket.name\",\n socketId: \"brick.socket.id\",\n socketMessages: \"brick.socket.messages\",\n socketBytes: \"brick.socket.bytes\",\n socketCloseCode: \"brick.socket.close_code\",\n traceId: \"brick.trace_id\",\n errorCode: \"brick.error.code\",\n errorMessage: \"brick.error.message\",\n errorStatus: \"brick.error.status\",\n logsDropped: \"brick.logs.dropped\",\n dbStatement: \"db.statement\",\n dbSystem: \"db.system\",\n dbOperation: \"db.operation\",\n exceptionMessage: \"exception.message\",\n exceptionStack: \"exception.stacktrace\",\n logLevel: \"log.level\",\n logMessage: \"log.message\",\n} as const;\n\n/**\n * `Symbol.for` names shared through globalThis, because the CLI and the app may\n * each hold their own copy of Brick.\n */\nexport const GLOBAL_SYMBOL = {\n /** Set by the CLI while a dashboard collects logs. */\n logsCapture: \"brickkit.logs.capture\",\n /** Brick's function that records a log line on the running span. */\n logsRecord: \"brickkit.logs.record\",\n /** The set of running event hubs, so the CLI can stop them all. */\n eventsStarted: \"brickkit.events.started\",\n /** The key the dashboard signs `/app/*` identities with. */\n dashboardKey: \"brickkit.dashboard.key\",\n /** The in-memory store of finished spans. Under this package's own namespace: core has no such key. */\n spans: \"brickkit.effect.telemetry.spans\",\n /**\n * A `Set` of functions that the CLI fills before the app loads: each gets the\n * start and end records of every span, as `SpanStore.subscribe` does. Under\n * this package's namespace, so a copy of core never reads it.\n */\n spanListeners: \"brickkit.effect.telemetry.listeners\",\n} as const;\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 { AsyncLocalStorage } from \"node:async_hooks\";\nimport { formatWithOptions } from \"node:util\";\nimport {\n Cause,\n Context,\n Effect,\n Exit,\n Layer,\n Option,\n Result,\n Tracer,\n} from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport { OtlpSerialization, OtlpTracer } from \"effect/observability\";\nimport { Statement } from \"effect/sql\";\nimport { failureOfCause } from \"./errors\";\nimport { ATTR, GLOBAL_SYMBOL, SPAN } from \"./telemetry-names\";\n\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STATEMENT_LENGTH = 2000;\nconst MAX_LOG_LENGTH = 4000;\nconst MAX_LOGS_PER_SPAN = 100;\nconst MAX_FINISHED = 10_000;\nconst SQL_SPAN = \"brick.sql\";\nconst SQL_TEXT = \"db.query.text\";\nconst SQL_SYSTEM = \"db.system.name\";\nconst SQL_METHOD = \"effect.sql.method\";\nconst FETCH_INSTRUMENTED = Symbol.for(\"brickkit.effect.telemetry.fetch\");\n\nexport type SpanAttributes = Record<string, unknown>;\n\nexport interface SpanEventRecord {\n name: string;\n timeMs: number;\n attributes: SpanAttributes;\n}\n\n/** A span began. The dashboard shows it as a request in flight. */\nexport interface SpanStartRecord {\n phase: \"start\";\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n attributes: SpanAttributes;\n}\n\n/** A span ended, with everything the dashboard shows of it. */\nexport interface SpanEndRecord {\n phase: \"end\";\n traceId: string;\n spanId: string;\n name: string;\n endMs: number;\n status: \"unset\" | \"ok\" | \"error\";\n statusMessage?: string;\n attributes: SpanAttributes;\n events: SpanEventRecord[];\n}\n\n/** What the dashboard reads: the records of the CLI's own tracer, in the same shape. */\nexport type TelemetryRecord = SpanStartRecord | SpanEndRecord;\n\n/** A span that ended, whole. */\nexport interface FinishedSpan {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n kind: Tracer.SpanKind;\n startMs: number;\n endMs: number;\n status: \"unset\" | \"error\";\n statusMessage?: string;\n attributes: SpanAttributes;\n events: SpanEventRecord[];\n}\n\n/**\n * The spans of this process, in memory: the finished ones (the newest 10,000)\n * for whoever reads them, and a feed of start and end records for a dashboard.\n */\nexport class SpanStore {\n readonly #finished: FinishedSpan[] = [];\n readonly #listeners = new Set<(records: TelemetryRecord[]) => void>();\n\n /** Our own subscribers, and those a CLI registered by name before this package loaded. */\n #audience(): Iterable<(records: TelemetryRecord[]) => void> {\n const shared = (globalThis as Record<symbol, unknown>)[\n Symbol.for(GLOBAL_SYMBOL.spanListeners)\n ] as Set<(records: TelemetryRecord[]) => void> | undefined;\n return shared?.size ? [...this.#listeners, ...shared] : this.#listeners;\n }\n\n /** The finished spans, oldest first. */\n spans(): readonly FinishedSpan[] {\n return this.#finished;\n }\n\n clear(): void {\n this.#finished.length = 0;\n }\n\n /** Call `listener` with each record as it happens. Returns the function that stops it. */\n subscribe(listener: (records: TelemetryRecord[]) => void): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n /** @internal */\n start(record: SpanStartRecord): void {\n for (const listener of this.#audience()) listener([record]);\n }\n\n /** @internal */\n finish(span: FinishedSpan): void {\n this.#finished.push(span);\n if (this.#finished.length > MAX_FINISHED) this.#finished.shift();\n const audience = this.#audience();\n if (audience === this.#listeners && this.#listeners.size === 0) return;\n const record: SpanEndRecord = {\n phase: \"end\",\n traceId: span.traceId,\n spanId: span.spanId,\n name: span.name,\n endMs: span.endMs,\n status: span.status,\n ...(span.statusMessage === undefined\n ? {}\n : { statusMessage: span.statusMessage }),\n attributes: span.attributes,\n events: span.events,\n };\n for (const listener of audience) listener([record]);\n }\n}\n\n/** Shared through `globalThis`, because the CLI and the app may each hold their own copy of Brick. */\nexport const spanStore: SpanStore = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(GLOBAL_SYMBOL.spans)\n] ??= new SpanStore()) as SpanStore;\n\nconst truncate = (text: string, limit = MAX_TEXT_LENGTH) =>\n text.length > limit ? `${text.slice(0, limit)}…` : text;\n\nconst toMs = (nanos: bigint) => Number(nanos) / 1e6;\nconst nowNanos = () =>\n BigInt(Math.round((performance.timeOrigin + performance.now()) * 1e6));\n\nconst messageOf = (error: unknown) =>\n error instanceof Error ? error.message : String(error);\n\ntype SpanOptions = Parameters<Tracer.Tracer[\"span\"]>[0];\n\n/** A span of the app's tracer: records what the dashboard reads when it starts and ends, and hands it to the OTLP tracer when there is one. */\nclass BrickSpan extends Tracer.NativeSpan {\n readonly #sql: boolean;\n readonly #options: SpanOptions;\n readonly #otlp: Tracer.Tracer | undefined;\n #started = false;\n #failure: { message: string } | undefined;\n #logs = 0;\n\n constructor(options: SpanOptions, otlp?: Tracer.Tracer) {\n super(options);\n this.#options = options;\n this.#otlp = otlp;\n this.#sql = options.name === SQL_SPAN;\n queueMicrotask(() => this.#begin());\n }\n\n #begin(): void {\n if (this.#started) return;\n this.#started = true;\n const parent = Option.getOrUndefined(this.parent);\n spanStore.start({\n phase: \"start\",\n traceId: this.traceId,\n spanId: this.spanId,\n ...(parent && { parentSpanId: parent.spanId }),\n name: this.name,\n startMs: toMs(this.status.startTime),\n attributes: this.#snapshot(),\n });\n }\n\n #snapshot(): SpanAttributes {\n const attributes: SpanAttributes = {};\n for (const [key, value] of this.attributes)\n attributes[key] =\n typeof value === \"string\" ? truncate(value, MAX_LOG_LENGTH) : value;\n return attributes;\n }\n\n override attribute(key: string, value: unknown): void {\n if (this.status._tag === \"Ended\") return;\n if (this.#sql) {\n if (key === SQL_METHOD) return;\n if (key === SQL_SYSTEM) return super.attribute(ATTR.dbSystem, value);\n if (key === SQL_TEXT) {\n const sql = String(value);\n const operation = sql.trim().split(/\\s+/, 1)[0]?.toUpperCase() || \"SQL\";\n Object.assign(this, { name: `SQL ${operation}` });\n super.attribute(ATTR.dbOperation, operation);\n return super.attribute(\n ATTR.dbStatement,\n truncate(sql, MAX_STATEMENT_LENGTH),\n );\n }\n }\n super.attribute(key, value);\n }\n\n /** Add a `ctx.logger` line to the span, up to 100 of them. */\n log(level: string, message: string): void {\n if (this.status._tag === \"Ended\") return;\n if (++this.#logs > MAX_LOGS_PER_SPAN)\n return super.attribute(ATTR.logsDropped, this.#logs - MAX_LOGS_PER_SPAN);\n this.event(SPAN.logEvent, nowNanos(), {\n [ATTR.logLevel]: level,\n [ATTR.logMessage]: message,\n });\n }\n\n #fail(error: unknown, endTime: bigint): void {\n const named = error instanceof Error;\n this.event(SPAN.exceptionEvent, endTime, {\n \"exception.type\": named ? error.name : typeof error,\n [ATTR.exceptionMessage]: messageOf(error),\n ...(named && error.stack ? { [ATTR.exceptionStack]: error.stack } : {}),\n });\n this.#failure = { message: truncate(messageOf(error)) };\n }\n\n #record(cause: Cause.Cause<unknown>, endTime: bigint): void {\n const found = Cause.findError(cause);\n const error = failureOfCause(cause);\n if (error) {\n super.attribute(ATTR.errorCode, error.code);\n super.attribute(ATTR.errorStatus, error.status);\n super.attribute(ATTR.errorMessage, truncate(error.message));\n if (error.status >= 500) this.#fail(error, endTime);\n return;\n }\n const defect = Cause.findDefect(cause);\n const thrown = Result.isSuccess(found)\n ? found.success\n : Result.isSuccess(defect)\n ? defect.success\n : Cause.squash(cause);\n if (this.attributes.has(ATTR.action)) {\n super.attribute(ATTR.errorCode, \"INTERNAL_SERVER_ERROR\");\n super.attribute(ATTR.errorStatus, 500);\n super.attribute(ATTR.errorMessage, \"Internal Server Error\");\n }\n this.#fail(thrown, endTime);\n }\n\n override end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n if (this.status._tag === \"Ended\") return;\n this.#begin();\n if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause))\n this.#record(exit.cause, endTime);\n const http = this.attributes.get(ATTR.httpStatus);\n if (\n typeof http === \"number\" &&\n http >= (this.kind === \"client\" ? 400 : 500)\n )\n this.#failure ??= { message: `HTTP ${http}` };\n super.end(endTime, exit);\n const parent = Option.getOrUndefined(this.parent);\n spanStore.finish({\n traceId: this.traceId,\n spanId: this.spanId,\n ...(parent && { parentSpanId: parent.spanId }),\n name: this.name,\n kind: this.kind,\n startMs: toMs(this.status.startTime),\n endMs: toMs(endTime),\n status: this.#failure ? \"error\" : \"unset\",\n ...(this.#failure && { statusMessage: this.#failure.message }),\n attributes: this.#snapshot(),\n events: this.events.map(([name, time, attributes]) => ({\n name,\n timeMs: toMs(time),\n attributes,\n })),\n });\n this.#export(endTime, exit);\n }\n\n /**\n * The OTLP tracer makes its span at the end, from this one's final state, and\n * under its ids, so a trace the exporter sends has the shape the store has.\n */\n #export(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n if (!this.#otlp) return;\n const span = this.#otlp.span({ ...this.#options, name: this.name });\n if (!(span instanceof Tracer.NativeSpan)) {\n // The exporter's span is its own class, with the same public fields.\n Object.assign(span, { _traceId: this.traceId, _spanId: this.spanId });\n } else {\n span._traceId = this.traceId;\n span._spanId = this.spanId;\n }\n for (const [key, value] of this.attributes) span.attribute(key, value);\n for (const [name, time, attributes] of this.events)\n span.event(name, time, attributes);\n span.end(endTime, exit);\n }\n}\n\n/**\n * The span the code running now belongs to. Effect runs each step of a fiber\n * inside it, so a promise an action starts keeps it across its `await`s.\n */\nconst running = new AsyncLocalStorage<BrickSpan>();\n\n/**\n * The tracer of an app with `telemetry`. A statement outside any span is not\n * recorded, as core records none outside a request.\n */\nconst makeBrickTracer = (otlp?: Tracer.Tracer): Tracer.Tracer =>\n Tracer.make({\n span: (options) =>\n options.name === SQL_SPAN && Option.isNone(options.parent)\n ? new Tracer.NativeSpan(options)\n : new BrickSpan(options, otlp),\n context: (primitive, fiber) => {\n const span = fiber.cache.span;\n return span instanceof BrickSpan\n ? running.run(span, () => primitive[\"~effect/Effect/evaluate\"](fiber))\n : primitive[\"~effect/Effect/evaluate\"](fiber);\n },\n });\n\nexport const brickTracer: Tracer.Tracer = makeBrickTracer();\n\n/** Provided when the app has `telemetry`: what the stages check before they add a span. */\nexport class Telemetry extends Context.Service<Telemetry, SpanStore>()(\n \"@brickkit/effect/Telemetry\",\n) {}\n\n/**\n * Turns the app's tracing on: its tracer, the span store, and SQL statements\n * named `SQL <OPERATION>` with `db.system`, `db.operation` and `db.statement`.\n */\nexport const telemetryLayer: Layer.Layer<Telemetry> = Layer.mergeAll(\n Layer.succeed(Telemetry)(spanStore),\n Layer.succeed(Tracer.Tracer)(brickTracer),\n Layer.succeed(Statement.SpanNameGenerator)(() => SQL_SPAN),\n) as Layer.Layer<Telemetry>;\n\n/** Where `brick({ telemetry: { otlp } })` sends spans, over OTLP/HTTP as JSON. */\nexport interface OtlpOptions {\n /** The traces endpoint, such as `http://localhost:4318/v1/traces`. */\n url: string;\n /** Request headers, such as an API key. */\n headers?: Record<string, string>;\n /** Names the service in the backend. */\n resource?: {\n serviceName?: string;\n serviceVersion?: string;\n attributes?: Record<string, unknown>;\n };\n /** How often a batch is sent, as a Duration (default `\"5 seconds\"`). */\n exportInterval?: Parameters<typeof OtlpTracer.layer>[0][\"exportInterval\"];\n}\n\n/** The `telemetry` option's object form. */\nexport interface TelemetryOptions {\n /**\n * Also export spans over OTLP/HTTP (JSON). An object names the endpoint; `true`\n * reads the standard `OTEL_EXPORTER_OTLP_ENDPOINT` (or `_TRACES_ENDPOINT`),\n * `OTEL_EXPORTER_OTLP_HEADERS` and `OTEL_SDK_DISABLED`, and exports only when\n * `OTEL_TRACES_EXPORTER=otlp`, an endpoint and `OTEL_SERVICE_NAME` are all\n * set. Spans still go to Brick's store too.\n */\n otlp?: true | OtlpOptions;\n}\n\n/**\n * `telemetryLayer`, and the OTLP export when `otlp` asks for it. The exporter\n * sends batches in the background and flushes them when the app stops.\n */\nexport const telemetryLayerOf = (\n otlp?: TelemetryOptions[\"otlp\"],\n): Layer.Layer<Telemetry> => {\n if (!otlp) return telemetryLayer;\n const exporter = (\n otlp === true\n ? OtlpTracer.layerFromConfig()\n : OtlpTracer.layer({\n url: otlp.url,\n ...(otlp.headers && { headers: otlp.headers }),\n ...(otlp.resource && { resource: otlp.resource }),\n ...(otlp.exportInterval && { exportInterval: otlp.exportInterval }),\n })\n ).pipe(\n Layer.provide(OtlpSerialization.layerJson),\n Layer.provide(FetchHttpClient.layer),\n );\n return Layer.effectContext(\n Effect.gen(function* () {\n // The exporter's layer holds the OTLP tracer too, though it is typed as the flusher.\n const built = yield* Layer.build(exporter);\n const tracer = Context.getOption(\n built as unknown as Context.Context<Tracer.Tracer>,\n Tracer.Tracer,\n );\n return Context.make(Telemetry, spanStore).pipe(\n Context.add(\n Tracer.Tracer,\n makeBrickTracer(Option.getOrUndefined(tracer)),\n ),\n Context.add(Statement.SpanNameGenerator, () => SQL_SPAN),\n );\n }),\n ) as unknown as Layer.Layer<Telemetry>;\n};\n\nconst TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\n/** The caller's span, from a W3C `traceparent` header. */\nfunction externalParent(\n header: string | null,\n): Tracer.ExternalSpan | undefined {\n const match = header ? TRACEPARENT.exec(header) : null;\n if (!match || /^0+$/.test(match[1]!) || /^0+$/.test(match[2]!))\n return undefined;\n return Tracer.externalSpan({\n traceId: match[1]!,\n spanId: match[2]!,\n sampled: (parseInt(match[3]!, 16) & 1) === 1,\n });\n}\n\n/** The `traceparent` a response carries, so the caller can continue the trace. */\nexport const traceparentOf = (span: Tracer.Span) =>\n `00-${span.traceId}-${span.spanId}-${span.sampled ? \"01\" : \"00\"}`;\n\n/**\n * Run `body` inside a server span for one HTTP request. The span continues the\n * caller's trace when a W3C `traceparent` arrives. `body` gets the span, so it\n * can answer with the trace id and record the response.\n */\nexport function traceRequest<A, E, R>(\n request: Request,\n method: string,\n route: string,\n body: (span: Tracer.Span) => Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> {\n const parent = externalParent(request.headers.get(\"traceparent\"));\n return Effect.useSpan(\n `${method} ${route}`,\n {\n kind: \"server\",\n ...(parent && { parent }),\n attributes: {\n [ATTR.httpMethod]: method,\n [ATTR.httpRoute]: route,\n [ATTR.urlPath]: new URL(request.url).pathname,\n },\n },\n (span) =>\n body(span).pipe(\n Effect.withParentSpan(span, { captureStackTrace: false }),\n ),\n );\n}\n\n/** One socket connection's span: from upgrade to close, the parent of what each callback runs. */\nexport interface SocketSpan {\n readonly span: Tracer.Span;\n /** Links a trace that only arrives in a frame; a started span cannot be re-parented. */\n link(traceparent: string): void;\n /** Ends the span with `attributes`; a `failure` marks it as an error. */\n end(attributes: SpanAttributes, failure?: unknown): void;\n}\n\n/**\n * Start `name` as a server span for a WebSocket upgrade, continuing the\n * caller's trace when a W3C `traceparent` arrives. It stays open until `end`,\n * so it is made by hand: `Effect.useSpan` would end it with its first callback.\n */\nexport function startSocketSpan(\n name: string,\n request: Request,\n attributes: SpanAttributes,\n // The app's tracer, which exports over OTLP when the app asks for it.\n tracer: Tracer.Tracer = brickTracer,\n): SocketSpan {\n const parent = externalParent(request.headers.get(\"traceparent\"));\n const span = tracer.span({\n name,\n parent: parent ? Option.some(parent) : Option.none(),\n annotations: Context.empty(),\n links: [],\n startTime: nowNanos(),\n kind: \"server\",\n root: !parent,\n sampled: parent?.sampled ?? true,\n });\n const record = (values: SpanAttributes) => {\n for (const [key, value] of Object.entries(values))\n span.attribute(key, value);\n };\n record({\n [ATTR.httpMethod]: \"GET\",\n [ATTR.urlPath]: new URL(request.url).pathname,\n ...attributes,\n });\n return {\n span,\n link(traceparent) {\n const linked = externalParent(traceparent);\n if (linked) span.addLinks([{ span: linked, attributes: {} }]);\n },\n end(final, failure) {\n record(final);\n span.end(\n nowNanos(),\n failure === undefined ? Exit.void : Exit.die(failure),\n );\n },\n };\n}\n\n/**\n * Wrap a raw route handler so each of its requests gets a server span in\n * Brick's span store (`spanStore`, which `brick dev` and the dashboard read).\n * For routes you serve yourself around `app.fetch`: they are outside actions\n * and endpoints, so `brick({ telemetry })` does not reach them. The span\n * continues the caller's `traceparent`.\n *\n * @param route - The route as it should read in the trace, such as `/raw/:id`.\n * @example\n * Bun.serve({ routes: { \"/hook\": traceRoute(\"/hook\", (request) => new Response(\"ok\")) } });\n */\nexport function traceRoute(\n route: string,\n handler: (request: Request) => Response | Promise<Response>,\n): (request: Request) => Promise<Response> {\n return async (request) => {\n const exit = await Effect.runPromiseExit(\n traceRequest(request, request.method, route, (span) =>\n Effect.tryPromise({\n try: async () => handler(request),\n catch: (error) => error,\n }).pipe(\n Effect.tap((response) =>\n Effect.sync(() =>\n recordResponse(\n span,\n response,\n request.headers.get(\"x-trace-id\") ?? span.traceId,\n ),\n ),\n ),\n ),\n ).pipe(Effect.provide(telemetryLayer)),\n );\n // The handler's own error, not Effect's wrapper of it.\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n };\n}\n\n/**\n * Record how a request ended: its status and the trace id the caller can quote.\n * A server fault (5xx) also keeps its code, as the dashboard's errors view lists it.\n */\nexport function recordResponse(\n span: Tracer.Span,\n response: { status: number },\n traceId: string,\n failure?: { code: string; status: number; message: string },\n): void {\n span.attribute(ATTR.httpStatus, response.status);\n span.attribute(ATTR.traceId, traceId);\n if (!failure) return;\n span.attribute(ATTR.errorCode, failure.code);\n span.attribute(ATTR.errorStatus, failure.status);\n span.attribute(ATTR.errorMessage, truncate(failure.message));\n}\n\n/**\n * Wrap a call of an action in a span. Over HTTP (`wire`) it is `action\n * <service>.<action>`. In-process it is `rpc <service>.<action>`, and only\n * inside a call that is already traced. Without `telemetry` it adds nothing.\n */\nexport function traceAction<A, E, R>(\n service: string,\n action: string,\n wire: boolean,\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> {\n return Effect.flatMap(\n Effect.all([\n Effect.serviceOption(Telemetry),\n Effect.withFiber((fiber) =>\n Effect.succeed(fiber.cache.span !== undefined),\n ),\n ]),\n ([telemetry, traced]) =>\n Option.isNone(telemetry) || (!wire && !traced)\n ? effect\n : Effect.withSpan(\n `${wire ? SPAN.actionPrefix : SPAN.rpcPrefix}${service}.${action}`,\n {\n attributes: { [ATTR.service]: service, [ATTR.action]: action },\n },\n { captureStackTrace: false },\n )(effect),\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 started the tick, such as the request that triggered it.\n */\nexport function traceScheduleRun<A, E, R>(\n run: { schedule: string; trigger: string; attempt: number; slot: string },\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> {\n return Effect.useSpan(\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 effect.pipe(\n Effect.onExit((exit) =>\n Effect.sync(() =>\n span.attribute(\n ATTR.scheduleOutcome,\n Exit.isFailure(exit) ? \"failed\" : \"succeeded\",\n ),\n ),\n ),\n Effect.withParentSpan(span, { captureStackTrace: false }),\n ),\n );\n}\n\n/** Note on the running span which webhook delivered, its event id and what became of it. Never the body or the signature. */\nexport const recordWebhook = (\n name: string,\n eventId: string | undefined,\n outcome: string,\n) =>\n Effect.annotateCurrentSpan({\n [ATTR.webhook]: name,\n ...(eventId === undefined ? {} : { [ATTR.webhookEventId]: eventId }),\n [ATTR.webhookOutcome]: outcome,\n });\n\n/**\n * Count outbound requests made under a traced call as client spans, with the\n * method, host, path and status: never the query, credentials, headers or body.\n * Calling it again does nothing.\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 globalThis.fetch = 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 const parent = running.getStore();\n if (!parent) 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 = brickTracer.span({\n name: truncate(`${method} ${url.host}${url.pathname}`),\n parent: Option.some(parent),\n annotations: Context.empty(),\n links: [],\n startTime: nowNanos(),\n kind: \"client\",\n root: false,\n sampled: true,\n });\n span.attribute(ATTR.httpMethod, method);\n span.attribute(ATTR.urlFull, truncate(`${url.origin}${url.pathname}`));\n span.attribute(ATTR.serverAddress, url.hostname);\n const fail = (error: unknown) => {\n span.end(nowNanos(), Exit.die(error));\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.attribute(ATTR.httpStatus, response.status);\n span.end(nowNanos(), Exit.void);\n return response;\n }, fail);\n },\n });\n}\n\n// ANSI colors and titles, which Better Auth and the like print and a web page shows as stray characters.\n// oxlint-disable no-control-regex\nconst ANSI =\n /\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\))/g;\n// oxlint-enable no-control-regex\n\nconst render = (args: unknown[]) => {\n const text = formatWithOptions(\n { depth: 3, breakLength: 120, maxArrayLength: 50, maxStringLength: 1000 },\n ...args,\n ).replace(ANSI, \"\");\n return text.length > MAX_LOG_LENGTH\n ? `${text.slice(0, MAX_LOG_LENGTH)}…`\n : text;\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. Only a dashboard\n * collecting logs turns it on (the CLI sets `GLOBAL_SYMBOL.logsCapture`).\n */\nexport function recordLog(level: string, args: unknown[]): boolean {\n if (\n (globalThis as Record<symbol, unknown>)[\n Symbol.for(GLOBAL_SYMBOL.logsCapture)\n ] !== true\n )\n return false;\n const span = running.getStore();\n if (!span) return false;\n span.log(level, render(args));\n return true;\n}\n\n// The CLI's console capture calls this by name; @brickkit/core may have set one first, so both record.\nconst LOGS_RECORD = Symbol.for(GLOBAL_SYMBOL.logsRecord);\nconst recordBefore = (globalThis as Record<symbol, unknown>)[LOGS_RECORD] as\n | ((level: string, args: unknown[]) => boolean)\n | undefined;\n(globalThis as Record<symbol, unknown>)[LOGS_RECORD] = (\n level: string,\n args: unknown[],\n) => recordLog(level, args) || recordBefore?.(level, args) === true;\n","import {\n dashboardIdentity,\n type DashboardIdentity,\n} from \"./dashboard-identity\";\nimport { recordLog } from \"./telemetry\";\n\n/** The logger of an action's `ctx`. */\nexport interface Logger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/**\n * A logger that prints to the console, each line starting with `[LEVEL]`. While\n * a dashboard collects logs, a line logged in a traced call becomes an event on\n * its span, and is not printed.\n */\nexport function createLogger(): Logger {\n const level =\n (name: keyof Logger, print: (...args: any[]) => void) =>\n (...args: any[]) => {\n if (!recordLog(name, args)) print(`[${name.toUpperCase()}]`, ...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 fields every action's `ctx` has. */\nexport interface BaseContext {\n request: Request;\n logger: Logger;\n traceId: string;\n requestId: string;\n /** The name of the service that called this one through `useService(service, { from })`. With `from`, a `caller` in the call's own context is ignored. In-process code that calls `action.run(input, { caller })` or `useService` without `from` sets it freely, as in core: an HTTP request never does, so trust it only for calls from your own code. */\n caller?: string;\n /** Set when the request came through the dashboard's `/app/*` proxy, signed by the dashboard: `user` is who `dashboard.auth.authorize` let in. */\n dashboard?: DashboardIdentity;\n}\n\n/**\n * What a caller of `action.run` may carry into the call's `ctx`. `deps` replaces\n * some of the service's own for this call, such as a fake in a test.\n */\nexport type CallContext = Partial<BaseContext> & {\n user?: unknown;\n deps?: Readonly<Record<string, unknown>>;\n};\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n/** What `ctx.logger` is when the caller gives none. */\nexport const defaultLogger = createLogger();\nconst newId = (kind: \"tr\" | \"req\") => `${kind}_${crypto.randomUUID()}`;\n\n/**\n * The caller's `x-trace-id` and `x-request-id` headers, else fresh ids (the\n * trace id of the request's span, when it has one). Both are echoed on the response.\n */\nexport function requestIds(\n headers: Headers,\n spanTraceId?: string,\n): {\n traceId: string;\n requestId: string;\n} {\n return {\n traceId: headers.get(\"x-trace-id\") || spanTraceId || newId(\"tr\"),\n requestId: headers.get(\"x-request-id\") || newId(\"req\"),\n };\n}\n\n/** The framework fields of a context: what the caller gave, the rest defaulted. */\nexport function baseContext(fields: CallContext = {}): BaseContext {\n const request = fields.request ?? DEFAULT_REQUEST;\n const dashboard = fields.dashboard ?? dashboardIdentity(request);\n return {\n request,\n logger: fields.logger ?? defaultLogger,\n traceId: fields.traceId ?? newId(\"tr\"),\n requestId: fields.requestId ?? newId(\"req\"),\n ...(fields.caller !== undefined && { caller: fields.caller }),\n ...(dashboard && { dashboard }),\n };\n}\n","/** Who a call comes from, as the audit log and `per: \"actor\"` rate limits see the service's `identity`. */\nexport interface Actor {\n /** Who: the rate-limit key and the audit actor. */\n readonly id: string;\n /** A display name for the audit log. */\n readonly label?: string;\n /** Which tenant: recorded in the audit log. */\n readonly tenant?: string;\n}\n\n/**\n * The actor of `user`, the value of the service's `identity`: `null` for no\n * user.\n *\n * @throws When the user is not an object with a non-empty string `id`, and optional string `label` and `tenant`.\n */\nexport function actorOf(service: string, user: unknown): Actor | null {\n if (user === null || user === undefined) return null;\n const { id, label, tenant } = user as Partial<Actor>;\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, or null, to rate limit per \"actor\" or record an audit log`,\n );\n return {\n id,\n ...(label !== undefined && { label }),\n ...(tenant !== undefined && { tenant }),\n };\n}\n","import { inArray } from \"drizzle-orm\";\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 { Effect } from \"effect\";\nimport type { Stage } from \"./action\";\nimport { actorOf } from \"./actor\";\nimport type { AnyDatabaseHandle } from \"./db\";\n\nconst AUDIT = Symbol.for(\"brickkit.effect.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 action that is\n * not a `GET`. Brick only ever inserts into it. It has the columns of\n * `@brickkit/core`'s, so a migrating app keeps its log.\n *\n * Brick does not create tables for you: put this in the database's tables and\n * your migration tool (such as drizzle-kit) creates it. The service must\n * declare an `identity`: that is where the actor comes from, its `id`, and\n * optional `label` and `tenant`.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_audit`.\n * @example\n * export const auditLog = auditTable(\"postgres\");\n * export const database = defineDatabase({ tables: { orders, auditLog }, postgres: url });\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\n/** The audit table among the tables of a database. */\nexport const auditTableOf = (\n database: AnyDatabaseHandle | undefined,\n): AuditTable | undefined =>\n database && Object.values(database.tables).find(isAuditTable);\n\n/** What an action says of its audit row. `false` leaves the action out. */\nexport interface AuditOptions<TInput = any, TOutput = any> {\n /** Which kind of record the action changes. */\n readonly resource?: string;\n /** Which record: its id, as a string or number; anything else is stored as JSON. */\n readonly record?: (args: { input: TInput; result: TOutput }) => unknown;\n}\n\n/**\n * Marks the `audit` option of an action that writes its own row, in its own\n * transaction, through `recordInline`: what CRUD and commands do. The stage\n * then adds no row of its own.\n */\nconst INLINE = Symbol.for(\"brickkit.effect.audit.inline\");\n\n/** The `audit` option of an action that records itself inline, for `resource`. */\nexport const inlineAuditOptions = (options: AuditOptions): AuditOptions =>\n Object.assign({ ...options }, { [INLINE]: true });\n\ninterface Call {\n /** The running recorded action; `undefined` where the action is not recorded. */\n readonly action: string | undefined;\n /** The action records itself in its own transaction, so the stage writes no row. */\n readonly inline: boolean;\n /** Where the row goes: the service and its audit table. */\n readonly target: { service: string; table: AuditTable };\n /** The ids of rows `recordAudit` wrote with a transaction of the caller's. */\n readonly inTransaction: string[];\n}\nconst calls = new WeakMap<object, Call>();\nconst targets = new WeakMap<object, { service: string; table: AuditTable }>();\n\n/** Lets `recordAudit` find the service and the table of an action's `ctx`. */\nexport function bindAuditTarget(\n ctx: object,\n service: string,\n table: AuditTable,\n): void {\n targets.set(ctx, { service, table });\n}\n\nconst recordIdText = (id: unknown): string | null =>\n id === undefined || id === null\n ? null\n : typeof id === \"string\"\n ? id\n : typeof id === \"number\" || typeof id === \"bigint\"\n ? String(id)\n : (JSON.stringify(id) ?? null);\n\nfunction auditRow(\n ctx: { user?: unknown; traceId?: string; requestId?: string },\n service: string,\n entry: {\n action: string;\n resource?: string | undefined;\n recordId?: unknown;\n meta?: unknown;\n },\n) {\n const actor = actorOf(service, ctx.user);\n return {\n id: crypto.randomUUID(),\n at: new Date(),\n service,\n action: entry.action,\n resource: entry.resource ?? null,\n recordId: recordIdText(entry.recordId),\n actorId: actor?.id ?? null,\n actorLabel: actor?.label ?? null,\n tenant: actor?.tenant ?? null,\n traceId: ctx.traceId ?? null,\n requestId: ctx.requestId ?? null,\n meta: entry.meta ?? null,\n };\n}\n\n/**\n * The stage of an action in a service whose database holds an audit table: it\n * inserts the call's row after the call succeeded, and its output checked\n * (it sits between `authorize` and the output check). A call that fails,\n * is refused or is invalid leaves no row, and a row that cannot be written is\n * logged without failing the call. A `GET` and `audit: false` are not recorded.\n */\nexport function auditStage(\n config: {\n name: string;\n method?: string | undefined;\n audit?: false | AuditOptions | undefined;\n },\n service: { name: string; database: AnyDatabaseHandle | undefined },\n /** What `setActionAudit` said of the action, read per call since a plugin says it after the action is made. */\n modeOf?: () => \"inline\" | \"none\" | undefined,\n): Stage | undefined {\n const table = auditTableOf(service.database);\n if (!table) return undefined;\n const options = config.audit || undefined;\n return {\n name: \"audit\",\n run: (call, next) =>\n Effect.gen(function* () {\n const { ctx } = call;\n const mode = modeOf?.();\n const recorded =\n config.audit !== false &&\n mode !== \"none\" &&\n (mode === \"inline\" || (config.method ?? \"POST\") !== \"GET\");\n yield* Effect.sync(() => actorOf(service.name, ctx.user));\n const outer = calls.get(ctx);\n const inline =\n recorded &&\n (mode === \"inline\" || (options !== undefined && INLINE in options));\n const mine: Call = {\n action: recorded ? config.name : undefined,\n inline,\n target: { service: service.name, table },\n inTransaction: [],\n };\n calls.set(ctx, mine);\n const result = yield* next(call).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n if (outer) calls.set(ctx, outer);\n else calls.delete(ctx);\n }),\n ),\n );\n if (!recorded || inline) return result;\n if (mine.inTransaction.length) {\n const committed = yield* ctx.db\n .select({ id: table.id })\n .from(table)\n .where(inArray(table.id, mine.inTransaction))\n .pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n ctx.logger?.error?.(\n `audit: could not tell whether the audit rows of '${config.name}' committed, so none is added`,\n error,\n );\n return undefined;\n }),\n ),\n );\n // A read that failed says nothing: adding a row now could record the call twice.\n if (!committed || committed.length === mine.inTransaction.length)\n return result;\n }\n let row: ReturnType<typeof auditRow> | undefined;\n yield* Effect.gen(function* () {\n row = auditRow(ctx, service.name, {\n action: config.name,\n resource: options?.resource,\n });\n row.recordId = recordIdText(\n options?.record?.({ input: call.input, result }),\n );\n yield* ctx.db.insert(table).values(row);\n }).pipe(\n Effect.catchCause((cause) =>\n Effect.sync(() =>\n ctx.logger?.error?.(\n `audit: '${config.name}' ran but its audit row was not written`,\n row,\n cause,\n ),\n ),\n ),\n );\n return result;\n }),\n };\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\n * row (when `tx` rolls back, it does).\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 * @example\n * yield* recordAudit(ctx, { resource: \"order\", recordId: input.orderId, meta: { reason: input.reason } });\n */\nexport const recordAudit = (\n ctx: object,\n entry: {\n action?: string;\n resource?: string;\n recordId?: string | number;\n meta?: unknown;\n },\n options: { tx?: any } = {},\n): Effect.Effect<void, unknown> =>\n Effect.gen(function* () {\n const target = targets.get(ctx);\n if (!target)\n return yield* Effect.die(\n new Error(\n \"recordAudit needs the ctx of an action of a service whose database holds an audit table\",\n ),\n );\n const call = calls.get(ctx);\n const action = entry.action ?? call?.action;\n if (!action)\n return yield* Effect.die(\n new Error(\n \"recordAudit needs an action: it defaults to the running action only when that action is recorded\",\n ),\n );\n const row = auditRow(ctx, target.service, { ...entry, action });\n const handle = options.tx ?? (ctx as { db: any }).db;\n yield* handle.insert(target.table).values(row) as Effect.Effect<\n unknown,\n unknown\n >;\n if (options.tx !== undefined && call?.action)\n call.inTransaction.push(row.id);\n });\n\n/**\n * Whether the action running with `ctx` records itself inline: its writes then\n * call `recordInline` in their transaction.\n */\nexport const isInlineAudit = (ctx: object): boolean =>\n calls.get(ctx)?.inline === true;\n\n/**\n * Write the audit row of a write in the transaction `tx` of the write, so the\n * row commits or rolls back with it. The action is `entry.action`, as the\n * single operation's name (`person.create`, also inside a bulk call).\n */\nexport const recordInline = (\n ctx: object,\n tx: any,\n entry: { action: string; resource?: string; recordId?: unknown },\n): Effect.Effect<void, unknown> =>\n Effect.suspend(() => {\n const { target } = calls.get(ctx)!;\n return tx\n .insert(target.table)\n .values(auditRow(ctx, target.service, entry)) as Effect.Effect<\n unknown,\n unknown\n >;\n }).pipe(Effect.asVoid);\n","import { Effect, Schema, SchemaAST, SchemaTransformation } from \"effect\";\n\n/** What `UploadedFile` accepts. */\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?: readonly string[];\n description?: string;\n}\n\n/** The mark on a file schema, which the server and OpenAPI find it by. */\nconst MARK = \"brickFile\";\ninterface Mark {\n maxSize?: number | undefined;\n accept?: readonly string[] | undefined;\n maxItems?: number | undefined;\n description?: string | undefined;\n}\n\nfunction accepts(accept: readonly 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\n// A file is not a JSON or string value, so its codecs pass what they are given through; a form is decoded by `formDecoder`, which keeps the files apart.\nconst passthrough = () =>\n Schema.link<unknown>()(\n Schema.String,\n SchemaTransformation.passthrough() as never,\n );\n\nfunction make(options: FileOptions, maxItems?: number) {\n const { maxSize, accept } = options;\n const limits = [\n maxSize !== undefined && `at most ${maxSize} bytes`,\n accept && `of type ${accept.join(\", \")}`,\n ].filter(Boolean);\n return Schema.declare(\n (value): value is File =>\n value instanceof Blob &&\n !(value.size > (maxSize ?? Infinity)) &&\n accepts(accept, value.type),\n {\n expected: `a file${limits.length ? ` ${limits.join(\" and \")}` : \"\"}`,\n ...(options.description && { description: options.description }),\n toCodecJson: passthrough,\n toCodecStringTree: passthrough,\n [MARK]: { maxSize, accept, maxItems, description: options.description },\n } as never,\n );\n}\n\n/**\n * A file from a `multipart/form-data` body: a `File` (a `Blob`), at most\n * `maxSize` bytes, of a type in `accept`. The counterpart of core's `t.File()`.\n * A call to it over HTTP is read as multipart; OpenAPI describes the field as\n * binary. A tool cannot take one.\n *\n * @example\n * input: Schema.Struct({ file: UploadedFile({ maxSize: 5_000_000, accept: [\"image/*\"] }), folder: Schema.String })\n */\nexport function UploadedFile(options: FileOptions = {}): Schema.declare<File> {\n return make(options);\n}\n\n/** Several files under one form field: the counterpart of core's `t.Files()`. A lone file is read as a list of one. */\nexport function UploadedFiles(\n options: FileOptions & { minItems?: number; maxItems?: number } = {},\n): Schema.$Array<Schema.declare<File>> {\n const { minItems, maxItems, ...file } = options;\n let files = Schema.Array(make(file, maxItems));\n if (minItems !== undefined) files = files.check(Schema.isMinLength(minItems));\n if (maxItems !== undefined) files = files.check(Schema.isMaxLength(maxItems));\n return files;\n}\n\nconst markOf = (ast: any): Mark | undefined => {\n if (ast._tag === \"Declaration\") return ast.annotations?.[MARK];\n if (ast._tag === \"Union\")\n for (const type of ast.types) {\n const mark = markOf(type);\n if (mark) return mark;\n }\n return undefined;\n};\n\ntype Decode = (\n input: unknown,\n options?: SchemaAST.ParseOptions,\n) => Effect.Effect<any, Schema.SchemaError>;\n\n/**\n * Decodes the fields of a multipart form: strings are read as `toCodecStringTree`\n * reads a query string (numbers, lists, JSON), and files are kept as they are\n * and checked against their schemas.\n */\nexport function formDecoder(input: Schema.ConstraintCodec<any, any>): Decode {\n const stringly = (schema: Schema.ConstraintCodec<any, any>) =>\n Schema.decodeUnknownEffect(\n Schema.toCodecArrayFromSingle(Schema.toCodecStringTree(schema)),\n ) as Decode;\n const fields = fileFields(input);\n if (!fields.length) return stringly(input);\n const keys = new Map(fields.map((field) => [field.key, field]));\n const rest = stringly(\n Schema.Struct(\n Object.fromEntries(\n Object.entries((input as unknown as { fields: object }).fields).filter(\n ([key]) => !keys.has(key),\n ),\n ),\n ) as never,\n );\n const check = Schema.decodeUnknownEffect(Schema.toType(input)) as Decode;\n return (raw, options) => {\n const strings: Record<string, unknown> = {};\n const files: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(raw as object)) {\n const field = keys.get(key);\n if (!field) strings[key] = value;\n else files[key] = field.many && !Array.isArray(value) ? [value] : value;\n }\n return Effect.flatMap(rest(strings, options), (decoded) =>\n check({ ...decoded, ...files }, options),\n );\n };\n}\n\n/** The array a field is, however it is made optional. */\nconst arraysOf = (ast: any): any =>\n ast._tag === \"Arrays\"\n ? ast\n : ast._tag === \"Union\"\n ? ast.types.map(arraysOf).find(Boolean)\n : undefined;\n\n/** A top-level field that holds a file, or a list of them. `maxBytes` is what the field can add to a body, when that is bounded. */\nexport interface FileField {\n readonly key: string;\n readonly many: boolean;\n readonly maxBytes: number | undefined;\n readonly description?: string | undefined;\n}\n\n/** The file fields of an input schema (a `Schema.Struct`): `UploadedFile` and `UploadedFiles` fields, optional or not. */\nexport function fileFields(schema: unknown): FileField[] {\n const fields = (schema as { fields?: Record<string, { ast: any }> } | null)\n ?.fields;\n const found: FileField[] = [];\n for (const [key, { ast }] of Object.entries(fields ?? {})) {\n const array = arraysOf(ast);\n // A tuple has no rest element: it holds no files.\n const mark = array ? array.rest[0] && markOf(array.rest[0]) : markOf(ast);\n if (!mark) continue;\n const count = array ? mark.maxItems : 1;\n found.push({\n key,\n many: Boolean(array),\n maxBytes:\n mark.maxSize === undefined || count === undefined\n ? undefined\n : mark.maxSize * count,\n description: mark.description,\n });\n }\n return found;\n}\n","import { Context, Effect } from \"effect\";\nimport type { AnyService } from \"./service\";\n\n/** Deps Brick built: a `ctx.deps` it made is not a test's override of the real ones. Global, so a second copy of this package sees them. */\nconst built: WeakSet<object> = ((globalThis as any)[\n Symbol.for(\"brickkit.effect.deps.built\")\n] ??= new WeakSet());\n\n/** Freezes `deps` and remembers that Brick made them. */\nexport function freezeAsBuiltDeps<T extends object>(deps: T): Readonly<T> {\n built.add(Object.freeze(deps));\n return deps;\n}\n\n/** The deps a caller passed to replace some of the service's, such as a fake in a test, or `undefined` when it passed none or only Brick's own. */\nexport function depsOverride(\n call: unknown,\n): Record<string, unknown> | undefined {\n const deps = (call as { deps?: unknown } | undefined)?.deps;\n return deps && typeof deps === \"object\" && !built.has(deps)\n ? (deps as Record<string, unknown>)\n : undefined;\n}\n\nconst isPlainObject = (value: unknown): value is object => {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\n/**\n * The deps of a service: a plain object of values by name, copied and frozen.\n *\n * @throws When `deps` is not a plain object, or a value is `undefined`.\n */\nexport function ownDeps(service: string, deps: unknown = {}) {\n if (!isPlainObject(deps))\n throw new Error(\n `Service \"${service}\": deps must be a plain object of values by name, such as { carrier: createCarrier() }`,\n );\n const snapshot: Record<string, unknown> = { ...deps };\n for (const [name, value] of Object.entries(snapshot))\n if (value === undefined)\n throw new Error(\n `Service \"${service}\": dep \"${name}\" is undefined; pass a value or leave it out`,\n );\n return freezeAsBuiltDeps(snapshot);\n}\n\n/** `deps` with an override on top: what a test replaced, kept for the call. */\nexport const withOverride = (\n deps: Readonly<Record<string, unknown>>,\n override: Record<string, unknown> | undefined,\n) => (override ? freezeAsBuiltDeps({ ...deps, ...override }) : deps);\n\n/** Where a listener a plugin added keeps the plugin's deps, so `useDeps()` in it returns them. */\nexport const PLUGIN_DEPS: unique symbol = Symbol.for(\n \"brickkit.effect.plugin.deps\",\n) as never;\n\n/** The deps the running listener or schedule sees, which `useDeps()` reads. Nothing outside one. */\nexport const AmbientDeps = Context.Reference<\n Readonly<Record<string, unknown>> | undefined\n>(\"@brickkit/effect/AmbientDeps\", { defaultValue: () => undefined });\n\n/** `effect` with `deps` as what `useDeps()` returns inside it. */\nexport const withAmbientDeps = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n deps: Readonly<Record<string, unknown>>,\n) => Effect.provideService(effect, AmbientDeps, deps);\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]?: Readonly<Record<string, unknown>> })[\n PLUGIN_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\n/**\n * The deps of all of an app's services by name, which its listeners and\n * schedules see through `useDeps()`. A name two services give different\n * values has no single answer, so reading it throws.\n */\nexport function appDeps(\n services: readonly AnyService[],\n): Readonly<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(service.deps)) {\n const seen = Object.getOwnPropertyDescriptor(deps, 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, owner.get(name), service.name);\n }\n return freezeAsBuiltDeps(deps);\n}\n\n/**\n * The deps of a service, for code that has no `ctx`: a listener, a schedule or\n * a workflow step. Actions, tools and socket handlers read `ctx.deps` instead.\n * File storages come as they were declared, so name the tenant with `in(tenant)`.\n *\n * `useDeps(service)` returns that service's deps, typed from it, anywhere.\n * Without an argument it is an Effect that returns what the running listener\n * or schedule sees: in one a plugin added, the deps of that install; in the\n * app's own, the deps of all the app's services by name, for code that cannot\n * import the service. A name two services give different values has no single\n * answer, so reading it throws.\n *\n * @param service - The service whose deps to return.\n * @returns The deps, typed from the service. Without `service`, an Effect of\n * them that dies outside a listener or schedule of a Brick app.\n * @example\n * const book = (orderId: string) => useDeps(orders).carrier.book(orderId);\n * const bookHere = (orderId: string) =>\n * Effect.map(useDeps<{ carrier: Carrier }>(), (deps) => deps.carrier.book(orderId));\n */\nexport function useDeps<S extends AnyService>(service: S): S[\"deps\"];\nexport function useDeps<T = Record<string, unknown>>(): Effect.Effect<T>;\nexport function useDeps(service?: AnyService): unknown {\n if (service) return service.deps;\n return Effect.flatMap(Effect.service(AmbientDeps), (deps) =>\n deps\n ? Effect.succeed(deps)\n : Effect.die(\n new Error(\n \"useDeps() was called outside a Brick app: call it from a listener or a schedule (actions read ctx.deps), or pass the service: useDeps(service).\",\n ),\n ),\n );\n}\n","import { fileURLToPath } from \"node:url\";\nimport { DuplicateNameError } from \"./errors\";\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 /** Validators declared before `transform`: they check the raw string. */\n private rawValidators: SecretValidator<string>[] = [];\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 * Validators declared before it check the raw string, those after it the\n * converted value; a throwing transform fails resolution.\n */\n transform<U>(fn: (raw: string) => U): SecretRef<U> {\n this.rawValidators.push(...(this.validators as SecretValidator<any>[]));\n this.validators = [];\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 check<V>(validators: SecretValidator<V>[], value: V): void {\n for (const fn of 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 }\n\n private coerce(raw: string): T {\n this.check(this.rawValidators, raw);\n let value: T;\n if (this.transformFn) {\n try {\n value = this.transformFn(raw);\n } catch (err) {\n // The cause stays off the message: parser errors such as JSON.parse's quote the raw value.\n throw new Error(\n `Invalid value for secret \"${this.name}\": transform failed`,\n { cause: err },\n );\n }\n } else {\n value = raw as unknown as T;\n }\n this.check(this.validators, value);\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[\"rawValidators\"] = [];\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 invalid: string[] = [];\n const resolved: Record<string, unknown> = {};\n for (const ref of registry.values()) {\n try {\n const v = ref.value(source);\n if (v === undefined) missing.push(ref.name);\n else resolved[ref.name] = v;\n } catch (error) {\n invalid.push((error as Error).message);\n }\n }\n if (missing.length > 0 || invalid.length > 0) {\n throw new Error(\n [\n ...(missing.length > 0\n ? [\n `Missing required secrets: ${missing.join(\", \")}. Set them in .env (local) or the environment (prod)`,\n ]\n : []),\n ...invalid,\n ].join(\"; \"),\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 { Data } from \"effect\";\n\n/** A storage could not be reached, or did not answer in time. Fails every call while it is down. A write that fails with it may still have been applied. */\nexport class StorageUnavailableError extends Data.TaggedError(\n \"StorageUnavailableError\",\n)<{ readonly message: string; readonly cause?: unknown }> {}\n\n/** A call that storage refused: a `ttlMs` that is no positive integer, a key that holds no counter, a tenant or file id that is invalid, a file that could not be written or read. */\nexport class StorageError extends Data.TaggedError(\"StorageError\")<{\n readonly message: string;\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 { Effect } from \"effect\";\nimport { actorOf } from \"./actor\";\nimport { freezeAsBuiltDeps } from \"./deps\";\nimport { SecretRef } from \"./secrets\";\nimport { StorageError } from \"./storage-errors\";\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/** The files of 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(\n file: Blob,\n options?: { contentType?: string },\n ): Effect.Effect<StoredFile, StorageError>;\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 ): Effect.Effect<string, StorageError>;\n /** The file, or `undefined` when this tenant has none with that id. */\n get(id: string): Effect.Effect<Blob | undefined, StorageError>;\n /** Removes the file; does nothing when this tenant has none with that id. */\n delete(id: string): Effect.Effect<void, StorageError>;\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 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\nconst attempt = <T>(run: () => Promise<T>) =>\n Effect.tryPromise({\n try: run,\n catch: (error) =>\n new StorageError({\n message: error instanceof Error ? error.message : String(error),\n }),\n });\n\nfunction scoped(driver: FileDriver, tenant: string): ScopedFiles {\n const folder = () => `${driver.prefix}${tenantKey(tenant, !!driver.local)}/`;\n const keyOf = (id: string) =>\n typeof id === \"string\" && UUID.test(id) ? folder() + id : undefined;\n return Object.freeze({\n put: (file: Blob, options?: { contentType?: string }) =>\n attempt(async () => {\n if (!(file instanceof Blob))\n throw new TypeError(\"File storage: put needs a Blob or a File\");\n const at = 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: (\n id: string,\n options: { expiresInMs?: number; download?: string } = {},\n ) =>\n attempt(async () => {\n const key = keyOf(id);\n if (!key)\n throw new Error(\n `File storage: ${JSON.stringify(id)} is not a file id`,\n );\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: (id: string) =>\n attempt(async () => {\n const key = keyOf(id);\n return key ? driver.read(key) : undefined;\n }),\n delete: (id: string) =>\n attempt(async () => {\n const key = keyOf(id);\n if (key) await driver.remove(key);\n }),\n });\n}\n\n/** The driver behind each handle `fileStorage` made. Global, so a second copy of this package finds them. */\nconst drivers: WeakMap<object, FileDriver> = ((globalThis as any)[\n Symbol.for(\"brickkit.effect.storage.files\")\n] ??= new WeakMap());\n\nexport function fileStorage(driver: FileDriver): FileStorage {\n const outside = () =>\n Effect.fail(\n new StorageError({\n message:\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, 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[]>();\n\n/**\n * `deps` for a call: each file storage in them scoped to the tenant of the\n * call's user (the service's `identity`). A call with no tenant fails the\n * file's methods with a `StorageError`. Without file storages, `deps` as it is.\n */\nexport function scopeFiles<T extends Readonly<Record<string, unknown>>>(\n deps: T,\n ctx: { user?: unknown },\n service: string,\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 = Effect.try({\n try: () => {\n const tenant = actorOf(service, ctx.user)?.tenant;\n if (!tenant)\n throw new Error(\n \"File storage: this call has no tenant. The service's identity must return { id, tenant } for callers that use files; outside a request use files.in(tenantId)\",\n );\n tenantKey(tenant); // `in` throws for a tenant the storage cannot use\n return tenant;\n },\n catch: (error) =>\n new StorageError({\n message: error instanceof Error ? error.message : String(error),\n }),\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 put: (file: Blob, options?: { contentType?: string }) =>\n Effect.flatMap(tenant, (id) => handle.in(id).put(file, options)),\n url: (\n id: string,\n options?: { expiresInMs?: number; download?: string },\n ) =>\n Effect.flatMap(tenant, (tenantId) =>\n handle.in(tenantId).url(id, options),\n ),\n get: (id: string) =>\n Effect.flatMap(tenant, (tenantId) => handle.in(tenantId).get(id)),\n delete: (id: string) =>\n Effect.flatMap(tenant, (tenantId) => handle.in(tenantId).delete(id)),\n });\n copy[name] = files;\n }\n return freezeAsBuiltDeps(copy) as T;\n}\n\n/**\n * Files are kept per tenant, so a service with file storage in its deps (or a\n * plugin's) needs an `identity` to say whose they are.\n *\n * @throws When it has none.\n */\nexport function checkFileStorages(\n service: { name: string; hasIdentity: boolean },\n deps: readonly Readonly<Record<string, unknown>>[],\n): void {\n if (service.hasIdentity) 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. Files are kept per tenant: add identity: (ctx) => Effect.succeed({ id, tenant }) to the service.`,\n );\n }\n}\n\nconst warned = new WeakSet<FileDriver>();\n\n/**\n * The directories the app serves signed links from: those of the file storages\n * in the deps it was given, and no others. Checks each driver, and warns once\n * about a local one in production.\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.effect.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\n/** Answers `/_brick/files?token=…`: a signed link the local driver made, until it expires. */\nexport function localFilesRoute(dirs: ReadonlySet<string>) {\n const byDigest = new Map([...dirs].map((dir) => [sha256(dir), dir]));\n return async (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 { createHash } from \"node:crypto\";\nimport { Context, Effect, Layer, Option } from \"effect\";\nimport { fileStorage, type FileDriver, type FileStorage } from \"./file-storage\";\nimport { StorageError, StorageUnavailableError } from \"./storage-errors\";\n\nexport { StorageError, StorageUnavailableError };\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(\n key: string,\n ): Effect.Effect<string | null, StorageError | StorageUnavailableError>;\n /** Stores the value; without `ttlMs` it never expires. */\n put(\n key: string,\n value: string,\n ttlMs?: number,\n ): Effect.Effect<void, StorageError | StorageUnavailableError>;\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 ): Effect.Effect<PutIfAbsentResult, StorageError | StorageUnavailableError>;\n /** Adds 1 to a counter that expires `ttlMs` after its first hit. Atomic. Fails on a key that holds something other than an integer. */\n increment(\n key: string,\n ttlMs: number,\n ): Effect.Effect<Counter, StorageError | StorageUnavailableError>;\n delete(\n key: string,\n ): Effect.Effect<void, StorageError | StorageUnavailableError>;\n /** Closes the connection, if any. The next call opens a new one. */\n close(): Effect.Effect<void>;\n}\n\n/** A driver for key-value storage, such as `redis()` or `memory()`. It sees full keys. */\nexport interface KeyValueDriver {\n readonly kind: \"key-value\";\n get(key: string): Promise<string | null>;\n put(key: string, value: string, ttlMs?: number): Promise<void>;\n putIfAbsent(\n key: string,\n value: string,\n ttlMs: number,\n ): Promise<PutIfAbsentResult>;\n increment(key: string, ttlMs: number): Promise<Counter>;\n delete(key: string): Promise<void>;\n close(): Promise<void>;\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 /** Closes the storage when the app stops. Put it in the app's `layer`. */\n readonly layer: Layer.Layer<never>;\n}\n\n/** Brick's side of a key-value storage: its keys live apart from the app's, and it can delete on a match. */\nexport interface FrameworkStorage extends KeyValueMethods {\n readonly kind: \"key-value\";\n compareAndDelete(\n key: string,\n expected: string,\n ): Effect.Effect<boolean, StorageError | StorageUnavailableError>;\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\nconst APP_PREFIX = \"app:\";\nconst BRICK_PREFIX = \"brick:storage:\";\n\n/** The framework side of each storage handle. */\nconst frameworkSides = new WeakMap<object, FrameworkStorage>();\n\n/** Brick's side of a storage the app defined, for the features that keep their own keys in it (rate limits, webhooks). */\nexport const frameworkStorage = (\n storage: KeyValueStorage,\n): FrameworkStorage | undefined => frameworkSides.get(storage);\n\n/** The key-value storage of the app, which `brick({ storage })` provides to every service that has none of its own. */\nexport class AppStorage extends Context.Service<AppStorage, KeyValueStorage>()(\n \"@brickkit/effect/AppStorage\",\n) {}\n\n/**\n * Brick's side of the storage a feature keeps its own keys in: the service's,\n * else the app's. Without one the call dies, saying what needs it.\n */\nexport const requireStorage = (\n service: { readonly storage: KeyValueStorage | undefined },\n needer: string,\n) =>\n Effect.gen(function* () {\n const handle =\n service.storage ??\n Option.getOrUndefined(yield* Effect.serviceOption(AppStorage));\n const side = handle && frameworkStorage(handle);\n if (!side)\n return yield* Effect.die(\n new Error(\n `${needer} needs a key-value storage, but neither its service nor the app has one. Add one: brick({ storage: defineStorage({ driver: memory() }) }) for tests and development, a shared one such as redis() for production, or defineService(name, { storage }).`,\n ),\n );\n return side;\n });\n\nconst notACounter = (key: string) =>\n new StorageError({ message: `Storage: \"${key}\" does not hold a counter` });\n\nconst counterOverflow = (key: string) =>\n new StorageError({\n message: `Storage: incrementing \"${key}\" would overflow`,\n });\n\nconst checkTtl = (ttlMs: number | undefined, required: boolean) =>\n (ttlMs === undefined && !required) ||\n (Number.isSafeInteger(ttlMs) && ttlMs! > 0)\n ? Effect.void\n : Effect.fail(\n new StorageError({\n message: `Storage ttlMs must be a positive integer, got ${ttlMs}`,\n }),\n );\n\n/** The key a feature stores under: its name, then its parts as JSON, with a part over 128 characters replaced by its digest. */\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\nconst driven = <T>(run: () => Promise<T>) =>\n Effect.tryPromise({\n try: run,\n catch: (error): StorageError | StorageUnavailableError =>\n error instanceof StorageError || error instanceof StorageUnavailableError\n ? error\n : new StorageUnavailableError({\n message: error instanceof Error ? error.message : String(error),\n cause: error,\n }),\n });\n\nfunction side(driver: KeyValueDriver, prefix: string) {\n return {\n kind: \"key-value\",\n get: (key: string) => driven(() => driver.get(prefix + key)),\n put: (key: string, value: string, ttlMs?: number) =>\n Effect.andThen(checkTtl(ttlMs, false), () =>\n driven(() => driver.put(prefix + key, value, ttlMs)),\n ),\n putIfAbsent: (key: string, value: string, ttlMs: number) =>\n Effect.andThen(checkTtl(ttlMs, true), () =>\n driven(() => driver.putIfAbsent(prefix + key, value, ttlMs)),\n ),\n increment: (key: string, ttlMs: number) =>\n Effect.andThen(checkTtl(ttlMs, true), () =>\n driven(() => driver.increment(prefix + key, ttlMs)),\n ),\n delete: (key: string) => driven(() => driver.delete(prefix + key)),\n close: () => Effect.promise(() => 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. Nothing connects until\n * 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`, each an Effect, and `layer`, which closes it with the\n * app. File: `in(tenant)`, which has `put`, `url`, `get` and `delete`.\n * @example\n * export const cache = defineStorage({ driver: redis({ url: process.env.REDIS_URL }) });\n * // in an action\n * yield* 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 = {\n ...side(driver, APP_PREFIX),\n layer: Layer.effectDiscard(\n Effect.addFinalizer(() => Effect.promise(() => driver.close())),\n ),\n } as KeyValueStorage;\n frameworkSides.set(handle, {\n ...side(driver, BRICK_PREFIX),\n compareAndDelete: (key: string, expected: string) =>\n driven(() => driver.compareAndDelete(BRICK_PREFIX + key, expected)),\n });\n return handle as StorageOf<D>;\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\n/** How long a command waits for Redis before the storage is called unavailable. */\nconst REDIS_WAIT_MS = 1000;\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// From the global, as @types/bun doesn't export RedisClient from \"bun\" for the .d.ts build.\ntype RedisClient = InstanceType<typeof Bun.RedisClient>;\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 fail with\n * `StorageUnavailableError`. A command Redis doesn't answer within a second\n * fails the same way, and the connection is dropped so the next call opens a\n * 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 client: RedisClient | undefined;\n const unavailable = (message: string, cause?: unknown) =>\n new StorageUnavailableError({ message, cause });\n const send = async (command: string, args: string[]): Promise<any> => {\n const current = (client ??= new Bun.RedisClient(options.url));\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n current.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 (client === current) client = undefined;\n current.close();\n throw unavailable(\n `Storage: Redis did not answer within ${REDIS_WAIT_MS} ms`,\n );\n }\n if (current.connected) {\n if (UNAVAILABLE_REPLY.test(String((error as Error)?.message)))\n throw unavailable(\n `Storage: Redis cannot serve the command right now (${(error as Error).message})`,\n error,\n );\n // Any other reply is Redis refusing this command, not an outage.\n throw new StorageError({\n message: `Storage: Redis refused the command (${(error as Error)?.message})`,\n });\n }\n if (client === current) client = undefined;\n current.close();\n throw unavailable(\"Storage: Redis is unreachable\", error);\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 client?.close();\n client = undefined;\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 { isIPv4, isIPv6 } from \"node:net\";\nimport { Effect } from \"effect\";\nimport type { Stage } from \"./action\";\nimport { actorOf } from \"./actor\";\nimport { BrickError } from \"./errors\";\nimport {\n requireStorage,\n storageKey,\n type Counter,\n type FrameworkStorage,\n type KeyValueStorage,\n type StorageError,\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 or the app's key-value storage.\n */\nexport interface RateLimit<TInput = any, TCtx = any> {\n /**\n * Whose calls count together: `\"actor\"` (the service's `identity`; 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 readonly per:\n | \"actor\"\n | \"ip\"\n | ((args: { input: TInput; ctx: TCtx }) => string | null | undefined);\n /** Calls allowed per window. */\n readonly max: number;\n /** The window's length in milliseconds. */\n readonly windowMs: number;\n}\n\n/** One limit, or several that all apply. */\nexport type RateLimits<TInput = any, TCtx = any> =\n | RateLimit<TInput, TCtx>\n | readonly RateLimit<TInput, TCtx>[];\n\n/** Where an app finds the client address, given the request and the socket peer: a non-empty string, or `undefined` for none. It must not be async. */\nexport type ClientIp = (args: {\n request: Request;\n peer: string | undefined;\n}) => string | undefined;\n\ninterface AddressSource {\n readonly clientIp?: ClientIp | undefined;\n readonly server?: () =>\n | { requestIP(request: Request): { address: string } | null }\n | null\n | undefined;\n}\nconst sources = new WeakMap<Request, AddressSource>();\n\nconst CLIENT_REQUEST = Symbol.for(\"brickkit.effect.clientRequest\");\n\n/**\n * Lets a call to another service (`useService`) count against the client of the\n * request that started it: `to` keeps the request apart from its own `request`.\n */\nexport function carryClientRequest(to: object, from: object | undefined): void {\n const request =\n (from as Record<symbol, Request | undefined> | undefined)?.[\n CLIENT_REQUEST\n ] ?? (from as { request?: Request } | undefined)?.request;\n if (request && sources.has(request))\n (to as Record<symbol, Request>)[CLIENT_REQUEST] = request;\n}\n\n/** Tells rate limits where `request` came from: the socket server that holds its peer, and the app's `clientIp`. */\nexport function markAddressSource(\n request: Request,\n source: AddressSource,\n): void {\n sources.set(request, source);\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: { request?: Request }): string | undefined {\n const request =\n (ctx as Record<symbol, Request | undefined>)[CLIENT_REQUEST] ?? ctx.request;\n const source = request && sources.get(request);\n if (!request || !source) return undefined;\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\n/** The limits of an action's `rateLimit`, checked. */\nexport function rateLimitsOf(config: {\n name: string;\n rateLimit?: RateLimits | undefined;\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\ninterface Fallback {\n active: boolean;\n counters: Map<string, { count: number; expiresAt: number }>;\n probeAt: number;\n healthySince?: number | undefined;\n sweepAt: number;\n}\nconst QUIET_MS = 10_000;\nconst PROBE_MS = 1_000;\nconst SWEEP_MS = 1_000;\nconst fallbacks = new WeakMap<FrameworkStorage, Fallback>();\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\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 probe(\n storage: FrameworkStorage,\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 (\n fallback.active &&\n fallback.healthySince !== undefined &&\n now - fallback.healthySince >= QUIET_MS\n ) {\n fallback.active = false;\n console.warn(\n \"[Brick-TS] Rate limits: storage is back; counting there again.\",\n );\n }\n };\n Effect.runFork(\n storage.increment(key, windowMs).pipe(\n Effect.map(answered),\n Effect.catchTag(\"StorageUnavailableError\", () =>\n Effect.sync(() => {\n fallback.healthySince = undefined;\n }),\n ),\n Effect.catchCause(() => Effect.sync(answered)),\n ),\n );\n}\n\n/** Counts one hit. While the storage is unavailable it counts in this process's memory, probes it once a second, and goes back after it has answered for a while. */\nfunction increment(\n storage: FrameworkStorage,\n key: string,\n windowMs: number,\n): Effect.Effect<Counter, StorageError> {\n return Effect.suspend(() => {\n let fallback = fallbacks.get(storage);\n if (fallback) {\n const now = Date.now();\n if (fallback.active) {\n if (now >= fallback.probeAt) {\n fallback.probeAt = now + PROBE_MS;\n probe(storage, fallback, key, windowMs);\n }\n return Effect.succeed(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 return storage.increment(key, windowMs).pipe(\n Effect.catchTag(\"StorageUnavailableError\", (error) =>\n Effect.sync(() => {\n const now = Date.now();\n let current = fallbacks.get(storage);\n if (!current)\n fallbacks.set(\n storage,\n (current = {\n active: false,\n counters: new Map(),\n probeAt: 0,\n sweepAt: now + SWEEP_MS,\n }),\n );\n if (!current.active) {\n Object.assign(current, {\n active: true,\n probeAt: now + PROBE_MS,\n healthySince: undefined,\n });\n console.warn(\n `[Brick-TS] Rate limits: storage is unavailable (${error.message}); counting in this process's memory until it is back.`,\n );\n }\n return countInMemory(current, key, windowMs, now);\n }),\n ),\n );\n });\n}\n\nfunction keyOf(\n limit: RateLimit,\n service: string,\n input: unknown,\n ctx: any,\n): 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 actor = actorOf(service, ctx.user);\n if (actor) return [\"actor\", actor.id];\n }\n const ip = clientAddress(ctx);\n return ip === undefined ? undefined : [\"ip\", ip];\n}\n\n/**\n * The stage of an action with `rateLimit`: it counts the call in each limit's\n * window and refuses the call over `max` with `RATE_LIMITED` (429), whose\n * `details.retryAfterSeconds` the server sends as `Retry-After`. It sits\n * between the input check and `authorize`: a malformed call is not counted,\n * and one `authorize` refuses is.\n *\n * @throws When a limit is not valid, or limits `per: \"actor\"` in a service without `identity`.\n */\nexport function rateLimitStage(\n config: { name: string; rateLimit?: RateLimits | undefined },\n service: {\n name: string;\n hasIdentity: boolean;\n storage: KeyValueStorage | undefined;\n },\n): Stage | undefined {\n const limits = rateLimitsOf(config);\n if (!limits) return undefined;\n if (limits.some(({ per }) => per === \"actor\") && !service.hasIdentity)\n throw new Error(\n `Service \"${service.name}\": action '${config.name}' limits per \"actor\", but the service declares no identity. Add identity: ({ request }) => Effect.succeed(user && { id: user.id }) to defineService(\"${service.name}\", { ... }).`,\n );\n return {\n name: \"rateLimit\",\n run: (call, next) =>\n Effect.gen(function* () {\n const storage = yield* requireStorage(\n service,\n `Action '${config.name}' of service \"${service.name}\", which declares rateLimit,`,\n );\n for (const [index, limit] of limits.entries()) {\n const key = yield* Effect.sync(() =>\n keyOf(limit, service.name, call.input, call.ctx),\n );\n if (!key) continue;\n const { count, expiresInMs } = yield* increment(\n storage,\n storageKey(\"rate-limit\", [\n service.name,\n \"action\",\n config.name,\n index,\n ...key,\n ]),\n limit.windowMs,\n );\n if (count > limit.max) {\n const retryAfterSeconds = Math.max(\n 1,\n Math.ceil(expiresInMs / 1000),\n );\n return yield* new BrickError({\n code: \"RATE_LIMITED\",\n message: `Too many calls to '${config.name}'; retry in ${retryAfterSeconds} s`,\n status: 429,\n details: { retryAfterSeconds },\n });\n }\n }\n return yield* next(call);\n }),\n };\n}\n","import { Effect } from \"effect\";\n\nconst isPlain = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null) return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\n/**\n * The value without the keys of plain objects that hold `undefined`, as\n * `JSON.stringify` and so core drop them. Schemas encode an `undefined` to\n * `null`, so a handler's `{ domain: row.domain ?? undefined }` would put\n * `\"domain\": null` on the wire. Array items, class instances, `Date` and the\n * rest are left as they are.\n */\nexport const omitUndefined = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(omitUndefined);\n if (!isPlain(value)) return value;\n // fromEntries defines own keys, so a `__proto__` key stays a key.\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .map(([key, item]) => [key, omitUndefined(item)]),\n );\n};\n\n/**\n * Runs `run` on the value without its undefined keys. A schema that requires\n * such a key (`Schema.UndefinedOr`) refuses that, so it then runs on the value\n * as it came, and the key encodes as `null`.\n */\nexport const omittingUndefined =\n <A, E, R>(run: (value: unknown) => Effect.Effect<A, E, R>) =>\n (value: unknown): Effect.Effect<A, E, R> =>\n run(omitUndefined(value)).pipe(Effect.catch(() => run(value)));\n","import { inspect } from \"node:util\";\nimport { Cause, Context, Effect, Schema, SchemaAST } from \"effect\";\nimport type { Stage } from \"./action\";\nimport type { Logger } from \"./context\";\nimport { BrickError, redactedCopy, toFailure, ValidationError } from \"./errors\";\n\nconst MARK = \"brickSensitive\";\n\n/**\n * The schema, unchanged in type and validation, marked sensitive. Its value is\n * kept out of logs and error responses for the rest of the call, an output\n * field with it is removed unless `reveal` allows it, and OpenAPI marks it\n * `writeOnly`.\n *\n * @example\n * Schema.Struct({ user: Schema.String, password: Sensitive(Schema.String) })\n */\nexport function Sensitive<S extends Schema.Top>(schema: S): S[\"Rebuild\"] {\n return schema.annotate({ [MARK]: true, writeOnly: true });\n}\n\nconst isMarked = (ast: SchemaAST.AST) => ast.annotations?.[MARK] === 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 /** Where a mark sits under a `Suspend`, which the walk does not follow. */\n hidden?: string;\n}\n\nconst pointer = (segments: Segment[]) =>\n segments.map((key) => `/${typeof key === \"string\" ? key : \"*\"}`).join(\"\") ||\n \"/\";\n\nexport const holdsMark = (\n ast: SchemaAST.AST,\n seen = new Set<SchemaAST.AST>(),\n): boolean => {\n if (seen.has(ast)) return false;\n seen.add(ast);\n if (isMarked(ast)) return true;\n const children: readonly SchemaAST.AST[] =\n ast._tag === \"Objects\"\n ? [\n ...ast.propertySignatures.map(({ type }) => type),\n ...ast.indexSignatures.map(({ type }) => type),\n ]\n : ast._tag === \"Arrays\"\n ? [...ast.elements, ...ast.rest]\n : ast._tag === \"Union\"\n ? ast.types\n : ast._tag === \"Suspend\"\n ? [ast.thunk()]\n : ast._tag === \"Declaration\"\n ? ast.typeParameters\n : [];\n return children.some((child) => holdsMark(child, seen));\n};\n\nfunction collect(\n ast: SchemaAST.AST,\n segments: Segment[],\n optional: boolean,\n walk: Analysis,\n): void {\n if (isMarked(ast)) {\n walk.paths.push({ segments, optional });\n return;\n }\n if (ast._tag === \"Suspend\") {\n if (holdsMark(ast)) walk.hidden ??= pointer(segments);\n return;\n }\n if (ast._tag === \"Union\") {\n for (const branch of ast.types) collect(branch, segments, optional, walk);\n return;\n }\n // A class: its instance holds the fields of the struct it wraps.\n if (ast._tag === \"Declaration\") {\n for (const part of ast.typeParameters)\n collect(part, segments, optional, walk);\n return;\n }\n if (ast._tag === \"Objects\") {\n const declared = ast.propertySignatures.map(({ name }) => String(name));\n for (const { name, type } of ast.propertySignatures) {\n const here = [...segments, String(name)];\n const absentable = type.context?.isOptional === true;\n if (!isMarked(type))\n walk.publics.push({ segments: here, required: !absentable });\n collect(type, here, absentable, walk);\n }\n for (const { type } of ast.indexSignatures)\n collect(\n type,\n [...segments, declared.length ? { except: declared } : null],\n true,\n walk,\n );\n return;\n }\n if (ast._tag === \"Arrays\") {\n const items: [SchemaAST.AST, Segment][] = [\n ...ast.elements.map((item, index): [SchemaAST.AST, Segment] => [\n item,\n String(index),\n ]),\n ...ast.rest.map((item): [SchemaAST.AST, Segment] => [item, null]),\n ];\n for (const [item, segment] of items) {\n if (!isMarked(item))\n walk.publics.push({ segments: [...segments, segment], required: true });\n collect(item, [...segments, segment], false, walk);\n }\n }\n}\n\nconst analyses = new WeakMap<SchemaAST.AST, Analysis>();\nfunction analyze(ast: SchemaAST.AST): Analysis {\n let analysis = analyses.get(ast);\n if (!analysis) {\n analysis = { paths: [], publics: [] };\n collect(ast, [], false, analysis);\n analyses.set(ast, analysis);\n }\n return analysis;\n}\n\n/**\n * Where a schema marks a field `Sensitive`, as a JSON pointer, or `undefined`\n * when it marks none. A mark under a `Suspend` is reported at the suspend.\n */\nexport function sensitivePointer(schema: Schema.Top): string | undefined {\n for (const ast of [\n Schema.toType(schema).ast,\n Schema.toCodecJson(schema).ast,\n ]) {\n const { paths, hidden } = analyze(ast);\n if (paths[0]) return pointer(paths[0].segments);\n if (hidden) return hidden;\n }\n return undefined;\n}\n\n/** Whether any part of a schema is marked `Sensitive`. */\nexport const hasSensitive = (schema: unknown): boolean =>\n Schema.isSchema(schema) &&\n sensitivePointer(schema as Schema.Top) !== undefined;\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\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\n/**\n * Whether the call may see a sensitive output field: `true` for every one, or\n * an Effect per field, given its JSON pointer. Anything but `true`, and a\n * failure, removes the field.\n */\nexport type Reveal<TInput = unknown, TCtx = any> =\n | boolean\n | ((args: {\n field: string;\n input: TInput;\n ctx: TCtx;\n }) => Effect.Effect<boolean, any, never>);\n\nconst 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)) all.push(parent[key]);\n return all;\n};\n\n/** Throws when the output could not lose its sensitive fields without breaking its schema. */\nfunction checkOutput(\n owner: string,\n output: Analysis,\n reveal: Reveal<any> | undefined,\n): void {\n if (reveal === true) return;\n for (const path of output.paths) {\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 optional in every union branch; an array item cannot be absent (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}\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]\";\nconst LEAF_DEPTH = 5;\n/** How many `reveal` checks of one call run at once: a list of rows is not one round trip each. */\nconst REVEAL_CONCURRENCY = 10;\n\n/** The secrets of one call, which its logs and errors have replaced with `[REDACTED]`. */\nexport interface Redactions {\n readonly values: Set<string>;\n count: number;\n sorted?: string[] | undefined;\n full?: boolean;\n}\n\n/** The redactions of the running call; nothing outside a call with sensitive fields. */\nexport const Redactions = Context.Reference<Redactions | undefined>(\n \"@brickkit/effect/Redactions\",\n { defaultValue: () => undefined },\n);\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. Bound an input's sensitive records and arrays with a length check.`,\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\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\n/**\n * Keep a secret out of what the rest of the call logs: its logger and its\n * error responses replace it with `[REDACTED]`. Call it as soon as `execute`\n * loads a secret, before it can be logged. It takes each string and number in\n * the value, as a `Sensitive` field's value is taken: booleans, and numbers\n * under 4 digits, are left out. Outside a call with sensitive fields it does nothing.\n *\n * @example\n * const key = yield* loadKey(input.id);\n * yield* redact(key);\n */\nexport const redact = (value: unknown): Effect.Effect<void> =>\n Effect.map(Effect.service(Redactions), (set) => {\n if (set) register(set, value, new Set());\n });\n\nexport function redactText(set: Redactions, text: string): string {\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 = 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(set, 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\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\n/** A copy of `value` with every secret replaced, as far as a log line shows it; `value` itself when it holds none. */\nexport function redactValues<T>(set: Redactions, value: T): T {\n if (!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 set,\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\n/** An error's `details`, with every secret in its keys and values replaced; withheld once the set is full. */\nexport function redactDetails(set: Redactions, details: unknown): unknown {\n if (details === undefined || (!set.full && !set.values.size)) 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\nconst redactingLoggers = new WeakMap<Logger, Redactions>();\n\nfunction redactingLogger(logger: Logger, set: Redactions): Logger {\n const wrap =\n (level: keyof Logger) =>\n (...args: unknown[]) =>\n logger[level](...args.map((arg) => redactValues(set, arg)));\n const wrapped: Logger = {\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n };\n redactingLoggers.set(wrapped, set);\n return wrapped;\n}\n\n/**\n * The stage of an action whose input or output has sensitive fields: it\n * redacts the input's values, runs the rest with a redacting logger and\n * redacted failures, and removes the output's sensitive fields unless\n * `reveal` allows them. It wraps everything after it, so it sits right\n * after the input check.\n *\n * @throws When a sensitive field could not be removed from the output without breaking its schema.\n */\nexport function sensitiveStage(\n config: {\n input?: Schema.ConstraintCodec<any, any> | undefined;\n output?: Schema.ConstraintCodec<any, any> | undefined;\n reveal?: Reveal<any> | undefined;\n },\n owner: string,\n): Stage | undefined {\n const { input, output, reveal = false } = config;\n const inputs = input && analyze(Schema.toType(input).ast);\n const outputs = output && analyze(Schema.toType(output).ast);\n for (const [kind, analysis] of [\n [\"input\", inputs],\n [\"output\", outputs],\n ] as const)\n if (analysis?.hidden !== undefined)\n throw new Error(\n `${owner}: the ${kind} schema marks a field Sensitive under a Suspend at '${analysis.hidden}', which sensitive fields do not follow; move the secret out of the recursive schema`,\n );\n if (!inputs?.paths.length && !outputs?.paths.length) return undefined;\n if (outputs) checkOutput(owner, outputs, reveal);\n const wireOutputs = output && analyze(Schema.toCodecJson(output).ast);\n return {\n name: \"sensitive\",\n run: (call, next) =>\n Effect.gen(function* () {\n const set: Redactions = (yield* Effect.service(Redactions)) ?? {\n values: new Set(),\n count: 0,\n };\n if (inputs)\n for (const value of values(call.input, inputs.paths))\n register(set, value, new Set());\n if (redactingLoggers.get(call.ctx.logger) !== set)\n call.ctx.logger = redactingLogger(call.ctx.logger, set);\n const result = yield* next(call).pipe(\n Effect.catchCause((cause) => {\n if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);\n const failure = toFailure(cause, {\n logger: call.ctx.logger,\n requestId: call.ctx.requestId,\n });\n return Effect.fail(\n failure instanceof BrickError ||\n failure instanceof ValidationError\n ? redactedCopy(failure, {\n message: redactText(set, failure.message),\n details:\n failure instanceof BrickError\n ? redactDetails(set, failure.details)\n : undefined,\n })\n : failure,\n );\n }),\n Effect.provideService(Redactions, set),\n );\n const paths = (call.wire ? wireOutputs : outputs)?.paths;\n if (!paths?.length || result instanceof Response) return result;\n for (const value of values(result, paths))\n register(set, value, new Set());\n if (reveal === true) return result;\n let revealed = result;\n for (const { segments } of paths) {\n const fields = [...found(result, segments)].map(\n ([, , field]) => field,\n );\n const allowed = yield* Effect.forEach(\n fields,\n (field) =>\n typeof reveal === \"function\"\n ? reveal({ field, input: call.input, ctx: call.ctx }).pipe(\n Effect.catchCause(() => Effect.succeed(false)),\n )\n : Effect.succeed(false),\n { concurrency: REVEAL_CONCURRENCY },\n );\n const hidden = new Set(fields.filter((_, i) => allowed[i] !== true));\n if (hidden.size) revealed = omit(revealed, segments, hidden);\n }\n return revealed;\n }),\n };\n}\n","import { Schema, SchemaAST, SchemaIssue } from \"effect\";\nimport type { ValidationIssue } from \"./errors\";\n\ntype Issue = SchemaIssue.Issue;\ntype Ast = SchemaAST.AST;\n/** `ignoreNested`: extra keys below the root are no issue. `rootOnly`: report the root's extra keys and nothing else. */\nexport type ExtraKeys = \"ignoreNested\" | \"rootOnly\";\ntype Sink = {\n input: unknown;\n extras?: ExtraKeys;\n items: Array<{ path: ReadonlyArray<PropertyKey>; message: string }>;\n};\n\nconst stock = SchemaIssue.makeFormatterStandardSchemaV1();\n\n/** The message Effect would give a leaf or a filter, for what has no core wording. */\nconst stockMessage = (issue: Issue) =>\n stock(issue).issues[0]?.message ?? \"Expected a valid value\";\n\nconst hasCheck = (ast: Ast, expected: string) =>\n (ast.checks as ReadonlyArray<any> | undefined)?.some(\n (check) => check.annotations?.expected === expected,\n ) ?? false;\n\nconst unit = (ast: Ast | undefined) =>\n ast?._tag === \"Number\" && hasCheck(ast, \"an integer\") ? \"integer\" : \"number\";\n\n/** The message of a value of the wrong type, as core words it; `undefined` for a type core has no wording for. */\nfunction typeMessage(ast: Ast): string | undefined {\n switch (ast._tag) {\n case \"String\":\n return \"Expected string\";\n case \"Number\":\n return `Expected ${unit(ast)}`;\n case \"Boolean\":\n return \"Expected boolean\";\n case \"Arrays\":\n return ast.rest.length === 0 ? \"Expected tuple\" : \"Expected array\";\n case \"Objects\":\n return \"Expected object\";\n case \"Null\":\n return \"Expected null\";\n case \"Undefined\":\n return \"Expected undefined\";\n case \"Literal\":\n return `Expected ${typeof ast.literal === \"string\" ? `'${ast.literal}'` : String(ast.literal)}`;\n case \"Union\": {\n // `Schema.optional(X)` is `X | undefined`: core's optional property just says what X is.\n const rest = ast.types.filter((type) => type._tag !== \"Undefined\");\n return rest.length === 1 && ast.types.length === 2\n ? typeMessage(rest[0]!)\n : \"Expected union value\";\n }\n default:\n return undefined;\n }\n}\n\nconst bound = (word: string, orEqual: boolean) =>\n `${word}${orEqual ? \" or equal to\" : \" than\"}`;\n\n/** The message of a failed check, as core words it; `undefined` for a check core has no wording for. */\nfunction checkMessage(\n issue: SchemaIssue.Filter,\n parent: Ast | undefined,\n): string | undefined {\n const custom = SchemaIssue.defaultCheckHook(issue);\n if (custom !== undefined) return custom;\n const expected = (issue.filter as { annotations?: { expected?: unknown } })\n .annotations?.expected;\n if (typeof expected !== \"string\") return undefined;\n const kind = parent?._tag;\n let match = /^a value with a length of at (least|most) (\\d+)$/.exec(expected);\n if (match) {\n const cmp = bound(match[1] === \"least\" ? \"greater\" : \"less\", true);\n if (kind === \"String\") return `Expected string length ${cmp} ${match[2]}`;\n if (kind === \"Arrays\")\n return `Expected array length to be ${cmp} ${match[2]}`;\n return undefined;\n }\n if (kind === \"Number\") {\n match = /^a value (greater|less) than( or equal to)? (.+)$/.exec(expected);\n if (match)\n return `Expected ${unit(parent)} to be ${bound(match[1]!, Boolean(match[2]))} ${match[3]}`;\n match = /^a value that is a multiple of (.+)$/.exec(expected);\n if (match)\n return `Expected ${unit(parent)} to be a multiple of ${match[1]}`;\n if (expected === \"an integer\") return \"Expected integer\";\n }\n if (kind === \"String\") {\n match = /^a string matching the RegExp (.+)$/.exec(expected);\n if (match) return `Expected string to match '${match[1]}'`;\n if (expected === \"a UUID\") return \"Expected string to match 'uuid' format\";\n }\n if (kind === \"Arrays\" && expected === \"an array with unique items\")\n return \"Expected array elements to be unique\";\n return undefined;\n}\n\nconst notUndefined = (issue: Issue) =>\n !(issue._tag === \"InvalidType\" && issue.ast._tag === \"Undefined\");\n\nconst isMissing = (issue: Issue) =>\n issue._tag === \"Pointer\" && issue.issue._tag === \"MissingKey\";\nconst isExtra = (issue: Issue) =>\n issue._tag === \"Pointer\" && issue.issue._tag === \"UnexpectedKey\";\n\nconst onlyExtraKeys = (issue: Issue): boolean => {\n switch (issue._tag) {\n case \"UnexpectedKey\":\n return true;\n case \"Pointer\":\n case \"Filter\":\n case \"Encoding\":\n return onlyExtraKeys(issue.issue);\n case \"Composite\":\n return issue.issues.length > 0 && issue.issues.every(onlyExtraKeys);\n default:\n return false;\n }\n};\n\nconst expectedOf = (issue: Issue) =>\n issue._tag === \"Filter\"\n ? (issue.filter as { annotations?: { expected?: unknown } }).annotations\n ?.expected\n : undefined;\n\nconst filtersOf = (checks: ReadonlyArray<any>): ReadonlyArray<any> =>\n checks.flatMap((check) =>\n check._tag === \"FilterGroup\" ? filtersOf(check.checks) : [check],\n );\n\nconst valueAt = (input: unknown, path: ReadonlyArray<PropertyKey>) =>\n path.reduce<any>((value, key) => value?.[key], input);\n\n/**\n * The children of a Composite issue on a number or an array, in TypeBox's order.\n * TypeBox stops at a failed integer check; Effect also reports the bounds.\n * Effect skips an array's own checks once an item fails; TypeBox reports the\n * lengths first and uniqueness last.\n */\nfunction childrenOf(\n issue: SchemaIssue.Composite,\n path: ReadonlyArray<PropertyKey>,\n input: unknown,\n): ReadonlyArray<Issue> {\n const { ast } = issue;\n if (ast._tag === \"Number\") {\n const integer = issue.issues.filter(\n (child) => expectedOf(child) === \"an integer\",\n );\n return integer.length ? integer : issue.issues;\n }\n const value = valueAt(input, path);\n if (\n ast._tag !== \"Arrays\" ||\n !Array.isArray(value) ||\n issue.issues.some((child) => child._tag === \"Filter\")\n )\n return issue.issues;\n // Only the checks core has a word for: a custom filter was written for decoded items, not these raw ones.\n const known = (check: any) =>\n /^a value with a length of at (least|most) \\d+$|^an array with unique items$/.test(\n check.annotations?.expected,\n );\n const failed = filtersOf(ast.checks ?? [])\n .filter(known)\n .flatMap((check) => {\n const found = check.run(value, ast, { errors: \"all\" });\n return found ? [new SchemaIssue.Filter(check, found, value, {})] : [];\n });\n const unique = (child: Issue) =>\n expectedOf(child) === \"an array with unique items\";\n return [\n ...failed.filter((child) => !unique(child)),\n ...issue.issues,\n ...failed.filter(unique),\n ];\n}\n\nfunction collect(\n issue: Issue,\n path: ReadonlyArray<PropertyKey>,\n parent: Ast | undefined,\n override: string | undefined,\n out: Sink,\n phase?: \"required\" | \"type\",\n): void {\n const add = (message: string): void => {\n out.items.push({ path, message });\n };\n switch (issue._tag) {\n case \"Filter\":\n return collect(\n issue.issue,\n path,\n parent,\n override ?? checkMessage(issue, parent) ?? stockMessage(issue),\n out,\n );\n case \"Encoding\": {\n // A JSON string where a number or boolean belongs fails here, before any check on it.\n const message =\n (issue.ast._tag === \"Number\" || issue.ast._tag === \"Boolean\") &&\n typeof issue.ast.annotations?.message !== \"string\"\n ? typeMessage(issue.ast)\n : undefined;\n if (message !== undefined) return add(override ?? message);\n return collect(issue.issue, path, parent, override, out);\n }\n case \"Pointer\":\n return collect(\n issue.issue,\n [...path, ...issue.path],\n parent,\n override,\n out,\n phase,\n );\n case \"Composite\": {\n if (issue.ast._tag !== \"Objects\") {\n const { ast } = issue;\n const value = valueAt(out.input, path);\n // TypeBox words any tuple of the wrong length as one issue at the tuple, and checks nothing inside it.\n if (\n ast._tag === \"Arrays\" &&\n ast.rest.length === 0 &&\n Array.isArray(value) &&\n value.length !== ast.elements.length\n )\n return add(\n override ??\n `Expected tuple to have ${ast.elements.length} elements`,\n );\n for (const child of childrenOf(issue, path, out.input))\n collect(child, path, ast, override, out);\n return;\n }\n if (out.extras === \"rootOnly\") {\n if (path.length === 0)\n for (const child of issue.issues.filter(isExtra))\n collect(child, path, issue.ast, override, out);\n return;\n }\n // TypeBox lists an object's absent keys first, then its extra keys, then the keys' own failures.\n const missing = issue.issues.filter((child) => isMissing(child));\n const extra = issue.issues.filter((child) => isExtra(child));\n for (const child of missing)\n collect(child, path, issue.ast, override, out, \"required\");\n if (out.extras !== \"ignoreNested\" || path.length === 0)\n for (const child of extra)\n collect(child, path, issue.ast, override, out);\n for (const child of issue.issues)\n if (!extra.includes(child))\n collect(\n child,\n path,\n issue.ast,\n override,\n out,\n isMissing(child) ? \"type\" : undefined,\n );\n return;\n }\n case \"AnyOf\": {\n const failedOnlyOnExtraKeys = issue.issues.some(onlyExtraKeys);\n if (out.extras === \"ignoreNested\" && failedOnlyOnExtraKeys) return;\n if (override !== undefined) return add(override);\n if (typeof issue.ast.annotations?.message === \"string\")\n return add(stockMessage(issue));\n // Only `X | undefined` (an optional property) reports what is wrong inside X; core words every other union \"Expected union value\".\n const { types } = issue.ast;\n if (\n types.length === 2 &&\n types.some((type) => type._tag === \"Undefined\")\n ) {\n const issues = issue.issues.filter(notUndefined);\n if (issues.length)\n return issues.forEach((child) =>\n collect(child, path, parent, override, out),\n );\n }\n return add(typeMessage(issue.ast) ?? stockMessage(issue));\n }\n case \"InvalidType\":\n return add(\n override ??\n (typeof issue.ast.annotations?.message === \"string\"\n ? undefined\n : typeMessage(issue.ast)) ??\n stockMessage(issue),\n );\n case \"MissingKey\": {\n if (\n override !== undefined ||\n typeof issue.annotations?.messageMissingKey === \"string\"\n )\n return phase === \"type\"\n ? undefined\n : add(override ?? stockMessage(issue));\n if (phase !== \"type\") add(\"Expected required property\");\n if (phase === \"required\") return;\n // core reports the type of the absent value too\n const key = path[path.length - 1];\n const property =\n parent?._tag === \"Objects\"\n ? parent.propertySignatures.find((item) => item.name === key)\n : undefined;\n const message = property && typeMessage(property.type);\n if (message) add(message);\n return;\n }\n case \"UnexpectedKey\":\n return add(\n override ??\n (typeof issue.ast.annotations?.messageUnexpectedKey === \"string\"\n ? stockMessage(issue)\n : \"Unexpected property\"),\n );\n default:\n return add(override ?? stockMessage(issue));\n }\n}\n\nconst pointer = (path: ReadonlyArray<unknown>) =>\n path\n .map((item) =>\n String(\n typeof item === \"object\" && item !== null && \"key\" in item\n ? item.key\n : item,\n )\n .replaceAll(\"~\", \"~0\")\n .replaceAll(\"/\", \"~1\"),\n )\n .map((key) => `/${key}`)\n .join(\"\");\n\n/**\n * The `{ path, message }` items of a schema failure, worded as `@brickkit/core`\n * words TypeBox's: a missing key is \"Expected required property\" and then the\n * type of the absent value, an extra key is \"Unexpected property\", and string,\n * number and array bounds, patterns, literals and unions use TypeBox's text.\n * Paths are JSON pointers, and messages never carry the rejected value.\n * A custom `message` annotation wins; a check or schema core has no wording for\n * keeps Effect's own text.\n */\nexport function issuesOf(\n error: Schema.SchemaError,\n input?: unknown,\n options?: { readonly extras?: ExtraKeys },\n): ValidationIssue[] {\n const out: Sink = { input, items: [], ...options };\n collect(error.issue, [], undefined, undefined, out);\n return out.items.map(({ path, message }) => ({\n path: pointer(path),\n message,\n }));\n}\n","import { Effect, Schema } from \"effect\";\nimport {\n BrickError,\n STANDARD_ERRORS,\n ValidationError,\n normalizeFailures,\n type StandardErrorCode,\n type ValidationIssue,\n} from \"./errors\";\nimport { actionMeta } from \"./action-meta\";\nimport { defaultLogger, type BaseContext, type CallContext } from \"./context\";\nimport type { DatabaseHandle } from \"./db\";\nimport type { KeyValueStorage } from \"./storage\";\nimport { auditStage, type AuditOptions } from \"./audit\";\nimport { formDecoder } from \"./file-schema\";\nimport { scopeFiles } from \"./file-storage\";\nimport { rateLimitStage, type RateLimits } from \"./rate-limit\";\nimport { omittingUndefined } from \"./omit-undefined\";\nimport { sensitiveStage, type Reveal } from \"./sensitive\";\nimport { traceAction } from \"./telemetry\";\nimport { issuesOf } from \"./validation-issues\";\n\n/** The HTTP methods an action can use. */\nexport const HTTP_METHODS = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"] as const;\n/** One of the methods in `HTTP_METHODS`. */\nexport type HttpMethod = (typeof HTTP_METHODS)[number];\n\n/** A schema that needs no services to decode or encode. */\nexport type AnySchema = Schema.ConstraintCodec<any, any>;\n\n/** A declared error code: its default message and HTTP status. */\nexport interface ErrorDefinition {\n readonly message: string;\n /** The HTTP status (default 400). */\n readonly status?: number;\n}\n/** The `errors` of an action: a definition per code. */\nexport type ErrorDefinitions = { readonly [code: string]: ErrorDefinition };\n\n/** One function per error code, standard ones included. `yield* error.NOT_FOUND()` fails the call with that code. */\nexport type ErrorHelpers<TErrors extends ErrorDefinitions> = {\n readonly [K in StandardErrorCode | Extract<keyof TErrors, string>]: (\n message?: string,\n details?: unknown,\n ) => Effect.Effect<never, BrickError>;\n};\n\ntype InputOf<S> = S extends AnySchema ? S[\"Type\"] : undefined;\ntype ResultOf<S, A> = S extends AnySchema ? S[\"Type\"] : A;\n/** Where `authorize` is declared, `execute` can rely on `ctx.user`. */\ntype Narrow<TCtx> = TCtx extends { user: infer U }\n ? Omit<TCtx, \"user\"> & { user: NonNullable<U> }\n : TCtx;\n\n/** What `execute` and `authorize` receive. */\nexport interface ActionParams<TInput, TCtx, TErrors extends ErrorDefinitions> {\n readonly input: InputOf<TInput>;\n readonly ctx: TCtx;\n readonly error: ErrorHelpers<TErrors>;\n}\n\n/** The `ctx` of an action defined outside a service (`defineAction`, `defineTool`), until a service takes it. */\nexport type ActionContext = BaseContext & { user: any; [key: string]: any };\n\n/** The declaration of an action, but for what it does with the call. */\nexport interface ActionConfigBase<\n TInput extends AnySchema | undefined,\n TOutput extends AnySchema | undefined,\n TErrors extends ErrorDefinitions,\n> {\n readonly name: string;\n readonly description?: string;\n /** POST unless set. GET and DELETE read their input from the query string. */\n readonly method?: HttpMethod;\n /** Relative to the service's route: `/documents/:name`. Path parameters are strings: decode them with `Schema.NumberFromString` and the like. */\n readonly path?: string;\n readonly tags?: readonly string[];\n /** The events the action emits, for the architecture and the dashboard. It documents; it does not check what `execute` records. */\n readonly emits?: readonly string[];\n /** Decoded from the call: the JSON body, the query string, or the value `run` is given. */\n readonly input?: TInput;\n /** The result is checked against it, and encoded for the response. */\n readonly output?: TOutput;\n /** Error codes of its own, which `error.CODE()` raises and OpenAPI lists. */\n readonly errors?: TErrors;\n /**\n * Reject keys the `input` schema does not declare instead of dropping them.\n * `true` checks the root object only, as core does with `additionalProperties: false` on the root:\n * extra keys inside nested objects are still dropped. `\"deep\"` checks every object.\n */\n readonly strict?: boolean | \"deep\";\n /** Runs on the raw input before it is decoded. Returns the issues that reject it. */\n readonly checkInput?: (\n input: unknown,\n ) => ReadonlyArray<ValidationIssue> | undefined;\n /** Only the dashboard may call it: through its `/app/*` proxy, which signs the caller. Anyone else gets `UNAUTHORIZED` (401). `ctx.dashboard` is then set. */\n readonly dashboard?: boolean;\n}\n\n/** An action that anyone may call. */\nexport interface ActionConfig<\n TInput extends AnySchema | undefined,\n TOutput extends AnySchema | undefined,\n TErrors extends ErrorDefinitions,\n TCtx,\n A,\n E,\n R,\n> extends ActionConfigBase<TInput, TOutput, TErrors> {\n readonly authorize?: undefined;\n readonly execute: (\n params: ActionParams<TInput, TCtx, TErrors>,\n ) => Effect.Effect<ResultOf<TOutput, A>, E, R>;\n}\n\n/**\n * An action with an `authorize` step. It returns `false` to refuse the call:\n * `UNAUTHORIZED` (401) with no `ctx.user`, `FORBIDDEN` (403) with one. Where it\n * is given, `execute` can rely on `ctx.user`.\n */\nexport interface AuthorizedActionConfig<\n TInput extends AnySchema | undefined,\n TOutput extends AnySchema | undefined,\n TErrors extends ErrorDefinitions,\n TCtx,\n A,\n E,\n R,\n RA,\n> extends ActionConfigBase<TInput, TOutput, TErrors> {\n readonly authorize: (\n params: ActionParams<TInput, TCtx, TErrors>,\n ) => Effect.Effect<boolean, any, RA>;\n readonly execute: (\n params: ActionParams<TInput, Narrow<TCtx>, TErrors>,\n ) => Effect.Effect<ResultOf<TOutput, A>, E, R>;\n}\n\n/** What a plugin adds to the checks of the actions it registers. */\nexport interface PluginActionChecks {\n /** Checked instead of `output` at run time, while `output` stays the published contract (OpenAPI, client types). */\n readonly runtimeOutput?: AnySchema;\n /** Runs before the input is decoded, in-process and over HTTP. The issues it returns reject the input with a 400. */\n readonly checkInput?: (\n input: unknown,\n ) => ReadonlyArray<ValidationIssue> | undefined;\n}\n\n/** The declaration of any action, as the pipeline sees it. */\nexport type AnyActionConfig = ActionConfigBase<any, any, any> &\n PluginActionChecks & {\n readonly authorize?: (params: any) => Effect.Effect<boolean, any, any>;\n readonly execute: (params: any) => Effect.Effect<any, any, any>;\n /** At most `max` calls per `windowMs`, per key. */\n readonly rateLimit?: RateLimits | undefined;\n /** Whether a call may see the output's `Sensitive` fields. */\n readonly reveal?: Reveal<any> | undefined;\n /** What the audit row says, or `false` for none. */\n readonly audit?: false | AuditOptions | undefined;\n };\n\n/** How the input of a call arrived: as a JSON body, as a query string, or as a multipart form. In-process calls have none. */\nexport type Wire = \"json\" | \"query\" | \"form\";\n\n/** What `action.execute` takes: the input, and the context the caller carries. */\nexport interface ExecuteParams<TInput> {\n readonly input?: InputOf<TInput>;\n readonly ctx?: CallContext;\n /** Set by the HTTP server: `input` is raw JSON or query data, and the result is the JSON body. */\n readonly wire?: Wire;\n}\n\ntype RunArgs<TInput> = TInput extends AnySchema\n ? [input: TInput[\"Type\"], ctx?: CallContext]\n : [input?: undefined, ctx?: CallContext];\n\n/** A declared action: serve it with `brick`, or call it with `run`. */\nexport interface Action<\n TInput extends AnySchema | undefined,\n TOutput extends AnySchema | undefined,\n TErrors extends ErrorDefinitions,\n A,\n R,\n> {\n readonly name: string;\n readonly serviceName: string;\n readonly config: ActionConfigBase<TInput, TOutput, TErrors> &\n Pick<AnyActionConfig, \"authorize\" | \"execute\" | \"rateLimit\">;\n /**\n * Run the whole call in-process, as over HTTP: resolve the context, check the\n * input, authorize, execute, check the output. Fails with a `BrickError` or a\n * `ValidationError`; anything else that goes wrong is logged and becomes a 500.\n */\n run(\n ...args: RunArgs<TInput>\n ): Effect.Effect<ResultOf<TOutput, A>, BrickError | ValidationError, R>;\n execute(\n params: ExecuteParams<TInput>,\n ): Effect.Effect<ResultOf<TOutput, A>, BrickError | ValidationError, R>;\n /** Set on a webhook, for the server and OpenAPI. */\n readonly webhook?: {\n readonly maxBodyBytes: number;\n readonly replay: false | { readonly ttlMs: number };\n };\n /** Set on a webhook: answers a delivery, given the request. The result may be a `Response`. */\n readonly deliver?: (\n request: Request,\n ctx: CallContext,\n ) => Effect.Effect<unknown, BrickError | ValidationError, R>;\n}\n\n/** Any action, whatever its schemas. */\nexport type AnyAction = Action<any, any, any, any, any>;\n\n/** The error helpers of an action: the standard codes, then its own. */\nexport function errorHelpers<TErrors extends ErrorDefinitions>(\n errors?: TErrors,\n): ErrorHelpers<TErrors> {\n const helpers: Record<string, unknown> = {};\n for (const [code, definition] of Object.entries({\n ...STANDARD_ERRORS,\n ...errors,\n }) as [string, ErrorDefinition][])\n helpers[code] = (message?: string, details?: unknown) =>\n Effect.fail(\n new BrickError({\n code,\n message: message || definition.message,\n status: definition.status || 400,\n details,\n }),\n );\n return helpers as ErrorHelpers<TErrors>;\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: ReadonlyArray<ValidationIssue>,\n): ValidationError {\n return new ValidationError({\n message: `Validation failed for action '${action}' ${stage}`,\n status: stage === \"output\" ? 500 : 400,\n errors,\n });\n}\n\n/** A refused `authorize`: 401 without a user, 403 with one. */\nexport const deny = (action: string, user: unknown) =>\n Effect.fail(\n new BrickError({\n code: user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n message: `Access denied for action '${action}'`,\n status: user == null ? 401 : 403,\n }),\n );\n\n/** What a stage sees of a call. `input` is raw until the `input` stage replaces it with the decoded one. */\nexport interface Call {\n readonly input: unknown;\n readonly ctx: any;\n readonly error: ErrorHelpers<ErrorDefinitions>;\n readonly wire?: Wire | undefined;\n /** The id of the delivery, in a webhook that remembers the events it has handled. */\n readonly eventId?: string | undefined;\n}\n\n/** Continues a call with the next stage. */\nexport type Next = (call: Call) => Effect.Effect<unknown, unknown, any>;\n\n/** One step of the pipeline. It runs `next` to continue, or fails to stop the call. */\nexport interface Stage {\n readonly name: string;\n readonly run: (\n call: Call,\n next: Next,\n ) => Effect.Effect<unknown, unknown, any>;\n}\n\n/**\n * The stages of an action, outermost first: `dashboard` → `checkInput` →\n * `input` → `sensitive` → `rateLimit` → `authorize` → `audit` → `output` →\n * `execute`. This is where the order of a call is decided, as in core. A stage\n * a call has no use for is left out.\n */\nexport function stagesOf(\n config: AnyActionConfig,\n host: ActionHost,\n /** The action these stages run, so `setActionAudit` can change how it is recorded. */\n action?: () => object,\n): readonly Stage[] {\n const { name, input, authorize, execute, strict, checkInput, dashboard } =\n config;\n const output = config.runtimeOutput ?? config.output;\n const sensitive = sensitiveStage(\n { ...config, output },\n `Service '${host.name}' action '${name}'`,\n );\n const rateLimit = rateLimitStage(config, host);\n const audit = auditStage(\n config,\n host,\n action && (() => actionMeta(action()).audit),\n );\n const decode = input && {\n value: Schema.decodeUnknownEffect(Schema.toType(input)),\n json: Schema.decodeUnknownEffect(Schema.toCodecJson(input)),\n query: Schema.decodeUnknownEffect(\n Schema.toCodecArrayFromSingle(Schema.toCodecStringTree(input)),\n ),\n form: formDecoder(input),\n // No body at all: the schema's own decoding, so a default or a transformation still applies.\n absent: Schema.decodeUnknownEffect(input),\n };\n const check = output && {\n value: Schema.decodeUnknownEffect(Schema.toType(output)),\n json: Schema.encodeUnknownEffect(Schema.toCodecJson(output)),\n };\n const all = { errors: \"all\" } as const;\n // `strict` is about the input's keys: the output check still drops extra ones.\n const strictInput = {\n ...all,\n ...(strict && { onExcessProperty: \"error\" }),\n } as const;\n // Parse options reach every depth, so `true` decodes strictly, then forgives the nested extras it finds.\n const strictRoot = strict === true;\n const decodeInput = (call: Call) => {\n const run = (options: typeof strictInput | typeof all) =>\n decode![\n // No body is no value, as in core: decode it as one, not as JSON.\n call.input === undefined\n ? call.wire\n ? \"absent\"\n : \"value\"\n : (call.wire ?? \"value\")\n ](call.input, options);\n const reject = (\n error: Schema.SchemaError,\n options?: Parameters<typeof issuesOf>[2],\n ) =>\n Effect.fail(invalid(name, \"input\", issuesOf(error, call.input, options)));\n return run(strictInput).pipe(\n Effect.catch((error: Schema.SchemaError) =>\n !strictRoot\n ? reject(error)\n : run(all).pipe(\n Effect.matchEffect({\n onFailure: (plain: Schema.SchemaError) =>\n // No extra key at the root: the plain decode's failures are the whole story, and include checks the strict decode never reached.\n issuesOf(error, call.input, { extras: \"rootOnly\" }).length\n ? reject(error, { extras: \"ignoreNested\" })\n : reject(plain),\n onSuccess: (value) =>\n issuesOf(error, call.input, { extras: \"rootOnly\" }).length\n ? reject(error, { extras: \"rootOnly\" })\n : Effect.succeed(value),\n }),\n ),\n ),\n );\n };\n return [\n ...(dashboard\n ? [\n {\n name: \"dashboard\",\n run: (call, next) =>\n call.ctx.dashboard\n ? next(call)\n : Effect.fail(\n new BrickError({\n code: \"UNAUTHORIZED\",\n message: `Action '${name}' is only for the dashboard`,\n status: 401,\n }),\n ),\n } satisfies Stage,\n ]\n : []),\n ...(checkInput\n ? [\n {\n name: \"checkInput\",\n run: (call, next) => {\n const issues = checkInput(call.input);\n return issues?.length\n ? Effect.fail(invalid(name, \"input\", issues))\n : next(call);\n },\n } satisfies Stage,\n ]\n : []),\n ...(decode\n ? [\n {\n name: \"input\",\n run: (call, next) =>\n decodeInput(call).pipe(\n Effect.flatMap((decoded) => next({ ...call, input: decoded })),\n ),\n } satisfies Stage,\n ]\n : []),\n ...(sensitive ? [sensitive] : []),\n ...(rateLimit ? [rateLimit] : []),\n ...(authorize\n ? [\n {\n name: \"authorize\",\n run: (call, next) =>\n authorize(call).pipe(\n Effect.flatMap((allowed) =>\n allowed ? next(call) : deny(name, call.ctx.user),\n ),\n ),\n } satisfies Stage,\n ]\n : []),\n ...(audit ? [audit] : []),\n ...(check\n ? [\n {\n name: \"output\",\n run: (call, next) =>\n next(call).pipe(\n Effect.flatMap((result) =>\n omittingUndefined<unknown, Schema.SchemaError, never>(\n (value) => check[call.wire ? \"json\" : \"value\"](value, all),\n )(result).pipe(\n Effect.mapError((error: Schema.SchemaError) =>\n invalid(name, \"output\", issuesOf(error, result)),\n ),\n ),\n ),\n ),\n } satisfies Stage,\n ]\n : []),\n { name: \"execute\", run: (call) => execute(call) } satisfies Stage,\n ];\n}\n\n/** Runs a call through its stages. */\nexport const runStages = (stages: readonly Stage[], call: Call) =>\n stages.reduceRight<Next>(\n (next, stage) => (current) => stage.run(current, next),\n () => Effect.die(\"A call needs a final stage\"),\n )(call);\n\n/** What an action needs of the service it was declared on. */\nexport interface ActionHost {\n readonly name: string;\n readonly hasIdentity: boolean;\n readonly storage: KeyValueStorage | undefined;\n readonly database: DatabaseHandle<any, any> | undefined;\n readonly resolveContext: (\n call?: CallContext,\n ) => Effect.Effect<unknown, unknown, any>;\n}\n\n/** Drops a deferred action's cached stages, so the next call builds them again. */\nexport const RESET_STAGES = Symbol.for(\"brickkit.effect.action.resetStages\");\n\n/**\n * Makes the action. With `deferred`, its stages are built on the first call\n * instead of now, once a service has taken the action: those that depend on\n * the service (rate limits, audit) then see it.\n */\nexport function createAction(\n host: ActionHost,\n config: AnyActionConfig,\n deferred = false,\n): AnyAction {\n const own = () => action;\n let built = deferred ? undefined : stagesOf(config, host, own);\n const error = errorHelpers(config.errors);\n const execute = ({ input, ctx: callContext, wire }: ExecuteParams<any>) =>\n Effect.flatMap(host.resolveContext(callContext), (resolved) => {\n const stages = (built ??= stagesOf(config, host, own));\n const plugin = actionMeta(action).deps?.values;\n // A plugin's action runs with the plugin's deps, its file storages scoped to the caller's tenant.\n const ctx = plugin\n ? {\n ...(resolved as object),\n deps: scopeFiles(plugin, resolved as { user?: unknown }, host.name),\n }\n : resolved;\n return traceAction(\n host.name,\n config.name,\n wire !== undefined,\n runStages(stages, { input, ctx, error, wire }),\n );\n }).pipe(\n normalizeFailures({\n logger: callContext?.logger ?? defaultLogger,\n requestId: callContext?.requestId,\n }),\n );\n const action = {\n name: config.name,\n serviceName: host.name,\n config,\n run: (input?: unknown, ctx?: CallContext) => execute({ input, ctx }),\n execute,\n } as AnyAction;\n // A deferred action that ran before a service took it built its stages without the service.\n Object.defineProperty(action, RESET_STAGES, {\n value: () => void (built = deferred ? undefined : built),\n });\n return action;\n}\n","import { Schema } from \"effect\";\nimport type { Column } from \"drizzle-orm\";\nimport type { AnySchema } from \"../action\";\nimport { BrickError, STANDARD_ERRORS } from \"../errors\";\n\nconst isoPattern = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/** A failure thrown while building a query: `perform` turns it into the call's failure. */\nexport const reject = (\n code: \"BAD_REQUEST\" | \"NOT_FOUND\",\n message: string,\n): BrickError =>\n new BrickError({ code, message, status: STANDARD_ERRORS[code].status });\n\nexport const invalid = (message: string): never => {\n throw reject(\"BAD_REQUEST\", message);\n};\n\nexport type ColumnKind =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"date\"\n | \"bigint\"\n | \"json\"\n | \"array\"\n | \"buffer\"\n | \"custom\";\n\n/** What a column holds, from drizzle's `dataType` (`\"number int53\"`, `\"object date\"`). */\nexport function kindOf(column: Column): ColumnKind {\n const [type, constraint] = String(column.dataType).split(\" \");\n if ((column as { dimensions?: number }).dimensions) return \"array\";\n if (type === \"object\")\n return constraint === \"date\"\n ? \"date\"\n : constraint === \"json\"\n ? \"json\"\n : constraint === \"buffer\"\n ? \"buffer\"\n : \"custom\";\n return type as ColumnKind;\n}\n\n/** A row value as JSON carries it: dates as ISO strings, bigints as decimal strings. */\nexport function jsonValue(value: unknown): unknown {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === \"bigint\") return String(value);\n if (Array.isArray(value)) return value.map(jsonValue);\n if (value && typeof value === \"object\")\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, jsonValue(item)]),\n );\n return value;\n}\n\n/**\n * A JSON value as its column stores it: an ISO string becomes a Date for a date\n * column, an integer string a BigInt for a bigint column.\n *\n * @returns `undefined` when the string can't be a value of the column.\n */\nexport function columnValue(column: Column, value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n if (kindOf(column) === \"date\") {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? undefined : date;\n }\n if (kindOf(column) === \"bigint\")\n return /^-?\\d+$/.test(value) ? BigInt(value) : undefined;\n return value;\n}\n\n/** `columnValue`, with a string the column can't hold rejected as a bad request. */\nexport function databaseValue(column: Column, value: unknown): unknown {\n const stored = columnValue(column, value);\n return stored === undefined && value !== undefined\n ? invalid(`Invalid value for column '${column.name}'`)\n : stored;\n}\n\nconst NOT_JSON = new Set([\n \"Declaration\",\n \"BigInt\",\n \"Symbol\",\n \"UniqueSymbol\",\n \"Undefined\",\n \"Void\",\n]);\n\n/** @throws When the schema holds a value JSON can't carry. */\nexport function checkJsonSchema(schema: AnySchema): void {\n const seen = new Set<object>();\n const walk = (ast: any): void => {\n if (seen.has(ast)) return;\n seen.add(ast);\n if (NOT_JSON.has(ast._tag))\n throw new Error(\n `CRUD schema '${ast._tag}' is not JSON-safe; use string date-time or decimal strings`,\n );\n if (ast._tag === \"Suspend\") return walk(ast.thunk());\n for (const child of [\n ...(ast.propertySignatures?.map((p: any) => p.type) ?? []),\n ...(ast.indexSignatures?.map((i: any) => i.type) ?? []),\n ...(ast.elements ?? []),\n ...(ast.rest ?? []),\n ...(ast.types ?? []),\n ])\n walk(child);\n };\n walk(Schema.toType(schema).ast);\n}\n\n/** Column types that sort; all but `boolean` also take ordered filters. */\nexport const SORTABLE_TYPES = new Set<ColumnKind>([\n \"string\",\n \"number\",\n \"date\",\n \"bigint\",\n \"boolean\",\n]);\nexport const ORDERED_TYPES = new Set<ColumnKind>([\n \"string\",\n \"number\",\n \"date\",\n \"bigint\",\n]);\n/** Column types no value filter can compare. */\nexport const UNFILTERABLE_TYPES = new Set<ColumnKind>([\n \"json\",\n \"array\",\n \"buffer\",\n \"custom\",\n]);\n\n/** The JSON value of a column: what `read` shows and `create` and `update` take. */\nexport function columnSchema(column: Column): AnySchema {\n const c = column as Column & { enumValues?: string[] };\n let schema: AnySchema;\n if (c.enumValues?.length) schema = Schema.Literals(c.enumValues);\n else\n switch (kindOf(column)) {\n case \"string\":\n schema = Schema.String;\n break;\n case \"number\":\n schema = Schema.Finite;\n break;\n case \"boolean\":\n schema = Schema.Boolean;\n break;\n case \"date\":\n schema = Schema.String.check(Schema.isPattern(isoPattern));\n break;\n case \"bigint\":\n schema = Schema.String.check(Schema.isPattern(/^-?(?:0|[1-9][0-9]*)$/));\n break;\n case \"array\":\n schema = Schema.Array(Schema.Unknown);\n break;\n default:\n schema = Schema.Unknown;\n }\n return c.notNull ? schema : Schema.NullOr(schema);\n}\n\n/** The schema without its `null` member, for filter values. */\nexport function withoutNull(schema: AnySchema): AnySchema {\n const { ast } = schema as { ast: any };\n if (ast._tag !== \"Union\") return schema;\n const rest = ast.types.filter((member: any) => member._tag !== \"Null\");\n return rest.length === ast.types.length\n ? schema\n : (Schema.Union(\n rest.map((member: any) => Schema.make(member)),\n ) as unknown as AnySchema);\n}\n\n/** The schema of a resource's `:id`: a string on the wire for a number column, as paths carry it. */\nexport const idSchema = (column: Column, wire: boolean): AnySchema =>\n kindOf(column) === \"number\"\n ? wire\n ? Schema.FiniteFromString\n : Schema.Finite\n : Schema.String;\n\n/** An opaque list cursor: the orderBy it was made for, and the last row's sort values. */\nexport function encodeCursor(spec: string, values: unknown[]): string {\n return Buffer.from(JSON.stringify([spec, values.map(jsonValue)])).toString(\n \"base64url\",\n );\n}\n\n/** The sort values a client cursor holds, checked against the columns they bind to. */\nexport function decodeCursor(\n cursor: string,\n spec: string,\n keyset: { column: Column }[],\n): unknown[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(cursor, \"base64url\").toString());\n } catch {\n return invalid(\"Invalid cursor\");\n }\n if (\n !Array.isArray(parsed) ||\n parsed[0] !== spec ||\n !Array.isArray(parsed[1]) ||\n parsed[1].length !== keyset.length ||\n keyset.some(\n ({ column }, index) =>\n !Schema.is(Schema.toType(columnSchema(column)))(\n (parsed as unknown[][])[1][index],\n ),\n )\n )\n return invalid(\"Invalid cursor for this orderBy\");\n return parsed[1];\n}\n","import type { AnyAction } from \"./action\";\nimport {\n actionMeta,\n type ActionAccessInfo,\n type ActionAccessPolicy,\n} from \"./action-meta\";\n\nexport type { ActionAccessInfo, ActionAccessPolicy };\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 and the dashboard read what\n * 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: AnyAction | object): ActionAccessInfo {\n const meta = actionMeta(action).access;\n const configAuthorize =\n typeof (action as Partial<AnyAction>).config?.authorize === \"function\";\n if (!meta)\n return {\n hasAuthorize: configAuthorize,\n hasScope: false,\n policy: configAuthorize ? \"authorized\" : \"public\",\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 // The policy always agrees with the effective flags, as in core.\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. An action with\n * `audit: false` stays unrecorded either way.\n */\nexport function setActionAudit(action: object, mode: \"inline\" | \"none\"): void {\n actionMeta(action).audit = mode;\n}\n","import { Schema } from \"effect\";\nimport type { AnyAction, HttpMethod } from \"./action\";\nimport { actionMeta, type PluginRouteBinding } from \"./action-meta\";\nimport { DuplicateNameError } from \"./errors\";\nimport { fileFields } from \"./file-schema\";\nimport type { AnyService } from \"./service\";\n\n/** The route prefix of actions when the app sets none. */\nexport const DEFAULT_PREFIX = \"/api\";\n\n/** `orderBilling` becomes `order-billing`, `importCSV` becomes `import-csv`. Dots and dashes stay. */\nexport function kebabCase(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase();\n}\n\nconst PATH_PARAM = /:([^/]+)/g;\n\n/** `/p/:slug` becomes `/p/{slug}` for OpenAPI. */\nexport const toOpenApiPath = (path: string) => path.replace(PATH_PARAM, \"{$1}\");\n\n/** The parameter names of a route path: `/p/:slug` gives `[\"slug\"]`. */\nexport const pathParamNames = (path: string) =>\n [...path.matchAll(PATH_PARAM)].map((match) => match[1]!);\n\n/** Two routes collide when their keys are equal: the same method and path, whatever the parameter names. */\nexport const routeKey = (method: string, path: string) =>\n `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n\n/** Where callers send an action's input: the query (GET, DELETE) or the body. */\nexport const inputSource = (method: HttpMethod): \"query\" | \"body\" =>\n method === \"GET\" || method === \"DELETE\" ? \"query\" : \"body\";\n\n/** Where a plugin route mounts: under the app prefix, its service, or its resource. */\nexport function pluginRoutePath(\n binding: PluginRouteBinding,\n prefix: string,\n): string {\n const root = prefix.replace(/\\/$/, \"\");\n const owner =\n binding.scope === \"app\"\n ? root\n : `${root}/${kebabCase(binding.service)}${binding.scope === \"resource\" && binding.resource !== undefined ? `/${kebabCase(binding.resource)}` : \"\"}`;\n return `${owner}${binding.path === \"/\" ? \"\" : binding.path}` || \"/\";\n}\n\n/** What the app records about one action route, as `@brickkit/core`'s `RouteIR`, for the CLI and the dashboard. */\nexport interface RouteIR {\n readonly method: HttpMethod;\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 readonly inputSource: \"query\" | \"body\";\n /** The most bytes of a body, for an action with file fields (by `Content-Length`): the files' sizes and room for the form's other fields. Absent when it is not bounded. */\n readonly bodyLimit?: number;\n}\n\nexport interface RouteBinding {\n readonly service: AnyService;\n readonly action: AnyAction;\n}\n\n/** Room for the form's other fields and the multipart framing around the files. */\nconst FORM_FIELDS_AND_FRAMING_BYTES = 1024 * 1024;\n\n/** The most bytes a body may have, when the action takes files and every one has a size limit. */\nconst bodyLimitOf = (action: AnyAction): number | undefined => {\n const files = fileFields(action.config.input);\n return files.length && files.every(({ maxBytes }) => maxBytes !== undefined)\n ? files.reduce((sum, { maxBytes }) => sum + (maxBytes ?? 0), 0) +\n FORM_FIELDS_AND_FRAMING_BYTES\n : undefined;\n};\n\nconst describe = (\n service: AnyService,\n action: AnyAction,\n method: HttpMethod,\n path: string,\n plugin?: string,\n): RouteIR => ({\n method,\n path,\n service: service.name,\n action: action.name,\n kind: action.webhook ? \"webhook\" : \"action\",\n ...(plugin && { plugin }),\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: service.hasContext,\n authorize: typeof action.config.authorize === \"function\",\n inputSource: inputSource(method),\n ...(bodyLimitOf(action) !== undefined && { bodyLimit: bodyLimitOf(action)! }),\n});\n\n/**\n * The routes of the services, in a canonical order, as `@brickkit/core` names\n * them: `${prefix}/${service}/${action}` in kebab-case, or the action's `path`\n * under the service. An action whose route an earlier one holds is left out.\n *\n * @throws When two services share a name, or two actions of a service share a URL segment.\n */\nexport function describeRoutes(\n services: readonly AnyService[],\n prefix: string,\n): { routes: RouteIR[]; bindings: RouteBinding[] } {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick: prefix must start with '/'\");\n const names = new Set<string>();\n const candidates: [string, number, RouteBinding, RouteIR][] = [];\n for (const [index, service] of services.entries()) {\n if (names.has(service.name))\n throw new DuplicateNameError(\n `Brick: duplicate service \"${service.name}\" in brick()`,\n );\n names.add(service.name);\n const segments = new Set<string>();\n for (const action of service.listActions()) {\n const bound = actionMeta(action).route;\n if (bound) {\n if (!bound.enabled) continue;\n const full = pluginRoutePath(bound, prefix);\n candidates.push([\n routeKey(bound.method, full),\n index,\n { service, action },\n describe(service, action, bound.method, full, bound.plugin),\n ]);\n continue;\n }\n if (\n action.config.path === undefined &&\n !actionMeta(action).resourceAction\n ) {\n const segment = kebabCase(action.name);\n if (segments.has(segment))\n throw new DuplicateNameError(\n `Brick: duplicate name \"${segment}\" in service \"${service.name}\": two actions share the URL segment`,\n );\n segments.add(segment);\n }\n const { method, path: full } = ownRoute(action, service.name, prefix);\n if (!full.startsWith(\"/\"))\n throw new Error(`Brick: invalid route '${method} ${full}'`);\n candidates.push([\n routeKey(method, full),\n index,\n { service, action },\n describe(service, action, method, full),\n ]);\n }\n }\n const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);\n candidates.sort(\n (a, b) =>\n compare(a[0], b[0]) ||\n a[1] - b[1] ||\n compare(a[2].action.name, b[2].action.name),\n );\n const taken = new Set<string>();\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n for (const [key, , binding, route] of candidates) {\n if (taken.has(key)) {\n const other = routes.find(\n (claimed) => routeKey(claimed.method, claimed.path) === key,\n )!;\n if (route.kind === \"webhook\" || other.kind === \"webhook\")\n throw new DuplicateNameError(\n `Brick: '${route.service}.${route.action}' and '${other.service}.${other.action}' both claim '${key}', and a webhook cannot share its route`,\n );\n if (route.plugin || other.plugin)\n throw new DuplicateNameError(\n `Brick: duplicate plugin route '${route.method} ${route.path}'`,\n );\n continue;\n }\n taken.add(key);\n routes.push(route);\n bindings.push(binding);\n }\n return { routes, bindings };\n}\n\n/** Where an action is served: its method and path. */\nexport interface ActionRoute {\n method: HttpMethod;\n path: string;\n}\n\n/** The route of an action no plugin mounted: its own `method` and `path`, else `${prefix}/${service}/${action}`. */\nconst ownRoute = (\n action: AnyAction,\n service: string,\n prefix: string,\n): ActionRoute => {\n const { path, method = \"POST\" } = action.config;\n const base = `${prefix.replace(/\\/$/, \"\")}/${kebabCase(service)}`;\n const owned = actionMeta(action).resourceAction;\n if (owned) {\n // A resource action mounts under its resource: `/:id/<name>` for a record action.\n const under = `${base}/${kebabCase(owned.resource)}`;\n return {\n method,\n path:\n path === undefined\n ? `${under}${owned.record ? \"/:id\" : \"\"}/${kebabCase(owned.name)}`\n : `${under}${path === \"/\" ? \"\" : path}`,\n };\n }\n return {\n method,\n path:\n path === undefined\n ? `${base}/${kebabCase(action.name)}`\n : `${base}${path === \"/\" ? \"\" : path}`,\n };\n};\n\n/**\n * Where an action is served over HTTP: its method and its path\n * (`${prefix}/${service}/${action}` in kebab-case, the action's own `path`\n * under the service, or the route a plugin mounted it at).\n *\n * @param action - An action registered on a service.\n * @param prefix - The app's route prefix (default `/api`).\n * @returns `false` when a plugin switched the route off, otherwise the route.\n */\nexport function getActionRoute(\n action: AnyAction,\n prefix: string = DEFAULT_PREFIX,\n): ActionRoute | false {\n const bound = actionMeta(action).route;\n if (bound)\n return bound.enabled\n ? { method: bound.method, path: pluginRoutePath(bound, prefix) }\n : false;\n return ownRoute(action, action.serviceName, prefix);\n}\n\n/** The plugin and resource that own an action, for OpenAPI, introspection and the client contract. */\nexport function actionOwners(action: AnyAction): {\n plugin?: string;\n resource?: string;\n} {\n const { route, resourceAction } = actionMeta(action);\n const resource = route?.resource ?? resourceAction?.resource;\n return {\n ...(route && { plugin: route.plugin }),\n ...(resource && { resource }),\n };\n}\n\n/** Whether a schema describes an object, which an absent input then stands for as `{}`. */\nexport const isObjectSchema = (schema: unknown): boolean =>\n Schema.isSchema(schema) && schema.ast._tag === \"Objects\";\n","import { Schema } from \"effect\";\nimport type { AnySchema, ErrorDefinition, HttpMethod } from \"./action\";\nimport { getActionAccess } from \"./access\";\nimport type { ActionAccessPolicy } from \"./action-meta\";\nimport { actionOwners, getActionRoute, type RouteIR } from \"./routes\";\nimport type { AnyService } from \"./service\";\nimport type { SocketSchema } from \"./socket-types\";\n\n/** A socket of the app, as `definition.sockets` lists it: its schema, its service and its path. */\nexport type AppSocket = SocketSchema & { service: string; path: string };\n\nexport interface ActionSchema {\n name: string;\n /** Present only when this action has a route. */\n method?: HttpMethod;\n path?: string;\n serviceName: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n hasAuthorize: boolean;\n hasScope: boolean;\n accessPolicy: ActionAccessPolicy;\n /** The plugin that registered the action, and its resource. */\n plugin?: string;\n resource?: string;\n errors?: Readonly<Record<string, ErrorDefinition>>;\n /** The events the action says it emits (documentation only). */\n emits?: readonly string[];\n tags?: readonly string[];\n}\n\nexport interface ServiceSchema {\n name: string;\n /** The service options as JSON. The functions, such as `context`, are left out. */\n options: Record<string, unknown>;\n hasDatabase: boolean;\n databaseConfig?: {\n engine: \"sqlite\" | \"postgres\";\n tables: string[];\n };\n /** Present when the application lists its sockets. */\n sockets?: AppSocket[];\n actions: ActionSchema[];\n /** The events the service declares, with their payload schemas; absent without a catalog or plugin events. */\n events?: { name: string; schema: unknown; plugin?: string }[];\n}\n\n/** The shape of the app that `/_brick/services` serves, and the CLI's dashboard and client contract read. */\nexport interface ArchitectureSchema {\n version: string;\n services: ServiceSchema[];\n /** Present when the app has an `events` option. */\n events?: unknown;\n /** Every plugin installation, with its dashboard extension. */\n plugins?: readonly unknown[];\n}\n\n/** What `app.definition` holds of the app: the part the architecture is built from. */\nexport interface ArchitectureApplication {\n services: readonly AnyService[];\n /** The routes the app mounted. Without them, every action has its default route under `/api`. */\n routes?: readonly RouteIR[];\n sockets?: readonly AppSocket[];\n events?: unknown;\n plugins?: readonly unknown[];\n}\n\nconst jsonSchema = (schema: AnySchema) => {\n const { schema: root, definitions } = Schema.toJsonSchemaDocument(schema);\n return Object.keys(definitions).length\n ? { ...root, $defs: definitions }\n : root;\n};\n\n/**\n * The architecture of an app: each service with its database and its actions,\n * and the method and path of every action that has a route.\n */\nexport function 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.map((service) => {\n const routes = new Map(\n application.routes\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 return {\n name: service.name,\n options: {},\n hasDatabase: Boolean(service.database),\n ...(service.database && {\n databaseConfig: {\n engine: service.database.engine,\n tables: Object.keys(service.database.tables),\n },\n }),\n ...(service.hasCatalog || Object.keys(service.events).length\n ? {\n events: Object.values(service.events).map((ref) => ({\n name: ref.name,\n schema: jsonSchema(ref.schema),\n ...(ref.plugin ? { plugin: ref.plugin } : {}),\n })),\n }\n : {}),\n ...(application.sockets && {\n sockets: application.sockets.filter(\n (socket) => socket.service === service.name,\n ),\n }),\n actions: service.listActions().map((action) => {\n const { config } = action;\n const route = routes.get(action.name);\n const access = getActionAccess(action);\n return {\n name: action.name,\n serviceName: service.name,\n ...(route && { method: route.method, path: route.path }),\n description: config.description,\n ...(config.input && { inputSchema: jsonSchema(config.input) }),\n ...(config.output && { outputSchema: jsonSchema(config.output) }),\n hasAuthorize: access.hasAuthorize,\n hasScope: access.hasScope,\n accessPolicy: access.policy,\n ...actionOwners(action),\n errors: config.errors,\n emits: config.emits,\n tags: config.tags,\n } satisfies ActionSchema;\n }),\n } satisfies ServiceSchema;\n }),\n };\n}\n","import {\n exportArchitecture,\n type ArchitectureApplication,\n type ArchitectureSchema,\n} from \"./architecture\";\nimport { claimName, definitionSite } from \"./definition-site\";\nimport type { AnyService } from \"./service\";\n\n/** The services every `defineService` adds to, by name. */\nexport class ServiceRegistry {\n private _revision = 0;\n private services = new Map<string, AnyService>();\n private sites = new Map<string, string | undefined>();\n\n /** Changes whenever a definition does, so what was built from them (OpenAPI, the architecture) is rebuilt. */\n get revision(): number {\n return this._revision;\n }\n\n touch(): void {\n this._revision++;\n }\n\n /** @throws When a different file already registered a service with this name. */\n register(service: AnyService, 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): AnyService | undefined {\n return this.services.get(name);\n }\n\n has(name: string): boolean {\n return this.services.has(name);\n }\n\n list(): AnyService[] {\n return [...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 exportArchitecture(application ?? { services: this.list() });\n }\n}\n\nlet globalRegistry = new ServiceRegistry();\n\n/**\n * The registry every `defineService` adds to: `brick()` serves its services\n * when it is given none, and `useService` finds services by name in it.\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 { Effect } from \"effect\";\nimport type {\n Action,\n ActionConfig,\n AnySchema,\n AuthorizedActionConfig,\n ErrorDefinitions,\n HttpMethod,\n PluginActionChecks,\n} from \"./action\";\nimport type { PluginInstance } from \"./define-plugin\";\nimport type { AnyResource } from \"./resource\";\nimport type { AnyService, Service } from \"./service\";\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];\n/** What the user may do with a plugin's routes: switch all off, or each off, or move it. */\nexport type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =\n | false\n | Readonly<Record<string, false | { path?: string; scope?: S }>>;\n\n/** The `ctx` of a service's actions. */\nexport type ContextOf<S> = S extends Service<any, infer C, any> ? C : never;\n/** What the actions of a service need to run. */\nexport type RequirementOf<S> = S extends Service<any, any, infer R> ? R : never;\n\n/** What a plugin's raw HTTP endpoint receives. */\nexport interface PluginEndpointContext<C = any> {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n /** The JSON body, the text of any other body, or `undefined`. */\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Set the response's status and headers. */\n set: { status?: number; headers: Record<string, string> };\n ctx: C;\n}\n\ninterface PluginRouteOptions<S extends PluginRouteScope> {\n readonly path: string;\n readonly method: PluginRouteMethod;\n readonly scope?: S;\n}\n\nexport interface PluginRouteRegistrar<\n C = any,\n S extends PluginRouteScope = PluginRouteScope,\n TRequirement = never,\n> {\n /**\n * Register an action at a route. It is callable in-process whatever the\n * route's state, and is named `<resource>.<name>` on a resource.\n */\n readonly action: {\n <\n I extends AnySchema | undefined = undefined,\n O extends AnySchema | undefined = undefined,\n const TErrors extends ErrorDefinitions = {},\n A = never,\n E = never,\n R = never,\n RA = never,\n >(\n config: AuthorizedActionConfig<I, O, TErrors, C, A, E, R, RA> &\n PluginActionChecks &\n PluginRouteOptions<S>,\n ): Action<I, O, TErrors, A, R | RA | TRequirement>;\n <\n I extends AnySchema | undefined = undefined,\n O extends AnySchema | undefined = undefined,\n const TErrors extends ErrorDefinitions = {},\n A = never,\n E = never,\n R = never,\n >(\n config: ActionConfig<I, O, TErrors, C, A, E, R> &\n PluginActionChecks &\n PluginRouteOptions<S>,\n ): Action<I, O, TErrors, A, R | TRequirement>;\n };\n /**\n * Register a raw HTTP endpoint. Its Effect's result is the response: a\n * `Response` as it is, a string as text, `undefined` as an empty 200, and\n * anything else as JSON.\n */\n endpoint<E = never, R = never>(\n config: PluginRouteOptions<S> & {\n name: string;\n handler: (\n context: PluginEndpointContext<C>,\n ) => Effect.Effect<unknown, E, R>;\n summary?: string;\n description?: string;\n tags?: string[];\n },\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<S extends AnyService = AnyService> {\n service: S;\n routes: PluginRouteRegistrar<\n ContextOf<S>,\n \"app\" | \"service\",\n RequirementOf<S>\n >;\n}\nexport interface ResourcePluginContext<\n S extends AnyService = AnyService,\n R extends AnyResource = AnyResource,\n> {\n service: S;\n resource: R;\n routes: PluginRouteRegistrar<\n ContextOf<S>,\n PluginRouteScope,\n RequirementOf<S>\n >;\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 copy of this package. */\nexport const PLUGIN_KIND: unique symbol = Symbol.for(\n \"brickkit.effect.plugin.kind\",\n);\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.effect.plugin.commit\",\n);\nexport interface ServicePlugin<S extends AnyService, A> {\n readonly [PLUGIN_KIND]: \"service\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes<\"app\" | \"service\"> | undefined;\n readonly setup: (context: ServicePluginContext<S>) => A;\n}\nexport interface ResourcePlugin<\n S extends AnyService,\n R extends AnyResource,\n A extends object,\n> {\n readonly [PLUGIN_KIND]: \"resource\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes | undefined;\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 type { EventRef } from \"./events/catalog\";\n\n/** What the plugin system needs of a service beyond its public API. */\nexport interface ServiceInternals {\n /** Records the declarations; the returned function puts them back (a failed install's rollback). */\n snapshot(): () => void;\n /** Adds events a plugin declares to the catalog, as `service.events` lists them. */\n addEvents(refs: Readonly<Record<string, EventRef>>): void;\n}\n\nconst internals = new WeakMap<object, ServiceInternals>();\n\nexport const setInternals = (service: object, own: ServiceInternals) =>\n void internals.set(service, own);\n\nexport const internalsOf = (service: object): ServiceInternals =>\n internals.get(service)!;\n","import { Effect, Schema } from \"effect\";\nimport { HTTP_METHODS, createAction, type AnyAction } from \"./action\";\nimport { actionMeta, type PluginRouteBinding } from \"./action-meta\";\nimport type { CallContext } from \"./context\";\nimport { DuplicateNameError } from \"./errors\";\nimport {\n PLUGIN_COMMIT,\n PLUGIN_KIND,\n PLUGIN_ROUTE_SCOPES,\n type ContextOf,\n type PluginEndpointContext,\n type PluginRouteMethod,\n type PluginRouteRegistrar,\n type PluginRouteScope,\n type PluginRoutes,\n type ResourcePlugin,\n type ResourcePluginContext,\n type ServicePlugin,\n type ServicePluginContext,\n} from \"./plugin-types\";\nimport type { AnyResource, Resource } from \"./resource\";\nimport {\n DEFAULT_PREFIX,\n kebabCase,\n pathParamNames,\n pluginRoutePath,\n} from \"./routes\";\nimport type { AnyService } from \"./service\";\nimport { internalsOf } from \"./service-internals\";\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 * export const greeting = (salutation = \"Hello\") =>\n * defineServicePlugin({\n * name: \"example/greeting\",\n * setup({ routes }) {\n * const hello = routes.action({\n * name: \"hello\",\n * method: \"POST\",\n * path: \"/hello\",\n * input: Schema.Struct({ name: Schema.String }),\n * output: Schema.String,\n * execute: ({ input }) => Effect.succeed(`${salutation}, ${input.name}!`),\n * });\n * return { hello };\n * },\n * });\n *\n * const api = greeterService.use(greeting(\"Welcome\"));\n * await Effect.runPromise(api.hello.run({ name: \"Ada\" }));\n */\nexport function defineServicePlugin<\n S extends AnyService = AnyService,\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/**\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 AnyService = AnyService,\n R extends AnyResource = 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}\nexport function 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}\nexport function 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\ninterface RawBinding extends PluginRouteBinding {\n handler: (\n context: PluginEndpointContext<any>,\n ) => Effect.Effect<unknown, unknown, any>;\n summary?: string | undefined;\n description?: string | undefined;\n tags?: string[] | undefined;\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<AnyAction, PluginRouteBinding>;\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: AnyService): 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}\n\n/** A raw HTTP endpoint a plugin registered, ready to mount on the app. */\nexport interface PluginEndpoint {\n path: string;\n method: PluginRouteMethod;\n service: AnyService;\n plugin: string;\n summary?: string | undefined;\n description?: string | undefined;\n tags?: string[] | undefined;\n /** Resolves the service's context (from `call`), then runs the plugin's handler. */\n handler(\n context: Omit<PluginEndpointContext, \"ctx\">,\n call?: CallContext,\n ): Effect.Effect<unknown, unknown, any>;\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.\n */\nexport function getPluginEndpoints(\n service: AnyService,\n prefix = DEFAULT_PREFIX,\n): PluginEndpoint[] {\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: (context, call) =>\n Effect.flatMap(service.resolveContext(call), (ctx) =>\n binding.handler({ ...context, ctx }),\n ),\n }));\n}\n\n/**\n * Where a plugin mounted an action over HTTP, for OpenAPI and the typed client.\n *\n * @returns `undefined` when no plugin bound the action (it uses its own route),\n * `false` when the plugin's route was switched off, otherwise the route's\n * `path`, `method`, the `clientPath` the typed client uses, and the owning\n * `plugin` and `resource`.\n */\nexport function getPluginActionRoute(\n action: AnyAction,\n prefix = DEFAULT_PREFIX,\n) {\n const binding = actionMeta(action).route;\n if (!binding) return undefined;\n if (!binding.enabled) return false;\n return {\n path: pluginRoutePath(binding, prefix),\n method: binding.method,\n clientPath: binding.clientPath,\n plugin: binding.plugin,\n resource: binding.resource,\n };\n}\n\n/** Whether `input` is a schema with a field named `name`. */\nconst declares = (input: unknown, name: string) => {\n if (!Schema.isSchema(input)) return false;\n const ast = Schema.toType(input as Schema.Top).ast;\n return (\n ast._tag === \"Objects\" &&\n ast.propertySignatures.some((property) => property.name === name)\n );\n};\n\n/** The plugin that claimed `segment` under `resource`, if one did. */\nexport function segmentClaimant(\n service: AnyService,\n resource: object,\n segment: string,\n): string | undefined {\n return states.get(service)?.claims.get(resource)?.get(segment);\n}\n\n/**\n * Reserve a URL segment under `resource` for `plugin`, as a plugin's\n * `routes.claim` does, for code that is not installed as a plugin (`crud`).\n *\n * @throws When a resource action already has that segment.\n */\nexport function claimSegment(\n service: AnyService,\n resource: AnyResource,\n segment: string,\n plugin: string,\n): void {\n const state = stateOf(service);\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 info?.resource === resource.name && kebabCase(info.name) === segment;\n });\n if (taken)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${taken.name}\" in service \"${service.name}\": \"${segment}\" is a ${plugin} route`,\n );\n claims.set(segment, plugin);\n}\n\n/** Descriptor identity is scoped to the service or resource installation host. */\nexport function installPlugin(\n service: AnyService,\n resource: AnyResource | undefined,\n descriptor: ServicePlugin<any, any> | ResourcePlugin<any, any, any>,\n) {\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 = internalsOf(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<AnyAction>();\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 claimSegment(service, resource, segment, descriptor.name);\n };\n const bindingFor = (config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: PluginRouteScope;\n }): PluginRouteBinding => {\n if (!active)\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 (!declares(config.input, name))\n throw new Error(\n `Plugin action path parameter '${name}' must be declared in its input schema`,\n );\n // The public name is resource/operation only (`page.list`). The owning\n // plugin stays in the binding, so it never leaks into names, OpenAPI or\n // 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 { scope: _scope, path: _path, ...rest } = config;\n const action = createAction(service, { ...rest, name });\n actionMeta(action).route = binding;\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: AnyResource },\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 === \"object\" && value !== null && \"run\" in value) {\n const binding = state.actions.get(value as AnyAction);\n if (binding && ownedActions.has(value as AnyAction)) {\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 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\n/** Whether a plugin named `name` is installed on `host` (the service or a resource). */\nexport function hasPlugin(\n service: AnyService,\n host: object,\n name: string,\n): boolean {\n return (\n states.get(service)?.hosts.get(host)?.get(name)?.status === \"installed\"\n );\n}\n\n/** Every descriptor installed on the service or its resources, in install order per host. */\nexport function installedPlugins(service: AnyService): 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","/** 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/** 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\n/**\n * The `documentation` option as the folder it names (`{ dir }`), kept in\n * `app.definition` for the dashboard.\n *\n * @throws When it names no folder.\n */\nexport function 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","export interface RequestLoggingOptions {\n /** Turn it off without removing the option (default true). */\n enabled?: boolean;\n /** Where each line goes (default: the console). */\n logger?: (message: string) => void;\n}\n\n/** One log line: `METHOD /path → status (Nms)`. */\nexport const formatLog = (\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number,\n): string => `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n\n/**\n * The sink the options name: `undefined` when logging is off (`false`, or\n * `enabled: false`), else the `logger` or `console.log`.\n */\nexport const loggerOf = (\n options: boolean | RequestLoggingOptions,\n): ((message: string) => void) | undefined =>\n options === false || (options !== true && options.enabled === false)\n ? undefined\n : options === true\n ? console.log\n : (options.logger ?? console.log);\n\ntype Handler = (request: Request) => Response | Promise<Response>;\n\n/**\n * Wraps a fetch handler so each request is logged as\n * `METHOD /path → status (Nms)`: for the routes you serve yourself around\n * `app.fetch`, as `brick` logs its own. A handler that throws is logged as 500\n * and the error goes on.\n *\n * @example\n * Bun.serve({ fetch: requestLoggingPlugin()(app.fetch) });\n */\nexport function requestLoggingPlugin(\n options: RequestLoggingOptions = {},\n): <F extends Handler>(handler: F) => F {\n const log = loggerOf(options);\n return <F extends Handler>(handler: F) =>\n (log\n ? async (request: Request) => {\n const started = Date.now();\n const path = new URL(request.url).pathname;\n try {\n const response = await handler(request);\n log(\n formatLog(\n request.method,\n path,\n response.status,\n Date.now() - started,\n ),\n );\n return response;\n } catch (error) {\n log(formatLog(request.method, path, 500, Date.now() - started));\n throw error;\n }\n }\n : handler) as F;\n}\n","import { Schema } from \"effect\";\nimport type { ErrorDefinition } from \"./action\";\nimport { fileFields } from \"./file-schema\";\nimport {\n actionOwners,\n describeRoutes,\n pathParamNames,\n toOpenApiPath,\n} from \"./routes\";\nimport type { AnyService } from \"./service\";\n\n/** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */\nexport const OPENAPI_DEFAULTS = Object.freeze({\n title: \"Brick API\",\n version: \"1.0.0\",\n path: \"/openapi.json\",\n});\n\n/** What `generateOpenApiSpec` describes, and how the document names it. */\nexport interface OpenApiOptions {\n title?: string;\n version?: string;\n description?: string;\n prefix?: string;\n services: readonly AnyService[];\n}\n\ntype Json = Record<string, any>;\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' Schemas, their declared\n * errors, tags by service, and a bearer security scheme where an action\n * authorizes. `brick()` serves it at `/openapi.json`.\n */\nexport function generateOpenApiSpec({\n title = OPENAPI_DEFAULTS.title,\n version = OPENAPI_DEFAULTS.version,\n description = \"OpenAPI specification of the Brick services.\",\n prefix = \"/api\",\n services,\n}: OpenApiOptions): Json {\n const paths: Json = {};\n const schemas: Json = { ErrorEnvelope };\n let authorizes = false;\n const toJson = (schema: Schema.ConstraintCodec<any, any>) => {\n const { schema: root, definitions } = Schema.toJsonSchemaDocument(schema);\n const keys = new Map(Object.keys(definitions).map((name) => [name, name]));\n const rewrite = (value: any): any =>\n Array.isArray(value)\n ? value.map(rewrite)\n : value && typeof value === \"object\"\n ? Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n key,\n key === \"$ref\" && typeof item === \"string\"\n ? item.replace(/[^/]+$/, (name) => keys.get(name) ?? name)\n : rewrite(item),\n ]),\n )\n : value;\n // A name already holding another definition (or a schema pointing at one) gets a new name.\n for (let changed = true; changed;) {\n changed = false;\n for (const [name, definition] of Object.entries(definitions)) {\n const held = schemas[keys.get(name)!];\n if (held === undefined) continue;\n if (JSON.stringify(held) === JSON.stringify(rewrite(definition)))\n continue;\n let n = 2;\n while (\n `${name}${n}` in schemas ||\n [...keys.values()].includes(`${name}${n}`)\n )\n n++;\n keys.set(name, `${name}${n}`);\n changed = true;\n }\n }\n for (const [name, definition] of Object.entries(definitions))\n schemas[keys.get(name)!] ??= rewrite(definition);\n return rewrite(root) as Json;\n };\n const propertiesOf = (root: Json) => {\n const target = root.$ref\n ? schemas[String(root.$ref).split(\"/\").pop()!]\n : root;\n return {\n properties: (target?.properties ?? {}) as Json,\n required: (target?.required ?? []) as string[],\n };\n };\n\n // `service · resource` groups, by service, in the order their routes come.\n const groups = new Map<string, Map<string, string>>();\n const { routes, bindings } = describeRoutes(services, prefix);\n for (const [index, route] of routes.entries()) {\n const { action } = bindings[index]!;\n const { resource } = actionOwners(action);\n // Resource routes group under `service · resource`.\n const group = resource ? `${route.service} · ${resource}` : route.service;\n if (resource) {\n const own = groups.get(route.service) ?? new Map<string, string>();\n groups.set(route.service, own);\n own.set(\n group,\n `Routes of resource '${resource}' in service '${route.service}'`,\n );\n }\n const { input, output, errors, authorize } = action.config;\n const method = route.method.toLowerCase();\n const pathParams = pathParamNames(route.path);\n const responses: Json = {\n \"200\": {\n description: \"Successful response\",\n ...(output && {\n content: { \"application/json\": { schema: toJson(output) } },\n }),\n },\n };\n const alternatives = new Set<string>();\n const addError = (code: string, status: number, message: string) => {\n const key = `${status}:${code}`;\n if (alternatives.has(key)) return;\n alternatives.add(key);\n const schema = {\n allOf: [\n { $ref: \"#/components/schemas/ErrorEnvelope\" },\n {\n type: \"object\",\n properties: { code: { const: code }, status: { const: status } },\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 if (input) addError(\"VALIDATION_FAILED\", 400, \"Validation error\");\n if (authorize) {\n authorizes = true;\n addError(\"UNAUTHORIZED\", 401, \"Authentication required\");\n addError(\"FORBIDDEN\", 403, \"Access denied\");\n }\n const { webhook } = action;\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.rateLimit) {\n addError(\n \"RATE_LIMITED\",\n 429,\n \"Too many calls; retry after Retry-After seconds\",\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.dashboard === true)\n addError(\"UNAUTHORIZED\", 401, \"Only for the dashboard\");\n for (const [code, definition] of Object.entries(errors ?? {}) as [\n string,\n ErrorDefinition,\n ][])\n addError(code, definition.status || 400, definition.message || code);\n addError(\"INTERNAL_SERVER_ERROR\", 500, \"Internal server error\");\n if (output) addError(\"VALIDATION_FAILED\", 500, \"Output validation error\");\n\n const operation: Json = {\n operationId: `${route.service}_${action.name}_${method}`,\n summary: `${route.service}.${action.name}`,\n description:\n action.config.description ??\n `Execute action '${action.name}' on service '${route.service}'`,\n tags: [...new Set([group, ...(action.config.tags ?? [])])],\n ...(webhook && { \"x-brick-webhook\": true }),\n ...(route.plugin && { \"x-brick-plugin\": route.plugin }),\n ...(resource && { \"x-brick-resource\": resource }),\n responses,\n };\n const root = input && toJson(input);\n const { properties, required } = root\n ? propertiesOf(root)\n : { properties: {}, required: [] };\n // A file is not JSON: the document says binary, and the body is a multipart form.\n const files = input ? fileFields(input) : [];\n for (const { key, many, description } of files) {\n const file = {\n type: \"string\",\n format: \"binary\",\n ...(description && { description }),\n };\n const field =\n properties[key]?.anyOf?.find((item: Json) => item.type === \"array\") ??\n properties[key];\n properties[key] = many\n ? {\n type: \"array\",\n items: file,\n ...(field?.minItems !== undefined && { minItems: field.minItems }),\n ...(field?.maxItems !== undefined && { maxItems: field.maxItems }),\n }\n : file;\n }\n const parameters: Json[] = [...new Set(pathParams)].map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: properties[name] ?? { type: \"string\" },\n }));\n if (root && route.inputSource === \"query\") {\n for (const [name, schema] of Object.entries(properties))\n if (!pathParams.includes(name))\n parameters.push({\n name,\n in: \"query\",\n required: required.includes(name),\n schema,\n });\n } else if (root) {\n const body = pathParams.length\n ? {\n ...(root.$ref\n ? schemas[String(root.$ref).split(\"/\").pop()!]\n : root),\n properties: Object.fromEntries(\n Object.entries(properties).filter(\n ([n]) => !pathParams.includes(n),\n ),\n ),\n required: required.filter((n) => !pathParams.includes(n)),\n }\n : root;\n operation.requestBody = {\n required: true,\n content: {\n [files.length ? \"multipart/form-data\" : \"application/json\"]: {\n schema: body,\n },\n ...(webhook && {\n \"application/x-www-form-urlencoded\": { schema: body },\n }),\n },\n };\n }\n if (parameters.length) operation.parameters = parameters;\n if (authorize) operation.security = [{ bearerAuth: [] }];\n (paths[toOpenApiPath(route.path)] ??= {})[method] = operation;\n }\n\n // The declared events, by name, with their payload schemas.\n const events = Object.fromEntries(\n services.flatMap((service) =>\n Object.values(service.events).map((ref) => [\n ref.name,\n {\n service: service.name,\n payload: toJson(ref.schema),\n ...(ref.plugin ? { \"x-brick-plugin\": ref.plugin } : {}),\n },\n ]),\n ),\n );\n const spec = {\n openapi: \"3.1.0\",\n info: { title, version, description },\n paths,\n tags: services.flatMap((service) => [\n {\n name: service.name,\n description: `Actions exposed by '${service.name}' service`,\n },\n ...[...(groups.get(service.name) ?? [])].map(([name, description]) => ({\n name,\n description,\n })),\n ]),\n ...(Object.keys(events).length && { \"x-brick-events\": events }),\n components: {\n schemas,\n ...(authorizes && {\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 return JSON.parse(\n JSON.stringify(spec).replaceAll(\"#/$defs/\", \"#/components/schemas/\"),\n );\n}\n\nconst 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: { path: { type: \"string\" }, message: { type: \"string\" } },\n },\n },\n },\n};\n","import { Effect, Schema } from \"effect\";\nimport type { AnySchema } from \"../action\";\nimport { omittingUndefined } from \"../omit-undefined\";\nimport { sensitivePointer } from \"../sensitive\";\n\n/**\n * One declared event. Pass it to `defineListener({ on })` for a typed payload,\n * 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: AnySchema;\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/** The events of a catalog: one `EventRef` per entry. */\nexport type EventRefs<C extends Record<string, AnySchema>> = {\n readonly [K in keyof C & string]: EventRef<C[K][\"Type\"]>;\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 [\"object\", \"function\"].includes(typeof (value as EventRef).schema)\n );\n}\n\n/**\n * Declare the events a service emits, with the schema of each payload.\n * Listeners that take one of them get a typed payload, and `emitEvent` checks\n * the payload against its schema.\n *\n * @param service - The service the events belong to: their names are `<service>.<event>`.\n * @param catalog - A payload schema per event, named like `shipped` or `itemAdded`.\n * @throws When an event name is not a plain name, a payload is not a schema, or it marks a field `Sensitive`.\n * @example\n * const events = defineEvents(\"orders\", {\n * shipped: Schema.Struct({ id: Schema.String, trackingId: Schema.String }),\n * });\n * // events.shipped.name === \"orders.shipped\"\n */\nexport function defineEvents<const C extends Record<string, AnySchema>>(\n service: string,\n catalog: C,\n): EventRefs<C> {\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.isSchema(schema))\n throw new Error(\n `Event \"${service}.${key}\" needs a payload schema, such as Schema.Struct({ ... })`,\n );\n const at = sensitivePointer(schema);\n if (at)\n throw new Error(\n `Event \"${service}.${key}\" payload marks '${at}' 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) as EventRefs<C>;\n}\n\n/**\n * The payload as JSON, checked against the event's schema.\n *\n * @throws (as a defect) When the payload does not match.\n */\nexport const encodePayload = (ref: EventRef, payload: unknown) =>\n omittingUndefined((value) =>\n Schema.encodeUnknownEffect(Schema.toCodecJson(ref.schema))(value, {\n errors: \"all\",\n }),\n )(payload).pipe(\n Effect.catch((error) =>\n Effect.die(\n new Error(\n `Event \"${ref.name}\" payload does not match its schema: ${error.message}`,\n ),\n ),\n ),\n );\n\n/** The payload of a delivery, decoded with the event's schema. */\nexport const decodePayload = (ref: EventRef, payload: unknown) =>\n Schema.decodeUnknownEffect(Schema.toCodecJson(ref.schema))(payload);\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/** 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 declared a catalog at all. */\n readonly hasCatalog: boolean;\n listResources(): readonly { name: string }[];\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 * (a payload not yet encoded is checked against its schema, and returned as\n * JSON) or a CRUD event of one of the service's resources\n * (`<resource>.create|update|delete`).\n *\n * @param encoded - The payload is JSON already, from `encodePayload`.\n * @returns The payload to record.\n * @throws (as a defect) 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 encoded = false,\n): Effect.Effect<unknown> {\n const prefix = `${service.name}.`;\n const ref = name.startsWith(prefix)\n ? service.events[name.slice(prefix.length)]\n : undefined;\n if (ref)\n return encoded ? Effect.succeed(payload) : encodePayload(ref, payload);\n if (\n !service.hasCatalog ||\n isCrudEvent(\n name,\n service.listResources().map((resource) => resource.name),\n )\n )\n return Effect.succeed(payload);\n return Effect.die(\n new Error(\n `Event \"${name}\" is not in the event catalog of service \"${service.name}\" (declared: ${\n Object.values(service.events)\n .map((declared) => declared.name)\n .join(\", \") || \"none\"\n })`,\n ),\n );\n}\n","import { Cause, Context, Effect, Exit, Option } from \"effect\";\nimport type { SqlClient } from \"effect/sql/SqlClient\";\n\n/** What the outermost `runInTransaction` of a fiber collects for after its commit. */\nclass OpenTransaction extends Context.Service<\n OpenTransaction,\n { readonly commits: Effect.Effect<void, unknown, any>[] }\n>()(\"@brickkit/effect/OpenTransaction\") {}\n\n/**\n * Run `fn` in a database transaction: everything it writes through `db` or the\n * `tx` it is given is committed together when it returns, or undone if it\n * fails. A transaction opened inside `fn` (by `runInTransaction`, `emitEvent` or\n * drizzle's own `db.transaction`) joins it as a savepoint: a nested failure\n * undoes only the nested work, and the outer transaction decides the commit.\n * Both drivers keep one connection per transaction, so a write made elsewhere\n * waits for it.\n *\n * @param db - A drizzle database, such as `ctx.db`.\n * @param fn - Receives the transaction handle to run queries on.\n */\nexport const runInTransaction = <A, E, R>(\n db: any,\n fn: (tx: any) => Effect.Effect<A, E, R>,\n): Effect.Effect<A, E | unknown, R> =>\n Effect.gen(function* () {\n const outer = yield* Effect.serviceOption(OpenTransaction);\n if (Option.isSome(outer)) {\n const { commits } = outer.value;\n const queued = commits.length;\n return yield* (db.transaction(fn) as Effect.Effect<A, E, R>).pipe(\n // Work that was rolled back must not run its commit callbacks.\n Effect.tapCause(() =>\n Effect.sync(() => {\n commits.length = queued;\n }),\n ),\n );\n }\n const open = { commits: [] as Effect.Effect<void, unknown, any>[] };\n const result = yield* (db.transaction(fn) as Effect.Effect<A, E, R>).pipe(\n Effect.provideService(OpenTransaction, open),\n );\n // Every callback runs, even after one fails: the commit is done either way.\n const failures: Cause.Cause<unknown>[] = [];\n for (const commit of open.commits) {\n const exit = yield* Effect.exit(commit);\n if (Exit.isFailure(exit)) failures.push(exit.cause);\n }\n if (failures.length)\n return yield* Effect.failCause(\n failures.reduce((all, cause) => Cause.combine(all, cause)),\n );\n return result;\n });\n\n/**\n * Run `effect` once the transaction opened by `runInTransaction` has committed,\n * or now when there is none. It never runs when that transaction, or the\n * savepoint it was queued in, rolls back. A failure of it reaches the caller of\n * the outermost `runInTransaction`, after the commit and after the other\n * callbacks have run.\n */\nexport const onTransactionCommit = <E, R>(\n effect: Effect.Effect<void, E, R>,\n): Effect.Effect<void, E, R> => queueOnCommit(effect, () => true);\n\n/**\n * `onTransactionCommit`, unless `effect` is already queued. A savepoint that\n * rolled back took its queued copy away, so it is queued again.\n */\nexport const onTransactionCommitOnce = <E, R>(\n effect: Effect.Effect<void, E, R>,\n): Effect.Effect<void, E, R> =>\n queueOnCommit(effect, (commits) => !commits.includes(effect));\n\nconst queueOnCommit = <E, R>(\n effect: Effect.Effect<void, E, R>,\n wanted: (commits: Effect.Effect<void, unknown, any>[]) => boolean,\n): Effect.Effect<void, E, R> =>\n Effect.flatMap(\n Effect.serviceOption(OpenTransaction),\n Option.match({\n onNone: () => effect,\n onSome: ({ commits }) =>\n Effect.sync(() => {\n if (wanted(commits)) commits.push(effect);\n }),\n }),\n );\n\n/** The `@effect/sql` client of a drizzle Effect database, which owns its transactions. */\nconst clientOf = (db: any): SqlClient | undefined => {\n const client = db?.$client;\n return typeof client?.afterCommit === \"function\" ? client : undefined;\n};\n\n/**\n * Run `effect` once the outermost transaction on `db` has committed, whoever\n * opened it (`runInTransaction`, or the app's own drizzle `db.transaction`); at\n * once when none is open. Never when it rolls back. It runs without that\n * transaction, so what it forks never touches its connection.\n */\nexport const afterCommitOn = (\n db: unknown,\n effect: Effect.Effect<void>,\n): Effect.Effect<void> => clientOf(db)?.afterCommit(effect) ?? effect;\n\n/**\n * `effect` without the transaction `db`'s client has open in the fiber. A fiber\n * forked from inside a transaction inherits it, and fails once it ends (or\n * delivers from an uncommitted row while it is open).\n */\nexport const outsideTransaction = <A, E, R>(\n db: unknown,\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> => {\n const client = clientOf(db);\n return client\n ? (Effect.updateContext(\n effect,\n Context.omit(client.transactionService) as any,\n ) as Effect.Effect<A, E, R>)\n : effect;\n};\n","// The server half of the `brick.v1` socket wire contract, the same as\n// `@brickkit/core`'s protocol.ts so its socket client works against it.\n\n/** The subprotocol a Brick socket client offers and the server echoes. */\nexport const SOCKET_PROTOCOL = \"brick.v1\";\n/** `brick.token.<token>`: a bearer token carried as a subprotocol, since browsers can't set headers on a WebSocket. */\nexport const SOCKET_TOKEN_PROTOCOL = \"brick.token.\";\n\n/** Control messages, sent as frames whose event starts with `$`. */\nexport const SOCKET_CONTROL = {\n /** Client: `{room, since?}`. Server ack: `{room, ok, seq?}`. */\n join: \"$join\",\n /** Client: `{room}`. Server ack: `{room}`. */\n leave: \"$leave\",\n /** Server: `{room, reason?}`, the client was removed from a room. */\n left: \"$left\",\n /** Server: `{room, seq}`, history was lost; resume from `seq`. */\n gap: \"$gap\",\n /** Server: `{event, ...WireError}`, a handler raised a declared error. */\n error: \"$error\",\n} as const;\n\n/** Event names starting with `$` are reserved for control messages. */\nexport const isControlEvent = (event: string) => event.startsWith(\"$\");\n\nexport const SOCKET_CLOSE = {\n normal: 1000,\n /** The server is draining: a raw socket still open at the drain deadline. */\n goingAway: 1001,\n unsupportedData: 1003,\n invalidPayload: 1007,\n policy: 1008,\n tooLarge: 1009,\n serverError: 1011,\n tryAgainLater: 1013,\n} as const;\n\nexport const SOCKET_MAX_BYTES = 64 * 1024;\nexport const SOCKET_BUFFER_BYTES = 1024 * 1024;\n/** How many messages of one connection may wait for their handlers. */\nexport const SOCKET_BUFFER_MESSAGES = 32;\nconst ROOM_MAX_BYTES = 200;\n/** The length of a sequence's signature: base64url of an HMAC, cut short. */\nexport const SOCKET_SIGNATURE_LENGTH = 22;\n\nexport const byteLength = (value: string) =>\n new TextEncoder().encode(value).byteLength;\n\nexport const encodeFrame = (event: string, data: unknown) =>\n JSON.stringify({ event, data });\n\n/** Adds the room and signed sequence to an encoded frame of a socket with replay. */\nexport const replayFrame = (frame: string, room: string, seq: string) =>\n `${frame.slice(0, -1)},\"room\":${JSON.stringify(room)},\"seq\":${JSON.stringify(seq)}}`;\n\n/** The longest signed sequence: two 20-digit numbers and a signature. */\nconst LONGEST_SEQ = `${\"9\".repeat(20)}-${\"9\".repeat(20)}.${\"x\".repeat(SOCKET_SIGNATURE_LENGTH)}`;\n\n/** Bytes an emit to `room` gains when replay adds its `room` and signed `seq` on delivery. */\nexport const replayHeadroom = (room: string) =>\n byteLength(replayFrame(\"{}\", room, LONGEST_SEQ)) - 2;\n\nexport function isSocketEnvelope(\n value: unknown,\n): value is { event: string; data: unknown } {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n \"event\" in value &&\n typeof value.event === \"string\" &&\n \"data\" in value &&\n Object.keys(value).length === 2\n );\n}\n\n/** `prefix:value`, at most 200 bytes, without control characters. */\nexport function isSocketRoom(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n // eslint-disable-next-line no-control-regex\n /^[A-Za-z][\\w-]*:[^\\u0000-\\u001f\\u007f]+$/.test(value) &&\n byteLength(value) <= ROOM_MAX_BYTES\n );\n}\n\n/** A replay sequence: `<number>-<number>`, the shape of a Redis stream id, then `.` and the server's signature for its room. */\nconst SIGNED_SEQ = new RegExp(\n `^\\\\d{1,20}-\\\\d{1,20}\\\\.[\\\\w-]{${SOCKET_SIGNATURE_LENGTH}}$`,\n);\n\nexport const isSocketSeq = (value: unknown): value is string =>\n typeof value === \"string\" && SIGNED_SEQ.test(value);\n\nexport const signSeq = (seq: string, signature: string) =>\n `${seq}.${signature}`;\n\n/** The sequence and signature of a signed sequence. */\nexport const splitSeq = (signed: string) =>\n signed.split(\".\") as [seq: string, signature: string];\n","import { Effect, Schema } from \"effect\";\nimport { omittingUndefined } from \"./omit-undefined\";\nimport { SOCKET_MAX_BYTES, byteLength, encodeFrame } from \"./socket-protocol\";\nimport type { SocketSchemas } from \"./socket-types\";\n\n/** The JSON codecs of a socket's events: payloads are decoded from and encoded to JSON, as an action's are on the wire. */\nexport function socketCodecs(schemas: SocketSchemas) {\n const codecs = new Map(\n Object.entries(schemas).map(([event, schema]) => {\n const json = Schema.toCodecJson(schema);\n return [\n event,\n {\n decode: Schema.decodeUnknownEffect(json),\n encode: Schema.encodeUnknownEffect(json),\n },\n ] as const;\n }),\n );\n return {\n /** The payload a client sent, decoded; fails when `event` is unknown or the payload is invalid. */\n decode: (event: string, data: unknown) => {\n const codec = codecs.get(event);\n return codec\n ? codec.decode(data).pipe(Effect.mapError(() => undefined))\n : Effect.fail(undefined);\n },\n /**\n * The frame for an output message. Dies with an `Error` when the event is\n * unknown, the payload is invalid, or the frame is over the size limit.\n */\n frame: (event: string, data: unknown) => {\n const codec = codecs.get(event);\n const refuse = (message: string) => Effect.die(new Error(message));\n if (!codec) return refuse(\"Invalid socket output\");\n return Effect.gen(function* () {\n const json = yield* omittingUndefined(codec.encode)(data).pipe(\n Effect.catch(() => refuse(\"Invalid socket output\")),\n );\n const frame = encodeFrame(event, json);\n if (byteLength(frame) > SOCKET_MAX_BYTES)\n return yield* refuse(\"Socket output too large\");\n return frame;\n });\n },\n };\n}\n","import { Data, Effect } from \"effect\";\nimport { errorHelpers } from \"./action\";\nimport { kebabCase } from \"./routes\";\nimport { onTransactionCommit } from \"./events/transaction\";\nimport { socketCodecs } from \"./socket-schema\";\nimport {\n SOCKET_MAX_BYTES,\n byteLength,\n isControlEvent,\n isSocketRoom,\n replayHeadroom,\n} from \"./socket-protocol\";\nimport type {\n BrickSocketHandle,\n BrickSocketSender,\n RegisteredSocket,\n SocketBroker,\n SocketBrokerMessage,\n SocketConfig,\n SocketPayloads,\n SocketSchemas,\n SocketWire,\n} from \"./socket-types\";\n\n/** A socket refused the call: the upgrade, a message, or a join with a bad room. The connection is closed with 1008. */\nexport class SocketDenied extends Data.TaggedError(\"SocketDenied\") {}\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: swept,\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\n/**\n * The socket a service declares. `resolve` builds the `ctx` of a request, and\n * runs again before every message so each one sees fresh identity.\n */\nexport function defineServiceSocket<\n I extends SocketSchemas,\n O extends SocketSchemas,\n Ctx,\n TErrors extends Record<string, { message: string; status?: number }>,\n>(\n service: string,\n config: SocketConfig<I, O, Ctx, TErrors>,\n resolve: (request: Request) => Effect.Effect<Ctx, unknown, any>,\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 const inputs = socketCodecs(input);\n const outputs = socketCodecs(output);\n const typed = (wire: SocketWire): BrickSocketSender<any> => ({\n send: (event, payload) =>\n Effect.flatMap(outputs.frame(event, payload), (frame) =>\n Effect.sync(() => wire.send(frame)),\n ),\n close: () => Effect.sync(() => wire.close()),\n });\n const error = errorHelpers(config.errors);\n const context = (request: Request) =>\n Effect.gen(function* () {\n const ctx = yield* resolve(request);\n if (config.authorize && !(yield* config.authorize({ ctx })))\n return yield* 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[]) =>\n Effect.sync(() => {\n for (const broker of brokers)\n for (const message of messages) broker.publish(message, replay);\n });\n const handle: BrickSocketHandle<any> = {\n name: config.name,\n emit: (rooms, event, payload, options) =>\n Effect.gen(function* () {\n const unique = [\n ...new Set(typeof rooms === \"string\" ? [rooms] : rooms),\n ];\n const topics = unique.map(topic);\n const frame = yield* outputs.frame(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 return yield* Effect.die(new Error(\"Socket output too large\"));\n const send = publish(\n topics.map((topic) => ({ type: \"emit\", topic, frame })),\n );\n yield* options?.after === undefined ? send : onTransactionCommit(send);\n }),\n kick: (room, options = {}) =>\n Effect.suspend(() =>\n publish([\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 ),\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 errors: config.errors && { ...config.errors },\n allowedOrigins: config.allowedOrigins && [...config.allowedOrigins],\n allowMissingOrigin: config.allowMissingOrigin,\n maxRooms,\n replay,\n brokers,\n topicPrefix,\n topic,\n handle,\n connect: (request) =>\n Effect.gen(function* () {\n const initial = yield* context(request);\n const rooms = [\n ...new Set(config.rooms ? yield* config.rooms({ ctx: initial }) : []),\n ];\n rooms.forEach(topic);\n if (rooms.length > maxRooms)\n return yield* Effect.die(new Error(\"Too many socket rooms\"));\n return {\n rooms,\n open: (wire) =>\n config.open\n ? config.open({ ctx: initial, socket: typed(wire) })\n : Effect.void,\n message: (event, data, wire) =>\n Effect.gen(function* () {\n const payload = yield* inputs\n .decode(event, data)\n .pipe(Effect.mapError(() => new SocketDenied()));\n const ctx = yield* context(request);\n if (!wire.isOpen) return;\n // The event was decoded above, so it has a handler.\n yield* handlers[event as keyof I]!({\n input: payload,\n ctx,\n socket: typed(wire) as BrickSocketSender<SocketPayloads<O>>,\n error,\n });\n }),\n join: (room) =>\n Effect.gen(function* () {\n const ctx = yield* context(request);\n return config.join ? yield* config.join({ ctx, room }) : false;\n }),\n close: (wire, code, reason) =>\n config.close\n ? config.close({\n ctx: initial,\n socket: typed(wire),\n code,\n reason,\n })\n : Effect.void,\n };\n }),\n };\n}\n\n/** The route of a socket: `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */\nexport function socketPath(\n prefix: string,\n service: string,\n {\n schema: { name, path },\n }: { schema: { name: string; path?: string | undefined } },\n): string {\n const base = `${prefix.replace(/\\/$/, \"\")}/${kebabCase(service)}`;\n return path === undefined\n ? `${base}/${kebabCase(name)}`\n : `${base}${path === \"/\" ? \"\" : path}`;\n}\n","import { Cause, Effect, Exit, Result, Schema, Tracer } from \"effect\";\nimport { createLogger } from \"./context\";\nimport type { AnySchema } from \"./action\";\nimport { socketPath } from \"./socket\";\nimport {\n SOCKET_BUFFER_BYTES,\n SOCKET_CLOSE,\n SOCKET_MAX_BYTES,\n} from \"./socket-protocol\";\nimport type { SocketRunner } from \"./socket-server\";\nimport { ATTR, SPAN } from \"./telemetry-names\";\nimport { startSocketSpan, type SocketSpan } from \"./telemetry\";\n\n/** Frames one connection may have waiting for its handlers. */\nconst RAW_QUEUE_FRAMES = 1024;\n/** After the drain deadline closes what is left with 1001, time for their `close` callbacks. */\nconst DRAIN_CLOSE_GRACE_MS = 1000;\n\nexport type RawSocketPhase = \"open\" | \"message\" | \"close\" | \"preAuth\";\n\n/** What a frame decodes to: `schema` gives its `Type`, `parse` its return type, neither the raw frame. */\nexport type RawSocketMessage<\n S extends AnySchema | undefined,\n Parsed,\n> = S extends AnySchema\n ? S[\"Type\"]\n : [Parsed] extends [never]\n ? string | Uint8Array\n : Parsed;\n\nexport interface RawSocketFrame<Msg> {\n data: Msg;\n}\n\n/** The connection a raw socket callback holds. Each method is an Effect that does nothing until it runs. */\nexport interface RawSocket<State> {\n readonly id: string;\n /** The upgrade request. */\n readonly request: Request;\n readonly authenticated: boolean;\n /** Per-connection, mutable. */\n state: State;\n /** `false` if the frame was dropped (backpressure) or the socket is closed. */\n send(data: string | Uint8Array): Effect.Effect<boolean>;\n close(code?: number, reason?: string): Effect.Effect<void>;\n /** Ends the `preAuth` stage and cancels its deadline; `patch` is merged into `state`. */\n authenticate(patch?: Partial<State>): Effect.Effect<void>;\n /** Adds a span link, for a trace id that only arrives in a frame. */\n link(traceparent: string): Effect.Effect<void>;\n}\n\n/** Returned by `service.rawSocket()`. Sums across the apps the route is mounted in. */\nexport interface RawSocketHandle {\n readonly live: number;\n readonly max?: number;\n}\n\ntype Callback<A> = Effect.Effect<A, unknown, any>;\n\n/** The declaration of `service.rawSocket`. Every callback returns an Effect, and may need the services of the app's `layer`. */\nexport interface RawSocketConfig<\n Ctx,\n State,\n Msg,\n S extends AnySchema | undefined = undefined,\n Parsed = never,\n> {\n readonly name: string;\n /** A static path relative to its service; default `/<kebab-name>`. */\n readonly path?: string;\n readonly description?: string;\n /** Upgrade gate. Runs with the context resolved from the upgrade request; `false` answers 403. */\n readonly authorize?: (params: {\n ctx: Ctx;\n request: Request;\n }) => Callback<boolean>;\n /** The initial per-connection `socket.state` (default `{}`). */\n readonly state?: (params: { ctx: Ctx; request: Request }) => Callback<State>;\n /**\n * Browser origins allowed. By default a request with an `Origin` header is\n * refused (403) and one without, as third-party servers send, is accepted.\n */\n readonly allowedOrigins?: readonly string[];\n /** Connections at once; an upgrade over the cap answers 503. */\n readonly maxConnections?: number;\n /** Per frame, default 64 KiB; over it closes 1009. */\n readonly maxPayloadBytes?: number;\n /** JSON text frames, decoded with it (invalid: 1007; binary: 1003). Not with `parse`. */\n readonly schema?: S;\n /** Decodes each frame; throwing closes 1007. Not with `schema`. */\n readonly parse?: (raw: string | Uint8Array) => Parsed;\n /**\n * Start unauthenticated: until `socket.authenticate()`, frames go only to\n * `preAuth.message`. Not authenticated within `timeoutMs` closes 1008.\n */\n readonly preAuth?: {\n readonly timeoutMs: number;\n readonly message: (\n params: RawSocketFrame<Msg> & { ctx: Ctx; socket: RawSocket<State> },\n ) => Callback<void>;\n };\n readonly open?: (params: {\n ctx: Ctx;\n socket: RawSocket<State>;\n }) => Callback<void>;\n readonly message: (\n params: RawSocketFrame<Msg> & { ctx: Ctx; socket: RawSocket<State> },\n ) => Callback<void>;\n readonly close?: (params: {\n ctx: Ctx;\n socket: RawSocket<State>;\n code: number;\n reason: string;\n }) => Callback<void>;\n /** A callback failed. Default: log with `ctx.logger` and close 1011. Succeed with `\"continue\"` to stay open. */\n readonly error?: (params: {\n ctx: Ctx;\n socket: RawSocket<State>;\n error: unknown;\n phase: RawSocketPhase;\n }) => Callback<void | \"continue\" | \"close\">;\n}\n\nexport interface RawSocketStats {\n draining: boolean;\n live: number;\n max?: number;\n routes: {\n service: string;\n name: string;\n path: string;\n live: number;\n max?: number;\n }[];\n}\n\nexport interface RegisteredRawSocket {\n /** `name` and `path` only: a raw route is not described to clients. */\n readonly schema: { name: string; path?: string | undefined };\n readonly config: RawSocketConfig<any, any, any, any, any>;\n readonly maxPayloadBytes: number;\n readonly max?: number | undefined;\n /** One entry per app the route is mounted in. */\n readonly mounts: Set<{ live: number }>;\n readonly handle: RawSocketHandle;\n /** The frame a client sent, decoded; `undefined` when `schema` rejects it. */\n readonly decode:\n | ((value: unknown) => { value: unknown } | undefined)\n | undefined;\n /** The deps of the plugin that declared the route, when one did. */\n deps?: Readonly<Record<string, unknown>>;\n resolve(request: Request): Effect.Effect<any, unknown, any>;\n}\n\nexport function defineRawSocket(\n config: RawSocketConfig<any, any, any, any, any>,\n resolve: (request: Request) => Effect.Effect<any, unknown, any>,\n): RegisteredRawSocket {\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 if (config.schema && config.parse)\n throw new Error(\"A raw socket takes a schema or a parse, not both\");\n const positive = (value: number | undefined, what: string) => {\n if (value !== undefined && !(Number.isInteger(value) && value > 0))\n throw new Error(`Raw socket ${what} must be a positive integer`);\n };\n positive(config.maxConnections, \"maxConnections\");\n positive(config.maxPayloadBytes, \"maxPayloadBytes\");\n if (\n config.preAuth &&\n !(config.preAuth.timeoutMs > 0 && Number.isFinite(config.preAuth.timeoutMs))\n )\n throw new Error(\"Raw socket preAuth.timeoutMs must be a positive number\");\n const decodeJson =\n config.schema &&\n Schema.decodeUnknownOption(Schema.toCodecJson(config.schema as AnySchema));\n const mounts = new Set<{ live: number }>();\n return {\n schema: { name: config.name, path: config.path },\n config,\n maxPayloadBytes: config.maxPayloadBytes ?? SOCKET_MAX_BYTES,\n max: config.maxConnections,\n mounts,\n handle: {\n get live() {\n let live = 0;\n for (const mount of mounts) live += mount.live;\n return live;\n },\n max: config.maxConnections,\n },\n decode:\n decodeJson &&\n ((value) => {\n const decoded = decodeJson(value);\n return decoded._tag === \"Some\" ? { value: decoded.value } : undefined;\n }),\n resolve,\n };\n}\n\ninterface RawData {\n mounted: {\n open(ws: Bun.ServerWebSocket<RawData>): void;\n message(ws: Bun.ServerWebSocket<RawData>, value: string | Buffer): void;\n close(\n ws: Bun.ServerWebSocket<RawData>,\n code: number,\n reason: string,\n ): Promise<void>;\n };\n connection: Connection;\n}\n\ninterface Connection {\n socket: RawSocket<any>;\n ctx: any;\n span: SocketSpan | undefined;\n ws?: Bun.ServerWebSocket<RawData>;\n closed: boolean;\n tail: Promise<void>;\n frames: number;\n queued: number;\n messages: number;\n bytes: number;\n /** The first thing a callback failed with: it marks the span as an error. */\n failure?: { error: unknown };\n deadline?: ReturnType<typeof setTimeout>;\n /** Closes the connection now: what the Effect `socket.close` does. */\n close(code?: number, reason?: string): void;\n}\n\n/** What the mounted routes offer `app.listen` and the app. */\nexport interface RawSocketMount {\n /** Every route's path: they join the duplicate and conflict checks of the sockets. */\n readonly paths: readonly string[];\n /** The largest `maxPayloadBytes` of the routes, at least 64 KiB: Bun's limit is the server's. */\n readonly maxPayloadBytes: number;\n matches(request: Request): boolean;\n /** Upgrades the request, or answers why it can't be. Resolves to `undefined` once upgraded. */\n upgrade(\n request: Request,\n server: Bun.Server<any>,\n ): Promise<Response | undefined>;\n drain(timeoutMs?: number): Promise<void>;\n stats(): RawSocketStats;\n /** Forgets the app in each route's `live` count. */\n dispose(): void;\n}\n\n/** Turns a failed run into what its callbacks threw: the typed failure, else the defect. */\nfunction thrown(cause: Cause.Cause<unknown>): unknown {\n const found = Cause.findError(cause);\n if (Result.isSuccess(found)) return found.success;\n const defect = Cause.findDefect(cause);\n return Result.isSuccess(defect) ? defect.success : Cause.squash(cause);\n}\n\n/**\n * Mounts the raw routes of the services: each answers a plain WebSocket upgrade\n * (no subprotocol, no `brick.v1`) and hands its callbacks the frames exactly as\n * the client sent them. One context is resolved at upgrade and reused for every\n * callback.\n */\nexport function mountRawSockets(options: {\n services: readonly {\n name: string;\n listRawSockets(): RegisteredRawSocket[];\n }[];\n prefix: string;\n run: SocketRunner;\n telemetry: boolean;\n drainTimeoutMs: number;\n}): RawSocketMount {\n const { run, telemetry } = options;\n // Read on the first upgrade, so mounting does not build the app's layer.\n let tracer: Promise<Tracer.Tracer | undefined> | undefined;\n const appTracer = () =>\n (tracer ??= run(Effect.tracer).then((exit) =>\n Exit.isSuccess(exit) ? exit.value : undefined,\n ));\n const routes = options.services.flatMap((service) =>\n service.listRawSockets().map((definition) => ({\n service: service.name,\n path: socketPath(options.prefix, service.name, definition),\n definition,\n live: 0,\n pending: 0,\n connections: new Set<Connection>(),\n })),\n );\n const byPath = new Map<string, (typeof routes)[number]>();\n for (const route of routes) {\n if (byPath.has(route.path))\n throw new Error(`Brick: duplicate socket route '${route.path}'`);\n byPath.set(route.path, route);\n }\n let draining = false;\n const quiet = new Set<() => void>();\n const total = () => routes.reduce((n, r) => n + r.live + r.pending, 0);\n const settled = () => {\n if (!total()) for (const wake of quiet) wake();\n };\n /** Resolves once no connection is open or upgrading, or after `ms`. */\n const empty = (ms: number) =>\n total() === 0\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n quiet.delete(done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n quiet.add(done);\n });\n let drained: Promise<void> | undefined;\n const drain = (timeoutMs = options.drainTimeoutMs) =>\n (drained ??= (async () => {\n draining = true;\n await empty(timeoutMs);\n for (const route of routes)\n for (const connection of route.connections)\n connection.close(SOCKET_CLOSE.goingAway, \"Server is shutting down\");\n await empty(DRAIN_CLOSE_GRACE_MS);\n })());\n const stats = (): RawSocketStats => {\n const capped = routes.length > 0 && routes.every((r) => r.definition.max);\n return {\n draining,\n live: routes.reduce((n, r) => n + r.live, 0),\n ...(capped\n ? { max: routes.reduce((n, r) => n + r.definition.max!, 0) }\n : {}),\n routes: routes.map((r) => ({\n service: r.service,\n name: r.definition.schema.name,\n path: r.path,\n live: r.live,\n ...(r.definition.max ? { max: r.definition.max } : {}),\n })),\n };\n };\n for (const route of routes) route.definition.mounts.add(route);\n\n const refuse = (status: number, text: string) =>\n new Response(text, {\n status,\n headers: status === 503 ? { \"Retry-After\": \"1\" } : undefined,\n });\n\n /** The handlers Bun calls for a connection of `route`, through `ws.data.mounted`. */\n const mountRoute = (route: (typeof routes)[number]) => {\n const { service, path, definition } = route;\n const { config } = definition;\n const name = definition.schema.name;\n const origins = config.allowedOrigins ?? [];\n const fallbackLogger = createLogger();\n\n const traced = <A, E, R>(\n conn: Connection,\n effect: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E, R> =>\n conn.span\n ? Effect.withParentSpan(effect, conn.span.span, {\n captureStackTrace: false,\n })\n : effect;\n\n /** A callback failed: the `error` hook decides, and by default the connection closes with 1011. */\n const failed = async (\n conn: Connection,\n at: RawSocketPhase,\n cause: Cause.Cause<unknown>,\n ) => {\n const error = thrown(cause);\n conn.failure ??= { error };\n const logger = conn.ctx?.logger ?? fallbackLogger;\n let outcome: unknown;\n try {\n if (config.error) {\n const hook = await run(\n traced(\n conn,\n config.error({\n ctx: conn.ctx,\n socket: conn.socket,\n error,\n phase: at,\n }),\n ),\n );\n if (Exit.isSuccess(hook)) outcome = hook.value;\n else if (!Cause.hasInterruptsOnly(hook.cause))\n logger.error({ error: thrown(hook.cause), service, socket: name });\n } else logger.error({ error, service, socket: name, phase: at });\n } catch (hookError) {\n logger.error({ error: hookError, service, socket: name });\n }\n if (outcome !== \"continue\" && at !== \"close\")\n conn.close(SOCKET_CLOSE.serverError, \"Socket handler failed\");\n };\n\n /** Runs `work` after the connection's earlier callbacks, in the connection's span. */\n const enqueue = (\n conn: Connection,\n phase: RawSocketPhase | (() => RawSocketPhase),\n work: () => Effect.Effect<void, unknown, any> | undefined,\n size = 0,\n ) => {\n conn.frames++;\n conn.queued += size;\n conn.tail = conn.tail.then(async () => {\n try {\n const at = typeof phase === \"function\" ? phase() : phase;\n // A callback that throws instead of failing is a defect, not a broken queue.\n const exit = await run(\n traced(\n conn,\n Effect.suspend(() => work() ?? Effect.void),\n ),\n );\n if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause))\n await failed(conn, at, exit.cause);\n } finally {\n conn.frames--;\n conn.queued -= size;\n }\n });\n };\n\n /** The frame as `message` gets it, or the close it earns. */\n const decode = (raw: string | Uint8Array) => {\n if (config.parse) return { data: config.parse(raw) };\n if (!definition.decode) return { data: raw };\n if (typeof raw !== \"string\")\n return {\n close: SOCKET_CLOSE.unsupportedData,\n reason: \"Only JSON text is supported\",\n };\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { close: SOCKET_CLOSE.invalidPayload, reason: \"Invalid JSON\" };\n }\n const decoded = definition.decode(json);\n return decoded\n ? { data: decoded.value }\n : { close: SOCKET_CLOSE.invalidPayload, reason: \"Invalid message\" };\n };\n\n const receive = (conn: Connection, raw: string | Uint8Array) => {\n if (conn.closed) return;\n const { socket } = conn;\n const size =\n typeof raw === \"string\" ? Buffer.byteLength(raw) : raw.byteLength;\n conn.messages++;\n conn.bytes += size;\n if (size > definition.maxPayloadBytes)\n return conn.close(SOCKET_CLOSE.tooLarge, \"Message too large\");\n if (\n conn.frames >= RAW_QUEUE_FRAMES ||\n conn.queued + size >\n Math.max(SOCKET_BUFFER_BYTES, definition.maxPayloadBytes)\n )\n return conn.close(SOCKET_CLOSE.tryAgainLater, \"Socket queue full\");\n let decoded: ReturnType<typeof decode>;\n try {\n decoded = decode(raw);\n } catch {\n return conn.close(SOCKET_CLOSE.invalidPayload, \"Invalid message\");\n }\n if (\"close\" in decoded) return conn.close(decoded.close, decoded.reason);\n const early = () =>\n config.preAuth && !socket.authenticated ? \"preAuth\" : \"message\";\n enqueue(\n conn,\n early,\n () => {\n if (conn.ws!.readyState !== 1) return;\n const frame = { data: decoded.data, ctx: conn.ctx, socket };\n return early() === \"preAuth\"\n ? config.preAuth!.message(frame)\n : config.message(frame);\n },\n size,\n );\n };\n\n /** Gives up a slot taken at upgrade that never became a connection. */\n const abandon = (conn: Connection, status: number) => {\n route.pending--;\n conn.span?.end({ [ATTR.httpStatus]: status }, conn.failure?.error);\n settled();\n };\n\n const handlers: RawData[\"mounted\"] = {\n open(ws) {\n const conn = ws.data.connection;\n conn.ws = ws;\n route.pending--;\n route.live++;\n route.connections.add(conn);\n if (config.preAuth)\n conn.deadline = setTimeout(\n () => conn.close(SOCKET_CLOSE.policy, \"Authentication timeout\"),\n config.preAuth.timeoutMs,\n );\n if (config.open)\n enqueue(conn, \"open\", () =>\n config.open!({ ctx: conn.ctx, socket: conn.socket }),\n );\n },\n message(ws, value) {\n receive(ws.data.connection, value);\n },\n async close(ws, code, reason) {\n const conn = ws.data.connection;\n if (conn.closed) return;\n conn.closed = true;\n clearTimeout(conn.deadline);\n if (config.close)\n enqueue(conn, \"close\", () =>\n config.close!({\n ctx: conn.ctx,\n socket: conn.socket,\n code,\n reason,\n }),\n );\n await conn.tail;\n conn.span?.end(\n {\n [ATTR.httpStatus]: 101,\n [ATTR.socketMessages]: conn.messages,\n [ATTR.socketBytes]: conn.bytes,\n [ATTR.socketCloseCode]: code,\n },\n conn.failure?.error,\n );\n route.connections.delete(conn);\n route.live--;\n settled();\n },\n };\n\n return async (request: Request, server: Bun.Server<any>) => {\n if (draining) return refuse(503, \"Server is shutting down\");\n const origin = request.headers.get(\"origin\");\n if (origin && !origins.includes(origin))\n return refuse(403, \"Socket origin refused\");\n if (\n definition.max !== undefined &&\n route.live + route.pending >= definition.max\n )\n return refuse(503, \"Too many connections\");\n route.pending++;\n const id = crypto.randomUUID();\n const span = telemetry\n ? startSocketSpan(\n `${SPAN.socketPrefix}${service}.${name}`,\n request,\n {\n [ATTR.httpRoute]: path,\n [ATTR.service]: service,\n [ATTR.socketName]: name,\n [ATTR.socketId]: id,\n },\n await appTracer(),\n )\n : undefined;\n const conn: Connection = {\n ctx: undefined,\n span,\n closed: false,\n tail: Promise.resolve(),\n frames: 0,\n queued: 0,\n messages: 0,\n bytes: 0,\n socket: undefined as never,\n close: (code = SOCKET_CLOSE.normal, reason = \"\") =>\n conn.ws?.close(code, reason),\n };\n let authenticated = !config.preAuth;\n const socket: RawSocket<any> = {\n id,\n request,\n get authenticated() {\n return authenticated;\n },\n state: undefined,\n send: (data) =>\n Effect.sync(() => !conn.closed && (conn.ws?.send(data) ?? 0) !== 0),\n close: (code, reason) => Effect.sync(() => conn.close(code, reason)),\n authenticate: (patch) =>\n Effect.sync(() => {\n authenticated = true;\n clearTimeout(conn.deadline);\n if (patch) Object.assign(socket.state, patch);\n }),\n link: (traceparent) => Effect.sync(() => span?.link(traceparent)),\n };\n conn.socket = socket;\n const upgrading = Effect.gen(function* () {\n conn.ctx = yield* definition.resolve(request);\n if (\n config.authorize &&\n !(yield* config.authorize({ ctx: conn.ctx, request }))\n )\n return 403;\n socket.state =\n (config.state\n ? yield* config.state({ ctx: conn.ctx, request })\n : undefined) ?? {};\n return draining ? 503 : undefined;\n });\n const exit = await run(traced(conn, upgrading));\n let status: number | undefined;\n if (Exit.isSuccess(exit)) status = exit.value;\n else {\n const error = thrown(exit.cause);\n conn.failure = { error };\n (conn.ctx?.logger ?? fallbackLogger).error({\n error,\n service,\n socket: name,\n });\n status = 500;\n }\n if (status === undefined)\n try {\n status = (server as Bun.Server<RawData>).upgrade(request, {\n data: { mounted: handlers, connection: conn },\n })\n ? undefined\n : 400;\n } catch {\n status = 400;\n }\n if (status !== undefined) {\n abandon(conn, status);\n return refuse(\n status,\n status === 403\n ? \"Socket connection refused\"\n : status === 503\n ? \"Server is shutting down\"\n : status === 400\n ? \"Socket upgrade failed\"\n : \"Socket connection failed\",\n );\n }\n return undefined;\n };\n };\n\n const upgrades = new Map(routes.map((route) => [route, mountRoute(route)]));\n const find = (request: Request) =>\n request.method === \"GET\" &&\n request.headers.get(\"upgrade\")?.toLowerCase() === \"websocket\"\n ? byPath.get(new URL(request.url).pathname)\n : undefined;\n return {\n paths: [...byPath.keys()],\n maxPayloadBytes: Math.max(\n SOCKET_MAX_BYTES,\n ...routes.map(({ definition }) => definition.maxPayloadBytes),\n ),\n matches: (request) => find(request) !== undefined,\n upgrade: (request, server) =>\n upgrades.get(find(request)!)!(request, server),\n drain,\n stats,\n dispose() {\n for (const route of routes) route.definition.mounts.delete(route);\n },\n };\n}\n","import type { Effect } from \"effect\";\n\n/** A drizzle query on an untyped `db`, as the Effect it is. */\nexport const query = <A = unknown>(builder: unknown) =>\n builder as Effect.Effect<A, unknown>;\n","import { Clock, Duration, Effect, type Schedule } from \"effect\";\n\n// Effect's own clock keeps the process alive while it sleeps; Brick's polling must not.\nconst unrefClock: Clock.Clock = Object.assign(\n Object.create(Effect.runSync(Clock.clockWith(Effect.succeed))),\n {\n sleep: (duration: Duration.Duration) =>\n Effect.callback<void>((resume) => {\n const handle = setTimeout(\n () => resume(Effect.void),\n Duration.toMillis(duration),\n );\n handle.unref?.();\n return Effect.sync(() => clearTimeout(handle));\n }),\n },\n);\n\n/** Runs `effect` on a clock whose sleeps do not hold the process open. */\nexport const unref = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.provideService(effect, Clock.Clock, unrefClock);\n\n/**\n * Repeats `tick` on `schedule`, with the pauses on the unref clock. The tick\n * itself, and the fibers it forks (listener deliveries, schedule runs), keep\n * the clock of the caller: a listener that sleeps must hold the process open.\n */\nexport const pollUnref = <A, E, R, O>(\n tick: Effect.Effect<A, E, R>,\n schedule: Schedule.Schedule<O, unknown>,\n) =>\n Effect.clockWith((clock) =>\n unref(\n Effect.repeat(Effect.provideService(tick, Clock.Clock, clock), schedule),\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 type { Effect } from \"effect\";\nimport {\n checkTimeZone,\n nextCron,\n parseCron,\n parseDuration,\n type CronExpression,\n} from \"./cron\";\n\n/** What a workflow schedule's `run` receives: the run, without `attempt` (a run starts one workflow however often it is tried). */\nexport type WorkflowScheduleRun = Omit<ScheduleRun, \"attempt\">;\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)`. */\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\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 run finished, once it succeeded or\n * ran out of tries: `\"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 /**\n * Runs in the process that claims the due time, with the services of the\n * app's layer. Failing retries it.\n */\n run: (run: ScheduleRun) => Effect.Effect<void, unknown, any>;\n workflow?: false;\n }\n | {\n /**\n * `run` is a durable workflow on the app's `WorkflowEngine`, started for\n * each due time and named after its run key, so a run that is tried again\n * starts no second workflow. The run counts as done once the workflow\n * started; the workflow retries its own steps, and a failure of `run` is\n * logged and does not retry the due time.\n */\n workflow: true;\n run: (run: WorkflowScheduleRun) => Effect.Effect<void, unknown, any>;\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) => Effect.Effect<void, unknown, any>;\n /** `run` is a durable workflow: see `ScheduleConfig`. */\n readonly workflow: boolean;\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: an Effect 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 run (a run that\n * used up its tries counts too).\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 * fails 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`, and\n * optionally `catchUp`, `maxAttempts`, `backoff`, `jitter` and `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 * @example\n * const backup = defineSchedule({\n * name: \"db-backup\",\n * cron: \"0 *\\/6 * * *\",\n * timeZone: \"Europe/Berlin\",\n * run: () => Backups.use((backups) => backups.run()),\n * });\n *\n * export default brick({ services, layer, 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 (typeof config.run !== \"function\") fail(\"run must be a function\");\n if (config.workflow !== undefined && typeof config.workflow !== \"boolean\")\n fail(\"workflow must be true or false\");\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 run: config.run as Schedule[\"run\"],\n workflow: config.workflow === true,\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 {\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp,\n} from \"drizzle-orm/pg-core\";\nimport {\n integer as sqliteInteger,\n sqliteTable,\n text as sqliteText,\n} from \"drizzle-orm/sqlite-core\";\n\nconst SCHEDULES = Symbol.for(\"brickkit.effect.schedules\");\n\n/** One finished run of a schedule, as the schedule table keeps it. */\nexport interface ScheduleRunRecord {\n /** The time the run was due, as an ISO timestamp. */\n slot: string;\n trigger: \"schedule\" | \"manual\";\n attempt: number;\n startedAt: string;\n finishedAt: string;\n /** `skipped`: a slot missed while no process ran, with `catchUp: \"skip\"`. */\n outcome: \"succeeded\" | \"failed\" | \"skipped\";\n error?: string;\n}\n\nfunction sqliteSchedules(name: string) {\n const at = (column: string) =>\n sqliteInteger(column, { mode: \"timestamp_ms\" });\n return sqliteTable(name, {\n name: sqliteText(\"name\").primaryKey(),\n spec: sqliteText(\"spec\").notNull(),\n slot: at(\"slot\").notNull(),\n nextAt: at(\"next_at\").notNull(),\n attempts: sqliteInteger(\"attempts\").notNull().default(0),\n trigger: sqliteText(\"trigger\")\n .$type<ScheduleRunRecord[\"trigger\"]>()\n .notNull(),\n runId: sqliteText(\"run_id\"),\n startedAt: at(\"started_at\"),\n leaseUntil: at(\"lease_until\"),\n lastSuccessAt: at(\"last_success_at\"),\n runs: sqliteText(\"runs\", { mode: \"json\" })\n .$type<ScheduleRunRecord[]>()\n .notNull(),\n });\n}\n\nfunction postgresSchedules(name: string) {\n const at = (column: string) => timestamp(column, { withTimezone: true });\n return pgTable(name, {\n name: pgText(\"name\").primaryKey(),\n spec: pgText(\"spec\").notNull(),\n slot: at(\"slot\").notNull(),\n nextAt: at(\"next_at\").notNull(),\n attempts: pgInteger(\"attempts\").notNull().default(0),\n trigger: pgText(\"trigger\").$type<ScheduleRunRecord[\"trigger\"]>().notNull(),\n runId: pgText(\"run_id\"),\n startedAt: at(\"started_at\"),\n leaseUntil: at(\"lease_until\"),\n lastSuccessAt: at(\"last_success_at\"),\n runs: jsonb(\"runs\").$type<ScheduleRunRecord[]>().notNull(),\n });\n}\n\n/** The schedule table of a SQLite database. */\nexport type SQLiteScheduleTable = ReturnType<typeof sqliteSchedules>;\n/** The schedule table of a Postgres database. */\nexport type PostgresScheduleTable = ReturnType<typeof postgresSchedules>;\n/** A schedule table, made by `scheduleTable`. */\nexport type ScheduleTable = SQLiteScheduleTable | PostgresScheduleTable;\nexport type ScheduleRow = ScheduleTable[\"$inferSelect\"];\n\n/**\n * The schedule table: one row per schedule, holding when it is next due, which\n * process is running it, and its last runs. Processes that share the table\n * share the schedules: each due time runs once among them, and a restart\n * picks up where the last process stopped.\n *\n * Brick does not create tables for you. Put it in the tables of one of the\n * app's databases, and your migration tool (such as drizzle-kit) creates it.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_schedules`.\n * @returns A Drizzle table.\n * @example\n * import { defineDatabase, scheduleTable } from \"@brickkit/effect\";\n *\n * export const schedules = scheduleTable(\"postgres\");\n * export const database = defineDatabase({\n * postgres: process.env.DATABASE_URL!,\n * tables: { users, schedules },\n * });\n */\nexport function scheduleTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteScheduleTable;\nexport function scheduleTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresScheduleTable;\nexport function scheduleTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): ScheduleTable {\n const name = options.name ?? \"brick_schedules\";\n const table =\n engine === \"sqlite\" ? sqliteSchedules(name) : postgresSchedules(name);\n Object.defineProperty(table, SCHEDULES, { value: { engine } });\n return table;\n}\n\nexport function scheduleEngine(table: ScheduleTable): \"sqlite\" | \"postgres\" {\n return (\n table as unknown as Record<symbol, { engine: \"sqlite\" | \"postgres\" }>\n )[SCHEDULES].engine;\n}\n\n/** Whether a value is a table made by `scheduleTable`. */\nexport function isScheduleTable(value: unknown): value is ScheduleTable {\n return typeof value === \"object\" && value !== null && SCHEDULES in value;\n}\n","import {\n and,\n eq,\n getTableColumns,\n inArray,\n isNull,\n lt,\n lte,\n or,\n sql,\n} from \"drizzle-orm\";\nimport {\n Cause,\n Effect,\n Fiber,\n Result,\n Schedule as Every,\n Semaphore,\n type Scope,\n} from \"effect\";\nimport { query } from \"../events/query\";\nimport { pollUnref, unref } from \"../events/unref\";\nimport { nextDue, type Schedule, type ScheduleRun } from \"./schedule\";\nimport {\n scheduleEngine,\n type ScheduleRow,\n type ScheduleRunRecord,\n type ScheduleTable,\n} 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/** What `app.events.schedules` offers: see and trigger the app's schedules. */\nexport interface Scheduler {\n readonly start: Effect.Effect<void>;\n /** Stop the timer and wait for the runs in progress. */\n readonly stop: Effect.Effect<void>;\n /** Every schedule, with when it is next due and its last runs. */\n readonly list: Effect.Effect<ScheduleState[]>;\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. Works with\n * `enabled: false` too.\n *\n * @returns `false` when the schedule is running now, so nothing was started.\n * @throws (as a defect) When no schedule has that name.\n */\n readonly trigger: (name: string) => Effect.Effect<boolean>;\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 readonly drain: Effect.Effect<number>;\n}\n\nconst logError = (error: unknown) =>\n Effect.sync(() => console.error(\"[Brick schedules]\", error));\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 *\n * The timer and the runs are fibers of `scope`, so closing it stops them.\n */\nexport function makeScheduler(config: {\n db: any;\n table: ScheduleTable;\n schedules: readonly Schedule[];\n runner: (\n schedule: Schedule,\n run: ScheduleRun,\n ) => Effect.Effect<void, unknown>;\n options: SchedulerOptions;\n scope: Scope.Scope;\n}): Scheduler {\n const { db, runner, options, scope } = config;\n const table = config.table as any;\n const postgres = scheduleEngine(config.table) === \"postgres\";\n const byName = new Map(config.schedules.map((s) => [s.name, s]));\n const inFlight = new Map<string, Fiber.Fiber<void>>();\n const gate = Semaphore.makeUnsafe(1);\n const syncGate = Semaphore.makeUnsafe(1);\n let worker: Fiber.Fiber<unknown> | undefined;\n let synced = false;\n\n /** Not held by a live claim. */\n const free = (now: Date) =>\n or(isNull(table.runId), lt(table.leaseUntil, clock(now)));\n /** Still held by the claim `runId`, or by none when it is null. */\n const unchanged = (runId: string | null) =>\n runId ? eq(table.runId, runId) : isNull(table.runId);\n /** Now, for claims: the database's clock on Postgres, this host's on SQLite (one host). */\n const clock = (now: Date) => (postgres ? sql`now()` : now);\n /** When a claim made or renewed now runs out. */\n const leaseFrom = (now: Date) =>\n postgres\n ? sql`now() + make_interval(secs => ${options.claimTimeoutMs / 1000})`\n : new Date(now.getTime() + options.claimTimeoutMs);\n\n const jittered = (schedule: Schedule, slot: Date): Date =>\n schedule.jitterMs\n ? new Date(slot.getTime() + Math.floor(Math.random() * schedule.jitterMs))\n : slot;\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 const 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: jittered(schedule, slot),\n attempts: 0,\n trigger: \"schedule\" as const,\n }\n );\n };\n\n const record = (\n row: ScheduleRow,\n startedAt: Date,\n outcome: ScheduleRunRecord[\"outcome\"],\n error?: string,\n ): ScheduleRunRecord => ({\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 * 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 const reset = (name: string, now: Date, values: Partial<ScheduleRow>) =>\n Effect.gen(function* () {\n const [row] = yield* query<ScheduleRow[]>(\n db.select().from(table).where(eq(table.name, name)),\n );\n if (!row) return false;\n const updated = yield* query<unknown[]>(\n db\n .update(table)\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 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(table.name, name), unchanged(row.runId), free(now)))\n .returning({ name: table.name }),\n );\n return updated.length > 0;\n });\n\n /** Give each schedule its row, and work its next due time out again when what decides it changed (an edited cron expression). Once per scheduler. */\n const sync = syncGate.withPermits(1)(\n Effect.suspend(() => {\n if (synced) return Effect.void;\n return Effect.gen(function* () {\n const now = new Date();\n for (const schedule of byName.values()) {\n const row = fresh(schedule, now);\n if (!row) continue;\n yield* query(\n db\n .insert(table)\n .values({ name: schedule.name, runs: [], ...row })\n .onConflictDoNothing(),\n );\n const [found] = yield* query<Pick<ScheduleRow, \"spec\">[]>(\n db\n .select({ spec: table.spec })\n .from(table)\n .where(eq(table.name, schedule.name)),\n );\n if (found && found.spec !== schedule.spec)\n yield* reset(schedule.name, now, row);\n }\n synced = true;\n });\n }),\n );\n\n const release = (row: ScheduleRow, values: Partial<ScheduleRow>) =>\n Effect.gen(function* () {\n const updated = yield* query<unknown[]>(\n db\n .update(table)\n .set({\n ...values,\n runs: values.runs?.slice(0, KEEP_RUNS),\n runId: null,\n leaseUntil: null,\n })\n .where(and(eq(table.name, row.name), eq(table.runId, row.runId)))\n .returning({ name: table.name }),\n );\n if (!updated.length)\n console.warn(\n `[Brick schedules] Schedule '${row.name}': another process took the run over, so this outcome is not recorded.`,\n );\n });\n\n /** Done with this due time: on to the next one. */\n const advance = (\n schedule: Schedule,\n row: ScheduleRow,\n runs: ScheduleRunRecord[],\n now: Date,\n succeeded: boolean,\n ) => {\n // Due times that passed during the run are skipped: runs never overlap.\n const slot = nextDue(schedule, now);\n return release(row, {\n spec: schedule.spec,\n ...(slot\n ? { slot, nextAt: 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 /** After a failure: try the same due time again later, unless the tries ran out or the next due time comes first. */\n const retry = (\n schedule: Schedule,\n row: ScheduleRow,\n runs: ScheduleRunRecord[],\n now: Date,\n ) => {\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 advance(schedule, row, runs, now, false);\n return release(row, { nextAt: retryAt, runs });\n };\n\n const renew = (row: ScheduleRow) =>\n Effect.gen(function* () {\n const updated = yield* query<unknown[]>(\n db\n .update(table)\n .set({ leaseUntil: leaseFrom(new Date()) })\n .where(and(eq(table.name, row.name), eq(table.runId, row.runId)))\n .returning({ name: table.name }),\n );\n if (!updated.length)\n console.warn(\n `[Brick schedules] Schedule '${row.name}' lost its claim while running; another process may run it too.`,\n );\n });\n\n const 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 ) =>\n Effect.gen(function* () {\n const runs = [...row.runs];\n const startedAt = row.startedAt!;\n const attemptNo = row.attempts;\n if (abandonedAt)\n runs.unshift(\n record(\n { ...row, attempts: attemptNo - 1 },\n abandonedAt,\n \"failed\",\n ABANDONED,\n ),\n );\n if (\n attemptNo === 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(record(row, startedAt, \"skipped\"));\n return yield* advance(schedule, row, runs, new Date(), false);\n }\n if (attemptNo > schedule.maxAttempts)\n return yield* advance(schedule, row, runs, new Date(), false);\n const slot = row.slot.toISOString();\n const run = Effect.suspend(() =>\n runner(schedule, {\n schedule: schedule.name,\n slot,\n trigger: row.trigger,\n attempt: attemptNo,\n runKey: `${schedule.name}:${slot}`,\n }),\n );\n // Renews the claim while the run goes on; raceFirst stops it with the run.\n const heartbeat = renew(row).pipe(\n Effect.catch(logError),\n Effect.catchDefect(logError),\n Effect.schedule(\n Every.spaced(Math.max(10, Math.floor(options.claimTimeoutMs / 3))),\n ),\n unref,\n );\n yield* run.pipe(\n Effect.raceFirst(heartbeat),\n Effect.matchCauseEffect({\n onFailure: (cause) => {\n if (Cause.hasInterruptsOnly(cause))\n return Effect.failCause(cause as Cause.Cause<never>);\n const found = Cause.findError(cause);\n const error = Result.isSuccess(found)\n ? found.success\n : Cause.squash(cause);\n runs.unshift(\n record(\n row,\n startedAt,\n \"failed\",\n error instanceof Error ? error.message : String(error),\n ),\n );\n return retry(schedule, row, runs, new Date());\n },\n onSuccess: () => {\n runs.unshift(record(row, startedAt, \"succeeded\"));\n return advance(schedule, row, runs, new Date(), true);\n },\n }),\n );\n });\n\n const claimAndRun = Effect.gen(function* () {\n yield* sync;\n const now = new Date();\n const due = yield* query<\n Pick<ScheduleRow, \"name\" | \"spec\" | \"trigger\" | \"runId\" | \"startedAt\">[]\n >(\n db\n .select({\n name: table.name,\n spec: table.spec,\n trigger: table.trigger,\n runId: table.runId,\n startedAt: table.startedAt,\n })\n .from(table)\n .where(\n and(\n inArray(table.name, [...byName.keys()]),\n lte(table.nextAt, now),\n free(now),\n ),\n ),\n );\n let started = 0;\n for (const candidate of due) {\n const schedule = byName.get(candidate.name)!;\n if (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 row = fresh(schedule, now);\n if (row) yield* reset(schedule.name, now, row);\n continue;\n }\n const runId = crypto.randomUUID();\n const [row] = yield* query<ScheduleRow[]>(\n db\n .update(table)\n .set({\n runId,\n startedAt: now,\n leaseUntil: leaseFrom(now),\n // Counted at the claim, so a try whose process dies still counts.\n attempts: sql`${table.attempts} + 1`,\n })\n .where(\n and(\n eq(table.name, schedule.name),\n lte(table.nextAt, now),\n free(now),\n // As read: the abandoned try recorded below is that claim's.\n unchanged(candidate.runId),\n ),\n )\n .returning(),\n );\n if (!row) continue; // Another process won it, or changed it.\n started++;\n const fiber = yield* Effect.forkIn(\n Effect.interruptible(\n execute(\n schedule,\n row,\n candidate.runId === null ? undefined : candidate.startedAt!,\n ).pipe(\n Effect.catch(logError),\n Effect.catchDefect(logError),\n Effect.ensuring(Effect.sync(() => inFlight.delete(schedule.name))),\n ),\n ),\n scope,\n );\n inFlight.set(schedule.name, fiber);\n }\n return started;\n }).pipe(\n Effect.catch((error) => Effect.as(logError(error), 0)),\n Effect.catchDefect((error) => Effect.as(logError(error), 0)),\n );\n\n // Not interruptible: a claim made must reach `inFlight`, or its run is lost until the claim times out.\n const tick: Effect.Effect<number> = gate.withPermits(1)(\n Effect.uninterruptible(claimAndRun),\n );\n const settled = Effect.suspend(() => Fiber.awaitAll([...inFlight.values()]));\n\n return {\n start: Effect.suspend(() => {\n if (worker || !options.timer) return Effect.void;\n return pollUnref(tick, Every.spaced(options.intervalMs)).pipe(\n Effect.forkIn(scope),\n Effect.map((fiber) => {\n worker = fiber;\n }),\n );\n }),\n stop: Effect.gen(function* () {\n const stopped = worker;\n worker = undefined;\n if (stopped) yield* Fiber.interrupt(stopped);\n yield* gate.withPermits(1)(Effect.void);\n yield* settled;\n }),\n list: Effect.gen(function* () {\n const now = new Date();\n // A lease is timed by the database's clock on Postgres, so judge it there.\n const rows = yield* query<(ScheduleRow & { live?: boolean })[]>(\n postgres\n ? db\n .select({\n ...getTableColumns(table),\n live: sql<boolean>`coalesce(${table.leaseUntil} > now(), false)`,\n })\n .from(table)\n : db.select().from(table),\n );\n const stored = new Map(rows.map((row) => [row.name, row]));\n return [...byName.values()].map((schedule): ScheduleState => {\n const row = stored.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(\n row?.runId &&\n (postgres ? row.live : row.leaseUntil && row.leaseUntil > now),\n ),\n attempts: row?.attempts ?? 0,\n lastSuccessAt: row?.lastSuccessAt?.toISOString() ?? null,\n runs: row?.runs ?? [],\n };\n });\n }).pipe(Effect.orDie),\n trigger: (name) =>\n Effect.gen(function* () {\n if (!byName.has(name))\n return yield* Effect.die(new Error(`No schedule named '${name}'`));\n yield* sync;\n const now = new Date();\n const set = yield* reset(name, now, {\n slot: now,\n nextAt: now,\n attempts: 0,\n trigger: \"manual\",\n });\n if (!set) return false;\n if (worker) yield* Effect.forkIn(tick, scope);\n return true;\n }).pipe(Effect.catch((error) => Effect.die(error))),\n drain: Effect.gen(function* () {\n let total = 0;\n for (;;) {\n const started = yield* tick;\n yield* settled;\n if (started === 0) return total;\n total += started;\n }\n }),\n };\n}\n","const ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nexport function newEventId(now: number = Date.now()): string {\n let time = \"\";\n let remaining = now;\n for (let index = 0; index < 10; index++) {\n time = ALPHABET[remaining % 32] + time;\n remaining = Math.floor(remaining / 32);\n }\n let random = \"\";\n for (const byte of crypto.getRandomValues(new Uint8Array(16))) {\n random += ALPHABET[byte % 32];\n }\n return `evt_${time}${random}`;\n}\n\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(\"brickkit.effect.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 tables 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/effect\";\n *\n * export const outbox = outboxTable(\"postgres\");\n * export const database = defineDatabase({\n * postgres: process.env.DATABASE_URL!,\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 Cause,\n Effect,\n Fiber,\n Result,\n Schedule,\n Semaphore,\n type Scope,\n} from \"effect\";\nimport { BrickError, asFailure } from \"../errors\";\nimport {\n deliveryOf,\n OUTBOX_STATUSES,\n outboxEngine,\n type OutboxRow,\n type OutboxStatus,\n type OutboxTable,\n} from \"./outbox\";\nimport { outsideTransaction, runInTransaction } from \"./transaction\";\nimport { query } from \"./query\";\nimport { pollUnref } from \"./unref\";\nimport type { DispatchOptions, EventDelivery, EventListener } from \"./types\";\n\n/** How many outbox rows are in each state. */\nexport type OutboxCounts = Record<OutboxStatus, number>;\n\n/** What the dispatcher runs for a delivery: the listener, with the app's services already provided. */\nexport interface Deliverable {\n readonly maxAttempts?: number;\n readonly errors?: EventListener[\"errors\"];\n readonly retry?: EventListener[\"retry\"];\n readonly run: (delivery: EventDelivery) => Effect.Effect<void, unknown>;\n}\n\nexport interface Dispatcher {\n /** Start looking for due deliveries on a timer. Does nothing if it already is, or `timer` is off. */\n readonly start: Effect.Effect<void>;\n /** Stop the timer and wait for the deliveries that are running to finish. */\n readonly stop: Effect.Effect<void>;\n /** Look for work soon, without waiting for the timer. Safe to call often. */\n readonly notify: Effect.Effect<void>;\n /** Deliver everything that is due now and wait for it. Deliveries that fail and are rescheduled are not waited for again. */\n readonly drain: Effect.Effect<number>;\n readonly counts: Effect.Effect<OutboxCounts>;\n /** Put parked deliveries back in line, with their attempts reset. */\n readonly retryDead: (deliveryId?: string) => Effect.Effect<number>;\n}\n\nconst PURGE_INTERVAL_MS = 60_000;\n\nexport function 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\nexport function backoffMs(attempt: number, maxBackoffMs: number): number {\n return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);\n}\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 const declared = asFailure(error);\n try {\n return listener.retry(\n declared instanceof BrickError && listener.errors?.[declared.code]\n ? {\n code: declared.code,\n message: declared.message,\n details: declared.details,\n }\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 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\nconst logError = (error: unknown) =>\n Effect.sync(() => console.error(\"[Brick events]\", error));\n\n/** A write whose failure is logged, not raised. */\nconst logged = (write: Effect.Effect<unknown, unknown>) =>\n write.pipe(\n Effect.asVoid,\n Effect.catch(logError),\n Effect.catchDefect(logError),\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 fails 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 *\n * The timer and the deliveries are fibers of `scope`, so closing it stops them.\n */\nexport function makeDispatcher(config: {\n db: any;\n table: OutboxTable;\n listener: (name: string) => Deliverable | undefined;\n options: DispatchOptions;\n scope: Scope.Scope;\n}): Dispatcher {\n const { db, listener: listenerOf, scope } = config;\n const table = config.table as any;\n const postgres = outboxEngine(config.table) === \"postgres\";\n const options = resolveDispatchOptions(config.options);\n const inFlight = new Set<Fiber.Fiber<void>>();\n const turn = Semaphore.makeUnsafe(1);\n let worker: Fiber.Fiber<number> | undefined;\n let lastPurge = 0;\n\n const claim = (limit: number) => {\n const now = new Date();\n const stale = new Date(now.getTime() - options.claimTimeoutMs);\n const due = or(\n and(eq(table.status, \"pending\"), lte(table.availableAt, now)),\n and(eq(table.status, \"claimed\"), lt(table.claimedAt, stale)),\n );\n return runInTransaction(db, (tx) =>\n Effect.gen(function* () {\n let select = tx\n .select()\n .from(table)\n .where(due)\n .orderBy(asc(table.seq))\n .limit(limit);\n if (postgres) select = select.for(\"update\", { skipLocked: true });\n const picked = yield* query<OutboxRow[]>(select);\n if (!picked.length) return [] as OutboxRow[];\n yield* query(\n tx\n .update(table)\n .set({\n status: \"claimed\",\n claimedAt: now,\n attempts: sql`${table.attempts} + 1`,\n })\n .where(\n inArray(\n table.seq,\n picked.map((row) => row.seq),\n ),\n ),\n );\n return picked.map((row) => ({\n ...row,\n status: \"claimed\" as const,\n claimedAt: now,\n attempts: row.attempts + 1,\n }));\n }),\n ) as Effect.Effect<OutboxRow[]>;\n };\n\n const purgeDelivered = Effect.suspend(() => {\n const now = Date.now();\n if (options.retainDeliveredMs === 0 || now - lastPurge < PURGE_INTERVAL_MS)\n return Effect.void;\n lastPurge = now;\n return db\n .delete(table)\n .where(\n and(\n eq(table.status, \"delivered\"),\n lt(table.deliveredAt, new Date(now - options.retainDeliveredMs)),\n ),\n ) as Effect.Effect<unknown>;\n });\n\n /** Still the claim this delivery made: a late outcome must not overwrite the claim that took the row over. */\n const held = (row: OutboxRow) =>\n and(\n eq(table.seq, row.seq),\n eq(table.status, \"claimed\"),\n eq(table.claimedAt, row.claimedAt),\n );\n\n const park = (row: OutboxRow, message: string) =>\n logged(\n db\n .update(table)\n .set({ status: \"dead\", lastError: message, claimedAt: null })\n .where(held(row)),\n );\n\n const markDelivered = (row: OutboxRow) =>\n logged(\n options.retainDeliveredMs === 0\n ? db.delete(table).where(held(row))\n : db\n .update(table)\n .set({\n status: \"delivered\",\n deliveredAt: new Date(),\n lastError: null,\n })\n .where(held(row)),\n );\n\n const fail = (\n row: OutboxRow,\n error: unknown,\n maxAttempts: number,\n decision: \"retry\" | \"dead\",\n ) => {\n const message = error instanceof Error ? error.message : String(error);\n if (decision === \"dead\" || row.attempts >= maxAttempts)\n return park(row, message);\n return logged(\n db\n .update(table)\n .set({\n status: \"pending\",\n lastError: message,\n claimedAt: null,\n availableAt: new Date(\n Date.now() + backoffMs(row.attempts, options.maxBackoffMs),\n ),\n })\n .where(held(row)),\n );\n };\n\n const deliver = (row: OutboxRow): Effect.Effect<void> => {\n const listener = listenerOf(row.listener);\n if (!listener)\n return park(row, `No listener named '${row.listener}' is registered`);\n return Effect.suspend(() => listener.run(deliveryOf(row))).pipe(\n Effect.matchCauseEffect({\n onFailure: (cause) => {\n if (Cause.hasInterruptsOnly(cause))\n return Effect.failCause(cause as Cause.Cause<never>);\n const found = Cause.findError(cause);\n const error = Result.isSuccess(found)\n ? found.success\n : Cause.squash(cause);\n return fail(\n row,\n error,\n listener.maxAttempts ?? options.maxAttempts,\n decideRetry(row.listener, listener, error),\n );\n },\n onSuccess: () => markDelivered(row),\n }),\n );\n };\n\n const claimAndRun = Effect.gen(function* () {\n const room = options.batchSize - inFlight.size;\n if (room <= 0) return 0;\n const rows = yield* claim(room);\n for (const row of rows) {\n const fiber = yield* Effect.forkIn(\n Effect.interruptible(deliver(row)),\n scope,\n );\n inFlight.add(fiber);\n fiber.addObserver(() => inFlight.delete(fiber));\n }\n // The deliveries are started: a failed purge must not hide them from `drain`.\n yield* logged(purgeDelivered);\n return rows.length;\n }).pipe(\n Effect.catch((error) => Effect.as(logError(error), 0)),\n Effect.catchDefect((error) => Effect.as(logError(error), 0)),\n );\n\n // Uninterruptible: stopping must not abandon rows that are claimed but not yet started.\n const tickWhen = (allowed: () => boolean): Effect.Effect<number> =>\n turn.withPermits(1)(\n Effect.uninterruptible(\n Effect.suspend(() => (allowed() ? claimAndRun : Effect.succeed(0))),\n ),\n );\n const tick = tickWhen(() => true);\n // For the ticks that `notify` and `retryDead` fork: one that waited for its\n // turn behind a `stop` finds the dispatcher stopped, and claims nothing.\n const backgroundTick = tickWhen(() => worker !== undefined);\n const settled = Effect.suspend(() => Fiber.awaitAll([...inFlight]));\n\n return {\n start: Effect.suspend(() => {\n if (worker || !options.timer) return Effect.void;\n return outsideTransaction(\n db,\n pollUnref(tick, Schedule.fixed(options.intervalMs)),\n ).pipe(\n Effect.forkIn(scope),\n Effect.map((fiber) => {\n worker = fiber;\n }),\n );\n }),\n stop: Effect.gen(function* () {\n const stopped = worker;\n worker = undefined;\n if (stopped) yield* Fiber.interrupt(stopped);\n yield* turn.withPermits(1)(Effect.void);\n yield* settled;\n }),\n notify: Effect.suspend(() =>\n worker\n ? Effect.asVoid(\n Effect.forkIn(outsideTransaction(db, backgroundTick), scope),\n )\n : Effect.void,\n ),\n drain: Effect.gen(function* () {\n let total = 0;\n for (;;) {\n const started = yield* tick;\n yield* settled;\n if (started === 0) return total;\n total += started;\n }\n }),\n counts: Effect.gen(function* () {\n const rows = yield* query<{ status: OutboxStatus; count: number }[]>(\n db\n .select({ status: table.status, count: sql<number>`count(*)` })\n .from(table)\n .groupBy(table.status),\n );\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 }).pipe(Effect.orDie),\n retryDead: (deliveryId) =>\n Effect.gen(function* () {\n const rows = yield* query<{ id: string }[]>(\n db\n .update(table)\n .set({ status: \"pending\", attempts: 0, availableAt: new Date() })\n .where(\n deliveryId\n ? and(eq(table.status, \"dead\"), eq(table.id, deliveryId))\n : eq(table.status, \"dead\"),\n )\n .returning({ id: table.id }),\n );\n if (rows.length && worker) yield* Effect.forkIn(backgroundTick, scope);\n return rows.length;\n }).pipe(Effect.orDie),\n };\n}\n","import { Cause, Context, Effect, Layer, Schema } from \"effect\";\nimport { Workflow, WorkflowEngine } from \"effect/workflow\";\nimport type { Schedule, ScheduleRun } from \"../schedules/schedule\";\nimport type { EventDelivery, EventListener } from \"./types\";\n\n/** What a run of a workflow listener starts with: the delivery, without `attempt`. */\nconst EventFields = {\n id: Schema.String,\n name: Schema.String,\n payload: Schema.Unknown,\n occurredAt: Schema.String,\n traceId: Schema.optionalKey(Schema.String),\n source: Schema.optionalKey(Schema.String),\n listener: Schema.String,\n deliveryId: Schema.String,\n};\n\n/** What a run of a workflow schedule starts with: the run, without `attempt`. */\nconst RunFields = {\n schedule: Schema.String,\n slot: Schema.String,\n trigger: Schema.Literals([\"schedule\", \"manual\"]),\n runKey: Schema.String,\n};\n\n/** Starts a durable run of a listener's or schedule's `run`, and returns once it has started. */\nexport interface WorkflowStarter<A> {\n readonly name: string;\n readonly start: (input: A) => Effect.Effect<void, unknown>;\n}\n\n/** Dies when the app has no `WorkflowEngine` for the listener or schedule `kind`/`name`, which runs a workflow. */\nexport const requireEngine = (\n kind: \"Listener\" | \"Schedule\",\n name: string,\n context: Context.Context<any>,\n) =>\n Context.getOption(context, WorkflowEngine.WorkflowEngine)._tag === \"None\"\n ? Effect.die(\n new Error(\n `${kind === \"Listener\" ? \"Event listener\" : \"Schedule\"} '${name}' runs a workflow, so the app's layer needs a workflow engine: add workflowEngine(database) to \\`brick({ layer })\\`.`,\n ),\n )\n : Effect.void;\n\n/**\n * Registers `run` as a durable workflow on the app's `WorkflowEngine`, for the\n * listener or schedule `kind`/`name`. The run is named after `key`, so a delivery\n * or a due time that is tried again finds the run it started instead of\n * starting another. A failure of `run` ends the run as failed, with its cause,\n * and is logged: the workflow retries its own steps, not the delivery.\n *\n * @param context - The app's context, which holds the engine and what `run` needs.\n * @throws (as a defect) When the app has no `WorkflowEngine`.\n */\nfunction register<A extends object>(\n kind: \"Listener\" | \"Schedule\",\n name: string,\n fields: Schema.Struct.Fields,\n key: (input: A) => string,\n run: (input: A) => Effect.Effect<void, unknown, any>,\n context: () => Context.Context<any>,\n): Effect.Effect<WorkflowStarter<A>, never, any> {\n return Effect.gen(function* () {\n yield* requireEngine(kind, name, context());\n const workflow = Workflow.make(`Brick${kind}/${name}`, {\n payload: fields,\n idempotencyKey: key as never,\n }) as any;\n const handler = (input: A) =>\n Effect.suspend(() => run(input)).pipe(\n // The workflow's own services stay: only the app's are added.\n Effect.provideContext(context()),\n Effect.tapCause((cause) =>\n Effect.sync(() => {\n if (!Cause.hasInterruptsOnly(cause))\n console.error(\n `[Brick] ${kind === \"Listener\" ? \"Workflow listener\" : \"Workflow schedule\"} '${name}' failed:`,\n Cause.pretty(cause),\n );\n }),\n ),\n );\n yield* Layer.build(workflow.toLayer(handler)).pipe(\n Effect.provideContext(context()),\n );\n return {\n name,\n start: (input: A) =>\n (\n workflow.execute(input, { discard: true }) as Effect.Effect<string>\n ).pipe(Effect.provideContext(context()), Effect.asVoid),\n };\n }) as unknown as Effect.Effect<WorkflowStarter<A>, never, any>;\n}\n\n/** The workflow of a `workflow: true` listener. Needs `Scope`: the runs belong to it. */\nexport const listenerWorkflow = (\n listener: EventListener,\n context: () => Context.Context<any>,\n) =>\n register<Omit<EventDelivery, \"attempt\">>(\n \"Listener\",\n listener.name,\n EventFields,\n (event) => event.deliveryId,\n (event) => listener.run(event as EventDelivery),\n context,\n );\n\n/** The workflow of a `workflow: true` schedule. Needs `Scope`: the runs belong to it. */\nexport const scheduleWorkflow = (\n schedule: Schedule,\n context: () => Context.Context<any>,\n) =>\n register<Omit<ScheduleRun, \"attempt\">>(\n \"Schedule\",\n schedule.name,\n RunFields,\n (run) => `schedule:${run.runKey}`,\n (run) => schedule.run(run as ScheduleRun),\n context,\n );\n","import { Effect } from \"effect\";\nimport {\n errorHelpers,\n type ErrorDefinitions,\n type ErrorHelpers,\n} from \"../action\";\nimport { decodePayload, isEventRef, type EventRef } from \"./catalog\";\nimport type {\n EventDelivery,\n EventListener,\n ListenerFailure,\n RetryDecision,\n WorkflowEvent,\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 ErrorDefinitions = {},\n> = {\n name: string;\n on: TOn;\n maxAttempts?: number;\n /** Errors `run` may fail with through `error.CODE()`. */\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: ErrorHelpers<TErrors> },\n ) => Effect.Effect<void, unknown, any>;\n workflow?: false;\n }\n | {\n /** `run` is a durable workflow: see `EventListener.workflow`. */\n workflow: true;\n run: (\n event: WorkflowEvent<TPayload>,\n helpers: { error: ErrorHelpers<TErrors> },\n ) => Effect.Effect<void, unknown, any>;\n }\n);\n\n/**\n * Define a listener: an Effect that runs for each event it listens for, after\n * the write that caused the event has been committed. Pass it to\n * `brick({ events: { listeners } })`.\n *\n * It runs in the process that delivers events, with the services of the app's\n * layer. Delivery is at least once. A listener that fails is retried later with\n * a growing delay, then parked as dead, so it can run again for the same event:\n * use `delivery.deliveryId` to make its work idempotent.\n *\n * With `workflow: true`, `run` is a durable workflow on the app's\n * `WorkflowEngine` (put `workflowEngine(database)` in the app's `layer`): it\n * receives the delivery without `attempt`, may use `Activity`, `DurableClock`\n * and `DurableDeferred`, and a restart resumes it where it stopped. A delivery\n * counts as done once its run has started, and starts one run however often it\n * is tried: the run is named after the delivery id. The workflow retries its\n * own steps, so a failure of `run` is logged and does not retry the delivery.\n *\n * A listener can declare `errors`, as an action does, and fail with them through\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.shipped`, which types the payload, or an event\n * name; or a list of either; a trailing `*` matches a prefix, as in `user.*`),\n * `run`, and optionally `maxAttempts`, `errors` and `retry`.\n * @returns The listener.\n * @throws When the name is empty or contains `:`, `on` is empty, or\n * `maxAttempts` is not a positive integer.\n * @example\n * const welcome = defineListener({\n * name: \"welcome-email\",\n * on: \"user.create\",\n * run: ({ payload, deliveryId }) =>\n * Mailer.use((mailer) => mailer.sendWelcome(payload.email, deliveryId)),\n * });\n *\n * export default brick({ services, layer, events: { listeners: [welcome] } });\n */\nexport function defineListener<\n const TOn extends EventOn,\n const TErrors extends ErrorDefinitions = {},\n>(\n config: ListenerConfig<PayloadOf<TOn>, TOn, TErrors>,\n): EventListener<PayloadOf<TOn>>;\nexport function defineListener<\n TPayload = any,\n const TErrors extends ErrorDefinitions = {},\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 items = (Array.isArray(config.on) ? config.on : [config.on]) as (\n | string\n | EventRef\n )[];\n const on = items.map((item) => (isEventRef(item) ? item.name : item));\n validateListener({ ...config, on } as unknown as EventListener);\n const refs = new Map(\n items.filter(isEventRef).map((ref) => [ref.name, ref] as const),\n );\n const helpers = errorHelpers(config.errors);\n return Object.freeze({\n name: config.name,\n on: Object.freeze(on),\n run: (delivery: EventDelivery) => {\n const ref = refs.get(delivery.name);\n return ref\n ? Effect.flatMap(decodePayload(ref, delivery.payload), (payload) =>\n config.run({ ...delivery, payload } as never, { error: helpers }),\n )\n : config.run(delivery as never, { error: helpers });\n },\n ...(config.workflow ? { workflow: true } : {}),\n ...(config.errors ? { errors: config.errors } : {}),\n ...(config.retry ? { retry: config.retry } : {}),\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 `run` is not a function.\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 (typeof run !== \"function\")\n throw new Error(`Event listener '${name}': run must be a function`);\n if (workflow !== undefined && typeof workflow !== \"boolean\")\n throw new Error(`Event listener '${name}': workflow must be true or false`);\n}\n","import { Cause, Context, Effect, Exit, Layer, Scope, Semaphore } from \"effect\";\nimport type { ManagedRuntime } from \"effect\";\nimport type { AnyDatabaseHandle } from \"../db\";\nimport { DuplicateNameError } from \"../errors\";\nimport { checkEvent, type EventChecker } from \"./catalog\";\nimport { makeScheduler, type Scheduler } from \"../schedules/scheduler\";\nimport type { ScheduleState } from \"../schedules/scheduler\";\nimport { isScheduleTable, type ScheduleTable } from \"../schedules/table\";\nimport type { AnyService } from \"../service\";\nimport {\n makeDispatcher,\n type Deliverable,\n type Dispatcher,\n type OutboxCounts,\n} from \"./dispatcher\";\nimport { newEventId } from \"./id\";\nimport { traceScheduleRun } from \"../telemetry\";\nimport {\n listenerWorkflow,\n requireEngine,\n scheduleWorkflow,\n type WorkflowStarter,\n} from \"./workflow\";\nimport { validateListener } from \"./listener\";\nimport { appDeps, listenerDeps, withAmbientDeps } from \"../deps\";\nimport type { Schedule } from \"../schedules/schedule\";\nimport {\n isOutboxTable,\n outboxRows,\n OUTBOX_STATUSES,\n type OutboxTable,\n} from \"./outbox\";\nimport {\n afterCommitOn,\n onTransactionCommitOnce,\n runInTransaction,\n} from \"./transaction\";\nimport type { EventListener, EventsOptions } from \"./types\";\n\nexport function matchesEvent(pattern: string, name: string): boolean {\n if (pattern === \"*\") return true;\n if (pattern.endsWith(\"*\")) return name.startsWith(pattern.slice(0, -1));\n return pattern === name;\n}\n\n/**\n * Records an event inside the transaction it was given. The event is committed\n * with the write, or not at all. A service with an event catalog records only\n * events from it, and checks their payloads; `encoded` says the payload is JSON\n * already.\n */\nexport type EventRecorder = (\n name: string,\n payload: unknown,\n options?: { readonly encoded?: boolean },\n) => Effect.Effect<void>;\n\n/** Who and what an event is recorded for. */\nexport interface EventContext {\n readonly traceId?: string | undefined;\n readonly source?: string | undefined;\n /** The service whose catalog checks the event. Defaults to the one that owns the database. */\n readonly service?: EventChecker | undefined;\n}\n\n/**\n * The events of a running app: who listens, where events are recorded, and the\n * dispatchers that deliver them. It is the `Events` service of the app's\n * runtime, which `emitEvent` and CRUD writes record through.\n */\nexport interface EventsHub {\n /** Whether any listener wants the event, so a write can skip recording one. */\n readonly wants: (name: string) => boolean;\n /** Whether `db` is the database of a service with an outbox table. */\n readonly records: (db: unknown) => boolean;\n /**\n * Run `fn` in a database transaction on `db`. Events it records are committed\n * with whatever else it wrote, or not at all, and delivered after the commit.\n * Inside an open transaction it joins that one, and delivery follows the\n * outer commit.\n */\n readonly transaction: <A, E, R>(\n db: unknown,\n context: EventContext,\n fn: (tx: any, record: EventRecorder) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | unknown, R>;\n readonly start: Effect.Effect<void>;\n readonly stop: Effect.Effect<void>;\n readonly drain: Effect.Effect<number>;\n readonly counts: Effect.Effect<OutboxCounts>;\n readonly retryDead: (deliveryId?: string) => Effect.Effect<number>;\n readonly scheduler: Scheduler | undefined;\n}\n\n/** The events of the app, as an Effect service. */\nexport class Events extends Context.Service<Events, EventsHub>()(\n \"@brickkit/effect/Events\",\n) {}\n\n// Shared by name: the CLI that stops the hubs may hold another copy of this package.\nconst startedHubs = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(\"brickkit.events.started\")\n] ??= new Set()) as Set<{ stop(): Promise<void> }>;\n\n/**\n * Stop every events hub started in this process, by any copy of Brick, and\n * wait for their deliveries. A hub that fails to stop does not cut the wait for\n * 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/** `app.events`: the hub, as Promises on the app's runtime. */\nexport interface AppEvents {\n /**\n * Start delivering recorded events and running schedules from this process.\n * Does nothing if this process only records events (`dispatch: false`),\n * already started, or a stop is still waiting.\n */\n start(): Promise<void>;\n /** Stop delivering, and wait for the deliveries and runs that are going on. */\n stop(): Promise<void>;\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 drain(): Promise<number>;\n /** How many rows are in each state, across the app's outbox tables. */\n counts(): Promise<OutboxCounts>;\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 retryDead(deliveryId?: string): Promise<number>;\n /** The app's schedules, when it has any. Running them follows `start()` and `stop()`. */\n readonly schedules: ScheduleControl | undefined;\n /** The listeners and settings of `events`, as plain data: what `app.definition.events` holds. */\n describe(): EventsDefinition;\n}\n\nconst NO_OUTBOX =\n \"ctx.db is not the database of a service with an outbox table (the app needs events, and ctx.db must be the service's own database)\";\n\n/**\n * Wire an app's `events` option: check it, and make the layer that builds the\n * hub from the services' databases. The layer needs those databases and the app\n * layer in its context (`Layer.provideMerge`), and listeners and schedules run\n * with that context.\n *\n * @throws When two listeners or two schedules share a name, or a listener is\n * malformed, or the schedules have no (or more than one) `scheduleTable()`\n * among the services' databases.\n */\nexport function createEvents(\n options: EventsOptions,\n services: readonly AnyService[],\n telemetry = false,\n) {\n const byName = new Map<string, EventListener>();\n const ambient = appDeps(services);\n for (const listener of options.listeners ?? []) {\n validateListener(listener);\n if (byName.has(listener.name))\n throw new DuplicateNameError(\n `Duplicate event listener '${listener.name}'`,\n );\n // `useDeps()` in it returns the plugin's deps for a plugin's listener, else the app's.\n const deps = listenerDeps(listener) ?? ambient;\n byName.set(listener.name, {\n ...listener,\n run: (delivery) => withAmbientDeps(listener.run(delivery), deps),\n });\n }\n const schedules = (options.schedules ?? []).map((schedule): Schedule => ({\n ...schedule,\n run: (run) => withAmbientDeps(schedule.run(run), ambient),\n }));\n const scheduleNames = new Set<string>();\n for (const schedule of schedules) {\n if (scheduleNames.has(schedule.name))\n throw new DuplicateNameError(`Duplicate schedule '${schedule.name}'`);\n scheduleNames.add(schedule.name);\n }\n const dispatch =\n options.dispatch === false\n ? false\n : options.dispatch === true || options.dispatch === undefined\n ? {}\n : options.dispatch;\n\n const tablesOf = <T>(handle: AnyDatabaseHandle, is: (v: unknown) => v is T) =>\n Object.values(handle.tables as Record<string, unknown>).find(is);\n const handles = [\n ...new Set(services.flatMap((s) => (s.database ? [s.database] : []))),\n ];\n const recording = handles.flatMap((handle) => {\n const table = tablesOf(handle, isOutboxTable);\n // The service whose name prefixes an event checks it; the last one checks the rest.\n const owners = services.filter((s) => s.database === handle);\n return table ? [{ handle, table, owners }] : [];\n });\n const recorderNames = services\n .filter((s) => s.database && tablesOf(s.database, isOutboxTable))\n .map((s) => s.name);\n if (recorderNames.length === 0 && byName.size > 0)\n console.warn(\n \"[Brick] 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 let scheduleSource:\n | { handle: AnyDatabaseHandle; table: ScheduleTable }\n | undefined;\n if (schedules.length) {\n const found = new Map<ScheduleTable, AnyDatabaseHandle>();\n for (const handle of handles) {\n const table = tablesOf(handle, isScheduleTable);\n if (table && !found.has(table)) found.set(table, handle);\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, handle]] = [...found];\n scheduleSource = { handle, table };\n }\n\n const matching = (name: string) =>\n [...byName.values()].filter((listener) =>\n listener.on.some((pattern) => matchesEvent(pattern, name)),\n );\n\n let built = false;\n const layer = Layer.effect(Events)(\n Effect.gen(function* () {\n built = true;\n const scope = yield* Effect.scope;\n let context = yield* Effect.context<any>();\n const deliverables = new Map<string, Deliverable>();\n // The durable runs of workflow listeners and schedules, on the app's workflow\n // engine. Registering one takes the runs that no process holds, so a process\n // that only records events (`dispatch: false`) does not, unless it drains by hand;\n // it still checks that the engine is there, so a missing one is reported at start.\n const starters = new Map<string, WorkflowStarter<any>>();\n const registering = Semaphore.makeUnsafe(1);\n const starter = (key: string): Effect.Effect<WorkflowStarter<any>> =>\n registering.withPermits(1)(\n Effect.suspend(() => {\n const found = starters.get(key);\n if (found) return Effect.succeed(found);\n const name = key.slice(key.indexOf(\":\") + 1);\n const made = (\n key.startsWith(\"listener:\")\n ? listenerWorkflow(byName.get(name)!, () => context)\n : scheduleWorkflow(\n schedules.find((schedule) => schedule.name === name)!,\n () => context,\n )\n ) as Effect.Effect<WorkflowStarter<any>>;\n // The runs belong to the app's scope, whichever fiber registers first.\n return Effect.tap(\n Effect.provideService(made, Scope.Scope, scope),\n (made) => Effect.sync(() => starters.set(key, made)),\n );\n }),\n );\n for (const listener of byName.values())\n if (listener.workflow)\n yield* dispatch !== false\n ? starter(`listener:${listener.name}`)\n : requireEngine(\"Listener\", listener.name, context);\n for (const schedule of schedules)\n if (schedule.workflow)\n yield* dispatch !== false\n ? starter(`schedule:${schedule.name}`)\n : requireEngine(\"Schedule\", schedule.name, context);\n const deliverable = (name: string) => {\n const listener = byName.get(name);\n if (!listener) return undefined;\n let found = deliverables.get(name);\n if (!found) {\n const { run, errors, retry, maxAttempts } = listener;\n found = {\n ...(errors ? { errors } : {}),\n ...(retry ? { retry } : {}),\n ...(maxAttempts !== undefined ? { maxAttempts } : {}),\n run: listener.workflow\n ? ({ attempt: _attempt, ...event }) =>\n Effect.flatMap(starter(`listener:${name}`), (found) =>\n found.start(event),\n )\n : (delivery) =>\n Effect.suspend(() => run(delivery)).pipe(\n Effect.provideContext(context),\n ),\n };\n deliverables.set(name, found);\n }\n return found;\n };\n\n const recorders = new Map<\n unknown,\n {\n table: OutboxTable;\n dispatcher: Dispatcher;\n owners: readonly EventChecker[];\n }\n >();\n for (const { handle, table, owners } of recording) {\n const db = yield* (handle as any).Database;\n recorders.set(db, {\n table,\n owners,\n dispatcher: makeDispatcher({\n db,\n table,\n listener: deliverable,\n options: dispatch || {},\n scope,\n }),\n });\n }\n const dispatchers = [...recorders.values()].map((r) => r.dispatcher);\n\n let scheduler: Scheduler | undefined;\n if (scheduleSource) {\n const db = yield* (scheduleSource.handle as any).Database;\n const settings = dispatch || {};\n scheduler = makeScheduler({\n db,\n table: scheduleSource.table,\n schedules,\n runner: (schedule, run) => {\n const ran = schedule.workflow\n ? Effect.suspend(() => {\n const { attempt: _attempt, ...started } = run;\n return Effect.flatMap(\n starter(`schedule:${schedule.name}`),\n (found) => found.start(started),\n );\n })\n : Effect.suspend(() => schedule.run(run)).pipe(\n Effect.provideContext(context),\n );\n return telemetry ? traceScheduleRun(run, ran) : ran;\n },\n options: {\n timer: settings.timer ?? true,\n intervalMs: settings.intervalMs ?? 1_000,\n claimTimeoutMs: settings.claimTimeoutMs ?? 60_000,\n },\n scope,\n });\n }\n\n let started = false;\n let stopping = false;\n const stopGate = Semaphore.makeUnsafe(1);\n const handle = {\n stop: () => Effect.runPromise(hub.stop),\n };\n\n const start = Effect.suspend(() => {\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 (dispatch === false || started || stopping) return Effect.void;\n started = true;\n startedHubs.add(handle);\n return Effect.all(\n [...dispatchers.map((d) => d.start), scheduler?.start ?? Effect.void],\n { discard: true },\n );\n });\n\n const insert = (\n recorder: { table: OutboxTable; owners: readonly EventChecker[] },\n tx: any,\n context: EventContext,\n name: string,\n payload: unknown,\n encoded = false,\n ): Effect.Effect<boolean> =>\n Effect.flatMap(\n checkEvent(\n context.service ??\n recorder.owners.find((s) => name.startsWith(`${s.name}.`)) ??\n recorder.owners.at(-1)!,\n name,\n payload,\n encoded,\n ),\n (json) => write(recorder, tx, context, name, json),\n );\n const write = (\n recorder: { table: OutboxTable },\n tx: any,\n context: EventContext,\n name: string,\n payload: unknown,\n ): Effect.Effect<boolean> => {\n const listeners = matching(name);\n if (!listeners.length) return Effect.succeed(false);\n return Effect.as(\n tx.insert(recorder.table as any).values(\n outboxRows(\n {\n id: newEventId(),\n name,\n payload,\n occurredAt: new Date(),\n ...(context.traceId ? { traceId: context.traceId } : {}),\n ...(context.source ? { source: context.source } : {}),\n },\n listeners.map((listener) => listener.name),\n ),\n ) as Effect.Effect<unknown>,\n true,\n ).pipe(Effect.orDie);\n };\n\n const hub: EventsHub = {\n wants: (name) => matching(name).length > 0,\n records: (db) => recorders.has(db),\n transaction: (db, eventContext, fn) =>\n Effect.suspend(() => {\n const recorder = recorders.get(db);\n if (!recorder) return Effect.die(new Error(NO_OUTBOX));\n // After the outermost commit, also of a transaction the app opened itself.\n const notify = afterCommitOn(\n db,\n Effect.andThen(start, recorder.dispatcher.notify),\n );\n return runInTransaction(db, (tx) =>\n fn(tx, (name, payload, options) =>\n Effect.flatMap(\n insert(\n recorder,\n tx,\n eventContext,\n name,\n payload,\n options?.encoded,\n ),\n (recorded) =>\n recorded ? onTransactionCommitOnce(notify) : Effect.void,\n ),\n ),\n );\n }),\n start,\n stop: stopGate.withPermits(1)(\n Effect.suspend(() => {\n stopping = true;\n started = false;\n return Effect.all(\n [\n ...dispatchers.map((d) => d.stop),\n scheduler?.stop ?? Effect.void,\n ],\n { discard: true },\n ).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n stopping = false;\n startedHubs.delete(handle);\n }),\n ),\n );\n }),\n ),\n drain: Effect.gen(function* () {\n let total = 0;\n for (const dispatcher of dispatchers)\n total += yield* dispatcher.drain;\n return total;\n }),\n counts: Effect.gen(function* () {\n const total = Object.fromEntries(\n OUTBOX_STATUSES.map((status) => [status, 0]),\n ) as OutboxCounts;\n for (const dispatcher of dispatchers) {\n const counts = yield* dispatcher.counts;\n for (const status of OUTBOX_STATUSES)\n total[status] += counts[status];\n }\n return total;\n }),\n retryDead: (deliveryId) =>\n Effect.gen(function* () {\n let total = 0;\n for (const dispatcher of dispatchers)\n total += yield* dispatcher.retryDead(deliveryId);\n return total;\n }),\n scheduler,\n };\n context = Context.add(context, Events, hub);\n yield* Effect.addFinalizer(() => hub.stop);\n return hub;\n }),\n ) as unknown as Layer.Layer<Events>;\n\n const describe = (): EventsDefinition => ({\n listeners: [...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: dispatch !== false,\n recorders: [...recorderNames],\n ...(schedules.length\n ? {\n schedules: schedules.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 /** `app.events`, over the runtime that `layer` was built into. Nothing is built until it is used. */\n const bind = (\n runtime: ManagedRuntime.ManagedRuntime<never, any>,\n ): AppEvents => {\n const run = async <A>(effect: Effect.Effect<A, unknown, Events>) => {\n const exit = await (\n runtime as ManagedRuntime.ManagedRuntime<Events, any>\n ).runPromiseExit(effect);\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n };\n const control: ScheduleControl = {\n list: () => run(Events.use((hub) => hub.scheduler!.list)),\n trigger: (name) => run(Events.use((hub) => hub.scheduler!.trigger(name))),\n drain: () => run(Events.use((hub) => hub.scheduler!.drain)),\n };\n return {\n start: () => run(Events.use((hub) => hub.start)),\n // Nothing to stop when the layer was never built: do not open the databases for it.\n stop: async () => {\n if (built) await run(Events.use((hub) => hub.stop));\n },\n drain: () => run(Events.use((hub) => hub.drain)),\n counts: () => run(Events.use((hub) => hub.counts)),\n retryDead: (deliveryId) =>\n run(Events.use((hub) => hub.retryDead(deliveryId))),\n schedules: schedules.length ? control : undefined,\n describe,\n };\n };\n\n return { layer, describe, bind };\n}\n","import {\n and,\n eq,\n getTableColumns,\n inArray,\n type Column,\n type SQL,\n} from \"drizzle-orm\";\nimport { Effect, Option, Schema } from \"effect\";\nimport {\n errorHelpers,\n type Action,\n type AnyAction,\n type AnySchema,\n type ErrorDefinitions,\n type ErrorHelpers,\n type HttpMethod,\n} from \"./action\";\nimport { actionMeta } from \"./action-meta\";\nimport {\n inlineAuditOptions,\n isAuditTable,\n isInlineAudit,\n recordInline,\n} from \"./audit\";\nimport type { AuditOptions } from \"./audit\";\nimport { encodePayload, type EventRef } from \"./events/catalog\";\nimport { crudEventSource } from \"./events/catalog\";\nimport { Events } from \"./events/hub\";\nimport { runInTransaction } from \"./events/transaction\";\nimport { columnValue, idSchema as columnIdSchema } from \"./crud/codec\";\nimport { BrickError, DuplicateNameError, asFailure } from \"./errors\";\nimport { installPlugin, segmentClaimant } from \"./plugin\";\nimport type { ResourcePlugin, ResourcePluginAPI } from \"./plugin-types\";\nimport type { RateLimits } from \"./rate-limit\";\nimport { kebabCase } from \"./routes\";\nimport type { Reveal } from \"./sensitive\";\nimport type { AnyService, Service } from \"./service\";\n\n/** A child table: rows that belong to one row of their resource. */\nexport interface ResourceChild<TTable = any> {\n table: TTable;\n /** The child's column that holds the parent row's id. */\n parent: Column;\n /** The child's id column. Defaults to its single primary key. */\n id?: Column;\n}\n\n/** The declaration of a resource: a table and its entity. */\nexport interface ResourceConfig<TTable = any> {\n /** Its route segment: `/api/<service>/<name>`, and the prefix of the actions plugins add (`<name>.list`). */\n name: string;\n table: TTable;\n /** The id column (default: the table's single primary key). */\n id?: Column;\n /**\n * Child tables of this resource, by name. A command can load them with its\n * row (`load: { children: [\"items\"] }`) and insert, update and delete their\n * rows in the same transaction.\n */\n children?: Record<string, ResourceChild>;\n}\n\n/** The part of a `ResourceConfig` the resource's type depends on. */\nexport type ResourceTypeOptions = Pick<\n ResourceConfig,\n \"name\" | \"id\" | \"children\"\n>;\n\ntype PrimaryColumn<T> = T extends { _: { columns: infer C } }\n ? {\n [K in keyof C]: C[K] extends { _: { isPrimaryKey: true } } ? C[K] : never;\n }[keyof C]\n : Column;\nexport type ResourceIdentity<T, O> = O & {\n id: O extends { id: infer I extends Column } ? I : PrimaryColumn<T>;\n};\n\ntype InputOf<S> = S extends AnySchema ? S[\"Type\"] : undefined;\ntype ResultOf<S, A> = S extends AnySchema ? S[\"Type\"] : A;\ntype RowOf<T> = T extends { $inferSelect: infer S } ? S : any;\ntype InsertOf<T> = T extends { $inferInsert: infer S } ? S : any;\n\n/**\n * Which rows a record action may load when its resource has no `crud`:\n * `\"public\"` loads any row by id, `scope` adds a SQL condition (such as the\n * caller's tenant). It applies whatever `crud` the resource has.\n */\nexport type ResourceActionAccess<TCtx = any> =\n | \"public\"\n | {\n scope: (args: { ctx: TCtx }) => Effect.Effect<SQL | undefined, any, any>;\n };\n\n/** A record action's input: its own fields and the `id` from the path. */\nexport type ResourceActionInput<\n TIn extends AnySchema | undefined,\n TRecord extends boolean,\n> = TRecord extends true\n ? (TIn extends AnySchema ? TIn[\"Type\"] : {}) & { id: string | number }\n : InputOf<TIn>;\n\ntype IdField = { readonly id: Schema.Codec<string | number> };\n/** The schema of a record action's input: its own, with the `id`. */\nexport type WithId<TIn> =\n TIn extends Schema.Struct<infer F>\n ? Schema.Struct<F & IdField>\n : Schema.Struct<IdField>;\ntype ActionInputSchema<\n TIn extends AnySchema | undefined,\n TRecord extends boolean,\n> = TRecord extends true ? WithId<TIn> : TIn;\n\n/** `resource.action(config)`: an action owned by a resource. */\nexport interface ResourceActionConfig<\n TIn extends AnySchema | undefined,\n TOut extends AnySchema | undefined,\n TErrors extends ErrorDefinitions,\n TCtx,\n TRow,\n TRecord extends boolean,\n A,\n E,\n R,\n RA,\n> {\n readonly name: string;\n readonly description?: string;\n /** POST unless set. GET and DELETE read their input from the query string. */\n readonly method?: HttpMethod;\n /** Under the resource's route. A record action's path needs `:id`. */\n readonly path?: string;\n readonly tags?: readonly string[];\n readonly input?: TIn;\n readonly output?: TOut;\n readonly errors?: TErrors;\n /** `true` rejects an extra key at the root of the input, as core's `additionalProperties: false`; `\"deep\"` at every depth. */\n readonly strict?: boolean | \"deep\";\n readonly dashboard?: boolean;\n /**\n * `true` makes it a record action at `/:id/<name>`: `id` joins the input,\n * the row loads through its `access`, and a missing or hidden row answers\n * 404 before `execute` runs.\n */\n readonly record?: TRecord;\n /** For a record action: which rows it may load. */\n readonly access?: ResourceActionAccess<TCtx>;\n readonly rateLimit?: RateLimits<ResourceActionInput<TIn, TRecord>, TCtx>;\n readonly reveal?: Reveal<ResourceActionInput<TIn, TRecord>, TCtx>;\n /**\n * Recorded in the audit log, with the resource and, for a record action, the\n * `id`, when the service has an audit table and the action's HTTP method is\n * not `GET`. `false` leaves it out.\n */\n readonly audit?:\n | false\n | AuditOptions<\n ResourceActionInput<TIn, TRecord>,\n TOut extends AnySchema ? TOut[\"Type\"] : any\n >;\n readonly authorize?: (params: {\n input: ResourceActionInput<TIn, TRecord>;\n ctx: TCtx;\n error: ErrorHelpers<TErrors>;\n }) => Effect.Effect<boolean, any, RA>;\n readonly execute: (params: {\n input: ResourceActionInput<TIn, TRecord>;\n ctx: TCtx;\n error: ErrorHelpers<TErrors>;\n /** The loaded row of a record action; `undefined` otherwise. */\n row: TRecord extends true ? TRow : undefined;\n }) => Effect.Effect<ResultOf<TOut, A>, E, R>;\n}\n\ntype ChildNames<TOptions> = TOptions extends {\n children: infer C extends Record<string, ResourceChild>;\n}\n ? keyof C & string\n : never;\n\n/** The child tables of a resource, by name. */\nexport type CommandChildren<TOptions> = TOptions extends {\n children: infer C extends Record<string, ResourceChild>;\n}\n ? { [K in keyof C]: C[K][\"table\"] }\n : {};\n\n/** The row `decide` receives: the resource's row with the children it loads. */\nexport type CommandRow<\n TTable,\n TOptions,\n TLoaded extends string,\n> = RowOf<TTable> & {\n [K in TLoaded & keyof CommandChildren<TOptions>]: RowOf<\n CommandChildren<TOptions>[K]\n >[];\n};\n\n/** The changes to one child table. Updates and deletes name rows by child id. */\nexport interface ChildChanges<TChild = any> {\n /** New rows. Their parent column is set to the parent's id. */\n insert?: Partial<InsertOf<TChild>>[];\n /** Partial rows, each with the child id; only rows of this parent change. */\n update?: Partial<RowOf<TChild>>[];\n /** Child ids to delete; only rows of this parent are deleted. */\n delete?: (string | number)[];\n}\n\ntype PayloadOf<T> = T extends EventRef<infer P> ? P : never;\n\n/** What `decide` returns when the command goes ahead. */\nexport interface CommandDecision<\n TRow = any,\n TChildren = {},\n TEvents extends Record<string, EventRef> = Record<string, EventRef>,\n> {\n /** Columns of the parent row to change. */\n set?: Partial<Omit<TRow, keyof TChildren>>;\n /** Inserts, updates and deletes per child table. */\n children?: { [K in keyof TChildren]?: ChildChanges<TChildren[K]> };\n /** Events to record with the write, by catalog name and payload. */\n emit?: { [K in keyof TEvents]?: PayloadOf<TEvents[K]> };\n}\n\n/**\n * The `error` helpers `decide` receives. Unlike an action's, they return the\n * rejection instead of failing with it, so `decide` stays a pure function.\n */\nexport type CommandErrors<TErrors extends ErrorDefinitions> = {\n [K in keyof ErrorHelpers<TErrors>]: (\n message?: string,\n details?: unknown,\n ) => BrickError;\n};\n\n/** `resource.command(name, config)`. */\nexport interface CommandConfig<\n TIn extends AnySchema | undefined,\n TOut extends AnySchema | undefined,\n TErrors extends ErrorDefinitions,\n TCtx,\n TRow,\n TChildren,\n TEvents extends Record<string, EventRef>,\n TLoad extends readonly string[],\n RA,\n> {\n readonly description?: string;\n readonly tags?: readonly string[];\n /** The command's own input; `id` from the path joins it. */\n readonly input?: TIn;\n /**\n * The reply: the updated row (with loaded children), cut down to this\n * schema's properties. Without it the reply is `{ id }`.\n */\n readonly output?: TOut;\n readonly reveal?: Reveal<ResourceActionInput<TIn, true>, TCtx>;\n readonly errors?: TErrors;\n /** Which child tables to load with the row, by their name on the resource. */\n readonly load?: { children?: TLoad };\n /** Which rows the command may load. */\n readonly access?: ResourceActionAccess<TCtx>;\n readonly rateLimit?: RateLimits<ResourceActionInput<TIn, true>, TCtx>;\n /**\n * Recorded in the audit log, with the resource and the record's `id`, in the\n * command's transaction, when the service has an audit table. `false` leaves\n * it out.\n */\n readonly audit?:\n | false\n | AuditOptions<\n ResourceActionInput<TIn, true>,\n TOut extends AnySchema ? TOut[\"Type\"] : { id: string | number }\n >;\n readonly authorize?: (params: {\n input: ResourceActionInput<TIn, true>;\n ctx: TCtx;\n error: ErrorHelpers<TErrors>;\n }) => Effect.Effect<boolean, any, RA>;\n /**\n * The rules: a pure function of the loaded row and the input. Return\n * `error.CODE()` to reject (nothing is written), or the changes to make.\n */\n readonly decide: (\n row: TRow,\n input: ResourceActionInput<TIn, true>,\n helpers: { error: CommandErrors<TErrors> },\n ) => CommandDecision<TRow, TChildren, TEvents> | BrickError;\n}\n\n/** A command: an action with its `decide`, callable without a database. */\nexport type Command<\n TIn extends AnySchema | undefined,\n TOut extends AnySchema | undefined,\n TErrors extends ErrorDefinitions,\n A,\n R,\n TRow,\n TChildren,\n TEvents extends Record<string, EventRef>,\n> = Action<\n WithId<TIn>,\n TOut extends AnySchema ? TOut : Schema.Struct<IdField>,\n TErrors,\n A,\n R\n> & {\n /**\n * Run the rules alone, with the standard and declared error helpers: for\n * unit tests that need no database.\n */\n decide(\n row: TRow,\n input: ResourceActionInput<TIn, true>,\n ): CommandDecision<TRow, TChildren, TEvents> | BrickError;\n};\n\n/**\n * A plugin host over a table. Plugins such as `crud` add actions to it, and\n * `action` and `command` declare its own.\n */\nexport interface Resource<\n TTable = any,\n TCtx = any,\n TOptions = {},\n TEvents extends Record<string, EventRef> = Record<string, EventRef>,\n TRequirement = never,\n> {\n /** Installs a plugin on the resource. It returns the resource, with the API the plugin contributed. */\n use<P extends ResourcePlugin<Service<any, TCtx, any>, this, any>>(\n plugin: P,\n ): this & ResourcePluginAPI<P, TTable, TCtx, this>;\n readonly name: string;\n readonly serviceName: string;\n readonly table: TTable;\n readonly id: TOptions extends { id: infer I extends Column } ? I : Column;\n readonly idField: string;\n readonly config: ResourceConfig<TTable> & TOptions;\n /**\n * Declare an action owned by this resource, registered as\n * `<resource>.<name>`. It mounts at `/<service>/<resource>/<name>`, or at\n * `/<service>/<resource>/:id/<name>` with `record: true`.\n */\n action<\n TIn extends AnySchema | undefined = undefined,\n TOut extends AnySchema | undefined = undefined,\n const TErrors extends ErrorDefinitions = {},\n const TRecord extends boolean = false,\n A = never,\n E = never,\n R = never,\n RA = never,\n >(\n config: ResourceActionConfig<\n TIn,\n TOut,\n TErrors,\n TCtx,\n RowOf<TTable>,\n TRecord,\n A,\n E,\n R,\n RA\n >,\n ): Action<\n ActionInputSchema<TIn, TRecord>,\n TOut,\n TErrors,\n A,\n R | RA | TRequirement\n >;\n /**\n * Declare a command: a record action whose body is the pure `decide`. Brick\n * loads the row (and the child rows it asks for) in a transaction, runs\n * `decide`, applies the changes it returns, records the events it emits in\n * the same transaction, and commits. Registered as `<resource>.<name>` at\n * `POST /<service>/<resource>/:id/<name>`.\n */\n command<\n TIn extends AnySchema | undefined = undefined,\n const TErrors extends ErrorDefinitions = {},\n const TLoad extends readonly ChildNames<TOptions>[] = [],\n TOut extends AnySchema | undefined = undefined,\n RA = never,\n >(\n name: string,\n config: CommandConfig<\n TIn,\n TOut,\n TErrors,\n TCtx,\n CommandRow<TTable, TOptions, TLoad[number]>,\n CommandChildren<TOptions>,\n TEvents,\n TLoad,\n RA\n >,\n ): Command<\n TIn,\n TOut,\n TErrors,\n never,\n RA | TRequirement,\n CommandRow<TTable, TOptions, TLoad[number]>,\n CommandChildren<TOptions>,\n TEvents\n >;\n}\n\n/** Any resource, whatever its table. */\nexport type AnyResource = Resource<any, any, any, any, any>;\n\n/** The schema of a resource's `:id` in a body: a number for a number column, else a string. */\nexport const idSchema = (column: Column): AnySchema =>\n columnIdSchema(column, false);\n\n/**\n * Load the row a record action (or command) works on, through its `access`.\n *\n * @param args - `id`, the call's `ctx`, `access`, and `db` (a transaction) in\n * place of `ctx.db`.\n * @returns The row, or `undefined` when it is missing or hidden.\n * @throws (as a defect) When `access` is missing.\n */\nexport const loadRecord = (\n resource: AnyResource,\n args: {\n id: unknown;\n ctx: any;\n db?: any;\n access?: ResourceActionAccess | undefined;\n },\n): Effect.Effect<Record<string, unknown> | undefined, unknown, any> =>\n Effect.gen(function* () {\n if (!args.access)\n return yield* Effect.die(\n new Error(\n `Resource '${resource.name}' has no access rule for loading records: set \\`access\\` on the record action`,\n ),\n );\n const db = args.db ?? args.ctx?.db;\n // An id its column can't hold names no row.\n const id = columnValue(resource.id, args.id);\n if (id === undefined) return undefined;\n if (!db)\n return yield* Effect.die(\n new Error(\"Record actions require a configured database\"),\n );\n const scope =\n args.access === \"public\"\n ? undefined\n : yield* args.access.scope({ ctx: args.ctx });\n const rows: Record<string, unknown>[] = yield* db\n .select()\n .from(resource.table)\n .where(and(scope, eq(resource.id, id)))\n .limit(1);\n return rows[0];\n });\n\n/**\n * Startup check: a record action needs its own `access`.\n *\n * @throws When one has none.\n */\nexport function checkRecordAccess(service: AnyService): void {\n for (const action of service.listActions()) {\n const info = actionMeta(action).resourceAction;\n if (info?.record && info.access === undefined)\n throw new Error(\n `Record action '${info.resource}.${info.name}' needs \\`access\\` (\"public\" or { scope })`,\n );\n }\n}\n\nfunction primaryColumn(table: unknown): [string, Column] | undefined {\n const primary = Object.entries(\n getTableColumns(table as Parameters<typeof getTableColumns>[0]),\n ).filter(([, column]) => column.primary);\n return primary.length === 1 ? primary[0] : undefined;\n}\n\nfunction fieldOf(table: unknown, column: Column): string | undefined {\n return Object.entries(\n getTableColumns(table as Parameters<typeof getTableColumns>[0]),\n ).find(([, own]) => own === column)?.[0];\n}\n\ninterface ChildInfo {\n table: any;\n parent: Column;\n parentField: string;\n id: Column;\n idField: string;\n}\n\nfunction childInfo(\n resource: AnyResource,\n name: string,\n where: string,\n): ChildInfo {\n const children = resource.config.children as\n | Record<string, ResourceChild>\n | undefined;\n const child =\n children && Object.hasOwn(children, name) ? children[name] : undefined;\n if (!child)\n throw new Error(\n `${where}: resource '${resource.name}' has no child table '${name}'`,\n );\n const parentField = fieldOf(child.table, child.parent);\n const id = child.id ?? primaryColumn(child.table)?.[1];\n const idField = id && fieldOf(child.table, id);\n if (!parentField || !id || !idField)\n throw new Error(\n `Resource '${resource.name}' child '${name}' needs a parent column and an id column of its table`,\n );\n return { table: child.table, parent: child.parent, parentField, id, idField };\n}\n\n/** The `error` helpers of `decide`: they return the rejection, not fail with it. */\nfunction commandErrors(errors?: ErrorDefinitions) {\n const failing = errorHelpers(errors) as Record<\n string,\n (message?: string, details?: unknown) => Effect.Effect<never, BrickError>\n >;\n return Object.fromEntries(\n Object.entries(failing).map(([code, helper]) => [\n code,\n (message?: string, details?: unknown) =>\n Effect.runSync(Effect.flip(helper(message, details))),\n ]),\n );\n}\n\nconst notFound = (resource: AnyResource, id: unknown, error: any) =>\n error.NOT_FOUND(`${resource.name} '${String(id)}' not found`);\n\ntype CommandRun = (args: {\n input: any;\n ctx: any;\n error: any;\n}) => Effect.Effect<unknown, unknown, any>;\n\nfunction defineResourceAction(\n service: AnyService,\n resource: AnyResource,\n config: any,\n /** A command's body: it loads the row itself, in its transaction. */\n command?: CommandRun,\n): AnyAction {\n const { record = false, access, execute, ...rest } = config;\n if (!config.name || /[./]/.test(config.name))\n throw new Error(`Invalid resource action name '${config.name}'`);\n const name = `${resource.name}.${config.name}`;\n const segment = kebabCase(config.name);\n // A plugin route on this resource (crud's `/count`) owns its first segment.\n const claimant = segmentClaimant(service, resource, segment);\n if (claimant)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${name}\" in service \"${service.name}\": \"${segment}\" is a ${claimant} route`,\n );\n const existing = service.getAction(name);\n if (existing && actionMeta(existing).route)\n throw new DuplicateNameError(\n `Brick: duplicate name \"${name}\" in service \"${service.name}\"`,\n );\n if (!record && access !== undefined)\n throw new Error(`Only record actions take \\`access\\` ('${name}')`);\n if (record && config.path !== undefined && !/\\/:id(\\/|$)/.test(config.path))\n throw new Error(`Record action '${name}' needs ':id' in its path`);\n let input = config.input as AnySchema | undefined;\n if (record) {\n if (input !== undefined && !(\"fields\" in input))\n throw new Error(`Record action '${name}' input must be a Schema.Struct`);\n input = Schema.Struct({\n ...(input as Schema.Struct<Schema.Struct.Fields> | undefined)?.fields,\n id: columnIdSchema(resource.id, true),\n }) as unknown as AnySchema;\n }\n // The audit row says which resource and, for a record action, which record.\n const audit =\n config.audit === false\n ? false\n : {\n resource: resource.name,\n ...(record && { record: ({ input }: any) => input.id }),\n ...config.audit,\n };\n const action = (service as any).action({\n ...rest,\n name,\n input,\n audit,\n execute: ({ input, ctx, error }: any) =>\n command\n ? command({ input, ctx, error })\n : Effect.gen(function* () {\n const row = record\n ? yield* loadRecord(resource, { id: input.id, ctx, access })\n : undefined;\n if (record && row === undefined)\n return yield* notFound(resource, input.id, error);\n return yield* execute({ input, ctx, error, row });\n }),\n } as any) as AnyAction;\n actionMeta(action).resourceAction = {\n resource: resource.name,\n name: config.name,\n record,\n ...(access === undefined ? {} : { access }),\n };\n return action;\n}\n\nfunction defineCommand(\n service: AnyService,\n resource: AnyResource,\n name: string,\n config: any,\n): AnyAction {\n const where = `Command '${resource.name}.${name}'`;\n if (isAuditTable(resource.table))\n throw new Error(\n `${where} is over the audit table, so it could rewrite audit rows. The audit log takes no commands.`,\n );\n if (typeof config.decide !== \"function\")\n throw new Error(`${where} needs a decide function`);\n const loaded = ((config.load?.children ?? []) as string[]).map((child) => ({\n name: child,\n ...childInfo(resource, child, where),\n }));\n const columns = getTableColumns(\n resource.table as Parameters<typeof getTableColumns>[0],\n );\n for (const { name: child } of loaded)\n if (Object.hasOwn(columns, child))\n throw new Error(\n `${where} loads the child '${child}', which is also a column of '${resource.name}', so the rows would replace its value`,\n );\n const rejections = commandErrors(config.errors);\n const decide = (row: any, input: any) =>\n config.decide(row, input, { error: rejections });\n\n const run: CommandRun = ({ input, ctx, error: helpers }) =>\n Effect.gen(function* () {\n const db = ctx.db;\n if (!db)\n return yield* Effect.die(\n new Error(`${where} requires a configured database`),\n );\n const hub = Option.getOrUndefined(yield* Effect.serviceOption(Events));\n const body = (\n tx: any,\n record?: (\n name: string,\n payload: unknown,\n options?: { encoded?: boolean },\n ) => Effect.Effect<void>,\n ) =>\n Effect.gen(function* () {\n const row = yield* loadRecord(resource, {\n id: input.id,\n ctx,\n db: tx,\n access: config.access,\n });\n if (row === undefined)\n return yield* notFound(resource, input.id, helpers);\n const id = row[resource.idField];\n for (const child of loaded)\n row[child.name] = yield* tx\n .select()\n .from(child.table)\n .where(eq(child.parent, id));\n\n const decision = decide(row, input);\n const rejected = asFailure(decision);\n if (rejected instanceof BrickError)\n return yield* Effect.fail(rejected);\n const { set, children, emit } = (decision ?? {}) as {\n set?: Record<string, unknown>;\n children?: Record<\n string,\n {\n insert?: Record<string, unknown>[];\n update?: Record<string, unknown>[];\n delete?: unknown[];\n }\n >;\n emit?: Record<string, unknown>;\n };\n // Every event is checked before anything is written.\n const declared = service.events as Record<string, EventRef>;\n const emits: (readonly [string, unknown])[] = [];\n for (const [key, payload] of Object.entries(emit ?? {})) {\n if (payload === undefined) continue;\n const ref = Object.hasOwn(declared, key)\n ? declared[key]\n : undefined;\n if (!ref)\n return yield* Effect.die(\n new Error(\n `${where} emits '${key}', which is not in the event catalog of service '${service.name}'`,\n ),\n );\n emits.push([ref.name, yield* encodePayload(ref, payload)]);\n }\n if (emits.length && !record)\n return yield* Effect.die(\n new Error(\n `${where} emits events, but service '${service.name}' records none: give its database an outbox table and the app \\`events\\``,\n ),\n );\n\n if (set && Object.keys(set).length)\n yield* tx\n .update(resource.table)\n .set(set)\n .where(eq(resource.id, id));\n for (const [childName, changes] of Object.entries(children ?? {})) {\n if (!changes) continue;\n const child = childInfo(resource, childName, where);\n const own = eq(child.parent, id);\n if (changes.insert?.length)\n yield* tx.insert(child.table).values(\n changes.insert.map((item) => ({\n ...item,\n [child.parentField]: id,\n })),\n );\n for (const item of changes.update ?? []) {\n const { [child.idField]: childId, ...values } = item;\n if (childId === undefined)\n return yield* Effect.die(\n new Error(\n `${where}: an update of child '${childName}' needs its '${child.idField}'`,\n ),\n );\n if (Object.keys(values).length)\n yield* tx\n .update(child.table)\n .set(values)\n .where(and(eq(child.id, childId), own));\n }\n if (changes.delete?.length)\n yield* tx\n .delete(child.table)\n .where(and(inArray(child.id, changes.delete as any[]), own));\n }\n for (const [eventName, payload] of emits)\n yield* record!(eventName, payload, { encoded: true });\n\n let reply: unknown = { id };\n if (config.output) {\n const [updated]: Record<string, unknown>[] = yield* tx\n .select()\n .from(resource.table)\n // `set` may have changed the id.\n .where(eq(resource.id, set?.[resource.idField] ?? id))\n .limit(1);\n for (const child of loaded)\n updated![child.name] = yield* tx\n .select()\n .from(child.table)\n .where(eq(child.parent, id));\n reply = updated;\n }\n if (isInlineAudit(ctx))\n yield* recordInline(ctx, tx, {\n action: `${resource.name}.${name}`,\n resource: config.audit?.resource ?? resource.name,\n recordId: config.audit?.record\n ? config.audit.record({ input, result: reply })\n : input.id,\n });\n return reply;\n });\n return yield* hub?.records(db)\n ? hub.transaction(\n db,\n {\n traceId: ctx.traceId,\n source: crudEventSource(service.name, resource.name),\n },\n body,\n )\n : runInTransaction(db, (tx) => body(tx));\n });\n\n const action = defineResourceAction(\n service,\n resource,\n {\n name,\n record: true,\n description: config.description,\n tags: config.tags,\n input: config.input,\n output:\n config.output ??\n Schema.Struct({ id: columnIdSchema(resource.id, false) }),\n reveal: config.reveal,\n errors: config.errors,\n ...(config.access === undefined ? {} : { access: config.access }),\n ...(config.authorize ? { authorize: config.authorize } : {}),\n ...(config.rateLimit ? { rateLimit: config.rateLimit } : {}),\n audit:\n config.audit === false\n ? false\n : inlineAuditOptions({\n ...config.audit,\n resource: config.audit?.resource ?? resource.name,\n }),\n execute: () => Effect.void,\n },\n run,\n );\n return Object.assign(action, { decide }) as AnyAction;\n}\n\n/** Declares a resource on `service`, which is what `service.resource` does. */\nexport function defineResource<\n TTable = any,\n TCtx = any,\n const O extends ResourceTypeOptions = ResourceTypeOptions,\n>(\n service: AnyService,\n config: ResourceConfig<TTable> & O,\n): Resource<TTable, TCtx, ResourceIdentity<TTable, O>> {\n const columns = getTableColumns(\n config.table as Parameters<typeof getTableColumns>[0],\n );\n const id: Column | undefined = config.id ?? primaryColumn(config.table)?.[1];\n const entry = Object.entries(columns).find(([, column]) => column === id);\n if (!entry || !id)\n throw new Error(\n `Resource '${config.name}' requires an id column belonging to its table`,\n );\n if (\n !config.name ||\n config.name.includes(\"/\") ||\n [\"__proto__\", \"constructor\", \"prototype\"].includes(config.name)\n )\n throw new Error(`Invalid resource name '${config.name}'`);\n const resource = {\n name: config.name,\n serviceName: service.name,\n table: config.table,\n id,\n idField: entry[0],\n config: Object.freeze({ ...config, id }),\n use: (plugin: ResourcePlugin<any, any, any>) =>\n installPlugin(service, resource as never, plugin),\n action: (actionConfig: unknown) =>\n defineResourceAction(service, resource as never, actionConfig),\n command: (name: string, commandConfig: unknown) =>\n defineCommand(service, resource as never, name, commandConfig),\n };\n return resource as never;\n}\n","import { Schema } from \"effect\";\nimport type { AnySchema, HttpMethod } from \"./action\";\nimport { actionMeta } from \"./action-meta\";\nimport type { RouteIR } from \"./routes\";\nimport type { AnyService } from \"./service\";\nimport { socketPath } from \"./socket\";\n\n/** A JSON Schema document, as `Schema.toJsonSchemaDocument` writes it, with its definitions under `$defs`. */\nexport type JsonSchema = Record<string, unknown>;\n\n/**\n * What the CLI's client contract is generated from: each action's route and\n * the JSON Schemas of what travels over the wire, and each socket's. The CLI\n * reads it with `app.clientContract()` and holds no copy of `effect`.\n */\nexport interface ClientContractSource {\n readonly actions: readonly {\n readonly service: string;\n readonly name: string;\n readonly method: HttpMethod;\n readonly path: string;\n readonly plugin?: string;\n readonly resource?: string;\n /** Where the typed client puts the action, when a plugin names it. */\n readonly clientPath?: readonly string[];\n readonly input?: JsonSchema;\n readonly output?: JsonSchema;\n /** The codes the action declares. */\n readonly errors: readonly string[];\n }[];\n readonly sockets: readonly {\n readonly service: string;\n readonly name: string;\n readonly path: string;\n readonly input: Readonly<Record<string, JsonSchema>>;\n readonly output: Readonly<Record<string, JsonSchema>>;\n readonly errors: readonly string[];\n }[];\n}\n\n/** Effect objects accept extra keys when decoding. The contract types what a caller sends, so it drops that. */\nconst withoutOpenObjects = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(withoutOpenObjects);\n if (!node || typeof node !== \"object\") return node;\n const entries = Object.entries(node as Record<string, unknown>)\n .filter(\n ([key, value]) => !(key === \"additionalProperties\" && value === true),\n )\n .map(([key, value]) => [key, withoutOpenObjects(value)]);\n return Object.fromEntries(entries);\n};\n\n/** The JSON form of a schema: what the client sends and receives. */\nexport function jsonSchemaOf(schema: AnySchema): JsonSchema {\n const { schema: root, definitions } = Schema.toJsonSchemaDocument(schema);\n return withoutOpenObjects(\n Object.keys(definitions).length ? { ...root, $defs: definitions } : root,\n ) as JsonSchema;\n}\n\n/**\n * Describe the routes and sockets a client reaches, in service order.\n * `routes` and `bindings` come from `describeRoutes`, so an action a plugin\n * switched off has no route and no entry.\n */\nexport function describeClientContract(\n services: readonly AnyService[],\n routes: readonly RouteIR[],\n prefix: string,\n): ClientContractSource {\n const byAction = new Map(\n routes.map((route) => [`${route.service}\\0${route.action}`, route]),\n );\n return {\n actions: services.flatMap((service) =>\n service.listActions().flatMap((action) => {\n const route = byAction.get(`${service.name}\\0${action.name}`);\n if (!route || route.kind === \"webhook\") return [];\n const bound = actionMeta(action).route;\n const { input, output, errors } = action.config;\n return [\n {\n service: service.name,\n name: action.name,\n method: route.method,\n path: route.path,\n ...(bound && { plugin: bound.plugin }),\n ...(bound?.resource !== undefined && { resource: bound.resource }),\n ...(bound?.clientPath && { clientPath: bound.clientPath }),\n ...(input && { input: jsonSchemaOf(input) }),\n ...(output && { output: jsonSchemaOf(output) }),\n errors: Object.keys(errors ?? {}),\n },\n ];\n }),\n ),\n sockets: services.flatMap((service) =>\n service.listSockets().map((socket) => ({\n service: service.name,\n name: socket.schema.name,\n path: socketPath(prefix, service.name, socket),\n input: Object.fromEntries(\n Object.entries(socket.input).map(([event, schema]) => [\n event,\n jsonSchemaOf(schema),\n ]),\n ),\n output: Object.fromEntries(\n Object.entries(socket.output).map(([event, schema]) => [\n event,\n jsonSchemaOf(schema),\n ]),\n ),\n errors: Object.keys(socket.errors ?? {}),\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 * What `brick({ cors })` does with a request: the headers to add to its\n * response, and, for a preflight, the response to give instead of routing. An\n * origin that doesn't match gets no `Access-Control-Allow-Origin`, so the\n * browser blocks it; origins are compared exactly and never reflected unless\n * the rule allows them.\n *\n * @throws When the rule lists the origin `\"*\"`.\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: Request,\n ): { headers: Record<string, string>; preflight?: Response } => {\n const from = request.headers.get(\"origin\");\n if (from === null) return { headers: {} };\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) return { headers };\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 { headers, preflight: new Response(null, { status: 204, headers }) };\n };\n}\n","import type { Effect } from \"effect\";\n\n/** What `brick({ onResponse })` receives for every response. */\nexport interface ResponseHookContext {\n request: Request;\n status: number;\n /** A copy of the response's headers: set, append or delete, and the response is sent with them. */\n headers: Headers;\n}\n\n/** What `brick({ onError })` receives for a request Brick answered with a 5xx. */\nexport interface ErrorHookContext {\n /** What failed: a defect, or a declared failure with a 5xx status. */\n error: unknown;\n request: Request;\n /** The response Brick built: the error JSON, with its trace headers. */\n response: Response;\n}\n\nexport type OnResponse = (\n context: ResponseHookContext,\n) => Effect.Effect<unknown, unknown, any>;\nexport type OnError = (\n context: ErrorHookContext,\n) => Effect.Effect<Response | void, unknown, any>;\n\n/** The same response with other headers. */\nexport const withHeaders = (response: Response, headers: Headers) =>\n new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n\n/** What an `onError` replacement keeps of the response it replaces, unless it sets its own. */\nexport function keepTraceIds(replacement: Response, replaced: Response) {\n const headers = new Headers(replacement.headers);\n for (const name of [\"x-trace-id\", \"x-request-id\", \"traceparent\"]) {\n const value = replaced.headers.get(name);\n if (value !== null && !headers.has(name)) headers.set(name, value);\n }\n return withHeaders(replacement, headers);\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. A signed-in user (one `auth.authorize` returned as\n * `{ user }`) can also run a schedule now, cancel or replay a run, and\n * resume a hook; anyone else the dashboard lets in (by token, or by\n * `authorize` returning `true`) can only look.\n *\n * Default: on when this process dispatches events (`events.dispatch` is not\n * false), off when it only records them, since another process runs its\n * schedules and workflows. Set `true` on such a process to see them anyway:\n * they are read-only there, for everyone, with a note that another process\n * runs them.\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 * A tool marked `dashboard: true` is offered there too, through\n * `DASHBOARD_MCP_ROUTE`.\n */\n mcp?: boolean;\n /**\n * How this instance's requests and logs are tagged once it copies its\n * peers' history (`peers`). Default `\"local\"`.\n */\n name?: string;\n /**\n * Other instances of the same app whose request history this dashboard\n * copies into its own, every `peerSyncMinutes`, so its history views show\n * all of them, each request tagged with its instance. It asks each peer's\n * dashboard for its requests with the peer's token, and only reads. A peer\n * that does not answer is shown as failing, and caught up on the next copy.\n * Needs `historyDays`: the copies are kept on disk with this instance's\n * own. The live view, Errors, Schedules and Workflows stay this\n * instance's own.\n */\n peers?: readonly DashboardPeer[];\n /** Minutes between copies of the peers' history. Default 5. */\n peerSyncMinutes?: number;\n}\n\n/** Another instance's dashboard, which `dashboard.peers` reads. */\nexport interface DashboardPeer {\n /** How its rows are tagged, such as `\"india\"`. Letters, digits, `-` and `_`. */\n name: string;\n /** The address its dashboard is served at, such as `https://brick-in.example.com`. */\n url: string;\n /** One of the peer's `dashboard.auth.token`, sent as `Authorization: Bearer`. */\n token: string;\n}\n\n/** Where the app answers MCP for the dashboard's `/mcp`, to a request the dashboard signed. */\nexport const DASHBOARD_MCP_ROUTE = \"/_brick/dashboard/mcp\";\n\n/** The dashboard's own MCP tools. */\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 {\n port,\n host,\n auth,\n historyDays,\n inspector,\n mcp,\n name,\n peers,\n peerSyncMinutes,\n } = 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 if (\n name !== undefined &&\n (typeof name !== \"string\" || !INSTANCE_NAME.test(name))\n )\n throw new Error(\n `Brick: dashboard name must be letters, digits, '-' and '_', not ${JSON.stringify(name)}.`,\n );\n const peerList =\n peers === undefined ? undefined : normalizePeers(peers, name);\n if (peerList && peerList.length > 0 && !(Number(historyDays) > 0))\n throw new Error(\n \"Brick: dashboard peers need historyDays: the copies of their requests are kept on disk.\",\n );\n if (\n peerSyncMinutes !== undefined &&\n (typeof peerSyncMinutes !== \"number\" ||\n !(peerSyncMinutes > 0 && peerSyncMinutes <= MAX_SYNC_MINUTES))\n )\n throw new Error(\n `Brick: dashboard peerSyncMinutes must be more than 0 and at most ${MAX_SYNC_MINUTES} minutes, not ${String(peerSyncMinutes)}.`,\n );\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 ...(name !== undefined ? { name } : {}),\n ...(peerSyncMinutes !== undefined ? { peerSyncMinutes } : {}),\n };\n if (auth !== undefined) {\n if (typeof auth !== \"object\" || auth === null)\n throw new Error(\"Brick: dashboard auth must be an object.\");\n if (\n auth.token !== undefined &&\n typeof auth.token !== \"string\" &&\n !Array.isArray(auth.token)\n )\n throw new Error(\n \"Brick: dashboard token must be a string or an array of strings.\",\n );\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 if (peerList !== undefined)\n // Hidden like `auth`: each peer carries its token.\n Object.defineProperty(normalized, \"peers\", {\n enumerable: false,\n get: () => peerList,\n });\n return Object.freeze(normalized);\n}\n\n/** The longest timer interval Node and Bun keep (2^31 - 1 ms), in whole minutes. */\nconst MAX_SYNC_MINUTES = 35_791;\n\nconst INSTANCE_NAME = /^[\\w-]{1,64}$/;\n\nfunction normalizePeers(\n peers: readonly DashboardPeer[],\n self: string | undefined,\n): readonly DashboardPeer[] {\n if (!Array.isArray(peers))\n throw new Error(\"Brick: dashboard peers must be an array.\");\n const names = new Set([self ?? \"local\"]);\n return Object.freeze(\n peers.map((peer) => {\n const { name, url, token } = peer ?? ({} as DashboardPeer);\n if (typeof name !== \"string\" || !INSTANCE_NAME.test(name))\n throw new Error(\n `Brick: a dashboard peer's name must be letters, digits, '-' and '_', not ${JSON.stringify(name)}.`,\n );\n if (names.has(name))\n throw new Error(\n `Brick: dashboard peer '${name}' has the name of another instance; give each its own.`,\n );\n names.add(name);\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(\n `Brick: dashboard peer '${name}' needs a url, such as 'https://brick-in.example.com'.`,\n );\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\")\n throw new Error(\n `Brick: dashboard peer '${name}' url must be http or https.`,\n );\n if (typeof token !== \"string\" || token.length < MIN_TOKEN_LENGTH)\n throw new Error(\n `Brick: dashboard peer '${name}' needs its dashboard token (at least ${MIN_TOKEN_LENGTH} characters).`,\n );\n return Object.freeze({\n name,\n url: parsed.origin + parsed.pathname.replace(/\\/+$/, \"\"),\n token,\n });\n }),\n );\n}\n","import { Effect, Result, Schema } from \"effect\";\nimport type { AnySchema } from \"./action\";\nimport type { CallContext } from \"./context\";\nimport { BrickError, DuplicateNameError, ValidationError } from \"./errors\";\nimport type { AnyService } from \"./service\";\nimport type { AnyTool, ToolAnnotations } from \"./tool\";\n\ntype Json = Record<string, any>;\n\nexport interface McpToolDefinition {\n name: string;\n title?: string;\n description: string;\n /** The JSON Schema of the tool's `input`. */\n inputSchema: Json;\n /** The JSON Schema of the tool's `output`; a non-object one is wrapped as `{ result }`. */\n outputSchema?: Json;\n annotations: ToolAnnotations;\n}\n\nexport interface McpRegistryOptions {\n services?: readonly Pick<AnyService, \"listTools\">[];\n tools?: readonly AnyTool[];\n}\n\nexport interface McpRegistry<R = any> {\n listTools(): McpToolDefinition[];\n /** Runs the tool as an MCP client would: arguments are JSON, and the result is its JSON form. */\n callTool(\n name: string,\n args?: Record<string, unknown>,\n ctx?: CallContext,\n ): Effect.Effect<unknown, BrickError | ValidationError | UnknownToolError, R>;\n}\n\nexport class UnknownToolError extends Error {\n override readonly name = \"UnknownToolError\";\n constructor(name: string) {\n super(`unknown tool: ${name}`);\n }\n}\n\n// MCP requires an object outputSchema, so other outputs travel as `{ result }`.\nexport const WRAP_RESULT = \"x-brick-wrap-result\";\n\nconst jsonSchema = (schema: AnySchema): Json => {\n const { schema: root, definitions } = Schema.toJsonSchemaDocument(schema);\n // An identified schema comes back as a bare `$ref`; MCP wants the object itself at the root.\n const ref = (root as Json).$ref;\n const base =\n typeof ref === \"string\" && definitions[ref.split(\"/\").pop()!]\n ? { ...definitions[ref.split(\"/\").pop()!] }\n : (root as Json);\n return Object.keys(definitions).length\n ? { ...base, $defs: definitions }\n : base;\n};\nconst wrapped = (schema: Json): Json =>\n schema.type === \"object\"\n ? schema\n : {\n type: \"object\",\n properties: { result: schema },\n required: [\"result\"],\n ...(schema.$defs && { $defs: schema.$defs }),\n [WRAP_RESULT]: true,\n };\n\n/** Collect only explicitly defined tools, without exposing ordinary actions. */\nexport function createMcpRegistry(options: McpRegistryOptions): McpRegistry {\n const described = new WeakMap<AnyTool, McpToolDefinition>();\n const toolsByName = () => {\n const tools = new Map<string, AnyTool>();\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 const describe = (tool: AnyTool): McpToolDefinition => {\n const known = described.get(tool);\n if (known) return known;\n const { title, annotations, description, input, output } = tool.config;\n const shown = title ?? annotations?.title;\n const definition: McpToolDefinition = {\n name: tool.name,\n ...(shown && { title: shown }),\n description: description ?? \"\",\n inputSchema: input\n ? jsonSchema(input)\n : { type: \"object\", properties: {}, additionalProperties: false },\n ...(output && { outputSchema: wrapped(jsonSchema(output)) }),\n annotations: annotations ?? {},\n };\n described.set(tool, definition);\n return definition;\n };\n toolsByName();\n return {\n listTools: () => Array.from(toolsByName().values(), describe),\n callTool: (name, args = {}, ctx) => {\n const tool = toolsByName().get(name);\n return tool\n ? tool.execute({ input: args, ctx, wire: \"json\" })\n : Effect.fail(new UnknownToolError(name));\n },\n };\n}\n\nexport interface McpHandlerOptions<R = any> {\n registry: McpRegistry<R>;\n serverInfo: { name: string; version: string; title?: string };\n /** Versions supported by this transport, newest first. */\n protocolVersions?: readonly string[];\n}\n\nconst PARSE_ERROR = Symbol(\"parse error\");\nconst result = (id: unknown, value: unknown) =>\n Response.json({ jsonrpc: \"2.0\", id, result: value });\nconst rpcError = (id: unknown, code: number, message: string) =>\n Response.json({ jsonrpc: \"2.0\", id, error: { code, message } });\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * A stateless MCP JSON-RPC handler over HTTP POST. It does no authentication:\n * wrap it with your own, and pass what the tools should see in `ctx` (the\n * `request` is added).\n */\nexport function createMcpHandler<R = any>(options: McpHandlerOptions<R>) {\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 (\n request: Request,\n ctx?: CallContext,\n ): Effect.Effect<Response, never, R> =>\n Effect.gen(function* () {\n if (request.method !== \"POST\")\n return new Response(null, { status: 405, headers: { Allow: \"POST\" } });\n const body: unknown = yield* Effect.tryPromise(() => request.json()).pipe(\n Effect.orElseSucceed(() => PARSE_ERROR),\n );\n if (body === PARSE_ERROR) return rpcError(null, -32700, \"parse error\");\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 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 const outcome = yield* options.registry\n .callTool(\n params.name,\n params.arguments as Record<string, unknown> | undefined,\n { ...ctx, request },\n )\n .pipe(Effect.result);\n if (Result.isFailure(outcome)) {\n const error = outcome.failure;\n return error instanceof UnknownToolError\n ? rpcError(id, -32602, error.message)\n : result(id, {\n content: [{ type: \"text\", text: error.message }],\n isError: true,\n });\n }\n const value = outcome.success;\n const schema = options.registry\n .listTools()\n .find((tool) => tool.name === params.name)?.outputSchema;\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 structuredContent: schema[WRAP_RESULT]\n ? { result: value }\n : value,\n }),\n });\n }\n default:\n return rpcError(id, -32601, `method not found: ${method}`);\n }\n });\n}\n","import type { Effect } from \"effect\";\nimport type { HttpMethod } from \"./action\";\nimport type { Logger } from \"./context\";\nimport type { AnyDatabaseHandle } from \"./db\";\nimport { pathParamNames, toOpenApiPath } from \"./routes\";\nimport type { AnyService } from \"./service\";\n\nexport type EndpointMethod = HttpMethod;\n\n/** What a raw endpoint's handler receives. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n /** The JSON body, the text of any other body, or `undefined`. */\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Set the response's status and headers. Mutate it from the handler. */\n set: { status?: number; headers: Record<string, string> };\n /** The database of `service` (or of the first service that has one); `undefined` when there is none. */\n db: any;\n logger: Logger;\n traceId: string;\n requestId: string;\n}\n\n/**\n * A plain route beside the actions: a page, a redirect, a webhook receiver for\n * a provider Brick has no verifier for. Mount it with `brick({ endpoints })` or\n * `app.endpoint()`. Its handler returns an Effect, which may need the services\n * of the app's `layer`; a failure becomes the same error JSON as an action's.\n */\nexport interface EndpointDefinition<E = any, R = any> {\n method: EndpointMethod;\n /** Path with `:name` parameters, such as `/p/:slug`. */\n path: string;\n /**\n * Its value is the response: a `Response`, text, or JSON; `undefined` is an\n * empty 200. `ctx.set` changes the status and headers of the other kinds.\n */\n handler: (ctx: EndpointContext) => Effect.Effect<unknown, E, R>;\n /** Where `ctx.db` comes from: a service, or its name. Defaults to the first service with a database. */\n service?: AnyService | string;\n /** An explicit database, independent of a service. */\n database?: AnyDatabaseHandle;\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/** The database of the service an endpoint names, or of the first that has one. */\nexport function resolveEndpointDatabase(\n service: AnyService | string | undefined,\n services: readonly AnyService[],\n): AnyDatabaseHandle | undefined {\n if (service)\n return (\n typeof service === \"string\"\n ? services.find((item) => item.name === service)\n : service\n )?.database;\n return services.find((item) => item.database)?.database;\n}\n\n/** The OpenAPI `paths` of the endpoints. */\nexport function endpointPaths(\n defs: readonly EndpointDefinition[],\n): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const path = toOpenApiPath(def.path);\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n (paths[path] ??= {})[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","import { Effect } from \"effect\";\nimport type {\n PluginInstallOptions,\n PluginInstance,\n PluginManifest,\n} from \"./define-plugin\";\nimport type { InstalledPlugin } from \"./plugin-types\";\nimport { PLUGIN_DEPS } from \"./deps\";\nimport type { EventListener } from \"./events/types\";\n\nexport const INTERNALS = Symbol.for(\"brickkit.effect.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 /** The absolute path of the plugin's dashboard extension. */\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}\nconst internalsOf = (value: unknown): Internals | undefined =>\n isPluginInstance(value)\n ? ((value as unknown as Record<symbol, Internals>)[INTERNALS] ?? undefined)\n : undefined;\n\n/** The deps a plugin was installed with. */\nexport const pluginDepsOf = (\n value: unknown,\n): Readonly<Record<string, unknown>> => internalsOf(value)?.deps ?? {};\n\ntype Hook = (context: any) => Effect.Effect<unknown, unknown, any>;\n\n/** What a plugin's app part contributes to a running app. */\nexport interface PluginLifecycle {\n start: Effect.Effect<void, unknown, any>;\n stop: Effect.Effect<void, unknown, any>;\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 and middleware 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: PluginLifecycle[] = [];\n const middleware: Hook[] = [];\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 Hook[], stop: [] as Hook[] };\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, returns the plugin's deps.\n listeners.push(\n ...items.map((listener) => ({ ...listener, [PLUGIN_DEPS]: deps })),\n );\n },\n });\n const run = (hooks: Hook[]) =>\n Effect.forEach(hooks, (handler) => handler(lifecycle), {\n discard: true,\n });\n lifecycles.push({ start: run(own.start), stop: run(own.stop) });\n }\n return {\n lifecycles,\n middleware,\n listeners,\n plugins: listed,\n /** The deps of every plugin installed in the app, for the file storages among them. */\n deps: ordered.map((plugin) => internalsOf(plugin)!.deps),\n };\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(\n lifecycles: readonly PluginLifecycle[],\n run: (effect: Effect.Effect<void, unknown, any>) => Promise<void>,\n) {\n let started: Promise<void> | undefined;\n const running: PluginLifecycle[] = [];\n const stopAll = async () => {\n const errors: unknown[] = [];\n for (const item of running.splice(0).reverse())\n try {\n await run(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 run(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 { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { Cause, Effect, Exit, Result } from \"effect\";\nimport { createLogger } from \"./context\";\nimport { publicOrigin } from \"./cors\";\nimport {\n BrickError,\n STANDARD_ERRORS,\n failureOfCause,\n toWireError,\n} from \"./errors\";\nimport type { AnyService } from \"./service\";\nimport type { RawSocketMount } from \"./raw-socket\";\nimport { SocketDenied, localBroker, socketPath } from \"./socket\";\nimport {\n SOCKET_BUFFER_BYTES,\n SOCKET_BUFFER_MESSAGES,\n SOCKET_CLOSE,\n SOCKET_CONTROL,\n SOCKET_MAX_BYTES,\n SOCKET_PROTOCOL,\n SOCKET_SIGNATURE_LENGTH,\n SOCKET_TOKEN_PROTOCOL,\n byteLength,\n encodeFrame,\n isSocketEnvelope,\n isSocketRoom,\n isSocketSeq,\n replayFrame,\n signSeq,\n splitSeq,\n} from \"./socket-protocol\";\nimport type {\n RegisteredSocket,\n SocketBroker,\n SocketBrokerMessage,\n SocketSession,\n SocketWire,\n} from \"./socket-types\";\n\n/** `brick({ sockets })`. */\nexport interface SocketsOptions {\n /** Carries emits and kicks between processes (default: `localBroker()`, this process only). */\n broker?: SocketBroker;\n /** Signs replay sequences, so they hold across processes and restarts (default: random per process). */\n secret?: string;\n}\n\n/** Runs an Effect in the app's runtime. */\nexport type SocketRunner = <A, E>(\n effect: Effect.Effect<A, E, any>,\n) => Promise<Exit.Exit<A, E>>;\n\ninterface Connection {\n ws: Bun.ServerWebSocket<SocketData>;\n session: SocketSession;\n wire: SocketWire;\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 /** Emits that arrive for a replay room while its history is read; sent after it. */\n joining: Map<string, (SocketBrokerMessage & { type: \"emit\" })[]>;\n}\n\n/** What Bun keeps with a connection. `mounted` is the route that owns it, a Brick socket or a raw one. */\ninterface SocketData {\n mounted: {\n open(ws: any): void | Promise<void>;\n message(ws: any, value: string | Buffer): void;\n close(ws: any, code: number, reason: string): Promise<void>;\n };\n session: SocketSession;\n connection?: Connection;\n}\n\n/** Carries a failed run to the place that decides what it means for the connection. */\nclass Failed {\n constructor(readonly cause: Cause.Cause<unknown>) {}\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/** Whether broker sequence `a` is after `b`; both are `<number>-<number>`. */\nconst seqAfter = (a: string, b: string) => {\n const [a0, a1] = a.split(\"-\").map(Number) as [number, number];\n const [b0, b1] = b.split(\"-\").map(Number) as [number, number];\n return a0 > b0 || (a0 === b0 && a1 > b1);\n};\n\n/** What `app.listen` serves sockets with: a check and an upgrade for the `fetch` handler, and the `websocket` handler. */\nexport interface SocketMount {\n /** Whether `request` asks to upgrade to one of the app's sockets. */\n matches(request: Request): boolean;\n /** Upgrades the request, or answers why it can't be. Resolves to `undefined` once upgraded, as `Bun.serve` requires. */\n upgrade(\n request: Request,\n server: Bun.Server<any>,\n ): Promise<Response | undefined>;\n readonly websocket: Bun.WebSocketHandler<SocketData>;\n dispose(): Promise<void>;\n}\n\n/**\n * Mounts the sockets of the services: validates their routes, registers the\n * broker with them, and builds the `Bun.serve` handlers that speak the\n * `brick.v1` protocol.\n *\n * `raw` brings the raw routes in: they share the route checks, the `websocket`\n * config and the close tracking, and are upgraded by the same `fetch`.\n *\n * @throws When two sockets share a route, a socket shares one with an action,\n * or a socket has replay and the broker has no history.\n */\nexport function mountSockets(options: {\n services: readonly AnyService[];\n prefix: string;\n routes: readonly { method: string; path: string }[];\n run: SocketRunner;\n sockets?: SocketsOptions | undefined;\n raw?: RawSocketMount | undefined;\n}): SocketMount | undefined {\n const { services, prefix, routes, run } = options;\n const { broker = localBroker(), secret } = options.sockets ?? {};\n if (secret === \"\") throw new Error(\"Brick: sockets.secret can't be empty\");\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 { raw } = options;\n if (!sockets.length && !raw?.paths.length && !options.sockets)\n return undefined;\n const taken = new Set<string>();\n for (const path of [\n ...sockets.map((socket) => socket.path),\n ...(raw?.paths ?? []),\n ]) {\n if (taken.has(path))\n throw new Error(`Brick: duplicate socket route '${path}'`);\n taken.add(path);\n }\n for (const { method, path } of routes)\n if (method === \"GET\" && taken.has(path))\n throw new Error(\n `Brick: route '${method} ${path}' conflicts with a socket`,\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 // 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 for (const { definition } of sockets) definition.brokers.add(broker);\n\n let server: Bun.Server<SocketData> | undefined;\n const closing = new Set<Promise<void>>();\n const mounted = sockets.map((socket) => ({\n path: socket.path,\n socket: mountSocket(socket, broker, run, () => server, sign, verify),\n }));\n const byPath = new Map(mounted.map(({ path, socket }) => [path, socket]));\n const find = (request: Request) =>\n request.method === \"GET\" &&\n request.headers.get(\"upgrade\")?.toLowerCase() === \"websocket\"\n ? byPath.get(new URL(request.url).pathname)\n : undefined;\n return {\n matches: (request) =>\n find(request) !== undefined || raw?.matches(request) === true,\n async upgrade(request, bun) {\n server = bun;\n const brickSocket = find(request);\n return brickSocket\n ? brickSocket.upgrade(request, bun)\n : raw!.upgrade(request, bun);\n },\n websocket: {\n // Bun has one limit for the server; each route enforces its own.\n maxPayloadLength: Math.max(SOCKET_MAX_BYTES, raw?.maxPayloadBytes ?? 0),\n backpressureLimit: SOCKET_BUFFER_BYTES,\n closeOnBackpressureLimit: true,\n open: (ws) => ws.data.mounted.open(ws),\n message: (ws, value) => ws.data.mounted.message(ws, value),\n close(ws, code, reason) {\n const closed = ws.data.mounted.close(ws, code, reason);\n closing.add(closed);\n void closed.finally(() => closing.delete(closed));\n },\n },\n async dispose() {\n // The `close` hooks of connections the server just dropped finish before the runtime goes.\n await Promise.all(closing);\n raw?.dispose();\n for (const { definition } of sockets) definition.brokers.delete(broker);\n await broker.close?.();\n },\n };\n}\n\ninterface MountedSocket {\n upgrade(\n request: Request,\n server: Bun.Server<SocketData>,\n ): Promise<Response | undefined>;\n open(ws: Bun.ServerWebSocket<SocketData>): Promise<void>;\n message(ws: Bun.ServerWebSocket<SocketData>, value: string | Buffer): void;\n close(\n ws: Bun.ServerWebSocket<SocketData>,\n code: number,\n reason: string,\n ): Promise<void>;\n}\n\n/** Each connection owns its queue and session. */\nfunction mountSocket(\n { service, definition }: { service: string; definition: RegisteredSocket },\n broker: SocketBroker,\n run: SocketRunner,\n getServer: () => Bun.Server<SocketData> | undefined,\n sign: (topic: string, seq: string) => string,\n verify: (topic: string, signed: string) => string | undefined,\n): MountedSocket {\n const logger = createLogger();\n const where = `[Brick socket ${service}.${definition.schema.name}]`;\n const holders = new Map<\n string,\n { connections: Set<Connection>; unsubscribe: () => void }\n >();\n const roomOf = (topic: string) => topic.slice(definition.topicPrefix.length);\n const control = (\n ws: Bun.ServerWebSocket<SocketData>,\n event: string,\n data: unknown,\n ) => {\n if (ws.readyState === 1) ws.send(encodeFrame(event, data));\n };\n const attempt = async <A>(effect: Effect.Effect<A, unknown, any>) => {\n const exit = await run(effect);\n if (Exit.isSuccess(exit)) return exit.value;\n throw new Failed(exit.cause);\n };\n /** The declared or core failure of a run, else the typed failure, else what was thrown. */\n const failureOf = (error: unknown) => {\n if (!(error instanceof Failed)) return error;\n const known = failureOfCause(error.cause);\n if (known) return known;\n const found = Cause.findError(error.cause);\n return Result.isSuccess(found) ? found.success : error;\n };\n const describe = (error: unknown) =>\n error instanceof Failed ? Cause.pretty(error.cause) : error;\n /** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */\n const enter = async (connection: Connection, topic: string, live = true) => {\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 = { connections: new Set(), unsubscribe: () => {} };\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 leave = (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 getServer()?.publish(message.topic, frameOf(message));\n for (const connection of holders.get(message.topic)?.connections ?? [])\n connection.joining.get(message.topic)?.push(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 leave(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 (connection: Connection, event: string, data: unknown) => {\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)) leave(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 attempt(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 // The socket is not subscribed yet, so what is emitted from here on is kept for after the history.\n if (replay) connection.joining.set(topic, []);\n const entered = enter(connection, topic, !replay);\n connection.requested.add(topic);\n try {\n await entered;\n if (replay && connection.rooms.has(topic)) {\n // Held in this process before reading history, so later emits are in it, kept for after 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 // Emits published after the history was read, which the subscription would have missed.\n const last =\n restart ??\n missed!\n .flatMap((m) => (m.type === \"emit\" && m.seq ? [m.seq] : []))\n .at(-1) ??\n start!;\n for (const message of connection.joining.get(topic) ?? [])\n if (seqAfter(message.seq!, last))\n connection.ws.send(frameOf(message));\n }\n }\n } finally {\n connection.joining.delete(topic);\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: Bun.ServerWebSocket<SocketData>, error: unknown) => {\n const denied = failureOf(error) instanceof SocketDenied;\n if (!denied) logger.error(where, describe(error));\n if (ws.readyState !== 1) return;\n ws.close(\n denied ? SOCKET_CLOSE.policy : SOCKET_CLOSE.serverError,\n denied ? \"Message refused\" : \"Socket handler failed\",\n );\n };\n const mounted: MountedSocket = {\n async upgrade(request, server) {\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 let session: SocketSession;\n try {\n session = await attempt(definition.connect(resolved));\n } catch (error) {\n const denied = failureOf(error) instanceof SocketDenied;\n if (!denied) logger.error(where, describe(error));\n return new Response(\"Socket connection refused\", {\n status: denied ? 403 : 500,\n });\n }\n const upgraded = server.upgrade(request, {\n data: { mounted, session },\n ...(protocols(request).includes(SOCKET_PROTOCOL) && {\n headers: { \"Sec-WebSocket-Protocol\": SOCKET_PROTOCOL },\n }),\n });\n return upgraded\n ? undefined\n : new Response(\"Socket upgrade failed\", { status: 400 });\n },\n async open(ws) {\n const wire: SocketWire = {\n get isOpen() {\n return !connection.closed && ws.readyState === 1;\n },\n send(frame) {\n if (!wire.isOpen) throw new Error(\"Socket is closed\");\n if (ws.send(frame) === 0) {\n ws.close(SOCKET_CLOSE.tryAgainLater, \"Socket buffer full\");\n throw new Error(\"Socket buffer full\");\n }\n },\n close() {\n ws.close(SOCKET_CLOSE.normal, \"\");\n },\n };\n const connection: Connection = {\n ws,\n session: ws.data.session,\n wire,\n tail: Promise.resolve(),\n pending: 0,\n bytes: 0,\n closed: false,\n rooms: new Set(),\n requested: new Set(),\n joining: new Map(),\n };\n ws.data.connection = connection;\n try {\n await Promise.all(\n connection.session.rooms.map((name) =>\n enter(connection, definition.topic(name)),\n ),\n );\n await attempt(connection.session.open(wire));\n } catch (error) {\n fail(ws, error);\n }\n },\n message(ws, value) {\n const connection = ws.data.connection;\n if (!connection || connection.closed || ws.readyState !== 1) return;\n if (typeof value !== \"string\") {\n ws.close(SOCKET_CLOSE.unsupportedData, \"Only JSON text is supported\");\n return;\n }\n const size = byteLength(value);\n if (size > SOCKET_MAX_BYTES) {\n ws.close(SOCKET_CLOSE.tooLarge, \"Message too large\");\n return;\n }\n let frame: unknown;\n try {\n frame = JSON.parse(value);\n } catch {\n ws.close(SOCKET_CLOSE.invalidPayload, \"Expected JSON envelope\");\n return;\n }\n if (!isSocketEnvelope(frame)) {\n ws.close(SOCKET_CLOSE.policy, \"Invalid socket envelope\");\n return;\n }\n if (\n connection.pending >= SOCKET_BUFFER_MESSAGES ||\n connection.bytes + size > SOCKET_BUFFER_BYTES\n ) {\n ws.close(SOCKET_CLOSE.tryAgainLater, \"Socket queue full\");\n return;\n }\n const { event, data } = frame;\n const isRoom =\n event === SOCKET_CONTROL.join || event === SOCKET_CONTROL.leave;\n connection.pending++;\n connection.bytes += size;\n connection.tail = connection.tail\n .then(async () => {\n if (connection.closed || ws.readyState !== 1) return;\n if (isRoom) await room(connection, event, data);\n else\n await attempt(\n connection.session.message(event, data, connection.wire),\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 const failure = failureOf(error);\n if (\n failure instanceof BrickError &&\n !connection.closed &&\n !isRoom &&\n Object.hasOwn(raisable, failure.code)\n )\n try {\n const reply = encodeFrame(SOCKET_CONTROL.error, {\n event,\n ...toWireError(failure),\n });\n if (byteLength(reply) > SOCKET_MAX_BYTES)\n throw new Error(\"Socket error too large\", { cause: error });\n if (ws.readyState === 1) ws.send(reply);\n return;\n } catch (unsent) {\n return fail(ws, unsent);\n }\n fail(ws, error);\n })\n .finally(() => {\n connection.pending--;\n connection.bytes -= size;\n });\n },\n async close(ws, code, reason) {\n const connection = ws.data.connection;\n if (!connection || connection.closed) return;\n connection.closed = true;\n for (const topic of connection.rooms) leave(connection, topic);\n try {\n await attempt(connection.session.close(connection.wire, code, reason));\n } catch (error) {\n logger.error(where, \"cleanup\", describe(error));\n }\n },\n };\n return mounted;\n}\n","import {\n and,\n eq,\n inArray,\n isNull,\n like,\n lt,\n or,\n sql,\n type SQL,\n} from \"drizzle-orm\";\nimport { bigint, pgTable, text as pgText } from \"drizzle-orm/pg-core\";\nimport {\n integer,\n sqliteTable,\n text as sqliteText,\n} from \"drizzle-orm/sqlite-core\";\nimport { Effect } from \"effect\";\nimport type { AnyDatabaseHandle } from \"./db\";\n\n/** The table the database-backed workflow engine keeps its state in. It creates it when missing. */\nexport const WORKFLOW_TABLE = \"brick_workflow_state\";\n\n/** The columns the engine added to `key` and `value`, with their SQL types. All are NULL on rows an older version wrote. */\nconst ADDED_COLUMNS = {\n run_id: \"text\",\n parent_id: \"text\",\n status: \"text\",\n owner: \"text\",\n lease_until: \"bigint\",\n finished_at: \"bigint\",\n} as const;\n\n/** The Postgres advisory lock key `ensure` holds while it changes the table. */\nconst ENSURE_LOCK = 7_240_815_302;\n\n/** A run's `status` column: `running` until it ends, then `done` or `failed`. */\nexport type RunStatus = \"running\" | \"done\" | \"failed\";\n\n/**\n * The run a state row belongs to, from its key: `execution/<workflow>/<id>`\n * (a workflow's name may hold slashes, an id does not), or `<kind>/<id>/...`.\n * `undefined` for a key that belongs to no run.\n */\nexport function runIdOf(key: string): string | undefined {\n if (key.startsWith(\"execution/\")) return key.slice(key.lastIndexOf(\"/\") + 1);\n const [kind, id] = key.split(\"/\");\n return [\"activity\", \"activity-at\", \"deferred\", \"clock\", \"sleep\"].includes(\n kind!,\n )\n ? id\n : undefined;\n}\n\ntype ExecutionValue = { done?: boolean; result?: string; completedAt?: number };\n\n/** What an execution row written before the engine kept `status` says about the run. */\nconst legacyStatus = (value: ExecutionValue): RunStatus => {\n if (!value.done) return \"running\";\n try {\n const exit = JSON.parse(value.result ?? \"null\")?.exit?._tag;\n return exit === \"Failure\" ? \"failed\" : \"done\";\n } catch {\n return \"done\";\n }\n};\n\n/**\n * The engine's rows: `key` and `value` hold the state, one kind of record per\n * key prefix. An execution's row also carries what the engine asks of a whole\n * run, in columns it can index: `status`, `owner` and `lease_until` (the\n * process that runs it, and until when), and `finished_at`. Every row of a run\n * carries its `run_id`, so retention removes the run in one statement.\n */\nexport function makeStore(database: AnyDatabaseHandle, db: any) {\n const postgres = database.engine !== \"sqlite\";\n const table: any = postgres\n ? pgTable(WORKFLOW_TABLE, {\n key: pgText(\"key\").primaryKey(),\n value: pgText(\"value\").notNull(),\n runId: pgText(\"run_id\"),\n parentId: pgText(\"parent_id\"),\n status: pgText(\"status\"),\n owner: pgText(\"owner\"),\n leaseUntil: bigint(\"lease_until\", { mode: \"number\" }),\n finishedAt: bigint(\"finished_at\", { mode: \"number\" }),\n })\n : sqliteTable(WORKFLOW_TABLE, {\n key: sqliteText(\"key\").primaryKey(),\n value: sqliteText(\"value\").notNull(),\n runId: sqliteText(\"run_id\"),\n parentId: sqliteText(\"parent_id\"),\n status: sqliteText(\"status\"),\n owner: sqliteText(\"owner\"),\n leaseUntil: integer(\"lease_until\"),\n finishedAt: integer(\"finished_at\"),\n });\n const dead = <A>(effect: unknown) =>\n Effect.orDie(effect as Effect.Effect<A, unknown>);\n const statement = (text: string, handle = db) =>\n dead<unknown>(\n postgres ? handle.execute(sql.raw(text)) : handle.run(sql.raw(text)),\n );\n\n /** A run no process holds: no owner, or one whose lease ran out. */\n const free = (now: number) =>\n or(isNull(table.owner), lt(table.leaseUntil, now)) as SQL;\n const unfinished = or(\n isNull(table.status),\n eq(table.status, \"running\"),\n ) as SQL;\n\n const columns = (handle = db) =>\n Effect.gen(function* () {\n if (postgres) {\n const found = yield* dead<{ rows: { name: string }[] }>(\n handle.execute(\n sql`select column_name as name from information_schema.columns where table_name = ${WORKFLOW_TABLE} and table_schema = current_schema()`,\n ),\n );\n return new Set(found.rows.map((row) => row.name));\n }\n const found = yield* dead<{ name: string }[]>(\n handle.all(sql.raw(`pragma table_info(${WORKFLOW_TABLE})`)),\n );\n return new Set(found.map((row) => row.name));\n });\n\n const set = (key: string, value: string) =>\n dead(\n db\n .insert(table)\n .values({ key, value, runId: runIdOf(key) ?? \"\" })\n .onConflictDoUpdate({ target: table.key, set: { value } }),\n );\n\n /**\n * Rows an older version wrote have no `run_id`: give each its run, and each\n * execution its status. Cheap when there are none, which is every start but\n * the first after an upgrade (or a process of the old version still running).\n */\n const backfill = () =>\n Effect.gen(function* () {\n for (;;) {\n const rows = yield* dead<{ key: string; value: string }[]>(\n db\n .select({ key: table.key, value: table.value })\n .from(table)\n .where(isNull(table.runId))\n // The same order in every process: two backfilling at once never wait on each other's rows.\n .orderBy(table.key)\n .limit(500),\n );\n if (rows.length === 0) return;\n for (const { key, value } of rows) {\n const execution = key.startsWith(\"execution/\")\n ? (JSON.parse(value) as ExecutionValue)\n : undefined;\n const status = execution && legacyStatus(execution);\n yield* dead(\n db\n .update(table)\n .set({\n runId: runIdOf(key) ?? \"\",\n ...(status && {\n status,\n ...(status !== \"running\" && {\n finishedAt: execution!.completedAt ?? Date.now(),\n }),\n }),\n })\n .where(eq(table.key, key)),\n );\n }\n }\n });\n\n const upgrade = (handle = db) =>\n Effect.gen(function* () {\n yield* statement(\n `create table if not exists ${WORKFLOW_TABLE} (key text primary key, value text not null, ${Object.entries(\n ADDED_COLUMNS,\n )\n .map(([name, type]) => `${name} ${type}`)\n .join(\", \")})`,\n handle,\n );\n const present = yield* columns(handle);\n for (const [name, type] of Object.entries(ADDED_COLUMNS))\n if (!present.has(name))\n // Another process may add it first: a SQLite refusal to add a column twice is not a failure.\n yield* Effect.catchCause(\n statement(\n `alter table ${WORKFLOW_TABLE} add column ${postgres ? \"if not exists \" : \"\"}${name} ${type}`,\n handle,\n ),\n () => Effect.void,\n );\n yield* statement(\n `create index if not exists ${WORKFLOW_TABLE}_status on ${WORKFLOW_TABLE} (status, finished_at)`,\n handle,\n );\n yield* statement(\n `create index if not exists ${WORKFLOW_TABLE}_run on ${WORKFLOW_TABLE} (run_id)`,\n handle,\n );\n });\n\n return {\n /**\n * Make the table, add the columns an older version lacks, index them, and\n * backfill the rows already there. Safe to run from several processes at once:\n * on Postgres they take turns, because concurrent `create ... if not exists`\n * statements still fail with a unique violation on its catalog. Only that\n * part holds the lock: the backfill is batches that commit on their own, so\n * a big legacy table blocks neither other engines nor the rows they write.\n */\n ensure: () =>\n Effect.andThen(\n postgres\n ? (\n db.transaction((tx: any) =>\n Effect.andThen(\n dead(\n tx.execute(\n sql`select pg_advisory_xact_lock(${ENSURE_LOCK})`,\n ),\n ),\n upgrade(tx),\n ),\n ) as Effect.Effect<void>\n ).pipe(Effect.orDie)\n : upgrade(),\n backfill(),\n ),\n /** Give the rows an older version wrote after this process started their run and status, so they are taken, renewed and swept. */\n backfill: backfill(),\n get: (key: string) =>\n dead<{ value: string }[]>(\n db.select().from(table).where(eq(table.key, key)),\n ).pipe(Effect.map((rows) => rows[0]?.value)),\n set,\n list: (prefix: string) =>\n dead<{ key: string; value: string }[]>(\n db\n .select()\n .from(table)\n .where(like(table.key, `${prefix}%`)),\n ).pipe(\n Effect.map((rows) => rows.filter((r) => r.key.startsWith(prefix))),\n ),\n /** Insert a run held by `owner` until `until`, started by the run `parentId`, if any. `false` when the run already has a row. */\n begin: (\n key: string,\n value: string,\n owner: string,\n until: number,\n parentId?: string,\n ) =>\n dead<unknown[]>(\n db\n .insert(table)\n .values({\n key,\n value,\n runId: runIdOf(key) ?? \"\",\n parentId,\n status: \"running\",\n owner,\n leaseUntil: until,\n })\n .onConflictDoNothing()\n .returning({ key: table.key }),\n ).pipe(Effect.map((rows) => rows.length > 0)),\n /**\n * Take a run no process holds. `false` when it is finished or another process holds it.\n * A row a process of an older version wrote has no `status` or `run_id` yet: they are set here, or the renewal and the retention would pass it by.\n */\n claim: (key: string, owner: string, now: number, until: number) =>\n dead<unknown[]>(\n db\n .update(table)\n .set({\n owner,\n leaseUntil: until,\n status: \"running\",\n runId: runIdOf(key) ?? \"\",\n })\n .where(and(eq(table.key, key), unfinished, free(now)))\n .returning({ key: table.key }),\n ).pipe(Effect.map((rows) => rows.length > 0)),\n /** Extend every lease `owner` holds. Returns the keys it still holds. */\n renew: (owner: string, until: number) =>\n dead<{ key: string }[]>(\n db\n .update(table)\n .set({ leaseUntil: until })\n .where(and(eq(table.owner, owner), eq(table.status, \"running\")))\n .returning({ key: table.key }),\n ).pipe(Effect.map((rows) => new Set(rows.map((row) => row.key)))),\n /** Let go of every lease `owner` holds, so another process takes those runs without waiting. */\n release: (owner: string) =>\n dead(\n db\n .update(table)\n .set({ owner: null, leaseUntil: null })\n .where(and(eq(table.owner, owner), eq(table.status, \"running\"))),\n ),\n /** End a run: its final value, its status and when it ended, and nobody holds it. */\n finish: (key: string, value: string, status: RunStatus, at: number) =>\n dead(\n db\n .update(table)\n .set({\n value,\n status,\n finishedAt: at,\n owner: null,\n leaseUntil: null,\n })\n .where(eq(table.key, key)),\n ),\n /** Unfinished runs nobody holds. */\n unheld: (now: number) =>\n dead<{ key: string; value: string }[]>(\n db\n .select({ key: table.key, value: table.value })\n .from(table)\n .where(and(eq(table.status, \"running\"), free(now))),\n ),\n /**\n * The ids of up to `limit` runs that ended with `status` before `before`,\n * and whose parent run, if any, is not running: the parent's replay reads\n * what its children ended with.\n */\n endedBefore: (status: RunStatus, before: number, limit: number) =>\n dead<{ runId: string }[]>(\n db\n .select({ runId: table.runId })\n .from(table)\n .where(\n and(\n eq(table.status, status),\n lt(table.finishedAt, before),\n sql`not exists (select 1 from ${sql.raw(WORKFLOW_TABLE)} parent where parent.run_id = ${table.parentId} and parent.status = 'running')`,\n ),\n )\n .limit(limit),\n ).pipe(Effect.map((rows) => rows.map((row) => row.runId))),\n /** Delete every row of these runs. */\n remove: (runIds: readonly string[]) =>\n dead(db.delete(table).where(inArray(table.runId, [...runIds]))),\n /** The keys of the durable deferreds saved for these runs. */\n deferreds: (runIds: readonly string[]) =>\n dead<{ key: string }[]>(\n db\n .select({ key: table.key })\n .from(table)\n .where(\n and(\n inArray(table.runId, [...runIds]),\n like(table.key, \"deferred/%\"),\n ),\n ),\n ).pipe(Effect.map((rows) => rows.map((row) => row.key))),\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport {\n Cause,\n Clock,\n Context,\n Deferred,\n Duration,\n Effect,\n Exit,\n Fiber,\n FiberMap,\n Layer,\n Option,\n Schema,\n Schedule,\n Scope,\n Semaphore,\n} from \"effect\";\nimport { Workflow, WorkflowEngine } from \"effect/workflow\";\nimport type { SqlError } from \"effect/sql/SqlError\";\nimport type { AnyDatabaseHandle } from \"./db\";\nimport { pollUnref } from \"./events/unref\";\nimport { makeStore, runIdOf } from \"./workflow-store\";\n\nexport {\n Activity,\n DurableClock,\n DurableDeferred,\n Workflow,\n WorkflowEngine,\n} from \"effect/workflow\";\n\nexport { WORKFLOW_TABLE } from \"./workflow-store\";\n\nconst AnyOrVoid = Schema.Union([Schema.Any, Schema.Void]);\nconst resultCodec = Schema.toCodecJson(\n Workflow.Result({ success: AnyOrVoid, error: AnyOrVoid }),\n);\n// A value of `undefined` has no JSON form, as the engines' own deferred results do.\nconst jsonable = (result: Workflow.Result<unknown, unknown>) =>\n result._tag === \"Complete\"\n ? new Workflow.Complete({\n exit: Exit.map(result.exit, (value: unknown) => value ?? null),\n })\n : result;\nconst encodeResult = (result: Workflow.Result<unknown, unknown>) =>\n Effect.map(\n Schema.encodeUnknownEffect(resultCodec)(jsonable(result)),\n (encoded) => JSON.stringify(encoded),\n ).pipe(Effect.orDie);\nexport const decodeResult = (text: string) =>\n Schema.decodeUnknownEffect(resultCodec)(JSON.parse(text)).pipe(\n Effect.orDie,\n ) as Effect.Effect<Workflow.Result<unknown, unknown>>;\n\n/**\n * The rows of the engine's state, which the dashboard reads for its Workflows\n * view. `workflowEngine` provides it beside the engine; `brick()` reads it from\n * the app's runtime. The keys are the engine's own, so it is read with\n * `workflowWorld` only.\n */\nexport class WorkflowState extends Context.Service<\n WorkflowState,\n {\n readonly get: (key: string) => Effect.Effect<string | undefined>;\n readonly list: (\n prefix: string,\n ) => Effect.Effect<readonly { key: string; value: string }[]>;\n }\n>()(\"@brickkit/effect/WorkflowState\") {}\n\n/** The key prefixes of the state: `execution/<workflow>/<id>`, `activity/<id>/<name>/<attempt>` and its `activity-at/` time. */\nexport const stateKeys = {\n execution: (name: string, id: string) => `execution/${name}/${id}`,\n activity: (id: string, name: string, attempt: number) =>\n `activity/${id}/${name}/${attempt}`,\n activityAt: (id: string, name: string, attempt: number) =>\n `activity-at/${id}/${name}/${attempt}`,\n} as const;\n\nconst RetryingExecution = Context.Reference<string | undefined>(\n \"effect/workflow/Activity/RetryingExecution\",\n { defaultValue: () => undefined },\n);\n\n/** Reuses `prev` while it is still an empty child of `parent`, so replays that register nothing do not grow `parent`. */\nconst reuseOrForkScope = (\n prev: Scope.Closeable | undefined,\n parent: Scope.Scope,\n): Scope.Closeable =>\n prev !== undefined && prev.parent === parent && prev.state._tag === \"Empty\"\n ? prev\n : Scope.forkUnsafe(parent);\n\ntype WakeMode = \"explicit\" | \"automatic\";\ntype Run = Workflow.Result<unknown, unknown>;\ntype Execute = (\n payload: object,\n executionId: string,\n) => Effect.Effect<\n unknown,\n unknown,\n WorkflowEngine.WorkflowInstance | WorkflowEngine.WorkflowEngine\n>;\n\nconst isUnwakeable = (result: Run, mode: WakeMode) =>\n result._tag === \"Complete\" ||\n (mode === \"automatic\" && result.failed === true);\n\nconst DAY = 86_400_000;\n\n/** What `workflowEngine` takes besides the database. */\nexport interface WorkflowEngineOptions {\n /**\n * How long finished runs are kept, and how often the sweep that deletes the\n * older ones runs. `false` keeps them for ever. A run's activity results,\n * deferreds and clocks go with it. Defaults: `doneDays` 7, `failedDays` 30,\n * `intervalMs` one hour.\n */\n readonly retention?:\n | false\n | {\n readonly doneDays?: number;\n readonly failedDays?: number;\n readonly intervalMs?: number;\n };\n /**\n * How long a process holds the runs it started, in milliseconds. It renews\n * them every third of this while it lives; the runs of a process that died are\n * taken by another once this has passed. Default 30000. Keep it far above the\n * clock difference between your processes.\n */\n readonly leaseMs?: number;\n}\n\n/**\n * A workflow engine that keeps its state in the app's database, so a run\n * survives a restart. It runs workflows as the in-memory engine of\n * `effect/workflow` does, and writes through what a restart needs:\n *\n * - each execution with its payload, until it finishes, and then its result;\n * - the result of each activity attempt that finished;\n * - each durable deferred that completed;\n * - the wake time of each durable clock.\n *\n * A run ends `done`, or `failed` when it fails (its handler fails or dies, or an\n * activity's retries run out and the failure escapes). The `status` column and\n * the run's value hold which, and the cause.\n *\n * One process runs a run at a time. A process takes a run by writing its own\n * `owner` and a `lease_until` on it, and renews that while the run lives; other\n * processes leave it alone. When a workflow registers (its `toLayer`), and then\n * on every renewal, the process takes the unfinished runs of its workflows that\n * nobody holds: ones a process released when it stopped, or whose lease ran out\n * because it died. They replay, reading the saved results, so an activity that\n * finished does not run twice; a durable clock sleeps only what was left. Run\n * workflows only in the processes that should run them: a process that does not\n * register a workflow never takes its runs.\n *\n * Finished runs are deleted by a periodic sweep: see `retention`.\n *\n * It creates the `brick_workflow_state` table on first use, and adds the columns\n * it needs to one an older version made. Put it in the app's `layer`, with the\n * workflows' `toLayer` layers provided by it.\n *\n * @example\n * const engine = workflowEngine(database, { retention: { doneDays: 3 } });\n * brick({ services, layer: Layer.mergeAll(engine, Layer.provide(OrderFlow.toLayer(run), engine)) });\n */\nexport function workflowEngine(\n database: AnyDatabaseHandle,\n options: WorkflowEngineOptions = {},\n): Layer.Layer<WorkflowEngine.WorkflowEngine, SqlError> {\n const leaseMs = options.leaseMs ?? 30_000;\n const retention =\n options.retention === false\n ? undefined\n : {\n doneDays: options.retention?.doneDays ?? 7,\n failedDays: options.retention?.failedDays ?? 30,\n intervalMs: options.retention?.intervalMs ?? 3_600_000,\n };\n const build = Effect.gen(function* () {\n const db = yield* database.Database;\n const store = makeStore(database, db);\n yield* store.ensure();\n const scope = yield* Effect.scope;\n // Names the process in the `owner` column of the runs it holds.\n const owner = randomUUID();\n yield* Effect.addFinalizer(() =>\n Effect.catchCause(store.release(owner), () => Effect.void),\n );\n\n const executionKey = stateKeys.execution;\n const activityKey = stateKeys.activity;\n const deferredKey = (id: string, name: string) => `deferred/${id}/${name}`;\n const clockKey = (id: string, name: string) => `clock/${id}/${name}`;\n // Durable deferreds of the runs this process runs that it has seen saved, by run: only a new one can wake a suspended run. A run's go when it ends or is lost.\n const seenDeferreds = new Map<string, Set<string>>();\n const sawDeferred = (key: string) => {\n const runId = runIdOf(key)!;\n const state = executions.get(runId);\n if (!state || state.finished) return;\n const seen = seenDeferreds.get(runId) ?? new Set<string>();\n seenDeferreds.set(runId, seen);\n seen.add(key);\n };\n const sleepKey = (id: string, name: string, attempt: number) =>\n `sleep/${id}/${name}/${attempt}`;\n\n /**\n * `DurableClock.sleep` of at most 60 seconds is an in-memory sleep inside an\n * activity named `DurableClock/<name>`. Its wake time is saved on the first\n * attempt, so a replay after a restart sleeps only what was left.\n */\n const resumableSleep = (key: string) =>\n Effect.updateService(Clock.Clock, (clock) =>\n Object.create(clock, {\n sleep: {\n value: (duration: Duration.Duration) =>\n Effect.gen(function* () {\n const saved = yield* store.get(key);\n const wakeAt =\n saved === undefined\n ? Date.now() + Duration.toMillis(duration)\n : Number(saved);\n if (saved === undefined) yield* store.set(key, String(wakeAt));\n return yield* clock.sleep(\n Duration.millis(Math.max(0, wakeAt - Date.now())),\n );\n }),\n },\n }),\n );\n\n const workflows = new Map<\n string,\n { workflow: Workflow.Any; execute: Execute; scope: Scope.Scope }\n >();\n\n type ExecutionState = {\n readonly payload: object;\n readonly execute: Execute;\n readonly parents: Set<string>;\n instance: WorkflowEngine.WorkflowInstance[\"Service\"];\n interrupted: boolean;\n interruptedUnsafe: boolean;\n resumeRequested: WakeMode | undefined;\n fiber: Fiber.Fiber<Run> | undefined;\n readonly done: Deferred.Deferred<void>;\n scope: Scope.Closeable;\n /** The run ended: the lease is let go and the row says how. */\n finished: boolean;\n };\n const executions = new Map<string, ExecutionState>();\n const activities = new Map<string, { exit: Exit.Exit<Run> | undefined }>();\n const deferredState = WorkflowEngine.makeDeferredState();\n const deferredResults = new Map<string, Exit.Exit<any, any>>();\n /** Drops a run that leaves this process, with what it cached, so a later run of the same id reads the store. */\n const forget = (executionId: string) => {\n executions.delete(executionId);\n const prefix = `${executionId}/`;\n for (const cache of [activities, deferredResults])\n for (const key of cache.keys())\n if (key.startsWith(prefix)) cache.delete(key);\n };\n const clocks = yield* FiberMap.make<string>();\n const runSetup = Semaphore.makeUnsafe(1);\n // Runs that ended here whose end the database refused, with the write to try again.\n const unsaved = new Map<string, Effect.Effect<void>>();\n // Child runs another process holds that a parent here waits for: the parent is suspended, and woken once the child's result is saved.\n const awaitedElsewhere = new Map<\n string,\n { name: string; parents: Set<string> }\n >();\n // Runs this process lost to another, with the `done` of each state that was lost: the turn completes them (see `settleLost`).\n const lost = new Map<\n string,\n { name: string; dones: Deferred.Deferred<void>[] }\n >();\n // Wall-clock time, like a run's own; a step ending in the same millisecond as the last one is stamped later.\n let lastStamp = 0;\n const stamp = () => (lastStamp = Math.max(Date.now(), lastStamp + 0.001));\n\n /**\n * Ends the execution, `failed` when its result is a failure, with the result,\n * which `poll` reads once the process that ran it is gone, and the cause.\n */\n const finish = (name: string, executionId: string, result: Run) =>\n Effect.flatMap(store.get(executionKey(name, executionId)), (row) =>\n row === undefined\n ? Effect.void\n : Effect.flatMap(encodeResult(result), (saved) => {\n const failed =\n result._tag === \"Complete\" && Exit.isFailure(result.exit);\n const at = Date.now();\n return Effect.asVoid(\n store.finish(\n executionKey(name, executionId),\n JSON.stringify({\n ...JSON.parse(row),\n done: true,\n ...(failed && {\n failed: true,\n error: Cause.pretty(\n (result.exit as Exit.Failure<unknown, unknown>).cause,\n ).slice(0, 4000),\n }),\n result: saved,\n completedAt: at,\n }),\n failed ? \"failed\" : \"done\",\n at,\n ),\n );\n }),\n );\n\n /** The result of an execution that finished before this process started, if it did. */\n const saved = (name: string, executionId: string) =>\n Effect.gen(function* () {\n const row = yield* store.get(executionKey(name, executionId));\n const { result } = row ? JSON.parse(row) : ({} as { result?: string });\n return result === undefined\n ? Option.none<Run>()\n : Option.some(yield* decodeResult(result));\n });\n\n const resume: (executionId: string, mode: WakeMode) => Effect.Effect<void> =\n Effect.fnUntraced(function* (\n executionId: string,\n mode: WakeMode,\n ): Effect.fn.Return<void> {\n const state = executions.get(executionId);\n if (!state) return;\n const exit = state.fiber?.pollUnsafe();\n if (exit && exit._tag === \"Success\" && isUnwakeable(exit.value, mode)) {\n return;\n } else if (state.fiber && !exit) {\n const requested = state.resumeRequested;\n state.resumeRequested =\n mode === \"explicit\" ? mode : (requested ?? mode);\n if (requested === undefined) {\n yield* Fiber.await(state.fiber).pipe(\n Effect.flatMap(() => {\n const mode = state.resumeRequested!;\n state.resumeRequested = undefined;\n return resume(executionId, mode);\n }),\n Effect.forkIn(scope),\n );\n }\n return;\n }\n\n const entry = workflows.get(state.instance.workflow._tag)!;\n if (state.scope.state._tag === \"Closed\")\n state.scope = Scope.makeUnsafe();\n const executionScope = state.scope;\n state.instance.awaitedDeferreds.clear();\n const instance = WorkflowEngine.WorkflowInstance.initial(\n state.instance.workflow,\n state.instance.executionId,\n { scope: reuseOrForkScope(state.instance.scope, executionScope) },\n );\n state.instance = instance;\n state.fiber = yield* state\n .execute(state.payload, state.instance.executionId)\n .pipe(\n Effect.onExit((exit) => {\n if (\n !state.interrupted ||\n (!state.interruptedUnsafe &&\n !instance.suspended &&\n !instance.abandoned &&\n !(\n Context.get(\n instance.workflow.annotations,\n Workflow.SuspendOnFailure,\n ) && Exit.isFailure(exit)\n ))\n )\n return Effect.void;\n instance.interrupted = true;\n instance.suspended = false;\n return Effect.withFiber((fiber) =>\n Effect.interruptible(Fiber.interrupt(fiber)),\n );\n }),\n (effect) => deferredState.trackRun(instance, effect),\n Workflow.intoResult,\n Effect.provideService(RetryingExecution, undefined),\n Effect.provideService(WorkflowEngine.WorkflowInstance, instance),\n Effect.provideService(WorkflowEngine.WorkflowEngine, engine),\n Effect.onExit((exit) => {\n if (Exit.isSuccess(exit) && exit.value._tag === \"Suspended\")\n return Effect.void;\n const close = Scope.close(executionScope, Exit.void);\n if (Exit.isFailure(exit)) return close;\n const wakeParents = (fiber: Fiber.Fiber<unknown, unknown>) =>\n Fiber.await(fiber).pipe(\n Effect.flatMap(() =>\n Effect.forEach(\n state.parents,\n (parent) =>\n Effect.forkIn(resume(parent, \"automatic\"), scope),\n { discard: true },\n ),\n ),\n Effect.forkIn(scope),\n );\n return close.pipe(\n Effect.andThen(\n Effect.suspend(() => {\n // Before the write: the renewal must not take a run that is ending for one that was lost.\n state.finished = true;\n seenDeferreds.delete(instance.executionId);\n const write = finish(\n instance.workflow._tag,\n instance.executionId,\n exit.value,\n );\n // The run has its result: if the row cannot take it now, it is written at a later turn, and the lease is renewed until then.\n return write.pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.sync(() => {\n console.error(\n `[Brick] Workflow run ${instance.executionId} ended, but its end could not be saved; trying again:`,\n Cause.pretty(cause),\n );\n unsaved.set(instance.executionId, write);\n }),\n ),\n );\n }),\n ),\n Effect.andThen(Deferred.succeed(state.done, void 0)),\n // Its row has the result: a later start, poll or wait reads that, as for a run another process ran. A run whose end is not saved yet stays until `saveUnsaved` writes it.\n Effect.andThen(\n Effect.sync(() => {\n if (\n !unsaved.has(instance.executionId) &&\n executions.get(instance.executionId) === state\n )\n forget(instance.executionId);\n }),\n ),\n Effect.ensuring(Effect.withFiber(wakeParents)),\n );\n }),\n Effect.forkIn(entry.scope),\n ) as Effect.Effect<Fiber.Fiber<Run>>;\n }, runSetup.withPermits(1));\n\n /**\n * What a start that did not take the run waits for: its result, once the\n * process that holds it has finished it, or its state here, if this process\n * takes it over meanwhile. A parent run does not wait: it suspends, and is\n * woken when the result is there (see `awaitedElsewhere`).\n */\n const held = (name: string, executionId: string, parentId?: string) =>\n Effect.gen(function* () {\n for (let delay = 20; ; delay = Math.min(delay * 2, 500)) {\n const state = executions.get(executionId);\n if (state?.fiber) return { state } as const;\n const row = yield* store.get(executionKey(name, executionId));\n if (row === undefined)\n return yield* Effect.die(\n new Error(`Workflow run \"${executionId}\" was deleted`),\n );\n const { result } = JSON.parse(row) as { result?: string };\n if (result !== undefined)\n return { result: yield* decodeResult(result) } as const;\n if (parentId !== undefined) {\n const waiting = awaitedElsewhere.get(executionId);\n if (waiting) waiting.parents.add(parentId);\n else\n awaitedElsewhere.set(executionId, {\n name,\n parents: new Set([parentId]),\n });\n return { suspended: true } as const;\n }\n yield* Effect.sleep(delay);\n }\n });\n\n const start = (\n workflow: Workflow.Any,\n options: {\n readonly executionId: string;\n readonly payload: object;\n readonly discard: boolean;\n readonly parent?:\n | WorkflowEngine.WorkflowInstance[\"Service\"]\n | undefined;\n readonly detached?: boolean | undefined;\n },\n ) =>\n Effect.gen(function* () {\n const entry = workflows.get(workflow._tag);\n if (!entry)\n return yield* Effect.orDie(\n Effect.fail(`Workflow ${workflow._tag} is not registered`),\n );\n const parentId = options.detached\n ? undefined\n : options.parent?.executionId;\n let state = executions.get(options.executionId);\n if (!state) {\n const key = executionKey(workflow._tag, options.executionId);\n const now = Date.now();\n const mine =\n (yield* store.begin(\n key,\n JSON.stringify({\n payload: options.payload,\n done: false,\n startedAt: now,\n }),\n owner,\n now + leaseMs,\n // The starting run, detached or not: retention keeps this run for its replay (`parentId` is what wakes and links).\n options.parent?.executionId,\n )) || (yield* store.claim(key, owner, now, now + leaseMs));\n if (!mine) {\n // Finished, or run by another process (or by this one, a moment ago).\n if (options.discard) return;\n const found = yield* held(\n workflow._tag,\n options.executionId,\n parentId,\n );\n if (\"suspended\" in found) return new Workflow.Suspended({}) as any;\n if (\"result\" in found) return found.result as any;\n state = found.state;\n } else {\n state = {\n payload: options.payload,\n execute: entry.execute,\n instance: WorkflowEngine.WorkflowInstance.initial(\n workflow,\n options.executionId,\n ),\n interrupted: false,\n interruptedUnsafe: false,\n resumeRequested: undefined,\n fiber: undefined,\n done: Deferred.makeUnsafe(),\n scope: Scope.makeUnsafe(),\n finished: false,\n parents: new Set(parentId === undefined ? [] : [parentId]),\n };\n executions.set(options.executionId, state);\n yield* resume(options.executionId, \"explicit\");\n }\n } else if (parentId !== undefined) {\n state.parents.add(parentId);\n }\n if (options.discard) return;\n for (;;) {\n const instance = state.instance;\n const exit = yield* Fiber.await(state.fiber!);\n if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) {\n if (instance.suspended) return new Workflow.Suspended({}) as any;\n // The run was lost to another process (see `renew`), not interrupted: wait for its result as for a run held elsewhere.\n if (executions.get(options.executionId) !== state) {\n const found = yield* held(\n workflow._tag,\n options.executionId,\n parentId,\n );\n if (\"suspended\" in found)\n return new Workflow.Suspended({}) as any;\n if (\"result\" in found) return found.result as any;\n state = found.state;\n continue;\n }\n }\n return (yield* exit) as any;\n }\n });\n\n /** Takes the unfinished runs of the registered workflows that no process holds, and runs them. */\n const recover = Effect.gen(function* () {\n const prefix = \"execution/\";\n for (const { key, value } of yield* store.unheld(Date.now())) {\n const rest = key.slice(prefix.length);\n const slash = rest.lastIndexOf(\"/\");\n const entry = workflows.get(rest.slice(0, slash));\n const executionId = rest.slice(slash + 1);\n // One that this process holds has its lease renewed first, so it is not unheld for long.\n if (!entry || executions.has(executionId)) continue;\n yield* start(entry.workflow, {\n executionId,\n payload: (JSON.parse(value) as { payload: object }).payload,\n discard: true,\n });\n }\n });\n\n /** Extends the leases this process holds. A run it no longer holds was taken by another process, which found its lease run out: stop running it here. */\n const renew = Effect.gen(function* () {\n // Only runs that were here before the renewal: one started meanwhile is not in `kept`, and is not lost.\n const before = [...executions.keys()];\n const kept = yield* store.renew(owner, Date.now() + leaseMs);\n for (const executionId of before) {\n const state = executions.get(executionId);\n if (\n !state ||\n state.finished ||\n kept.has(executionKey(state.instance.workflow._tag, executionId))\n )\n continue;\n forget(executionId);\n seenDeferreds.delete(executionId);\n console.warn(\n `[Brick] Workflow run ${executionId} was taken by another process: its lease ran out here.`,\n );\n if (state.fiber) yield* Fiber.interrupt(state.fiber);\n // `awaitComplete` waits on `done`: `settleLost` completes it once the run has its result, wherever it ran.\n const waiting = lost.get(executionId);\n if (waiting) waiting.dones.push(state.done);\n else\n lost.set(executionId, {\n name: state.instance.workflow._tag,\n dones: [state.done],\n });\n }\n });\n\n /** Completes the `done` of the lost runs that have ended, here or in the process that took them: one read of each per turn, and none for a run this process took back. */\n const settleLost = Effect.gen(function* () {\n for (const [executionId, { name, dones }] of lost) {\n const here = executions.get(executionId);\n if (here && !here.finished) continue;\n if (!here) {\n const row = yield* store.get(executionKey(name, executionId));\n if (\n row !== undefined &&\n (JSON.parse(row) as { result?: string }).result === undefined\n )\n continue;\n }\n lost.delete(executionId);\n for (const done of dones) yield* Deferred.succeed(done, void 0);\n }\n });\n\n /** Writes the end of the runs whose write failed. */\n const saveUnsaved = Effect.gen(function* () {\n for (const [executionId, write] of unsaved) {\n const exit = yield* Effect.exit(write);\n if (Exit.isSuccess(exit)) {\n unsaved.delete(executionId);\n if (executions.get(executionId)?.finished) forget(executionId);\n } else if (Cause.hasInterruptsOnly(exit.cause))\n return yield* Effect.failCause(exit.cause);\n }\n });\n\n /**\n * A durable deferred another process completed was saved, but only the\n * process that holds a suspended run can wake it: look for those. A parent\n * suspended on a child another process runs is woken when the child ends.\n */\n const wake = Effect.gen(function* () {\n for (const [executionId, { name, parents }] of awaitedElsewhere) {\n const row = yield* store.get(executionKey(name, executionId));\n if (\n row !== undefined &&\n (JSON.parse(row) as { result?: string }).result === undefined\n )\n continue;\n awaitedElsewhere.delete(executionId);\n for (const parent of parents)\n yield* Effect.forkIn(resume(parent, \"automatic\"), scope);\n }\n const suspended = [...executions]\n .filter(([, state]) => {\n const exit = state.fiber?.pollUnsafe();\n return (\n !state.finished &&\n exit?._tag === \"Success\" &&\n exit.value._tag === \"Suspended\"\n );\n })\n .map(([executionId]) => executionId);\n for (let i = 0; i < suspended.length; i += 200)\n for (const key of yield* store.deferreds(suspended.slice(i, i + 200))) {\n if (seenDeferreds.get(runIdOf(key)!)?.has(key)) continue;\n sawDeferred(key);\n yield* resume(runIdOf(key)!, \"automatic\");\n }\n });\n\n /** Deletes the runs that ended before the retention allows. */\n const sweep = Effect.gen(function* () {\n if (!retention) return;\n for (const [status, days] of [\n [\"done\", retention.doneDays],\n [\"failed\", retention.failedDays],\n ] as const)\n for (;;) {\n const ids = yield* store.endedBefore(\n status,\n Date.now() - days * DAY,\n 500,\n );\n if (ids.length === 0) break;\n yield* store.remove(ids);\n }\n });\n\n // A failure or a defect of one step is logged: it must not stop the steps after it, or the next turn.\n const guarded = (what: string, effect: Effect.Effect<void>) =>\n Effect.catchCause(effect, (cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.sync(() =>\n console.error(\n `[Brick] Workflow engine ${what} failed:`,\n Cause.pretty(cause),\n ),\n ),\n );\n let lastSweep = 0;\n const turn = Effect.gen(function* () {\n yield* guarded(\"saving the end of runs\", saveUnsaved);\n yield* guarded(\"backfill\", store.backfill);\n yield* guarded(\"recovery\", recover);\n yield* guarded(\"deferred check\", wake);\n yield* guarded(\"lost runs\", settleLost);\n if (Date.now() - lastSweep >= (retention?.intervalMs ?? 0)) {\n lastSweep = Date.now();\n yield* guarded(\"retention sweep\", sweep);\n }\n });\n let maintaining = false;\n /** What a process does once it runs workflows: take what is free now, and go on renewing, taking and sweeping. A process that registers none never starts it. */\n const maintain = Effect.gen(function* () {\n yield* recover;\n if (maintaining) return;\n maintaining = true;\n const every = Schedule.spaced(Math.max(10, Math.floor(leaseMs / 3)));\n // Renewal has a loop of its own: a long recovery or sweep must not delay it past the lease.\n yield* Effect.forkIn(\n pollUnref(guarded(\"lease renewal\", renew), every),\n scope,\n );\n yield* Effect.forkIn(pollUnref(turn, every), scope);\n });\n\n const engine: WorkflowEngine.WorkflowEngine[\"Service\"] =\n WorkflowEngine.makeUnsafe({\n register: Effect.fnUntraced(function* (workflow, execute) {\n workflows.set(workflow._tag, {\n workflow,\n execute,\n scope: yield* Effect.scope,\n });\n yield* maintain;\n }),\n execute: start as never,\n awaitComplete: (workflow, executionId) =>\n Effect.suspend(() => {\n const state = executions.get(executionId);\n if (state) return Deferred.await(state.done);\n // Not here: a run that ended here is gone from memory, and one another process holds has no result yet (the caller's retry schedule covers that).\n return saved(workflow._tag, executionId).pipe(\n Effect.flatMap((result) =>\n Option.isSome(result) ? Effect.void : Effect.never,\n ),\n );\n }),\n interrupt: Effect.fnUntraced(function* (_workflow, executionId) {\n const state = executions.get(executionId);\n if (!state) return;\n state.interrupted = true;\n yield* resume(executionId, \"explicit\");\n }),\n interruptUnsafe: Effect.fnUntraced(function* (_workflow, executionId) {\n const state = executions.get(executionId);\n if (!state) return;\n state.interrupted = true;\n state.interruptedUnsafe = true;\n if (state.fiber) yield* Fiber.interrupt(state.fiber);\n yield* resume(executionId, \"explicit\");\n }),\n resume: (_workflow, executionId) => resume(executionId, \"explicit\"),\n activityExecute: Effect.fnUntraced(function* (activity, attempt) {\n const instance = yield* WorkflowEngine.WorkflowInstance;\n const activityId = `${instance.executionId}/${activity.name}/${attempt}`;\n const key = activityKey(instance.executionId, activity.name, attempt);\n let state = activities.get(activityId);\n if (state) {\n const exit = state.exit;\n if (\n exit &&\n exit._tag === \"Success\" &&\n exit.value._tag === \"Suspended\"\n )\n state.exit = undefined;\n else if (exit) return yield* exit;\n } else {\n const saved = yield* store.get(key);\n state = {\n exit:\n saved === undefined\n ? undefined\n : Exit.succeed(yield* decodeResult(saved)),\n };\n activities.set(activityId, state);\n if (state.exit) return yield* state.exit;\n }\n if (\n executions.get(instance.executionId)?.interrupted &&\n !instance.interrupted\n )\n return new Workflow.Suspended({});\n const activityInstance = WorkflowEngine.WorkflowInstance.initial(\n instance.workflow,\n instance.executionId,\n );\n activityInstance.interrupted = instance.interrupted;\n const tracked = state;\n return yield* activity.executeEncoded.pipe(\n activity.name.startsWith(\"DurableClock/\")\n ? resumableSleep(\n sleepKey(instance.executionId, activity.name, attempt),\n )\n : (effect) => effect,\n Workflow.intoResult,\n Effect.provideService(\n WorkflowEngine.WorkflowInstance,\n activityInstance,\n ),\n Effect.tap((result) =>\n result._tag === \"Complete\"\n ? Effect.flatMap(encodeResult(result), (saved) =>\n Effect.andThen(\n store.set(key, saved),\n // When it finished: the dashboard's Workflows view shows it.\n store.set(\n stateKeys.activityAt(\n instance.executionId,\n activity.name,\n attempt,\n ),\n String(stamp()),\n ),\n ),\n )\n : Effect.void,\n ),\n Effect.onExit((exit) => {\n tracked.exit =\n Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)\n ? undefined\n : exit;\n return Effect.void;\n }),\n );\n }),\n poll: (workflow, executionId) =>\n Effect.suspend(() => {\n const state = executions.get(executionId);\n if (!state) return saved(workflow._tag, executionId);\n const exit = state.fiber?.pollUnsafe();\n if (!exit) return Effect.succeedNone;\n return exit._tag === \"Success\"\n ? Effect.succeedSome(exit.value)\n : Effect.die(exit.cause);\n }),\n deferredResult: Effect.fnUntraced(function* (deferred) {\n const instance = yield* WorkflowEngine.WorkflowInstance;\n const id = `${instance.executionId}/${deferred.name}`;\n const known = deferredResults.get(id);\n if (known) return Option.some(known);\n const key = deferredKey(instance.executionId, deferred.name);\n const saved = yield* store.get(key);\n if (saved === undefined) return Option.none();\n sawDeferred(key);\n const result = yield* decodeResult(saved);\n if (result._tag !== \"Complete\") return Option.none();\n deferredResults.set(id, result.exit);\n return Option.some(result.exit);\n }),\n deferredDone: (options) =>\n Effect.suspend(() => {\n const id = `${options.executionId}/${options.deferredName}`;\n if (deferredResults.has(id)) return Effect.void;\n deferredResults.set(id, options.exit);\n sawDeferred(deferredKey(options.executionId, options.deferredName));\n const wake = Effect.andThen(\n deferredState.deferredDone(\n options.executionId,\n options.deferredName,\n ),\n resume(options.executionId, \"automatic\"),\n );\n return Effect.flatMap(\n Effect.flatMap(\n encodeResult(new Workflow.Complete({ exit: options.exit })),\n (saved) =>\n store.set(\n deferredKey(options.executionId, options.deferredName),\n saved,\n ),\n ),\n () =>\n Effect.flatMap(\n Effect.serviceOption(WorkflowEngine.WorkflowInstance),\n (instance) =>\n Option.isSome(instance) &&\n instance.value.executionId === options.executionId\n ? wake.pipe(Effect.forkIn(scope), Effect.asVoid)\n : wake,\n ),\n );\n }),\n scheduleClock: (workflow, options) =>\n Effect.gen(function* () {\n const key = clockKey(options.executionId, options.clock.name);\n const saved = yield* store.get(key);\n const wakeAt =\n saved === undefined\n ? Date.now() + Duration.toMillis(options.clock.duration)\n : Number(saved);\n if (saved === undefined) yield* store.set(key, String(wakeAt));\n yield* engine\n .deferredDone(options.clock.deferred, {\n workflowName: workflow._tag,\n executionId: options.executionId,\n deferredName: options.clock.deferred.name,\n exit: Exit.void,\n })\n .pipe(\n Effect.delay(Math.max(0, wakeAt - Date.now())),\n FiberMap.run(\n clocks,\n `${options.executionId}/${options.clock.name}`,\n { onlyIfMissing: true },\n ),\n Effect.asVoid,\n );\n }),\n });\n return Context.make(WorkflowEngine.WorkflowEngine, engine).pipe(\n Context.add(WorkflowState, { get: store.get, list: store.list }),\n );\n });\n return Layer.effectContext(build).pipe(\n Layer.provide(database.layer),\n ) as never;\n}\n","import { Cause, Effect, Exit } from \"effect\";\nimport { decodeResult, type WorkflowState } from \"./workflows\";\n\n/**\n * What the dashboard's Workflows view reads of a Workflow SDK `World`, made from\n * `workflowEngine`'s state. Read-only: the view lists runs, shows one with its\n * steps (an activity attempt is a step) and its events, and follows it as it\n * goes. Cancelling, replaying and waking a run, and hooks and streams, are not\n * offered, so those are empty or refused.\n */\nexport interface WorkflowWorld {\n readonly runs: {\n list(\n options?: ListOptions & { workflowName?: string; status?: string },\n ): Promise<Page<Run>>;\n get(runId: string, options?: Resolve): Promise<Run>;\n };\n readonly steps: {\n get(runId: string, stepId: string, options?: Resolve): Promise<Step>;\n };\n readonly events: {\n list(options: ListOptions & { runId: string }): Promise<Page<WorldEvent>>;\n get(runId: string, eventId: string, options?: Resolve): Promise<WorldEvent>;\n listByCorrelationId(\n options: ListOptions & { correlationId: string; runId?: string },\n ): Promise<Page<WorldEvent>>;\n };\n readonly hooks: {\n list(options?: ListOptions): Promise<Page<never>>;\n get(hookId: string): Promise<never>;\n };\n readonly streams: {\n list(runId: string): Promise<string[]>;\n getChunks(\n runId: string,\n name: string,\n ): Promise<Page<never> & { done: true }>;\n };\n}\n\ninterface Resolve {\n resolveData?: \"none\" | \"all\";\n}\ninterface ListOptions extends Resolve {\n pagination?: {\n cursor?: string;\n limit?: number;\n sortOrder?: \"asc\" | \"desc\";\n };\n}\ninterface Page<T> {\n data: T[];\n cursor: string | null;\n hasMore: boolean;\n}\n\ntype Status = \"running\" | \"completed\" | \"failed\";\ninterface Run {\n runId: string;\n status: Status;\n deploymentId: string;\n workflowName: string;\n input?: unknown;\n output?: unknown;\n error?: unknown;\n attributes: Record<string, string>;\n createdAt: Date;\n updatedAt: Date;\n startedAt: Date;\n completedAt?: Date;\n}\ninterface Step {\n runId: string;\n stepId: string;\n stepName: string;\n status: \"completed\" | \"failed\";\n output?: unknown;\n error?: unknown;\n attempt: number;\n createdAt: Date;\n updatedAt: Date;\n startedAt: Date;\n completedAt: Date;\n}\ninterface WorldEvent {\n eventId: string;\n runId: string;\n eventType: string;\n correlationId?: string;\n eventData?: Record<string, unknown>;\n createdAt: Date;\n}\n\ntype Row = {\n payload: unknown;\n done: boolean;\n result?: string;\n startedAt?: number;\n completedAt?: number;\n};\n\n/**\n * A value as the inspector's page reads it. It treats an array as devalue's\n * flat form, so an array is sent as that, and any other value as it is.\n */\nfunction display(value: unknown): unknown {\n if (!Array.isArray(value)) return value;\n const flat: unknown[] = [];\n const add = (item: unknown): number => {\n const index = flat.length;\n flat.push(undefined);\n flat[index] = Array.isArray(item)\n ? item.map(add)\n : item && typeof item === \"object\"\n ? Object.fromEntries(\n Object.entries(item).map(([key, entry]) => [key, add(entry)]),\n )\n : item;\n return index;\n };\n add(value);\n return flat;\n}\n\nconst failure = (cause: Cause.Cause<unknown>) => {\n const error = Cause.squash(cause);\n return {\n name: error instanceof Error ? error.name : \"Error\",\n message: error instanceof Error ? error.message : Cause.pretty(cause),\n ...(error instanceof Error && error.stack && { stack: error.stack }),\n };\n};\n\n/** The outcome of a finished execution or activity: its output, or its error. */\nconst outcome = (text: string) =>\n Effect.map(decodeResult(text), (result) =>\n result._tag === \"Complete\" && Exit.isSuccess(result.exit)\n ? ({ status: \"completed\", output: display(result.exit.value) } as const)\n : ({\n status: \"failed\",\n error: failure(\n result._tag === \"Complete\" && Exit.isFailure(result.exit)\n ? result.exit.cause\n : Cause.fail(\"The workflow suspended\"),\n ),\n } as const),\n );\n\nconst stepIdOf = (name: string, attempt: number) => `${name}:${attempt}`;\n\n/** Pages `items` (already in ascending order) by an offset cursor. */\nfunction paginate<T>(items: T[], options: ListOptions = {}): Page<T> {\n const { cursor, limit = 100, sortOrder = \"desc\" } = options.pagination ?? {};\n const ordered = sortOrder === \"asc\" ? items : [...items].reverse();\n const start = Number(cursor ?? 0);\n const end = start + limit;\n return {\n data: ordered.slice(start, end),\n cursor: end < ordered.length ? String(end) : null,\n hasMore: end < ordered.length,\n };\n}\n\n/**\n * Present the state of a `workflowEngine` as the part of a Workflow SDK world\n * the dashboard's Workflows view calls. A run is an execution, a step is one\n * attempt of an activity, and the events (`run_created`, `step_completed` and\n * the like) are made from both, in the order things finished.\n *\n * Times come from what the engine writes: when an execution started and ended,\n * and when each activity attempt finished. An attempt's start is taken to be\n * when the one before it finished, and rows written before the engine kept\n * times show the epoch.\n *\n * @param state - What `workflowEngine` provides: its rows.\n * @param run - Runs an Effect against the app's runtime.\n */\nexport function workflowWorld(\n state: WorkflowState[\"Service\"],\n run: <A>(effect: Effect.Effect<A>) => Promise<A>,\n): WorkflowWorld {\n const runOf = (key: string, value: string, prefix = \"execution/\") => {\n const rest = key.slice(prefix.length);\n // An execution id is a hash, so it has no slash; a workflow's name may.\n const slash = rest.lastIndexOf(\"/\");\n return {\n name: rest.slice(0, slash),\n id: rest.slice(slash + 1),\n row: JSON.parse(value) as Row,\n };\n };\n\n const toRun = (name: string, id: string, row: Row, data: boolean) =>\n Effect.gen(function* () {\n const startedAt = new Date(row.startedAt ?? 0);\n const done =\n row.done && row.result !== undefined\n ? yield* outcome(row.result)\n : undefined;\n const completedAt = row.done ? new Date(row.completedAt ?? 0) : undefined;\n return {\n runId: id,\n status: done?.status ?? \"running\",\n deploymentId: \"effect\",\n workflowName: name,\n attributes: {},\n createdAt: startedAt,\n startedAt,\n updatedAt: completedAt ?? startedAt,\n ...(completedAt && { completedAt }),\n ...(data && {\n input: display(row.payload),\n ...(done &&\n (\"output\" in done\n ? { output: done.output }\n : { error: done.error })),\n }),\n } as Run;\n });\n\n const executions = Effect.map(state.list(\"execution/\"), (rows) =>\n rows.map(({ key, value }) => runOf(key, value)),\n );\n\n const find = (runId: string) =>\n Effect.flatMap(executions, (all) => {\n const found = all.find((item) => item.id === runId);\n return found\n ? Effect.succeed(found)\n : Effect.die(new Error(`No workflow run \"${runId}\"`));\n });\n\n /** The attempts of an execution's activities, in the order they finished. */\n const attempts = (runId: string, started: number) =>\n Effect.gen(function* () {\n const prefix = `activity/${runId}/`;\n const times = new Map(\n (yield* state.list(`activity-at/${runId}/`)).map(({ key, value }) => [\n key.slice(\"activity-at/\".length),\n Number(value),\n ]),\n );\n const rows = (yield* state.list(prefix)).filter(({ key }) =>\n key.startsWith(prefix),\n );\n const found = yield* Effect.forEach(rows, ({ key, value }) =>\n Effect.map(outcome(value), (result) => {\n const rest = key.slice(prefix.length);\n const slash = rest.lastIndexOf(\"/\");\n return {\n name: rest.slice(0, slash),\n attempt: Number(rest.slice(slash + 1)),\n completedAt: times.get(key.slice(\"activity/\".length)) ?? 0,\n ...result,\n };\n }),\n );\n found.sort(\n (a, b) =>\n a.completedAt - b.completedAt ||\n a.name.localeCompare(b.name) ||\n a.attempt - b.attempt,\n );\n let previous = started;\n return found.map((item) => {\n const startedAt = Math.min(previous, item.completedAt || previous);\n previous = Math.max(previous, item.completedAt);\n return { ...item, startedAt };\n });\n });\n\n type Attempt = Effect.Success<ReturnType<typeof attempts>>[number];\n const toStep = (runId: string, item: Attempt, data: boolean): Step => ({\n runId,\n stepId: stepIdOf(item.name, item.attempt),\n stepName: item.name,\n status: item.status,\n attempt: item.attempt,\n createdAt: new Date(item.startedAt),\n startedAt: new Date(item.startedAt),\n updatedAt: new Date(item.completedAt),\n completedAt: new Date(item.completedAt),\n ...(data &&\n (\"output\" in item ? { output: item.output } : { error: item.error })),\n });\n\n const eventsOf = (runId: string, data: boolean) =>\n Effect.flatMap(find(runId), (found) => eventsFrom(found, data));\n\n const eventsFrom = (\n { id: runId, name, row }: { id: string; name: string; row: Row },\n data: boolean,\n ) =>\n Effect.gen(function* () {\n const current = yield* toRun(name, runId, row, true);\n const events: Omit<WorldEvent, \"eventId\" | \"runId\">[] = [\n {\n eventType: \"run_created\",\n createdAt: current.createdAt,\n eventData: {\n deploymentId: current.deploymentId,\n workflowName: name,\n ...(data && { input: current.input }),\n },\n },\n { eventType: \"run_started\", createdAt: current.startedAt },\n ];\n for (const item of yield* attempts(runId, current.startedAt.getTime())) {\n const correlationId = stepIdOf(item.name, item.attempt);\n const created = new Date(item.startedAt);\n events.push(\n {\n eventType: \"step_created\",\n correlationId,\n createdAt: created,\n eventData: { stepName: item.name },\n },\n {\n eventType: \"step_started\",\n correlationId,\n createdAt: created,\n eventData: { stepName: item.name, attempt: item.attempt },\n },\n {\n eventType:\n item.status === \"completed\" ? \"step_completed\" : \"step_failed\",\n correlationId,\n createdAt: new Date(item.completedAt),\n eventData:\n item.status === \"completed\"\n ? { stepName: item.name, ...(data && { result: item.output }) }\n : {\n stepName: item.name,\n attempt: item.attempt,\n ...(data && { error: item.error }),\n },\n },\n );\n }\n if (current.status !== \"running\")\n events.push({\n eventType:\n current.status === \"completed\" ? \"run_completed\" : \"run_failed\",\n createdAt: current.completedAt!,\n eventData:\n current.status === \"completed\"\n ? data\n ? { output: current.output }\n : {}\n : data\n ? { error: current.error }\n : {},\n });\n // Stable: events of one time keep the order they were made in.\n return events.map((event, index) => ({\n ...event,\n eventId: `evnt_${String(index).padStart(6, \"0\")}`,\n runId,\n }));\n });\n\n const notFound = (what: string) => Promise.reject(new Error(`No ${what}`));\n const withData = (options?: Resolve) => options?.resolveData !== \"none\";\n\n return {\n runs: {\n list: (options = {}) =>\n run(\n Effect.gen(function* () {\n const all = (yield* executions).filter(\n (item) =>\n !options.workflowName || item.name === options.workflowName,\n );\n const runs = yield* Effect.forEach(all, (item) =>\n toRun(item.name, item.id, item.row, withData(options)),\n );\n const matching = runs\n .filter(\n (item) => !options.status || item.status === options.status,\n )\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n return paginate(matching, options);\n }),\n ),\n get: (runId, options) =>\n run(\n Effect.flatMap(find(runId), (item) =>\n toRun(item.name, item.id, item.row, withData(options)),\n ),\n ),\n },\n steps: {\n get: (runId, stepId, options) =>\n run(\n Effect.gen(function* () {\n const { row } = yield* find(runId);\n const found = (yield* attempts(runId, row.startedAt ?? 0)).find(\n (item) => stepIdOf(item.name, item.attempt) === stepId,\n );\n return found\n ? toStep(runId, found, withData(options))\n : yield* Effect.die(new Error(`No step \"${stepId}\"`));\n }),\n ),\n },\n events: {\n list: (options) =>\n run(\n Effect.map(eventsOf(options.runId, withData(options)), (events) =>\n paginate(events as WorldEvent[], options),\n ),\n ),\n get: (runId, eventId, options) =>\n run(\n Effect.flatMap(eventsOf(runId, withData(options)), (events) => {\n const found = events.find((event) => event.eventId === eventId);\n return found\n ? Effect.succeed(found as WorldEvent)\n : Effect.die(new Error(`No event \"${eventId}\"`));\n }),\n ),\n listByCorrelationId: (options) =>\n run(\n Effect.gen(function* () {\n const found = options.runId\n ? [yield* find(options.runId)]\n : yield* executions;\n const matching: WorldEvent[] = [];\n for (const item of found)\n for (const event of yield* eventsFrom(item, withData(options)))\n if (event.correlationId === options.correlationId)\n matching.push(event as WorldEvent);\n return paginate(matching, options);\n }),\n ),\n },\n hooks: {\n list: async () => ({ data: [], cursor: null, hasMore: false }),\n get: () => notFound(\"hooks: this engine has none to show\"),\n },\n streams: {\n list: async () => [],\n getChunks: async () => ({\n data: [],\n cursor: null,\n hasMore: false,\n done: true,\n }),\n },\n };\n}\n","import {\n Cause,\n Effect,\n type Fiber,\n Layer,\n ManagedRuntime,\n Option,\n Result,\n type Tracer,\n} from \"effect\";\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from \"effect/http\";\nimport { invalid, type AnyAction, type Wire } from \"./action\";\nimport {\n exportArchitecture,\n type AppSocket,\n type ArchitectureSchema,\n} from \"./architecture\";\nimport { describeClientContract, type ClientContractSource } from \"./contract\";\nimport { createLogger, requestIds } from \"./context\";\nimport { corsHook, type CorsOptions } from \"./cors\";\nimport {\n keepTraceIds,\n withHeaders,\n type OnError,\n type OnResponse,\n} from \"./response-hooks\";\nimport { dashboardMcpCaller, markDashboardArrival } from \"./dashboard-identity\";\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 {\n scalarDocsHTML,\n swaggerDocsHTML,\n normalizeDocumentation,\n type ApiDocument,\n type DocumentationOptions,\n type OpenApiDocument,\n type ReferenceOptions,\n} from \"./docs\";\nimport {\n endpointPaths,\n resolveEndpointDatabase,\n type EndpointContext,\n type EndpointDefinition,\n} from \"./endpoints\";\nimport {\n BrickError,\n DuplicateNameError,\n ValidationError,\n asFailure,\n toErrorResponse,\n} from \"./errors\";\nimport {\n LOCAL_FILES_ROUTE,\n checkFileStorages,\n localFileDirs,\n localFilesRoute,\n} from \"./file-storage\";\nimport { OPENAPI_DEFAULTS, generateOpenApiSpec } from \"./openapi\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { loggerOf, type RequestLoggingOptions } from \"./request-logger\";\nimport { resolveSecrets, type SecretSource } from \"./secrets\";\nimport {\n instrumentFetch,\n recordResponse,\n telemetryLayerOf,\n type TelemetryOptions,\n traceparentOf,\n traceRequest,\n} from \"./telemetry\";\nimport { AppStorage, type KeyValueStorage } from \"./storage\";\nimport { markAddressSource, type ClientIp } from \"./rate-limit\";\nimport {\n getPluginEndpoints,\n installedPlugins,\n type PluginEndpoint,\n} from \"./plugin\";\nimport { pluginDepsOf, pluginLifecycle, setupAppPlugins } from \"./plugin-app\";\nimport { checkRecordAccess } from \"./resource\";\nimport type { PluginInstance } from \"./define-plugin\";\nimport type { InstalledPlugin } from \"./plugin-types\";\nimport {\n DEFAULT_PREFIX,\n describeRoutes,\n isObjectSchema,\n routeKey,\n type RouteIR,\n} from \"./routes\";\nimport type { AnyService } from \"./service\";\nimport type { AnyTool } from \"./tool\";\nimport {\n createEvents,\n type AppEvents,\n type EventsDefinition,\n} from \"./events/hub\";\nimport type { EventsOptions } from \"./events/types\";\nimport { mountSockets, type SocketsOptions } from \"./socket-server\";\nimport { mountRawSockets, type RawSocketStats } from \"./raw-socket\";\nimport { workflowWorld, type WorkflowWorld } from \"./workflow-world\";\nimport { WorkflowState } from \"./workflows\";\nimport { socketPath } from \"./socket\";\n\nexport type { RequestLoggingOptions };\n\nexport interface BrickOptions {\n /** The services to serve. Default: every service `defineService` registered, from the global registry. */\n services?: readonly AnyService[];\n /**\n * The Effect layer that provides the services the callbacks use. It is built\n * with the services' databases, once, on the first request, and released when the app stops.\n */\n layer?: Layer.Layer<never, any, never>;\n /** The route prefix of actions (default `/api`). */\n prefix?: string;\n /** `title`, `version` and `description` go in the OpenAPI document. */\n title?: string;\n version?: string;\n description?: string;\n /** Serve the OpenAPI document, Scalar and Swagger UI (default true). */\n docs?: boolean;\n /** Where the OpenAPI document is served (default `/openapi.json`). */\n openApiPath?: string;\n /** Where the Scalar page is served (default `/docs`). */\n docsPath?: string;\n /** Where the Swagger UI page is served (default `/swagger`). */\n swaggerPath?: string;\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;\n /**\n * Developer documentation for the `brick dev` dashboard (its Docs tab): a\n * folder of `.md`/`.mdx` pages. A string is the folder. It is kept in\n * `app.definition` for the dashboard to read.\n */\n documentation?: string | DocumentationOptions;\n /** Raw endpoints (plain routes, not actions), mounted at startup. `app.endpoint()` adds more later. */\n endpoints?: readonly EndpointDefinition[];\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 * Runs on every response the app sends, last, after the CORS headers: its\n * own routes, `/_health`, docs, errors, preflights and what plugin middleware\n * answers. Change `headers` to add, replace or remove a header (security\n * headers, say). A failure in it is logged and the response goes out as it was.\n *\n * @example\n * onResponse: ({ headers }) => Effect.sync(() => headers.set(\"x-frame-options\", \"DENY\"))\n */\n onResponse?: OnResponse;\n /**\n * Runs when a request ends in a 5xx Brick built from a defect or a failure,\n * to report it. The response keeps its hidden message; succeed with a\n * `Response` to send that one instead (it keeps `x-trace-id` and\n * `x-request-id` unless it sets them). A failure in it is logged and the\n * response goes out as it was. A 5xx a handler returned itself has no error\n * and does not run it.\n *\n * @example\n * onError: ({ error }) => Effect.sync(() => report(error))\n */\n onError?: OnError;\n /** Log `METHOD /path → status (Nms)` per request (default true). */\n requestLogging?: boolean | RequestLoggingOptions;\n /**\n * Listeners, schedules and delivery. Events are recorded in the same\n * transaction as the writes that cause them once a service's database holds\n * an `outboxTable()`.\n */\n events?: EventsOptions;\n /**\n * Where the client address of a request comes from, for `rateLimit` per\n * `\"ip\"`: the socket peer (what `listen` knows) by default. Behind a proxy,\n * read the header the proxy sets, and only after checking the request came\n * from it. It must not be async.\n *\n * @example\n * clientIp: ({ request, peer }) => request.headers.get(\"x-real-ip\") ?? peer\n */\n clientIp?: ClientIp;\n /** Where the services' sockets deliver: a broker to reach other processes, and the secret that signs replay sequences. `listen` serves the sockets. */\n sockets?: SocketsOptions;\n /**\n * How long `app.drain()` waits for open raw sockets to close, before it\n * closes them with 1001 (default 30 000). `stop()` and `shutdown()` drain\n * first. Brick `brick.v1` sockets are not drained: they close when the\n * server stops.\n */\n drainTimeoutMs?: number;\n /**\n * The key-value storage of the app, from `defineStorage`: where `rateLimit`\n * and webhook replay count, for the services that have no `storage` of their own.\n * The app closes it when it stops.\n */\n storage?: KeyValueStorage;\n /**\n * App-wide plugins from `definePlugin`, in install order: their `app` part\n * adds start/stop lifecycle and middleware. Plugins installed with\n * `service.use()` or `resource.use()` run their `app` part too.\n */\n plugins?: readonly PluginInstance<any, any>[];\n /**\n * Record a span for each request, action, outbound `fetch` and SQL\n * statement (default false). `brick dev` and the dashboard read them from\n * `spanStore`.\n */\n telemetry?: boolean | TelemetryOptions;\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 /** Where `defineSecret` reads from, and whether to check every secret at startup (default true). */\n secrets?: { source?: SecretSource; validate?: boolean };\n}\n\nexport interface ListeningServer {\n readonly port: number | undefined;\n readonly url: URL;\n}\n\n/** The app `brick` returns: a fetch handler, a server, and a description of what it serves. */\nexport interface BrickApp {\n /** A plain fetch handler: `Bun.serve({ fetch: app.fetch })`. */\n readonly fetch: (\n input: Request | string | URL,\n init?: RequestInit,\n ) => Promise<Response>;\n /** `fetch` under the name `@brickkit/core`'s app has. */\n readonly handle: (\n input: Request | string | URL,\n init?: RequestInit,\n ) => Promise<Response>;\n /**\n * Serve over HTTP with `Bun.serve`. Requests wait for the plugins to start;\n * if one fails, the failure is logged and the server stops.\n */\n listen(port: number): ListeningServer;\n /** Start the plugins, in install order, once. A failed start stops those before it and rejects. */\n start(): Promise<void>;\n /**\n * Drain, then stop the server, then the plugins in reverse order, then\n * release the layer and the databases. `force` skips the drain and closes\n * every connection at once.\n */\n stop(force?: boolean): Promise<void>;\n /**\n * Stop accepting raw socket upgrades (503) and wait until the open ones close,\n * then close what is left with 1001. Other routes keep serving. Resolves at\n * once without raw sockets. Shared: later calls return the first one's\n * promise. `stop()` and `shutdown()` call it unless `force` is true.\n * `timeoutMs` defaults to `drainTimeoutMs`.\n */\n drain(timeoutMs?: number): Promise<void>;\n /** The raw socket routes of this app: connections open now and whether it is draining. */\n rawSockets(): RawSocketStats;\n /** Drive delivery by hand: `drain()`, `start()`, `stop()`. `undefined` without the `events` option. */\n readonly events: AppEvents | undefined;\n /**\n * Run `effect` in the app's runtime, with the services its layer, databases,\n * events and storage provide: for code that runs outside a request, such as\n * a callback a library calls. Inside it `emitEvent` finds the app's events,\n * and `runInTransaction` opens a transaction that `emitEvent` joins. Works as\n * soon as the app is built, as `fetch` does, and rejects after `stop()`.\n * @example\n * const queueEmail = (to: string) =>\n * app.runPromise(\n * Effect.gen(function* () {\n * const db = yield* database.Database;\n * yield* emitEvent({ db }, \"email.queued\", { to });\n * }),\n * );\n */\n runPromise<A, E>(effect: Effect.Effect<A, E, any>): Promise<A>;\n /** `runPromise` for a fiber you control: interrupt it, or join it later. Throws after `stop()`. */\n runFork<A, E>(effect: Effect.Effect<A, E, any>): Fiber.Fiber<A, E>;\n /** The server `listen` or `serve` opened, until the app stops. */\n readonly server: ListeningServer | undefined;\n /** Start serving on `port`: what `brick start` and the CLI's workers call. */\n serve(options: { port: number }): Promise<BrickApp>;\n /** Stop for good: what the CLI calls at SIGINT and SIGTERM. `force` is passed to `stop()`. */\n shutdown(force?: boolean): Promise<void>;\n /** The OpenAPI document `/openapi.json` serves (also when `docs` is false). */\n openApiDocument(): Record<string, any>;\n /** The OpenAPI documents the dashboard's APIs view shows: the app's own, when `docs` is on, and `reference.documents`. */\n referenceDocuments(): Promise<ApiDocument[]>;\n /** Register a raw endpoint (a plain route, not an action). One that a built-in route, an action or an earlier endpoint already holds is listed but not served. */\n endpoint(def: EndpointDefinition): void;\n /** Every endpoint registered, plugins' first, in declaration order. */\n listEndpoints(): EndpointDefinition[];\n /** The architecture `/_brick/services` serves: what the CLI's dashboard and `brick info` read. */\n architecture(): ArchitectureSchema;\n /** What the CLI generates the client contract from: each route and socket with the JSON Schemas of what travels. */\n clientContract(): ClientContractSource;\n /**\n * The runs of the app's `workflowEngine`, as the part of a Workflow SDK world\n * the dashboard's Workflows view reads. `undefined` when the app's layer has\n * no engine. It builds the app's layer if nothing has yet.\n */\n workflowWorld(): Promise<WorkflowWorld | undefined>;\n readonly definition: {\n readonly services: readonly AnyService[];\n readonly prefix: string;\n readonly routes: readonly RouteIR[];\n readonly documentation?: DocumentationOptions;\n /** The sockets the services declare, each at the path `listen` serves it on. */\n readonly sockets: readonly AppSocket[];\n readonly events?: EventsDefinition;\n readonly plugins: readonly InstalledPlugin[];\n /** Whether spans are recorded: `telemetry`, or a `dashboard`. */\n readonly telemetry: boolean;\n readonly dashboard: DashboardOptions | undefined;\n };\n}\n\nconst success = (result: unknown) =>\n result === undefined\n ? HttpServerResponse.empty({ status: 200 })\n : result instanceof Response\n ? HttpServerResponse.fromWeb(result)\n : typeof result === \"string\"\n ? HttpServerResponse.text(result)\n : HttpServerResponse.jsonUnsafe(result);\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** The body of a plugin endpoint's request: JSON, else text. Read from a copy, so the handler's `request` stays unread. */\nconst readBody = (web: Request) =>\n web.method === \"GET\" || web.method === \"HEAD\"\n ? Effect.succeed(undefined)\n : Effect.gen(function* () {\n const text = yield* Effect.promise(() => web.clone().text());\n if (!text) return undefined;\n if (!web.headers.get(\"content-type\")?.toLowerCase().includes(\"json\"))\n return text;\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return yield* invalid(\"endpoint\", \"input\", [\n { path: \"\", message: \"Body is not valid JSON\" },\n ]);\n }\n });\n\n/** The response for what a plugin endpoint or middleware returned. */\nconst answer = (\n result: unknown,\n set: {\n status?: number | string | undefined;\n headers: Record<string, string>;\n },\n): Response =>\n result instanceof Response\n ? result\n : new Response(\n result === undefined\n ? null\n : typeof result === \"string\"\n ? result\n : JSON.stringify(result),\n {\n status: set.status === undefined ? 200 : Number(set.status),\n headers: {\n ...(result !== undefined &&\n typeof result !== \"string\" && {\n \"content-type\": \"application/json\",\n }),\n ...set.headers,\n },\n },\n );\n\n/** A multipart form as an object: a field sent twice is a list. */\nconst formObject = (form: FormData | URLSearchParams) =>\n Object.fromEntries(\n [...new Set(form.keys())].map((key) => {\n const values = form.getAll(key);\n return [key, values.length > 1 ? values : values[0]];\n }),\n );\n\n/** The body's bytes, or `undefined` once it passes `limit`: a chunked body has no Content-Length to check. */\nconst readBounded = async (body: ReadableStream<Uint8Array>, limit: number) => {\n const chunks: Uint8Array[] = [];\n let size = 0;\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n size += chunk.byteLength;\n if (size > limit) return undefined;\n chunks.push(chunk);\n }\n return new Uint8Array(Buffer.concat(chunks));\n};\n\n/**\n * The action's input and how it arrived: the query string, a multipart form, or\n * the JSON body, with the path parameters on top.\n */\nconst readInput = (route: RouteIR, action: AnyAction, web: Request) =>\n Effect.gen(function* () {\n const { input } = action.config;\n // A body over what the action's files can fill is refused before it is read.\n const tooLarge = () =>\n new BrickError({\n code: \"PAYLOAD_TOO_LARGE\",\n message: `Request body exceeds ${route.bodyLimit} bytes`,\n status: 413,\n });\n if (\n route.bodyLimit !== undefined &&\n Number(web.headers.get(\"content-length\")) > route.bodyLimit\n )\n return yield* tooLarge();\n if (!input) return { input: undefined, wire: \"json\" as Wire };\n const params = Object.fromEntries(\n Object.entries(yield* HttpRouter.params).filter(\n ([, value]) => value !== undefined,\n ),\n );\n if (route.inputSource === \"query\")\n return {\n input: { ...(yield* HttpServerRequest.ParsedSearchParams), ...params },\n wire: \"query\" as Wire,\n };\n // A body with no Content-Length is counted as it is read.\n const bounded =\n route.bodyLimit !== undefined && web.body\n ? yield* Effect.promise(() => readBounded(web.body!, route.bodyLimit!))\n : undefined;\n if (route.bodyLimit !== undefined && web.body && !bounded)\n return yield* tooLarge();\n const contentType = web.headers.get(\"content-type\") ?? \"\";\n const type = contentType.toLowerCase();\n if (type.startsWith(\"multipart/form-data\")) {\n const form = yield* Effect.tryPromise({\n try: () =>\n (bounded\n ? new Response(bounded, {\n headers: { \"content-type\": contentType },\n })\n : web\n ).formData(),\n catch: () =>\n invalid(action.name, \"input\", [\n { path: \"\", message: \"Body is not valid multipart/form-data\" },\n ]),\n });\n return {\n input: { ...formObject(form), ...params },\n wire: \"form\" as Wire,\n };\n }\n const request = yield* HttpServerRequest.HttpServerRequest;\n const text = bounded\n ? new TextDecoder().decode(bounded)\n : yield* request.text;\n let body: unknown;\n // As core reads it: JSON only when the content type says so and there is text, a form as its fields, a text type as the text itself, and any other type or no type as no body.\n if (type.includes(\"json\"))\n try {\n body = text ? (JSON.parse(text) ?? undefined) : undefined;\n } catch {\n return yield* invalid(action.name, \"input\", [\n { path: \"\", message: \"Body is not valid JSON\" },\n ]);\n }\n else if (type.startsWith(\"application/x-www-form-urlencoded\"))\n body = text ? formObject(new URLSearchParams(text)) : undefined;\n else body = type.startsWith(\"text/\") ? text || undefined : undefined;\n const merged =\n Object.keys(params).length && (body === undefined || isPlainObject(body))\n ? { ...body, ...params }\n : body === undefined && isObjectSchema(input)\n ? {}\n : body;\n return { input: merged, wire: \"json\" as Wire };\n });\n\n/** The error an endpoint's handler failed with, as a 4xx the way a thrown `{ status }` is in core. */\nconst httpStatusError = (error: unknown): unknown =>\n !asFailure(error) &&\n error !== null &&\n typeof error === \"object\" &&\n \"status\" in error &&\n typeof error.status === \"number\" &&\n Number.isInteger(error.status) &&\n error.status >= 400 &&\n error.status < 500\n ? new BrickError({\n code: \"HTTP_ERROR\",\n message:\n \"message\" in error && typeof error.message === \"string\"\n ? error.message\n : \"Endpoint error\",\n status: error.status,\n })\n : error;\n\n/** The JSON of `build`, kept until the registry (or the endpoints) change. */\nfunction cachedJson(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n): () => string {\n let seen: readonly [unknown, number] | undefined;\n let json = \"\";\n return () => {\n const current = revision();\n if (!seen || seen[0] !== current[0] || seen[1] !== current[1]) {\n json = JSON.stringify(build());\n seen = current;\n }\n return json;\n };\n}\n\n/**\n * Create the app: a fetch handler that serves every service's actions, plus\n * `/_health`, an OpenAPI document at `/openapi.json` and Scalar at `/docs`.\n * Routes, success bodies and error JSON are the same as `@brickkit/core`'s, so\n * its typed client works against it.\n *\n * @throws When two services share a name, or two actions share a URL segment.\n * @example\n * export default brick({ services: [pages], layer: Mailer.layer });\n */\nexport function brick(options: BrickOptions = {}): BrickApp {\n const {\n prefix = DEFAULT_PREFIX,\n title = OPENAPI_DEFAULTS.title,\n version = OPENAPI_DEFAULTS.version,\n docs = true,\n openApiPath = OPENAPI_DEFAULTS.path,\n docsPath = \"/docs\",\n swaggerPath = \"/swagger\",\n requestLogging = true,\n } = options;\n const services = options.services ?? getGlobalRegistry().list();\n if (options.secrets?.validate !== false)\n resolveSecrets({ source: options.secrets?.source });\n const dashboard = normalizeDashboard(options.dashboard);\n // The dashboard shows what is traced, so having one means tracing.\n const telemetry = Boolean(options.telemetry) || dashboard !== undefined;\n if (telemetry) instrumentFetch();\n const cors = options.cors ? corsHook(options.cors) : undefined;\n const documentation = normalizeDocumentation(options.documentation);\n for (const service of services) checkRecordAccess(service);\n const described = describeRoutes(services, prefix);\n const plugins = setupAppPlugins(\n services.flatMap((service) => installedPlugins(service)),\n options.plugins ?? [],\n );\n // Files are kept per tenant, so a service with file storage needs an identity.\n for (const service of services)\n checkFileStorages(service, [\n service.deps,\n ...installedPlugins(service).map(pluginDepsOf),\n ]);\n const localDirs = localFileDirs([\n ...services.map((service) => service.deps),\n ...plugins.deps,\n ]);\n\n // Routes the app serves, by key; `true` marks a plugin's. Built-ins first, so nothing shadows them.\n const claimed = new Map<string, boolean>();\n const webhookRoutes = new Map<string, string>();\n const claim = (\n method: string,\n path: string,\n plugin = false,\n webhook?: string,\n ) => {\n const key = routeKey(method, path);\n if (!claimed.has(key)) {\n claimed.set(key, plugin);\n if (webhook) webhookRoutes.set(key, webhook);\n return true;\n }\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 || claimed.get(key))\n throw new DuplicateNameError(\n `Brick: duplicate plugin route '${method} ${path}'`,\n );\n return false;\n };\n const builtIn = (path: string) => void claim(\"GET\", path);\n builtIn(\"/_health\");\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) builtIn(referencePath);\n if (docs)\n for (const path of [openApiPath, docsPath, swaggerPath]) builtIn(path);\n builtIn(\"/_brick/services\");\n if (localDirs.size) builtIn(LOCAL_FILES_ROUTE);\n\n const endpointDefs: EndpointDefinition[] = [];\n /** The endpoints a route serves: a refused one is not described in OpenAPI. */\n const served = new Set<EndpointDefinition>();\n let endpointRevision = 0;\n const logger = createLogger();\n const pluginEndpoint = (endpoint: PluginEndpoint): EndpointDefinition => ({\n method: endpoint.method,\n path: endpoint.path,\n service: endpoint.service,\n plugin: endpoint.plugin,\n ...(endpoint.summary && { summary: endpoint.summary }),\n ...(endpoint.description && { description: endpoint.description }),\n ...(endpoint.tags && { tags: endpoint.tags }),\n handler: ({ params, query, body, headers, request, set, ...call }) =>\n endpoint.handler(\n { params, query, body, headers, request, set },\n { request, ...call },\n ),\n });\n // Endpoints beat actions to a route, as in core: they are claimed first.\n const mountedEndpoints: EndpointDefinition[] = [];\n const mountEndpoint = (def: EndpointDefinition, plugin = false) => {\n const mounted = claim(def.method, def.path, plugin);\n endpointDefs.push(def);\n if (mounted) served.add(def);\n endpointRevision++;\n return mounted;\n };\n for (const service of services)\n for (const endpoint of getPluginEndpoints(service, prefix)) {\n const def = pluginEndpoint(endpoint);\n if (mountEndpoint(def, true)) mountedEndpoints.push(def);\n }\n for (const def of options.endpoints ?? [])\n if (mountEndpoint(def)) mountedEndpoints.push(def);\n\n const routes: RouteIR[] = [];\n const bindings: typeof described.bindings = [];\n for (const [index, route] of described.routes.entries())\n if (\n claim(\n route.method,\n route.path,\n Boolean(route.plugin),\n route.kind === \"webhook\"\n ? `${route.service}.${route.action}`\n : undefined,\n )\n ) {\n routes.push(route);\n bindings.push(described.bindings[index]!);\n }\n\n let architecture: string | undefined;\n let architectureAt: readonly [unknown, number] | undefined;\n const architectureJson = () => {\n const registry = getGlobalRegistry();\n if (\n !architecture ||\n architectureAt?.[0] !== registry ||\n architectureAt[1] !== registry.revision\n ) {\n architecture = JSON.stringify(exportArchitecture(definition));\n architectureAt = [registry, registry.revision];\n }\n return architecture;\n };\n const openApiDocument = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n const paths: Record<string, any> = { ...spec.paths };\n for (const [path, operations] of Object.entries(\n endpointPaths(endpointDefs.filter((def) => served.has(def))),\n ))\n paths[path] = { ...paths[path], ...operations };\n return { ...spec, paths };\n };\n const specJson = cachedJson(openApiDocument, () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision + endpointRevision];\n });\n\n // The app's databases: its services', and those the endpoints given at startup name.\n const databases = new Set(\n [\n ...services.map((service) => service.database),\n ...(options.endpoints ?? []).map((endpoint) => endpoint.database),\n ].flatMap((database) => (database ? [database.layer] : [])),\n );\n const storages = new Set([\n ...(options.storage ? [options.storage] : []),\n ...services.flatMap((service) =>\n service.storage ? [service.storage] : [],\n ),\n ]);\n const layers = [\n ...(options.layer ? [options.layer] : []),\n ...databases,\n ...[...storages].map((storage) => storage.layer),\n ...(options.storage ? [Layer.succeed(AppStorage)(options.storage)] : []),\n ...(telemetry\n ? [\n telemetryLayerOf(\n typeof options.telemetry === \"object\"\n ? options.telemetry.otlp\n : undefined,\n ),\n ]\n : []),\n ];\n const base: Layer.Layer<never, any, never> = layers.length\n ? Layer.mergeAll(...(layers as [Layer.Layer<never, any, never>]))\n : Layer.empty;\n const eventsOptions = plugins.listeners.length\n ? {\n ...options.events,\n listeners: [...(options.events?.listeners ?? []), ...plugins.listeners],\n }\n : options.events;\n const events =\n eventsOptions && createEvents(eventsOptions, services, telemetry);\n const definition = Object.freeze({\n services: Object.freeze([...services]),\n prefix,\n routes: Object.freeze(routes),\n ...(documentation ? { documentation } : {}),\n sockets: Object.freeze(\n services.flatMap((service) =>\n service.listSockets().map((socket) => ({\n ...socket.schema,\n service: service.name,\n path: socketPath(prefix, service.name, socket),\n })),\n ),\n ),\n ...(events ? { events: events.describe() } : {}),\n plugins: Object.freeze(plugins.plugins),\n telemetry,\n dashboard,\n });\n const runtime = ManagedRuntime.make(\n events\n ? (events.layer.pipe(Layer.provideMerge(base)) as unknown as Layer.Layer<\n never,\n any,\n never\n >)\n : base,\n );\n const appEvents = events?.bind(runtime);\n\n const log = loggerOf(requestLogging);\n // The error behind each 5xx answer, for `onError`.\n const failures = new WeakMap<Request, unknown>();\n const noteFailure = (\n request: Request,\n cause: Cause.Cause<unknown>,\n envelope: { status: number },\n ) => {\n if (envelope.status < 500) return;\n const error = Cause.squash(cause);\n // A failure keeps the error it stands for as `cause`.\n failures.set(\n request,\n (error instanceof BrickError || error instanceof ValidationError) &&\n error.cause !== undefined\n ? error.cause\n : error,\n );\n };\n\n /**\n * The route's response, with the trace ids echoed and the request logged.\n * With `trace`, and `telemetry` on, the request is a span.\n */\n const serve = (\n respond: (\n ids: ReturnType<typeof requestIds>,\n web: Request,\n ) => Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n unknown,\n HttpServerRequest.ParsedSearchParams | HttpRouter.RouteContext\n >,\n trace?: { method: string; path: string },\n ) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const web =\n request.source instanceof Request\n ? request.source\n : yield* HttpServerRequest.toWeb(request);\n markDashboardArrival(web);\n const started = Date.now();\n const build = (span?: Tracer.Span) =>\n Effect.gen(function* () {\n const ids = requestIds(web.headers, span?.traceId);\n let failure: ReturnType<typeof toErrorResponse> | undefined;\n const response = HttpServerResponse.setHeaders(\n yield* respond(ids, web).pipe(\n Effect.catchCause((cause) =>\n Effect.sync(() => {\n const envelope = toErrorResponse(cause, {\n logger,\n requestId: ids.requestId,\n });\n failure = envelope;\n noteFailure(web, cause, envelope);\n const retry = (\n envelope.details as { retryAfterSeconds?: unknown }\n )?.retryAfterSeconds;\n return HttpServerResponse.jsonUnsafe(envelope, {\n status: envelope.status,\n ...(envelope.status === 429 &&\n Number.isFinite(retry) && {\n headers: {\n \"retry-after\": String(\n Math.max(1, Math.ceil(retry as number)),\n ),\n },\n }),\n });\n }),\n ),\n ),\n {\n \"x-trace-id\": ids.traceId,\n \"x-request-id\": ids.requestId,\n ...(span && { traceparent: traceparentOf(span) }),\n },\n );\n if (span) recordResponse(span, response, ids.traceId, failure);\n return response;\n });\n const response =\n trace && telemetry\n ? yield* Effect.flatMap(runtime.contextEffect, (context) =>\n traceRequest(web, trace.method, trace.path, build).pipe(\n Effect.provideContext(context),\n ),\n )\n : yield* build();\n log?.(\n `${web.method} ${new URL(web.url).pathname} → ${response.status} (${Date.now() - started}ms)`,\n );\n return response;\n });\n\n const actionRoutes = routes.map((route, index) => {\n const { action } = bindings[index]!;\n return HttpRouter.route(\n route.method,\n route.path as `/${string}`,\n serve(\n ({ traceId, requestId }, web) =>\n Effect.gen(function* () {\n const call = { request: web, logger, traceId, requestId };\n const run = action.deliver\n ? action.deliver(web, call)\n : action.execute({\n ...(yield* readInput(route, action, web)),\n ctx: call,\n });\n const context = yield* runtime.contextEffect;\n return success(yield* run.pipe(Effect.provideContext(context)));\n }),\n { method: route.method, path: route.path },\n ),\n );\n });\n\n const endpointRoute = (def: EndpointDefinition) => {\n const database =\n def.database ?? resolveEndpointDatabase(def.service, services);\n return HttpRouter.route(\n def.method,\n def.path as `/${string}`,\n serve(\n ({ traceId, requestId }, web) =>\n Effect.gen(function* () {\n const set: EndpointContext[\"set\"] = { headers: {} };\n const params = Object.fromEntries(\n Object.entries(yield* HttpRouter.params).filter(\n ([, value]) => value !== undefined,\n ),\n ) as Record<string, string>;\n const body = yield* readBody(web);\n const result = yield* Effect.gen(function* () {\n const db = database && (yield* database.Database);\n return yield* def.handler({\n params,\n query: Object.fromEntries(new URL(web.url).searchParams),\n body,\n headers: Object.fromEntries(web.headers),\n request: web,\n set,\n db,\n logger,\n traceId,\n requestId,\n });\n }).pipe(\n // A thrown `{ status }` is a defect here, as it is a throw in core.\n Effect.catchCause((cause) => {\n const thrown = Cause.findDefect(cause);\n const failure = Result.isSuccess(thrown)\n ? httpStatusError(thrown.success)\n : thrown;\n return failure instanceof BrickError\n ? Effect.fail(failure)\n : Effect.failCause(cause);\n }),\n Effect.mapError(httpStatusError),\n Effect.provideContext(yield* runtime.contextEffect),\n );\n return HttpServerResponse.fromWeb(answer(result, set));\n }),\n { method: def.method, path: def.path },\n ),\n );\n };\n const endpointRoutes = mountedEndpoints.map(endpointRoute);\n\n const dashboardTools = new Map<string, { tool: AnyTool; service: string }>();\n for (const service of services)\n for (const tool of service.listTools()) {\n if ((tool.config as { dashboard?: boolean }).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 = dashboardTools.get(tool.name);\n if (other)\n throw new DuplicateNameError(\n `Brick: the services '${other.service}' 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 dashboardTools.set(tool.name, { tool, service: service.name });\n }\n const mcpKey = routeKey(\"POST\", DASHBOARD_MCP_ROUTE);\n const mcpRouteTaken = () =>\n new DuplicateNameError(\n `Brick: 'POST ${DASHBOARD_MCP_ROUTE}' is the dashboard's MCP endpoint`,\n );\n if (claimed.has(mcpKey)) throw mcpRouteTaken();\n const toolRegistry = createMcpRegistry({\n tools: [...dashboardTools.values()].map(({ tool }) => tool),\n });\n const readsOnly = (tool: McpToolDefinition) =>\n tool.annotations.readOnlyHint === true;\n // A tool that can change data is for a signed-in user: a token only reads.\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 return tool && !write && !readsOnly(tool)\n ? Effect.fail(\n new BrickError({\n code: \"FORBIDDEN\",\n status: 403,\n message: `${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 )\n : 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 const get = (\n path: `/${string}`,\n response: () => HttpServerResponse.HttpServerResponse,\n ) =>\n HttpRouter.route(\n \"GET\",\n path,\n serve(() => Effect.sync(response)),\n );\n const page = (path: string, html: string) =>\n get(path as `/${string}`, () =>\n HttpServerResponse.text(html, {\n contentType: \"text/html; charset=utf-8\",\n }),\n );\n const builtIns = [\n get(\"/_health\", () =>\n HttpServerResponse.jsonUnsafe({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }),\n ),\n ...(referencePath !== undefined\n ? [\n page(\n referencePath,\n scalarDocsHTML(\n referenceOptions.specUrl ?? openApiPath,\n referenceOptions.title ?? title,\n ),\n ),\n ]\n : []),\n ...(docs\n ? [\n get(openApiPath as `/${string}`, () =>\n HttpServerResponse.text(specJson(), {\n contentType: \"application/json;charset=utf-8\",\n }),\n ),\n page(docsPath, scalarDocsHTML(openApiPath, title)),\n page(swaggerPath, swaggerDocsHTML(openApiPath, title)),\n ]\n : []),\n get(\"/_brick/services\", () =>\n HttpServerResponse.text(architectureJson(), {\n contentType: \"application/json;charset=utf-8\",\n }),\n ),\n HttpRouter.route(\n \"POST\",\n DASHBOARD_MCP_ROUTE,\n serve((_, web) =>\n Effect.gen(function* () {\n const caller = dashboardMcpCaller(web);\n if (!caller)\n return HttpServerResponse.text(\"Unauthorized\", { status: 401 });\n const context = yield* runtime.contextEffect;\n const response = yield* mcpHandlers[caller.write ? 1 : 0]!(web, {\n dashboard: caller.user ? { user: caller.user } : {},\n }).pipe(Effect.provideContext(context));\n return HttpServerResponse.fromWeb(response);\n }),\n ),\n ),\n ...(localDirs.size\n ? [\n HttpRouter.route(\n \"GET\",\n LOCAL_FILES_ROUTE,\n serve((_, web) =>\n Effect.promise(() => localFilesRoute(localDirs)(web)).pipe(\n Effect.map(HttpServerResponse.fromWeb),\n ),\n ),\n ),\n ]\n : []),\n ];\n // Core's Elysia answers an unmatched route with its own problem+json and no Brick headers.\n const notFound = HttpRouter.route(\n \"*\",\n \"*\",\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n log?.(\n `${request.method} ${new URL(request.url, \"http://x\").pathname} → 404 (0ms)`,\n );\n return HttpServerResponse.text(\n JSON.stringify({\n type: \"not-found\",\n code: \"not-found\",\n status: 404,\n title: \"Not Found\",\n }),\n { status: 404, contentType: \"application/problem+json\" },\n );\n }),\n );\n\n // Endpoints added after startup need the router built again; the old one is kept until `stop`, for requests in flight.\n const lateRoutes: ReturnType<typeof endpointRoute>[] = [];\n const buildWeb = () =>\n HttpRouter.toWebHandler(\n HttpRouter.addAll([\n ...builtIns,\n ...actionRoutes,\n ...endpointRoutes,\n ...lateRoutes,\n notFound,\n ]),\n { disableLogger: true },\n );\n let web = buildWeb();\n const retired: (typeof web)[] = [];\n let stale = false;\n const router = () => {\n if (stale) {\n retired.push(web);\n web = buildWeb();\n stale = false;\n }\n return web;\n };\n /** What a plugin's middleware answers with, or `undefined` to let the request through. `carried` collects the headers each one set, for the response either way. */\n const intercept = async (\n request: Request,\n carried: Record<string, string>,\n ) => {\n for (const handler of plugins.middleware) {\n const set: { status?: number | string; headers: Record<string, string> } =\n { headers: {} };\n const answered = await runtime.runPromise(\n handler({ request, set }).pipe(\n Effect.map((result) =>\n result === undefined ? undefined : answer(result, set),\n ),\n Effect.catchCause((cause) =>\n Effect.sync(() => {\n const envelope = toErrorResponse(cause, { logger });\n noteFailure(request, cause, envelope);\n return Response.json(envelope, { status: envelope.status });\n }),\n ),\n ) as Effect.Effect<Response | undefined>,\n );\n Object.assign(carried, set.headers);\n if (answered) return answered;\n }\n };\n /** Run an app hook: its result, or `undefined` after logging a failure of it, which is never the request's. */\n const runHook = async <A>(\n name: string,\n effect: Effect.Effect<A, unknown, any>,\n ): Promise<{ value: A } | undefined> => {\n try {\n return await runtime.runPromise(\n effect.pipe(\n Effect.map((value) => ({ value })),\n Effect.catchCause((cause) =>\n Effect.sync(() => {\n logger.error(`The ${name} hook failed`, {}, Cause.pretty(cause));\n return undefined;\n }),\n ),\n ) as Effect.Effect<{ value: A } | undefined>,\n );\n } catch (error) {\n logger.error(`The ${name} hook failed`, {}, error);\n }\n };\n /** `onError`, then `onResponse`, on what the app is about to send. */\n const hooked = async (request: Request, response: Response) => {\n if (options.onError && response.status >= 500 && failures.has(request)) {\n const replacement = await runHook(\n \"onError\",\n options.onError({ error: failures.get(request), request, response }),\n );\n if (replacement?.value instanceof Response)\n response = keepTraceIds(replacement.value, response);\n }\n if (!options.onResponse) return response;\n const headers = new Headers(response.headers);\n const done = await runHook(\n \"onResponse\",\n options.onResponse({ request, status: response.status, headers }),\n );\n // A hook that failed may have left `headers` half changed.\n return done ? withHeaders(response, headers) : response;\n };\n const fetch: BrickApp[\"fetch\"] = async (input, init) => {\n const request =\n input instanceof Request && init === undefined\n ? input\n : new Request(input, init);\n markAddressSource(request, {\n clientIp: options.clientIp,\n server: () => server,\n });\n // CORS first, so a preflight is answered and its headers reach what plugins' middleware answers too.\n const policy = cors?.(request);\n if (policy?.preflight) return hooked(request, policy.preflight);\n const carried: Record<string, string> = {};\n let response =\n (plugins.middleware.length\n ? await intercept(request, carried)\n : undefined) ?? (await router().handler(request));\n const corsHeaders = policy?.headers ?? {};\n if (Object.keys(carried).length || Object.keys(corsHeaders).length) {\n const headers = new Headers(response.headers);\n // Headers a middleware set, under the response's own, as in core; CORS over both.\n for (const [name, value] of Object.entries(carried))\n if (!headers.has(name)) headers.set(name, value);\n for (const [name, value] of Object.entries(corsHeaders))\n headers.set(name, value);\n response = withHeaders(response, headers);\n }\n return hooked(request, response);\n };\n // The layer is the app's only source of services, as for actions.\n const run = (effect: Effect.Effect<any, any, any>) =>\n runtime.runPromiseExit(effect as Effect.Effect<any, any, never>);\n const raw = mountRawSockets({\n services,\n prefix,\n run,\n telemetry,\n drainTimeoutMs: options.drainTimeoutMs ?? 30_000,\n });\n const sockets = mountSockets({\n services,\n prefix,\n routes: [...routes, ...endpointDefs],\n sockets: options.sockets,\n raw,\n run,\n });\n const plugged = pluginLifecycle(plugins.lifecycles, (effect) =>\n runtime.runPromise(effect as Effect.Effect<void, unknown>),\n );\n let stopped = false;\n const live = () => {\n if (stopped)\n throw new Error(\n \"Brick: the app has stopped, so it cannot run an effect in its runtime\",\n );\n return runtime;\n };\n let server:\n | (ListeningServer & {\n stop(force?: boolean): unknown;\n requestIP(request: Request): { address: string } | null;\n })\n | undefined;\n const app: BrickApp = {\n fetch,\n handle: fetch,\n start: plugged.start,\n listen(port) {\n const ready = plugins.lifecycles.length ? plugged.start() : undefined;\n void server?.stop(true);\n server = Bun.serve({\n port,\n fetch: async (request, bun) => {\n await ready;\n if (sockets?.matches(request)) return sockets.upgrade(request, bun);\n return fetch(request);\n },\n websocket: sockets?.websocket ?? { message() {} },\n });\n const startEvents = () =>\n appEvents\n ?.start()\n .catch((error) => console.error(\"[Brick events]\", error));\n if (ready)\n ready.then(startEvents, (error) => {\n console.error(\"[Brick] A plugin failed to start:\", error);\n app\n .stop()\n .catch((stopError) =>\n console.error(\n \"[Brick] Stopping after a failed start failed:\",\n stopError,\n ),\n );\n });\n else startEvents();\n return server;\n },\n async stop(force) {\n // Before the server closes every connection.\n if (force !== true) await raw.drain();\n await server?.stop(true);\n server = undefined;\n try {\n try {\n await sockets?.dispose();\n } finally {\n await plugged.stop();\n }\n } finally {\n try {\n await appEvents?.stop();\n } finally {\n for (const handler of [web, ...retired.splice(0)])\n await handler.dispose();\n stopped = true;\n await runtime.dispose();\n }\n }\n },\n runPromise: (effect) =>\n Promise.resolve().then(() =>\n live().runPromise(effect as Effect.Effect<any, any, never>),\n ),\n runFork: (effect) =>\n live().runFork(effect as Effect.Effect<any, any, never>) as Fiber.Fiber<\n any,\n any\n >,\n events: appEvents,\n get server() {\n return server;\n },\n async serve({ port }) {\n await plugged.start();\n app.listen(port);\n return app;\n },\n shutdown: (force) => app.stop(force),\n drain: raw.drain,\n rawSockets: raw.stats,\n openApiDocument,\n architecture: () => JSON.parse(architectureJson()) as ArchitectureSchema,\n clientContract: () => describeClientContract(services, routes, prefix),\n workflowWorld: async () => {\n const state = Option.getOrUndefined(\n await runtime.runPromise(Effect.serviceOption(WorkflowState)),\n );\n return (\n state && workflowWorld(state, (effect) => runtime.runPromise(effect))\n );\n },\n referenceDocuments: async () => {\n const documents: ApiDocument[] = docs\n ? [{ title, document: openApiDocument() as OpenApiDocument }]\n : [];\n for (const extra of referenceOptions.documents ?? [])\n try {\n documents.push({\n title: extra.title,\n document:\n typeof extra.document === \"function\"\n ? await extra.document()\n : extra.document,\n });\n } catch (error) {\n console.warn(\n `[Brick] Skipping the \"${extra.title}\" API document: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return documents;\n },\n endpoint(def) {\n // Served by the app itself, and not in `claimed`: a second handler breaks the router.\n if (routeKey(def.method, def.path) === mcpKey) throw mcpRouteTaken();\n if (def.database && !databases.has(def.database.layer))\n throw new Error(\n `Brick: the endpoint '${def.method} ${def.path}' names a database the app does not hold: give it to a service, or pass the endpoint in brick({ endpoints }).`,\n );\n if (\n def.method === \"GET\" &&\n (definition.sockets.some((socket) => socket.path === def.path) ||\n raw.paths.includes(def.path))\n )\n throw new DuplicateNameError(\n `Brick: route '${def.method} ${def.path}' conflicts with a socket`,\n );\n if (mountEndpoint(def)) {\n lateRoutes.push(endpointRoute(def));\n stale = true;\n }\n },\n listEndpoints: () => [...endpointDefs],\n definition,\n };\n return app;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAGA,MAAa,kBAAkB;CAC7B,aAAa;EAAE,QAAQ;EAAK,SAAS;CAAc;CACnD,cAAc;EAAE,QAAQ;EAAK,SAAS;CAAe;CACrD,WAAW;EAAE,QAAQ;EAAK,SAAS;CAAY;CAC/C,WAAW;EAAE,QAAQ;EAAK,SAAS;CAAY;CAC/C,UAAU;EAAE,QAAQ;EAAK,SAAS;CAAW;CAC7C,cAAc;EAAE,QAAQ;EAAK,SAAS;CAAoB;CAC1D,uBAAuB;EAAE,QAAQ;EAAK,SAAS;CAAwB;AACzE;;AAKA,IAAa,aAAb,cAAgC,KAAK,YAAY,YAAY,CAAC,CAO3D,CAAC;;AASJ,IAAa,kBAAb,cAAqC,KAAK,YAAY,iBAAiB,CAAC,CAMrE;CACQ,OAAO;AAClB;;AAGA,IAAa,qBAAb,cAAwC,MAAM;CAC1B,OAAO;AAC3B;;;;;;;;;AAiCA,MAAM,gBAAgB,OAAe,SAA0B;CAC7D,IAAI,iBAAiB,SAAS,MAAM,SAAS,MAAM,OAAO;CAC1D,KACE,IAAI,KAAK,OAAO,eAAe,KAAK,GACpC,IACA,KAAK,OAAO,eAAe,EAAE,GAE7B,IAAI,OAAO,OAAO,IAAI,aAAa,KAAK,GAAG,aAAa,SAAS,MAC/D,OAAO;CACX,OAAO;AACT;AAEA,MAAM,gBAAgB,WACpB,OAAO,UAAU,MAAM,KACtB,UAAqB,OACrB,SAAoB;AAEvB,MAAM,WAAW,SACf,SAAS,QACT,OAAO,SAAS,YAChB,OAAQ,KAAyB,SAAS,YAC1C,OAAQ,KAAyB,YAAY;;AAG/C,MAAM,wBAAQ,IAAI,QAAyB;AAE3C,SAAS,MAAyB,SAA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