@brickkit/core 0.11.0 → 0.13.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,2762 +1,51 @@
1
- import { Static, TIntersect, TNumber, TObject, TSchema, TString, TUnion } from "@sinclair/typebox";
2
- import { Table } from "drizzle-orm";
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
- import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
6
- import { Sql } from "postgres";
7
- import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
8
- import { Database } from "bun:sqlite";
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; };
19
- /**
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).
23
- *
24
- * @returns A slot typed as `T`. It holds nothing at runtime.
25
- * @example
26
- * import { defineService, port } from "@brickkit/core";
27
- *
28
- * export const orders = defineService("orders", {
29
- * database,
30
- * deps: { carrier: port<Carrier>() },
31
- * });
32
- *
33
- * // app.ts
34
- * export default brick({ services: [orders], deps: { carrier: createCarrier() } });
35
- */
36
- declare function port<T>(): Port<T>;
37
- /**
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.
40
- *
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 })`.
44
- *
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>() };
51
- *
52
- * async function bookCarrier(orderId: string) {
53
- * "use step";
54
- * return useDeps(ordersDeps).carrier.book(orderId);
55
- * }
56
- */
57
- declare function useDeps<const P extends Ports>(ports: P): DepsOf<P>;
58
- declare function useDeps<T = Record<string, unknown>>(): T;
59
- //#endregion
60
- //#region src/events/catalog.d.ts
61
- /** A service's declared events: payload schema by event name. */
62
- type EventCatalog = Record<string, TSchema>;
63
- /**
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.
66
- */
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;
80
- //#endregion
81
- //#region src/events/types.d.ts
82
- /**
83
- * An event, as it was recorded. It is the same for every listener of it.
84
- */
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;
98
- }
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;
106
- /**
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.
109
- */
110
- deliveryId: string;
111
- /** 1 on the first try, 2 on the first retry, and so on. */
112
- attempt: number;
113
- }
114
- /**
115
- * The CRUD events of a resource called `user`, by operation. Listeners of
116
- * `user.create`, `user.update` and `user.delete` receive these payloads.
117
- */
118
- type CrudEventPayload<TRow = Record<string, unknown>> = {
119
- id: unknown;
120
- row: TRow;
121
- } | {
122
- id: unknown;
123
- before: TRow;
124
- after: TRow;
125
- };
126
- /**
127
- * What `retry` receives: one member per error the listener declares, or the
128
- * fallback for anything else it threw.
129
- */
130
- type ListenerFailure<TErrors extends Record<string, ActionErrorDefinition>> = { [K in keyof TErrors & string]: {
131
- code: K;
132
- message: string;
133
- details: ErrorDetails<TErrors[K]>;
134
- }; }[keyof TErrors & string] | {
135
- code: "UNKNOWN";
136
- message: string;
137
- cause: unknown;
138
- };
139
- /** What a listener's `retry` decides: try again later, or park the delivery as dead now. */
140
- type RetryDecision = "retry" | "dead";
141
- /**
142
- * A listener: code that runs when an event it listens for has been recorded.
143
- */
144
- interface EventListener<TPayload = any> {
145
- /** Unique among the app's listeners. It is part of each delivery's id. */
146
- readonly name: string;
147
- /**
148
- * The event names to listen for. A trailing `*` matches a prefix (`user.*`),
149
- * and `*` alone matches every event.
150
- */
151
- readonly on: readonly string[];
152
- /**
153
- * A handler that runs in the dispatching process for each delivery. Throwing
154
- * retries the delivery with a growing delay. A listener has this or `workflow`.
155
- */
156
- readonly run?: (delivery: EventDelivery<TPayload>) => void | Promise<void>;
157
- /**
158
- * Decides what a failed delivery does next. Without it, every failure retries
159
- * until `maxAttempts`. It cannot extend the attempts: `"retry"` still parks the
160
- * delivery as dead once they run out.
161
- */
162
- readonly errors?: Record<string, ActionErrorDefinition>;
163
- readonly retry?: (error: ListenerFailure<any>) => RetryDecision;
164
- /**
165
- * A durable workflow that runs for each delivery, on the app's `events.world`.
166
- * The delivery counts as done once its run has started; the workflow retries
167
- * its own steps from there. A listener has this or `run`.
168
- */
169
- readonly workflow?: EventWorkflow<TPayload>;
170
- /** Attempts before the delivery is parked as dead. Defaults to the dispatcher's. */
171
- readonly maxAttempts?: number;
172
- }
173
- /**
174
- * What a workflow listener's workflow receives: the event and which listener it
175
- * is for. It has no `attempt`, because one delivery starts one run however many
176
- * times it is tried.
177
- */
178
- type WorkflowEvent<TPayload = any> = Omit<EventDelivery<TPayload>, "attempt">;
179
- /**
180
- * A function marked `"use workflow"`, run once per delivery of the listener it is
181
- * given to.
182
- */
183
- type EventWorkflow<TPayload = any> = (event: WorkflowEvent<TPayload>) => Promise<unknown>;
184
- /**
185
- * The world workflow listeners run on: the queue and storage behind the Workflow
186
- * SDK. `createWorld()` from `@brickkit/redis-world` or `@brickkit/bullmq-world`
187
- * makes one. Brick starts it with the app's events and closes it when they stop.
188
- */
189
- interface EventsWorld {
190
- /**
191
- * Names a run after its key so that starting it twice makes one run. A world
192
- * without it would start a second run when an event is delivered again, so
193
- * Brick refuses such a world.
194
- */
195
- createRunId?(options?: Readonly<Record<string, unknown>>): string;
196
- start?(): Promise<void>;
197
- close?(): Promise<void>;
198
- registerHandler?(prefix: any, handler: (request: Request) => Promise<Response>): void;
199
- }
200
- /**
201
- * Where the workflows of an app are built from. The CLI (`brick dev`,
202
- * `brick start`) writes the bundle to `<root>/.well-known/workflow/v1` before
203
- * events start, and events read it from there.
204
- */
205
- interface WorkflowsOptions {
206
- /** The project root: where the Workflow SDK is installed. Default: the working directory. */
207
- root?: string;
208
- }
209
- /**
210
- * How the dispatcher delivers recorded events.
211
- */
212
- interface DispatchOptions {
213
- /**
214
- * Whether to look for due deliveries on a timer, and right after a commit.
215
- * Default `true`. With `false`, deliveries run only when something calls
216
- * `app.events.drain()`: a cron job, a worker you drive yourself, or a test.
217
- */
218
- timer?: boolean;
219
- /** How often to look for deliveries that are due, in milliseconds. Default 1000. */
220
- intervalMs?: number;
221
- /** Most deliveries claimed at once. Default 50. */
222
- batchSize?: number;
223
- /** Attempts before a delivery is parked as dead. Default 8. */
224
- maxAttempts?: number;
225
- /** How long a claimed delivery may run before another dispatcher takes it, in milliseconds. Default 60000. */
226
- claimTimeoutMs?: number;
227
- /** Longest wait before a retry, in milliseconds. Default 300000. */
228
- maxBackoffMs?: number;
229
- /** How long delivered rows are kept, in milliseconds. Default 86400000 (one day). 0 keeps none. */
230
- retainDeliveredMs?: number;
231
- }
232
- /**
233
- * The `events` option of `brick()`.
234
- */
235
- interface EventsOptions {
236
- /** The listeners of the app. */
237
- listeners?: readonly EventListener[];
238
- /**
239
- * Whether this process delivers recorded events. `true` (the default) starts a
240
- * dispatcher with the default settings, an object tunes it, and `false` only
241
- * records events, for an app whose events are delivered by another process.
242
- */
243
- dispatch?: boolean | DispatchOptions;
244
- /**
245
- * The world that runs `workflow` listeners. Required when any listener has one.
246
- * Brick starts it when the app's events start and closes it when they stop.
247
- */
248
- world?: EventsWorld;
249
- /** Where the workflow bundle lives. Only used with workflow listeners. */
250
- workflows?: WorkflowsOptions;
251
- }
252
- /**
253
- * Records an event inside the transaction it was given. The event is committed
254
- * with the write, or not at all.
255
- */
256
- type EventRecorder = (name: string, payload: unknown) => Promise<void>;
257
- /**
258
- * What a service with events offers the code that writes to its database. A
259
- * service has it once `brick({ events })` is set up and its database holds an
260
- * outbox table.
261
- */
262
- interface ServiceEvents {
263
- /** Whether any listener wants the event, so a write can skip recording one. */
264
- wants(name: string): boolean;
265
- /**
266
- * Run `fn` in a database transaction. Events it records are committed with
267
- * whatever else it wrote, or not at all, and are delivered after the commit.
268
- */
269
- transaction<T>(db: unknown, context: {
270
- traceId?: string;
271
- source?: string;
272
- }, fn: (tx: any, record: EventRecorder) => Promise<T>): Promise<T>;
273
- /**
274
- * Record an event in a transaction the caller already has open. It is
275
- * committed with that transaction. Nothing tells Brick when the caller commits,
276
- * so delivery waits for the dispatcher's next poll.
277
- */
278
- record(tx: unknown, context: {
279
- traceId?: string;
280
- source?: string;
281
- }, name: string, payload: unknown): Promise<void>;
282
- }
283
- //#endregion
284
- //#region src/secrets.d.ts
285
- /**
286
- * Type-safe secrets & environment variables.
287
- *
288
- * Declare each secret once at module scope instead of scattering untyped
289
- * `process.env.FOO` reads:
290
- *
291
- * const port = defineSecret("PORT").default("3333").transform(Number).require();
292
- * const baseUrl = defineSecret("BASE_URL").url().require();
293
- * const key = defineSecret("STRIPE_KEY").validate((v) =>
294
- * v.startsWith("sk_") || "must start with sk_"
295
- * ).require();
296
- *
297
- * Values resolve from the environment (Bun populates `process.env` from
298
- * `.env` locally; in prod the same env source applies — a future
299
- * `SecretSource` such as AWS can slot in without touching call sites).
300
- *
301
- * Resolution order per secret: test/session override → source (`process.env`
302
- * by default) → declared `default`. `resolveSecrets()` validates every
303
- * registered secret at boot and throws listing all missing required ones.
304
- */
305
- interface SecretSource {
306
- get(name: string): string | undefined;
307
- }
308
- /** Default source: `process.env` (Bun loads `.env` into it automatically). */
309
- declare const envSource: SecretSource;
310
- interface SecretOptions {
311
- /** Fallback when the source has no value. Secrets without a default are required. */
312
- default?: string;
313
- }
314
- /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
315
- type SecretValidator<T> = (value: T) => void | boolean | string;
316
- declare class SecretRef<T = string> {
317
- readonly name: string;
318
- readonly options: SecretOptions;
319
- private transformFn?;
320
- private validators;
321
- constructor(name: string, options?: SecretOptions);
322
- /** True when a default was declared (i.e. the secret is optional). */
323
- get hasDefault(): boolean;
324
- /** Fallback used when the source has no value. Makes the secret optional. */
325
- default(value: string): this;
326
- /**
327
- * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
328
- * Runs before validators; a throwing transform fails resolution.
329
- */
330
- transform<U>(fn: (raw: string) => U): SecretRef<U>;
331
- /** Run a custom check on the (transformed) value at every resolution. */
332
- validate(fn: SecretValidator<T>): this;
333
- /** Shorthand validator: value must parse as a URL. String refs only. */
334
- url(this: SecretRef<string>): SecretRef<string>;
335
- private resolveRaw;
336
- private coerce;
337
- /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
338
- value(source?: SecretSource): T | undefined;
339
- /** Resolved value, or throws naming the missing/invalid secret. */
340
- require(source?: SecretSource): T;
341
- /** True when a value would resolve (override, source, or default). */
342
- isSet(source?: SecretSource): boolean;
343
- }
344
- /**
345
- * Declare a secret. Idempotent: re-declaring the same name returns the
346
- * original ref (first declaration wins) so module re-evaluation is safe.
347
- */
348
- declare function defineSecret(name: string, options?: SecretOptions): SecretRef<string>;
349
- /**
350
- * Validate every registered secret at boot. Throws a single error listing
351
- * all missing required secrets. Returns the resolved values.
352
- */
353
- declare function resolveSecrets(opts?: {
354
- source?: SecretSource;
355
- }): Record<string, unknown>;
356
- /** Metadata for introspection (values never exposed — future dashboard use). */
357
- declare function listSecrets(opts?: {
358
- source?: SecretSource;
359
- }): Array<{
360
- name: string;
361
- hasDefault: boolean;
362
- isSet: boolean;
363
- }>;
364
- /** Test/session override for one secret (`undefined` clears the override). */
365
- declare function overrideSecret(name: string, value: string | undefined): void;
366
- /** Bulk overrides (test/session scoped). */
367
- declare function overrideSecrets(values: Record<string, string | undefined>): void;
368
- /** Clear registry and overrides. Test-only. */
369
- declare function resetSecrets(): void;
370
- //#endregion
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;
374
- /**
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.
377
- */
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>;
514
- };
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. */
522
- readonly engine: "sqlite" | "postgres";
523
- };
524
- interface HookBase<C> {
525
- ctx: C;
526
- /** The write's open transaction: write other tables through it. */
527
- tx: any;
528
- }
529
- /**
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.
699
- *
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());
725
- */
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
- });
759
- /**
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 } })`.
763
- *
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.
771
- *
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`.
783
- * @example
784
- * import { brick, defineListener } from "@brickkit/core";
785
- *
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
- * },
792
- * });
793
- *
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
- * });
810
- */
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>;
859
- //#endregion
860
- //#region src/events/outbox.d.ts
861
- /** What the outbox rows are in, by state. */
862
- type OutboxStatus = "pending" | "claimed" | "delivered" | "dead";
863
- declare function sqliteOutbox(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
864
- name: string;
865
- schema: undefined;
866
- columns: {
867
- seq: import("drizzle-orm/sqlite-core").SQLiteColumn<{
868
- name: "seq";
869
- tableName: string;
870
- dataType: "number";
871
- columnType: "SQLiteInteger";
872
- data: number;
873
- driverParam: number;
874
- notNull: true;
875
- hasDefault: true;
876
- isPrimaryKey: true;
877
- isAutoincrement: false;
878
- hasRuntimeDefault: false;
879
- enumValues: undefined;
880
- baseColumn: never;
881
- identity: undefined;
882
- generated: undefined;
883
- }, {}, {}>;
884
- id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
885
- name: "id";
886
- tableName: string;
887
- dataType: "string";
888
- columnType: "SQLiteText";
889
- data: string;
890
- driverParam: string;
891
- notNull: true;
892
- hasDefault: false;
893
- isPrimaryKey: false;
894
- isAutoincrement: false;
895
- hasRuntimeDefault: false;
896
- enumValues: [string, ...string[]];
897
- baseColumn: never;
898
- identity: undefined;
899
- generated: undefined;
900
- }, {}, {
901
- length: number | undefined;
902
- }>;
903
- eventId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
904
- name: "event_id";
905
- tableName: string;
906
- dataType: "string";
907
- columnType: "SQLiteText";
908
- data: string;
909
- driverParam: string;
910
- notNull: true;
911
- hasDefault: false;
912
- isPrimaryKey: false;
913
- isAutoincrement: false;
914
- hasRuntimeDefault: false;
915
- enumValues: [string, ...string[]];
916
- baseColumn: never;
917
- identity: undefined;
918
- generated: undefined;
919
- }, {}, {
920
- length: number | undefined;
921
- }>;
922
- listener: import("drizzle-orm/sqlite-core").SQLiteColumn<{
923
- name: "listener";
924
- tableName: string;
925
- dataType: "string";
926
- columnType: "SQLiteText";
927
- data: string;
928
- driverParam: string;
929
- notNull: true;
930
- hasDefault: false;
931
- isPrimaryKey: false;
932
- isAutoincrement: false;
933
- hasRuntimeDefault: false;
934
- enumValues: [string, ...string[]];
935
- baseColumn: never;
936
- identity: undefined;
937
- generated: undefined;
938
- }, {}, {
939
- length: number | undefined;
940
- }>;
941
- name: import("drizzle-orm/sqlite-core").SQLiteColumn<{
942
- name: "name";
943
- tableName: string;
944
- dataType: "string";
945
- columnType: "SQLiteText";
946
- data: string;
947
- driverParam: string;
948
- notNull: true;
949
- hasDefault: false;
950
- isPrimaryKey: false;
951
- isAutoincrement: false;
952
- hasRuntimeDefault: false;
953
- enumValues: [string, ...string[]];
954
- baseColumn: never;
955
- identity: undefined;
956
- generated: undefined;
957
- }, {}, {
958
- length: number | undefined;
959
- }>;
960
- payload: import("drizzle-orm/sqlite-core").SQLiteColumn<{
961
- name: "payload";
962
- tableName: string;
963
- dataType: "json";
964
- columnType: "SQLiteTextJson";
965
- data: unknown;
966
- driverParam: string;
967
- notNull: true;
968
- hasDefault: false;
969
- isPrimaryKey: false;
970
- isAutoincrement: false;
971
- hasRuntimeDefault: false;
972
- enumValues: undefined;
973
- baseColumn: never;
974
- identity: undefined;
975
- generated: undefined;
976
- }, {}, {}>;
977
- traceId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
978
- name: "trace_id";
979
- tableName: string;
980
- dataType: "string";
981
- columnType: "SQLiteText";
982
- data: string;
983
- driverParam: string;
984
- notNull: false;
985
- hasDefault: false;
986
- isPrimaryKey: false;
987
- isAutoincrement: false;
988
- hasRuntimeDefault: false;
989
- enumValues: [string, ...string[]];
990
- baseColumn: never;
991
- identity: undefined;
992
- generated: undefined;
993
- }, {}, {
994
- length: number | undefined;
995
- }>;
996
- source: import("drizzle-orm/sqlite-core").SQLiteColumn<{
997
- name: "source";
998
- tableName: string;
999
- dataType: "string";
1000
- columnType: "SQLiteText";
1001
- data: string;
1002
- driverParam: string;
1003
- notNull: false;
1004
- hasDefault: false;
1005
- isPrimaryKey: false;
1006
- isAutoincrement: false;
1007
- hasRuntimeDefault: false;
1008
- enumValues: [string, ...string[]];
1009
- baseColumn: never;
1010
- identity: undefined;
1011
- generated: undefined;
1012
- }, {}, {
1013
- length: number | undefined;
1014
- }>;
1015
- occurredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1016
- name: string;
1017
- tableName: string;
1018
- dataType: "date";
1019
- columnType: "SQLiteTimestamp";
1020
- data: Date;
1021
- driverParam: number;
1022
- notNull: true;
1023
- hasDefault: false;
1024
- isPrimaryKey: false;
1025
- isAutoincrement: false;
1026
- hasRuntimeDefault: false;
1027
- enumValues: undefined;
1028
- baseColumn: never;
1029
- identity: undefined;
1030
- generated: undefined;
1031
- }, {}, {}>;
1032
- status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1033
- name: "status";
1034
- tableName: string;
1035
- dataType: "string";
1036
- columnType: "SQLiteText";
1037
- data: OutboxStatus;
1038
- driverParam: string;
1039
- notNull: true;
1040
- hasDefault: false;
1041
- isPrimaryKey: false;
1042
- isAutoincrement: false;
1043
- hasRuntimeDefault: false;
1044
- enumValues: [string, ...string[]];
1045
- baseColumn: never;
1046
- identity: undefined;
1047
- generated: undefined;
1048
- }, {}, {
1049
- length: number | undefined;
1050
- $type: OutboxStatus;
1051
- }>;
1052
- attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1053
- name: "attempts";
1054
- tableName: string;
1055
- dataType: "number";
1056
- columnType: "SQLiteInteger";
1057
- data: number;
1058
- driverParam: number;
1059
- notNull: true;
1060
- hasDefault: true;
1061
- isPrimaryKey: false;
1062
- isAutoincrement: false;
1063
- hasRuntimeDefault: false;
1064
- enumValues: undefined;
1065
- baseColumn: never;
1066
- identity: undefined;
1067
- generated: undefined;
1068
- }, {}, {}>;
1069
- lastError: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1070
- name: "last_error";
1071
- tableName: string;
1072
- dataType: "string";
1073
- columnType: "SQLiteText";
1074
- data: string;
1075
- driverParam: string;
1076
- notNull: false;
1077
- hasDefault: false;
1078
- isPrimaryKey: false;
1079
- isAutoincrement: false;
1080
- hasRuntimeDefault: false;
1081
- enumValues: [string, ...string[]];
1082
- baseColumn: never;
1083
- identity: undefined;
1084
- generated: undefined;
1085
- }, {}, {
1086
- length: number | undefined;
1087
- }>;
1088
- availableAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1089
- name: string;
1090
- tableName: string;
1091
- dataType: "date";
1092
- columnType: "SQLiteTimestamp";
1093
- data: Date;
1094
- driverParam: number;
1095
- notNull: true;
1096
- hasDefault: false;
1097
- isPrimaryKey: false;
1098
- isAutoincrement: false;
1099
- hasRuntimeDefault: false;
1100
- enumValues: undefined;
1101
- baseColumn: never;
1102
- identity: undefined;
1103
- generated: undefined;
1104
- }, {}, {}>;
1105
- claimedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1106
- name: string;
1107
- tableName: string;
1108
- dataType: "date";
1109
- columnType: "SQLiteTimestamp";
1110
- data: Date;
1111
- driverParam: number;
1112
- notNull: false;
1113
- hasDefault: false;
1114
- isPrimaryKey: false;
1115
- isAutoincrement: false;
1116
- hasRuntimeDefault: false;
1117
- enumValues: undefined;
1118
- baseColumn: never;
1119
- identity: undefined;
1120
- generated: undefined;
1121
- }, {}, {}>;
1122
- deliveredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1123
- name: string;
1124
- tableName: string;
1125
- dataType: "date";
1126
- columnType: "SQLiteTimestamp";
1127
- data: Date;
1128
- driverParam: number;
1129
- notNull: false;
1130
- hasDefault: false;
1131
- isPrimaryKey: false;
1132
- isAutoincrement: false;
1133
- hasRuntimeDefault: false;
1134
- enumValues: undefined;
1135
- baseColumn: never;
1136
- identity: undefined;
1137
- generated: undefined;
1138
- }, {}, {}>;
1139
- };
1140
- dialect: "sqlite";
1141
- }>;
1142
- declare function postgresOutbox(name: string): import("drizzle-orm/pg-core").PgTableWithColumns<{
1143
- name: string;
1144
- schema: undefined;
1145
- columns: {
1146
- seq: import("drizzle-orm/pg-core").PgColumn<{
1147
- name: "seq";
1148
- tableName: string;
1149
- dataType: "number";
1150
- columnType: "PgBigSerial53";
1151
- data: number;
1152
- driverParam: number;
1153
- notNull: true;
1154
- hasDefault: true;
1155
- isPrimaryKey: true;
1156
- isAutoincrement: false;
1157
- hasRuntimeDefault: false;
1158
- enumValues: undefined;
1159
- baseColumn: never;
1160
- identity: undefined;
1161
- generated: undefined;
1162
- }, {}, {}>;
1163
- id: import("drizzle-orm/pg-core").PgColumn<{
1164
- name: "id";
1165
- tableName: string;
1166
- dataType: "string";
1167
- columnType: "PgText";
1168
- data: string;
1169
- driverParam: string;
1170
- notNull: true;
1171
- hasDefault: false;
1172
- isPrimaryKey: false;
1173
- isAutoincrement: false;
1174
- hasRuntimeDefault: false;
1175
- enumValues: [string, ...string[]];
1176
- baseColumn: never;
1177
- identity: undefined;
1178
- generated: undefined;
1179
- }, {}, {}>;
1180
- eventId: import("drizzle-orm/pg-core").PgColumn<{
1181
- name: "event_id";
1182
- tableName: string;
1183
- dataType: "string";
1184
- columnType: "PgText";
1185
- data: string;
1186
- driverParam: string;
1187
- notNull: true;
1188
- hasDefault: false;
1189
- isPrimaryKey: false;
1190
- isAutoincrement: false;
1191
- hasRuntimeDefault: false;
1192
- enumValues: [string, ...string[]];
1193
- baseColumn: never;
1194
- identity: undefined;
1195
- generated: undefined;
1196
- }, {}, {}>;
1197
- listener: import("drizzle-orm/pg-core").PgColumn<{
1198
- name: "listener";
1199
- tableName: string;
1200
- dataType: "string";
1201
- columnType: "PgText";
1202
- data: string;
1203
- driverParam: string;
1204
- notNull: true;
1205
- hasDefault: false;
1206
- isPrimaryKey: false;
1207
- isAutoincrement: false;
1208
- hasRuntimeDefault: false;
1209
- enumValues: [string, ...string[]];
1210
- baseColumn: never;
1211
- identity: undefined;
1212
- generated: undefined;
1213
- }, {}, {}>;
1214
- name: import("drizzle-orm/pg-core").PgColumn<{
1215
- name: "name";
1216
- tableName: string;
1217
- dataType: "string";
1218
- columnType: "PgText";
1219
- data: string;
1220
- driverParam: string;
1221
- notNull: true;
1222
- hasDefault: false;
1223
- isPrimaryKey: false;
1224
- isAutoincrement: false;
1225
- hasRuntimeDefault: false;
1226
- enumValues: [string, ...string[]];
1227
- baseColumn: never;
1228
- identity: undefined;
1229
- generated: undefined;
1230
- }, {}, {}>;
1231
- payload: import("drizzle-orm/pg-core").PgColumn<{
1232
- name: "payload";
1233
- tableName: string;
1234
- dataType: "json";
1235
- columnType: "PgJsonb";
1236
- data: unknown;
1237
- driverParam: unknown;
1238
- notNull: true;
1239
- hasDefault: false;
1240
- isPrimaryKey: false;
1241
- isAutoincrement: false;
1242
- hasRuntimeDefault: false;
1243
- enumValues: undefined;
1244
- baseColumn: never;
1245
- identity: undefined;
1246
- generated: undefined;
1247
- }, {}, {}>;
1248
- traceId: import("drizzle-orm/pg-core").PgColumn<{
1249
- name: "trace_id";
1250
- tableName: string;
1251
- dataType: "string";
1252
- columnType: "PgText";
1253
- data: string;
1254
- driverParam: string;
1255
- notNull: false;
1256
- hasDefault: false;
1257
- isPrimaryKey: false;
1258
- isAutoincrement: false;
1259
- hasRuntimeDefault: false;
1260
- enumValues: [string, ...string[]];
1261
- baseColumn: never;
1262
- identity: undefined;
1263
- generated: undefined;
1264
- }, {}, {}>;
1265
- source: import("drizzle-orm/pg-core").PgColumn<{
1266
- name: "source";
1267
- tableName: string;
1268
- dataType: "string";
1269
- columnType: "PgText";
1270
- data: string;
1271
- driverParam: string;
1272
- notNull: false;
1273
- hasDefault: false;
1274
- isPrimaryKey: false;
1275
- isAutoincrement: false;
1276
- hasRuntimeDefault: false;
1277
- enumValues: [string, ...string[]];
1278
- baseColumn: never;
1279
- identity: undefined;
1280
- generated: undefined;
1281
- }, {}, {}>;
1282
- occurredAt: import("drizzle-orm/pg-core").PgColumn<{
1283
- name: string;
1284
- tableName: string;
1285
- dataType: "date";
1286
- columnType: "PgTimestamp";
1287
- data: Date;
1288
- driverParam: string;
1289
- notNull: true;
1290
- hasDefault: false;
1291
- isPrimaryKey: false;
1292
- isAutoincrement: false;
1293
- hasRuntimeDefault: false;
1294
- enumValues: undefined;
1295
- baseColumn: never;
1296
- identity: undefined;
1297
- generated: undefined;
1298
- }, {}, {}>;
1299
- status: import("drizzle-orm/pg-core").PgColumn<{
1300
- name: "status";
1301
- tableName: string;
1302
- dataType: "string";
1303
- columnType: "PgText";
1304
- data: OutboxStatus;
1305
- driverParam: string;
1306
- notNull: true;
1307
- hasDefault: false;
1308
- isPrimaryKey: false;
1309
- isAutoincrement: false;
1310
- hasRuntimeDefault: false;
1311
- enumValues: [string, ...string[]];
1312
- baseColumn: never;
1313
- identity: undefined;
1314
- generated: undefined;
1315
- }, {}, {
1316
- $type: OutboxStatus;
1317
- }>;
1318
- attempts: import("drizzle-orm/pg-core").PgColumn<{
1319
- name: "attempts";
1320
- tableName: string;
1321
- dataType: "number";
1322
- columnType: "PgInteger";
1323
- data: number;
1324
- driverParam: string | number;
1325
- notNull: true;
1326
- hasDefault: true;
1327
- isPrimaryKey: false;
1328
- isAutoincrement: false;
1329
- hasRuntimeDefault: false;
1330
- enumValues: undefined;
1331
- baseColumn: never;
1332
- identity: undefined;
1333
- generated: undefined;
1334
- }, {}, {}>;
1335
- lastError: import("drizzle-orm/pg-core").PgColumn<{
1336
- name: "last_error";
1337
- tableName: string;
1338
- dataType: "string";
1339
- columnType: "PgText";
1340
- data: string;
1341
- driverParam: string;
1342
- notNull: false;
1343
- hasDefault: false;
1344
- isPrimaryKey: false;
1345
- isAutoincrement: false;
1346
- hasRuntimeDefault: false;
1347
- enumValues: [string, ...string[]];
1348
- baseColumn: never;
1349
- identity: undefined;
1350
- generated: undefined;
1351
- }, {}, {}>;
1352
- availableAt: import("drizzle-orm/pg-core").PgColumn<{
1353
- name: string;
1354
- tableName: string;
1355
- dataType: "date";
1356
- columnType: "PgTimestamp";
1357
- data: Date;
1358
- driverParam: string;
1359
- notNull: true;
1360
- hasDefault: false;
1361
- isPrimaryKey: false;
1362
- isAutoincrement: false;
1363
- hasRuntimeDefault: false;
1364
- enumValues: undefined;
1365
- baseColumn: never;
1366
- identity: undefined;
1367
- generated: undefined;
1368
- }, {}, {}>;
1369
- claimedAt: import("drizzle-orm/pg-core").PgColumn<{
1370
- name: string;
1371
- tableName: string;
1372
- dataType: "date";
1373
- columnType: "PgTimestamp";
1374
- data: Date;
1375
- driverParam: string;
1376
- notNull: false;
1377
- hasDefault: false;
1378
- isPrimaryKey: false;
1379
- isAutoincrement: false;
1380
- hasRuntimeDefault: false;
1381
- enumValues: undefined;
1382
- baseColumn: never;
1383
- identity: undefined;
1384
- generated: undefined;
1385
- }, {}, {}>;
1386
- deliveredAt: import("drizzle-orm/pg-core").PgColumn<{
1387
- name: string;
1388
- tableName: string;
1389
- dataType: "date";
1390
- columnType: "PgTimestamp";
1391
- data: Date;
1392
- driverParam: string;
1393
- notNull: false;
1394
- hasDefault: false;
1395
- isPrimaryKey: false;
1396
- isAutoincrement: false;
1397
- hasRuntimeDefault: false;
1398
- enumValues: undefined;
1399
- baseColumn: never;
1400
- identity: undefined;
1401
- generated: undefined;
1402
- }, {}, {}>;
1403
- };
1404
- dialect: "pg";
1405
- }>;
1406
- /** The outbox table of a SQLite database. */
1407
- type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;
1408
- /** The outbox table of a Postgres database. */
1409
- type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;
1410
- /** An outbox table, made by `outboxTable`. */
1411
- type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;
1412
- /**
1413
- * The outbox table: where recorded events wait, one row per listener, until they
1414
- * are delivered. A write and the events it causes are inserted in one transaction,
1415
- * so an event is neither lost when the process dies after the write nor sent for a
1416
- * write that was rolled back.
1417
- *
1418
- * Brick does not create tables for you. Put this in the schema of the database
1419
- * whose writes emit events, and your migration tool (such as drizzle-kit) creates
1420
- * it. A service whose database holds the table records events; one without it does
1421
- * not.
1422
- *
1423
- * @param engine - The database engine, `"sqlite"` or `"postgres"`.
1424
- * @param options - `name` to call the table something other than `brick_outbox`.
1425
- * @returns A Drizzle table.
1426
- * @example
1427
- * import { defineDatabase, outboxTable } from "@brickkit/core";
1428
- *
1429
- * export const outbox = outboxTable("postgres");
1430
- * export const database = defineDatabase({
1431
- * engine: "postgres",
1432
- * tables: { users, outbox },
1433
- * });
1434
- */
1435
- declare function outboxTable(engine: "sqlite", options?: {
1436
- name?: string;
1437
- }): SQLiteOutboxTable;
1438
- declare function outboxTable(engine: "postgres", options?: {
1439
- name?: string;
1440
- }): PostgresOutboxTable;
1441
- /**
1442
- * Whether a value is an outbox table made by `outboxTable`.
1443
- *
1444
- * @param value - Anything.
1445
- * @returns `true` for an outbox table, narrowing its type.
1446
- */
1447
- declare function isOutboxTable(value: unknown): value is OutboxTable;
1448
- //#endregion
1449
- //#region src/events/dispatcher.d.ts
1450
- /** How many outbox rows are in each state. */
1451
- type OutboxCounts = Record<OutboxStatus, number>;
1452
- /**
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`.
1462
- */
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;
1479
- /**
1480
- * Stop the timer and wait for the deliveries that are running to finish.
1481
- */
1482
- stop(): Promise<void>;
1483
- /** Look for work soon, without waiting for the timer. Safe to call often. */
1484
- notify(): void;
1485
- /**
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.
1490
- */
1491
- tick(): Promise<number>;
1492
- /**
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.
1497
- */
1498
- drain(): Promise<number>;
1499
- /**
1500
- * How many rows are in each state.
1501
- */
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;
1527
- }
1528
- /**
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.
1532
- */
1533
- declare function stopAllEvents(): Promise<void>;
1534
- /**
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.
1537
- */
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[];
1547
- }
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>;
1554
- }
1555
- /**
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`.
1559
- */
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;
1570
- /**
1571
- * @param options - The `events` option.
1572
- * @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
1573
- * listeners and workflow steps.
1574
- */
1575
- constructor(options: EventsOptions, deps?: Record<string, unknown>);
1576
- /**
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.
1583
- */
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;
1589
- /**
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.
1594
- */
1595
- get workflows(): {
1596
- root: string;
1597
- dir: string;
1598
- world: EventsWorld;
1599
- } | undefined;
1600
- /**
1601
- * Resume the workflow that waits on a webhook. The server mounts this on the
1602
- * route the Workflow SDK puts in webhook URLs.
1603
- */
1604
- webhook(request: Request): Promise<Response>;
1605
- /**
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.
1609
- */
1610
- start(): void;
1611
- /**
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.
1615
- */
1616
- stop(): Promise<void>;
1617
- private shutDown;
1618
- /**
1619
- * Deliver everything that is due now and wait for it. For tests and for
1620
- * workers that drive delivery themselves.
1621
- *
1622
- * @returns How many deliveries ran.
1623
- */
1624
- drain(): Promise<number>;
1625
- /** How many rows are in each state, across the app's outbox tables. */
1626
- counts(): Promise<OutboxCounts>;
1627
- /**
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.
1632
- */
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;
1
+ import { Q as BrickSocketConnectOptions, X as BrickSocketClient, Y as BrickClientSocket, bt as StandardErrorCode, c as ActionExecutionError, dr as HttpMethod, s as ActionErrorDefinition, t as Action } from "./types.js";
2
+ import { Static, TSchema } from "@sinclair/typebox";
3
+ /**
4
+ * The URL segment for a declared name: `orderBilling` becomes `order-billing`,
5
+ * `importCSV` becomes `import-csv`. Dots and existing dashes stay.
6
+ */
7
+ declare function kebabCase(name: string): string;
8
+ declare const SPAN: {
9
+ /** `action <service>.<action>` */
10
+ readonly actionPrefix: "action ";
11
+ /** `rpc <service>.<action>` */
12
+ readonly rpcPrefix: "rpc ";
13
+ readonly exceptionEvent: "exception";
14
+ /** The span event a `ctx.logger` line becomes. */
15
+ readonly logEvent: "log";
1834
16
  };
