@brickkit/core 0.10.0 → 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,266 +1,351 @@
1
- import { Static, TSchema } from "@sinclair/typebox";
2
- import { Elysia } from "elysia";
1
+ import { Static, TIntersect, TNumber, TObject, TSchema, TString, TUnion } from "@sinclair/typebox";
3
2
  import { Table } from "drizzle-orm";
4
- 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";
5
5
  import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
6
6
  import { Sql } from "postgres";
7
7
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
8
8
  import { Database } from "bun:sqlite";
9
- //#region src/plugin.d.ts
10
- type PluginRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
11
- type PluginRouteScope = "app" | "service" | "resource";
12
- type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> = false | Readonly<Record<string, false | {
13
- path?: string;
14
- scope?: S;
15
- }>>;
16
- type ContextOf<S> = S extends Service<infer D, infer C> ? BaseContext<D> & C : never;
17
- interface PluginEndpointContext<C extends ActionContext = ActionContext> {
18
- params: Record<string, string>;
19
- query: Record<string, string | undefined>;
20
- body: unknown;
21
- headers: Record<string, string>;
22
- request: Request;
23
- set: {
24
- status?: number;
25
- headers: Record<string, string>;
26
- };
27
- ctx: C;
28
- }
29
- interface PluginRouteRegistrar<C extends ActionContext = ActionContext, S extends PluginRouteScope = PluginRouteScope> {
30
- 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> & {
31
- path: string;
32
- method: PluginRouteMethod;
33
- scope?: S;
34
- }): Action<I, O, E, C>;
35
- 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> & {
36
- path: string;
37
- method: PluginRouteMethod;
38
- scope?: S;
39
- }): Action<I, O, E, C>;
40
- endpoint(config: {
41
- name: string;
42
- path: string;
43
- method: PluginRouteMethod;
44
- scope?: S;
45
- handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;
46
- summary?: string;
47
- description?: string;
48
- tags?: string[];
49
- }): void;
50
- }
51
- interface ServicePluginContext<S extends Service<any, any> = Service<any, any>> {
52
- service: S;
53
- routes: PluginRouteRegistrar<ContextOf<S>, "app" | "service">;
54
- }
55
- interface ResourcePluginContext<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>> {
56
- service: S;
57
- resource: R;
58
- routes: PluginRouteRegistrar<ContextOf<S>>;
59
- }
60
- /** Plugins may specialize their returned API for the installation host. */
61
- interface ResourcePluginTypes {
62
- readonly table: unknown;
63
- readonly context: unknown;
64
- readonly resource: unknown;
65
- readonly api: object;
66
- }
67
- type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
68
- readonly types: infer H extends ResourcePluginTypes;
69
- } ? (H & {
70
- readonly table: T;
71
- readonly context: C;
72
- readonly resource: R;
73
- })["api"] : P extends ResourcePlugin<any, any, infer A> ? A : never;
74
- declare const pluginKind: unique symbol;
75
- interface ServicePlugin<S extends Service<any, any>, A> {
76
- readonly [pluginKind]: "service";
77
- readonly name: string;
78
- readonly routes?: PluginRoutes<"app" | "service">;
79
- readonly setup: (context: ServicePluginContext<S>) => A;
80
- }
81
- interface ResourcePlugin<S extends Service<any, any>, R extends Resource<any, any, any>, A extends object> {
82
- readonly [pluginKind]: "resource";
83
- readonly name: string;
84
- readonly routes?: PluginRoutes;
85
- readonly setup: (context: ResourcePluginContext<S, R>) => A;
86
- }
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; };
87
19
  /**
88
- * Define a plugin that installs onto a service with `service.use(plugin)`. Its
89
- * `setup` receives the service and a `routes` registrar for adding actions and
90
- * 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).
91
23
  *
92
- * @param definition - A unique `name`, optional `routes` controls that let the
93
- * user move or switch off the plugin's routes, and `setup`, which must be
94
- * synchronous.
95
- * @returns The plugin descriptor, frozen.
96
- * @throws When the name is empty or has surrounding whitespace.
24
+ * @returns A slot typed as `T`. It holds nothing at runtime.
97
25
  * @example
98
- * import { defineServicePlugin, t } from "@brickkit/core";
26
+ * import { defineService, port } from "@brickkit/core";
99
27
  *
100
- * export const greeting = (salutation = "Hello") =>
101
- * defineServicePlugin({
102
- * name: "example/greeting",
103
- * setup({ routes }) {
104
- * const hello = routes.action({
105
- * name: "hello",
106
- * input: t.Object({ name: t.String() }),
107
- * output: t.String(),
108
- * execute: ({ input }) => `${salutation}, ${input.name}!`,
109
- * });
110
- * return { hello };
111
- * },
112
- * });
28
+ * export const orders = defineService("orders", {
29
+ * database,
30
+ * deps: { carrier: port<Carrier>() },
31
+ * });
113
32
  *
114
- * const api = greeterService.use(greeting("Welcome"));
115
- * await api.hello({ input: { name: "Ada" } });
33
+ * // app.ts
34
+ * export default brick({ services: [orders], deps: { carrier: createCarrier() } });
116
35
  */
