@brickkit/core 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,265 +1,351 @@
1
- import { Static, TSchema } from "@sinclair/typebox";
1
+ import { Static, TIntersect, TNumber, TObject, TSchema, TString, TUnion } from "@sinclair/typebox";
2
2
  import { Table } from "drizzle-orm";
3
- import { blob, foreignKey, index as index$1, integer as integer$1, primaryKey, real, sqliteTable as sqliteTable$1, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
3
+ import { SQLiteColumnBuilderBase, blob, foreignKey, index as index$1, integer as integer$1, primaryKey, real as real$1, sqliteTable as sqliteTable$1, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
4
+ import { Elysia } from "elysia";
4
5
  import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
5
6
  import { Sql } from "postgres";
6
7
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
7
8
  import { Database } from "bun:sqlite";
8
- //#region src/plugin.d.ts
9
- type PluginRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
10
- type PluginRouteScope = "app" | "service" | "resource";
11
- type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> = false | Readonly<Record<string, false | {
12
- path?: string;
13
- scope?: S;
14
- }>>;
15
- type ContextOf<S> = S extends Service<infer D, infer C> ? BaseContext<D> & C : never;
16
- interface PluginEndpointContext<C extends ActionContext = ActionContext> {
17
- params: Record<string, string>;
18
- query: Record<string, string | undefined>;
19
- body: unknown;
20
- headers: Record<string, string>;
21
- request: Request;
22
- set: {
23
- status?: number;
24
- headers: Record<string, string>;
25
- };
26
- ctx: C;
27
- }
28
- interface PluginRouteRegistrar<C extends ActionContext = ActionContext, S extends PluginRouteScope = PluginRouteScope> {
29
- action<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<I, O, E, C> & {
30
- path: string;
31
- method: PluginRouteMethod;
32
- scope?: S;
33
- }): Action<I, O, E, C>;
34
- action<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<I, O, E, C> & {
35
- path: string;
36
- method: PluginRouteMethod;
37
- scope?: S;
38
- }): Action<I, O, E, C>;
39
- endpoint(config: {
40
- name: string;
41
- path: string;
42
- method: PluginRouteMethod;
43
- scope?: S;
44
- handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;
45
- summary?: string;
46
- description?: string;
47
- tags?: string[];
48
- }): void;
49
- }
50
- interface ServicePluginContext<S extends Service<any, any> = Service<any, any>> {
51
- service: S;
52
- routes: PluginRouteRegistrar<ContextOf<S>, "app" | "service">;
53
- }
54
- interface ResourcePluginContext<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>> {
55
- service: S;
56
- resource: R;
57
- routes: PluginRouteRegistrar<ContextOf<S>>;
58
- }
59
- /** Plugins may specialize their returned API for the installation host. */
60
- interface ResourcePluginTypes {
61
- readonly table: unknown;
62
- readonly context: unknown;
63
- readonly resource: unknown;
64
- readonly api: object;
65
- }
66
- type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
67
- readonly types: infer H extends ResourcePluginTypes;
68
- } ? (H & {
69
- readonly table: T;
70
- readonly context: C;
71
- readonly resource: R;
72
- })["api"] : P extends ResourcePlugin<any, any, infer A> ? A : never;
73
- declare const pluginKind: unique symbol;
74
- interface ServicePlugin<S extends Service<any, any>, A> {
75
- readonly [pluginKind]: "service";
76
- readonly name: string;
77
- readonly routes?: PluginRoutes<"app" | "service">;
78
- readonly setup: (context: ServicePluginContext<S>) => A;
79
- }
80
- interface ResourcePlugin<S extends Service<any, any>, R extends Resource<any, any, any>, A extends object> {
81
- readonly [pluginKind]: "resource";
82
- readonly name: string;
83
- readonly routes?: PluginRoutes;
84
- readonly setup: (context: ResourcePluginContext<S, R>) => A;
85
- }
9
+ //#region src/deps.d.ts
10
+ declare const portType: unique symbol;
11
+ /** A typed dependency slot, declared with `port<T>()` and filled by `brick({ deps })`. */
12
+ interface Port<T> {
13
+ readonly [portType]?: T;
14
+ }
15
+ /** The dependency slots of a service: `{ carrier: port<Carrier>() }`. */
16
+ type Ports = Record<string, Port<unknown>>;
17
+ /** The values a set of ports is filled with: `{ carrier: Carrier }`. */
18
+ type DepsOf<P> = { [K in keyof P]: P[K] extends Port<infer T> ? T : never; };
86
19
  /**
87
- * Define a plugin that installs onto a service with `service.use(plugin)`. Its
88
- * `setup` receives the service and a `routes` registrar for adding actions and
89
- * raw HTTP endpoints, and returns the typed API that `service.use` hands back.
20
+ * Declare a dependency a service needs, without creating it. The app provides
21
+ * the value with `brick({ deps })`, and the service's code reads it as
22
+ * `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).
90
23
  *
91
- * @param definition - A unique `name`, optional `routes` controls that let the
92
- * user move or switch off the plugin's routes, and `setup`, which must be
93
- * synchronous.
94
- * @returns The plugin descriptor, frozen.
95
- * @throws When the name is empty or has surrounding whitespace.
24
+ * @returns A slot typed as `T`. It holds nothing at runtime.
96
25
  * @example
97
- * import { defineServicePlugin, t } from "@brickkit/core";
26
+ * import { defineService, port } from "@brickkit/core";
98
27
  *
99
- * export const greeting = (salutation = "Hello") =>
100
- * defineServicePlugin({
101
- * name: "example/greeting",
102
- * setup({ routes }) {
103
- * const hello = routes.action({
104
- * name: "hello",
105
- * input: t.Object({ name: t.String() }),
106
- * output: t.String(),
107
- * execute: ({ input }) => `${salutation}, ${input.name}!`,
108
- * });
109
- * return { hello };
110
- * },
111
- * });
28
+ * export const orders = defineService("orders", {
29
+ * database,
30
+ * deps: { carrier: port<Carrier>() },
31
+ * });
112
32
  *
113
- * const api = greeterService.use(greeting("Welcome"));
114
- * await api.hello({ input: { name: "Ada" } });
33
+ * // app.ts
34
+ * export default brick({ services: [orders], deps: { carrier: createCarrier() } });
115
35
  */
116
- declare function defineServicePlugin<S extends Service<any, any> = Service<any, any>, A = unknown>(definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & {
117
- setup: (context: ServicePluginContext<S>) => A & (A extends PromiseLike<unknown> ? never : unknown);
118
- }): ServicePlugin<S, A>;
36
+ declare function port<T>(): Port<T>;
119
37
  /**
120
- * Define a plugin that installs onto a resource (a table and its entity) with
121
- * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
122
- * `routes` registrar, whose routes are scoped under the resource's name, and
123
- * returns the typed API that `resource.use` hands back. `crud` is built this way.
38
+ * The deps of the app that is running the current listener or workflow step.
39
+ * Actions, tools and socket handlers read `ctx.deps` instead.
124
40
  *
125
- * @param definition - A unique `name`, optional `routes` controls, and `setup`,
126
- * which must be synchronous.
127
- * @returns The plugin descriptor, frozen.
128
- * @throws When the name is empty or has surrounding whitespace.
129
- */
130
- declare function defineResourcePlugin<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>, A extends object = object>(definition: Omit<ResourcePlugin<S, R, A>, typeof pluginKind> & {
131
- setup: (context: ResourcePluginContext<S, R>) => A & (A extends PromiseLike<unknown> ? never : unknown);
132
- }): ResourcePlugin<S, R, A>;
133
- /**
134
- * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
135
- * compiler, and the typed client.
41
+ * A workflow step is a plain function the Workflow SDK calls by name, so it
42
+ * cannot close over the app that started it. Brick runs every listener and every
43
+ * step inside its app, and this returns that app's `brick({ deps })`.
136
44
  *
137
- * @param action - An action.
138
- * @param prefix - The application's route prefix (default `/api`).
139
- * @returns `undefined` when no plugin bound the action (it uses its own route),
140
- * `false` when the plugin's route was switched off, otherwise the route's
141
- * `path` and `method`, the `clientPath` the typed client uses, and the owning
142
- * `plugin` and `resource`.
143
- */
144
- declare function getPluginActionRoute(action: Action<any, any, any, any>, prefix?: string): false | {
145
- path: string;
146
- method: PluginRouteMethod;
147
- clientPath: string[] | undefined;
148
- plugin: string;
149
- resource: string | undefined;
150
- } | undefined;
151
- /**
152
- * The raw HTTP endpoints plugins registered on a service, ready to mount on the
153
- * application. Each handler resolves the service's context before it runs.
45
+ * @param ports - Optional: the ports to type the result by (the same object a
46
+ * service passes as its `deps` option). Otherwise pass the type: `useDeps<{ carrier: Carrier }>()`.
47
+ * @returns The app's deps.
48
+ * @throws When called outside a listener or workflow step of a Brick app.
49
+ * @example
50
+ * export const ordersDeps = { carrier: port<Carrier>() };
154
51
  *
155
- * @param service - The service plugins were installed on.
156
- * @param prefix - The application's route prefix (default `/api`).
157
- * @returns The enabled endpoints: `path`, `method`, `handler`, and the
158
- * `summary`, `description`, and `tags` for OpenAPI.
52
+ * async function bookCarrier(orderId: string) {
53
+ * "use step";
54
+ * return useDeps(ordersDeps).carrier.book(orderId);
55
+ * }
159
56
  */
160
- declare function getPluginEndpoints(service: Service<any, any>, prefix?: string): {
161
- path: string;
162
- method: PluginRouteMethod;
163
- service: Service<any, any>;
164
- summary: string | undefined;
165
- description: string | undefined;
166
- tags: string[] | undefined;
167
- handler: (context: Omit<PluginEndpointContext, "ctx">) => Promise<unknown>;
168
- }[];
57
+ declare function useDeps<const P extends Ports>(ports: P): DepsOf<P>;
58
+ declare function useDeps<T = Record<string, unknown>>(): T;
169
59
  //#endregion
170
- //#region src/db/sqlite.d.ts
171
- interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
172
- /** Database file path or ':memory:' (default: ':memory:') */
173
- path?: string;
174
- /** Alias for path */
175
- filename?: string;
176
- /** Whether to enable WAL journal mode for file-based DBs (default: true) */
177
- wal?: boolean;
178
- /** Whether to enforce foreign key constraints (default: true) */
179
- foreignKeys?: boolean;
180
- /** Optional existing bun:sqlite Database instance */
181
- client?: Database;
182
- /** Optional Drizzle schema object for typed relational queries */
183
- schema?: TSchema;
184
- }
185
- type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<TSchema> & {
186
- $client: Database;
187
- };
60
+ //#region src/events/catalog.d.ts
61
+ /** A service's declared events: payload schema by event name. */
62
+ type EventCatalog = Record<string, TSchema>;
188
63
  /**
189
- * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
190
- * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
191
- *
192
- * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
193
- * other runtimes (e.g. Node) stays safe until this function is actually
194
- * called.
64
+ * One declared event, as `service.events.<name>`. Pass it to `defineListener({ on })`
65
+ * for a typed payload, or to `emitEvent` for a checked one.
195
66
  */
196
- declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase<TSchema>;
67
+ interface EventRef<TPayload = unknown> {
68
+ /** The event name on the wire: `<service>.<event>`, such as `orders.shipped`. */
69
+ readonly name: string;
70
+ readonly service: string;
71
+ readonly schema: TSchema;
72
+ /** The plugin that declared it, for events a `definePlugin` adds. */
73
+ readonly plugin?: string;
74
+ /** Type-level only: the payload this event carries. */
75
+ readonly __payload?: TPayload;
76
+ }
77
+ /** `service.events`: one `EventRef` per catalog entry. */
78
+ type EventRefs<C extends EventCatalog> = { readonly [K in keyof C & string]: EventRef<Static<C[K]>>; };
79
+ declare function isEventRef(value: unknown): value is EventRef;
197
80
  //#endregion
198
- //#region src/secrets.d.ts
81
+ //#region src/events/types.d.ts
199
82
  /**
200
- * Type-safe secrets & environment variables.
201
- *
202
- * Declare each secret once at module scope instead of scattering untyped
203
- * `process.env.FOO` reads:
204
- *
205
- * const port = secret("PORT").default("3333").transform(Number).require();
206
- * const baseUrl = secret("BASE_URL").url().require();
207
- * const key = secret("STRIPE_KEY").validate((v) =>
208
- * v.startsWith("sk_") || "must start with sk_"
209
- * ).require();
210
- *
211
- * Values resolve from the environment (Bun populates `process.env` from
212
- * `.env` locally; in prod the same env source applies — a future
213
- * `SecretSource` such as AWS can slot in without touching call sites).
214
- *
215
- * Resolution order per secret: test/session override → source (`process.env`
216
- * by default) → declared `default`. `resolveSecrets()` validates every
217
- * registered secret at boot and throws listing all missing required ones.
83
+ * An event, as it was recorded. It is the same for every listener of it.
218
84
  */