1835
- /**
1836
- * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
1837
- * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
1838
- *
1839
- * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
1840
- * other runtimes (e.g. Node) stays safe until this function is actually
1841
- * called.
1842
- */
1843
- declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase<TSchema>;
1844
- //#endregion
1845
- //#region src/db/postgres.d.ts
1846
- interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
1847
- /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */
1848
- client?: Sql;
1849
- /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */
1850
- url?: string;
1851
- /** Connection string alias */
1852
- connectionString?: string;
1853
- host?: string;
1854
- port?: number;
1855
- user?: string;
1856
- password?: string;
1857
- database?: string;
1858
- ssl?: boolean | "require" | "allow" | "prefer" | "verify-full";
1859
- max?: number;
1860
- /**
1861
- * Disable prepared statements (required for transaction-mode poolers such
1862
- * as Supabase's Supavisor on :6543, which cannot hold named prepared
1863
- * statements across transactions).
1864
- */
1865
- prepare?: boolean;
1866
- /** Optional Drizzle schema for relational queries */
1867
- schema?: TSchema;
1868
- /** Custom schema name for Encore-style isolated schemas */
1869
- schemaName?: string;
1870
- }
1871
- type PostgresDatabase<_TSchema extends Record<string, unknown> = Record<string, unknown>> = any;
1872
- interface DatabaseAdapter<TDb = any, TConfig = any> {
1873
- createDatabase(config?: TConfig): TDb;
1874
- }
1875
- /**
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.
1880
- */
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;
1891
- }
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"];
17
+ declare const ATTR: {
18
+ readonly httpMethod: "http.request.method";
19
+ readonly httpRoute: "http.route";
20
+ readonly httpStatus: "http.response.status_code";
21
+ readonly urlPath: "url.path";
22
+ readonly service: "brick.service";
23
+ readonly action: "brick.action";
24
+ readonly traceId: "brick.trace_id";
25
+ readonly errorCode: "brick.error.code";
26
+ readonly errorMessage: "brick.error.message";
27
+ readonly errorStatus: "brick.error.status";
28
+ readonly logsDropped: "brick.logs.dropped";
29
+ readonly dbStatement: "db.statement";
30
+ readonly dbSystem: "db.system";
31
+ readonly dbOperation: "db.operation";
32
+ readonly exceptionMessage: "exception.message";
33
+ readonly exceptionStack: "exception.stacktrace";
34
+ readonly logLevel: "log.level";
35
+ readonly logMessage: "log.message";
1905
36
  };