117
- declare function defineServicePlugin<S extends Service<any, any> = Service<any, any>, A = unknown>(definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & {
118
- setup: (context: ServicePluginContext<S>) => A & (A extends PromiseLike<unknown> ? never : unknown);
119
- }): ServicePlugin<S, A>;
36
+ declare function port<T>(): Port<T>;
120
37
  /**
121
- * Define a plugin that installs onto a resource (a table and its entity) with
122
- * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
123
- * `routes` registrar, whose routes are scoped under the resource's name, and
124
- * 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.
125
40
  *
126
- * @param definition - A unique `name`, optional `routes` controls, and `setup`,
127
- * which must be synchronous.
128
- * @returns The plugin descriptor, frozen.
129
- * @throws When the name is empty or has surrounding whitespace.
130
- */
131
- 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> & {
132
- setup: (context: ResourcePluginContext<S, R>) => A & (A extends PromiseLike<unknown> ? never : unknown);
133
- }): ResourcePlugin<S, R, A>;
134
- /**
135
- * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
136
- * 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 })`.
137
44
  *
138
- * @param action - An action.
139
- * @param prefix - The application's route prefix (default `/api`).
140
- * @returns `undefined` when no plugin bound the action (it uses its own route),
141
- * `false` when the plugin's route was switched off, otherwise the route's
142
- * `path` and `method`, the `clientPath` the typed client uses, and the owning
143
- * `plugin` and `resource`.
144
- */
145
- declare function getPluginActionRoute(action: Action<any, any, any, any>, prefix?: string): false | {
146
- path: string;
147
- method: PluginRouteMethod;
148
- clientPath: string[] | undefined;
149
- plugin: string;
150
- resource: string | undefined;
151
- } | undefined;
152
- /**
153
- * The raw HTTP endpoints plugins registered on a service, ready to mount on the
154
- * 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>() };
155
51
  *
156
- * @param service - The service plugins were installed on.
157
- * @param prefix - The application's route prefix (default `/api`).
158
- * @returns The enabled endpoints: `path`, `method`, `handler`, and the
159
- * `summary`, `description`, and `tags` for OpenAPI.
52
+ * async function bookCarrier(orderId: string) {
53
+ * "use step";
54
+ * return useDeps(ordersDeps).carrier.book(orderId);
55
+ * }
160
56
  */
161
- declare function getPluginEndpoints(service: Service<any, any>, prefix?: string): {
162
- path: string;
163
- method: PluginRouteMethod;
164
- service: Service<any, any>;
165
- summary: string | undefined;
166
- description: string | undefined;
167
- tags: string[] | undefined;
168
- handler: (context: Omit<PluginEndpointContext, "ctx">) => Promise<unknown>;
169
- }[];
57
+ declare function useDeps<const P extends Ports>(ports: P): DepsOf<P>;
58
+ declare function useDeps<T = Record<string, unknown>>(): T;
170
59
  //#endregion
171
- //#region src/db/sqlite.d.ts
172
- interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
173
- /** Database file path or ':memory:' (default: ':memory:') */
174
- path?: string;
175
- /** Alias for path */
176
- filename?: string;
177
- /** Whether to enable WAL journal mode for file-based DBs (default: true) */
178
- wal?: boolean;
179
- /** Whether to enforce foreign key constraints (default: true) */
180
- foreignKeys?: boolean;
181
- /** Optional existing bun:sqlite Database instance */
182
- client?: Database;
183
- /** Optional Drizzle schema object for typed relational queries */
184
- schema?: TSchema;
185
- }
186
- type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<TSchema> & {
187
- $client: Database;
188
- };
60
+ //#region src/events/catalog.d.ts
61
+ /** A service's declared events: payload schema by event name. */
62
+ type EventCatalog = Record<string, TSchema>;
189
63
  /**
190
- * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
191
- * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
192
- *
193
- * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
194
- * other runtimes (e.g. Node) stays safe until this function is actually
195
- * 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.
196
66
  */
197
- 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;
198
80
  //#endregion
199
- //#region src/secrets.d.ts
81
+ //#region src/events/types.d.ts
200
82
  /**
201
- * Type-safe secrets & environment variables.
202
- *
203
- * Declare each secret once at module scope instead of scattering untyped
204
- * `process.env.FOO` reads:
205
- *
206
- * const port = secret("PORT").default("3333").transform(Number).require();
207
- * const baseUrl = secret("BASE_URL").url().require();
208
- * const key = secret("STRIPE_KEY").validate((v) =>
209
- * v.startsWith("sk_") || "must start with sk_"
210
- * ).require();
211
- *
212
- * Values resolve from the environment (Bun populates `process.env` from
213
- * `.env` locally; in prod the same env source applies — a future
214
- * `SecretSource` such as AWS can slot in without touching call sites).
215
- *
216
- * Resolution order per secret: test/session override → source (`process.env`
217
- * by default) → declared `default`. `resolveSecrets()` validates every
218
- * 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.
219
84
  */
220
- interface SecretSource {
221
- get(name: string): string | undefined;
222
- }
223
- /** Default source: `process.env` (Bun loads `.env` into it automatically). */
224
- declare const envSource: SecretSource;
225
- interface SecretOptions {
226
- /** Fallback when the source has no value. Secrets without a default are required. */
227
- 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;
228
98
  }
229
- /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
230
- type SecretValidator<T> = (value: T) => void | boolean | string;
231
- declare class SecretRef<T = string> {
232
- readonly name: string;
233
- readonly options: SecretOptions;
234
- private transformFn?;
235
- private validators;
236
- constructor(name: string, options?: SecretOptions);
237
- /** True when a default was declared (i.e. the secret is optional). */
238
- get hasDefault(): boolean;
239
- /** Fallback used when the source has no value. Makes the secret optional. */
240
- 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;
241
106
  /**
242
- * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
243
- * 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.
244
109
  */
245
- transform<U>(fn: (raw: string) => U): SecretRef<U>;
246
- /** Run a custom check on the (transformed) value at every resolution. */
247
- validate(fn: SecretValidator<T>): this;
248
- /** Shorthand validator: value must parse as a URL. String refs only. */
249
- url(this: SecretRef<string>): SecretRef<string>;
250
- private resolveRaw;
251
- private coerce;
252
- /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
253
- value(source?: SecretSource): T | undefined;
254
- /** Resolved value, or throws naming the missing/invalid secret. */
255
- require(source?: SecretSource): T;
256
- /** True when a value would resolve (override, source, or default). */
257
- isSet(source?: SecretSource): boolean;
110
+ deliveryId: string;
111
+ /** 1 on the first try, 2 on the first retry, and so on. */
112
+ attempt: number;
258
113
  }
259
114
  /**
260
- * Declare a secret. Idempotent: re-declaring the same name returns the
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
261
346
  * original ref (first declaration wins) so module re-evaluation is safe.
262
347
  */