219
- interface SecretSource {
220
- get(name: string): string | undefined;
221
- }
222
- /** Default source: `process.env` (Bun loads `.env` into it automatically). */
223
- declare const envSource: SecretSource;
224
- interface SecretOptions {
225
- /** Fallback when the source has no value. Secrets without a default are required. */
226
- default?: string;
85
+ interface EventEnvelope<TPayload = unknown> {
86
+ /** Unique per event. Every listener's delivery of the event shares it. */
87
+ id: string;
88
+ /** The event name, such as `user.create`. */
89
+ name: string;
90
+ /** What happened. JSON data. */
91
+ payload: TPayload;
92
+ /** When it happened, as an ISO timestamp. */
93
+ occurredAt: string;
94
+ /** The trace of the request that caused it, so a listener continues the same trace. */
95
+ traceId?: string;
96
+ /** What emitted it, such as `identity.user` for a generated CRUD write. */
97
+ source?: string;
227
98
  }
228
- /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
229
- type SecretValidator<T> = (value: T) => void | boolean | string;
230
- declare class SecretRef<T = string> {
231
- readonly name: string;
232
- readonly options: SecretOptions;
233
- private transformFn?;
234
- private validators;
235
- constructor(name: string, options?: SecretOptions);
236
- /** True when a default was declared (i.e. the secret is optional). */
237
- get hasDefault(): boolean;
238
- /** Fallback used when the source has no value. Makes the secret optional. */
239
- default(value: string): this;
99
+ /**
100
+ * One listener's delivery of an event: the envelope, plus which listener it is for
101
+ * and which attempt this is.
102
+ */
103
+ interface EventDelivery<TPayload = unknown> extends EventEnvelope<TPayload> {
104
+ /** The name of the listener this delivery is for. */
105
+ listener: string;
240
106
  /**
241
- * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
242
- * Runs before validators; a throwing transform fails resolution.
107
+ * `<event id>:<listener>`. It is the same on every retry, so a listener can use
108
+ * it to avoid doing the work twice: delivery is at least once.
243
109
  */
244
- transform<U>(fn: (raw: string) => U): SecretRef<U>;
245
- /** Run a custom check on the (transformed) value at every resolution. */
246
- validate(fn: SecretValidator<T>): this;
247
- /** Shorthand validator: value must parse as a URL. String refs only. */
248
- url(this: SecretRef<string>): SecretRef<string>;
249
- private resolveRaw;
250
- private coerce;
251
- /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
252
- value(source?: SecretSource): T | undefined;
253
- /** Resolved value, or throws naming the missing/invalid secret. */
254
- require(source?: SecretSource): T;
255
- /** True when a value would resolve (override, source, or default). */
256
- isSet(source?: SecretSource): boolean;
110
+ deliveryId: string;
111
+ /** 1 on the first try, 2 on the first retry, and so on. */
112
+ attempt: number;
257
113
  }
258
114
  /**
259
- * Declare a secret. Idempotent: re-declaring the same name returns the
260
- * original ref (first declaration wins) so module re-evaluation is safe.
261
- */
262
- declare function secret(name: string, options?: SecretOptions): SecretRef<string>;
115
+ * The CRUD events of a resource called `user`, by operation. Listeners of
116
+ * `user.create`, `user.update` and `user.delete` receive these payloads.
117
+ */
118
+ type CrudEventPayload<TRow = Record<string, unknown>> = {
119
+ id: unknown;
120
+ row: TRow;
121
+ } | {
122
+ id: unknown;
123
+ before: TRow;
124
+ after: TRow;
125
+ };
126
+ /**
127
+ * What `retry` receives: one member per error the listener declares, or the
128
+ * fallback for anything else it threw.
129
+ */
130
+ type ListenerFailure<TErrors extends Record<string, ActionErrorDefinition>> = { [K in keyof TErrors & string]: {
131
+ code: K;
132
+ message: string;
133
+ details: ErrorDetails<TErrors[K]>;
134
+ }; }[keyof TErrors & string] | {
135
+ code: "UNKNOWN";
136
+ message: string;
137
+ cause: unknown;
138
+ };
139
+ /** What a listener's `retry` decides: try again later, or park the delivery as dead now. */
140
+ type RetryDecision = "retry" | "dead";
141
+ /**
142
+ * A listener: code that runs when an event it listens for has been recorded.
143
+ */
144
+ interface EventListener<TPayload = any> {
145
+ /** Unique among the app's listeners. It is part of each delivery's id. */
146
+ readonly name: string;
147
+ /**
148
+ * The event names to listen for. A trailing `*` matches a prefix (`user.*`),
149
+ * and `*` alone matches every event.
150
+ */
151
+ readonly on: readonly string[];
152
+ /**
153
+ * A handler that runs in the dispatching process for each delivery. Throwing
154
+ * retries the delivery with a growing delay. A listener has this or `workflow`.
155
+ */
156
+ readonly run?: (delivery: EventDelivery<TPayload>) => void | Promise<void>;
157
+ /**
158
+ * Decides what a failed delivery does next. Without it, every failure retries
159
+ * until `maxAttempts`. It cannot extend the attempts: `"retry"` still parks the
160
+ * delivery as dead once they run out.
161
+ */
162
+ readonly errors?: Record<string, ActionErrorDefinition>;
163
+ readonly retry?: (error: ListenerFailure<any>) => RetryDecision;
164
+ /**
165
+ * A durable workflow that runs for each delivery, on the app's `events.world`.
166
+ * The delivery counts as done once its run has started; the workflow retries
167
+ * its own steps from there. A listener has this or `run`.
168
+ */
169
+ readonly workflow?: EventWorkflow<TPayload>;
170
+ /** Attempts before the delivery is parked as dead. Defaults to the dispatcher's. */
171
+ readonly maxAttempts?: number;
172
+ }
173
+ /**
174
+ * What a workflow listener's workflow receives: the event and which listener it
175
+ * is for. It has no `attempt`, because one delivery starts one run however many
176
+ * times it is tried.
177
+ */
178
+ type WorkflowEvent<TPayload = any> = Omit<EventDelivery<TPayload>, "attempt">;
179
+ /**
180
+ * A function marked `"use workflow"`, run once per delivery of the listener it is
181
+ * given to.
182
+ */
183
+ type EventWorkflow<TPayload = any> = (event: WorkflowEvent<TPayload>) => Promise<unknown>;
184
+ /**
185
+ * The world workflow listeners run on: the queue and storage behind the Workflow
186
+ * SDK. `createWorld()` from `@brickkit/redis-world` or `@brickkit/bullmq-world`
187
+ * makes one. Brick starts it with the app's events and closes it when they stop.
188
+ */
189
+ interface EventsWorld {
190
+ /**
191
+ * Names a run after its key so that starting it twice makes one run. A world
192
+ * without it would start a second run when an event is delivered again, so
193
+ * Brick refuses such a world.
194
+ */
195
+ createRunId?(options?: Readonly<Record<string, unknown>>): string;
196
+ start?(): Promise<void>;
197
+ close?(): Promise<void>;
198
+ registerHandler?(prefix: any, handler: (request: Request) => Promise<Response>): void;
199
+ }
200
+ /**
201
+ * Where the workflows of an app are built from. The CLI (`brick dev`,
202
+ * `brick start`) writes the bundle to `<root>/.well-known/workflow/v1` before
203
+ * events start, and events read it from there.
204
+ */
205
+ interface WorkflowsOptions {
206
+ /** The project root: where the Workflow SDK is installed. Default: the working directory. */
207
+ root?: string;
208
+ }
209
+ /**
210
+ * How the dispatcher delivers recorded events.
211
+ */
212
+ interface DispatchOptions {
213
+ /**
214
+ * Whether to look for due deliveries on a timer, and right after a commit.
215
+ * Default `true`. With `false`, deliveries run only when something calls
216
+ * `app.events.drain()`: a cron job, a worker you drive yourself, or a test.
217
+ */
218
+ timer?: boolean;
219
+ /** How often to look for deliveries that are due, in milliseconds. Default 1000. */
220
+ intervalMs?: number;
221
+ /** Most deliveries claimed at once. Default 50. */
222
+ batchSize?: number;
223
+ /** Attempts before a delivery is parked as dead. Default 8. */
224
+ maxAttempts?: number;
225
+ /** How long a claimed delivery may run before another dispatcher takes it, in milliseconds. Default 60000. */
226
+ claimTimeoutMs?: number;
227
+ /** Longest wait before a retry, in milliseconds. Default 300000. */
228
+ maxBackoffMs?: number;
229
+ /** How long delivered rows are kept, in milliseconds. Default 86400000 (one day). 0 keeps none. */
230
+ retainDeliveredMs?: number;
231
+ }
232
+ /**
233
+ * The `events` option of `brick()`.
234
+ */
235
+ interface EventsOptions {
236
+ /** The listeners of the app. */
237
+ listeners?: readonly EventListener[];
238
+ /**
239
+ * Whether this process delivers recorded events. `true` (the default) starts a
240
+ * dispatcher with the default settings, an object tunes it, and `false` only
241
+ * records events, for an app whose events are delivered by another process.
242
+ */
243
+ dispatch?: boolean | DispatchOptions;
244
+ /**
245
+ * The world that runs `workflow` listeners. Required when any listener has one.
246
+ * Brick starts it when the app's events start and closes it when they stop.
247
+ */
248
+ world?: EventsWorld;
249
+ /** Where the workflow bundle lives. Only used with workflow listeners. */
250
+ workflows?: WorkflowsOptions;
251
+ }
252
+ /**
253
+ * Records an event inside the transaction it was given. The event is committed
254
+ * with the write, or not at all.
255
+ */
256
+ type EventRecorder = (name: string, payload: unknown) => Promise<void>;
257
+ /**
258
+ * What a service with events offers the code that writes to its database. A
259
+ * service has it once `brick({ events })` is set up and its database holds an
260
+ * outbox table.
261
+ */
262
+ interface ServiceEvents {
263
+ /** Whether any listener wants the event, so a write can skip recording one. */
264
+ wants(name: string): boolean;
265
+ /**
266
+ * Run `fn` in a database transaction. Events it records are committed with
267
+ * whatever else it wrote, or not at all, and are delivered after the commit.
268
+ */
269
+ transaction<T>(db: unknown, context: {
270
+ traceId?: string;
271
+ source?: string;
272
+ }, fn: (tx: any, record: EventRecorder) => Promise<T>): Promise<T>;
273
+ /**
274
+ * Record an event in a transaction the caller already has open. It is
275
+ * committed with that transaction. Nothing tells Brick when the caller commits,
276
+ * so delivery waits for the dispatcher's next poll.
277
+ */
278
+ record(tx: unknown, context: {
279
+ traceId?: string;
280
+ source?: string;
281
+ }, name: string, payload: unknown): Promise<void>;
282
+ }
283
+ //#endregion
284
+ //#region src/secrets.d.ts
285
+ /**
286
+ * Type-safe secrets & environment variables.
287
+ *
288
+ * Declare each secret once at module scope instead of scattering untyped
289
+ * `process.env.FOO` reads:
290
+ *
291
+ * const port = defineSecret("PORT").default("3333").transform(Number).require();
292
+ * const baseUrl = defineSecret("BASE_URL").url().require();
293
+ * const key = defineSecret("STRIPE_KEY").validate((v) =>
294
+ * v.startsWith("sk_") || "must start with sk_"
295
+ * ).require();
296
+ *
297
+ * Values resolve from the environment (Bun populates `process.env` from
298
+ * `.env` locally; in prod the same env source applies — a future
299
+ * `SecretSource` such as AWS can slot in without touching call sites).
300
+ *
301
+ * Resolution order per secret: test/session override → source (`process.env`
302
+ * by default) → declared `default`. `resolveSecrets()` validates every
303
+ * registered secret at boot and throws listing all missing required ones.
304
+ */
305
+ interface SecretSource {
306
+ get(name: string): string | undefined;
307
+ }
308
+ /** Default source: `process.env` (Bun loads `.env` into it automatically). */
309
+ declare const envSource: SecretSource;
310
+ interface SecretOptions {
311
+ /** Fallback when the source has no value. Secrets without a default are required. */
312
+ default?: string;
313
+ }
314
+ /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
315
+ type SecretValidator<T> = (value: T) => void | boolean | string;
316
+ declare class SecretRef<T = string> {
317
+ readonly name: string;
318
+ readonly options: SecretOptions;
319
+ private transformFn?;
320
+ private validators;
321
+ constructor(name: string, options?: SecretOptions);
322
+ /** True when a default was declared (i.e. the secret is optional). */
323
+ get hasDefault(): boolean;
324
+ /** Fallback used when the source has no value. Makes the secret optional. */
325
+ default(value: string): this;
326
+ /**
327
+ * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
328
+ * Runs before validators; a throwing transform fails resolution.
329
+ */
330
+ transform<U>(fn: (raw: string) => U): SecretRef<U>;
331
+ /** Run a custom check on the (transformed) value at every resolution. */
332
+ validate(fn: SecretValidator<T>): this;
333
+ /** Shorthand validator: value must parse as a URL. String refs only. */
334
+ url(this: SecretRef<string>): SecretRef<string>;
335
+ private resolveRaw;
336
+ private coerce;
337
+ /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
338
+ value(source?: SecretSource): T | undefined;
339
+ /** Resolved value, or throws naming the missing/invalid secret. */
340
+ require(source?: SecretSource): T;
341
+ /** True when a value would resolve (override, source, or default). */
342
+ isSet(source?: SecretSource): boolean;
343
+ }
344
+ /**
345
+ * Declare a secret. Idempotent: re-declaring the same name returns the
346
+ * original ref (first declaration wins) so module re-evaluation is safe.
347
+ */
348
+ declare function defineSecret(name: string, options?: SecretOptions): SecretRef<string>;
263
349
  /**
264
350
  * Validate every registered secret at boot. Throws a single error listing
265
351
  * all missing required secrets. Returns the resolved values.
@@ -282,113 +368,494 @@ declare function overrideSecrets(values: Record<string, string | undefined>): vo
282
368
  /** Clear registry and overrides. Test-only. */
283
369
  declare function resetSecrets(): void;
284
370
  //#endregion
285
- //#region src/db/postgres.d.ts
286
- interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
287
- /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */
288
- client?: Sql;
289
- /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */
290
- url?: string;
291
- /** Connection string alias */
292
- connectionString?: string;
293
- host?: string;
294
- port?: number;
295
- user?: string;
296
- password?: string;
297
- database?: string;
298
- ssl?: boolean | "require" | "allow" | "prefer" | "verify-full";
299
- max?: number;
300
- /**
301
- * Disable prepared statements (required for transaction-mode poolers such
302
- * as Supabase's Supavisor on :6543, which cannot hold named prepared
303
- * statements across transactions).
304
- */
305
- prepare?: boolean;
306
- /** Optional Drizzle schema for relational queries */
307
- schema?: TSchema;
308
- /** Custom schema name for Encore-style isolated schemas */
309
- schemaName?: string;
310
- }
311
- type PostgresDatabase<_TSchema extends Record<string, unknown> = Record<string, unknown>> = any;
312
- interface DatabaseAdapter<TDb = any, TConfig = any> {
313
- createDatabase(config?: TConfig): TDb;
314
- }
371
+ //#region src/define-plugin.d.ts
372
+ /** The version of this @brickkit/core, read from its package.json; `""` when unknown. */
373
+ declare function brickVersion(): string;
315
374
  /**
316
- * Creates a PostgreSQL Drizzle instance using postgres-js.
317
- * Static imports (both are hard dependencies in package.json) so bundlers
318
- * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
319
- * `sqlite.ts` since it only exists under Bun.
375
+ * Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,
376
+ * `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.
320
377
  */
321
- declare function createPostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: PostgresDatabaseConfig<TSchema>): PostgresDatabase<TSchema>;
322
- //#endregion
323
- //#region src/db/define.d.ts
324
- type EnvInput<T> = T | SecretRef<T>;
325
- type EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>>; };
326
- interface DefinitionOptions<TSchema extends Record<string, unknown>> {
327
- name?: string;
328
- /** Drizzle tables retained for schema tooling. Never applied at runtime. */
329
- tables?: (TSchema & Record<string, Table>) | readonly Table[];
330
- schema?: TSchema;
331
- }
332
- type SQLiteDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
333
- engine?: "sqlite";
334
- client?: SQLiteDatabaseConfig<TSchema>["client"];
335
- url?: never;
336
- connectionString?: never;
337
- };
338
- type PostgresDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema" | "client">> & {
339
- engine: "postgres";
340
- path?: never;
341
- filename?: never;
342
- wal?: never;
343
- foreignKeys?: never;
344
- client?: PostgresDatabaseConfig<TSchema>["client"];
378
+ declare function satisfiesRange(version: string, range: string): boolean;
379
+ declare const sqliteBuilders: {
380
+ /** A table. Its name gets the plugin's prefix (`page_comments`). */
381
+ table: <C extends Record<string, SQLiteColumnBuilderBase>>(name: string, columns: C) => import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
382
+ name: string;
383
+ schema: undefined;
384
+ columns: { [Key in keyof C]: import("drizzle-orm/sqlite-core").SQLiteColumn<{
385
+ name: (Omit<C[Key]["_"], "name"> & {
386
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
387
+ })["name"];
388
+ tableName: string;
389
+ dataType: (Omit<C[Key]["_"], "name"> & {
390
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
391
+ })["dataType"];
392
+ columnType: (Omit<C[Key]["_"], "name"> & {
393
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
394
+ })["columnType"];
395
+ data: Omit<C[Key]["_"], "name"> & {
396
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
397
+ } extends (infer T) ? T extends Omit<C[Key]["_"], "name"> & {
398
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
399
+ } ? T extends {
400
+ $type: infer U;
401
+ } ? U : T["data"] : never : never;
402
+ driverParam: (Omit<C[Key]["_"], "name"> & {
403
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
404
+ })["driverParam"];
405
+ notNull: Omit<C[Key]["_"], "name"> & {
406
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
407
+ } extends (infer T_1) ? T_1 extends Omit<C[Key]["_"], "name"> & {
408
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
409
+ } ? T_1 extends {
410
+ notNull: true;
411
+ } ? true : false : never : never;
412
+ hasDefault: Omit<C[Key]["_"], "name"> & {
413
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
414
+ } extends (infer T_2) ? T_2 extends Omit<C[Key]["_"], "name"> & {
415
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
416
+ } ? T_2 extends {
417
+ hasDefault: true;
418
+ } ? true : false : never : never;
419
+ isPrimaryKey: Omit<C[Key]["_"], "name"> & {
420
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
421
+ } extends (infer T_3) ? T_3 extends Omit<C[Key]["_"], "name"> & {
422
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
423
+ } ? T_3 extends {
424
+ isPrimaryKey: true;
425
+ } ? true : false : never : never;
426
+ isAutoincrement: Omit<C[Key]["_"], "name"> & {
427
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
428
+ } extends (infer T_4) ? T_4 extends Omit<C[Key]["_"], "name"> & {
429
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
430
+ } ? T_4 extends {
431
+ isAutoincrement: true;
432
+ } ? true : false : never : never;
433
+ hasRuntimeDefault: Omit<C[Key]["_"], "name"> & {
434
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
435
+ } extends (infer T_5) ? T_5 extends Omit<C[Key]["_"], "name"> & {
436
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
437
+ } ? T_5 extends {
438
+ hasRuntimeDefault: true;
439
+ } ? true : false : never : never;
440
+ enumValues: (Omit<C[Key]["_"], "name"> & {
441
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
442
+ })["enumValues"];
443
+ baseColumn: Omit<C[Key]["_"], "name"> & {
444
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
445
+ } extends (infer T_6) ? T_6 extends Omit<C[Key]["_"], "name"> & {
446
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
447
+ } ? T_6 extends {
448
+ baseBuilder: infer U_1 extends import("drizzle-orm").ColumnBuilderBase;
449
+ } ? import("drizzle-orm").Column<{
450
+ name: U_1["_"]["name"];
451
+ tableName: string;
452
+ dataType: U_1["_"]["dataType"];
453
+ columnType: U_1["_"]["columnType"];
454
+ data: U_1["_"] extends (infer T_7) ? T_7 extends U_1["_"] ? T_7 extends {
455
+ $type: infer U;
456
+ } ? U : T_7["data"] : never : never;
457
+ driverParam: U_1["_"]["driverParam"];
458
+ notNull: U_1["_"] extends (infer T_8) ? T_8 extends U_1["_"] ? T_8 extends {
459
+ notNull: true;
460
+ } ? true : false : never : never;
461
+ hasDefault: U_1["_"] extends (infer T_9) ? T_9 extends U_1["_"] ? T_9 extends {
462
+ hasDefault: true;
463
+ } ? true : false : never : never;
464
+ isPrimaryKey: U_1["_"] extends (infer T_10) ? T_10 extends U_1["_"] ? T_10 extends {
465
+ isPrimaryKey: true;
466
+ } ? true : false : never : never;
467
+ isAutoincrement: U_1["_"] extends (infer T_11) ? T_11 extends U_1["_"] ? T_11 extends {
468
+ isAutoincrement: true;
469
+ } ? true : false : never : never;
470
+ hasRuntimeDefault: U_1["_"] extends (infer T_12) ? T_12 extends U_1["_"] ? T_12 extends {
471
+ hasRuntimeDefault: true;
472
+ } ? true : false : never : never;
473
+ enumValues: U_1["_"]["enumValues"];
474
+ baseColumn: U_1["_"] extends (infer T_13) ? T_13 extends U_1["_"] ? T_13 extends {
475
+ baseBuilder: infer U_1 extends import("drizzle-orm").ColumnBuilderBase;
476
+ } ? import("drizzle-orm").Column< /*elided*/ any, {}, Omit<U_1["_"], "name" | "brand" | "dataType" | "columnType" | "data" | "driverParam" | "notNull" | "hasDefault" | "enumValues" | "identity" | "generated" | "dialect" | "tableName" | "isPrimaryKey" | "isAutoincrement" | "hasRuntimeDefault" | "baseColumn"> extends (infer T_14) ? { [K in keyof T_14]: T_14[K]; } : never> : never : never : never;
477
+ identity: U_1["_"] extends (infer T_15) ? T_15 extends U_1["_"] ? T_15 extends {
478
+ identity: "always";
479
+ } ? "always" : T_15 extends {
480
+ identity: "byDefault";
481
+ } ? "byDefault" : undefined : never : never;
482
+ generated: U_1["_"] extends (infer T_16) ? T_16 extends U_1["_"] ? T_16 extends {
483
+ generated: infer G;
484
+ } ? unknown extends G ? undefined : G extends undefined ? undefined : G : undefined : never : never;
485
+ }, {}, Omit<U_1["_"], "name" | "brand" | "dataType" | "columnType" | "data" | "driverParam" | "notNull" | "hasDefault" | "enumValues" | "identity" | "generated" | "dialect" | "tableName" | "isPrimaryKey" | "isAutoincrement" | "hasRuntimeDefault" | "baseColumn"> extends (infer T_17) ? { [K in keyof T_17]: T_17[K]; } : never> : never : never : never;
486
+ identity: Omit<C[Key]["_"], "name"> & {
487
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
488
+ } extends (infer T_18) ? T_18 extends Omit<C[Key]["_"], "name"> & {
489
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
490
+ } ? T_18 extends {
491
+ identity: "always";
492
+ } ? "always" : T_18 extends {
493
+ identity: "byDefault";
494
+ } ? "byDefault" : undefined : never : never;
495
+ generated: Omit<C[Key]["_"], "name"> & {
496
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
497
+ } extends (infer T_19) ? T_19 extends Omit<C[Key]["_"], "name"> & {
498
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
499
+ } ? T_19 extends {
500
+ generated: infer G;
501
+ } ? unknown extends G ? undefined : G extends undefined ? undefined : G : undefined : never : never;
502
+ }, {}, Omit<Omit<C[Key]["_"], "name"> & {
503
+ name: C[Key]["_"]["name"] extends "" ? import("drizzle-orm").Assume<Key, string> : C[Key]["_"]["name"];
504
+ }, "name" | "brand" | "dataType" | "columnType" | "data" | "driverParam" | "notNull" | "hasDefault" | "enumValues" | "identity" | "generated" | "dialect" | "tableName" | "isPrimaryKey" | "isAutoincrement" | "hasRuntimeDefault" | "baseColumn"> extends (infer T_20) ? { [K_1 in keyof T_20]: T_20[K_1]; } : never>; };
505
+ dialect: "sqlite";
506
+ }>;
507
+ text: (name: string) => import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<string, [string, ...string[]], number | undefined>;
508
+ integer: (name: string) => import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<string>;
509
+ real: (name: string) => import("drizzle-orm/sqlite-core").SQLiteRealBuilderInitial<string>;
510
+ boolean: (name: string) => import("drizzle-orm/sqlite-core").SQLiteBooleanBuilderInitial<string>;
511
+ /** A `Date`, stored as epoch milliseconds or `timestamptz`. */
512
+ timestamp: (name: string) => import("drizzle-orm/sqlite-core").SQLiteTimestampBuilderInitial<string>;
513
+ json: (name: string) => import("drizzle-orm/sqlite-core").SQLiteTextJsonBuilderInitial<string>;
345
514
  };