1906
- type DatabaseDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;
1907
- interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>> {
1908
- readonly kind: "brick-database";
1909
- readonly name?: string;
1910
- readonly engine: "sqlite" | "postgres";
1911
- readonly tables: Readonly<Record<string, Table>>;
1912
- readonly schema: TSchema;
1913
- /**
1914
- * Add a table after definition, as `definePlugin` does for the tables a
1915
- * plugin owns. Before `getDb()` it also joins the relational schema.
1916
- */
1917
- addTable?(key: string, table: Table): void;
1918
- getDb(): TDb;
1919
- close?(): void | Promise<void>;
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
37
  /**
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 } });
38
+ * `Symbol.for` names shared through globalThis, because the CLI and the app may
39
+ * each hold their own copy of core.
1952
40
  */
1953
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase$1<TSchema>, TSchema>;
1954
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
1955
- $client: Sql;
1956
- }, TSchema>;
1957
- //#endregion
1958
- //#region src/socket-types.d.ts
1959
- type SocketSchemas = Record<string, TSchema>;
1960
- type SocketPayloads<S extends SocketSchemas> = { [K in keyof S]: Static<S[K]>; };
1961
- type SocketEventArgs<Events> = { [K in keyof Events & string]: [event: K, payload: Events[K]]; }[keyof Events & string];
1962
- interface BrickSocketSender<Events> {
1963
- /** Locally accepts a message. Does not acknowledge remote delivery. */
1964
- send(...args: SocketEventArgs<Events>): void;
1965
- close(): void;
1966
- }
1967
- interface BrickSocketConfig<I extends SocketSchemas, O extends SocketSchemas, Ctx> {
1968
- name: string;
1969
- path?: string;
1970
- description?: string;
1971
- input: I;
1972
- output: O;
1973
- /** Defaults to the upgrade request's origin. */
1974
- allowedOrigins?: readonly string[];
1975
- allowMissingOrigin?: boolean;
1976
- authorize?: (params: {
1977
- ctx: Ctx;
1978
- }) => boolean | Promise<boolean>;
1979
- /** Rooms the connection is put in when it opens. */
1980
- rooms?: (params: {
1981
- ctx: Ctx;
1982
- }) => readonly string[] | Promise<readonly string[]>;
1983
- /** Decides each room a client asks to join. Without it, client joins are refused. */
1984
- join?: (params: {
1985
- ctx: Ctx;
1986
- room: string;
1987
- }) => boolean | Promise<boolean>;
1988
- /** Rooms one connection can be in at once (default 100). */
1989
- maxRooms?: number;
1990
- /** Keep recent emits per room so a reconnecting client gets what it missed. Off by default. */
1991
- replay?: SocketReplay;
1992
- handlers: { [K in keyof I]: (params: {
1993
- input: Static<I[K]>;
1994
- ctx: Ctx;
1995
- socket: BrickSocketSender<SocketPayloads<O>>;
1996
- }) => void | Promise<void>; };
1997
- open?: (params: {
1998
- ctx: Ctx;
1999
- socket: BrickSocketSender<SocketPayloads<O>>;
2000
- }) => void | Promise<void>;
2001
- close?: (params: {
2002
- ctx: Ctx;
2003
- socket: BrickSocketSender<SocketPayloads<O>>;
2004
- code: number;
2005
- reason: string;
2006
- }) => void | Promise<void>;
2007
- }
2008
- interface SocketEmitOptions {
2009
- /** A transaction handle from `runInTransaction`: send on commit, drop on rollback. */
2010
- after?: unknown;
2011
- }
2012
- type SocketEmitArgs<Events> = { [K in keyof Events & string]: [event: K, payload: Events[K], options?: SocketEmitOptions]; }[keyof Events & string];
2013
- /** Returned by `service.socket()`. Emits and kicks reach every process through the app's broker. */
2014
- interface BrickSocketHandle<Output> {
2015
- readonly name: string;
2016
- /** Validates and serializes once, then sends to every connection in the rooms. At most once, unacknowledged. */
2017
- emit(rooms: string | readonly string[], ...args: SocketEmitArgs<Output>): void;
2018
- /** Removes connections from a room; `also` limits it to connections also in that room. */
2019
- kick(room: string, options?: {
2020
- also?: string;
2021
- reason?: string;
2022
- }): void;
2023
- }
2024
- interface SocketReplay {
2025
- /** Emits kept per room. */
2026
- keep: number;
2027
- /** How long a room's history lasts without new emits. */
2028
- maxAgeMs: number;
2029
- }
2030
- type SocketBrokerMessage =
2031
- /** `seq` is set by the broker for sockets with replay: `<number>-<number>`, rising per room. */
2032
- {
2033
- type: "emit";
2034
- topic: string;
2035
- frame: string;
2036
- seq?: string;
2037
- } | {
2038
- type: "kick";
2039
- topic: string;
2040
- also?: string;
2041
- reason?: string;
41
+ declare const GLOBAL_SYMBOL: {
42
+ /** Set by the CLI while a dashboard collects logs. */
43
+ readonly logsCapture: "brickkit.logs.capture";
44
+ /** Core's function that records a log line on the running span. */
45
+ readonly logsRecord: "brickkit.logs.record";
46
+ /** The set of running event hubs, so the CLI can stop them all. */
47
+ readonly eventsStarted: "brickkit.events.started";
2042
48
  };
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";
2069
- interface BrickSocketConnectOptions {
2070
- signal?: AbortSignal;
2071
- /** Limits each opening attempt. */
2072
- timeoutMs?: number;
2073
- /** Called on every connect and reconnect; sent as the `brick.token.<token>` subprotocol. */
2074
- token?: () => string | Promise<string>;
2075
- /** On by default. `false` ends the client at the first close. */
2076
- reconnect?: false | BrickSocketReconnectOptions;
2077
- }
2078
- declare class BrickSocketError extends Error {
2079
- readonly kind: "connection" | "protocol" | "backpressure" | "refused";
2080
- constructor(kind: "connection" | "protocol" | "backpressure" | "refused", message: string, options?: ErrorOptions);
2081
- }
2082
- interface BrickSocketClient<Input, Output> extends BrickSocketSender<Input> {
2083
- /** Resolves on the first open; rejects if the client closes before it. */
2084
- readonly ready: Promise<void>;
2085
- readonly status: BrickSocketStatus;
2086
- onStatus(listener: (status: BrickSocketStatus) => void): () => void;
2087
- /** After each reconnect. Messages sent while offline are not replayed. */
2088
- onReconnect(listener: () => void): () => void;
2089
- on<K extends keyof Output & string>(event: K, listener: (payload: Output[K]) => void): () => void;
2090
- /** Resolves when the server accepts the room; rejects with kind `refused` otherwise. */
2091
- join(room: string): Promise<void>;
2092
- leave(room: string): void;
2093
- /** The server removed this connection from a room. */
2094
- onLeave(listener: (room: string, reason?: string) => void): () => void;
2095
- /** Replay could not cover what this client missed in a room while away: refetch it. */
2096
- onGap(listener: (room: string) => void): () => void;
2097
- onError(listener: (error: BrickSocketError) => void): () => void;
2098
- onClose(listener: (info: {
2099
- code: number;
2100
- reason: string;
2101
- }) => void): () => void;
2102
- }
2103
- /** Browser metadata. Schemas retain TypeBox kinds as JSON-safe annotations. */
2104
- interface BrickClientSocket<Input = unknown, Output = unknown> {
2105
- kind: "socket";
2106
- name: string;
2107
- serviceName: string;
2108
- config: {
2109
- path: string;
2110
- };
2111
- output: Record<string, unknown>;
2112
- readonly __types?: {
2113
- input: Input;
2114
- output: Output;
2115
- };
2116
- }
2117
- interface BrickSocketSchema {
2118
- name: string;
2119
- path?: string;
2120
- description?: string;
2121
- input: string[];
2122
- output: string[];
2123
- hasAuthorize: boolean;
2124
- }
2125
- //#endregion
2126
- //#region src/socket.d.ts
2127
- interface SocketSender {
2128
- readonly isOpen: boolean;
2129
- send(event: string, payload: unknown): void;
2130
- close(): void;
2131
- }
2132
- interface SocketSession {
2133
- /** Server rooms, resolved from the handshake context. */
2134
- rooms: readonly string[];
2135
- open(socket: SocketSender): Promise<void>;
2136
- message(event: string, data: unknown, socket: SocketSender): Promise<void>;
2137
- join(room: string): Promise<boolean>;
2138
- close(socket: SocketSender, code: number, reason: string): Promise<void>;
2139
- }
2140
- interface RegisteredSocket {
2141
- schema: BrickSocketSchema;
2142
- input: SocketSchemas;
2143
- output: SocketSchemas;
2144
- allowedOrigins?: readonly string[];
2145
- allowMissingOrigin?: boolean;
2146
- maxRooms: number;
2147
- replay?: SocketReplay;
2148
- /** Brokers of the apps this socket is mounted in. */
2149
- brokers: Set<SocketBroker>;
2150
- handle: BrickSocketHandle<any>;
2151
- topicPrefix: string;
2152
- topic(room: string): string;
2153
- connect(request: Request): Promise<SocketSession>;
2154
- }
2155
- //#endregion
2156
- //#region src/types.d.ts
2157
- /**
2158
- * The logger on action, tool, and endpoint contexts. While a dashboard is on
2159
- * (`brick dev`, or `brick start` with the `dashboard` option) a line logged
2160
- * during a traced request appears in the dashboard with that request, instead
2161
- * of on the console (as does a plain `console.log`); anywhere else it prints
2162
- * to the console.
2163
- */
2164
- interface Logger {
2165
- info: (...args: any[]) => void;
2166
- warn: (...args: any[]) => void;
2167
- error: (...args: any[]) => void;
2168
- debug: (...args: any[]) => void;
2169
- }
2170
- /**
2171
- * Base framework context supplied to all service resolvers and action executions.
2172
- */
2173
- interface BaseContext<TDb = any> {
2174
- request: Request;
2175
- db: TDb;
2176
- logger: Logger;
2177
- traceId: string;
2178
- requestId?: string;
2179
- caller?: string;
2180
- tenantId?: string;
2181
- services?: Record<string, any>;
2182
- metadata?: Record<string, unknown>;
2183
- }
2184
- /**
2185
- * Default fallback service context for untyped or simple services.
2186
- */
2187
- interface DefaultServiceContext {
2188
- user?: any;
2189
- session?: any;
2190
- [key: string]: any;
2191
- }
2192
- /**
2193
- * The combined execution context: BaseContext & TServiceContext.
2194
- */
2195
- type ActionContext<TDb = any, TServiceContext = DefaultServiceContext> = BaseContext<TDb> & TServiceContext;
2196
- /**
2197
- * Type utility that automatically narrows ctx.user from User | null to User
2198
- * in execute() when authorize() is declared on the action.
2199
- */
2200
- type NarrowAuthorizedContext<TCtx> = TCtx extends {
2201
- user: infer U;
2202
- } ? [U] extends [null | undefined] ? TCtx : Omit<TCtx, "user"> & {
2203
- user: NonNullable<U>;
2204
- } : TCtx;
2205
- interface ActionErrorDefinition {
2206
- status?: number;
2207
- message: string;
2208
- /** Schema of the `details` the error carries. Checked in types only, not at runtime. */
2209
- details?: TSchema;
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;
2215
- interface ValidationErrorItem {
2216
- path: string;
2217
- message: string;
2218
- value?: unknown;
2219
- type?: number;
2220
- }
2221
- declare class ValidationError extends Error {
2222
- readonly code = "VALIDATION_FAILED";
2223
- readonly status: number;
2224
- readonly errors: ValidationErrorItem[];
2225
- constructor(message: string, errors?: ValidationErrorItem[], status?: number);
2226
- toJSON(): {
2227
- name: string;
2228
- code: string;
2229
- message: string;
2230
- status: number;
2231
- errors: ValidationErrorItem[];
2232
- };
2233
- }
2234
- declare class ActionExecutionError extends Error {
2235
- readonly code: string;
2236
- readonly status: number;
2237
- readonly details?: unknown;
2238
- constructor(code: string, message: string, status?: number, details?: unknown, options?: ErrorOptions);
2239
- toJSON(): {
2240
- name: string;
2241
- code: string;
2242
- message: string;
2243
- status: number;
2244
- details: unknown;
2245
- };
2246
- }
2247
- interface StandardErrorMap {
2248
- BAD_REQUEST: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2249
- UNAUTHORIZED: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2250
- FORBIDDEN: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2251
- NOT_FOUND: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2252
- CONFLICT: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2253
- INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2254
- [key: string]: ((overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never) | undefined;
2255
- }
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; };
2259
- interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
2260
- name: string;
2261
- description?: string;
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
- */
2268
- path?: string;
2269
- /** Single HTTP method exposed for this action (default POST). */
2270
- method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
2271
- input?: TInputSchema;
2272
- output?: TOutputSchema;
2273
- errors?: TErrors;
2274
- emits?: string[];
2275
- tags?: string[];
2276
- }
2277
- interface ActionConfigWithAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
2278
- authorize: (params: {
2279
- user?: TContext extends {
2280
- user: infer U;
2281
- } ? U : any;
2282
- input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2283
- ctx: TContext;
2284
- }) => boolean | Promise<boolean>;
2285
- execute: (params: {
2286
- input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2287
- ctx: NarrowAuthorizedContext<TContext>;
2288
- error: ErrorBuilder<TErrors>;
2289
- }) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
2290
- }
2291
- interface ActionConfigWithoutAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
2292
- authorize?: undefined;
2293
- execute: (params: {
2294
- input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2295
- ctx: TContext;
2296
- error: ErrorBuilder<TErrors>;
2297
- }) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
2298
- }
2299
- type ActionConfig<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> = ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext> | ActionConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>;
2300
- interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> {
2301
- (params: {
2302
- input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2303
- ctx?: Partial<TContext>;
2304
- }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2305
- name: string;
2306
- serviceName?: string;
2307
- /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
2308
- plugin?: string;
2309
- /** Owning resource name for resource-plugin actions (e.g. `page`). */
2310
- resource?: string;
2311
- config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;
2312
- /**
2313
- * Optional runtime-only output schema. When present, `validateOutput` and
2314
- * HTTP output checking validate against it instead of `config.output`,
2315
- * while `config.output` remains the published contract (client types,
2316
- * OpenAPI). Lets projected/subset responses validate at runtime without
2317
- * leaking optionality into the generated contract.
2318
- */
2319
- outputValidationSchema?: TSchema;
2320
- run(input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: Partial<TContext>): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2321
- execute(params: {
2322
- input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2323
- ctx?: Partial<TContext>;
2324
- }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2325
- executeResolved?(params: {
2326
- input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2327
- ctx: TContext;
2328
- }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2329
- validateInput(input: unknown): {
2330
- success: true;
2331
- data: any;
2332
- } | {
2333
- success: false;
2334
- errors: ValidationErrorItem[];
2335
- };
2336
- validateOutput(output: unknown): {
2337
- success: true;
2338
- data: any;
2339
- } | {
2340
- success: false;
2341
- errors: ValidationErrorItem[];
2342
- };
2343
- errorHelpers?: ErrorBuilder<TErrors>;
2344
- }
2345
- /** MCP tool metadata, kept with the executable definition. */
2346
- interface ToolAnnotations {
2347
- title?: string;
2348
- readOnlyHint?: boolean;
2349
- destructiveHint?: boolean;
2350
- idempotentHint?: boolean;
2351
- openWorldHint?: boolean;
2352
- }
2353
- interface ToolOptions {
2354
- title?: string;
2355
- annotations?: ToolAnnotations;
2356
- /** Also register HTTP routes and OpenAPI. Defaults to false. */
2357
- http?: boolean;
2358
- }
2359
- type ToolConfigWithAuthorize<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, C extends ActionContext = ActionContext> = ActionConfigWithAuthorize<I, O, E, C> & ToolOptions;
2360
- type ToolConfigWithoutAuthorize<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, C extends ActionContext = ActionContext> = ActionConfigWithoutAuthorize<I, O, E, C> & ToolOptions;
2361
- interface Tool<I extends TSchema | undefined = any, O extends TSchema | undefined = any, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, C extends ActionContext = ActionContext> extends Action<I, O, E, C> {
2362
- readonly kind: "tool";
2363
- config: ToolConfigWithAuthorize<I, O, E, C> | ToolConfigWithoutAuthorize<I, O, E, C>;
2364
- }
2365
- /** A resource declares identity and a table; plugins supply behavior. */
2366
- interface ResourceConfig<TTable = any, _TCtx = any> {
2367
- name: string;
2368
- table: TTable;
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;
2384
- }
2385
- type InferTableRow<TTable> = TTable extends {
2386
- $inferSelect: infer S;
2387
- } ? S : any;
2388
- type InferTableInsert<TTable> = TTable extends {
2389
- $inferInsert: infer S;
2390
- } ? S : any;
2391
- type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id" | "children">;
2392
- type PrimaryColumn<T> = T extends {
2393
- _: {
2394
- columns: infer C;
2395
- };
2396
- } ? { [K in keyof C]: C[K] extends {
2397
- _: {
2398
- isPrimaryKey: true;
2399
- };
2400
- } ? C[K] : never; }[keyof C] : import("drizzle-orm").Column;
2401
- type ResourceIdentity<T, O> = O & {
2402
- id: O extends {
2403
- id: infer I extends import("drizzle-orm").Column;
2404
- } ? I : PrimaryColumn<T>;
2405
- };
2406
- /** Generic preparation declarations consumed by the application compiler. */
2407
- interface PreparationContribution {
2408
- readonly name: string;
2409
- describe(): unknown;
2410
- prepare(): void;
2411
- }
2412
- interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}, TEvents extends EventCatalog = EventCatalog> {
2413
- use<P extends ResourcePlugin<Service<TCtx["db"], Omit<TCtx, keyof BaseContext>>, this, any>>(plugin: P): this & ResourcePluginAPI<P, TTable, TCtx, this>;
2414
- readonly name: string;
2415
- readonly serviceName: string;
2416
- readonly table: TTable;
2417
- readonly id: TOptions extends {
2418
- id: infer I extends import("drizzle-orm").Column;
2419
- } ? I : import("drizzle-orm").Column;
2420
- readonly idField: string;
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);
2555
- }
2556
- interface ServiceAuthOptions {
2557
- requireAuth?: boolean;
2558
- allowedRoles?: string[];
2559
- policy?: (ctx: ActionContext) => boolean | Promise<boolean>;
2560
- }
2561
- interface RateLimitOptions {
2562
- maxRequests: number;
2563
- window: number | string;
2564
- scope?: "ip" | "user" | "tenant";
2565
- }
2566
- interface CacheOptions {
2567
- driver?: "memory" | "redis";
2568
- defaultTtl?: number;
2569
- }
2570
- interface ResilienceOptions {
2571
- timeoutMs?: number;
2572
- retry?: {
2573
- attempts: number;
2574
- backoff: "linear" | "exponential";
2575
- delayMs: number;
2576
- };
2577
- circuitBreaker?: {
2578
- errorThresholdPercentage: number;
2579
- resetTimeoutMs: number;
2580
- };
2581
- }
2582
- interface TelemetryOptions {
2583
- traceQueries?: boolean;
2584
- auditLog?: boolean;
2585
- tags?: Record<string, string>;
2586
- }
2587
- interface LifecycleOptions {
2588
- onInit?: (ctx: {
2589
- db?: any;
2590
- logger?: Logger;
2591
- }) => Promise<void>;
2592
- onDestroy?: () => Promise<void>;
2593
- }
2594
- interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
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;
2601
- context?: (baseCtx: BaseContext<TDb> & {
2602
- user?: unknown;
2603
- }) => Promise<TServiceContext> | TServiceContext;
2604
- auth?: ServiceAuthOptions;
2605
- rateLimit?: RateLimitOptions;
2606
- cache?: CacheOptions;
2607
- resilience?: ResilienceOptions;
2608
- telemetry?: TelemetryOptions;
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;
2615
- }
2616
- type ActionAccessPolicy = "public" | "authorized" | "scoped";
2617
- interface ActionSchema {
2618
- name: string;
2619
- /** Present only when this action has a registered HTTP route. */
2620
- method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
2621
- path?: string;
2622
- serviceName?: string;
2623
- /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
2624
- plugin?: string;
2625
- /** Owning resource name for resource-plugin actions (e.g. `page`). */
2626
- resource?: string;
2627
- description?: string;
2628
- inputSchema?: unknown;
2629
- outputSchema?: unknown;
2630
- hasAuthorize: boolean;
2631
- hasScope?: boolean;
2632
- accessPolicy?: ActionAccessPolicy;
2633
- errors?: Record<string, ActionErrorDefinition>;
2634
- emits?: string[];
2635
- tags?: string[];
2636
- }
2637
- interface ServiceSchema {
2638
- name: string;
2639
- /** The service options as JSON: functions, such as `context` and hooks, are left out. */
2640
- options: Record<string, unknown>;
2641
- hasDatabase: boolean;
2642
- databaseConfig?: {
2643
- name?: string;
2644
- engine: "sqlite" | "postgres";
2645
- tables: string[];
2646
- /** The plugin that owns each table it contributed, by table key. */
2647
- plugins?: Record<string, string>;
2648
- };
2649
- actions: ActionSchema[];
2650
- sockets?: BrickSocketSchema[];
2651
- /** MCP tools. A tool with an HTTP route is also listed under `actions`. */
2652
- tools?: {
2653
- name: string;
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
- }[];
2661
- resources?: {
2662
- name: string;
2663
- }[];
2664
- }
2665
- interface ArchitectureSchema {
2666
- version: string;
2667
- services: ServiceSchema[];
2668
- /** Present when the app has an `events` option. */
2669
- events?: EventsDefinition;
2670
- /** Every `definePlugin` installation, with its dashboard extension. */
2671
- plugins?: InstalledPlugin[];
2672
- }
2673
- interface CompiledRoutePlan {
2674
- service: Service<any, any>;
2675
- action: Action<any, any, any, any>;
2676
- actionName: string;
2677
- serviceName: string;
2678
- routePath: string;
2679
- method?: string;
2680
- isGetLike: boolean;
2681
- hasInput: boolean;
2682
- hasContextHook: boolean;
2683
- contextHook?: (baseCtx: any) => Promise<any> | any;
2684
- hasAuthorize: boolean;
2685
- authorize?: (params: any) => boolean | Promise<boolean>;
2686
- execute: (params: any) => Promise<any> | any;
2687
- inputChecker?: {
2688
- Check: (val: any) => boolean;
2689
- Errors: (val: any) => Iterable<any>;
2690
- };
2691
- outputChecker?: {
2692
- Check: (val: any) => boolean;
2693
- Errors: (val: any) => Iterable<any>;
2694
- };
2695
- coercions?: Array<{
2696
- key: string;
2697
- isNumber: boolean;
2698
- isBoolean: boolean;
2699
- isArray?: boolean;
2700
- }>;
2701
- logger: Logger;
2702
- errorBuilder: any;
2703
- cachedDb: any;
2704
- }
2705
- interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>, TEvents extends EventCatalog = EventCatalog> {
2706
- readonly name: string;
2707
- /** The declared events, as handles for `defineListener` and `emitEvent`. */
2708
- readonly events: EventRefs<TEvents>;
2709
- readonly options: ServiceOptions<TServiceContext, TDb>;
2710
- readonly actions: Map<string, Action<any, any, any, any>>;
2711
- readonly tools: Map<string, Tool<any, any, any, any>>;
2712
- readonly tables: Map<string, any>;
2713
- readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext>>;
2714
- readonly db?: TDb;
2715
- readonly isBuilt?: boolean;
2716
- use<A>(plugin: ServicePlugin<this, A>): A;
2717
- build(): this;
2718
- socket<const I extends SocketSchemas, const O extends SocketSchemas>(config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext>): BrickSocketHandle<SocketPayloads<O>>;
2719
- listSockets(): RegisteredSocket[];
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;
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>;
2722
- action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
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;
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>;
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>;
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>;
2727
- readonly preparations: Map<string, PreparationContribution>;
2728
- contributePreparation(contribution: PreparationContribution): void;
2729
- listPreparations(): PreparationContribution[];
2730
- prepareContributions(): void;
2731
- registerTable(table: any): this;
2732
- getAction(name: string): Action<any, any, any, any> | undefined;
2733
- listActions(): Action<any, any, any, any>[];
2734
- getTool(name: string): Tool<any, any, any, any> | undefined;
2735
- listTools(): Tool<any, any, any, any>[];
2736
- getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
2737
- listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
2738
- getDb(): TDb | undefined;
2739
- /** The handle from `defineDatabase`, without connecting. */
2740
- getDatabaseHandle?(): DatabaseHandle<TDb> | undefined;
2741
- setDb(database: DatabaseHandle<TDb>): void;
2742
- /** The outbox table of this service's database, if it holds one (see `outboxTable`). */
2743
- getOutbox?(): OutboxTable | undefined;
2744
- /** What a write needs to record events. Set by `brick({ events })`; absent otherwise. */
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;
2750
- resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
2751
- introspect(): ServiceSchema;
2752
- }
2753
- interface ProxyOptions {
2754
- /** Name of the service creating this proxy. Populates ctx.caller on the target's envelope. */
2755
- from?: string;
2756
- context?: Partial<ActionContext>;
2757
- }
2758
- //#endregion
2759
- //#region src/client.d.ts
2760
49
  /**
2761
50
  * Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.
2762
51
  *
@@ -2802,18 +91,13 @@ interface ProxyOptions {
2802
91
  *
2803
92
  * ## URL mapping
2804
93
  *
2805
- * A client path is a namespace walk ending in an action call. The leaf segment
2806
- * decides the route, matching the server compiler (`packages/cli/src/compiler`):
2807
- *
2808
- * | Client call | HTTP request |
2809
- * |---|---|
2810
- * Generated browser contracts carry each action's HTTP method and path,
2811
- * including plugin routes, resource routes and consumer overrides. Without
94
+ * A client path is a namespace walk ending in an action call. Generated
95
+ * browser contracts carry each action's HTTP method and path, including
96
+ * plugin routes, resource routes and consumer overrides. Without
2812
97
  * runtime metadata, callers use `POST /api/<service>/<action>` with the names
2813
98
  * in kebab-case (`getSummary` → `get-summary`); resource and plugin routes
2814
99
  * need the contract.
2815
100
  * GET/DELETE input is serialized as a query string; other methods send JSON.
2816
-
2817
101
  */