263
- declare function secret(name: string, options?: SecretOptions): SecretRef<string>;
348
+ declare function defineSecret(name: string, options?: SecretOptions): SecretRef<string>;
264
349
  /**
265
350
  * Validate every registered secret at boot. Throws a single error listing
266
351
  * all missing required secrets. Returns the resolved values.
@@ -283,113 +368,494 @@ declare function overrideSecrets(values: Record<string, string | undefined>): vo
283
368
  /** Clear registry and overrides. Test-only. */
284
369
  declare function resetSecrets(): void;
285
370
  //#endregion
286
- //#region src/db/postgres.d.ts
287
- interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
288
- /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */
289
- client?: Sql;
290
- /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */
291
- url?: string;
292
- /** Connection string alias */
293
- connectionString?: string;
294
- host?: string;
295
- port?: number;
296
- user?: string;
297
- password?: string;
298
- database?: string;
299
- ssl?: boolean | "require" | "allow" | "prefer" | "verify-full";
300
- max?: number;
301
- /**
302
- * Disable prepared statements (required for transaction-mode poolers such
303
- * as Supabase's Supavisor on :6543, which cannot hold named prepared
304
- * statements across transactions).
305
- */
306
- prepare?: boolean;
307
- /** Optional Drizzle schema for relational queries */
308
- schema?: TSchema;
309
- /** Custom schema name for Encore-style isolated schemas */
310
- schemaName?: string;
311
- }
312
- type PostgresDatabase<_TSchema extends Record<string, unknown> = Record<string, unknown>> = any;
313
- interface DatabaseAdapter<TDb = any, TConfig = any> {
314
- createDatabase(config?: TConfig): TDb;
315
- }
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;
316
374
  /**
317
- * Creates a PostgreSQL Drizzle instance using postgres-js.
318
- * Static imports (both are hard dependencies in package.json) so bundlers
319
- * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
320
- * `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.
321
377
  */
322
- declare function createPostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: PostgresDatabaseConfig<TSchema>): PostgresDatabase<TSchema>;
323
- //#endregion
324
- //#region src/db/define.d.ts
325
- type EnvInput<T> = T | SecretRef<T>;
326
- type EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>>; };
327
- interface DefinitionOptions<TSchema extends Record<string, unknown>> {
328
- name?: string;
329
- /** Drizzle tables retained for schema tooling. Never applied at runtime. */
330
- tables?: (TSchema & Record<string, Table>) | readonly Table[];
331
- schema?: TSchema;
332
- }
333
- type SQLiteDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
334
- engine?: "sqlite";
335
- client?: SQLiteDatabaseConfig<TSchema>["client"];
336
- url?: never;
337
- connectionString?: never;
338
- };
339
- type PostgresDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema" | "client">> & {
340
- engine: "postgres";
341
- path?: never;
342
- filename?: never;
343
- wal?: never;
344
- foreignKeys?: never;
345
- 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>;
346
514
  };
347
- type DatabaseDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;
348
- interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>> {
349
- readonly kind: "brick-database";
350
- 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. */
351
522
  readonly engine: "sqlite" | "postgres";
352
- readonly tables: Readonly<Record<string, Table>>;
353
- readonly schema: TSchema;
354
- getDb(): TDb;
355
- 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;
356
528
  }
357
529
  /**
358
- * 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.
359
699
  *
360
- * @param value - Anything.
361
- * @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());
362
725
  */
363
- 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
+ });
364
759
  /**
365
- * Declare a service's database: its engine, its Drizzle tables, and how to
366
- * reach it. Nothing connects until the handle is used (`getDb()`), so defining
367
- * 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 } })`.
368
763
  *
369
- * SQLite is the default and needs no options. Pass `engine: "postgres"` with a
370
- * `url` for Postgres. Options that belong to the other engine (such as `url` for
371
- * 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.
372
771
  *
373
- * @param options - `engine` (`"sqlite"` or `"postgres"`), `tables`, an optional
374
- * `name`, and the engine's connection settings.
375
- * @returns A handle to give to `defineService({ database })`. `getDb()` returns
376
- * the Drizzle database.
377
- * @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`.
378
783
  * @example
379
- * import { defineDatabase } from "@brickkit/core";
380
- * import { sqliteTable, text } from "drizzle-orm/sqlite-core";
784
+ * import { brick, defineListener } from "@brickkit/core";
381
785
  *
382
- * const pages = sqliteTable("pages", {
383
- * id: text("id").primaryKey(),
384
- * 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
+ * },
385
792
  * });
386
793
  *
387
- * 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
+ * });
388
810
  */
389
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase$1<TSchema>, TSchema>;
390
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
391
- $client: Sql;
392
- }, 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>;
393
859
  //#endregion
394
860
  //#region src/events/outbox.d.ts
395
861
  /** What the outbox rows are in, by state. */