346
- type DatabaseDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;
347
- interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>> {
348
- readonly kind: "brick-database";
349
- readonly name?: string;
515
+ /**
516
+ * Engine-neutral column builders for `tables`. Brick passes the SQLite or
517
+ * Postgres ones to match the host database; the types follow SQLite's, and the
518
+ * JavaScript values are the same on both (a `Date` for `timestamp`).
519
+ */
520
+ type PluginTableBuilders = typeof sqliteBuilders & {
521
+ /** The host database's engine. */
350
522
  readonly engine: "sqlite" | "postgres";
351
- readonly tables: Readonly<Record<string, Table>>;
352
- readonly schema: TSchema;
353
- getDb(): TDb;
354
- close?(): void | Promise<void>;
523
+ };
524
+ interface HookBase<C> {
525
+ ctx: C;
526
+ /** The write's open transaction: write other tables through it. */
527
+ tx: any;
355
528
  }
356
529
  /**
357
- * Whether a value is a database handle made by `defineDatabase`.
530
+ * Subscribe to the host's CRUD writes (resources with `crud()`). `before*` and
531
+ * `after*` run inside the write's transaction, after the host's own crud hooks;
532
+ * a hook that throws rolls the write back. `afterCommit` runs after the commit.
533
+ */
534
+ interface PluginHooks<C = ActionContext> {
535
+ beforeCreate(hook: (args: HookBase<C> & {
536
+ data: Record<string, unknown>;
537
+ }) => unknown): void;
538
+ afterCreate(hook: (args: HookBase<C> & {
539
+ row: Record<string, unknown>;
540
+ }) => unknown): void;
541
+ beforeUpdate(hook: (args: HookBase<C> & {
542
+ id: unknown;
543
+ data: Record<string, unknown>;
544
+ }) => unknown): void;
545
+ afterUpdate(hook: (args: HookBase<C> & {
546
+ id: unknown;
547
+ row: Record<string, unknown>;
548
+ }) => unknown): void;
549
+ beforeDelete(hook: (args: HookBase<C> & {
550
+ id: unknown;
551
+ }) => unknown): void;
552
+ afterDelete(hook: (args: HookBase<C> & {
553
+ id: unknown;
554
+ }) => unknown): void;
555
+ afterCommit(hook: (args: {
556
+ operation: "create" | "update" | "delete";
557
+ id: unknown;
558
+ row?: Record<string, unknown>;
559
+ ctx: C;
560
+ }) => unknown): void;
561
+ }
562
+ type Secrets = Record<string, SecretRef<any>>;
563
+ type OptionsOf<O> = O extends TSchema ? Static<O> : {};
564
+ /**
565
+ * The context of a plugin's actions, endpoints and hooks: the host's request
566
+ * context, loosely typed, with `deps` set to the plugin's own declared deps.
567
+ */
568
+ type PluginContext<P extends Ports = {}> = BaseContext<any> & PluginServiceContext<P>;
569
+ /** A plugin's view of its host's service context: loose, except `deps`, which is the plugin's. */
570
+ type PluginServiceContext<P extends Ports = {}> = {
571
+ [key: string]: any;
572
+ /** The values passed for the plugin's `deps` when it was installed. */
573
+ deps: DepsOf<P>;
574
+ };
575
+ /** What every setup callback receives. */
576
+ interface PluginSetupContext<O, S, T, E extends EventCatalog, P extends Ports = {}> {
577
+ /** The validated options, defaults filled in. */
578
+ options: O;
579
+ /** The declared secrets, to read when they are needed. */
580
+ secrets: S;
581
+ /** The tables this plugin owns, by the keys `tables` returned. */
582
+ tables: T;
583
+ /** The plugin's events, as `emitEvent` and `defineListener` take them. */
584
+ events: EventRefs<E>;
585
+ /** The values passed for `deps` when the plugin was installed. */
586
+ deps: DepsOf<P>;
587
+ /** The host service. Actions registered on it read the plugin's deps as `ctx.deps`. */
588
+ service: Service<any, PluginServiceContext<P>>;
589
+ routes: PluginRouteRegistrar<PluginContext<P>>;
590
+ /** The host's CRUD writes: on a service, those of all its resources. */
591
+ hooks: PluginHooks<PluginContext<P>>;
592
+ }
593
+ /** The lifecycle context of `on("start")` and `on("stop")`. */
594
+ interface PluginLifecycleContext<O, S, P extends Ports = {}> {
595
+ options: O;
596
+ secrets: S;
597
+ deps: DepsOf<P>;
598
+ }
599
+ /** What `app` receives: the app-wide part of a plugin. */
600
+ interface PluginAppContext<O, S, P extends Ports = {}> {
601
+ options: O;
602
+ secrets: S;
603
+ /** The values passed for `deps` when the plugin was installed. */
604
+ deps: DepsOf<P>;
605
+ /**
606
+ * Run when the app starts (`app.start()`, which `listen`, `brick dev` and
607
+ * `brick start` call) in install order, and when it stops in reverse order.
608
+ */
609
+ on(event: "start" | "stop", handler: (context: PluginLifecycleContext<O, S, P>) => void | Promise<void>): void;
610
+ /**
611
+ * Run before every request is routed. Return a `Response` (or any value) to
612
+ * answer it here; return nothing to let it through.
613
+ */
614
+ middleware(handler: (context: {
615
+ request: Request;
616
+ set: {
617
+ status?: number | string;
618
+ headers: Record<string, string>;
619
+ };
620
+ }) => unknown): void;
621
+ /** Event listeners to add to the app's `events`; `useDeps()` in their `run` returns the plugin's deps. */
622
+ listeners(...listeners: EventListener[]): void;
623
+ }
624
+ interface PluginManifest<O extends TSchema | undefined = undefined, S extends Secrets = {}, T extends Record<string, Table> = {}, E extends EventCatalog = {}, RA extends object = {}, SA = unknown, P extends Ports = {}> {
625
+ /** The npm package name, scoped: `@acme/brick-comments`. */
626
+ name: string;
627
+ description?: string;
628
+ /** The Brick versions it supports, as a semver range: `^0.11.0`. */
629
+ brick?: string;
630
+ /** Plugins that must be installed on the same host first, by name. */
631
+ requires?: readonly string[];
632
+ /** A TypeBox schema for the options; defaults fill what the user leaves out. */
633
+ options?: O;
634
+ /** Secrets it reads, from `defineSecret`. */
635
+ secrets?: S;
636
+ /**
637
+ * What it needs from the app, declared with `port<T>()`. The user passes the
638
+ * values when installing: `notify(options, { deps: { mailer } })`. Setup
639
+ * parts read them as `deps`, the plugin's actions as `ctx.deps`.
640
+ */
641
+ deps?: P;
642
+ /**
643
+ * Tables it owns. They are created in the host service's database for its
644
+ * engine, named `<host>_<table>` (or with the install's `prefix`), and join
645
+ * schema sync and migrations through `database.tables`.
646
+ */
647
+ tables?: (builders: PluginTableBuilders) => T;
648
+ /** Events it emits; they join the host catalog as `<plugin>.<event>`. */
649
+ events?: E;
650
+ /** Installed with `resource.use()`; returns what the resource gains. */
651
+ resource?: (context: PluginSetupContext<OptionsOf<O>, S, T, E, P> & {
652
+ resource: Resource<any, PluginContext<P>, any>;
653
+ }) => RA & (RA extends PromiseLike<unknown> ? never : unknown);
654
+ /** Installed with `service.use()`; returns what `use` hands back. */
655
+ service?: (context: PluginSetupContext<OptionsOf<O>, S, T, E, P>) => SA & (SA extends PromiseLike<unknown> ? never : unknown);
656
+ /**
657
+ * The app-wide part: lifecycle, middleware and listeners. Runs once per
658
+ * plugin instance when `brick()` creates the app, whether the plugin was
659
+ * installed with `brick({ plugins })`, `service.use()` or `resource.use()`.
660
+ */
661
+ app?: (context: PluginAppContext<OptionsOf<O>, S, P>) => void;
662
+ /**
663
+ * A dashboard extension module (`defineDashboard`), relative to the file
664
+ * that calls `definePlugin`. `brick dev` merges it with the app's own.
665
+ */
666
+ dashboard?: string;
667
+ }
668
+ /** Where the plugin is installed, besides its options. */
669
+ interface PluginInstallOptions {
670
+ /** Table name prefix instead of `<host>_`, such as `"blog_"`; `""` for none. */
671
+ prefix?: string;
672
+ }
673
+ /** What the plugin's capabilities are, read from its manifest. */
674
+ interface PluginInfo {
675
+ readonly name: string;
676
+ readonly description?: string;
677
+ readonly brick?: string;
678
+ readonly requires: readonly string[];
679
+ readonly options?: TSchema;
680
+ readonly secrets: readonly string[];
681
+ /** The names of the deps it declares, passed when installing. */
682
+ readonly deps: readonly string[];
683
+ readonly capabilities: readonly ("tables" | "events" | "resource" | "service" | "app" | "dashboard")[];
684
+ }
685
+ /** A plugin ready to install: `resource.use(p)`, `service.use(p)` or `brick({ plugins: [p] })`. */
686
+ type PluginInstance<RA extends object = {}, SA = unknown> = ResourcePlugin<any, any, RA> & ServicePlugin<any, SA> & {
687
+ readonly info: PluginInfo;
688
+ };
689
+ /** `definePlugin`'s result: call it with options to get an instance. */
690
+ type PluginFactory<O extends TSchema | undefined, RA extends object, SA, P extends Ports = {}> = ((...args: {} extends P ? [options?: Partial<OptionsOf<O>>, install?: PluginInstallOptions] : [options: Partial<OptionsOf<O>> | undefined, install: PluginInstallOptions & {
691
+ deps: DepsOf<P>;
692
+ }]) => PluginInstance<RA, SA>) & {
693
+ readonly info: PluginInfo;
694
+ };
695
+ /**
696
+ * Define a plugin: a manifest Brick checks, plus the capabilities the plugin
697
+ * brings. Install its instances with `resource.use()`, `service.use()` or
698
+ * `brick({ plugins })`; scope comes from where it is installed.
358
699
  *
359
- * @param value - Anything.
360
- * @returns `true` for a handle, narrowing its type.
700
+ * @param manifest - `name`, `brick` (semver range), `requires`, `options`
701
+ * (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`
702
+ * parts, and a `dashboard` extension.
703
+ * @returns A factory: `comments({ maxLength: 500 })` validates the options and
704
+ * the Brick version and returns an instance to install.
705
+ * @throws From the factory, when the running Brick is outside `brick` or an
706
+ * option is invalid; when installed, when a required plugin is missing or the
707
+ * host does not suit the plugin.
708
+ * @example
709
+ * export const audit = definePlugin({
710
+ * name: "@acme/brick-audit",
711
+ * brick: "^0.11.0",
712
+ * requires: ["@brickkit/crud"],
713
+ * options: t.Object({ table: t.String({ default: "audit" }) }),
714
+ * tables: ({ table, text, timestamp }) => ({
715
+ * log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
716
+ * }),
717
+ * resource: ({ tables, hooks }) => {
718
+ * hooks.afterCreate(({ row, tx }) =>
719
+ * tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
720
+ * return {};
721
+ * },
722
+ * });
723
+ *
724
+ * page.use(audit());
361
725
  */
362
- declare function isDatabaseHandle(value: unknown): value is DatabaseHandle<unknown>;
726
+ declare function definePlugin<O extends TSchema | undefined = undefined, S extends Secrets = {}, T extends Record<string, Table> = {}, const E extends EventCatalog = {}, RA extends object = {}, SA = unknown, P extends Ports = {}>(manifest: PluginManifest<O, S, T, E, RA, SA, P>): PluginFactory<O, RA, SA, P>;
727
+ /** A plugin as `app.definition.plugins` lists it. */
728
+ interface InstalledPlugin {
729
+ readonly name: string;
730
+ readonly brick?: string;
731
+ readonly scope: "app" | "service" | "resource";
732
+ readonly service?: string;
733
+ readonly resource?: string;
734
+ /** The plugin's dashboard extension, an absolute path. */
735
+ readonly dashboard?: string;
736
+ }
737
+ declare function isPluginInstance(value: unknown): value is PluginInstance;
738
+ //#endregion
739
+ //#region src/events/listener.d.ts
740
+ type EventOn = EventRef<any> | readonly EventRef<any>[];
741
+ type PayloadOf<O> = O extends EventRef<infer P> ? P : O extends readonly EventRef<infer P>[] ? P : never;
742
+ type ListenerConfig<TPayload, TOn = string | readonly string[], TErrors extends Record<string, ActionErrorDefinition> = {}> = {
743
+ name: string;
744
+ on: TOn;
745
+ maxAttempts?: number;
746
+ /** Errors `run` may raise with `error.CODE()`. Spread `defineError(...)` results or `errorsOf(action)` here. */
747
+ errors?: TErrors;
748
+ /** Decides what a failure does next. Without it every failure retries until `maxAttempts`. */
749
+ retry?: (error: ListenerFailure<TErrors>) => RetryDecision;
750
+ } & ({
751
+ run: (delivery: EventDelivery<TPayload>, helpers: {
752
+ error: ErrorBuilder<TErrors>;
753
+ }) => void | Promise<void>;
754
+ workflow?: never;
755
+ } | {
756
+ workflow: EventWorkflow<TPayload>;
757
+ run?: never;
758
+ });
363
759
  /**
364
- * Declare a service's database: its engine, its Drizzle tables, and how to
365
- * reach it. Nothing connects until the handle is used (`getDb()`), so defining
366
- * one has no side effects.
760
+ * Define a listener: code that runs for each event it listens for, after the write
761
+ * that caused the event has been committed. Pass it to `brick({ events: {
762
+ * listeners } })`.
367
763
  *
368
- * SQLite is the default and needs no options. Pass `engine: "postgres"` with a
369
- * `url` for Postgres. Options that belong to the other engine (such as `url` for
370
- * SQLite, or `path` for Postgres) are refused.
764
+ * It either runs a handler (`run`) in the process that delivers events, or starts
765
+ * a durable workflow (`workflow`) on the app's `events.world`. Delivery is at
766
+ * least once. A handler that throws is retried later with a growing delay, then
767
+ * parked as dead, so it can run again for the same event: use
768
+ * `delivery.deliveryId` to make its work idempotent. A workflow needs no such
769
+ * care: a delivery starts one run however often it is tried, and the workflow
770
+ * retries its own steps.
371
771
  *
372
- * @param options - `engine` (`"sqlite"` or `"postgres"`), `tables`, an optional
373
- * `name`, and the engine's connection settings.
374
- * @returns A handle to give to `defineService({ database })`. `getDb()` returns
375
- * the Drizzle database.
376
- * @throws When the engine is unsupported, or an option does not suit the engine.
772
+ * A listener can declare `errors`, as an action does, and raise them in `run` with
773
+ * `error.CODE()`. `retry(error)` then picks `"retry"` or `"dead"` from the typed
774
+ * `error.code`; anything not declared arrives as `{ code: "UNKNOWN", cause }`.
775
+ *
776
+ * @param config - `name` (unique; it is part of each delivery's id), `on` (a
777
+ * declared event such as `orders.events.shipped`, which types the payload, or an
778
+ * event name; or a list of either; a trailing `*` matches a prefix, as in
779
+ * `user.*`), `run` or `workflow`, and optionally `maxAttempts`.
780
+ * @returns The listener.
781
+ * @throws When the name is empty or contains `:`, `on` is empty, or the listener
782
+ * has both or neither of `run` and `workflow`.
377
783
  * @example
378
- * import { defineDatabase } from "@brickkit/core";
379
- * import { sqliteTable, text } from "drizzle-orm/sqlite-core";
784
+ * import { brick, defineListener } from "@brickkit/core";
380
785
  *
381
- * const pages = sqliteTable("pages", {
382
- * id: text("id").primaryKey(),
383
- * title: text("title").notNull(),
786
+ * const welcome = defineListener({
787
+ * name: "welcome-email",
788
+ * on: "user.create",
789
+ * run: async ({ payload, deliveryId }) => {
790
+ * await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });
791
+ * },
384
792
  * });
385
793
  *
386
- * export const database = defineDatabase({ tables: { pages } });
794
+ * export default brick({ services, events: { listeners: [welcome] } });
795
+ * @example
796
+ * // src/workflows/onboard.ts
797
+ * export async function onboard(event: WorkflowEvent<CrudEventPayload>) {
798
+ * "use workflow";
799
+ * await sendWelcome(event.payload.row.email);
800
+ * }
801
+ *
802
+ * defineListener({ name: "onboard", on: "user.create", workflow: onboard });
803
+ * @example
804
+ * // payload is { id: string; trackingId: string }, from the orders catalog.
805
+ * defineListener({
806
+ * name: "notify-shipped",
807
+ * on: orders.events.shipped,
808
+ * run: ({ payload }) => notify(payload.id, payload.trackingId),
809
+ * });
387
810
  */
388
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase$1<TSchema>, TSchema>;
389
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
390
- $client: Sql;
391
- }, TSchema>;
811
+ declare function defineListener<const TOn extends EventOn, const TErrors extends Record<string, ActionErrorDefinition> = {}>(config: ListenerConfig<PayloadOf<TOn>, TOn, TErrors>): EventListener<PayloadOf<TOn>>;
812
+ declare function defineListener<TPayload = any, const TErrors extends Record<string, ActionErrorDefinition> = {}>(config: ListenerConfig<TPayload, string | EventRef<any> | readonly (string | EventRef<any>)[], TErrors>): EventListener<TPayload>;
813
+ //#endregion
814
+ //#region src/events/emit.d.ts
815
+ /**
816
+ * Record an event of your own from an action, a tool or a hook. Listeners get it
817
+ * as they get a generated CRUD event, with the payload you give.
818
+ *
819
+ * By default the event is committed in a transaction of its own. Pass the `tx`
820
+ * of a transaction you have open to commit it with your writes instead: then it
821
+ * is delivered at the dispatcher's next poll, because Brick does not see your
822
+ * commit. Nothing is recorded when no listener wants the event.
823
+ *
824
+ * @param ctx - The action context: its `db` finds the service's outbox, and its
825
+ * `traceId` follows the event to its listeners.
826
+ * @param event - A declared event, such as `orders.events.shipped`, whose payload
827
+ * is typed and checked against its schema; or an event name such as
828
+ * `orders.refunded`. A service with an event catalog only records names from it
829
+ * (and the CRUD events of its resources).
830
+ * @param payload - JSON data for the listeners.
831
+ * @param options - `tx`: an open transaction on the service's database. `source`:
832
+ * what emitted it, shown to listeners.
833
+ * @throws When the context's database has no outbox table, or the app has no
834
+ * `events`; when the event is not in the service's catalog, or its payload does
835
+ * not match the declared schema.
836
+ * @example
837
+ * refund: service.action({
838
+ * name: "refund",
839
+ * execute: async ({ ctx, input }) => {
840
+ * await ctx.db.update(orders).set({ status: "refunded" }).where(eq(orders.id, input.id));
841
+ * await emitEvent(ctx, orders.events.refunded, { id: input.id });
842
+ * },
843
+ * });
844
+ */
845
+ declare function emitEvent<TPayload>(ctx: {
846
+ db?: unknown;
847
+ traceId?: string;
848
+ }, event: EventRef<TPayload>, payload: NoInfer<TPayload>, options?: {
849
+ tx?: unknown;
850
+ source?: string;
851
+ }): Promise<void>;
852
+ declare function emitEvent(ctx: {
853
+ db?: unknown;
854
+ traceId?: string;
855
+ }, name: string, payload: unknown, options?: {
856
+ tx?: unknown;
857
+ source?: string;
858
+ }): Promise<void>;
392
859
  //#endregion