2818
102
  interface BrickClientOptions {
2819
103
  /** Server origin, e.g. `"http://localhost:4000"`. No trailing slash required. */
@@ -2853,11 +137,11 @@ interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}> {
2853
137
  serviceName: string;
2854
138
  /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
2855
139
  plugin?: string;
2856
- /** Owning resource name for resource-plugin actions (e.g. `page`). */
140
+ /** Owning resource name for resource actions (e.g. `page`). */
2857
141
  resource?: string;
2858
142
  config: {
2859
143
  path: string;
2860
- method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
144
+ method: HttpMethod;
2861
145
  };
2862
146
  /** Type information only; never emitted at runtime. */
2863
147
  readonly __types?: {
@@ -2964,7 +248,7 @@ type InferActionErrorCodes<A> = A extends BrickClientAction<any, any, infer E> ?
2964
248
  * (Standard framework codes are always possible alongside declared ones.)
2965
249
  */
2966
250
  type InferActionFailure<A> = ActionExecutionError & {
2967
- code: InferActionErrorCodes<A> | "BAD_REQUEST" | "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "INTERNAL_SERVER_ERROR" | "VALIDATION_FAILED";
251
+ code: InferActionErrorCodes<A> | StandardErrorCode | "VALIDATION_FAILED";
2968
252
  };
2969
253
  /**
2970
254
  * Typed caller for one action. Required inputs stay required; actions whose
@@ -2972,8 +256,8 @@ type InferActionFailure<A> = ActionExecutionError & {
2972
256
  */
2973
257
  type BrickActionCaller<A> = undefined extends InferActionInput<A> ? (input?: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>> : (input: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>>;
2974
258
  /** Recursively maps action leaves and their namespaces to browser callers. */
2975
- type BrickClient<T> = T extends BrickClientSocket<infer I, infer O> ? {
2976
- connect(options?: BrickSocketConnectOptions): BrickSocketClient<I, O>;
259
+ type BrickClient<T> = T extends BrickClientSocket<infer I, infer O, infer E> ? {
260
+ connect(options?: BrickSocketConnectOptions): BrickSocketClient<I, O, E>;
2977
261
  } : T extends BrickClientAction<any, any, any> | Action<any, any, any, any> ? BrickActionCaller<T> : T extends ((...args: any[]) => any) ? BrickActionCaller<T> : T extends object ? { [K in keyof T]: BrickClient<T[K]>; } : T;
2978
262
  /**
2979
263
  * Create an Eden/tRPC-style typed client for the application contract `TApp`.
@@ -2984,6 +268,5 @@ declare function createBrickClient<TApp extends Record<string, any>>(options: Br
2984
268
  contract: TApp;
2985
269
  }): BrickClient<TApp>;
2986
270
  declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
2987
- //#endregion
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 };
271
+ export { GLOBAL_SYMBOL as _, BrickClientOptions as a, BrickTransportError as c, InferActionInput as d, InferActionOutput as f, ATTR as g, isBrickTransportError as h, BrickClientAction as i, InferActionErrorCodes as l, isBrickServerError as m, BrickCallOptions as n, BrickServerError as o, createBrickClient as p, BrickClient as r, BrickServices as s, BrickActionCaller as t, InferActionFailure as u, SPAN as v, kebabCase as y };
2989
272
  //# sourceMappingURL=client.d.ts.map