@@ -980,365 +1446,514 @@ declare function outboxTable(engine: "postgres", options?: {
980
1446
  */
981
1447
  declare function isOutboxTable(value: unknown): value is OutboxTable;
982
1448
  //#endregion
983
- //#region src/events/types.d.ts
984
- /**
985
- * An event, as it was recorded. It is the same for every listener of it.
986
- */
987
- interface EventEnvelope<TPayload = unknown> {
988
- /** Unique per event. Every listener's delivery of the event shares it. */
989
- id: string;
990
- /** The event name, such as `user.create`. */
991
- name: string;
992
- /** What happened. JSON data. */
993
- payload: TPayload;
994
- /** When it happened, as an ISO timestamp. */
995
- occurredAt: string;
996
- /** The trace of the request that caused it, so a listener continues the same trace. */
997
- traceId?: string;
998
- /** What emitted it, such as `identity.user` for a generated CRUD write. */
999
- source?: string;
1000
- }
1449
+ //#region src/events/dispatcher.d.ts
1450
+ /** How many outbox rows are in each state. */
1451
+ type OutboxCounts = Record<OutboxStatus, number>;
1001
1452
  /**
1002
- * One listener's delivery of an event: the envelope, plus which listener it is for
1003
- * 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`.
1004
1462
  */
1005
- interface EventDelivery<TPayload = unknown> extends EventEnvelope<TPayload> {
1006
- /** The name of the listener this delivery is for. */
1007
- 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;
1008
1479
  /**
1009
- * `<event id>:<listener>`. It is the same on every retry, so a listener can use
1010
- * 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.
1011
1481
  */
1012
- deliveryId: string;
1013
- /** 1 on the first try, 2 on the first retry, and so on. */
1014
- attempt: number;
1015
- }
1016
- /**
1017
- * The CRUD events of a resource called `user`, by operation. Listeners of
1018
- * `user.create`, `user.update` and `user.delete` receive these payloads.
1019
- */
1020
- type CrudEventPayload<TRow = Record<string, unknown>> = {
1021
- id: unknown;
1022
- row: TRow;
1023
- } | {
1024
- id: unknown;
1025
- before: TRow;
1026
- after: TRow;
1027
- };
1028
- /**
1029
- * A listener: code that runs when an event it listens for has been recorded.
1030
- */
1031
- interface EventListener<TPayload = any> {
1032
- /** Unique among the app's listeners. It is part of each delivery's id. */
1033
- readonly name: string;
1482
+ stop(): Promise<void>;
1483
+ /** Look for work soon, without waiting for the timer. Safe to call often. */
1484
+ notify(): void;
1034
1485
  /**
1035
- * The event names to listen for. A trailing `*` matches a prefix (`user.*`),
1036
- * 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.
1037
1490
  */
1038
- readonly on: readonly string[];
1491
+ tick(): Promise<number>;
1039
1492
  /**
1040
- * A handler that runs in the dispatching process for each delivery. Throwing
1041
- * 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.
1042
1497
  */
1043
- readonly run?: (delivery: EventDelivery<TPayload>) => void | Promise<void>;
1498
+ drain(): Promise<number>;
1044
1499
  /**
1045
- * A durable workflow that runs for each delivery, on the app's `events.world`.
1046
- * The delivery counts as done once its run has started; the workflow retries
1047
- * its own steps from there. A listener has this or `run`.
1500
+ * How many rows are in each state.
1048
1501
  */
1049
- readonly workflow?: EventWorkflow<TPayload>;
1050
- /** Attempts before the delivery is parked as dead. Defaults to the dispatcher's. */
1051
- 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;
1052
1527
  }
1053
1528
  /**
1054
- * What a workflow listener's workflow receives: the event and which listener it
1055
- * is for. It has no `attempt`, because one delivery starts one run however many
1056
- * times it is tried.
1057
- */
1058
- type WorkflowEvent<TPayload = any> = Omit<EventDelivery<TPayload>, "attempt">;
1059
- /**
1060
- * A function marked `"use workflow"`, run once per delivery of the listener it is
1061
- * 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.
1062
1532
  */
1063
- type EventWorkflow<TPayload = any> = (event: WorkflowEvent<TPayload>) => Promise<unknown>;
1533
+ declare function stopAllEvents(): Promise<void>;
1064
1534
  /**
1065
- * The world workflow listeners run on: the queue and storage behind the Workflow
1066
- * SDK. `createWorld()` from `@brickkit/redis-world` or `@brickkit/bullmq-world`
1067
- * 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.
1068
1537
  */
1069
- interface EventsWorld {
1070
- /**
1071
- * Names a run after its key so that starting it twice makes one run. A world
1072
- * without it would start a second run when an event is delivered again, so
1073
- * Brick refuses such a world.
1074
- */
1075
- createRunId?(options?: Readonly<Record<string, unknown>>): string;
1076
- start?(): Promise<void>;
1077
- close?(): Promise<void>;
1078
- 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[];
1079
1547
  }
1080
- /**
1081
- * Where the workflows of an app are built from. The CLI (`brick dev`,
1082
- * `brick start`) writes the bundle to `<root>/.well-known/workflow/v1` before
1083
- * events start, and events read it from there.
1084
- */
1085
- interface WorkflowsOptions {
1086
- /** The project root: where the Workflow SDK is installed. Default: the working directory. */
1087
- 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>;
1088
1554
  }
1089
1555
  /**
1090
- * 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`.
1091
1559
  */
1092
- 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;
1093
1570
  /**
1094
- * Whether to look for due deliveries on a timer, and right after a commit.
1095
- * Default `true`. With `false`, deliveries run only when something calls
1096
- * `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.
1097
1574
  */
1098
- timer?: boolean;
1099
- /** How often to look for deliveries that are due, in milliseconds. Default 1000. */
1100
- intervalMs?: number;
1101
- /** Most deliveries claimed at once. Default 50. */
1102
- batchSize?: number;
1103
- /** Attempts before a delivery is parked as dead. Default 8. */
1104
- maxAttempts?: number;
1105
- /** How long a claimed delivery may run before another dispatcher takes it, in milliseconds. Default 60000. */
1106
- claimTimeoutMs?: number;
1107
- /** Longest wait before a retry, in milliseconds. Default 300000. */
1108
- maxBackoffMs?: number;
1109
- /** How long delivered rows are kept, in milliseconds. Default 86400000 (one day). 0 keeps none. */
1110
- retainDeliveredMs?: number;
1111
- }
1112
- /**
1113
- * The `events` option of `brick()`.
1114
- */
1115
- interface EventsOptions {
1116
- /** The listeners of the app. */
1117
- listeners?: readonly EventListener[];
1575
+ constructor(options: EventsOptions, deps?: Record<string, unknown>);
1118
1576
  /**
1119
- * Whether this process delivers recorded events. `true` (the default) starts a
1120
- * dispatcher with the default settings, an object tunes it, and `false` only
1121
- * 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.
1122
1583
  */
1123
- 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;
1124
1589
  /**
1125
- * The world that runs `workflow` listeners. Required when any listener has one.
1126
- * 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.
1127
1594
  */
1128
- world?: EventsWorld;
1129
- /** Where the workflow bundle lives. Only used with workflow listeners. */
1130
- workflows?: WorkflowsOptions;
1131
- }
1132
- /**
1133
- * Records an event inside the transaction it was given. The event is committed
1134
- * with the write, or not at all.
1135
- */
1136
- type EventRecorder = (name: string, payload: unknown) => Promise<void>;
1137
- /**
1138
- * What a service with events offers the code that writes to its database. A
1139
- * service has it once `brick({ events })` is set up and its database holds an
1140
- * outbox table.
1141
- */
1142
- interface ServiceEvents {
1143
- /** Whether any listener wants the event, so a write can skip recording one. */
1144
- wants(name: string): boolean;
1595
+ get workflows(): {
1596
+ root: string;
1597
+ dir: string;
1598
+ world: EventsWorld;
1599
+ } | undefined;
1145
1600
  /**
1146
- * Run `fn` in a database transaction. Events it records are committed with
1147
- * 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.
1148
1603
  */
1149
- transaction<T>(db: unknown, context: {
1150
- traceId?: string;
1151
- source?: string;
1152
- }, fn: (tx: any, record: EventRecorder) => Promise<T>): Promise<T>;
1604
+ webhook(request: Request): Promise<Response>;
1153
1605
  /**
1154
- * Record an event in a transaction the caller already has open. It is
1155
- * committed with that transaction. Nothing tells Brick when the caller commits,
1156
- * 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.
1157
1609
  */
1158
- record(tx: unknown, context: {
1159
- traceId?: string;
1160
- source?: string;
1161
- }, name: string, payload: unknown): Promise<void>;
1162
- }
1163
- //#endregion
1164
- //#region src/events/dispatcher.d.ts
1165
- /** How many outbox rows are in each state. */
1166
- type OutboxCounts = Record<OutboxStatus, number>;
1167
- /**
1168
- * Delivers the events recorded in one outbox table to the app's listeners.
1169
- *
1170
- * It claims a batch of due rows, runs each listener, and marks the row delivered.
1171
- * A listener that throws is retried later with a growing delay, and parked as
1172
- * dead after its attempts run out. Several dispatchers can share a table: on
1173
- * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
1174
- * finished within `claimTimeoutMs` (the process died) is taken by another.
1175
- * Delivery is at least once, so a listener should tolerate running twice for the
1176
- * same `deliveryId`.
1177
- */
1178
- declare class Dispatcher {
1179
- private readonly db;
1180
- private readonly table;
1181
- private readonly listeners;
1182
- private readonly onError;
1183
- private readonly engine;
1184
- private readonly options;
1185
- private readonly inFlight;
1186
- private timer?;
1187
- private tickQueue?;
1188
- private lastPurge;
1189
- constructor(db: any, table: OutboxTable, listeners: (name: string) => Deliverable | undefined, options?: DispatchOptions, onError?: (error: unknown) => void);
1190
- /** Whether the dispatcher is looking for work on a timer. */
1191
- get running(): boolean;
1192
- /** Start looking for due deliveries on a timer. Does nothing if it already is. */
1193
1610
  start(): void;
1194
1611
  /**
1195
- * 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.
1196
1615
  */
1197
1616
  stop(): Promise<void>;
1198
- /** Look for work soon, without waiting for the timer. Safe to call often. */
1199
- notify(): void;
1617
+ private shutDown;
1200
1618
  /**
1201
- * 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
1202
1620
  * workers that drive delivery themselves.
1203
1621
  *
1204
- * @returns How many deliveries it started.
1205
- */
1206
- tick(): Promise<number>;
1207
- /**
1208
- * Deliver everything that is due now and wait until those deliveries are done.
1209
- * Deliveries that fail and are rescheduled are not waited for again.
1210
- *
1211
- * @returns How many deliveries it ran.
1622
+ * @returns How many deliveries ran.
1212
1623
  */
1213
1624
  drain(): Promise<number>;
1625
+ /** How many rows are in each state, across the app's outbox tables. */
1626
+ counts(): Promise<OutboxCounts>;
1214
1627
  /**
1215
- * How many rows are in each state.
1628
+ * Put parked deliveries back in line.
1629
+ *
1630
+ * @param deliveryId - One delivery. Omit it to retry every dead one.
1631
+ * @returns How many deliveries were put back.
1216
1632
  */
1217
- counts(): Promise<OutboxCounts>;
1633
+ retryDead(deliveryId?: string): Promise<number>;
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;
1218
1860
  /**
1219
- * Put parked deliveries back in line, with their attempts reset.
1220
- *
1221
- * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
1222
- * @returns How many deliveries were put back.
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).
1223
1864
  */
1224
- retryDead(deliveryId?: string): Promise<number>;
1225
- private claimAndRun;
1226
- private claim;
1227
- private deliver;
1228
- private markDelivered;
1229
- private fail;
1230
- private park;
1231
- private purgeDelivered;
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;
1232
1870
  }
1233
- //#endregion
1234
- //#region src/events/hub.d.ts
1235
- interface EventsHost {
1236
- readonly name: string;
1237
- getDb(): unknown;
1238
- getOutbox?(): OutboxTable | undefined;
1239
- 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;
1240
1874
  }
1241
1875
  /**
1242
- * Stop every events hub started in this process, by any copy of `@brickkit/core`,
1243
- * and wait for their deliveries. A hub that fails to stop does not cut the wait
1244
- * for the others: the first failure is thrown once every hub is done.
1245
- */
1246
- declare function stopAllEvents(): Promise<void>;
1247
- /**
1248
- * What an app's `events` option describes, as plain data. It goes in the app
1249
- * 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.
1250
1880
  */
1251
- interface EventsDefinition {
1252
- listeners: {
1253
- name: string;
1254
- on: string[];
1255
- kind: "handler" | "workflow";
1256
- }[];
1257
- dispatch: boolean;
1258
- /** Names of the services whose writes record events. */
1259
- recorders: string[];
1260
- }
1261
- /** What the dispatcher runs for a delivery. */
1262
- interface Deliverable {
1263
- readonly maxAttempts?: number;
1264
- run(delivery: EventDelivery): void | Promise<void>;
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;
1265
1891
  }
1266
- /**
1267
- * The events of one app: who listens, where events are recorded, and the
1268
- * dispatchers that deliver them. `brick({ events })` makes one and puts it on
1269
- * `app.events`.
1270
- */
1271
- declare class EventsHub {
1272
- private readonly byName;
1273
- private readonly dispatchers;
1274
- private readonly deliverables;
1275
- private readonly dispatchOptions;
1276
- private readonly runtime;
1277
- private readonly recorderNames;
1278
- private started;
1279
- private stopping;
1280
- constructor(options: EventsOptions);
1281
- /**
1282
- * Give each service whose database holds an outbox table a recorder, and a
1283
- * dispatcher for that table. Call it before the first request: a service has no
1284
- * recorder until then.
1285
- *
1286
- * @param services - The app's services.
1287
- * @returns The hub, for chaining.
1288
- */
1289
- attach(services: readonly EventsHost[]): this;
1290
- /** The listeners that want an event. */
1291
- matching(name: string): EventListener[];
1292
- /** The listeners and settings, as plain data. */
1293
- describe(): EventsDefinition;
1294
- /**
1295
- * Where the workflow bundle is read from, the project it is built from, and
1296
- * the world the workflows run on. Only set when a listener runs a workflow.
1297
- * The CLI builds the bundle there before events start, and shows the world's
1298
- * runs in the dev dashboard.
1299
- */
1300
- get workflows(): {
1301
- root: string;
1302
- dir: string;
1303
- world: EventsWorld;
1304
- } | undefined;
1305
- /**
1306
- * Resume the workflow that waits on a webhook. The server mounts this on the
1307
- * route the Workflow SDK puts in webhook URLs.
1308
- */
1309
- webhook(request: Request): Promise<Response>;
1310
- /**
1311
- * Start delivering recorded events from this process, and start the world that
1312
- * runs workflow listeners. Does nothing if this process only records events
1313
- * (`dispatch: false`), already started, or a stop is still waiting.
1314
- */
1315
- start(): void;
1316
- /**
1317
- * Stop delivering, wait for the deliveries that are running, and close the
1318
- * world. A world cannot be started again, so workflow listeners stop for good.
1319
- * A stop that arrives while another runs waits for that one.
1320
- */
1321
- stop(): Promise<void>;
1322
- private shutDown;
1323
- /**
1324
- * Deliver everything that is due now and wait for it. For tests and for
1325
- * workers that drive delivery themselves.
1326
- *
1327
- * @returns How many deliveries ran.
1328
- */
1329
- drain(): Promise<number>;
1330
- /** How many rows are in each state, across the app's outbox tables. */
1331
- counts(): Promise<OutboxCounts>;
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;
1332
1913
  /**
1333
- * Put parked deliveries back in line.
1334
- *
1335
- * @param deliveryId - One delivery. Omit it to retry every dead one.
1336
- * @returns How many deliveries were put back.
1914
+ * Add a table after definition, as `definePlugin` does for the tables a
1915
+ * plugin owns. Before `getDb()` it also joins the relational schema.
1337
1916
  */
1338
- retryDead(deliveryId?: string): Promise<number>;
1339
- private deliverable;
1340
- private bind;
1917
+ addTable?(key: string, table: Table): void;
1918
+ getDb(): TDb;
1919
+ close?(): void | Promise<void>;
1341
1920
  }
1921
+ /**
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.
1926
+ */
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>;
1342
1957
  //#endregion
1343
1958
  //#region src/socket-types.d.ts
1344
1959
  type SocketSchemas = Record<string, TSchema>;
@@ -1361,6 +1976,19 @@ interface BrickSocketConfig<I extends SocketSchemas, O extends SocketSchemas, Ct
1361
1976
  authorize?: (params: {
1362
1977
  ctx: Ctx;
1363
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;
1364
1992
  handlers: { [K in keyof I]: (params: {
1365
1993
  input: Static<I[K]>;
1366
1994
  ctx: Ctx;
@@ -1377,17 +2005,95 @@ interface BrickSocketConfig<I extends SocketSchemas, O extends SocketSchemas, Ct
1377
2005
  reason: string;
1378
2006
  }) => void | Promise<void>;
1379
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 {
2045
+ /**
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`.
2048
+ */
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";
1380
2069
  interface BrickSocketConnectOptions {
1381
2070
  signal?: AbortSignal;
2071
+ /** Limits each opening attempt. */
1382
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;
1383
2077
  }
1384
2078
  declare class BrickSocketError extends Error {
1385
- readonly kind: "connection" | "protocol" | "backpressure";
1386
- constructor(kind: "connection" | "protocol" | "backpressure", message: string, options?: ErrorOptions);
2079
+ readonly kind: "connection" | "protocol" | "backpressure" | "refused";
2080
+ constructor(kind: "connection" | "protocol" | "backpressure" | "refused", message: string, options?: ErrorOptions);
1387
2081
  }
1388
2082
  interface BrickSocketClient<Input, Output> extends BrickSocketSender<Input> {
2083
+ /** Resolves on the first open; rejects if the client closes before it. */
1389
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;
1390
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;
1391
2097
  onError(listener: (error: BrickSocketError) => void): () => void;
1392
2098
  onClose(listener: (info: {
1393
2099
  code: number;
@@ -1424,8 +2130,11 @@ interface SocketSender {
1424
2130
  close(): void;
1425
2131
  }
1426
2132
  interface SocketSession {
2133
+ /** Server rooms, resolved from the handshake context. */
2134
+ rooms: readonly string[];
1427
2135
  open(socket: SocketSender): Promise<void>;
1428
2136
  message(event: string, data: unknown, socket: SocketSender): Promise<void>;
2137
+ join(room: string): Promise<boolean>;
1429
2138
  close(socket: SocketSender, code: number, reason: string): Promise<void>;
1430
2139
  }
1431
2140
  interface RegisteredSocket {
@@ -1434,6 +2143,13 @@ interface RegisteredSocket {
1434
2143
  output: SocketSchemas;
1435
2144
  allowedOrigins?: readonly string[];
1436
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;
1437
2153
  connect(request: Request): Promise<SocketSession>;
1438
2154
  }
1439
2155
  //#endregion
@@ -1489,7 +2205,13 @@ type NarrowAuthorizedContext<TCtx> = TCtx extends {
1489
2205
  interface ActionErrorDefinition {
1490
2206
  status?: number;
1491
2207
  message: string;
2208
+ /** Schema of the `details` the error carries. Checked in types only, not at runtime. */
2209
+ details?: TSchema;
1492
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;
1493
2215
  interface ValidationErrorItem {
1494
2216
  path: string;
1495
2217
  message: string;
@@ -1531,11 +2253,18 @@ interface StandardErrorMap {
1531
2253
  INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
1532
2254
  [key: string]: ((overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never) | undefined;
1533
2255
  }
1534
- 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; };
1535
2259
  interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
1536
2260
  name: string;
1537
2261
  description?: string;
1538
- /** 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
+ */
1539
2268
  path?: string;
1540
2269
  /** Single HTTP method exposed for this action (default POST). */
1541
2270
  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
@@ -1638,6 +2367,20 @@ interface ResourceConfig<TTable = any, _TCtx = any> {
1638
2367
  name: string;
1639
2368
  table: TTable;
1640
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;
1641
2384
  }
1642
2385
  type InferTableRow<TTable> = TTable extends {
1643
2386
  $inferSelect: infer S;
@@ -1645,7 +2388,7 @@ type InferTableRow<TTable> = TTable extends {
1645
2388
  type InferTableInsert<TTable> = TTable extends {
1646
2389
  $inferInsert: infer S;
1647
2390
  } ? S : any;
1648
- type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id">;
2391
+ type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id" | "children">;
1649
2392
  type PrimaryColumn<T> = T extends {
1650
2393
  _: {
1651
2394
  columns: infer C;
@@ -1666,7 +2409,7 @@ interface PreparationContribution {
1666
2409
  describe(): unknown;
1667
2410
  prepare(): void;
1668
2411
  }
1669
- interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}> {
2412
+ interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}, TEvents extends EventCatalog = EventCatalog> {
1670
2413
  use<P extends ResourcePlugin<Service<TCtx["db"], Omit<TCtx, keyof BaseContext>>, this, any>>(plugin: P): this & ResourcePluginAPI<P, TTable, TCtx, this>;
1671
2414
  readonly name: string;
1672
2415
  readonly serviceName: string;
@@ -1676,6 +2419,139 @@ interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOp
1676
2419
  } ? I : import("drizzle-orm").Column;
1677
2420
  readonly idField: string;
1678
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);
1679
2555
  }
1680
2556
  interface ServiceAuthOptions {
1681
2557
  requireAuth?: boolean;
@@ -1717,6 +2593,11 @@ interface LifecycleOptions {
1717
2593
  }
1718
2594
  interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
1719
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;
1720
2601
  context?: (baseCtx: BaseContext<TDb> & {
1721
2602
  user?: unknown;
1722
2603
  }) => Promise<TServiceContext> | TServiceContext;
@@ -1726,6 +2607,11 @@ interface ServiceOptions<TServiceContext extends Record<string, any> = Record<st
1726
2607
  resilience?: ResilienceOptions;
1727
2608
  telemetry?: TelemetryOptions;
1728
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;
1729
2615
  }
1730
2616
  type ActionAccessPolicy = "public" | "authorized" | "scoped";
1731
2617
  interface ActionSchema {
@@ -1757,6 +2643,8 @@ interface ServiceSchema {
1757
2643
  name?: string;
1758
2644
  engine: "sqlite" | "postgres";
1759
2645
  tables: string[];
2646
+ /** The plugin that owns each table it contributed, by table key. */
2647
+ plugins?: Record<string, string>;
1760
2648
  };
1761
2649
  actions: ActionSchema[];
1762
2650
  sockets?: BrickSocketSchema[];
@@ -1764,6 +2652,12 @@ interface ServiceSchema {
1764
2652
  tools?: {
1765
2653
  name: string;
1766
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
+ }[];
1767
2661
  resources?: {
1768
2662
  name: string;
1769
2663
  }[];
@@ -1773,6 +2667,8 @@ interface ArchitectureSchema {
1773
2667
  services: ServiceSchema[];
1774
2668
  /** Present when the app has an `events` option. */
1775
2669
  events?: EventsDefinition;
2670
+ /** Every `definePlugin` installation, with its dashboard extension. */
2671
+ plugins?: InstalledPlugin[];
1776
2672
  }
1777
2673
  interface CompiledRoutePlan {
1778
2674
  service: Service<any, any>;
@@ -1806,8 +2702,10 @@ interface CompiledRoutePlan {
1806
2702
  errorBuilder: any;
1807
2703
  cachedDb: any;
1808
2704
  }
1809
- 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> {
1810
2706
  readonly name: string;
2707
+ /** The declared events, as handles for `defineListener` and `emitEvent`. */
2708
+ readonly events: EventRefs<TEvents>;
1811
2709
  readonly options: ServiceOptions<TServiceContext, TDb>;
1812
2710
  readonly actions: Map<string, Action<any, any, any, any>>;
1813
2711
  readonly tools: Map<string, Tool<any, any, any, any>>;
@@ -1817,7 +2715,7 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
1817
2715
  readonly isBuilt?: boolean;
1818
2716
  use<A>(plugin: ServicePlugin<this, A>): A;
1819
2717
  build(): this;
1820
- socket<const I extends SocketSchemas, const O extends SocketSchemas>(config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext>): this;
2718
+ socket<const I extends SocketSchemas, const O extends SocketSchemas>(config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext>): BrickSocketHandle<SocketPayloads<O>>;
1821
2719
  listSockets(): RegisteredSocket[];
1822
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;
1823
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>;
@@ -1825,7 +2723,7 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
1825
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;
1826
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>;
1827
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>;
1828
- 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>;
1829
2727
  readonly preparations: Map<string, PreparationContribution>;
1830
2728
  contributePreparation(contribution: PreparationContribution): void;
1831
2729
  listPreparations(): PreparationContribution[];
@@ -1838,17 +2736,21 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
1838
2736
  getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
1839
2737
  listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
1840
2738
  getDb(): TDb | undefined;
2739
+ /** The handle from `defineDatabase`, without connecting. */
2740
+ getDatabaseHandle?(): DatabaseHandle<TDb> | undefined;
1841
2741
  setDb(database: DatabaseHandle<TDb>): void;
1842
2742
  /** The outbox table of this service's database, if it holds one (see `outboxTable`). */
1843
2743
  getOutbox?(): OutboxTable | undefined;
1844
2744
  /** What a write needs to record events. Set by `brick({ events })`; absent otherwise. */
1845
- readonly events?: ServiceEvents;
1846
- 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;
1847
2750
  resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
1848
2751
  introspect(): ServiceSchema;
1849
2752
  }
1850
2753
  interface ProxyOptions {
1851
- isMonolith?: boolean;
1852
2754
  /** Name of the service creating this proxy. Populates ctx.caller on the target's envelope. */
1853
2755
  from?: string;
1854
2756
  context?: Partial<ActionContext>;
@@ -1906,8 +2808,10 @@ interface ProxyOptions {
1906
2808
  * | Client call | HTTP request |
1907
2809
  * |---|---|
1908
2810
  * Generated browser contracts carry each action's HTTP method and path,
1909
- * including plugin routes and consumer overrides. Without runtime metadata,
1910
- * 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.
1911
2815
  * GET/DELETE input is serialized as a query string; other methods send JSON.
1912
2816
 
1913
2817
  */
@@ -1937,6 +2841,11 @@ interface BrickClientOptions {
1937
2841
  */
1938
2842
  contract?: Record<string, any>;
1939
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 {}
1940
2849
  /** Browser-safe action metadata generated by the Brick Vite plugin. */
1941
2850
  interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}> {
1942
2851
  kind: "action";
@@ -2076,5 +2985,5 @@ declare function createBrickClient<TApp extends Record<string, any>>(options: Br
2076
2985
  }): BrickClient<TApp>;
2077
2986
  declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
2078
2987
  //#endregion
2079
- export { ToolConfigWithoutAuthorize as $, overrideSecret as $t, ErrorBuilder as A, getPluginActionRoute as An, WorkflowsOptions as At, Resource as B, PostgresDefinition as Bt, ActionSchema as C, ResourcePluginAPI as Cn, EventListener as Ct, CacheOptions as D, ServicePluginContext as Dn, EventsWorld as Dt, BaseContext as E, ServicePlugin as En, EventsOptions as Et, NarrowAuthorizedContext as F, isOutboxTable as Ft, ServiceAuthOptions as G, PostgresDatabase as Gt, ResourceIdentity as H, defineDatabase as Ht, PreparationContribution as I, outboxTable as It, StandardErrorMap as J, SecretOptions as Jt, ServiceOptions as K, PostgresDatabaseConfig as Kt, ProxyOptions as L, DatabaseDefinition as Lt, InferTableRow as M, OutboxTable as Mt, LifecycleOptions as N, PostgresOutboxTable as Nt, CompiledRoutePlan as O, defineResourcePlugin as On, ServiceEvents as Ot, Logger as P, SQLiteOutboxTable as Pt, ToolConfigWithAuthorize as Q, listSecrets as Qt, RateLimitOptions as R, DatabaseHandle as Rt, ActionExecutionError as S, ResourcePlugin as Sn, EventEnvelope as St, BaseActionConfig as T, ResourcePluginTypes as Tn, EventWorkflow as Tt, ResourceTypeOptions as U, isDatabaseHandle as Ut, ResourceConfig as V, SQLiteDefinition as Vt, Service as W, DatabaseAdapter as Wt, Tool as X, SecretSource as Xt, TelemetryOptions as Y, SecretRef as Yt, ToolAnnotations as Z, envSource as Zt, ActionConfig as _, PluginEndpointContext as _n, Dispatcher as _t, BrickClientOptions as a, BunSQLiteDatabase$1 as an, BrickSocketClient as at, ActionContext as b, PluginRouteScope as bn, DispatchOptions as bt, InferActionErrorCodes as c, createSQLiteDatabase as cn, BrickSocketError as ct, InferActionOutput as d, integer$1 as dn, SocketEventArgs as dt, overrideSecrets as en, ToolOptions as et, createBrickClient as f, primaryKey as fn, SocketPayloads as ft, ActionAccessPolicy as g, uniqueIndex as gn, stopAllEvents as gt, Action as h, text$1 as hn, EventsHub as ht, BrickClientAction as i, BrickSQLiteDatabase as in, BrickClientSocket as it, InferTableInsert as j, getPluginEndpoints as jn, OutboxStatus as jt, DefaultServiceContext as k, defineServicePlugin as kn, WorkflowEvent as kt, InferActionFailure as l, foreignKey as ln, BrickSocketSchema as lt, isBrickTransportError as m, sqliteTable$1 as mn, EventsDefinition as mt, BrickCallOptions as n, resolveSecrets as nn, ValidationErrorItem as nt, BrickServerError as o, SQLiteDatabaseConfig as on, BrickSocketConfig as ot, isBrickServerError as p, real as pn, SocketSchemas as pt, ServiceSchema as q, createPostgresDatabase as qt, BrickClient as r, secret as rn, RegisteredSocket as rt, BrickTransportError as s, blob as sn, BrickSocketConnectOptions as st, BrickActionCaller as t, resetSecrets as tn, ValidationError as tt, InferActionInput as u, index$1 as un, BrickSocketSender as ut, ActionConfigWithAuthorize as v, PluginRouteMethod as vn, OutboxCounts as vt, ArchitectureSchema as w, ResourcePluginContext as wn, EventRecorder as wt, ActionErrorDefinition as x, PluginRoutes as xn, EventDelivery as xt, ActionConfigWithoutAuthorize as y, PluginRouteRegistrar as yn, CrudEventPayload as yt, ResilienceOptions as z, EnvInput 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 };
2080
2989
  //# sourceMappingURL=client.d.ts.map