393
860
  //#region src/events/outbox.d.ts
394
861
  /** What the outbox rows are in, by state. */
@@ -979,364 +1446,711 @@ declare function outboxTable(engine: "postgres", options?: {
979
1446
  */
980
1447
  declare function isOutboxTable(value: unknown): value is OutboxTable;
981
1448
  //#endregion
982
- //#region src/events/types.d.ts
983
- /**
984
- * An event, as it was recorded. It is the same for every listener of it.
985
- */
986
- interface EventEnvelope<TPayload = unknown> {
987
- /** Unique per event. Every listener's delivery of the event shares it. */
988
- id: string;
989
- /** The event name, such as `user.create`. */
990
- name: string;
991
- /** What happened. JSON data. */
992
- payload: TPayload;
993
- /** When it happened, as an ISO timestamp. */
994
- occurredAt: string;
995
- /** The trace of the request that caused it, so a listener continues the same trace. */
996
- traceId?: string;
997
- /** What emitted it, such as `identity.user` for a generated CRUD write. */
998
- source?: string;
999
- }
1449
+ //#region src/events/dispatcher.d.ts
1450
+ /** How many outbox rows are in each state. */
1451
+ type OutboxCounts = Record<OutboxStatus, number>;
1000
1452
  /**
1001
- * One listener's delivery of an event: the envelope, plus which listener it is for
1002
- * and which attempt this is.
1453
+ * Delivers the events recorded in one outbox table to the app's listeners.
1454
+ *
1455
+ * It claims a batch of due rows, runs each listener, and marks the row delivered.
1456
+ * A listener that throws is retried later with a growing delay, and parked as
1457
+ * dead after its attempts run out. Several dispatchers can share a table: on
1458
+ * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
1459
+ * finished within `claimTimeoutMs` (the process died) is taken by another.
1460
+ * Delivery is at least once, so a listener should tolerate running twice for the
1461
+ * same `deliveryId`.
1003
1462
  */
1004
- interface EventDelivery<TPayload = unknown> extends EventEnvelope<TPayload> {
1005
- /** The name of the listener this delivery is for. */
1006
- listener: string;
1463
+ declare class Dispatcher {
1464
+ private readonly db;
1465
+ private readonly table;
1466
+ private readonly listeners;
1467
+ private readonly onError;
1468
+ private readonly engine;
1469
+ private readonly options;
1470
+ private readonly inFlight;
1471
+ private timer?;
1472
+ private tickQueue?;
1473
+ private lastPurge;
1474
+ constructor(db: any, table: OutboxTable, listeners: (name: string) => Deliverable | undefined, options?: DispatchOptions, onError?: (error: unknown) => void);
1475
+ /** Whether the dispatcher is looking for work on a timer. */
1476
+ get running(): boolean;
1477
+ /** Start looking for due deliveries on a timer. Does nothing if it already is. */
1478
+ start(): void;
1007
1479
  /**
1008
- * `<event id>:<listener>`. It is the same on every retry, so a listener can use
1009
- * it to avoid doing the work twice: delivery is at least once.
1480
+ * Stop the timer and wait for the deliveries that are running to finish.
1010
1481
  */
1011
- deliveryId: string;
1012
- /** 1 on the first try, 2 on the first retry, and so on. */
1013
- attempt: number;
1014
- }
1015
- /**
1016
- * The CRUD events of a resource called `user`, by operation. Listeners of
1017
- * `user.create`, `user.update` and `user.delete` receive these payloads.
1018
- */
1019
- type CrudEventPayload<TRow = Record<string, unknown>> = {
1020
- id: unknown;
1021
- row: TRow;
1022
- } | {
1023
- id: unknown;
1024
- before: TRow;
1025
- after: TRow;
1026
- };
1027
- /**
1028
- * A listener: code that runs when an event it listens for has been recorded.
1029
- */
1030
- interface EventListener<TPayload = any> {
1031
- /** Unique among the app's listeners. It is part of each delivery's id. */
1032
- readonly name: string;
1482
+ stop(): Promise<void>;
1483
+ /** Look for work soon, without waiting for the timer. Safe to call often. */
1484
+ notify(): void;
1033
1485
  /**
1034
- * The event names to listen for. A trailing `*` matches a prefix (`user.*`),
1035
- * and `*` alone matches every event.
1486
+ * Claim what is due and run it, once. Used by the timer, and by tests and
1487
+ * workers that drive delivery themselves.
1488
+ *
1489
+ * @returns How many deliveries it started.
1036
1490
  */
1037
- readonly on: readonly string[];
1491
+ tick(): Promise<number>;
1038
1492
  /**
1039
- * A handler that runs in the dispatching process for each delivery. Throwing
1040
- * retries the delivery with a growing delay. A listener has this or `workflow`.
1493
+ * Deliver everything that is due now and wait until those deliveries are done.
1494
+ * Deliveries that fail and are rescheduled are not waited for again.
1495
+ *
1496
+ * @returns How many deliveries it ran.
1041
1497
  */
1042
- readonly run?: (delivery: EventDelivery<TPayload>) => void | Promise<void>;
1498
+ drain(): Promise<number>;
1043
1499
  /**
1044
- * A durable workflow that runs for each delivery, on the app's `events.world`.
1045
- * The delivery counts as done once its run has started; the workflow retries
1046
- * its own steps from there. A listener has this or `run`.
1500
+ * How many rows are in each state.
1047
1501
  */
1048
- readonly workflow?: EventWorkflow<TPayload>;
1049
- /** Attempts before the delivery is parked as dead. Defaults to the dispatcher's. */
1050
- readonly maxAttempts?: number;
1502
+ counts(): Promise<OutboxCounts>;
1503
+ /**
1504
+ * Put parked deliveries back in line, with their attempts reset.
1505
+ *
1506
+ * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
1507
+ * @returns How many deliveries were put back.
1508
+ */
1509
+ retryDead(deliveryId?: string): Promise<number>;
1510
+ private claimAndRun;
1511
+ private claim;
1512
+ private deliver;
1513
+ private markDelivered;
1514
+ private fail;
1515
+ private park;
1516
+ private purgeDelivered;
1517
+ }
1518
+ //#endregion
1519
+ //#region src/events/hub.d.ts
1520
+ interface EventsHost {
1521
+ readonly name: string;
1522
+ getDb(): unknown;
1523
+ getOutbox?(): OutboxTable | undefined;
1524
+ setRecorder?(recorder: ServiceEvents | undefined): void;
1525
+ /** Throws for an event the service's catalog does not allow. */
1526
+ checkEvent?(name: string, payload: unknown): void;
1051
1527
  }
1052
1528
  /**
1053
- * What a workflow listener's workflow receives: the event and which listener it
1054
- * is for. It has no `attempt`, because one delivery starts one run however many
1055
- * times it is tried.
1056
- */
1057
- type WorkflowEvent<TPayload = any> = Omit<EventDelivery<TPayload>, "attempt">;
1058
- /**
1059
- * A function marked `"use workflow"`, run once per delivery of the listener it is
1060
- * given to.
1529
+ * Stop every events hub started in this process, by any copy of `@brickkit/core`,
1530
+ * and wait for their deliveries. A hub that fails to stop does not cut the wait
1531
+ * for the others: the first failure is thrown once every hub is done.
1061
1532
  */
1062
- type EventWorkflow<TPayload = any> = (event: WorkflowEvent<TPayload>) => Promise<unknown>;
1533
+ declare function stopAllEvents(): Promise<void>;
1063
1534
  /**
1064
- * The world workflow listeners run on: the queue and storage behind the Workflow
1065
- * SDK. `createWorld()` from `@brickkit/redis-world` or `@brickkit/bullmq-world`
1066
- * makes one. Brick starts it with the app's events and closes it when they stop.
1535
+ * What an app's `events` option describes, as plain data. It goes in the app
1536
+ * definition, which is sent to the dev dashboard, so it holds no functions.
1067
1537
  */
1068
- interface EventsWorld {
1069
- /**
1070
- * Names a run after its key so that starting it twice makes one run. A world
1071
- * without it would start a second run when an event is delivered again, so
1072
- * Brick refuses such a world.
1073
- */
1074
- createRunId?(options?: Readonly<Record<string, unknown>>): string;
1075
- start?(): Promise<void>;
1076
- close?(): Promise<void>;
1077
- registerHandler?(prefix: any, handler: (request: Request) => Promise<Response>): void;
1538
+ interface EventsDefinition {
1539
+ listeners: {
1540
+ name: string;
1541
+ on: string[];
1542
+ kind: "handler" | "workflow";
1543
+ }[];
1544
+ dispatch: boolean;
1545
+ /** Names of the services whose writes record events. */
1546
+ recorders: string[];
1078
1547
  }
1079
- /**
1080
- * Where the workflows of an app are built from. The CLI (`brick dev`,
1081
- * `brick start`) writes the bundle to `<root>/.well-known/workflow/v1` before
1082
- * events start, and events read it from there.
1083
- */
1084
- interface WorkflowsOptions {
1085
- /** The project root: where the Workflow SDK is installed. Default: the working directory. */
1086
- root?: string;
1548
+ /** What the dispatcher runs for a delivery. */
1549
+ interface Deliverable {
1550
+ readonly maxAttempts?: number;
1551
+ readonly errors?: EventListener["errors"];
1552
+ readonly retry?: EventListener["retry"];
1553
+ run(delivery: EventDelivery): void | Promise<void>;
1087
1554
  }
1088
1555
  /**
1089
- * How the dispatcher delivers recorded events.
1556
+ * The events of one app: who listens, where events are recorded, and the
1557
+ * dispatchers that deliver them. `brick({ events })` makes one and puts it on
1558
+ * `app.events`.
1090
1559
  */
1091
- interface DispatchOptions {
1560
+ declare class EventsHub {
1561
+ private readonly deps;
1562
+ private readonly byName;
1563
+ private readonly dispatchers;
1564
+ private readonly deliverables;
1565
+ private readonly dispatchOptions;
1566
+ private readonly runtime;
1567
+ private readonly recorderNames;
1568
+ private started;
1569
+ private stopping;
1092
1570
  /**
1093
- * Whether to look for due deliveries on a timer, and right after a commit.
1094
- * Default `true`. With `false`, deliveries run only when something calls
1095
- * `app.events.drain()`: a cron job, a worker you drive yourself, or a test.
1571
+ * @param options - The `events` option.
1572
+ * @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
1573
+ * listeners and workflow steps.
1096
1574
  */
1097
- timer?: boolean;
1098
- /** How often to look for deliveries that are due, in milliseconds. Default 1000. */
1099
- intervalMs?: number;
1100
- /** Most deliveries claimed at once. Default 50. */
1101
- batchSize?: number;
1102
- /** Attempts before a delivery is parked as dead. Default 8. */
1103
- maxAttempts?: number;
1104
- /** How long a claimed delivery may run before another dispatcher takes it, in milliseconds. Default 60000. */
1105
- claimTimeoutMs?: number;
1106
- /** Longest wait before a retry, in milliseconds. Default 300000. */
1107
- maxBackoffMs?: number;
1108
- /** How long delivered rows are kept, in milliseconds. Default 86400000 (one day). 0 keeps none. */
1109
- retainDeliveredMs?: number;
1110
- }
1111
- /**
1112
- * The `events` option of `brick()`.
1113
- */
1114
- interface EventsOptions {
1115
- /** The listeners of the app. */
1116
- listeners?: readonly EventListener[];
1575
+ constructor(options: EventsOptions, deps?: Record<string, unknown>);
1117
1576
  /**
1118
- * Whether this process delivers recorded events. `true` (the default) starts a
1119
- * dispatcher with the default settings, an object tunes it, and `false` only
1120
- * records events, for an app whose events are delivered by another process.
1577
+ * Give each service whose database holds an outbox table a recorder, and a
1578
+ * dispatcher for that table. Call it before the first request: a service has no
1579
+ * recorder until then.
1580
+ *
1581
+ * @param services - The app's services.
1582
+ * @returns The hub, for chaining.
1121
1583
  */
1122
- dispatch?: boolean | DispatchOptions;
1584
+ attach(services: readonly EventsHost[]): this;
1585
+ /** The listeners that want an event. */
1586
+ matching(name: string): EventListener[];
1587
+ /** The listeners and settings, as plain data. */
1588
+ describe(): EventsDefinition;
1123
1589
  /**
1124
- * The world that runs `workflow` listeners. Required when any listener has one.
1125
- * Brick starts it when the app's events start and closes it when they stop.
1590
+ * Where the workflow bundle is read from, the project it is built from, and
1591
+ * the world the workflows run on. Only set when a listener runs a workflow.
1592
+ * The CLI builds the bundle there before events start, and shows the world's
1593
+ * runs in the dev dashboard.
1126
1594
  */
1127
- world?: EventsWorld;
1128
- /** Where the workflow bundle lives. Only used with workflow listeners. */
1129
- workflows?: WorkflowsOptions;
1130
- }
1131
- /**
1132
- * Records an event inside the transaction it was given. The event is committed
1133
- * with the write, or not at all.
1134
- */
1135
- type EventRecorder = (name: string, payload: unknown) => Promise<void>;
1136
- /**
1137
- * What a service with events offers the code that writes to its database. A
1138
- * service has it once `brick({ events })` is set up and its database holds an
1139
- * outbox table.
1140
- */
1141
- interface ServiceEvents {
1142
- /** Whether any listener wants the event, so a write can skip recording one. */
1143
- wants(name: string): boolean;
1595
+ get workflows(): {
1596
+ root: string;
1597
+ dir: string;
1598
+ world: EventsWorld;
1599
+ } | undefined;
1144
1600
  /**
1145
- * Run `fn` in a database transaction. Events it records are committed with
1146
- * whatever else it wrote, or not at all, and are delivered after the commit.
1601
+ * Resume the workflow that waits on a webhook. The server mounts this on the
1602
+ * route the Workflow SDK puts in webhook URLs.
1147
1603
  */
1148
- transaction<T>(db: unknown, context: {
1149
- traceId?: string;
1150
- source?: string;
1151
- }, fn: (tx: any, record: EventRecorder) => Promise<T>): Promise<T>;
1604
+ webhook(request: Request): Promise<Response>;
1152
1605
  /**
1153
- * Record an event in a transaction the caller already has open. It is
1154
- * committed with that transaction. Nothing tells Brick when the caller commits,
1155
- * so delivery waits for the dispatcher's next poll.
1606
+ * Start delivering recorded events from this process, and start the world that
1607
+ * runs workflow listeners. Does nothing if this process only records events
1608
+ * (`dispatch: false`), already started, or a stop is still waiting.
1156
1609
  */
1157
- record(tx: unknown, context: {
1158
- traceId?: string;
1159
- source?: string;
1160
- }, name: string, payload: unknown): Promise<void>;
1161
- }
1162
- //#endregion
1163
- //#region src/events/dispatcher.d.ts
1164
- /** How many outbox rows are in each state. */
1165
- type OutboxCounts = Record<OutboxStatus, number>;
1166
- /**
1167
- * Delivers the events recorded in one outbox table to the app's listeners.
1168
- *
1169
- * It claims a batch of due rows, runs each listener, and marks the row delivered.
1170
- * A listener that throws is retried later with a growing delay, and parked as
1171
- * dead after its attempts run out. Several dispatchers can share a table: on
1172
- * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
1173
- * finished within `claimTimeoutMs` (the process died) is taken by another.
1174
- * Delivery is at least once, so a listener should tolerate running twice for the
1175
- * same `deliveryId`.
1176
- */
1177
- declare class Dispatcher {
1178
- private readonly db;
1179
- private readonly table;
1180
- private readonly listeners;
1181
- private readonly onError;
1182
- private readonly engine;
1183
- private readonly options;
1184
- private readonly inFlight;
1185
- private timer?;
1186
- private tickQueue?;
1187
- private lastPurge;
1188
- constructor(db: any, table: OutboxTable, listeners: (name: string) => Deliverable | undefined, options?: DispatchOptions, onError?: (error: unknown) => void);
1189
- /** Whether the dispatcher is looking for work on a timer. */
1190
- get running(): boolean;
1191
- /** Start looking for due deliveries on a timer. Does nothing if it already is. */
1192
1610
  start(): void;
1193
1611
  /**
1194
- * Stop the timer and wait for the deliveries that are running to finish.
1612
+ * Stop delivering, wait for the deliveries that are running, and close the
1613
+ * world. A world cannot be started again, so workflow listeners stop for good.
1614
+ * A stop that arrives while another runs waits for that one.
1195
1615
  */
1196
1616
  stop(): Promise<void>;
1197
- /** Look for work soon, without waiting for the timer. Safe to call often. */
1198
- notify(): void;
1617
+ private shutDown;
1199
1618
  /**
1200
- * Claim what is due and run it, once. Used by the timer, and by tests and
1619
+ * Deliver everything that is due now and wait for it. For tests and for
1201
1620
  * workers that drive delivery themselves.
1202
1621
  *
1203
- * @returns How many deliveries it started.
1204
- */
1205
- tick(): Promise<number>;
1206
- /**
1207
- * Deliver everything that is due now and wait until those deliveries are done.
1208
- * Deliveries that fail and are rescheduled are not waited for again.
1209
- *
1210
- * @returns How many deliveries it ran.
1622
+ * @returns How many deliveries ran.
1211
1623
  */
1212
1624
  drain(): Promise<number>;
1213
- /**
1214
- * How many rows are in each state.
1215
- */
1625
+ /** How many rows are in each state, across the app's outbox tables. */
1216
1626
  counts(): Promise<OutboxCounts>;
1217
1627
  /**
1218
- * Put parked deliveries back in line, with their attempts reset.
1628
+ * Put parked deliveries back in line.
1219
1629
  *
1220
- * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
1630
+ * @param deliveryId - One delivery. Omit it to retry every dead one.
1221
1631
  * @returns How many deliveries were put back.
1222
1632
  */
1223
1633
  retryDead(deliveryId?: string): Promise<number>;
1224
- private claimAndRun;
1225
- private claim;
1226
- private deliver;
1227
- private markDelivered;
1228
- private fail;
1229
- private park;
1230
- private purgeDelivered;
1634
+ private deliverable;
1635
+ private bind;
1636
+ }
1637
+ //#endregion
1638
+ //#region src/events/workflows.d.ts
1639
+ /**
1640
+ * Where the workflow bundle is read from, and the project it is built from.
1641
+ *
1642
+ * @param options - The `events.workflows` option.
1643
+ * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the
1644
+ * builder finds the SDK from where it writes, and skips only this directory when it
1645
+ * looks for workflows.
1646
+ */
1647
+ declare function resolveWorkflowPaths(options?: WorkflowsOptions): {
1648
+ root: string;
1649
+ dir: string;
1650
+ };
1651
+ //#endregion
1652
+ //#region src/plugin.d.ts
1653
+ type PluginRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1654
+ type PluginRouteScope = "app" | "service" | "resource";
1655
+ type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> = false | Readonly<Record<string, false | {
1656
+ path?: string;
1657
+ scope?: S;
1658
+ }>>;
1659
+ type ContextOf<S> = S extends Service<infer D, infer C> ? BaseContext<D> & C : never;
1660
+ interface PluginEndpointContext<C extends ActionContext = ActionContext> {
1661
+ params: Record<string, string>;
1662
+ query: Record<string, string | undefined>;
1663
+ body: unknown;
1664
+ headers: Record<string, string>;
1665
+ request: Request;
1666
+ set: {
1667
+ status?: number;
1668
+ headers: Record<string, string>;
1669
+ };
1670
+ ctx: C;
1671
+ }
1672
+ interface PluginRouteRegistrar<C extends ActionContext = ActionContext, S extends PluginRouteScope = PluginRouteScope> {
1673
+ action<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<I, O, E, C> & {
1674
+ path: string;
1675
+ method: PluginRouteMethod;
1676
+ scope?: S;
1677
+ }): Action<I, O, E, C>;
1678
+ action<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<I, O, E, C> & {
1679
+ path: string;
1680
+ method: PluginRouteMethod;
1681
+ scope?: S;
1682
+ }): Action<I, O, E, C>;
1683
+ endpoint(config: {
1684
+ name: string;
1685
+ path: string;
1686
+ method: PluginRouteMethod;
1687
+ scope?: S;
1688
+ handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;
1689
+ summary?: string;
1690
+ description?: string;
1691
+ tags?: string[];
1692
+ }): void;
1693
+ }
1694
+ interface ServicePluginContext<S extends Service<any, any> = Service<any, any>> {
1695
+ service: S;
1696
+ routes: PluginRouteRegistrar<ContextOf<S>, "app" | "service">;
1697
+ }
1698
+ interface ResourcePluginContext<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>> {
1699
+ service: S;
1700
+ resource: R;
1701
+ routes: PluginRouteRegistrar<ContextOf<S>>;
1702
+ }
1703
+ /** Plugins may specialize their returned API for the installation host. */
1704
+ interface ResourcePluginTypes {
1705
+ readonly table: unknown;
1706
+ readonly context: unknown;
1707
+ readonly resource: unknown;
1708
+ readonly api: object;
1709
+ }
1710
+ type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
1711
+ readonly types: infer H extends ResourcePluginTypes;
1712
+ } ? (H & {
1713
+ readonly table: T;
1714
+ readonly context: C;
1715
+ readonly resource: R;
1716
+ })["api"] : P extends PluginInstance<infer A extends object, any> ? A : P extends ResourcePlugin<any, any, infer A> ? A : never;
1717
+ declare const pluginKind: unique symbol;
1718
+ interface ServicePlugin<S extends Service<any, any>, A> {
1719
+ readonly [pluginKind]: "service" | "plugin";
1720
+ readonly name: string;
1721
+ readonly routes?: PluginRoutes<"app" | "service">;
1722
+ readonly setup: (context: ServicePluginContext<S>) => A;
1723
+ }
1724
+ interface ResourcePlugin<S extends Service<any, any>, R extends Resource<any, any, any>, A extends object> {
1725
+ readonly [pluginKind]: "resource" | "plugin";
1726
+ readonly name: string;
1727
+ readonly routes?: PluginRoutes;
1728
+ readonly setup: (context: ResourcePluginContext<S, R>) => A;
1729
+ }
1730
+ /**
1731
+ * Define a plugin that installs onto a service with `service.use(plugin)`. Its
1732
+ * `setup` receives the service and a `routes` registrar for adding actions and
1733
+ * raw HTTP endpoints, and returns the typed API that `service.use` hands back.
1734
+ *
1735
+ * @param definition - A unique `name`, optional `routes` controls that let the
1736
+ * user move or switch off the plugin's routes, and `setup`, which must be
1737
+ * synchronous.
1738
+ * @returns The plugin descriptor, frozen.
1739
+ * @throws When the name is empty or has surrounding whitespace.
1740
+ * @example
1741
+ * import { defineServicePlugin, t } from "@brickkit/core";
1742
+ *
1743
+ * export const greeting = (salutation = "Hello") =>
1744
+ * defineServicePlugin({
1745
+ * name: "example/greeting",
1746
+ * setup({ routes }) {
1747
+ * const hello = routes.action({
1748
+ * name: "hello",
1749
+ * input: t.Object({ name: t.String() }),
1750
+ * output: t.String(),
1751
+ * execute: ({ input }) => `${salutation}, ${input.name}!`,
1752
+ * });
1753
+ * return { hello };
1754
+ * },
1755
+ * });
1756
+ *
1757
+ * const api = greeterService.use(greeting("Welcome"));
1758
+ * await api.hello({ input: { name: "Ada" } });
1759
+ */
1760
+ declare function defineServicePlugin<S extends Service<any, any> = Service<any, any>, A = unknown>(definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & {
1761
+ setup: (context: ServicePluginContext<S>) => A & (A extends PromiseLike<unknown> ? never : unknown);
1762
+ }): ServicePlugin<S, A>;
1763
+ /**
1764
+ * Define a plugin that installs onto a resource (a table and its entity) with
1765
+ * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
1766
+ * `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and
1767
+ * returns the typed API that `resource.use` hands back. `crud` is built this way.
1768
+ *
1769
+ * @param definition - A unique `name`, optional `routes` controls, and `setup`,
1770
+ * which must be synchronous.
1771
+ * @returns The plugin descriptor, frozen.
1772
+ * @throws When the name is empty or has surrounding whitespace.
1773
+ */
1774
+ declare function defineResourcePlugin<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>, A extends object = object>(definition: Omit<ResourcePlugin<S, R, A>, typeof pluginKind> & {
1775
+ setup: (context: ResourcePluginContext<S, R>) => A & (A extends PromiseLike<unknown> ? never : unknown);
1776
+ }): ResourcePlugin<S, R, A>;
1777
+ /**
1778
+ * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
1779
+ * compiler, and the typed client.
1780
+ *
1781
+ * @param action - An action.
1782
+ * @param prefix - The application's route prefix (default `/api`).
1783
+ * @returns `undefined` when no plugin bound the action (it uses its own route),
1784
+ * `false` when the plugin's route was switched off, otherwise the route's
1785
+ * `path`, the v0.10 `legacyPath`, `method`, the `clientPath` the typed client uses, and the owning
1786
+ * `plugin` and `resource`.
1787
+ */
1788
+ declare function getPluginActionRoute(action: Action<any, any, any, any>, prefix?: string): false | {
1789
+ path: string;
1790
+ legacyPath: string;
1791
+ method: PluginRouteMethod;
1792
+ clientPath: string[] | undefined;
1793
+ plugin: string;
1794
+ resource: string | undefined;
1795
+ } | undefined;
1796
+ /**
1797
+ * The raw HTTP endpoints plugins registered on a service, ready to mount on the
1798
+ * application. Each handler resolves the service's context before it runs.
1799
+ *
1800
+ * @param service - The service plugins were installed on.
1801
+ * @param prefix - The application's route prefix (default `/api`).
1802
+ * @returns The enabled endpoints: `path`, `method`, `handler`, and the
1803
+ * `summary`, `description`, and `tags` for OpenAPI.
1804
+ */
1805
+ declare function getPluginEndpoints(service: Service<any, any>, prefix?: string): {
1806
+ path: string;
1807
+ legacyPath: string;
1808
+ method: PluginRouteMethod;
1809
+ service: Service<any, any, EventCatalog>;
1810
+ plugin: string;
1811
+ summary: string | undefined;
1812
+ description: string | undefined;
1813
+ tags: string[] | undefined;
1814
+ handler: (context: Omit<PluginEndpointContext, "ctx">) => Promise<unknown>;
1815
+ }[];
1816
+ //#endregion
1817
+ //#region src/db/sqlite.d.ts
1818
+ interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
1819
+ /** Database file path or ':memory:' (default: ':memory:') */
1820
+ path?: string;
1821
+ /** Alias for path */
1822
+ filename?: string;
1823
+ /** Whether to enable WAL journal mode for file-based DBs (default: true) */
1824
+ wal?: boolean;
1825
+ /** Whether to enforce foreign key constraints (default: true) */
1826
+ foreignKeys?: boolean;
1827
+ /** Optional existing bun:sqlite Database instance */
1828
+ client?: Database;
1829
+ /** Optional Drizzle schema object for typed relational queries */
1830
+ schema?: TSchema;
1831
+ }
1832
+ type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<TSchema> & {
1833
+ $client: Database;
1834
+ };
1835
+ /**
1836
+ * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
1837
+ * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
1838
+ *
1839
+ * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
1840
+ * other runtimes (e.g. Node) stays safe until this function is actually
1841
+ * called.
1842
+ */
1843
+ declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase<TSchema>;
1844
+ //#endregion
1845
+ //#region src/db/postgres.d.ts
1846
+ interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
1847
+ /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */
1848
+ client?: Sql;
1849
+ /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */
1850
+ url?: string;
1851
+ /** Connection string alias */
1852
+ connectionString?: string;
1853
+ host?: string;
1854
+ port?: number;
1855
+ user?: string;
1856
+ password?: string;
1857
+ database?: string;
1858
+ ssl?: boolean | "require" | "allow" | "prefer" | "verify-full";
1859
+ max?: number;
1860
+ /**
1861
+ * Disable prepared statements (required for transaction-mode poolers such
1862
+ * as Supabase's Supavisor on :6543, which cannot hold named prepared
1863
+ * statements across transactions).
1864
+ */
1865
+ prepare?: boolean;
1866
+ /** Optional Drizzle schema for relational queries */
1867
+ schema?: TSchema;
1868
+ /** Custom schema name for Encore-style isolated schemas */
1869
+ schemaName?: string;
1231
1870
  }
1232
- //#endregion
1233
- //#region src/events/hub.d.ts
1234
- interface EventsHost {
1235
- readonly name: string;
1236
- getDb(): unknown;
1237
- getOutbox?(): OutboxTable | undefined;
1238
- setEvents?(events: ServiceEvents | undefined): void;
1871
+ type PostgresDatabase<_TSchema extends Record<string, unknown> = Record<string, unknown>> = any;
1872
+ interface DatabaseAdapter<TDb = any, TConfig = any> {
1873
+ createDatabase(config?: TConfig): TDb;
1239
1874
  }
1240
1875
  /**
1241
- * Stop every events hub started in this process, by any copy of `@brickkit/core`,
1242
- * and wait for their deliveries. A hub that fails to stop does not cut the wait
1243
- * for the others: the first failure is thrown once every hub is done.
1244
- */
1245
- declare function stopAllEvents(): Promise<void>;
1246
- /**
1247
- * What an app's `events` option describes, as plain data. It goes in the app
1248
- * definition, which is sent to the dev dashboard, so it holds no functions.
1876
+ * Creates a PostgreSQL Drizzle instance using postgres-js.
1877
+ * Static imports (both are hard dependencies in package.json) so bundlers
1878
+ * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
1879
+ * `sqlite.ts` since it only exists under Bun.
1249
1880
  */
1250
- interface EventsDefinition {
1251
- listeners: {
1252
- name: string;
1253
- on: string[];
1254
- kind: "handler" | "workflow";
1255
- }[];
1256
- dispatch: boolean;
1257
- /** Names of the services whose writes record events. */
1258
- recorders: string[];
1881
+ declare function createPostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: PostgresDatabaseConfig<TSchema>): PostgresDatabase<TSchema>;
1882
+ //#endregion
1883
+ //#region src/db/define.d.ts
1884
+ type EnvInput<T> = T | SecretRef<T>;
1885
+ type EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>>; };
1886
+ interface DefinitionOptions<TSchema extends Record<string, unknown>> {
1887
+ name?: string;
1888
+ /** Drizzle tables retained for schema tooling. Never applied at runtime. */
1889
+ tables?: (TSchema & Record<string, Table>) | readonly Table[];
1890
+ schema?: TSchema;
1259
1891
  }
1260
- /** What the dispatcher runs for a delivery. */
1261
- interface Deliverable {
1262
- readonly maxAttempts?: number;
1263
- run(delivery: EventDelivery): void | Promise<void>;
1892
+ type SQLiteDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
1893
+ engine?: "sqlite";
1894
+ client?: SQLiteDatabaseConfig<TSchema>["client"];
1895
+ url?: never;
1896
+ connectionString?: never;
1897
+ };
1898
+ type PostgresDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema" | "client">> & {
1899
+ engine: "postgres";
1900
+ path?: never;
1901
+ filename?: never;
1902
+ wal?: never;
1903
+ foreignKeys?: never;
1904
+ client?: PostgresDatabaseConfig<TSchema>["client"];
1905
+ };
1906
+ type DatabaseDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;
1907
+ interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>> {
1908
+ readonly kind: "brick-database";
1909
+ readonly name?: string;
1910
+ readonly engine: "sqlite" | "postgres";
1911
+ readonly tables: Readonly<Record<string, Table>>;
1912
+ readonly schema: TSchema;
1913
+ /**
1914
+ * Add a table after definition, as `definePlugin` does for the tables a
1915
+ * plugin owns. Before `getDb()` it also joins the relational schema.
1916
+ */
1917
+ addTable?(key: string, table: Table): void;
1918
+ getDb(): TDb;
1919
+ close?(): void | Promise<void>;
1264
1920
  }
1265
1921
  /**
1266
- * The events of one app: who listens, where events are recorded, and the
1267
- * dispatchers that deliver them. `brick({ events })` makes one and puts it on
1268
- * `app.events`.
1922
+ * Whether a value is a database handle made by `defineDatabase`.
1923
+ *
1924
+ * @param value - Anything.
1925
+ * @returns `true` for a handle, narrowing its type.
1269
1926
  */
1270
- declare class EventsHub {
1271
- private readonly byName;
1272
- private readonly dispatchers;
1273
- private readonly deliverables;
1274
- private readonly dispatchOptions;
1275
- private readonly runtime;
1276
- private readonly recorderNames;
1277
- private started;
1278
- private stopping;
1279
- constructor(options: EventsOptions);
1280
- /**
1281
- * Give each service whose database holds an outbox table a recorder, and a
1282
- * dispatcher for that table. Call it before the first request: a service has no
1283
- * recorder until then.
1284
- *
1285
- * @param services - The app's services.
1286
- * @returns The hub, for chaining.
1287
- */
1288
- attach(services: readonly EventsHost[]): this;
1289
- /** The listeners that want an event. */
1290
- matching(name: string): EventListener[];
1291
- /** The listeners and settings, as plain data. */
1292
- describe(): EventsDefinition;
1293
- /**
1294
- * Where the workflow bundle is read from, the project it is built from, and
1295
- * the world the workflows run on. Only set when a listener runs a workflow.
1296
- * The CLI builds the bundle there before events start, and shows the world's
1297
- * runs in the dev dashboard.
1298
- */
1299
- get workflows(): {
1300
- root: string;
1301
- dir: string;
1302
- world: EventsWorld;
1303
- } | undefined;
1304
- /**
1305
- * Resume the workflow that waits on a webhook. The server mounts this on the
1306
- * route the Workflow SDK puts in webhook URLs.
1307
- */
1308
- webhook(request: Request): Promise<Response>;
1309
- /**
1310
- * Start delivering recorded events from this process, and start the world that
1311
- * runs workflow listeners. Does nothing if this process only records events
1312
- * (`dispatch: false`), already started, or a stop is still waiting.
1313
- */
1314
- start(): void;
1315
- /**
1316
- * Stop delivering, wait for the deliveries that are running, and close the
1317
- * world. A world cannot be started again, so workflow listeners stop for good.
1318
- * A stop that arrives while another runs waits for that one.
1319
- */
1320
- stop(): Promise<void>;
1321
- private shutDown;
1322
- /**
1323
- * Deliver everything that is due now and wait for it. For tests and for
1324
- * workers that drive delivery themselves.
1325
- *
1326
- * @returns How many deliveries ran.
1327
- */
1328
- drain(): Promise<number>;
1329
- /** How many rows are in each state, across the app's outbox tables. */
1330
- counts(): Promise<OutboxCounts>;
1927
+ declare function isDatabaseHandle(value: unknown): value is DatabaseHandle<unknown>;
1928
+ /**
1929
+ * Declare a service's database: its engine, its Drizzle tables, and how to
1930
+ * reach it. Nothing connects until the handle is used (`getDb()`), so defining
1931
+ * one has no side effects.
1932
+ *
1933
+ * SQLite is the default and needs no options. Pass `engine: "postgres"` with a
1934
+ * `url` for Postgres. Options that belong to the other engine (such as `url` for
1935
+ * SQLite, or `path` for Postgres) are refused.
1936
+ *
1937
+ * @param options - `engine` (`"sqlite"` or `"postgres"`), `tables`, an optional
1938
+ * `name`, and the engine's connection settings.
1939
+ * @returns A handle to give to `defineService({ database })`. `getDb()` returns
1940
+ * the Drizzle database.
1941
+ * @throws When the engine is unsupported, or an option does not suit the engine.
1942
+ * @example
1943
+ * import { defineDatabase } from "@brickkit/core";
1944
+ * import { sqliteTable, text } from "drizzle-orm/sqlite-core";
1945
+ *
1946
+ * const pages = sqliteTable("pages", {
1947
+ * id: text("id").primaryKey(),
1948
+ * title: text("title").notNull(),
1949
+ * });
1950
+ *
1951
+ * export const database = defineDatabase({ tables: { pages } });
1952
+ */
1953
+ declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase$1<TSchema>, TSchema>;
1954
+ declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
1955
+ $client: Sql;
1956
+ }, TSchema>;
1957
+ //#endregion
1958
+ //#region src/socket-types.d.ts
1959
+ type SocketSchemas = Record<string, TSchema>;
1960
+ type SocketPayloads<S extends SocketSchemas> = { [K in keyof S]: Static<S[K]>; };
1961
+ type SocketEventArgs<Events> = { [K in keyof Events & string]: [event: K, payload: Events[K]]; }[keyof Events & string];
1962
+ interface BrickSocketSender<Events> {
1963
+ /** Locally accepts a message. Does not acknowledge remote delivery. */
1964
+ send(...args: SocketEventArgs<Events>): void;
1965
+ close(): void;
1966
+ }
1967
+ interface BrickSocketConfig<I extends SocketSchemas, O extends SocketSchemas, Ctx> {
1968
+ name: string;
1969
+ path?: string;
1970
+ description?: string;
1971
+ input: I;
1972
+ output: O;
1973
+ /** Defaults to the upgrade request's origin. */
1974
+ allowedOrigins?: readonly string[];
1975
+ allowMissingOrigin?: boolean;
1976
+ authorize?: (params: {
1977
+ ctx: Ctx;
1978
+ }) => boolean | Promise<boolean>;
1979
+ /** Rooms the connection is put in when it opens. */
1980
+ rooms?: (params: {
1981
+ ctx: Ctx;
1982
+ }) => readonly string[] | Promise<readonly string[]>;
1983
+ /** Decides each room a client asks to join. Without it, client joins are refused. */
1984
+ join?: (params: {
1985
+ ctx: Ctx;
1986
+ room: string;
1987
+ }) => boolean | Promise<boolean>;
1988
+ /** Rooms one connection can be in at once (default 100). */
1989
+ maxRooms?: number;
1990
+ /** Keep recent emits per room so a reconnecting client gets what it missed. Off by default. */
1991
+ replay?: SocketReplay;
1992
+ handlers: { [K in keyof I]: (params: {
1993
+ input: Static<I[K]>;
1994
+ ctx: Ctx;
1995
+ socket: BrickSocketSender<SocketPayloads<O>>;
1996
+ }) => void | Promise<void>; };
1997
+ open?: (params: {
1998
+ ctx: Ctx;
1999
+ socket: BrickSocketSender<SocketPayloads<O>>;
2000
+ }) => void | Promise<void>;
2001
+ close?: (params: {
2002
+ ctx: Ctx;
2003
+ socket: BrickSocketSender<SocketPayloads<O>>;
2004
+ code: number;
2005
+ reason: string;
2006
+ }) => void | Promise<void>;
2007
+ }
2008
+ interface SocketEmitOptions {
2009
+ /** A transaction handle from `runInTransaction`: send on commit, drop on rollback. */
2010
+ after?: unknown;
2011
+ }
2012
+ type SocketEmitArgs<Events> = { [K in keyof Events & string]: [event: K, payload: Events[K], options?: SocketEmitOptions]; }[keyof Events & string];
2013
+ /** Returned by `service.socket()`. Emits and kicks reach every process through the app's broker. */
2014
+ interface BrickSocketHandle<Output> {
2015
+ readonly name: string;
2016
+ /** Validates and serializes once, then sends to every connection in the rooms. At most once, unacknowledged. */
2017
+ emit(rooms: string | readonly string[], ...args: SocketEmitArgs<Output>): void;
2018
+ /** Removes connections from a room; `also` limits it to connections also in that room. */
2019
+ kick(room: string, options?: {
2020
+ also?: string;
2021
+ reason?: string;
2022
+ }): void;
2023
+ }
2024
+ interface SocketReplay {
2025
+ /** Emits kept per room. */
2026
+ keep: number;
2027
+ /** How long a room's history lasts without new emits. */
2028
+ maxAgeMs: number;
2029
+ }
2030
+ type SocketBrokerMessage =
2031
+ /** `seq` is set by the broker for sockets with replay: `<number>-<number>`, rising per room. */
2032
+ {
2033
+ type: "emit";
2034
+ topic: string;
2035
+ frame: string;
2036
+ seq?: string;
2037
+ } | {
2038
+ type: "kick";
2039
+ topic: string;
2040
+ also?: string;
2041
+ reason?: string;
2042
+ };
2043
+ /** Carries emits and kicks between processes. Topics are `<service>.<socket>:<room>`. */
2044
+ interface SocketBroker {
1331
2045
  /**
1332
- * Put parked deliveries back in line.
1333
- *
1334
- * @param deliveryId - One delivery. Omit it to retry every dead one.
1335
- * @returns How many deliveries were put back.
2046
+ * Sends to every subscriber of `message.topic`, in every process, this one
2047
+ * included. With `replay`, also keeps the emit and gives it a `seq`.
1336
2048
  */
1337
- retryDead(deliveryId?: string): Promise<number>;
1338
- private deliverable;
1339
- private bind;
2049
+ publish(message: SocketBrokerMessage, replay?: SocketReplay): void;
2050
+ /** The current position of a room, below every later `seq`. Needed for replay. */
2051
+ head?(topic: string): string | Promise<string>;
2052
+ /** Kept emits after `since`, or undefined when the history no longer covers it. Needed for replay. */
2053
+ history?(topic: string, since: string, replay: SocketReplay): SocketBrokerMessage[] | undefined | Promise<SocketBrokerMessage[] | undefined>;
2054
+ /** Called once per local holder of a topic; returns its unsubscribe. */
2055
+ subscribe(topic: string, deliver: (message: SocketBrokerMessage) => void): () => void;
2056
+ /** Resolves once messages for a topic just subscribed reach this process. */
2057
+ ready?(topic: string): Promise<void>;
2058
+ close?(): void | Promise<void>;
2059
+ }
2060
+ interface BrickSocketReconnectOptions {
2061
+ /** Default 500. */
2062
+ minDelayMs?: number;
2063
+ /** Default 30 000. */
2064
+ maxDelayMs?: number;
2065
+ /** Random spread around each delay, 0 to 1. Default 0.2. */
2066
+ jitter?: number;
2067
+ }
2068
+ type BrickSocketStatus = "connecting" | "open" | "reconnecting" | "closed";
2069
+ interface BrickSocketConnectOptions {
2070
+ signal?: AbortSignal;
2071
+ /** Limits each opening attempt. */
2072
+ timeoutMs?: number;
2073
+ /** Called on every connect and reconnect; sent as the `brick.token.<token>` subprotocol. */
2074
+ token?: () => string | Promise<string>;
2075
+ /** On by default. `false` ends the client at the first close. */
2076
+ reconnect?: false | BrickSocketReconnectOptions;
2077
+ }
2078
+ declare class BrickSocketError extends Error {
2079
+ readonly kind: "connection" | "protocol" | "backpressure" | "refused";
2080
+ constructor(kind: "connection" | "protocol" | "backpressure" | "refused", message: string, options?: ErrorOptions);
2081
+ }
2082
+ interface BrickSocketClient<Input, Output> extends BrickSocketSender<Input> {
2083
+ /** Resolves on the first open; rejects if the client closes before it. */
2084
+ readonly ready: Promise<void>;
2085
+ readonly status: BrickSocketStatus;
2086
+ onStatus(listener: (status: BrickSocketStatus) => void): () => void;
2087
+ /** After each reconnect. Messages sent while offline are not replayed. */
2088
+ onReconnect(listener: () => void): () => void;
2089
+ on<K extends keyof Output & string>(event: K, listener: (payload: Output[K]) => void): () => void;
2090
+ /** Resolves when the server accepts the room; rejects with kind `refused` otherwise. */
2091
+ join(room: string): Promise<void>;
2092
+ leave(room: string): void;
2093
+ /** The server removed this connection from a room. */
2094
+ onLeave(listener: (room: string, reason?: string) => void): () => void;
2095
+ /** Replay could not cover what this client missed in a room while away: refetch it. */
2096
+ onGap(listener: (room: string) => void): () => void;
2097
+ onError(listener: (error: BrickSocketError) => void): () => void;
2098
+ onClose(listener: (info: {
2099
+ code: number;
2100
+ reason: string;
2101
+ }) => void): () => void;
2102
+ }
2103
+ /** Browser metadata. Schemas retain TypeBox kinds as JSON-safe annotations. */
2104
+ interface BrickClientSocket<Input = unknown, Output = unknown> {
2105
+ kind: "socket";
2106
+ name: string;
2107
+ serviceName: string;
2108
+ config: {
2109
+ path: string;
2110
+ };
2111
+ output: Record<string, unknown>;
2112
+ readonly __types?: {
2113
+ input: Input;
2114
+ output: Output;
2115
+ };
2116
+ }
2117
+ interface BrickSocketSchema {
2118
+ name: string;
2119
+ path?: string;
2120
+ description?: string;
2121
+ input: string[];
2122
+ output: string[];
2123
+ hasAuthorize: boolean;
2124
+ }
2125
+ //#endregion
2126
+ //#region src/socket.d.ts
2127
+ interface SocketSender {
2128
+ readonly isOpen: boolean;
2129
+ send(event: string, payload: unknown): void;
2130
+ close(): void;
2131
+ }
2132
+ interface SocketSession {
2133
+ /** Server rooms, resolved from the handshake context. */
2134
+ rooms: readonly string[];
2135
+ open(socket: SocketSender): Promise<void>;
2136
+ message(event: string, data: unknown, socket: SocketSender): Promise<void>;
2137
+ join(room: string): Promise<boolean>;
2138
+ close(socket: SocketSender, code: number, reason: string): Promise<void>;
2139
+ }
2140
+ interface RegisteredSocket {
2141
+ schema: BrickSocketSchema;
2142
+ input: SocketSchemas;
2143
+ output: SocketSchemas;
2144
+ allowedOrigins?: readonly string[];
2145
+ allowMissingOrigin?: boolean;
2146
+ maxRooms: number;
2147
+ replay?: SocketReplay;
2148
+ /** Brokers of the apps this socket is mounted in. */
2149
+ brokers: Set<SocketBroker>;
2150
+ handle: BrickSocketHandle<any>;
2151
+ topicPrefix: string;
2152
+ topic(room: string): string;
2153
+ connect(request: Request): Promise<SocketSession>;
1340
2154
  }
1341
2155
  //#endregion
1342
2156
  //#region src/types.d.ts
@@ -1391,7 +2205,13 @@ type NarrowAuthorizedContext<TCtx> = TCtx extends {
1391
2205
  interface ActionErrorDefinition {
1392
2206
  status?: number;
1393
2207
  message: string;
2208
+ /** Schema of the `details` the error carries. Checked in types only, not at runtime. */
2209
+ details?: TSchema;
1394
2210
  }
2211
+ /** The `details` type of a declared error: its schema's type, or `unknown` when it has none. */
2212
+ type ErrorDetails<TDef> = TDef extends {
2213
+ details: infer D extends TSchema;
2214
+ } ? Static<D> : unknown;
1395
2215
  interface ValidationErrorItem {
1396
2216
  path: string;
1397
2217
  message: string;
@@ -1433,11 +2253,18 @@ interface StandardErrorMap {
1433
2253
  INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
1434
2254
  [key: string]: ((overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never) | undefined;
1435
2255
  }
1436
- type ErrorBuilder<TErrors extends Record<string, ActionErrorDefinition>> = StandardErrorMap & { [K in keyof TErrors]: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never; };
2256
+ type ErrorBuilder<TErrors extends Record<string, ActionErrorDefinition>> = StandardErrorMap & { [K in keyof TErrors]: TErrors[K] extends {
2257
+ details: TSchema;
2258
+ } ? (overrideMessage: string | undefined, details: ErrorDetails<TErrors[K]>, options?: ErrorOptions) => never : (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never; };
1437
2259
  interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
1438
2260
  name: string;
1439
2261
  description?: string;
1440
- /** Effective HTTP path, including the prefix; replaces the default action path. */
2262
+ /**
2263
+ * HTTP path relative to the action's owner (`/api/<service>` for a service
2264
+ * action, `/api/<service>/<resource>` for a resource action); replaces the
2265
+ * default `/<action>` segment. Path parameters (`/:id/summary`) are merged
2266
+ * into the input.
2267
+ */
1441
2268
  path?: string;
1442
2269
  /** Single HTTP method exposed for this action (default POST). */
1443
2270
  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
@@ -1540,6 +2367,20 @@ interface ResourceConfig<TTable = any, _TCtx = any> {
1540
2367
  name: string;
1541
2368
  table: TTable;
1542
2369
  id?: import("drizzle-orm").Column;
2370
+ /**
2371
+ * Child tables of this resource, by name. A command can load them with its
2372
+ * row (`load: { children: ["items"] }`) and insert, update and delete their
2373
+ * rows in the same transaction.
2374
+ */
2375
+ children?: Record<string, ResourceChild>;
2376
+ }
2377
+ /** A child table: rows that belong to one row of their resource. */
2378
+ interface ResourceChild<TTable = any> {
2379
+ table: TTable;
2380
+ /** The child's column that holds the parent row's id. */
2381
+ parent: import("drizzle-orm").Column;
2382
+ /** The child's id column. Defaults to its single primary key. */
2383
+ id?: import("drizzle-orm").Column;
1543
2384
  }
1544
2385
  type InferTableRow<TTable> = TTable extends {
1545
2386
  $inferSelect: infer S;
@@ -1547,7 +2388,7 @@ type InferTableRow<TTable> = TTable extends {
1547
2388
  type InferTableInsert<TTable> = TTable extends {
1548
2389
  $inferInsert: infer S;
1549
2390
  } ? S : any;
1550
- type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id">;
2391
+ type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id" | "children">;
1551
2392
  type PrimaryColumn<T> = T extends {
1552
2393
  _: {
1553
2394
  columns: infer C;
@@ -1568,7 +2409,7 @@ interface PreparationContribution {
1568
2409
  describe(): unknown;
1569
2410
  prepare(): void;
1570
2411
  }
1571
- interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}> {
2412
+ interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}, TEvents extends EventCatalog = EventCatalog> {
1572
2413
  use<P extends ResourcePlugin<Service<TCtx["db"], Omit<TCtx, keyof BaseContext>>, this, any>>(plugin: P): this & ResourcePluginAPI<P, TTable, TCtx, this>;
1573
2414
  readonly name: string;
1574
2415
  readonly serviceName: string;
@@ -1578,6 +2419,139 @@ interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOp
1578
2419
  } ? I : import("drizzle-orm").Column;
1579
2420
  readonly idField: string;
1580
2421
  readonly config: ResourceConfig<TTable, TCtx> & TOptions;
2422
+ /**
2423
+ * Declare an action owned by this resource, registered as
2424
+ * `<resource>.<name>`. It mounts at `/api/<service>/<resource>/<name>`, or at
2425
+ * `/api/<service>/<resource>/:id/<name>` with `record: true`.
2426
+ */
2427
+ action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, const TRecord extends boolean = false>(config: ResourceActionConfig<TIn, TOut, TErr, TCtx, InferTableRow<TTable>, TRecord>): Action<TRecord extends true ? TIntersect<[TIn extends TSchema ? TIn : TObject<{}>, TObject<{
2428
+ id: TUnion<[TString, TNumber]>;
2429
+ }>]> : TIn, TOut, TErr, TCtx>;
2430
+ /**
2431
+ * Declare a command: a record action whose body is the pure `decide`. Brick
2432
+ * loads the row (and the child rows it asks for) in a transaction, runs
2433
+ * `decide`, applies the changes it returns, records the events it emits in
2434
+ * the same transaction, and commits. Registered as `<resource>.<name>` at
2435
+ * `POST /api/<service>/<resource>/:id/<name>`.
2436
+ */
2437
+ command<TIn extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = {}, const TLoad extends readonly ChildNames<TOptions>[] = [], TOut extends TSchema | undefined = undefined>(name: string, config: CommandConfig<TIn, TOut, TErr, TCtx, CommandRow<TTable, TOptions, TLoad[number]>, CommandChildren<TOptions>, TEvents, TLoad>): Command<TIn, TOut, TErr, TCtx, CommandRow<TTable, TOptions, TLoad[number]>, CommandChildren<TOptions>, TEvents>;
2438
+ }
2439
+ type ChildNames<TOptions> = TOptions extends {
2440
+ children: infer C extends Record<string, ResourceChild>;
2441
+ } ? keyof C & string : never;
2442
+ /** The child tables of a resource, by name. */
2443
+ type CommandChildren<TOptions> = TOptions extends {
2444
+ children: infer C extends Record<string, ResourceChild>;
2445
+ } ? { [K in keyof C]: C[K]["table"]; } : {};
2446
+ /** The row `decide` receives: the resource's row with the children it loads. */
2447
+ type CommandRow<TTable, TOptions, TLoaded extends string> = InferTableRow<TTable> & { [K in TLoaded & keyof CommandChildren<TOptions>]: InferTableRow<CommandChildren<TOptions>[K]>[]; };
2448
+ /** The changes to one child table. Updates and deletes name rows by child id. */
2449
+ interface ChildChanges<TChild = any> {
2450
+ /** New rows. Their parent column is set to the parent's id. */
2451
+ insert?: Partial<InferTableInsert<TChild>>[];
2452
+ /** Partial rows, each with the child id; only rows of this parent change. */
2453
+ update?: Partial<InferTableRow<TChild>>[];
2454
+ /** Child ids to delete; only rows of this parent are deleted. */
2455
+ delete?: (string | number)[];
2456
+ }
2457
+ /** What `decide` returns when the command goes ahead. */
2458
+ interface CommandDecision<TRow = any, TChildren = {}, TEvents extends EventCatalog = EventCatalog> {
2459
+ /** Columns of the parent row to change. */
2460
+ set?: Partial<Omit<TRow, keyof TChildren>>;
2461
+ /** Inserts, updates and deletes per child table. */
2462
+ children?: { [K in keyof TChildren]?: ChildChanges<TChildren[K]>; };
2463
+ /** Events to record with the write, by catalog name and payload. */
2464
+ emit?: { [K in keyof TEvents]?: Static<TEvents[K]>; };
2465
+ }
2466
+ /**
2467
+ * The `error` helpers `decide` receives. Unlike an action's, they return the
2468
+ * rejection instead of throwing, so `decide` stays a pure function.
2469
+ */
2470
+ type CommandErrors<TErrors extends Record<string, ActionErrorDefinition>> = { [K in keyof TErrors | StandardErrorCode]: (overrideMessage?: string, details?: unknown) => ActionExecutionError; };
2471
+ type StandardErrorCode = "BAD_REQUEST" | "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "INTERNAL_SERVER_ERROR";
2472
+ /** `resource.command(name, config)`. */
2473
+ interface CommandConfig<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = {}, TCtx extends ActionContext = ActionContext, TRow = any, TChildren = {}, TEvents extends EventCatalog = EventCatalog, TLoad extends readonly string[] = readonly string[]> {
2474
+ description?: string;
2475
+ tags?: string[];
2476
+ /** The command's own input; `id` from the path joins it. */
2477
+ input?: TIn;
2478
+ /**
2479
+ * The reply: the updated row (with loaded children), cut down to this
2480
+ * schema's properties. Without it the reply is `{ id }`.
2481
+ */
2482
+ output?: TOut;
2483
+ errors?: TErr;
2484
+ /** Which child tables to load with the row, by their name on the resource. */
2485
+ load?: {
2486
+ children?: TLoad;
2487
+ };
2488
+ /** For a resource without `crud`: which rows the command may load. */
2489
+ access?: ResourceActionAccess<TCtx>;
2490
+ authorize?: (params: {
2491
+ user?: TCtx extends {
2492
+ user: infer U;
2493
+ } ? U : any;
2494
+ input: ResourceActionInput<TIn, true>;
2495
+ ctx: TCtx;
2496
+ }) => boolean | Promise<boolean>;
2497
+ /**
2498
+ * The rules: a pure function of the loaded row and the input. Return
2499
+ * `error.CODE()` to reject (nothing is written), or the changes to make.
2500
+ */
2501
+ decide: (row: TRow, input: ResourceActionInput<TIn, true>, helpers: {
2502
+ error: CommandErrors<TErr>;
2503
+ }) => CommandDecision<TRow, TChildren, TEvents> | ActionExecutionError;
2504
+ }
2505
+ /** A command: an action with its `decide`, callable without a database. */
2506
+ type Command<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = {}, TCtx extends ActionContext = ActionContext, TRow = any, TChildren = {}, TEvents extends EventCatalog = EventCatalog> = Action<TIntersect<[TIn extends TSchema ? TIn : TObject<{}>, TObject<{
2507
+ id: TUnion<[TString, TNumber]>;
2508
+ }>]>, TOut extends TSchema ? TOut : TObject<{
2509
+ id: TUnion<[TString, TNumber]>;
2510
+ }>, TErr, TCtx> & {
2511
+ /**
2512
+ * Run the rules alone, with the standard and declared error helpers: for
2513
+ * unit tests that need no database.
2514
+ */
2515
+ decide(row: TRow, input: ResourceActionInput<TIn, true>): CommandDecision<TRow, TChildren, TEvents> | ActionExecutionError;
2516
+ };
2517
+ /**
2518
+ * Which rows a record action may load when its resource has no `crud`:
2519
+ * `"public"` loads any row by id, `scope` adds a SQL condition (such as the
2520
+ * caller's tenant). With `crud` installed, its `access` always applies instead.
2521
+ */
2522
+ type ResourceActionAccess<TCtx = any> = "public" | {
2523
+ scope: (args: {
2524
+ ctx: TCtx;
2525
+ }) => import("drizzle-orm").SQL | undefined | Promise<import("drizzle-orm").SQL | undefined>;
2526
+ };
2527
+ /** A record action's input: its own fields and the `id` from the path. */
2528
+ type ResourceActionInput<TIn extends TSchema | undefined, TRecord extends boolean> = TRecord extends true ? (TIn extends TSchema ? Static<TIn> : {}) & {
2529
+ id: string | number;
2530
+ } : TIn extends TSchema ? Static<TIn> : any;
2531
+ /** `resource.action(config)`: an action owned by a resource. */
2532
+ interface ResourceActionConfig<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TCtx extends ActionContext = ActionContext, TRow = any, TRecord extends boolean = false> extends BaseActionConfig<TIn, TOut, TErr> {
2533
+ /**
2534
+ * `true` makes it a record action at `/:id/<name>`: `id` joins the input,
2535
+ * the row loads through the resource's access, and a missing or hidden row
2536
+ * answers 404 before `execute` runs.
2537
+ */
2538
+ record?: TRecord;
2539
+ /** For a record action on a resource without `crud`: which rows it may load. */
2540
+ access?: ResourceActionAccess<TCtx>;
2541
+ authorize?: (params: {
2542
+ user?: TCtx extends {
2543
+ user: infer U;
2544
+ } ? U : any;
2545
+ input: ResourceActionInput<TIn, TRecord>;
2546
+ ctx: TCtx;
2547
+ }) => boolean | Promise<boolean>;
2548
+ execute: (params: {
2549
+ input: ResourceActionInput<TIn, TRecord>;
2550
+ ctx: TCtx;
2551
+ error: ErrorBuilder<TErr>;
2552
+ /** The loaded row of a record action; `undefined` otherwise. */
2553
+ row: TRecord extends true ? TRow : undefined;
2554
+ }) => Promise<TOut extends TSchema ? Static<TOut> : any> | (TOut extends TSchema ? Static<TOut> : any);
1581
2555
  }
1582
2556
  interface ServiceAuthOptions {
1583
2557
  requireAuth?: boolean;
@@ -1619,6 +2593,11 @@ interface LifecycleOptions {
1619
2593
  }
1620
2594
  interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
1621
2595
  database?: DatabaseHandle<TDb>;
2596
+ /**
2597
+ * What the service needs from the app, as typed slots: `{ carrier: port<Carrier>() }`.
2598
+ * `brick({ deps })` provides the values, and actions read them as `ctx.deps`.
2599
+ */
2600
+ deps?: Ports;
1622
2601
  context?: (baseCtx: BaseContext<TDb> & {
1623
2602
  user?: unknown;
1624
2603
  }) => Promise<TServiceContext> | TServiceContext;
@@ -1628,6 +2607,11 @@ interface ServiceOptions<TServiceContext extends Record<string, any> = Record<st
1628
2607
  resilience?: ResilienceOptions;
1629
2608
  telemetry?: TelemetryOptions;
1630
2609
  lifecycle?: LifecycleOptions;
2610
+ /**
2611
+ * The service's event catalog: payload schema by event name. Each becomes
2612
+ * `service.events.<name>`, recorded as `<service>.<name>`.
2613
+ */
2614
+ events?: EventCatalog;
1631
2615
  }
1632
2616
  type ActionAccessPolicy = "public" | "authorized" | "scoped";
1633
2617
  interface ActionSchema {
@@ -1659,12 +2643,21 @@ interface ServiceSchema {
1659
2643
  name?: string;
1660
2644
  engine: "sqlite" | "postgres";
1661
2645
  tables: string[];
2646
+ /** The plugin that owns each table it contributed, by table key. */
2647
+ plugins?: Record<string, string>;
1662
2648
  };
1663
2649
  actions: ActionSchema[];
2650
+ sockets?: BrickSocketSchema[];
1664
2651
  /** MCP tools. A tool with an HTTP route is also listed under `actions`. */
1665
2652
  tools?: {
1666
2653
  name: string;
1667
2654
  }[];
2655
+ /** The event catalog: each event's wire name and payload JSON Schema. */
2656
+ events?: {
2657
+ name: string;
2658
+ schema: unknown;
2659
+ plugin?: string;
2660
+ }[];
1668
2661
  resources?: {
1669
2662
  name: string;
1670
2663
  }[];
@@ -1674,6 +2667,8 @@ interface ArchitectureSchema {
1674
2667
  services: ServiceSchema[];
1675
2668
  /** Present when the app has an `events` option. */
1676
2669
  events?: EventsDefinition;
2670
+ /** Every `definePlugin` installation, with its dashboard extension. */
2671
+ plugins?: InstalledPlugin[];
1677
2672
  }
1678
2673
  interface CompiledRoutePlan {
1679
2674
  service: Service<any, any>;
@@ -1707,8 +2702,10 @@ interface CompiledRoutePlan {
1707
2702
  errorBuilder: any;
1708
2703
  cachedDb: any;
1709
2704
  }
1710
- interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> {
2705
+ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>, TEvents extends EventCatalog = EventCatalog> {
1711
2706
  readonly name: string;
2707
+ /** The declared events, as handles for `defineListener` and `emitEvent`. */
2708
+ readonly events: EventRefs<TEvents>;
1712
2709
  readonly options: ServiceOptions<TServiceContext, TDb>;
1713
2710
  readonly actions: Map<string, Action<any, any, any, any>>;
1714
2711
  readonly tools: Map<string, Tool<any, any, any, any>>;
@@ -1718,13 +2715,15 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
1718
2715
  readonly isBuilt?: boolean;
1719
2716
  use<A>(plugin: ServicePlugin<this, A>): A;
1720
2717
  build(): this;
2718
+ socket<const I extends SocketSchemas, const O extends SocketSchemas>(config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext>): BrickSocketHandle<SocketPayloads<O>>;
2719
+ listSockets(): RegisteredSocket[];
1721
2720
  action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
1722
2721
  action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
1723
2722
  action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
1724
2723
  tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
1725
2724
  tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
1726
2725
  tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
1727
- resource<TTable = any, const TOptions extends ResourceTypeOptions = ResourceTypeOptions>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> & TOptions & Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>): Resource<TTable, BaseContext<TDb> & TServiceContext, ResourceIdentity<TTable, TOptions>>;
2726
+ resource<TTable = any, const TOptions extends ResourceTypeOptions = ResourceTypeOptions>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> & TOptions & Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>): Resource<TTable, BaseContext<TDb> & TServiceContext, ResourceIdentity<TTable, TOptions>, TEvents>;
1728
2727
  readonly preparations: Map<string, PreparationContribution>;
1729
2728
  contributePreparation(contribution: PreparationContribution): void;
1730
2729
  listPreparations(): PreparationContribution[];
@@ -1737,17 +2736,21 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
1737
2736
  getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
1738
2737
  listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
1739
2738
  getDb(): TDb | undefined;
2739
+ /** The handle from `defineDatabase`, without connecting. */
2740
+ getDatabaseHandle?(): DatabaseHandle<TDb> | undefined;
1740
2741
  setDb(database: DatabaseHandle<TDb>): void;
1741
2742
  /** The outbox table of this service's database, if it holds one (see `outboxTable`). */
1742
2743
  getOutbox?(): OutboxTable | undefined;
1743
2744
  /** What a write needs to record events. Set by `brick({ events })`; absent otherwise. */
1744
- readonly events?: ServiceEvents;
1745
- setEvents?(events: ServiceEvents | undefined): void;
2745
+ readonly recorder?: ServiceEvents;
2746
+ setRecorder?(recorder: ServiceEvents | undefined): void;
2747
+ /** The values of this service's `deps`. Set by `brick({ deps })`. */
2748
+ readonly deps?: Readonly<Record<string, unknown>>;
2749
+ setDeps?(deps: Readonly<Record<string, unknown>>): void;
1746
2750
  resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
1747
2751
  introspect(): ServiceSchema;
1748
2752
  }
1749
2753
  interface ProxyOptions {
1750
- isMonolith?: boolean;
1751
2754
  /** Name of the service creating this proxy. Populates ctx.caller on the target's envelope. */
1752
2755
  from?: string;
1753
2756
  context?: Partial<ActionContext>;
@@ -1805,8 +2808,10 @@ interface ProxyOptions {
1805
2808
  * | Client call | HTTP request |
1806
2809
  * |---|---|
1807
2810
  * Generated browser contracts carry each action's HTTP method and path,
1808
- * including plugin routes and consumer overrides. Without runtime metadata,
1809
- * callers use `POST /api/<service>/<action>` with dotted action names.
2811
+ * including plugin routes, resource routes and consumer overrides. Without
2812
+ * runtime metadata, callers use `POST /api/<service>/<action>` with the names
2813
+ * in kebab-case (`getSummary` → `get-summary`); resource and plugin routes
2814
+ * need the contract.
1810
2815
  * GET/DELETE input is serialized as a query string; other methods send JSON.
1811
2816
 
1812
2817
  */
@@ -1836,6 +2841,11 @@ interface BrickClientOptions {
1836
2841
  */
1837
2842
  contract?: Record<string, any>;
1838
2843
  }
2844
+ /**
2845
+ * The contract of each service by name, which types `useService`. The generated
2846
+ * contract (`_brick/contract.ts`) fills it in; nothing needs to be written by hand.
2847
+ */
2848
+ interface BrickServices {}
1839
2849
  /** Browser-safe action metadata generated by the Brick Vite plugin. */
1840
2850
  interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}> {
1841
2851
  kind: "action";
@@ -1962,7 +2972,9 @@ type InferActionFailure<A> = ActionExecutionError & {
1962
2972
  */
1963
2973
  type BrickActionCaller<A> = undefined extends InferActionInput<A> ? (input?: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>> : (input: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>>;
1964
2974
  /** Recursively maps action leaves and their namespaces to browser callers. */
1965
- type BrickClient<T> = T extends BrickClientAction<any, any, any> | Action<any, any, any, any> ? BrickActionCaller<T> : T extends ((...args: any[]) => any) ? BrickActionCaller<T> : T extends object ? { [K in keyof T]: BrickClient<T[K]>; } : T;
2975
+ type BrickClient<T> = T extends BrickClientSocket<infer I, infer O> ? {
2976
+ connect(options?: BrickSocketConnectOptions): BrickSocketClient<I, O>;
2977
+ } : T extends BrickClientAction<any, any, any> | Action<any, any, any, any> ? BrickActionCaller<T> : T extends ((...args: any[]) => any) ? BrickActionCaller<T> : T extends object ? { [K in keyof T]: BrickClient<T[K]>; } : T;
1966
2978
  /**
1967
2979
  * Create an Eden/tRPC-style typed client for the application contract `TApp`.
1968
2980
  * `TApp` is a type-only parameter: `import type { AppServer }` keeps backend
@@ -1973,5 +2985,5 @@ declare function createBrickClient<TApp extends Record<string, any>>(options: Br
1973
2985
  }): BrickClient<TApp>;
1974
2986
  declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
1975
2987
  //#endregion
1976
- export { ToolConfigWithoutAuthorize as $, index$1 as $t, ErrorBuilder as A, SQLiteDefinition as At, Resource as B, envSource as Bt, ActionSchema as C, SQLiteOutboxTable as Ct, CacheOptions as D, DatabaseHandle as Dt, BaseContext as E, DatabaseDefinition as Et, NarrowAuthorizedContext as F, PostgresDatabaseConfig as Ft, ServiceAuthOptions as G, resolveSecrets as Gt, ResourceIdentity as H, overrideSecret as Ht, PreparationContribution as I, createPostgresDatabase as It, StandardErrorMap as J, BunSQLiteDatabase$1 as Jt, ServiceOptions as K, secret as Kt, ProxyOptions as L, SecretOptions as Lt, InferTableRow as M, isDatabaseHandle as Mt, LifecycleOptions as N, DatabaseAdapter as Nt, CompiledRoutePlan as O, EnvInput as Ot, Logger as P, PostgresDatabase as Pt, ToolConfigWithAuthorize as Q, foreignKey as Qt, RateLimitOptions as R, SecretRef as Rt, ActionExecutionError as S, PostgresOutboxTable as St, BaseActionConfig as T, outboxTable as Tt, ResourceTypeOptions as U, overrideSecrets as Ut, ResourceConfig as V, listSecrets as Vt, Service as W, resetSecrets as Wt, Tool as X, blob as Xt, TelemetryOptions as Y, SQLiteDatabaseConfig as Yt, ToolAnnotations as Z, createSQLiteDatabase as Zt, ActionConfig as _, defineResourcePlugin as _n, ServiceEvents as _t, BrickClientOptions as a, uniqueIndex as an, stopAllEvents as at, ActionContext as b, getPluginEndpoints as bn, OutboxStatus as bt, InferActionErrorCodes as c, PluginRouteRegistrar as cn, CrudEventPayload as ct, InferActionOutput as d, ResourcePlugin as dn, EventEnvelope as dt, integer$1 as en, ToolOptions as et, createBrickClient as f, ResourcePluginAPI as fn, EventListener as ft, ActionAccessPolicy as g, ServicePluginContext as gn, EventsWorld as gt, Action as h, ServicePlugin as hn, EventsOptions as ht, BrickClientAction as i, text$1 as in, EventsHub as it, InferTableInsert as j, defineDatabase as jt, DefaultServiceContext as k, PostgresDefinition as kt, InferActionFailure as l, PluginRouteScope as ln, DispatchOptions as lt, isBrickTransportError as m, ResourcePluginTypes as mn, EventWorkflow as mt, BrickCallOptions as n, real as nn, ValidationErrorItem as nt, BrickServerError as o, PluginEndpointContext as on, Dispatcher as ot, isBrickServerError as p, ResourcePluginContext as pn, EventRecorder as pt, ServiceSchema as q, BrickSQLiteDatabase as qt, BrickClient as r, sqliteTable$1 as rn, EventsDefinition as rt, BrickTransportError as s, PluginRouteMethod as sn, OutboxCounts as st, BrickActionCaller as t, primaryKey as tn, ValidationError as tt, InferActionInput as u, PluginRoutes as un, EventDelivery as ut, ActionConfigWithAuthorize as v, defineServicePlugin as vn, WorkflowEvent as vt, ArchitectureSchema as w, isOutboxTable as wt, ActionErrorDefinition as x, OutboxTable as xt, ActionConfigWithoutAuthorize as y, getPluginActionRoute as yn, WorkflowsOptions as yt, ResilienceOptions as z, SecretSource as zt };
2988
+ export { ResourceChild as $, SecretSource as $n, integer$1 as $t, Command as A, isOutboxTable as An, SocketEmitOptions as At, InferTableInsert as B, PluginInstallOptions as Bn, defineDatabase as Bt, ActionExecutionError as C, stopAllEvents as Cn, EventRefs as Cr, BrickSocketReconnectOptions as Ct, BaseContext as D, OutboxTable as Dn, Ports as Dr, SocketBroker as Dt, BaseActionConfig as E, OutboxStatus as En, Port as Er, BrickSocketStatus as Et, CommandRow as F, PluginAppContext as Fn, DatabaseDefinition as Ft, PreparationContribution as G, PluginSetupContext as Gn, createPostgresDatabase as Gt, LifecycleOptions as H, PluginLifecycleContext as Hn, DatabaseAdapter as Ht, CompiledRoutePlan as I, PluginContext as In, DatabaseHandle as It, ResilienceOptions as J, definePlugin as Jn, SQLiteDatabaseConfig as Jt, ProxyOptions as K, PluginTableBuilders as Kn, BrickSQLiteDatabase as Kt, DefaultServiceContext as L, PluginFactory as Ln, EnvInput as Lt, CommandConfig as M, emitEvent as Mn, SocketPayloads as Mt, CommandDecision as N, defineListener as Nn, SocketReplay as Nt, CacheOptions as O, PostgresOutboxTable as On, port as Or, SocketBrokerMessage as Ot, CommandErrors as P, InstalledPlugin as Pn, SocketSchemas as Pt, ResourceActionInput as Q, SecretRef as Qn, index$1 as Qt, ErrorBuilder as R, PluginHooks as Rn, PostgresDefinition as Rt, ActionErrorDefinition as S, EventsHub as Sn, EventRef as Sr, BrickSocketHandle as St, ArchitectureSchema as T, OutboxCounts as Tn, DepsOf as Tr, BrickSocketSender as Tt, Logger as U, PluginManifest as Un, PostgresDatabase as Ut, InferTableRow as V, PluginInstance as Vn, isDatabaseHandle as Vt, NarrowAuthorizedContext as W, PluginServiceContext as Wn, PostgresDatabaseConfig as Wt, ResourceActionAccess as X, satisfiesRange as Xn, createSQLiteDatabase as Xt, Resource as Y, isPluginInstance as Yn, blob as Yt, ResourceActionConfig as Z, SecretOptions as Zn, foreignKey as Zt, ActionAccessPolicy as _, defineServicePlugin as _n, RetryDecision as _r, BrickClientSocket as _t, BrickClientOptions as a, PluginEndpointContext as an, resetSecrets as ar, ServiceOptions as at, ActionConfigWithoutAuthorize as b, resolveWorkflowPaths as bn, WorkflowsOptions as br, BrickSocketConnectOptions as bt, BrickTransportError as c, PluginRouteScope as cn, DispatchOptions as cr, TelemetryOptions as ct, InferActionInput as d, ResourcePluginAPI as dn, EventListener as dr, ToolConfigWithAuthorize as dt, primaryKey as en, defineSecret as er, ResourceConfig as et, InferActionOutput as f, ResourcePluginContext as fn, EventRecorder as fr, ToolConfigWithoutAuthorize as ft, Action as g, defineResourcePlugin as gn, ListenerFailure as gr, RegisteredSocket as gt, isBrickTransportError as h, ServicePluginContext as hn, EventsWorld as hr, ValidationErrorItem as ht, BrickClientAction as i, uniqueIndex as in, overrideSecrets as ir, ServiceAuthOptions as it, CommandChildren as j, outboxTable as jn, SocketEventArgs as jt, ChildChanges as k, SQLiteOutboxTable as kn, useDeps as kr, SocketEmitArgs as kt, InferActionErrorCodes as l, PluginRoutes as ln, EventDelivery as lr, Tool as lt, isBrickServerError as m, ServicePlugin as mn, EventsOptions as mr, ValidationError as mt, BrickCallOptions as n, sqliteTable$1 as nn, listSecrets as nr, ResourceTypeOptions as nt, BrickServerError as o, PluginRouteMethod as on, resolveSecrets as or, ServiceSchema as ot, createBrickClient as p, ResourcePluginTypes as pn, EventWorkflow as pr, ToolOptions as pt, RateLimitOptions as q, brickVersion as qn, BunSQLiteDatabase$1 as qt, BrickClient as r, text$1 as rn, overrideSecret as rr, Service as rt, BrickServices as s, PluginRouteRegistrar as sn, CrudEventPayload as sr, StandardErrorMap as st, BrickActionCaller as t, real$1 as tn, envSource as tr, ResourceIdentity as tt, InferActionFailure as u, ResourcePlugin as un, EventEnvelope as ur, ToolAnnotations as ut, ActionConfig as v, getPluginActionRoute as vn, ServiceEvents as vr, BrickSocketClient as vt, ActionSchema as w, Dispatcher as wn, isEventRef as wr, BrickSocketSchema as wt, ActionContext as x, EventsDefinition as xn, EventCatalog as xr, BrickSocketError as xt, ActionConfigWithAuthorize as y, getPluginEndpoints as yn, WorkflowEvent as yr, BrickSocketConfig as yt, ErrorDetails as z, PluginInfo as zn, SQLiteDefinition as zt };
1977
2989
  //# sourceMappingURL=client.d.ts.map