@brickkit/effect 0.0.0-stage → 0.16.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4873 @@
1
+ import { Cause, Context, Duration, Effect, Fiber, Layer, Schema, Scope, Tracer } from "effect";
2
+ import { OtlpTracer } from "effect/observability";
3
+ import { Column, ColumnBuilderBase, ExtractTablesFromSchema, ExtractTablesWithRelations, SQL, Table } from "drizzle-orm";
4
+ import { SqlError } from "effect/sql/SqlError";
5
+ import { Activity, DurableClock, DurableDeferred, Workflow, WorkflowEngine, WorkflowEngine as WorkflowEngine$1 } from "effect/workflow";
6
+ import { ConnectionOptions } from "node:tls";
7
+ import { EffectSQLiteBunDatabase } from "drizzle-orm/effect-sqlite-bun";
8
+ import { EffectPgDatabase } from "drizzle-orm/effect-postgres";
9
+ /** The codes every action can raise, with their status and default message. The same as `@brickkit/core`. */
10
+ declare const STANDARD_ERRORS: {
11
+ readonly BAD_REQUEST: {
12
+ readonly status: 400;
13
+ readonly message: "Bad Request";
14
+ };
15
+ readonly UNAUTHORIZED: {
16
+ readonly status: 401;
17
+ readonly message: "Unauthorized";
18
+ };
19
+ readonly FORBIDDEN: {
20
+ readonly status: 403;
21
+ readonly message: "Forbidden";
22
+ };
23
+ readonly NOT_FOUND: {
24
+ readonly status: 404;
25
+ readonly message: "Not Found";
26
+ };
27
+ readonly CONFLICT: {
28
+ readonly status: 409;
29
+ readonly message: "Conflict";
30
+ };
31
+ readonly RATE_LIMITED: {
32
+ readonly status: 429;
33
+ readonly message: "Too Many Requests";
34
+ };
35
+ readonly INTERNAL_SERVER_ERROR: {
36
+ readonly status: 500;
37
+ readonly message: "Internal Server Error";
38
+ };
39
+ };
40
+ type StandardErrorCode = keyof typeof STANDARD_ERRORS;
41
+ declare const BrickError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => Cause.YieldableError & {
42
+ readonly _tag: "BrickError";
43
+ } & Readonly<A>;
44
+ /** A declared failure of an action: a `code`, an HTTP `status`, and optional `details`. */
45
+ declare class BrickError extends BrickError_base<{
46
+ readonly code: string;
47
+ readonly message: string;
48
+ readonly status: number;
49
+ readonly details?: unknown;
50
+ /** The error this one stands for, kept for the log: core's error with its own `cause`. */
51
+ readonly cause?: unknown;
52
+ }> {}
53
+ /** One reason an input or output failed its schema: a JSON pointer to the field, and a message that never carries the rejected value. */
54
+ interface ValidationIssue {
55
+ readonly path: string;
56
+ readonly message: string;
57
+ }
58
+ declare const ValidationError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => Cause.YieldableError & {
59
+ readonly _tag: "ValidationError";
60
+ } & Readonly<A>;
61
+ /** The input (400) or output (500) of an action did not match its schema. */
62
+ declare class ValidationError extends ValidationError_base<{
63
+ readonly message: string;
64
+ readonly status: number;
65
+ readonly errors: ReadonlyArray<ValidationIssue>;
66
+ /** The error this one stands for, kept for the log. */
67
+ readonly cause?: unknown;
68
+ }> {
69
+ readonly code = "VALIDATION_FAILED";
70
+ }
71
+ /** Two declarations claim one name or URL segment. */
72
+ declare class DuplicateNameError extends Error {
73
+ readonly name = "DuplicateNameError";
74
+ }
75
+ /** An error as JSON: the body of a failed HTTP call, as `@brickkit/core`'s client decodes it. */
76
+ interface WireError {
77
+ name: string;
78
+ code: string;
79
+ message: string;
80
+ status: number;
81
+ details?: unknown;
82
+ errors?: ValidationIssue[];
83
+ }
84
+ /** `WireError` plus the id of the request, the body of every failed HTTP call. */
85
+ interface ErrorEnvelope extends WireError {
86
+ requestId: string;
87
+ }
88
+ /** Where unexpected failures are logged, and the id of the request they are logged for. */
89
+ interface FailureContext {
90
+ readonly logger: {
91
+ error: (...args: any[]) => void;
92
+ };
93
+ readonly requestId?: string | undefined;
94
+ }
95
+ type Failure = BrickError | ValidationError;
96
+ /** A failure as JSON. A failed output check (status 500) leaves out its `errors`, which describe internals. */
97
+ declare function toWireError(error: Failure): WireError;
98
+ /**
99
+ * The JSON body of a failed HTTP call. Declared failures and validation errors
100
+ * keep their code, status and details; anything else is logged and answered as a
101
+ * generic `INTERNAL_SERVER_ERROR` (500), so internals are never exposed.
102
+ */
103
+ declare function toErrorResponse(cause: Cause.Cause<unknown>, context: FailureContext): ErrorEnvelope;
104
+ /** The person `dashboard.auth.authorize` let in. */
105
+ interface DashboardUser {
106
+ id: string;
107
+ name?: string;
108
+ }
109
+ /**
110
+ * Who a request came from, when it reached the app through the dashboard's
111
+ * `/app/*` proxy. `user` is missing when the dashboard let the request in
112
+ * without one: by token, by `authorize` returning `true`, or with no `auth`.
113
+ */
114
+ interface DashboardIdentity {
115
+ user?: DashboardUser;
116
+ }
117
+ /** The header the dashboard's `/app/*` proxy signs the identity into. */
118
+ declare const DASHBOARD_IDENTITY_HEADER = "x-brick-dashboard";
119
+ /** How `brick dev` hands the signing key to the app's process. */
120
+ declare const DASHBOARD_KEY_ENV = "BRICK_DASHBOARD_KEY";
121
+ /**
122
+ * The key the dashboard signs identities with: random per process, or the one
123
+ * `brick dev` or the Vite plugin handed the app.
124
+ */
125
+ declare function dashboardKey(): string;
126
+ /** Note when `request` arrived, before its body is read. */
127
+ declare function markDashboardArrival(request: Request): void;
128
+ /** The header value for an identity: `<base64url(json)>.<hmac>`. */
129
+ declare function signDashboardIdentity(identity: DashboardIdentity, now?: number): string;
130
+ /** A signature made for the MCP route carries a `scope`, and is not an identity here. */
131
+ declare function dashboardIdentity(request: Request | undefined): DashboardIdentity | undefined;
132
+ /** Who a call forwarded by the dashboard's `/mcp` is for, and whether tools that change data may run. */
133
+ interface DashboardMcpCaller extends DashboardIdentity {
134
+ write: boolean;
135
+ }
136
+ /**
137
+ * The header value for a call the dashboard's `/mcp` forwards to the app. It is
138
+ * scoped to the MCP route: the `/app` proxy never signs one, and a signature
139
+ * made for `/app` is not accepted there.
140
+ */
141
+ declare function signDashboardMcp(caller: DashboardMcpCaller, now?: number): string;
142
+ declare function dashboardMcpCaller(request: Request | undefined): DashboardMcpCaller | undefined;
143
+ /**
144
+ * The dashboard user a request came from, for an endpoint: the person
145
+ * `dashboard.auth.authorize` let in, when the request arrived through the
146
+ * dashboard's `/app/*` proxy. Undefined for any other request, and for one the
147
+ * dashboard let in by token. Actions read it as `ctx.dashboard?.user`.
148
+ */
149
+ declare function dashboardUser(request: Request): DashboardUser | undefined;
150
+ /** The logger of an action's `ctx`. */
151
+ interface Logger {
152
+ info: (...args: any[]) => void;
153
+ warn: (...args: any[]) => void;
154
+ error: (...args: any[]) => void;
155
+ debug: (...args: any[]) => void;
156
+ }
157
+ /**
158
+ * A logger that prints to the console, each line starting with `[LEVEL]`. While
159
+ * a dashboard collects logs, a line logged in a traced call becomes an event on
160
+ * its span, and is not printed.
161
+ */
162
+ declare function createLogger(): Logger;
163
+ /** The fields every action's `ctx` has. */
164
+ interface BaseContext {
165
+ request: Request;
166
+ logger: Logger;
167
+ traceId: string;
168
+ requestId: string;
169
+ /** The name of the service that called this one through `useService(service, { from })`. With `from`, a `caller` in the call's own context is ignored. In-process code that calls `action.run(input, { caller })` or `useService` without `from` sets it freely, as in core: an HTTP request never does, so trust it only for calls from your own code. */
170
+ caller?: string;
171
+ /** Set when the request came through the dashboard's `/app/*` proxy, signed by the dashboard: `user` is who `dashboard.auth.authorize` let in. */
172
+ dashboard?: DashboardIdentity;
173
+ }
174
+ /**
175
+ * What a caller of `action.run` may carry into the call's `ctx`. `deps` replaces
176
+ * some of the service's own for this call, such as a fake in a test.
177
+ */
178
+ type CallContext = Partial<BaseContext> & {
179
+ user?: unknown;
180
+ deps?: Readonly<Record<string, unknown>>;
181
+ };
182
+ type RelationsOf<TTables extends Record<string, unknown>> = ExtractTablesWithRelations<{}, ExtractTablesFromSchema<TTables>>;
183
+ /** The `Database` service of one database: what `ctx.db` of its services is. */
184
+ interface DatabaseService<TDb> {
185
+ readonly "~brick/database": TDb;
186
+ }
187
+ /** What `defineDatabase` returns: the tables, the `Database` service, and the layer that connects it. */
188
+ interface DatabaseHandle<TDb, TTables = Record<string, unknown>> {
189
+ readonly kind: "brick-database";
190
+ readonly tables: TTables;
191
+ readonly engine: "sqlite" | "postgres";
192
+ /** `defineDatabase({ name })`: names the folder `brick db` keeps this database's migrations in. */
193
+ readonly name?: string;
194
+ /**
195
+ * How `defineDatabase` was told to connect, for `brick db migrate` and `push`,
196
+ * which open a connection of their own. Not enumerable, so the URL's password
197
+ * does not travel with the handle into a log or a JSON body.
198
+ */
199
+ readonly connection: DatabaseConnection;
200
+ /** The service `ctx.db` is read from. Yield it to reach the same database outside an action. */
201
+ readonly Database: Context.Service<DatabaseService<TDb>, TDb>;
202
+ /** Opens the connection when first used and closes it with the app (`brick`'s runtime). */
203
+ readonly layer: Layer.Layer<DatabaseService<TDb>, SqlError>;
204
+ }
205
+ /** Any database, whatever its engine. */
206
+ type AnyDatabaseHandle = DatabaseHandle<any, any>;
207
+ /**
208
+ * Whether a value is a database handle made by `defineDatabase`.
209
+ *
210
+ * @param value - Anything.
211
+ * @returns `true` for a handle, narrowing its type.
212
+ */
213
+ declare function isDatabaseHandle(value: unknown): value is AnyDatabaseHandle;
214
+ /** The settings a database was defined with: its SQLite file or Postgres URL, and the engine's options. */
215
+ type DatabaseConnection = ({
216
+ engine: "sqlite";
217
+ filename: string;
218
+ } & SQLiteOptions) | ({
219
+ engine: "postgres";
220
+ url: string;
221
+ } & PostgresOptions);
222
+ /** What every database takes besides its connection. */
223
+ interface DatabaseNaming {
224
+ /** Names the folder `brick db` writes this database's migrations to (default: the first service that uses it). Give each database its own. */
225
+ name?: string;
226
+ }
227
+ /** What SQLite takes besides its file. */
228
+ interface SQLiteOptions {
229
+ /** Enforce foreign key constraints, by `PRAGMA foreign_keys` (default `true`). */
230
+ foreignKeys?: boolean;
231
+ /** Use the write-ahead log journal (default `true`). It does not apply to `":memory:"`. */
232
+ wal?: boolean;
233
+ }
234
+ /** What Postgres takes besides its URL. */
235
+ interface PostgresOptions {
236
+ /** Encrypt the connection: `true`, or Node's TLS options (`{ rejectUnauthorized: false }`, a `ca`). A `sslmode` in the URL works too. */
237
+ ssl?: boolean | ConnectionOptions;
238
+ /** Most connections the pool opens. */
239
+ max?: number;
240
+ /** Fewest connections the pool keeps open. */
241
+ min?: number;
242
+ /** How long an idle connection stays open, as a Duration (`"30 seconds"`). */
243
+ idleTimeout?: Duration.Input;
244
+ /** How long a connection lives before the pool replaces it, as a Duration (`"30 minutes"`). */
245
+ maxLifetime?: Duration.Input;
246
+ /** How long opening a connection may take, as a Duration (`"10 seconds"`), to the millisecond (default 5 seconds). */
247
+ connectTimeout?: Duration.Input;
248
+ /** Cancel any statement that runs longer, as a Duration (`"30 seconds"`): the connection's `statement_timeout`, down to the millisecond. */
249
+ statementTimeout?: Duration.Input;
250
+ /** The name `pg_stat_activity.application_name` shows for these connections (default `"@effect/sql-pg"`). */
251
+ applicationName?: string;
252
+ /**
253
+ * Cache prepared statements (default `true`). Turn it off behind a pooler in
254
+ * transaction mode, such as Supabase's Supavisor on :6543.
255
+ */
256
+ prepare?: boolean;
257
+ }
258
+ type Tables = Record<string, unknown>;
259
+ /** What `createSQLiteDatabase` takes: `defineDatabase`'s SQLite options, and the file. */
260
+ interface SQLiteDatabaseConfig<TTables extends Tables = Tables> extends SQLiteOptions {
261
+ /** The database file, made with its folders when missing; `":memory:"` (the default) for tests. */
262
+ filename?: string;
263
+ /** The drizzle tables, so `db.query` knows them. */
264
+ tables?: TTables;
265
+ }
266
+ /** What `createPostgresDatabase` takes: `defineDatabase`'s Postgres options, and the URL. */
267
+ interface PostgresDatabaseConfig<TTables extends Tables = Tables> extends PostgresOptions {
268
+ /** The connection URL, such as `postgresql://user:pass@host:5432/dbname`. */
269
+ url: string;
270
+ /** The drizzle tables, so `db.query` knows them. */
271
+ tables?: TTables;
272
+ }
273
+ /**
274
+ * Open a SQLite database over drizzle's Effect driver, until the scope closes:
275
+ * the file's folders are made, `PRAGMA foreign_keys` is set, and the journal is
276
+ * the write-ahead log, unless `foreignKeys` or `wal` say otherwise. Needs
277
+ * `@effect/sql-sqlite-bun`, loaded here and nowhere else.
278
+ *
279
+ * @param config - The `filename` (default `":memory:"`), `tables`, `foreignKeys` and `wal`.
280
+ * @returns The drizzle database, whose queries are Effects.
281
+ * @example
282
+ * const db = yield* createSQLiteDatabase({ filename: "./data/app.db", tables: { pages } });
283
+ * const rows = yield* db.select().from(pages);
284
+ */
285
+ declare function createSQLiteDatabase<const TTables extends Tables = Record<never, never>>(config?: SQLiteDatabaseConfig<TTables>): Effect.Effect<EffectSQLiteBunDatabase<RelationsOf<TTables>>, SqlError, Scope.Scope>;
286
+ /**
287
+ * Open a Postgres database over drizzle's Effect driver, until the scope
288
+ * closes. Needs `@effect/sql-pg`, loaded here and nowhere else.
289
+ *
290
+ * @param config - The `url`, `tables`, and the connection's `ssl`, pool size (`max`, `min`), lifetimes (`idleTimeout`, `maxLifetime`, `connectTimeout`), `statementTimeout`, `applicationName` and `prepare`.
291
+ * @returns The drizzle database, whose queries are Effects.
292
+ * @example
293
+ * const db = yield* createPostgresDatabase({ url: process.env.DATABASE_URL!, ssl: true, max: 10 });
294
+ */
295
+ declare function createPostgresDatabase<const TTables extends Tables = Record<never, never>>(config: PostgresDatabaseConfig<TTables>): Effect.Effect<EffectPgDatabase<RelationsOf<TTables>>, SqlError, Scope.Scope>;
296
+ /**
297
+ * Declare a database over drizzle's Effect drivers. Queries are Effects:
298
+ * `yield* ctx.db.select().from(tables.pages)`. SQLite needs `@effect/sql-sqlite-bun`
299
+ * and Postgres `@effect/sql-pg`, loaded only for the engine in use. Nothing
300
+ * connects until the layer is built, so defining one has no side effects.
301
+ *
302
+ * @param config - The drizzle `tables`, and the SQLite file (`":memory:"` for tests) or the Postgres URL, with the engine's options: `foreignKeys` and `wal` for SQLite; `ssl`, `max`, `min`, `idleTimeout`, `maxLifetime`, `connectTimeout`, `statementTimeout`, `applicationName` and `prepare` for Postgres.
303
+ */
304
+ declare function defineDatabase<const TTables extends Record<string, unknown>>(config: {
305
+ tables: TTables;
306
+ sqlite: string;
307
+ } & SQLiteOptions & DatabaseNaming): DatabaseHandle<EffectSQLiteBunDatabase<RelationsOf<TTables>>, TTables>;
308
+ declare function defineDatabase<const TTables extends Record<string, unknown>>(config: {
309
+ tables: TTables;
310
+ postgres: string;
311
+ } & PostgresOptions & DatabaseNaming): DatabaseHandle<EffectPgDatabase<RelationsOf<TTables>>, TTables>;
312
+ /**
313
+ * A `timestamp with time zone` column read as text. Drizzle's own
314
+ * `timestamp(name, { mode: "string", withTimezone: true })` throws a defect on
315
+ * every non-null read through the Effect driver, because the driver hands the
316
+ * value over as a `Date` and drops the offset. This column takes that `Date` and
317
+ * gives it back as PostgreSQL would write it in UTC (`2026-12-01 10:11:12.123+00`).
318
+ *
319
+ * Writes go to the server as given, with their offset and every digit
320
+ * (`"2026-12-01 15:41:12.123456+05:30"`). Reads are the same instant in UTC, cut
321
+ * to the millisecond, as drizzle's `timestamp` string mode is. For a default use
322
+ * `.default(sql`now()`)`. The server takes `infinity` and `-infinity` as given,
323
+ * but the driver reads them as an invalid `Date` that cannot say which it was,
324
+ * so reading one fails with an error that says so: cast the column to text in
325
+ * SQL (`"at"::text`) or leave those rows out.
326
+ *
327
+ * @param name - The column's name in the table.
328
+ * @param config - `precision`: the fractional-second digits the column keeps, `0` to `6`.
329
+ * @example
330
+ * const calls = pgTable("calls", { startedAt: timestamptzText("started_at").notNull() });
331
+ */
332
+ declare const timestamptzText: {
333
+ <TConfig extends Record<string, any> & {
334
+ precision?: number;
335
+ }>(fieldConfig?: TConfig | undefined): import("drizzle-orm/pg-core").PgCustomColumnBuilder<{
336
+ dataType: 'custom';
337
+ data: string;
338
+ driverParam: string;
339
+ }>;
340
+ (dbName: string, fieldConfig?: {
341
+ precision?: number;
342
+ } | undefined): import("drizzle-orm/pg-core").PgCustomColumnBuilder<{
343
+ dataType: 'custom';
344
+ data: string;
345
+ driverParam: string;
346
+ }>;
347
+ };
348
+ /**
349
+ * Type-safe secrets & environment variables.
350
+ *
351
+ * Declare each secret once at module scope instead of scattering untyped
352
+ * `process.env.FOO` reads:
353
+ *
354
+ * const port = defineSecret("PORT").default("3333").transform(Number).require();
355
+ * const baseUrl = defineSecret("BASE_URL").url().require();
356
+ * const key = defineSecret("STRIPE_KEY").validate((v) =>
357
+ * v.startsWith("sk_") || "must start with sk_"
358
+ * ).require();
359
+ *
360
+ * Values resolve from the environment (Bun populates `process.env` from
361
+ * `.env` locally; in prod the same env source applies — a future
362
+ * `SecretSource` such as AWS can slot in without touching call sites).
363
+ *
364
+ * Resolution order per secret: test/session override → source (`process.env`
365
+ * by default) → declared `default`. `resolveSecrets()` validates every
366
+ * registered secret at boot and throws listing all missing required ones.
367
+ */
368
+ interface SecretSource {
369
+ get(name: string): string | undefined;
370
+ }
371
+ /** Default source: `process.env` (Bun loads `.env` into it automatically). */
372
+ declare const envSource: SecretSource;
373
+ interface SecretOptions {
374
+ /** Fallback when the source has no value. Secrets without a default are required. */
375
+ default?: string;
376
+ }
377
+ /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
378
+ type SecretValidator<T> = (value: T) => void | boolean | string;
379
+ declare class SecretRef<T = string> {
380
+ readonly name: string;
381
+ readonly options: SecretOptions;
382
+ private transformFn?;
383
+ private validators;
384
+ /** Validators declared before `transform`: they check the raw string. */
385
+ private rawValidators;
386
+ constructor(name: string, options?: SecretOptions);
387
+ /** True when a default was declared (i.e. the secret is optional). */
388
+ get hasDefault(): boolean;
389
+ /** Fallback used when the source has no value. Makes the secret optional. */
390
+ default(value: string): this;
391
+ /**
392
+ * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
393
+ * Validators declared before it check the raw string, those after it the
394
+ * converted value; a throwing transform fails resolution.
395
+ */
396
+ transform<U>(fn: (raw: string) => U): SecretRef<U>;
397
+ /** Run a custom check on the (transformed) value at every resolution. */
398
+ validate(fn: SecretValidator<T>): this;
399
+ /** Shorthand validator: value must parse as a URL. String refs only. */
400
+ url(this: SecretRef<string>): SecretRef<string>;
401
+ private resolveRaw;
402
+ private check;
403
+ private coerce;
404
+ /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
405
+ value(source?: SecretSource): T | undefined;
406
+ /** Resolved value, or throws naming the missing/invalid secret. */
407
+ require(source?: SecretSource): T;
408
+ /** True when a value would resolve (override, source, or default). */
409
+ isSet(source?: SecretSource): boolean;
410
+ }
411
+ /**
412
+ * Declare a secret. Calling it again for the name returns the same ref. From
413
+ * the same line (a module evaluated again) it starts the declaration over, so
414
+ * its builder calls replace the earlier ones instead of adding to them.
415
+ */
416
+ declare function defineSecret(name: string, options?: SecretOptions): SecretRef<string>;
417
+ /**
418
+ * Validate every registered secret at boot. Throws a single error listing
419
+ * all missing required secrets. Returns the resolved values.
420
+ */
421
+ declare function resolveSecrets(opts?: {
422
+ source?: SecretSource;
423
+ }): Record<string, unknown>;
424
+ /** Metadata for introspection (values never exposed — future dashboard use). */
425
+ declare function listSecrets(opts?: {
426
+ source?: SecretSource;
427
+ }): Array<{
428
+ name: string;
429
+ hasDefault: boolean;
430
+ isSet: boolean;
431
+ }>;
432
+ /** Test/session override for one secret (`undefined` clears the override). */
433
+ declare function overrideSecret(name: string, value: string | undefined): void;
434
+ /** Clear registry and overrides. Test-only. */
435
+ declare function resetSecrets(): void;
436
+ declare const StorageUnavailableError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
437
+ readonly _tag: "StorageUnavailableError";
438
+ } & Readonly<A>;
439
+ /** A storage could not be reached, or did not answer in time. Fails every call while it is down. A write that fails with it may still have been applied. */
440
+ declare class StorageUnavailableError extends StorageUnavailableError_base<{
441
+ readonly message: string;
442
+ readonly cause?: unknown;
443
+ }> {}
444
+ declare const StorageError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
445
+ readonly _tag: "StorageError";
446
+ } & Readonly<A>;
447
+ /** A call that storage refused: a `ttlMs` that is no positive integer, a key that holds no counter, a tenant or file id that is invalid, a file that could not be written or read. */
448
+ declare class StorageError extends StorageError_base<{
449
+ readonly message: string;
450
+ }> {}
451
+ /** What `put` returns: the id to keep, and what was stored. */
452
+ interface StoredFile {
453
+ id: string;
454
+ size: number;
455
+ contentType: string;
456
+ }
457
+ /** The files of one tenant. Ids are the ones `put` returned; nothing takes a key, a path or a URL. */
458
+ interface ScopedFiles {
459
+ /** Stores the file under a new id Brick generates. `contentType` defaults to the file's own type. */
460
+ put(file: Blob, options?: {
461
+ contentType?: string;
462
+ }): Effect.Effect<StoredFile, StorageError>;
463
+ /** A short-lived signed link that downloads the file as an attachment. `expiresInMs` defaults to 5 minutes. */
464
+ url(id: string, options?: {
465
+ expiresInMs?: number;
466
+ download?: string;
467
+ }): Effect.Effect<string, StorageError>;
468
+ /** The file, or `undefined` when this tenant has none with that id. */
469
+ get(id: string): Effect.Effect<Blob | undefined, StorageError>;
470
+ /** Removes the file; does nothing when this tenant has none with that id. */
471
+ delete(id: string): Effect.Effect<void, StorageError>;
472
+ }
473
+ /**
474
+ * The handle of a file storage. In a call, `ctx.deps.<name>` is scoped to the
475
+ * caller's tenant; outside one, name the tenant with `in(tenant)`.
476
+ */
477
+ interface FileStorage extends ScopedFiles {
478
+ readonly kind: "file";
479
+ /** The files of one tenant, for server code outside a request: a listener, a schedule, a webhook. */
480
+ in(tenant: string): ScopedFiles;
481
+ }
482
+ /** A file storage as a call sees it in `ctx.deps`: the caller's tenant only, with no `in`. */
483
+ interface CallFiles extends ScopedFiles {
484
+ readonly kind: "file";
485
+ }
486
+ /** Deps as a call sees them: each file storage scoped to the caller's tenant. */
487
+ type CallDeps<T> = { [K in keyof T]: CallDep<T[K]>; };
488
+ type CallDep<V> = V extends FileStorage ? CallFiles : V;
489
+ type RawDeps<T> = { [K in keyof T]: RawDep<T[K]>; };
490
+ type RawDep<V> = V extends CallFiles ? FileStorage : V;
491
+ /** A driver for file storage, such as `s3()`. It sees full keys; the handle builds them. */
492
+ interface FileDriver {
493
+ readonly kind: "file";
494
+ /** Put in front of every key. */
495
+ readonly prefix: string;
496
+ /** The directory files are written under, in local mode. */
497
+ readonly local?: string;
498
+ /** Throws when the driver cannot work as configured; `brick()` calls it at startup. */
499
+ check?(): void;
500
+ write(key: string, file: Blob, contentType: string): Promise<void>;
501
+ read(key: string): Promise<Blob | undefined>;
502
+ remove(key: string): Promise<void>;
503
+ /** A signed GET for the key, served with `contentDisposition`. */
504
+ sign(key: string, expiresInMs: number, contentDisposition: string): Promise<string>;
505
+ }
506
+ type Setting = string | SecretRef<string>;
507
+ /** Options of the `s3()` storage driver. Settings left out come from Bun's `S3_*` and `AWS_*` environment variables. */
508
+ interface S3StorageOptions {
509
+ bucket?: string;
510
+ /** Put in front of every key, such as `"files/"`. */
511
+ prefix?: string;
512
+ /** A directory: store files there instead of S3, for local development and tests. */
513
+ local?: string;
514
+ accessKeyId?: Setting;
515
+ secretAccessKey?: Setting;
516
+ sessionToken?: Setting;
517
+ region?: Setting;
518
+ /** An S3-compatible endpoint, such as R2 or MinIO. */
519
+ endpoint?: Setting;
520
+ }
521
+ declare const LOCAL_FILES_ROUTE = "/_brick/files";
522
+ /**
523
+ * File storage in S3 or an S3-compatible store (R2, MinIO), through Bun's
524
+ * built-in client. Nothing connects or reads credentials until the first call.
525
+ * With `local`, files are written under that directory instead.
526
+ *
527
+ * @param options - `bucket`, `prefix`, `local`, and the credentials and
528
+ * `endpoint` Bun's client takes, each a string or a `SecretRef`; left out,
529
+ * Bun's `S3_*` and `AWS_*` environment variables apply.
530
+ */
531
+ declare function s3(options?: S3StorageOptions): FileDriver;
532
+ /** What `increment` returns: the count after this hit, and when the counter expires. */
533
+ interface Counter {
534
+ count: number;
535
+ expiresInMs: number;
536
+ }
537
+ /** What `putIfAbsent` returns: whether this call stored its value, and the value now stored. */
538
+ interface PutIfAbsentResult {
539
+ stored: boolean;
540
+ value: string;
541
+ }
542
+ /** Key-value methods: values are strings, durations are milliseconds. */
543
+ interface KeyValueMethods {
544
+ /** The value, or `null` when the key is missing or expired. */
545
+ get(key: string): Effect.Effect<string | null, StorageError | StorageUnavailableError>;
546
+ /** Stores the value; without `ttlMs` it never expires. */
547
+ put(key: string, value: string, ttlMs?: number): Effect.Effect<void, StorageError | StorageUnavailableError>;
548
+ /** Stores the value unless the key exists; says whether it did, and the value now stored. Atomic. */
549
+ putIfAbsent(key: string, value: string, ttlMs: number): Effect.Effect<PutIfAbsentResult, StorageError | StorageUnavailableError>;
550
+ /** Adds 1 to a counter that expires `ttlMs` after its first hit. Atomic. Fails on a key that holds something other than an integer. */
551
+ increment(key: string, ttlMs: number): Effect.Effect<Counter, StorageError | StorageUnavailableError>;
552
+ delete(key: string): Effect.Effect<void, StorageError | StorageUnavailableError>;
553
+ /** Closes the connection, if any. The next call opens a new one. */
554
+ close(): Effect.Effect<void>;
555
+ }
556
+ /** A driver for key-value storage, such as `redis()` or `memory()`. It sees full keys. */
557
+ interface KeyValueDriver {
558
+ readonly kind: "key-value";
559
+ get(key: string): Promise<string | null>;
560
+ put(key: string, value: string, ttlMs?: number): Promise<void>;
561
+ putIfAbsent(key: string, value: string, ttlMs: number): Promise<PutIfAbsentResult>;
562
+ increment(key: string, ttlMs: number): Promise<Counter>;
563
+ delete(key: string): Promise<void>;
564
+ close(): Promise<void>;
565
+ /** Deletes the key only while it holds exactly `expected`; says whether it did. Atomic. */
566
+ compareAndDelete(key: string, expected: string): Promise<boolean>;
567
+ }
568
+ /** Every kind of storage driver; `kind` decides the handle `defineStorage` returns. */
569
+ type StorageDriver = KeyValueDriver | FileDriver;
570
+ /** The handle of a key-value storage. App keys live apart from Brick's own. */
571
+ interface KeyValueStorage extends KeyValueMethods {
572
+ readonly kind: "key-value";
573
+ /** Closes the storage when the app stops. Put it in the app's `layer`. */
574
+ readonly layer: Layer.Layer<never>;
575
+ }
576
+ /** Brick's side of a key-value storage: its keys live apart from the app's, and it can delete on a match. */
577
+ interface FrameworkStorage extends KeyValueMethods {
578
+ readonly kind: "key-value";
579
+ compareAndDelete(key: string, expected: string): Effect.Effect<boolean, StorageError | StorageUnavailableError>;
580
+ }
581
+ /** The handle `defineStorage` returns for a driver. */
582
+ type StorageOf<D extends StorageDriver> = D extends KeyValueDriver ? KeyValueStorage : D extends FileDriver ? FileStorage : never;
583
+ /** Brick's side of a storage the app defined, for the features that keep their own keys in it (rate limits, webhooks). */
584
+ declare const frameworkStorage: (storage: KeyValueStorage) => FrameworkStorage | undefined;
585
+ /** The key a feature stores under: its name, then its parts as JSON, with a part over 128 characters replaced by its digest. */
586
+ declare function storageKey(feature: string, parts: unknown[]): string;
587
+ /**
588
+ * Declare a storage. The driver decides its kind: `redis()` and `memory()` make
589
+ * key-value storage, `s3()` file storage kept per tenant. Nothing connects until
590
+ * the first call.
591
+ *
592
+ * @param options - `driver`: `redis({ url })`, or `memory()` for tests and local
593
+ * development; `s3({ bucket, prefix, local })` for files.
594
+ * @returns The handle. Key-value: `get`, `put`, `putIfAbsent`, `increment`,
595
+ * `delete` and `close`, each an Effect, and `layer`, which closes it with the
596
+ * app. File: `in(tenant)`, which has `put`, `url`, `get` and `delete`.
597
+ * @example
598
+ * export const cache = defineStorage({ driver: redis({ url: process.env.REDIS_URL }) });
599
+ * // in an action
600
+ * yield* cache.put(`otp:${input.email}`, code, 5 * 60_000);
601
+ */
602
+ declare function defineStorage<D extends StorageDriver>(options: {
603
+ driver: D;
604
+ }): StorageOf<D>;
605
+ /** Options of the `redis()` storage driver. */
606
+ interface RedisStorageOptions {
607
+ /** Defaults to `REDIS_URL`, then `redis://localhost:6379`. */
608
+ url?: string;
609
+ /** Put in front of every key, Brick's own included, so two apps or environments can share one Redis database. */
610
+ prefix?: string;
611
+ }
612
+ /**
613
+ * Key-value storage in Redis, through Bun's built-in client. Connects on first
614
+ * use and reconnects by itself. While Redis is unreachable, calls fail with
615
+ * `StorageUnavailableError`. A command Redis doesn't answer within a second
616
+ * fails the same way, and the connection is dropped so the next call opens a
617
+ * fresh one.
618
+ *
619
+ * @param options - `url`: defaults to `REDIS_URL`, then `redis://localhost:6379`.
620
+ * `prefix`: put in front of every key, to share one Redis database between apps.
621
+ */
622
+ declare function redis(options?: RedisStorageOptions): KeyValueDriver;
623
+ /**
624
+ * Key-value storage in this process's memory, for tests and local development.
625
+ * Lost on restart and not shared between processes.
626
+ */
627
+ declare function memory(): KeyValueDriver;
628
+ declare function sqliteAudit(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
629
+ name: string;
630
+ schema: undefined;
631
+ columns: {
632
+ seq: import("drizzle-orm/sqlite-core").SQLiteColumn<{
633
+ name: string;
634
+ tableName: string;
635
+ dataType: "number int53";
636
+ data: number;
637
+ driverParam: number;
638
+ notNull: true;
639
+ hasDefault: true;
640
+ isPrimaryKey: true;
641
+ isAutoincrement: false;
642
+ hasRuntimeDefault: false;
643
+ enumValues: undefined;
644
+ baseColumn: never;
645
+ identity: undefined;
646
+ generated: undefined;
647
+ }, {}>;
648
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
649
+ name: string;
650
+ tableName: string;
651
+ dataType: "string";
652
+ data: string;
653
+ driverParam: string;
654
+ notNull: true;
655
+ hasDefault: false;
656
+ isPrimaryKey: false;
657
+ isAutoincrement: false;
658
+ hasRuntimeDefault: false;
659
+ enumValues: [string, ...string[]];
660
+ baseColumn: never;
661
+ identity: undefined;
662
+ generated: undefined;
663
+ }, {}>;
664
+ at: import("drizzle-orm/sqlite-core").SQLiteColumn<{
665
+ name: string;
666
+ tableName: string;
667
+ dataType: "object date";
668
+ data: Date;
669
+ driverParam: number;
670
+ notNull: true;
671
+ hasDefault: false;
672
+ isPrimaryKey: false;
673
+ isAutoincrement: false;
674
+ hasRuntimeDefault: false;
675
+ enumValues: undefined;
676
+ baseColumn: never;
677
+ identity: undefined;
678
+ generated: undefined;
679
+ }, {}>;
680
+ service: import("drizzle-orm/sqlite-core").SQLiteColumn<{
681
+ name: string;
682
+ tableName: string;
683
+ dataType: "string";
684
+ data: string;
685
+ driverParam: string;
686
+ notNull: true;
687
+ hasDefault: false;
688
+ isPrimaryKey: false;
689
+ isAutoincrement: false;
690
+ hasRuntimeDefault: false;
691
+ enumValues: [string, ...string[]];
692
+ baseColumn: never;
693
+ identity: undefined;
694
+ generated: undefined;
695
+ }, {}>;
696
+ action: import("drizzle-orm/sqlite-core").SQLiteColumn<{
697
+ name: string;
698
+ tableName: string;
699
+ dataType: "string";
700
+ data: string;
701
+ driverParam: string;
702
+ notNull: true;
703
+ hasDefault: false;
704
+ isPrimaryKey: false;
705
+ isAutoincrement: false;
706
+ hasRuntimeDefault: false;
707
+ enumValues: [string, ...string[]];
708
+ baseColumn: never;
709
+ identity: undefined;
710
+ generated: undefined;
711
+ }, {}>;
712
+ resource: import("drizzle-orm/sqlite-core").SQLiteColumn<{
713
+ name: string;
714
+ tableName: string;
715
+ dataType: "string";
716
+ data: string;
717
+ driverParam: string;
718
+ notNull: false;
719
+ hasDefault: false;
720
+ isPrimaryKey: false;
721
+ isAutoincrement: false;
722
+ hasRuntimeDefault: false;
723
+ enumValues: [string, ...string[]];
724
+ baseColumn: never;
725
+ identity: undefined;
726
+ generated: undefined;
727
+ }, {}>;
728
+ recordId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
729
+ name: string;
730
+ tableName: string;
731
+ dataType: "string";
732
+ data: string;
733
+ driverParam: string;
734
+ notNull: false;
735
+ hasDefault: false;
736
+ isPrimaryKey: false;
737
+ isAutoincrement: false;
738
+ hasRuntimeDefault: false;
739
+ enumValues: [string, ...string[]];
740
+ baseColumn: never;
741
+ identity: undefined;
742
+ generated: undefined;
743
+ }, {}>;
744
+ actorId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
745
+ name: string;
746
+ tableName: string;
747
+ dataType: "string";
748
+ data: string;
749
+ driverParam: string;
750
+ notNull: false;
751
+ hasDefault: false;
752
+ isPrimaryKey: false;
753
+ isAutoincrement: false;
754
+ hasRuntimeDefault: false;
755
+ enumValues: [string, ...string[]];
756
+ baseColumn: never;
757
+ identity: undefined;
758
+ generated: undefined;
759
+ }, {}>;
760
+ actorLabel: import("drizzle-orm/sqlite-core").SQLiteColumn<{
761
+ name: string;
762
+ tableName: string;
763
+ dataType: "string";
764
+ data: string;
765
+ driverParam: string;
766
+ notNull: false;
767
+ hasDefault: false;
768
+ isPrimaryKey: false;
769
+ isAutoincrement: false;
770
+ hasRuntimeDefault: false;
771
+ enumValues: [string, ...string[]];
772
+ baseColumn: never;
773
+ identity: undefined;
774
+ generated: undefined;
775
+ }, {}>;
776
+ tenant: import("drizzle-orm/sqlite-core").SQLiteColumn<{
777
+ name: string;
778
+ tableName: string;
779
+ dataType: "string";
780
+ data: string;
781
+ driverParam: string;
782
+ notNull: false;
783
+ hasDefault: false;
784
+ isPrimaryKey: false;
785
+ isAutoincrement: false;
786
+ hasRuntimeDefault: false;
787
+ enumValues: [string, ...string[]];
788
+ baseColumn: never;
789
+ identity: undefined;
790
+ generated: undefined;
791
+ }, {}>;
792
+ traceId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
793
+ name: string;
794
+ tableName: string;
795
+ dataType: "string";
796
+ data: string;
797
+ driverParam: string;
798
+ notNull: false;
799
+ hasDefault: false;
800
+ isPrimaryKey: false;
801
+ isAutoincrement: false;
802
+ hasRuntimeDefault: false;
803
+ enumValues: [string, ...string[]];
804
+ baseColumn: never;
805
+ identity: undefined;
806
+ generated: undefined;
807
+ }, {}>;
808
+ requestId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
809
+ name: string;
810
+ tableName: string;
811
+ dataType: "string";
812
+ data: string;
813
+ driverParam: string;
814
+ notNull: false;
815
+ hasDefault: false;
816
+ isPrimaryKey: false;
817
+ isAutoincrement: false;
818
+ hasRuntimeDefault: false;
819
+ enumValues: [string, ...string[]];
820
+ baseColumn: never;
821
+ identity: undefined;
822
+ generated: undefined;
823
+ }, {}>;
824
+ meta: import("drizzle-orm/sqlite-core").SQLiteColumn<{
825
+ name: string;
826
+ tableName: string;
827
+ dataType: "object json";
828
+ data: unknown;
829
+ driverParam: string;
830
+ notNull: false;
831
+ hasDefault: false;
832
+ isPrimaryKey: false;
833
+ isAutoincrement: false;
834
+ hasRuntimeDefault: false;
835
+ enumValues: undefined;
836
+ baseColumn: never;
837
+ identity: undefined;
838
+ generated: undefined;
839
+ }, {}>;
840
+ };
841
+ dialect: 'sqlite';
842
+ isAlias: false;
843
+ }>;
844
+ declare function postgresAudit(name: string): import("drizzle-orm/pg-core").PgTableWithColumns<{
845
+ name: string;
846
+ schema: undefined;
847
+ columns: {
848
+ seq: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgBigSerial53Builder>, {
849
+ name: string;
850
+ tableName: string;
851
+ dataType: "number int53";
852
+ data: number;
853
+ driverParam: number;
854
+ notNull: true;
855
+ hasDefault: true;
856
+ isPrimaryKey: false;
857
+ isAutoincrement: false;
858
+ hasRuntimeDefault: false;
859
+ enumValues: undefined;
860
+ identity: undefined;
861
+ generated: undefined;
862
+ }>;
863
+ id: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
864
+ name: string;
865
+ tableName: string;
866
+ dataType: "string";
867
+ data: string;
868
+ driverParam: string;
869
+ notNull: true;
870
+ hasDefault: false;
871
+ isPrimaryKey: false;
872
+ isAutoincrement: false;
873
+ hasRuntimeDefault: false;
874
+ enumValues: undefined;
875
+ identity: undefined;
876
+ generated: undefined;
877
+ }>;
878
+ at: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>, {
879
+ name: string;
880
+ tableName: string;
881
+ dataType: "object date";
882
+ data: Date;
883
+ driverParam: string;
884
+ notNull: true;
885
+ hasDefault: false;
886
+ isPrimaryKey: false;
887
+ isAutoincrement: false;
888
+ hasRuntimeDefault: false;
889
+ enumValues: undefined;
890
+ identity: undefined;
891
+ generated: undefined;
892
+ }>;
893
+ service: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
894
+ name: string;
895
+ tableName: string;
896
+ dataType: "string";
897
+ data: string;
898
+ driverParam: string;
899
+ notNull: true;
900
+ hasDefault: false;
901
+ isPrimaryKey: false;
902
+ isAutoincrement: false;
903
+ hasRuntimeDefault: false;
904
+ enumValues: undefined;
905
+ identity: undefined;
906
+ generated: undefined;
907
+ }>;
908
+ action: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
909
+ name: string;
910
+ tableName: string;
911
+ dataType: "string";
912
+ data: string;
913
+ driverParam: string;
914
+ notNull: true;
915
+ hasDefault: false;
916
+ isPrimaryKey: false;
917
+ isAutoincrement: false;
918
+ hasRuntimeDefault: false;
919
+ enumValues: undefined;
920
+ identity: undefined;
921
+ generated: undefined;
922
+ }>;
923
+ resource: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
924
+ name: string;
925
+ tableName: string;
926
+ dataType: "string";
927
+ data: string;
928
+ driverParam: string;
929
+ notNull: false;
930
+ hasDefault: false;
931
+ isPrimaryKey: false;
932
+ isAutoincrement: false;
933
+ hasRuntimeDefault: false;
934
+ enumValues: undefined;
935
+ identity: undefined;
936
+ generated: undefined;
937
+ }>;
938
+ recordId: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
939
+ name: string;
940
+ tableName: string;
941
+ dataType: "string";
942
+ data: string;
943
+ driverParam: string;
944
+ notNull: false;
945
+ hasDefault: false;
946
+ isPrimaryKey: false;
947
+ isAutoincrement: false;
948
+ hasRuntimeDefault: false;
949
+ enumValues: undefined;
950
+ identity: undefined;
951
+ generated: undefined;
952
+ }>;
953
+ actorId: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
954
+ name: string;
955
+ tableName: string;
956
+ dataType: "string";
957
+ data: string;
958
+ driverParam: string;
959
+ notNull: false;
960
+ hasDefault: false;
961
+ isPrimaryKey: false;
962
+ isAutoincrement: false;
963
+ hasRuntimeDefault: false;
964
+ enumValues: undefined;
965
+ identity: undefined;
966
+ generated: undefined;
967
+ }>;
968
+ actorLabel: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
969
+ name: string;
970
+ tableName: string;
971
+ dataType: "string";
972
+ data: string;
973
+ driverParam: string;
974
+ notNull: false;
975
+ hasDefault: false;
976
+ isPrimaryKey: false;
977
+ isAutoincrement: false;
978
+ hasRuntimeDefault: false;
979
+ enumValues: undefined;
980
+ identity: undefined;
981
+ generated: undefined;
982
+ }>;
983
+ tenant: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
984
+ name: string;
985
+ tableName: string;
986
+ dataType: "string";
987
+ data: string;
988
+ driverParam: string;
989
+ notNull: false;
990
+ hasDefault: false;
991
+ isPrimaryKey: false;
992
+ isAutoincrement: false;
993
+ hasRuntimeDefault: false;
994
+ enumValues: undefined;
995
+ identity: undefined;
996
+ generated: undefined;
997
+ }>;
998
+ traceId: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
999
+ name: string;
1000
+ tableName: string;
1001
+ dataType: "string";
1002
+ data: string;
1003
+ driverParam: string;
1004
+ notNull: false;
1005
+ hasDefault: false;
1006
+ isPrimaryKey: false;
1007
+ isAutoincrement: false;
1008
+ hasRuntimeDefault: false;
1009
+ enumValues: undefined;
1010
+ identity: undefined;
1011
+ generated: undefined;
1012
+ }>;
1013
+ requestId: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
1014
+ name: string;
1015
+ tableName: string;
1016
+ dataType: "string";
1017
+ data: string;
1018
+ driverParam: string;
1019
+ notNull: false;
1020
+ hasDefault: false;
1021
+ isPrimaryKey: false;
1022
+ isAutoincrement: false;
1023
+ hasRuntimeDefault: false;
1024
+ enumValues: undefined;
1025
+ identity: undefined;
1026
+ generated: undefined;
1027
+ }>;
1028
+ meta: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgJsonbBuilder, {
1029
+ name: string;
1030
+ tableName: string;
1031
+ dataType: "object json";
1032
+ data: unknown;
1033
+ driverParam: unknown;
1034
+ notNull: false;
1035
+ hasDefault: false;
1036
+ isPrimaryKey: false;
1037
+ isAutoincrement: false;
1038
+ hasRuntimeDefault: false;
1039
+ enumValues: undefined;
1040
+ identity: undefined;
1041
+ generated: undefined;
1042
+ }>;
1043
+ };
1044
+ dialect: 'pg';
1045
+ isAlias: false;
1046
+ }>;
1047
+ /** The audit table of a SQLite database. */
1048
+ type SQLiteAuditTable = ReturnType<typeof sqliteAudit>;
1049
+ /** The audit table of a Postgres database. */
1050
+ type PostgresAuditTable = ReturnType<typeof postgresAudit>;
1051
+ /** An audit table, made by `auditTable`. */
1052
+ type AuditTable = SQLiteAuditTable | PostgresAuditTable;
1053
+ /**
1054
+ * The audit table: one row per change, saying who made it, what ran and on
1055
+ * which record. A service whose database holds it records every action that is
1056
+ * not a `GET`. Brick only ever inserts into it. It has the columns of
1057
+ * `@brickkit/core`'s, so a migrating app keeps its log.
1058
+ *
1059
+ * Brick does not create tables for you: put this in the database's tables and
1060
+ * your migration tool (such as drizzle-kit) creates it. The service must
1061
+ * declare an `identity`: that is where the actor comes from, its `id`, and
1062
+ * optional `label` and `tenant`.
1063
+ *
1064
+ * @param engine - The database engine, `"sqlite"` or `"postgres"`.
1065
+ * @param options - `name` to call the table something other than `brick_audit`.
1066
+ * @example
1067
+ * export const auditLog = auditTable("postgres");
1068
+ * export const database = defineDatabase({ tables: { orders, auditLog }, postgres: url });
1069
+ */
1070
+ declare function auditTable(engine: "sqlite", options?: {
1071
+ name?: string;
1072
+ }): SQLiteAuditTable;
1073
+ declare function auditTable(engine: "postgres", options?: {
1074
+ name?: string;
1075
+ }): PostgresAuditTable;
1076
+ /** Whether a value is an audit table made by `auditTable`. */
1077
+ declare function isAuditTable(value: unknown): value is AuditTable;
1078
+ /** What an action says of its audit row. `false` leaves the action out. */
1079
+ interface AuditOptions<TInput = any, TOutput = any> {
1080
+ /** Which kind of record the action changes. */
1081
+ readonly resource?: string;
1082
+ /** Which record: its id, as a string or number; anything else is stored as JSON. */
1083
+ readonly record?: (args: {
1084
+ input: TInput;
1085
+ result: TOutput;
1086
+ }) => unknown;
1087
+ }
1088
+ /**
1089
+ * Record a change of your own from an action: for what Brick cannot see, or to
1090
+ * add `meta`. By default the row is inserted at once. Pass the `tx` of a
1091
+ * transaction you have open to commit it with your writes instead: once `tx`
1092
+ * commits it is the record of this call, and Brick does not add the automatic
1093
+ * row (when `tx` rolls back, it does).
1094
+ *
1095
+ * Brick copies no input or output into the log: `meta` holds what you pass.
1096
+ *
1097
+ * @param ctx - The action context: it names the service and the actor.
1098
+ * @param entry - `action` defaults to the running action's name, and is needed
1099
+ * in an action that is not itself recorded (a `GET`, `audit: false`).
1100
+ * `resource` and `recordId` say which record; `meta` is JSON of your choosing.
1101
+ * @param options - `tx`: an open transaction on the service's database.
1102
+ * @example
1103
+ * yield* recordAudit(ctx, { resource: "order", recordId: input.orderId, meta: { reason: input.reason } });
1104
+ */
1105
+ declare const recordAudit: (ctx: object, entry: {
1106
+ action?: string;
1107
+ resource?: string;
1108
+ recordId?: string | number;
1109
+ meta?: unknown;
1110
+ }, options?: {
1111
+ tx?: any;
1112
+ }) => Effect.Effect<void, unknown>;
1113
+ /**
1114
+ * A limit on how often an action runs: at most `max` calls per `windowMs`, per key.
1115
+ * A fixed window, counted in the service's or the app's key-value storage.
1116
+ */
1117
+ interface RateLimit<TInput = any, TCtx = any> {
1118
+ /**
1119
+ * Whose calls count together: `"actor"` (the service's `identity`; an
1120
+ * anonymous caller counts by IP), `"ip"` (the client address; skipped when
1121
+ * there is none, as in-process), or a function of the validated input and
1122
+ * the context. A function that returns `null` or `undefined` skips this
1123
+ * limit for the call.
1124
+ */
1125
+ readonly per: "actor" | "ip" | ((args: {
1126
+ input: TInput;
1127
+ ctx: TCtx;
1128
+ }) => string | null | undefined);
1129
+ /** Calls allowed per window. */
1130
+ readonly max: number;
1131
+ /** The window's length in milliseconds. */
1132
+ readonly windowMs: number;
1133
+ }
1134
+ /** One limit, or several that all apply. */
1135
+ type RateLimits<TInput = any, TCtx = any> = RateLimit<TInput, TCtx> | readonly RateLimit<TInput, TCtx>[];
1136
+ /** Where an app finds the client address, given the request and the socket peer: a non-empty string, or `undefined` for none. It must not be async. */
1137
+ type ClientIp = (args: {
1138
+ request: Request;
1139
+ peer: string | undefined;
1140
+ }) => string | undefined;
1141
+ /**
1142
+ * The client address of a call as rate limits count it, or `undefined` when it
1143
+ * has none: in-process without a request, or `app.handle` without `clientIp`.
1144
+ * An IPv4-mapped or NAT64 IPv6 address counts as its IPv4 address, any other
1145
+ * IPv6 address by its /64, and every spelling of one address the same. For a
1146
+ * custom `per` that combines it with another key.
1147
+ *
1148
+ * @throws When `clientIp` returns anything but a non-empty string or `undefined`.
1149
+ */
1150
+ declare function clientAddress(ctx: {
1151
+ request?: Request;
1152
+ }): string | undefined;
1153
+ /**
1154
+ * The schema, unchanged in type and validation, marked sensitive. Its value is
1155
+ * kept out of logs and error responses for the rest of the call, an output
1156
+ * field with it is removed unless `reveal` allows it, and OpenAPI marks it
1157
+ * `writeOnly`.
1158
+ *
1159
+ * @example
1160
+ * Schema.Struct({ user: Schema.String, password: Sensitive(Schema.String) })
1161
+ */
1162
+ declare function Sensitive<S extends Schema.Top>(schema: S): S["Rebuild"];
1163
+ /** Whether any part of a schema is marked `Sensitive`. */
1164
+ declare const hasSensitive: (schema: unknown) => boolean;
1165
+ /**
1166
+ * Whether the call may see a sensitive output field: `true` for every one, or
1167
+ * an Effect per field, given its JSON pointer. Anything but `true`, and a
1168
+ * failure, removes the field.
1169
+ */
1170
+ type Reveal<TInput = unknown, TCtx = any> = boolean | ((args: {
1171
+ field: string;
1172
+ input: TInput;
1173
+ ctx: TCtx;
1174
+ }) => Effect.Effect<boolean, any, never>);
1175
+ /**
1176
+ * Keep a secret out of what the rest of the call logs: its logger and its
1177
+ * error responses replace it with `[REDACTED]`. Call it as soon as `execute`
1178
+ * loads a secret, before it can be logged. It takes each string and number in
1179
+ * the value, as a `Sensitive` field's value is taken: booleans, and numbers
1180
+ * under 4 digits, are left out. Outside a call with sensitive fields it does nothing.
1181
+ *
1182
+ * @example
1183
+ * const key = yield* loadKey(input.id);
1184
+ * yield* redact(key);
1185
+ */
1186
+ declare const redact: (value: unknown) => Effect.Effect<void>;
1187
+ /** The HTTP methods an action can use. */
1188
+ declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE"];
1189
+ /** One of the methods in `HTTP_METHODS`. */
1190
+ type HttpMethod = (typeof HTTP_METHODS)[number];
1191
+ /** A schema that needs no services to decode or encode. */
1192
+ type AnySchema = Schema.ConstraintCodec<any, any>;
1193
+ /** A declared error code: its default message and HTTP status. */
1194
+ interface ErrorDefinition {
1195
+ readonly message: string;
1196
+ /** The HTTP status (default 400). */
1197
+ readonly status?: number;
1198
+ }
1199
+ /** The `errors` of an action: a definition per code. */
1200
+ type ErrorDefinitions = {
1201
+ readonly [code: string]: ErrorDefinition;
1202
+ };
1203
+ /** One function per error code, standard ones included. `yield* error.NOT_FOUND()` fails the call with that code. */
1204
+ type ErrorHelpers<TErrors extends ErrorDefinitions> = { readonly [K in StandardErrorCode | Extract<keyof TErrors, string>]: (message?: string, details?: unknown) => Effect.Effect<never, BrickError>; };
1205
+ type InputOf$2<S> = S extends AnySchema ? S["Type"] : undefined;
1206
+ type ResultOf$1<S, A> = S extends AnySchema ? S["Type"] : A;
1207
+ /** Where `authorize` is declared, `execute` can rely on `ctx.user`. */
1208
+ type Narrow<TCtx> = TCtx extends {
1209
+ user: infer U;
1210
+ } ? Omit<TCtx, "user"> & {
1211
+ user: NonNullable<U>;
1212
+ } : TCtx;
1213
+ /** What `execute` and `authorize` receive. */
1214
+ interface ActionParams<TInput, TCtx, TErrors extends ErrorDefinitions> {
1215
+ readonly input: InputOf$2<TInput>;
1216
+ readonly ctx: TCtx;
1217
+ readonly error: ErrorHelpers<TErrors>;
1218
+ }
1219
+ /** The `ctx` of an action defined outside a service (`defineAction`, `defineTool`), until a service takes it. */
1220
+ type ActionContext = BaseContext & {
1221
+ user: any;
1222
+ [key: string]: any;
1223
+ };
1224
+ /** The declaration of an action, but for what it does with the call. */
1225
+ interface ActionConfigBase<TInput extends AnySchema | undefined, TOutput extends AnySchema | undefined, TErrors extends ErrorDefinitions> {
1226
+ readonly name: string;
1227
+ readonly description?: string;
1228
+ /** POST unless set. GET and DELETE read their input from the query string. */
1229
+ readonly method?: HttpMethod;
1230
+ /** Relative to the service's route: `/documents/:name`. Path parameters are strings: decode them with `Schema.NumberFromString` and the like. */
1231
+ readonly path?: string;
1232
+ readonly tags?: readonly string[];
1233
+ /** The events the action emits, for the architecture and the dashboard. It documents; it does not check what `execute` records. */
1234
+ readonly emits?: readonly string[];
1235
+ /** Decoded from the call: the JSON body, the query string, or the value `run` is given. */
1236
+ readonly input?: TInput;
1237
+ /** The result is checked against it, and encoded for the response. */
1238
+ readonly output?: TOutput;
1239
+ /** Error codes of its own, which `error.CODE()` raises and OpenAPI lists. */
1240
+ readonly errors?: TErrors;
1241
+ /**
1242
+ * Reject keys the `input` schema does not declare instead of dropping them.
1243
+ * `true` checks the root object only, as core does with `additionalProperties: false` on the root:
1244
+ * extra keys inside nested objects are still dropped. `"deep"` checks every object.
1245
+ */
1246
+ readonly strict?: boolean | "deep";
1247
+ /** Runs on the raw input before it is decoded. Returns the issues that reject it. */
1248
+ readonly checkInput?: (input: unknown) => ReadonlyArray<ValidationIssue> | undefined;
1249
+ /** Only the dashboard may call it: through its `/app/*` proxy, which signs the caller. Anyone else gets `UNAUTHORIZED` (401). `ctx.dashboard` is then set. */
1250
+ readonly dashboard?: boolean;
1251
+ }
1252
+ /** An action that anyone may call. */
1253
+ interface ActionConfig<TInput extends AnySchema | undefined, TOutput extends AnySchema | undefined, TErrors extends ErrorDefinitions, TCtx, A, E, R> extends ActionConfigBase<TInput, TOutput, TErrors> {
1254
+ readonly authorize?: undefined;
1255
+ readonly execute: (params: ActionParams<TInput, TCtx, TErrors>) => Effect.Effect<ResultOf$1<TOutput, A>, E, R>;
1256
+ }
1257
+ /**
1258
+ * An action with an `authorize` step. It returns `false` to refuse the call:
1259
+ * `UNAUTHORIZED` (401) with no `ctx.user`, `FORBIDDEN` (403) with one. Where it
1260
+ * is given, `execute` can rely on `ctx.user`.
1261
+ */
1262
+ interface AuthorizedActionConfig<TInput extends AnySchema | undefined, TOutput extends AnySchema | undefined, TErrors extends ErrorDefinitions, TCtx, A, E, R, RA> extends ActionConfigBase<TInput, TOutput, TErrors> {
1263
+ readonly authorize: (params: ActionParams<TInput, TCtx, TErrors>) => Effect.Effect<boolean, any, RA>;
1264
+ readonly execute: (params: ActionParams<TInput, Narrow<TCtx>, TErrors>) => Effect.Effect<ResultOf$1<TOutput, A>, E, R>;
1265
+ }
1266
+ /** What a plugin adds to the checks of the actions it registers. */
1267
+ interface PluginActionChecks {
1268
+ /** Checked instead of `output` at run time, while `output` stays the published contract (OpenAPI, client types). */
1269
+ readonly runtimeOutput?: AnySchema;
1270
+ /** Runs before the input is decoded, in-process and over HTTP. The issues it returns reject the input with a 400. */
1271
+ readonly checkInput?: (input: unknown) => ReadonlyArray<ValidationIssue> | undefined;
1272
+ }
1273
+ /** The declaration of any action, as the pipeline sees it. */
1274
+ type AnyActionConfig = ActionConfigBase<any, any, any> & PluginActionChecks & {
1275
+ readonly authorize?: (params: any) => Effect.Effect<boolean, any, any>;
1276
+ readonly execute: (params: any) => Effect.Effect<any, any, any>;
1277
+ /** At most `max` calls per `windowMs`, per key. */
1278
+ readonly rateLimit?: RateLimits | undefined;
1279
+ /** Whether a call may see the output's `Sensitive` fields. */
1280
+ readonly reveal?: Reveal<any> | undefined;
1281
+ /** What the audit row says, or `false` for none. */
1282
+ readonly audit?: false | AuditOptions | undefined;
1283
+ };
1284
+ /** How the input of a call arrived: as a JSON body, as a query string, or as a multipart form. In-process calls have none. */
1285
+ type Wire = "json" | "query" | "form";
1286
+ /** What `action.execute` takes: the input, and the context the caller carries. */
1287
+ interface ExecuteParams<TInput> {
1288
+ readonly input?: InputOf$2<TInput>;
1289
+ readonly ctx?: CallContext;
1290
+ /** Set by the HTTP server: `input` is raw JSON or query data, and the result is the JSON body. */
1291
+ readonly wire?: Wire;
1292
+ }
1293
+ type RunArgs<TInput> = TInput extends AnySchema ? [input: TInput["Type"], ctx?: CallContext] : [input?: undefined, ctx?: CallContext];
1294
+ /** A declared action: serve it with `brick`, or call it with `run`. */
1295
+ interface Action<TInput extends AnySchema | undefined, TOutput extends AnySchema | undefined, TErrors extends ErrorDefinitions, A, R> {
1296
+ readonly name: string;
1297
+ readonly serviceName: string;
1298
+ readonly config: ActionConfigBase<TInput, TOutput, TErrors> & Pick<AnyActionConfig, "authorize" | "execute" | "rateLimit">;
1299
+ /**
1300
+ * Run the whole call in-process, as over HTTP: resolve the context, check the
1301
+ * input, authorize, execute, check the output. Fails with a `BrickError` or a
1302
+ * `ValidationError`; anything else that goes wrong is logged and becomes a 500.
1303
+ */
1304
+ run(...args: RunArgs<TInput>): Effect.Effect<ResultOf$1<TOutput, A>, BrickError | ValidationError, R>;
1305
+ execute(params: ExecuteParams<TInput>): Effect.Effect<ResultOf$1<TOutput, A>, BrickError | ValidationError, R>;
1306
+ /** Set on a webhook, for the server and OpenAPI. */
1307
+ readonly webhook?: {
1308
+ readonly maxBodyBytes: number;
1309
+ readonly replay: false | {
1310
+ readonly ttlMs: number;
1311
+ };
1312
+ };
1313
+ /** Set on a webhook: answers a delivery, given the request. The result may be a `Response`. */
1314
+ readonly deliver?: (request: Request, ctx: CallContext) => Effect.Effect<unknown, BrickError | ValidationError, R>;
1315
+ }
1316
+ /** Any action, whatever its schemas. */
1317
+ type AnyAction = Action<any, any, any, any, any>;
1318
+ /** What a stage sees of a call. `input` is raw until the `input` stage replaces it with the decoded one. */
1319
+ interface Call {
1320
+ readonly input: unknown;
1321
+ readonly ctx: any;
1322
+ readonly error: ErrorHelpers<ErrorDefinitions>;
1323
+ readonly wire?: Wire | undefined;
1324
+ /** The id of the delivery, in a webhook that remembers the events it has handled. */
1325
+ readonly eventId?: string | undefined;
1326
+ }
1327
+ /** Continues a call with the next stage. */
1328
+ type Next = (call: Call) => Effect.Effect<unknown, unknown, any>;
1329
+ /** One step of the pipeline. It runs `next` to continue, or fails to stop the call. */
1330
+ interface Stage {
1331
+ readonly name: string;
1332
+ readonly run: (call: Call, next: Next) => Effect.Effect<unknown, unknown, any>;
1333
+ }
1334
+ /**
1335
+ * The stages of an action, outermost first: `dashboard` → `checkInput` →
1336
+ * `input` → `sensitive` → `rateLimit` → `authorize` → `audit` → `output` →
1337
+ * `execute`. This is where the order of a call is decided, as in core. A stage
1338
+ * a call has no use for is left out.
1339
+ */
1340
+ declare function stagesOf(config: AnyActionConfig, host: ActionHost,
1341
+ /** The action these stages run, so `setActionAudit` can change how it is recorded. */
1342
+ action?: () => object): readonly Stage[];
1343
+ /** Runs a call through its stages. */
1344
+ declare const runStages: (stages: readonly Stage[], call: Call) => Effect.Effect<unknown, unknown, any>;
1345
+ /** What an action needs of the service it was declared on. */
1346
+ interface ActionHost {
1347
+ readonly name: string;
1348
+ readonly hasIdentity: boolean;
1349
+ readonly storage: KeyValueStorage | undefined;
1350
+ readonly database: DatabaseHandle<any, any> | undefined;
1351
+ readonly resolveContext: (call?: CallContext) => Effect.Effect<unknown, unknown, any>;
1352
+ }
1353
+ /**
1354
+ * One declared event. Pass it to `defineListener({ on })` for a typed payload,
1355
+ * or to `emitEvent` for a checked one.
1356
+ */
1357
+ interface EventRef<TPayload = unknown> {
1358
+ /** The event name on the wire: `<service>.<event>`, such as `orders.shipped`. */
1359
+ readonly name: string;
1360
+ readonly service: string;
1361
+ readonly schema: AnySchema;
1362
+ /** The plugin that declared it, for events a `definePlugin` adds. */
1363
+ readonly plugin?: string;
1364
+ /** Type-level only: the payload this event carries. */
1365
+ readonly __payload?: TPayload;
1366
+ }
1367
+ /** The events of a catalog: one `EventRef` per entry. */
1368
+ type EventRefs<C extends Record<string, AnySchema>> = { readonly [K in keyof C & string]: EventRef<C[K]["Type"]>; };
1369
+ /**
1370
+ * Declare the events a service emits, with the schema of each payload.
1371
+ * Listeners that take one of them get a typed payload, and `emitEvent` checks
1372
+ * the payload against its schema.
1373
+ *
1374
+ * @param service - The service the events belong to: their names are `<service>.<event>`.
1375
+ * @param catalog - A payload schema per event, named like `shipped` or `itemAdded`.
1376
+ * @throws When an event name is not a plain name, a payload is not a schema, or it marks a field `Sensitive`.
1377
+ * @example
1378
+ * const events = defineEvents("orders", {
1379
+ * shipped: Schema.Struct({ id: Schema.String, trackingId: Schema.String }),
1380
+ * });
1381
+ * // events.shipped.name === "orders.shipped"
1382
+ */
1383
+ declare function defineEvents<const C extends Record<string, AnySchema>>(service: string, catalog: C): EventRefs<C>;
1384
+ /** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
1385
+ declare const CRUD_EVENT_OPERATIONS: readonly ["create", "update", "delete"];
1386
+ type CrudEventOperation = (typeof CRUD_EVENT_OPERATIONS)[number];
1387
+ /** The event a CRUD write records: `<resource>.<operation>`. */
1388
+ declare const crudEventName: (resource: string, operation: CrudEventOperation) => string;
1389
+ /** The `source` of a resource's events: `<service>.<resource>`. */
1390
+ declare const crudEventSource: (service: string, resource: string) => string;
1391
+ /** Whether `name` is the CRUD event of one of `resources`. */
1392
+ declare function isCrudEvent(name: string, resources: readonly string[]): boolean;
1393
+ /** What a service with a catalog checks before recording an event. */
1394
+ interface EventChecker {
1395
+ readonly name: string;
1396
+ readonly events: Readonly<Record<string, EventRef>>;
1397
+ /** Whether the service declared a catalog at all. */
1398
+ readonly hasCatalog: boolean;
1399
+ listResources(): readonly {
1400
+ name: string;
1401
+ }[];
1402
+ }
1403
+ /** What a verifier sees of a delivery. */
1404
+ interface WebhookRequest {
1405
+ /** The body exactly as it arrived. */
1406
+ readonly rawBody: Uint8Array;
1407
+ readonly headers: Headers;
1408
+ readonly url: string;
1409
+ readonly method: string;
1410
+ }
1411
+ /**
1412
+ * Decides whether the provider sent a delivery. `false`, a failure or a defect
1413
+ * refuses it (401); `true` accepts; `{ eventId }` accepts and names the event.
1414
+ * Set `suppliesEventId` on a verifier that always returns one, so a webhook
1415
+ * needs no `eventId` option.
1416
+ */
1417
+ type WebhookVerifier = ((request: WebhookRequest) => Effect.Effect<boolean | {
1418
+ eventId: string | number;
1419
+ }, unknown>) & {
1420
+ suppliesEventId?: true;
1421
+ /** Set on a verifier that signs the body (a GET has none, so it cannot serve one). */
1422
+ signsBody?: true;
1423
+ };
1424
+ type InputOf$1<S> = S extends AnySchema ? S["Type"] : undefined;
1425
+ /** What `service.webhook` takes. */
1426
+ interface WebhookConfig<TInput extends AnySchema, TErrors extends ErrorDefinitions, TCtx, A, E, R> extends Pick<ActionConfigBase<TInput, undefined, TErrors>, "description" | "path" | "tags" | "errors"> {
1427
+ /** Its route is `<method> /api/<service>/<name>` (POST by default), as for an action. */
1428
+ readonly name: string;
1429
+ /** Default `"POST"`. With `"GET"` the input is the query string. */
1430
+ readonly method?: "POST" | "GET";
1431
+ /** Runs first, on the raw body. Nothing else runs until it accepts. */
1432
+ readonly verify: WebhookVerifier;
1433
+ /** The payload: JSON, or a form (`application/x-www-form-urlencoded`). Properties it does not declare are dropped. */
1434
+ readonly input: TInput;
1435
+ /**
1436
+ * The delivery's id, so one sent twice runs once: a non-empty string or a
1437
+ * safe integer (`7` and `"7"` are one id); anything else, `undefined`
1438
+ * included, is no id. Not needed when the verifier supplies one.
1439
+ */
1440
+ readonly eventId?: (args: {
1441
+ input: InputOf$1<TInput>;
1442
+ headers: Headers;
1443
+ url: string;
1444
+ method: string;
1445
+ }) => Effect.Effect<string | number | undefined>;
1446
+ /** `false` runs every delivery, with no check for repeats. Else `ttlMs` is how long a handled id is remembered (default 7 days); the service's or the app's key-value storage remembers it. */
1447
+ readonly replay?: false | {
1448
+ readonly ttlMs?: number;
1449
+ };
1450
+ /** Largest body accepted, in bytes (default 1 MiB). */
1451
+ readonly maxBodyBytes?: number;
1452
+ /** At most `max` deliveries per `windowMs`, per key, counted in the service's or the app's key-value storage. */
1453
+ readonly rateLimit?: RateLimits<InputOf$1<TInput>, TCtx>;
1454
+ /** The delivery's audit row when the service's database holds an audit table: written when the handler returns, not for a refused or repeated delivery or one whose handler fails. `false` leaves it out. */
1455
+ readonly audit?: false | AuditOptions<InputOf$1<TInput>, unknown>;
1456
+ /** What the provider is answered: the return value, which may be a `Response`; `{ ok: true }` for nothing. */
1457
+ readonly execute: (params: ActionParams<TInput, TCtx, TErrors> & {
1458
+ /** `undefined` when `replay` is `false` and the delivery has no id. */
1459
+ readonly eventId: string | undefined;
1460
+ }) => Effect.Effect<A, E, R>;
1461
+ }
1462
+ /** Whether an action was declared with `service.webhook`. */
1463
+ declare function isWebhook(action: object): boolean;
1464
+ /** The events of one direction of a socket, each with the Schema of its payload. Payloads travel as JSON. */
1465
+ type SocketSchemas = Record<string, AnySchema>;
1466
+ type SocketPayloads<S extends SocketSchemas> = { [K in keyof S]: S[K]["Type"]; };
1467
+ type SocketEventArgs<Events> = { [K in keyof Events & string]: [event: K, payload: Events[K]]; }[keyof Events & string];
1468
+ /** What an `emit` takes beside the event and its payload. */
1469
+ interface SocketEmitOptions {
1470
+ /** The `tx` of a `runInTransaction`: the emit is sent when that transaction commits, and dropped when it rolls back. Outside one it is sent at once. */
1471
+ readonly after?: unknown;
1472
+ }
1473
+ type SocketEmitArgs<Events> = { [K in keyof Events & string]: [event: K, payload: Events[K], options?: SocketEmitOptions]; }[keyof Events & string];
1474
+ /** What a handler sends through. Each call is an Effect that does nothing until it runs. */
1475
+ interface BrickSocketSender<Events> {
1476
+ /** Locally accepts a message. Does not acknowledge remote delivery. An invalid payload or a closed socket is a defect. */
1477
+ send(...args: SocketEventArgs<Events>): Effect.Effect<void>;
1478
+ close(): Effect.Effect<void>;
1479
+ }
1480
+ interface SocketReplay {
1481
+ /** Emits kept per room. */
1482
+ keep: number;
1483
+ /** How long a room's history lasts without new emits. */
1484
+ maxAgeMs: number;
1485
+ }
1486
+ /** The declaration of `service.socket`. Every callback returns an Effect, and may need the services of the app's `layer`. */
1487
+ interface SocketConfig<I extends SocketSchemas, O extends SocketSchemas, Ctx, TErrors extends ErrorDefinitions = {}> {
1488
+ readonly name: string;
1489
+ /** Relative to the service's route, static: `/live`. Default: the kebab-cased `name`. */
1490
+ readonly path?: string;
1491
+ readonly description?: string;
1492
+ /** Events the client sends, and the Schemas of their payloads. */
1493
+ readonly input: I;
1494
+ /** Events the server sends. */
1495
+ readonly output: O;
1496
+ /** Defaults to the upgrade request's origin. */
1497
+ readonly allowedOrigins?: readonly string[];
1498
+ readonly allowMissingOrigin?: boolean;
1499
+ /** `false` refuses the upgrade (403), and any later message (close 1008). */
1500
+ readonly authorize?: (params: {
1501
+ ctx: Ctx;
1502
+ }) => Effect.Effect<boolean, unknown, any>;
1503
+ /** Rooms the connection is put in when it opens. */
1504
+ readonly rooms?: (params: {
1505
+ ctx: Ctx;
1506
+ }) => Effect.Effect<readonly string[], unknown, any>;
1507
+ /** Decides each room a client asks to join. Without it, client joins are refused. */
1508
+ readonly join?: (params: {
1509
+ ctx: Ctx;
1510
+ room: string;
1511
+ }) => Effect.Effect<boolean, unknown, any>;
1512
+ /** Rooms one connection can be in at once (default 100). */
1513
+ readonly maxRooms?: number;
1514
+ /** Keep recent emits per room so a reconnecting client gets what it missed. Off by default. */
1515
+ readonly replay?: SocketReplay;
1516
+ /**
1517
+ * Errors handlers may raise with `error.CODE()`, as an action declares them.
1518
+ * A raised error, with a declared or standard code, reaches the client's
1519
+ * `onHandlerError` and the connection stays open; anything else a handler
1520
+ * fails with, or any failure deciding a join, closes it with `1011` and is logged.
1521
+ */
1522
+ readonly errors?: TErrors;
1523
+ readonly handlers: { readonly [K in keyof I]: (params: {
1524
+ input: I[K]["Type"];
1525
+ ctx: Ctx;
1526
+ socket: BrickSocketSender<SocketPayloads<O>>;
1527
+ error: ErrorHelpers<TErrors>;
1528
+ }) => Effect.Effect<void, unknown, any>; };
1529
+ readonly open?: (params: {
1530
+ ctx: Ctx;
1531
+ socket: BrickSocketSender<SocketPayloads<O>>;
1532
+ }) => Effect.Effect<void, unknown, any>;
1533
+ readonly close?: (params: {
1534
+ ctx: Ctx;
1535
+ socket: BrickSocketSender<SocketPayloads<O>>;
1536
+ code: number;
1537
+ reason: string;
1538
+ }) => Effect.Effect<void, unknown, any>;
1539
+ }
1540
+ /** Returned by `service.socket()`. Emits and kicks reach every process through the app's broker. */
1541
+ interface BrickSocketHandle<Output> {
1542
+ readonly name: string;
1543
+ /** Validates and serializes once, then sends to every connection in the rooms. At most once, unacknowledged. An invalid room or payload is a defect. */
1544
+ emit(rooms: string | readonly string[], ...args: SocketEmitArgs<Output>): Effect.Effect<void>;
1545
+ /** Removes connections from a room; `also` limits it to connections also in that room. */
1546
+ kick(room: string, options?: {
1547
+ also?: string;
1548
+ reason?: string;
1549
+ }): Effect.Effect<void>;
1550
+ }
1551
+ type SocketBrokerMessage =
1552
+ /** `seq` is set by the broker for sockets with replay: `<number>-<number>`, rising per room. */
1553
+ {
1554
+ type: "emit";
1555
+ topic: string;
1556
+ frame: string;
1557
+ seq?: string;
1558
+ } | {
1559
+ type: "kick";
1560
+ topic: string;
1561
+ also?: string;
1562
+ reason?: string;
1563
+ };
1564
+ /** Carries emits and kicks between processes. Topics are `<service>.<socket>:<room>`. The same as `@brickkit/core`'s, so a broker written for it fits. */
1565
+ interface SocketBroker {
1566
+ /**
1567
+ * Sends to every subscriber of `message.topic`, in every process, this one
1568
+ * included. With `replay`, also keeps the emit and gives it a `seq`.
1569
+ */
1570
+ publish(message: SocketBrokerMessage, replay?: SocketReplay): void;
1571
+ /** The current position of a room, below every later `seq`. Needed for replay. */
1572
+ head?(topic: string): string | Promise<string>;
1573
+ /** Kept emits after `since`, or undefined when the history no longer covers it. Needed for replay. */
1574
+ history?(topic: string, since: string, replay: SocketReplay): SocketBrokerMessage[] | undefined | Promise<SocketBrokerMessage[] | undefined>;
1575
+ /** Called once per local holder of a topic; returns its unsubscribe. */
1576
+ subscribe(topic: string, deliver: (message: SocketBrokerMessage) => void): () => void;
1577
+ /** Resolves once messages for a topic just subscribed reach this process. */
1578
+ ready?(topic: string): Promise<void>;
1579
+ close?(): void | Promise<void>;
1580
+ }
1581
+ /** What the server knows of one connection's wire. */
1582
+ interface SocketWire {
1583
+ readonly isOpen: boolean;
1584
+ /** Sends an encoded frame. Throws when the socket is closed or its buffer is full. */
1585
+ send(frame: string): void;
1586
+ close(): void;
1587
+ }
1588
+ /** One connection's callbacks, from its upgrade to its close. */
1589
+ interface SocketSession {
1590
+ /** Server rooms, resolved from the handshake context. */
1591
+ readonly rooms: readonly string[];
1592
+ open(wire: SocketWire): Effect.Effect<void, unknown, any>;
1593
+ /** `data` is the payload of a client frame, still JSON. */
1594
+ message(event: string, data: unknown, wire: SocketWire): Effect.Effect<void, unknown, any>;
1595
+ join(room: string): Effect.Effect<boolean, unknown, any>;
1596
+ close(wire: SocketWire, code: number, reason: string): Effect.Effect<void, unknown, any>;
1597
+ }
1598
+ /** What the app records about a socket. */
1599
+ interface SocketSchema {
1600
+ readonly name: string;
1601
+ readonly path?: string | undefined;
1602
+ readonly description?: string | undefined;
1603
+ readonly input: readonly string[];
1604
+ readonly output: readonly string[];
1605
+ readonly hasAuthorize: boolean;
1606
+ }
1607
+ interface RegisteredSocket {
1608
+ readonly schema: SocketSchema;
1609
+ readonly input: SocketSchemas;
1610
+ readonly output: SocketSchemas;
1611
+ /** The errors its handlers declare. */
1612
+ readonly errors?: ErrorDefinitions | undefined;
1613
+ readonly allowedOrigins?: readonly string[] | undefined;
1614
+ readonly allowMissingOrigin?: boolean | undefined;
1615
+ readonly maxRooms: number;
1616
+ readonly replay?: SocketReplay | undefined;
1617
+ /** Brokers of the apps this socket is mounted in. */
1618
+ readonly brokers: Set<SocketBroker>;
1619
+ readonly handle: BrickSocketHandle<any>;
1620
+ readonly topicPrefix: string;
1621
+ topic(room: string): string;
1622
+ connect(request: Request): Effect.Effect<SocketSession, unknown, any>;
1623
+ }
1624
+ /** `brick({ sockets })`. */
1625
+ interface SocketsOptions {
1626
+ /** Carries emits and kicks between processes (default: `localBroker()`, this process only). */
1627
+ broker?: SocketBroker;
1628
+ /** Signs replay sequences, so they hold across processes and restarts (default: random per process). */
1629
+ secret?: string;
1630
+ }
1631
+ type RawSocketPhase = "open" | "message" | "close" | "preAuth";
1632
+ /** What a frame decodes to: `schema` gives its `Type`, `parse` its return type, neither the raw frame. */
1633
+ type RawSocketMessage<S extends AnySchema | undefined, Parsed> = S extends AnySchema ? S["Type"] : [Parsed] extends [never] ? string | Uint8Array : Parsed;
1634
+ interface RawSocketFrame<Msg> {
1635
+ data: Msg;
1636
+ }
1637
+ /** The connection a raw socket callback holds. Each method is an Effect that does nothing until it runs. */
1638
+ interface RawSocket<State> {
1639
+ readonly id: string;
1640
+ /** The upgrade request. */
1641
+ readonly request: Request;
1642
+ readonly authenticated: boolean;
1643
+ /** Per-connection, mutable. */
1644
+ state: State;
1645
+ /** `false` if the frame was dropped (backpressure) or the socket is closed. */
1646
+ send(data: string | Uint8Array): Effect.Effect<boolean>;
1647
+ close(code?: number, reason?: string): Effect.Effect<void>;
1648
+ /** Ends the `preAuth` stage and cancels its deadline; `patch` is merged into `state`. */
1649
+ authenticate(patch?: Partial<State>): Effect.Effect<void>;
1650
+ /** Adds a span link, for a trace id that only arrives in a frame. */
1651
+ link(traceparent: string): Effect.Effect<void>;
1652
+ }
1653
+ /** Returned by `service.rawSocket()`. Sums across the apps the route is mounted in. */
1654
+ interface RawSocketHandle {
1655
+ readonly live: number;
1656
+ readonly max?: number;
1657
+ }
1658
+ type Callback<A> = Effect.Effect<A, unknown, any>;
1659
+ /** The declaration of `service.rawSocket`. Every callback returns an Effect, and may need the services of the app's `layer`. */
1660
+ interface RawSocketConfig<Ctx, State, Msg, S extends AnySchema | undefined = undefined, Parsed = never> {
1661
+ readonly name: string;
1662
+ /** A static path relative to its service; default `/<kebab-name>`. */
1663
+ readonly path?: string;
1664
+ readonly description?: string;
1665
+ /** Upgrade gate. Runs with the context resolved from the upgrade request; `false` answers 403. */
1666
+ readonly authorize?: (params: {
1667
+ ctx: Ctx;
1668
+ request: Request;
1669
+ }) => Callback<boolean>;
1670
+ /** The initial per-connection `socket.state` (default `{}`). */
1671
+ readonly state?: (params: {
1672
+ ctx: Ctx;
1673
+ request: Request;
1674
+ }) => Callback<State>;
1675
+ /**
1676
+ * Browser origins allowed. By default a request with an `Origin` header is
1677
+ * refused (403) and one without, as third-party servers send, is accepted.
1678
+ */
1679
+ readonly allowedOrigins?: readonly string[];
1680
+ /** Connections at once; an upgrade over the cap answers 503. */
1681
+ readonly maxConnections?: number;
1682
+ /** Per frame, default 64 KiB; over it closes 1009. */
1683
+ readonly maxPayloadBytes?: number;
1684
+ /** JSON text frames, decoded with it (invalid: 1007; binary: 1003). Not with `parse`. */
1685
+ readonly schema?: S;
1686
+ /** Decodes each frame; throwing closes 1007. Not with `schema`. */
1687
+ readonly parse?: (raw: string | Uint8Array) => Parsed;
1688
+ /**
1689
+ * Start unauthenticated: until `socket.authenticate()`, frames go only to
1690
+ * `preAuth.message`. Not authenticated within `timeoutMs` closes 1008.
1691
+ */
1692
+ readonly preAuth?: {
1693
+ readonly timeoutMs: number;
1694
+ readonly message: (params: RawSocketFrame<Msg> & {
1695
+ ctx: Ctx;
1696
+ socket: RawSocket<State>;
1697
+ }) => Callback<void>;
1698
+ };
1699
+ readonly open?: (params: {
1700
+ ctx: Ctx;
1701
+ socket: RawSocket<State>;
1702
+ }) => Callback<void>;
1703
+ readonly message: (params: RawSocketFrame<Msg> & {
1704
+ ctx: Ctx;
1705
+ socket: RawSocket<State>;
1706
+ }) => Callback<void>;
1707
+ readonly close?: (params: {
1708
+ ctx: Ctx;
1709
+ socket: RawSocket<State>;
1710
+ code: number;
1711
+ reason: string;
1712
+ }) => Callback<void>;
1713
+ /** A callback failed. Default: log with `ctx.logger` and close 1011. Succeed with `"continue"` to stay open. */
1714
+ readonly error?: (params: {
1715
+ ctx: Ctx;
1716
+ socket: RawSocket<State>;
1717
+ error: unknown;
1718
+ phase: RawSocketPhase;
1719
+ }) => Callback<void | "continue" | "close">;
1720
+ }
1721
+ interface RawSocketStats {
1722
+ draining: boolean;
1723
+ live: number;
1724
+ max?: number;
1725
+ routes: {
1726
+ service: string;
1727
+ name: string;
1728
+ path: string;
1729
+ live: number;
1730
+ max?: number;
1731
+ }[];
1732
+ }
1733
+ interface RegisteredRawSocket {
1734
+ /** `name` and `path` only: a raw route is not described to clients. */
1735
+ readonly schema: {
1736
+ name: string;
1737
+ path?: string | undefined;
1738
+ };
1739
+ readonly config: RawSocketConfig<any, any, any, any, any>;
1740
+ readonly maxPayloadBytes: number;
1741
+ readonly max?: number | undefined;
1742
+ /** One entry per app the route is mounted in. */
1743
+ readonly mounts: Set<{
1744
+ live: number;
1745
+ }>;
1746
+ readonly handle: RawSocketHandle;
1747
+ /** The frame a client sent, decoded; `undefined` when `schema` rejects it. */
1748
+ readonly decode: ((value: unknown) => {
1749
+ value: unknown;
1750
+ } | undefined) | undefined;
1751
+ /** The deps of the plugin that declared the route, when one did. */
1752
+ deps?: Readonly<Record<string, unknown>>;
1753
+ resolve(request: Request): Effect.Effect<any, unknown, any>;
1754
+ }
1755
+ /** A parsed cron expression: the allowed values of each field. */
1756
+ interface CronExpression {
1757
+ readonly source: string;
1758
+ readonly seconds: ReadonlySet<number>;
1759
+ readonly minutes: ReadonlySet<number>;
1760
+ readonly hours: ReadonlySet<number>;
1761
+ readonly days: ReadonlySet<number>;
1762
+ readonly months: ReadonlySet<number>;
1763
+ /** 0 is Sunday. */
1764
+ readonly weekdays: ReadonlySet<number>;
1765
+ /** Both day fields are restricted: a day matches when either does. */
1766
+ readonly eitherDay: boolean;
1767
+ }
1768
+ /** What a workflow schedule's `run` receives: the run, without `attempt` (a run starts one workflow however often it is tried). */
1769
+ type WorkflowScheduleRun = Omit<ScheduleRun, "attempt">;
1770
+ /** What a schedule's `run` receives: which run this is. */
1771
+ interface ScheduleRun {
1772
+ /** The schedule's name. */
1773
+ schedule: string;
1774
+ /**
1775
+ * When this run was due, as an ISO timestamp: the cron time, the end of the
1776
+ * interval, or the moment someone triggered it. Retries of a failed run keep it.
1777
+ */
1778
+ slot: string;
1779
+ /** `manual` when started with `schedules.trigger(name)`. */
1780
+ trigger: "schedule" | "manual";
1781
+ /** 1 on the first try, 2 on the first retry, and so on. */
1782
+ attempt: number;
1783
+ /** `<schedule>:<slot>`: the same on every retry, for idempotency keys. */
1784
+ runKey: string;
1785
+ }
1786
+ type When = {
1787
+ /**
1788
+ * A cron expression: `"0 2 * * *"` is 02:00 every day. Five fields, or six
1789
+ * with seconds first; `@daily` and the other macros work too.
1790
+ */
1791
+ cron: string;
1792
+ /** The IANA time zone `cron` is read in, such as `"Europe/Berlin"`. Default `"UTC"`. */
1793
+ timeZone?: string;
1794
+ every?: never;
1795
+ } | {
1796
+ /**
1797
+ * Run again this long after the last run finished, once it succeeded or
1798
+ * ran out of tries: `"6h"`,
1799
+ * `"15m"`, `"1h30m"`, or milliseconds. The first run is due as soon as a
1800
+ * process starts the schedules.
1801
+ */
1802
+ every: string | number;
1803
+ cron?: never;
1804
+ timeZone?: never;
1805
+ };
1806
+ /** What `defineSchedule` takes. */
1807
+ type ScheduleConfig = When & {
1808
+ /** Unique among the app's schedules, and the key its state is stored under: renaming it starts it afresh. */
1809
+ name: string;
1810
+ /**
1811
+ * A due time that passed while no process ran the schedules (or one more
1812
+ * than a minute late): `"once"` (the default) runs it once, however many
1813
+ * were missed; `"skip"` skips it and waits for the next.
1814
+ */
1815
+ catchUp?: "once" | "skip";
1816
+ /** Tries per due time, the first included. Default 3. */
1817
+ maxAttempts?: number;
1818
+ /** The wait before the first retry, doubling on each retry after it; 0 retries at once. Default `"1m"`. */
1819
+ backoff?: string | number;
1820
+ /** A random delay of up to this much, added to every due time, so many processes or apps do not all start at once. */
1821
+ jitter?: string | number;
1822
+ /** `false` keeps the schedule from running on its own; `trigger` still runs it. Default `true`. */
1823
+ enabled?: boolean;
1824
+ } & ({
1825
+ /**
1826
+ * Runs in the process that claims the due time, with the services of the
1827
+ * app's layer. Failing retries it.
1828
+ */
1829
+ run: (run: ScheduleRun) => Effect.Effect<void, unknown, any>;
1830
+ workflow?: false;
1831
+ } | {
1832
+ /**
1833
+ * `run` is a durable workflow on the app's `WorkflowEngine`, started for
1834
+ * each due time and named after its run key, so a run that is tried again
1835
+ * starts no second workflow. The run counts as done once the workflow
1836
+ * started; the workflow retries its own steps, and a failure of `run` is
1837
+ * logged and does not retry the due time.
1838
+ */
1839
+ workflow: true;
1840
+ run: (run: WorkflowScheduleRun) => Effect.Effect<void, unknown, any>;
1841
+ });
1842
+ /** A schedule, made by `defineSchedule`. */
1843
+ interface Schedule {
1844
+ readonly name: string;
1845
+ readonly cron?: CronExpression;
1846
+ readonly timeZone?: string;
1847
+ /** The interval, in milliseconds. */
1848
+ readonly every?: number;
1849
+ readonly catchUp: "once" | "skip";
1850
+ readonly maxAttempts: number;
1851
+ readonly backoffMs: number;
1852
+ readonly jitterMs: number;
1853
+ readonly enabled: boolean;
1854
+ readonly run: (run: ScheduleRun) => Effect.Effect<void, unknown, any>;
1855
+ /** `run` is a durable workflow: see `ScheduleConfig`. */
1856
+ readonly workflow: boolean;
1857
+ /** What decides the due times, as stored with them: a change makes the next one be worked out again. */
1858
+ readonly spec: string;
1859
+ }
1860
+ /**
1861
+ * Define a schedule: an Effect that runs at set times, in one process among all
1862
+ * those that run the app. Pass it to `brick({ events: { schedules } })`.
1863
+ *
1864
+ * It runs either on a `cron` expression, at fixed wall-clock times in a time
1865
+ * zone, or `every` so long, counted from the end of the last run (a run that
1866
+ * used up its tries counts too).
1867
+ * State lives in the app's `scheduleTable()`, so a due time runs once however
1868
+ * many processes there are, and a restart or deploy carries on where it
1869
+ * stopped. A due time counts as done only once its run succeeds: a run that
1870
+ * fails is retried with a growing delay, and one whose process died is taken
1871
+ * over by another process. A run is never started while the last one is still
1872
+ * running; due times that pass in the meantime are skipped.
1873
+ *
1874
+ * @param config - `name`, `cron` (and `timeZone`) or `every`, `run`, and
1875
+ * optionally `catchUp`, `maxAttempts`, `backoff`, `jitter` and `enabled`.
1876
+ * @returns The schedule.
1877
+ * @throws When the name is empty or contains `:`, the cron expression or time
1878
+ * zone is invalid, or the schedule has both or neither of `cron` and `every`.
1879
+ * @example
1880
+ * const backup = defineSchedule({
1881
+ * name: "db-backup",
1882
+ * cron: "0 *\/6 * * *",
1883
+ * timeZone: "Europe/Berlin",
1884
+ * run: () => Backups.use((backups) => backups.run()),
1885
+ * });
1886
+ *
1887
+ * export default brick({ services, layer, events: { schedules: [backup] } });
1888
+ */
1889
+ declare function defineSchedule(config: ScheduleConfig): Schedule;
1890
+ /** An event, as it was recorded. It is the same for every listener of it. */
1891
+ interface EventEnvelope<TPayload = unknown> {
1892
+ /** Unique per event. Every listener's delivery of the event shares it. */
1893
+ id: string;
1894
+ /** The event name, such as `orders.shipped`. */
1895
+ name: string;
1896
+ /** What happened. JSON data. */
1897
+ payload: TPayload;
1898
+ /** When it happened, as an ISO timestamp. */
1899
+ occurredAt: string;
1900
+ /** The trace of the request that caused it, so a listener continues the same trace. */
1901
+ traceId?: string;
1902
+ /** What emitted it, shown to listeners. */
1903
+ source?: string;
1904
+ }
1905
+ /** One listener's delivery of an event: the envelope, plus which listener it is for and which attempt this is. */
1906
+ interface EventDelivery<TPayload = unknown> extends EventEnvelope<TPayload> {
1907
+ /** The name of the listener this delivery is for. */
1908
+ listener: string;
1909
+ /**
1910
+ * `<event id>:<listener>`. It is the same on every retry, so a listener can use
1911
+ * it to avoid doing the work twice: delivery is at least once.
1912
+ */
1913
+ deliveryId: string;
1914
+ /** 1 on the first try, 2 on the first retry, and so on. */
1915
+ attempt: number;
1916
+ }
1917
+ /**
1918
+ * What a workflow listener's `run` receives: the delivery, without `attempt`,
1919
+ * because one delivery starts one run however many times it is tried.
1920
+ */
1921
+ type WorkflowEvent<TPayload = unknown> = Omit<EventDelivery<TPayload>, "attempt">;
1922
+ /**
1923
+ * The CRUD events of a resource called `user`, by operation. Listeners of
1924
+ * `user.create`, `user.update` and `user.delete` receive these payloads.
1925
+ */
1926
+ type CrudEventPayload<TRow = Record<string, unknown>> = {
1927
+ id: unknown;
1928
+ row: TRow;
1929
+ } | {
1930
+ id: unknown;
1931
+ before: TRow;
1932
+ after: TRow;
1933
+ };
1934
+ /**
1935
+ * What `retry` receives: one member per error the listener declares, or the
1936
+ * fallback for anything else it failed with.
1937
+ */
1938
+ type ListenerFailure<TErrors extends ErrorDefinitions> = { [K in keyof TErrors & string]: {
1939
+ code: K;
1940
+ message: string;
1941
+ details: unknown;
1942
+ }; }[keyof TErrors & string] | {
1943
+ code: "UNKNOWN";
1944
+ message: string;
1945
+ cause: unknown;
1946
+ };
1947
+ /** What a listener's `retry` decides: try again later, or park the delivery as dead now. */
1948
+ type RetryDecision = "retry" | "dead";
1949
+ /** A listener: an Effect that runs when an event it listens for has been recorded. */
1950
+ interface EventListener<TPayload = any> {
1951
+ /** Unique among the app's listeners. It is part of each delivery's id. */
1952
+ readonly name: string;
1953
+ /**
1954
+ * The event names to listen for. A trailing `*` matches a prefix (`orders.*`),
1955
+ * and `*` alone matches every event.
1956
+ */
1957
+ readonly on: readonly string[];
1958
+ /**
1959
+ * Runs in the dispatching process for each delivery, with the services of the
1960
+ * app's layer. Failing retries the delivery with a growing delay.
1961
+ */
1962
+ readonly run: (delivery: EventDelivery<TPayload>) => Effect.Effect<void, unknown, any>;
1963
+ /**
1964
+ * `run` is a durable workflow on the app's `WorkflowEngine`: it may use
1965
+ * `Activity`, `DurableClock` and `DurableDeferred`, and a restart resumes it.
1966
+ * The delivery counts as done once its run has started; the workflow retries
1967
+ * its own steps from there.
1968
+ */
1969
+ readonly workflow?: boolean;
1970
+ /** The typed errors `run` can fail with; `retry` receives them as a `ListenerFailure`. */
1971
+ readonly errors?: ErrorDefinitions;
1972
+ /**
1973
+ * Decides what a failed delivery does next. Without it, every failure retries
1974
+ * until `maxAttempts`. It cannot extend the attempts: `"retry"` still parks the
1975
+ * delivery as dead once they run out.
1976
+ */
1977
+ readonly retry?: (error: ListenerFailure<any>) => RetryDecision;
1978
+ /** Attempts before the delivery is parked as dead. Defaults to the dispatcher's. */
1979
+ readonly maxAttempts?: number;
1980
+ }
1981
+ /** How the dispatcher delivers recorded events. */
1982
+ interface DispatchOptions {
1983
+ /**
1984
+ * Whether to look for due deliveries on a timer, and right after a commit.
1985
+ * Default `true`. With `false`, deliveries run only when something calls
1986
+ * `app.events.drain()`: a cron job, a worker you drive yourself, or a test.
1987
+ */
1988
+ timer?: boolean;
1989
+ /** How often to look for deliveries that are due, in milliseconds. Default 1000. */
1990
+ intervalMs?: number;
1991
+ /** Most deliveries claimed at once. Default 50. */
1992
+ batchSize?: number;
1993
+ /** Attempts before a delivery is parked as dead. Default 8. */
1994
+ maxAttempts?: number;
1995
+ /** How long a claimed delivery may run before another dispatcher takes it, in milliseconds. Default 60000. */
1996
+ claimTimeoutMs?: number;
1997
+ /** Longest wait before a retry, in milliseconds. Default 300000. */
1998
+ maxBackoffMs?: number;
1999
+ /** How long delivered rows are kept, in milliseconds. Default 86400000 (one day). 0 keeps none. */
2000
+ retainDeliveredMs?: number;
2001
+ }
2002
+ /** The `events` option of `brick()`. */
2003
+ interface EventsOptions {
2004
+ /** The listeners of the app. */
2005
+ listeners?: readonly EventListener[];
2006
+ /**
2007
+ * The schedules of the app, from `defineSchedule`. Their state lives in the
2008
+ * one `scheduleTable()` among the services' databases, and they run in the
2009
+ * processes that deliver events, by the same `dispatch` settings.
2010
+ */
2011
+ schedules?: readonly Schedule[];
2012
+ /**
2013
+ * Whether this process delivers recorded events and runs schedules. `true`
2014
+ * (the default) starts a dispatcher with the default settings, an object
2015
+ * tunes it, and `false` only records events, for an app whose events are
2016
+ * delivered by another process.
2017
+ */
2018
+ dispatch?: boolean | DispatchOptions;
2019
+ }
2020
+ /** A child table: rows that belong to one row of their resource. */
2021
+ interface ResourceChild<TTable = any> {
2022
+ table: TTable;
2023
+ /** The child's column that holds the parent row's id. */
2024
+ parent: Column;
2025
+ /** The child's id column. Defaults to its single primary key. */
2026
+ id?: Column;
2027
+ }
2028
+ /** The declaration of a resource: a table and its entity. */
2029
+ interface ResourceConfig<TTable = any> {
2030
+ /** Its route segment: `/api/<service>/<name>`, and the prefix of the actions plugins add (`<name>.list`). */
2031
+ name: string;
2032
+ table: TTable;
2033
+ /** The id column (default: the table's single primary key). */
2034
+ id?: Column;
2035
+ /**
2036
+ * Child tables of this resource, by name. A command can load them with its
2037
+ * row (`load: { children: ["items"] }`) and insert, update and delete their
2038
+ * rows in the same transaction.
2039
+ */
2040
+ children?: Record<string, ResourceChild>;
2041
+ }
2042
+ /** The part of a `ResourceConfig` the resource's type depends on. */
2043
+ type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id" | "children">;
2044
+ type PrimaryColumn<T> = T extends {
2045
+ _: {
2046
+ columns: infer C;
2047
+ };
2048
+ } ? { [K in keyof C]: C[K] extends {
2049
+ _: {
2050
+ isPrimaryKey: true;
2051
+ };
2052
+ } ? C[K] : never; }[keyof C] : Column;
2053
+ type ResourceIdentity<T, O> = O & {
2054
+ id: O extends {
2055
+ id: infer I extends Column;
2056
+ } ? I : PrimaryColumn<T>;
2057
+ };
2058
+ type InputOf<S> = S extends AnySchema ? S["Type"] : undefined;
2059
+ type ResultOf<S, A> = S extends AnySchema ? S["Type"] : A;
2060
+ type RowOf<T> = T extends {
2061
+ $inferSelect: infer S;
2062
+ } ? S : any;
2063
+ type InsertOf<T> = T extends {
2064
+ $inferInsert: infer S;
2065
+ } ? S : any;
2066
+ /**
2067
+ * Which rows a record action may load when its resource has no `crud`:
2068
+ * `"public"` loads any row by id, `scope` adds a SQL condition (such as the
2069
+ * caller's tenant). It applies whatever `crud` the resource has.
2070
+ */
2071
+ type ResourceActionAccess<TCtx = any> = "public" | {
2072
+ scope: (args: {
2073
+ ctx: TCtx;
2074
+ }) => Effect.Effect<SQL | undefined, any, any>;
2075
+ };
2076
+ /** A record action's input: its own fields and the `id` from the path. */
2077
+ type ResourceActionInput<TIn extends AnySchema | undefined, TRecord extends boolean> = TRecord extends true ? (TIn extends AnySchema ? TIn["Type"] : {}) & {
2078
+ id: string | number;
2079
+ } : InputOf<TIn>;
2080
+ type IdField = {
2081
+ readonly id: Schema.Codec<string | number>;
2082
+ };
2083
+ /** The schema of a record action's input: its own, with the `id`. */
2084
+ type WithId<TIn> = TIn extends Schema.Struct<infer F> ? Schema.Struct<F & IdField> : Schema.Struct<IdField>;
2085
+ type ActionInputSchema<TIn extends AnySchema | undefined, TRecord extends boolean> = TRecord extends true ? WithId<TIn> : TIn;
2086
+ /** `resource.action(config)`: an action owned by a resource. */
2087
+ interface ResourceActionConfig<TIn extends AnySchema | undefined, TOut extends AnySchema | undefined, TErrors extends ErrorDefinitions, TCtx, TRow, TRecord extends boolean, A, E, R, RA> {
2088
+ readonly name: string;
2089
+ readonly description?: string;
2090
+ /** POST unless set. GET and DELETE read their input from the query string. */
2091
+ readonly method?: HttpMethod;
2092
+ /** Under the resource's route. A record action's path needs `:id`. */
2093
+ readonly path?: string;
2094
+ readonly tags?: readonly string[];
2095
+ readonly input?: TIn;
2096
+ readonly output?: TOut;
2097
+ readonly errors?: TErrors;
2098
+ /** `true` rejects an extra key at the root of the input, as core's `additionalProperties: false`; `"deep"` at every depth. */
2099
+ readonly strict?: boolean | "deep";
2100
+ readonly dashboard?: boolean;
2101
+ /**
2102
+ * `true` makes it a record action at `/:id/<name>`: `id` joins the input,
2103
+ * the row loads through its `access`, and a missing or hidden row answers
2104
+ * 404 before `execute` runs.
2105
+ */
2106
+ readonly record?: TRecord;
2107
+ /** For a record action: which rows it may load. */
2108
+ readonly access?: ResourceActionAccess<TCtx>;
2109
+ readonly rateLimit?: RateLimits<ResourceActionInput<TIn, TRecord>, TCtx>;
2110
+ readonly reveal?: Reveal<ResourceActionInput<TIn, TRecord>, TCtx>;
2111
+ /**
2112
+ * Recorded in the audit log, with the resource and, for a record action, the
2113
+ * `id`, when the service has an audit table and the action's HTTP method is
2114
+ * not `GET`. `false` leaves it out.
2115
+ */
2116
+ readonly audit?: false | AuditOptions<ResourceActionInput<TIn, TRecord>, TOut extends AnySchema ? TOut["Type"] : any>;
2117
+ readonly authorize?: (params: {
2118
+ input: ResourceActionInput<TIn, TRecord>;
2119
+ ctx: TCtx;
2120
+ error: ErrorHelpers<TErrors>;
2121
+ }) => Effect.Effect<boolean, any, RA>;
2122
+ readonly execute: (params: {
2123
+ input: ResourceActionInput<TIn, TRecord>;
2124
+ ctx: TCtx;
2125
+ error: ErrorHelpers<TErrors>;
2126
+ /** The loaded row of a record action; `undefined` otherwise. */
2127
+ row: TRecord extends true ? TRow : undefined;
2128
+ }) => Effect.Effect<ResultOf<TOut, A>, E, R>;
2129
+ }
2130
+ type ChildNames<TOptions> = TOptions extends {
2131
+ children: infer C extends Record<string, ResourceChild>;
2132
+ } ? keyof C & string : never;
2133
+ /** The child tables of a resource, by name. */
2134
+ type CommandChildren<TOptions> = TOptions extends {
2135
+ children: infer C extends Record<string, ResourceChild>;
2136
+ } ? { [K in keyof C]: C[K]["table"]; } : {};
2137
+ /** The row `decide` receives: the resource's row with the children it loads. */
2138
+ type CommandRow<TTable, TOptions, TLoaded extends string> = RowOf<TTable> & { [K in TLoaded & keyof CommandChildren<TOptions>]: RowOf<CommandChildren<TOptions>[K]>[]; };
2139
+ /** The changes to one child table. Updates and deletes name rows by child id. */
2140
+ interface ChildChanges<TChild = any> {
2141
+ /** New rows. Their parent column is set to the parent's id. */
2142
+ insert?: Partial<InsertOf<TChild>>[];
2143
+ /** Partial rows, each with the child id; only rows of this parent change. */
2144
+ update?: Partial<RowOf<TChild>>[];
2145
+ /** Child ids to delete; only rows of this parent are deleted. */
2146
+ delete?: (string | number)[];
2147
+ }
2148
+ type PayloadOf<T> = T extends EventRef<infer P> ? P : never;
2149
+ /** What `decide` returns when the command goes ahead. */
2150
+ interface CommandDecision<TRow = any, TChildren = {}, TEvents extends Record<string, EventRef> = Record<string, EventRef>> {
2151
+ /** Columns of the parent row to change. */
2152
+ set?: Partial<Omit<TRow, keyof TChildren>>;
2153
+ /** Inserts, updates and deletes per child table. */
2154
+ children?: { [K in keyof TChildren]?: ChildChanges<TChildren[K]>; };
2155
+ /** Events to record with the write, by catalog name and payload. */
2156
+ emit?: { [K in keyof TEvents]?: PayloadOf<TEvents[K]>; };
2157
+ }
2158
+ /**
2159
+ * The `error` helpers `decide` receives. Unlike an action's, they return the
2160
+ * rejection instead of failing with it, so `decide` stays a pure function.
2161
+ */
2162
+ type CommandErrors<TErrors extends ErrorDefinitions> = { [K in keyof ErrorHelpers<TErrors>]: (message?: string, details?: unknown) => BrickError; };
2163
+ /** `resource.command(name, config)`. */
2164
+ interface CommandConfig<TIn extends AnySchema | undefined, TOut extends AnySchema | undefined, TErrors extends ErrorDefinitions, TCtx, TRow, TChildren, TEvents extends Record<string, EventRef>, TLoad extends readonly string[], RA> {
2165
+ readonly description?: string;
2166
+ readonly tags?: readonly string[];
2167
+ /** The command's own input; `id` from the path joins it. */
2168
+ readonly input?: TIn;
2169
+ /**
2170
+ * The reply: the updated row (with loaded children), cut down to this
2171
+ * schema's properties. Without it the reply is `{ id }`.
2172
+ */
2173
+ readonly output?: TOut;
2174
+ readonly reveal?: Reveal<ResourceActionInput<TIn, true>, TCtx>;
2175
+ readonly errors?: TErrors;
2176
+ /** Which child tables to load with the row, by their name on the resource. */
2177
+ readonly load?: {
2178
+ children?: TLoad;
2179
+ };
2180
+ /** Which rows the command may load. */
2181
+ readonly access?: ResourceActionAccess<TCtx>;
2182
+ readonly rateLimit?: RateLimits<ResourceActionInput<TIn, true>, TCtx>;
2183
+ /**
2184
+ * Recorded in the audit log, with the resource and the record's `id`, in the
2185
+ * command's transaction, when the service has an audit table. `false` leaves
2186
+ * it out.
2187
+ */
2188
+ readonly audit?: false | AuditOptions<ResourceActionInput<TIn, true>, TOut extends AnySchema ? TOut["Type"] : {
2189
+ id: string | number;
2190
+ }>;
2191
+ readonly authorize?: (params: {
2192
+ input: ResourceActionInput<TIn, true>;
2193
+ ctx: TCtx;
2194
+ error: ErrorHelpers<TErrors>;
2195
+ }) => Effect.Effect<boolean, any, RA>;
2196
+ /**
2197
+ * The rules: a pure function of the loaded row and the input. Return
2198
+ * `error.CODE()` to reject (nothing is written), or the changes to make.
2199
+ */
2200
+ readonly decide: (row: TRow, input: ResourceActionInput<TIn, true>, helpers: {
2201
+ error: CommandErrors<TErrors>;
2202
+ }) => CommandDecision<TRow, TChildren, TEvents> | BrickError;
2203
+ }
2204
+ /** A command: an action with its `decide`, callable without a database. */
2205
+ type Command<TIn extends AnySchema | undefined, TOut extends AnySchema | undefined, TErrors extends ErrorDefinitions, A, R, TRow, TChildren, TEvents extends Record<string, EventRef>> = Action<WithId<TIn>, TOut extends AnySchema ? TOut : Schema.Struct<IdField>, TErrors, A, R> & {
2206
+ /**
2207
+ * Run the rules alone, with the standard and declared error helpers: for
2208
+ * unit tests that need no database.
2209
+ */
2210
+ decide(row: TRow, input: ResourceActionInput<TIn, true>): CommandDecision<TRow, TChildren, TEvents> | BrickError;
2211
+ };
2212
+ /**
2213
+ * A plugin host over a table. Plugins such as `crud` add actions to it, and
2214
+ * `action` and `command` declare its own.
2215
+ */
2216
+ interface Resource<TTable = any, TCtx = any, TOptions = {}, TEvents extends Record<string, EventRef> = Record<string, EventRef>, TRequirement = never> {
2217
+ /** Installs a plugin on the resource. It returns the resource, with the API the plugin contributed. */
2218
+ use<P extends ResourcePlugin<Service<any, TCtx, any>, this, any>>(plugin: P): this & ResourcePluginAPI<P, TTable, TCtx, this>;
2219
+ readonly name: string;
2220
+ readonly serviceName: string;
2221
+ readonly table: TTable;
2222
+ readonly id: TOptions extends {
2223
+ id: infer I extends Column;
2224
+ } ? I : Column;
2225
+ readonly idField: string;
2226
+ readonly config: ResourceConfig<TTable> & TOptions;
2227
+ /**
2228
+ * Declare an action owned by this resource, registered as
2229
+ * `<resource>.<name>`. It mounts at `/<service>/<resource>/<name>`, or at
2230
+ * `/<service>/<resource>/:id/<name>` with `record: true`.
2231
+ */
2232
+ action<TIn extends AnySchema | undefined = undefined, TOut extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, const TRecord extends boolean = false, A = never, E = never, R = never, RA = never>(config: ResourceActionConfig<TIn, TOut, TErrors, TCtx, RowOf<TTable>, TRecord, A, E, R, RA>): Action<ActionInputSchema<TIn, TRecord>, TOut, TErrors, A, R | RA | TRequirement>;
2233
+ /**
2234
+ * Declare a command: a record action whose body is the pure `decide`. Brick
2235
+ * loads the row (and the child rows it asks for) in a transaction, runs
2236
+ * `decide`, applies the changes it returns, records the events it emits in
2237
+ * the same transaction, and commits. Registered as `<resource>.<name>` at
2238
+ * `POST /<service>/<resource>/:id/<name>`.
2239
+ */
2240
+ command<TIn extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, const TLoad extends readonly ChildNames<TOptions>[] = [], TOut extends AnySchema | undefined = undefined, RA = never>(name: string, config: CommandConfig<TIn, TOut, TErrors, TCtx, CommandRow<TTable, TOptions, TLoad[number]>, CommandChildren<TOptions>, TEvents, TLoad, RA>): Command<TIn, TOut, TErrors, never, RA | TRequirement, CommandRow<TTable, TOptions, TLoad[number]>, CommandChildren<TOptions>, TEvents>;
2241
+ }
2242
+ /** Any resource, whatever its table. */
2243
+ type AnyResource = Resource<any, any, any, any, any>;
2244
+ /** The schema of a resource's `:id` in a body: a number for a number column, else a string. */
2245
+ declare const idSchema: (column: Column) => AnySchema;
2246
+ /**
2247
+ * Load the row a record action (or command) works on, through its `access`.
2248
+ *
2249
+ * @param args - `id`, the call's `ctx`, `access`, and `db` (a transaction) in
2250
+ * place of `ctx.db`.
2251
+ * @returns The row, or `undefined` when it is missing or hidden.
2252
+ * @throws (as a defect) When `access` is missing.
2253
+ */
2254
+ declare const loadRecord: (resource: AnyResource, args: {
2255
+ id: unknown;
2256
+ ctx: any;
2257
+ db?: any;
2258
+ access?: ResourceActionAccess | undefined;
2259
+ }) => Effect.Effect<Record<string, unknown> | undefined, unknown, any>;
2260
+ /** Declares a resource on `service`, which is what `service.resource` does. */
2261
+ declare function defineResource<TTable = any, TCtx = any, const O extends ResourceTypeOptions = ResourceTypeOptions>(service: AnyService, config: ResourceConfig<TTable> & O): Resource<TTable, TCtx, ResourceIdentity<TTable, O>>;
2262
+ interface HookBase<C> {
2263
+ ctx: C;
2264
+ /** The write's open transaction: write other tables through it. */
2265
+ tx: any;
2266
+ /** The resource that is written. */
2267
+ resource: AnyResource;
2268
+ }
2269
+ /** The arguments each host CRUD hook receives, by hook name. */
2270
+ interface PluginHookArgs<C = any> {
2271
+ beforeCreate: HookBase<C> & {
2272
+ data: Record<string, unknown>;
2273
+ };
2274
+ afterCreate: HookBase<C> & {
2275
+ row: Record<string, unknown>;
2276
+ };
2277
+ beforeUpdate: HookBase<C> & {
2278
+ id: unknown;
2279
+ data: Record<string, unknown>;
2280
+ };
2281
+ afterUpdate: HookBase<C> & {
2282
+ id: unknown;
2283
+ row: Record<string, unknown>;
2284
+ };
2285
+ beforeDelete: HookBase<C> & {
2286
+ id: unknown;
2287
+ };
2288
+ afterDelete: HookBase<C> & {
2289
+ id: unknown;
2290
+ };
2291
+ afterCommit: {
2292
+ operation: "create" | "update" | "delete";
2293
+ id: unknown;
2294
+ row?: Record<string, unknown>;
2295
+ ctx: C;
2296
+ };
2297
+ }
2298
+ /** What a hook returns: an Effect, which may fail to roll the write back. */
2299
+ type HookResult = Effect.Effect<unknown, any, any>;
2300
+ /**
2301
+ * Subscribe to the host's CRUD writes (resources with `crud()`). `before*` and
2302
+ * `after*` run inside the write's transaction, after the host's own crud hooks;
2303
+ * a hook that fails rolls the write back. `afterCommit` runs after the commit.
2304
+ */
2305
+ type PluginHooks<C = any> = { [K in keyof PluginHookArgs<C>]: (hook: (args: PluginHookArgs<C>[K]) => HookResult) => void; };
2306
+ type HostHooks = { [K in keyof PluginHookArgs]?: ((args: PluginHookArgs[K]) => HookResult)[]; };
2307
+ declare const HOOK_NAMES: (keyof PluginHookArgs)[];
2308
+ /** The plugin hooks installed on a service or resource, by hook name. */
2309
+ declare function getHostHooks(host: object): HostHooks | undefined;
2310
+ /** Add hooks to a host, after those already there. */
2311
+ declare function addHostHooks(host: object, added: HostHooks): void;
2312
+ /** The plugin that owns a table, for tables a `definePlugin` contributed. */
2313
+ declare function pluginOwner(table: unknown): string | undefined;
2314
+ declare const sqliteBuilders: {
2315
+ /** A table. Its name gets the plugin's prefix (`page_comments`). */
2316
+ table: <C extends Record<string, ColumnBuilderBase>>(name: string, columns: C) => import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
2317
+ name: string;
2318
+ schema: undefined;
2319
+ columns: { [Key in keyof C]: import("drizzle-orm/sqlite-core").SQLiteColumn<{
2320
+ name: string;
2321
+ tableName: string;
2322
+ dataType: C[Key]["_"]["dataType"];
2323
+ data: C[Key]["_"] extends (infer T) ? T extends C[Key]["_"] ? T extends {
2324
+ $type: infer U;
2325
+ } ? U : T["data"] : never : never;
2326
+ driverParam: C[Key]["_"]["driverParam"];
2327
+ notNull: C[Key]["_"]["notNull"] extends true ? true : false;
2328
+ hasDefault: C[Key]["_"]["hasDefault"] extends true ? true : false;
2329
+ isPrimaryKey: C[Key]["_"] extends (infer T_1) ? T_1 extends C[Key]["_"] ? T_1 extends {
2330
+ isPrimaryKey: true;
2331
+ } ? true : false : never : never;
2332
+ isAutoincrement: C[Key]["_"] extends (infer T_2) ? T_2 extends C[Key]["_"] ? T_2 extends {
2333
+ isAutoincrement: true;
2334
+ } ? true : false : never : never;
2335
+ hasRuntimeDefault: C[Key]["_"] extends (infer T_3) ? T_3 extends C[Key]["_"] ? T_3 extends {
2336
+ hasRuntimeDefault: true;
2337
+ } ? true : false : never : never;
2338
+ enumValues: C[Key]["_"] extends (infer T_4) ? T_4 extends C[Key]["_"] ? T_4 extends {
2339
+ enumValues: [string, ...string[]];
2340
+ } ? T_4["enumValues"] : undefined : never : never;
2341
+ baseColumn: C[Key]["_"] extends (infer T_5) ? T_5 extends C[Key]["_"] ? T_5 extends {
2342
+ baseBuilder: infer U_1 extends ColumnBuilderBase;
2343
+ } ? import("drizzle-orm/sqlite-core").SQLiteColumn<{
2344
+ name: string;
2345
+ tableName: string;
2346
+ dataType: U_1["_"]["dataType"];
2347
+ data: U_1["_"] extends (infer T_6) ? T_6 extends U_1["_"] ? T_6 extends {
2348
+ $type: infer U;
2349
+ } ? U : T_6["data"] : never : never;
2350
+ driverParam: U_1["_"]["driverParam"];
2351
+ notNull: U_1["_"]["notNull"] extends true ? true : false;
2352
+ hasDefault: U_1["_"]["hasDefault"] extends true ? true : false;
2353
+ isPrimaryKey: U_1["_"] extends (infer T_7) ? T_7 extends U_1["_"] ? T_7 extends {
2354
+ isPrimaryKey: true;
2355
+ } ? true : false : never : never;
2356
+ isAutoincrement: U_1["_"] extends (infer T_8) ? T_8 extends U_1["_"] ? T_8 extends {
2357
+ isAutoincrement: true;
2358
+ } ? true : false : never : never;
2359
+ hasRuntimeDefault: U_1["_"] extends (infer T_9) ? T_9 extends U_1["_"] ? T_9 extends {
2360
+ hasRuntimeDefault: true;
2361
+ } ? true : false : never : never;
2362
+ enumValues: U_1["_"] extends (infer T_10) ? T_10 extends U_1["_"] ? T_10 extends {
2363
+ enumValues: [string, ...string[]];
2364
+ } ? T_10["enumValues"] : undefined : never : never;
2365
+ baseColumn: U_1["_"] extends (infer T_11) ? T_11 extends U_1["_"] ? T_11 extends {
2366
+ baseBuilder: infer U_1 extends ColumnBuilderBase;
2367
+ } ? import("drizzle-orm/sqlite-core").SQLiteColumn< /*elided*/ any, {}> : never : never : never;
2368
+ identity: U_1["_"] extends (infer T_12) ? T_12 extends U_1["_"] ? T_12 extends {
2369
+ identity: 'always';
2370
+ } ? "always" : T_12 extends {
2371
+ identity: 'byDefault';
2372
+ } ? "byDefault" : undefined : never : never;
2373
+ generated: U_1["_"] extends (infer T_13) ? T_13 extends U_1["_"] ? T_13 extends {
2374
+ generated: infer G;
2375
+ } ? unknown extends G ? undefined : G extends undefined ? undefined : G : undefined : never : never;
2376
+ }, {}> : never : never : never;
2377
+ identity: C[Key]["_"] extends (infer T_14) ? T_14 extends C[Key]["_"] ? T_14 extends {
2378
+ identity: 'always';
2379
+ } ? "always" : T_14 extends {
2380
+ identity: 'byDefault';
2381
+ } ? "byDefault" : undefined : never : never;
2382
+ generated: C[Key]["_"] extends (infer T_15) ? T_15 extends C[Key]["_"] ? T_15 extends {
2383
+ generated: infer G;
2384
+ } ? unknown extends G ? undefined : G extends undefined ? undefined : G : undefined : never : never;
2385
+ }, {}>; };
2386
+ dialect: 'sqlite';
2387
+ isAlias: false;
2388
+ }>;
2389
+ text: (name: string) => import("drizzle-orm/sqlite-core").SQLiteTextBuilder<[string, ...string[]]>;
2390
+ integer: (name: string) => import("drizzle-orm/sqlite-core").SQLiteIntegerBuilder;
2391
+ real: (name: string) => import("drizzle-orm/sqlite-core").SQLiteRealBuilder;
2392
+ boolean: (name: string) => import("drizzle-orm/sqlite-core").SQLiteBooleanBuilder;
2393
+ /** A `Date`, stored as epoch milliseconds or `timestamptz`. */
2394
+ timestamp: (name: string) => import("drizzle-orm/sqlite-core").SQLiteTimestampBuilder;
2395
+ json: (name: string) => import("drizzle-orm/sqlite-core").SQLiteTextJsonBuilder;
2396
+ };
2397
+ /**
2398
+ * Engine-neutral column builders for `tables`. Brick passes the SQLite or
2399
+ * Postgres ones to match the host database; the types follow SQLite's, and the
2400
+ * JavaScript values are the same on both (a `Date` for `timestamp`).
2401
+ */
2402
+ type PluginTableBuilders = typeof sqliteBuilders & {
2403
+ /** The host database's engine. */
2404
+ readonly engine: "sqlite" | "postgres";
2405
+ };
2406
+ type Secrets = Record<string, SecretRef<any>>;
2407
+ type Events$1 = Record<string, AnySchema>;
2408
+ type OptionsOf<O> = O extends AnySchema ? O["Type"] : {};
2409
+ type OptionsInput<O> = O extends AnySchema ? Partial<O["Encoded"]> : {};
2410
+ /** A plugin's view of its host's service context: loose, except `deps`, which is the plugin's. */
2411
+ type PluginServiceContext<P extends Record<string, unknown> = {}> = {
2412
+ [key: string]: any;
2413
+ /** The values passed for the plugin's `deps` when it was installed. */
2414
+ deps: Readonly<P>;
2415
+ };
2416
+ /** The context of a plugin's actions, endpoints and hooks. */
2417
+ type PluginContext<P extends Record<string, unknown> = {}> = BaseContext & PluginServiceContext<P>;
2418
+ /** What every setup callback receives. */
2419
+ interface PluginSetupContext<O, S, T, E extends Events$1, P extends Record<string, unknown> = {}> {
2420
+ /** The validated options, defaults filled in. */
2421
+ options: O;
2422
+ /** The declared secrets, to read when they are needed. */
2423
+ secrets: S;
2424
+ /** The tables this plugin owns, by the keys `tables` returned. */
2425
+ tables: T;
2426
+ /** The plugin's events, as `emitEvent` and `defineListener` take them. */
2427
+ events: EventRefs<E>;
2428
+ /** The values passed for `deps` when the plugin was installed. */
2429
+ deps: Readonly<P>;
2430
+ /** The host service. Actions registered on it read the plugin's deps as `ctx.deps`. */
2431
+ service: Service<string, PluginServiceContext<P>, never>;
2432
+ routes: PluginRouteRegistrar<PluginContext<P>>;
2433
+ /** The host's CRUD writes: on a service, those of all its resources. */
2434
+ hooks: PluginHooks<PluginContext<P>>;
2435
+ }
2436
+ /** The lifecycle context of `on("start")` and `on("stop")`. */
2437
+ interface PluginLifecycleContext<O, S, P extends Record<string, unknown> = {}> {
2438
+ options: O;
2439
+ secrets: S;
2440
+ deps: Readonly<P>;
2441
+ }
2442
+ type AppHook<R = any> = Effect.Effect<void, unknown, R>;
2443
+ /** What `app` receives: the app-wide part of a plugin. */
2444
+ interface PluginAppContext<O, S, P extends Record<string, unknown> = {}> {
2445
+ options: O;
2446
+ secrets: S;
2447
+ /** The values passed for `deps` when the plugin was installed. */
2448
+ deps: Readonly<P>;
2449
+ /**
2450
+ * Run when the app starts (`app.start()`, which `listen` calls) in install
2451
+ * order, and when it stops in reverse order.
2452
+ */
2453
+ on(event: "start" | "stop", handler: (context: PluginLifecycleContext<O, S, P>) => AppHook): void;
2454
+ /**
2455
+ * Run before every request is routed. Succeed with a `Response` (or any
2456
+ * value) to answer it here; with nothing to let it through.
2457
+ */
2458
+ middleware(handler: (context: {
2459
+ request: Request;
2460
+ set: {
2461
+ status?: number | string;
2462
+ headers: Record<string, string>;
2463
+ };
2464
+ }) => Effect.Effect<unknown, unknown, any>): void;
2465
+ /**
2466
+ * Event listeners to add to the app's `events`. `useDeps()` in their `run`,
2467
+ * and in their workflow, returns the plugin's deps, never the host's.
2468
+ */
2469
+ listeners(...listeners: EventListener[]): void;
2470
+ }
2471
+ interface PluginManifest<O extends AnySchema | undefined = undefined, S extends Secrets = {}, T extends Record<string, Table> = {}, E extends Events$1 = {}, RA extends object = {}, SA = unknown, P extends Record<string, unknown> = {}> {
2472
+ /** The npm package name, scoped: `@acme/brick-comments`. */
2473
+ name: string;
2474
+ description?: string;
2475
+ /** The Brick versions it supports, as a semver range: `^0.12.0`. */
2476
+ brick?: string;
2477
+ /** Plugins that must be installed on the same host first, by name. */
2478
+ requires?: readonly string[];
2479
+ /** A Schema for the options; its decoding defaults fill what the user leaves out. */
2480
+ options?: O;
2481
+ /** Secrets it reads, from `defineSecret`. */
2482
+ secrets?: S;
2483
+ /**
2484
+ * What it needs from the app, by name, each with a placeholder of its type:
2485
+ * `{ mailer: {} as Mailer }`. Only the names and types are used. The user passes
2486
+ * the values when installing: `notify(options, { deps: { mailer } })`. Setup
2487
+ * parts read them as `deps`, the plugin's actions as `ctx.deps`.
2488
+ */
2489
+ deps?: P;
2490
+ /**
2491
+ * Tables it owns. They are created for the host database's engine, named
2492
+ * `<host>_<table>` (or with the install's `prefix`), and join its `tables`.
2493
+ */
2494
+ tables?: (builders: PluginTableBuilders) => T;
2495
+ /** Events it emits; they join the host catalog as `<plugin>.<event>`. */
2496
+ events?: E;
2497
+ /** Installed with `resource.use()`; returns what the resource gains. */
2498
+ resource?: (context: PluginSetupContext<OptionsOf<O>, S, T, E, P> & {
2499
+ resource: Resource<any, PluginContext<P>, any>;
2500
+ }) => RA & (RA extends PromiseLike<unknown> ? never : unknown);
2501
+ /** Installed with `service.use()`; returns what `use` hands back. */
2502
+ service?: (context: PluginSetupContext<OptionsOf<O>, S, T, E, P>) => SA & (SA extends PromiseLike<unknown> ? never : unknown);
2503
+ /**
2504
+ * The app-wide part: lifecycle, middleware and listeners. Runs once per plugin instance
2505
+ * when `brick()` creates the app, whether the plugin was installed with
2506
+ * `brick({ plugins })`, `service.use()` or `resource.use()`.
2507
+ */
2508
+ app?: (context: PluginAppContext<OptionsOf<O>, S, P>) => void;
2509
+ /**
2510
+ * A dashboard extension module (`defineDashboard`), relative to the file
2511
+ * that calls `definePlugin`. The dashboard merges it with the app's own.
2512
+ */
2513
+ dashboard?: string;
2514
+ }
2515
+ /** Where the plugin is installed, besides its options. */
2516
+ interface PluginInstallOptions {
2517
+ /** Table name prefix instead of `<host>_`, such as `"blog_"`; `""` for none. */
2518
+ prefix?: string;
2519
+ }
2520
+ /** What the plugin's capabilities are, read from its manifest. */
2521
+ interface PluginInfo {
2522
+ readonly name: string;
2523
+ readonly description?: string | undefined;
2524
+ readonly brick?: string | undefined;
2525
+ readonly requires: readonly string[];
2526
+ readonly options?: AnySchema | undefined;
2527
+ /** The names of the secrets it declares. */
2528
+ readonly secrets: readonly string[];
2529
+ /** The names of the deps it declares, passed when installing. */
2530
+ readonly deps: readonly string[];
2531
+ readonly capabilities: readonly ("tables" | "events" | "resource" | "service" | "app" | "dashboard")[];
2532
+ }
2533
+ /** A plugin ready to install: `resource.use(p)`, `service.use(p)` or `brick({ plugins: [p] })`. */
2534
+ type PluginInstance<RA extends object = {}, SA = unknown> = ResourcePlugin<any, any, RA> & ServicePlugin<any, SA> & {
2535
+ readonly info: PluginInfo;
2536
+ };
2537
+ /** `definePlugin`'s result: call it with options to get an instance. */
2538
+ type PluginFactory<O extends AnySchema | undefined, RA extends object, SA, P extends Record<string, unknown> = {}> = ((...args: {} extends P ? [options?: OptionsInput<O>, install?: PluginInstallOptions] : [options: OptionsInput<O> | undefined, install: PluginInstallOptions & {
2539
+ deps: P;
2540
+ }]) => PluginInstance<RA, SA>) & {
2541
+ readonly info: PluginInfo;
2542
+ };
2543
+ /**
2544
+ * Define a plugin: a manifest Brick checks, plus the capabilities the plugin
2545
+ * brings. Install its instances with `resource.use()`, `service.use()` or
2546
+ * `brick({ plugins })`; scope comes from where it is installed.
2547
+ *
2548
+ * @param manifest - `name`, `brick` (semver range), `requires`, `options`
2549
+ * (Schema), `secrets`, `deps`, `tables`, `events`, the `resource`, `service`
2550
+ * and `app` parts, and a `dashboard` extension.
2551
+ * @returns A factory: `comments({ maxLength: 500 })` validates the options and
2552
+ * the Brick version and returns an instance to install.
2553
+ * @throws From the factory, when the running Brick is outside `brick` or an
2554
+ * option is invalid; when installed, when a required plugin is missing or the
2555
+ * host does not suit the plugin.
2556
+ * @example
2557
+ * export const audit = definePlugin({
2558
+ * name: "@acme/brick-audit",
2559
+ * requires: ["@brickkit/crud"],
2560
+ * options: Schema.Struct({
2561
+ * table: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed("audit"))),
2562
+ * }),
2563
+ * tables: ({ table, text, timestamp }) => ({
2564
+ * log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
2565
+ * }),
2566
+ * resource: ({ tables, hooks }) => {
2567
+ * hooks.afterCreate(({ row, tx }) =>
2568
+ * tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
2569
+ * return {};
2570
+ * },
2571
+ * });
2572
+ *
2573
+ * page.use(audit());
2574
+ */
2575
+ declare function definePlugin<O extends AnySchema | undefined = undefined, S extends Secrets = {}, T extends Record<string, Table> = {}, const E extends Events$1 = {}, RA extends object = {}, SA = unknown, P extends Record<string, unknown> = {}>(manifest: PluginManifest<O, S, T, E, RA, SA, P>): PluginFactory<O, RA, SA, P>;
2576
+ type PluginRouteMethod = HttpMethod;
2577
+ /** Where a plugin route mounts: under the app prefix, its service, or its resource. */
2578
+ declare const PLUGIN_ROUTE_SCOPES: readonly ["app", "service", "resource"];
2579
+ type PluginRouteScope = (typeof PLUGIN_ROUTE_SCOPES)[number];
2580
+ /** What the user may do with a plugin's routes: switch all off, or each off, or move it. */
2581
+ type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> = false | Readonly<Record<string, false | {
2582
+ path?: string;
2583
+ scope?: S;
2584
+ }>>;
2585
+ /** The `ctx` of a service's actions. */
2586
+ type ContextOf<S> = S extends Service<any, infer C, any> ? C : never;
2587
+ /** What the actions of a service need to run. */
2588
+ type RequirementOf<S> = S extends Service<any, any, infer R> ? R : never;
2589
+ /** What a plugin's raw HTTP endpoint receives. */
2590
+ interface PluginEndpointContext<C = any> {
2591
+ params: Record<string, string>;
2592
+ query: Record<string, string | undefined>;
2593
+ /** The JSON body, the text of any other body, or `undefined`. */
2594
+ body: unknown;
2595
+ headers: Record<string, string>;
2596
+ request: Request;
2597
+ /** Set the response's status and headers. */
2598
+ set: {
2599
+ status?: number;
2600
+ headers: Record<string, string>;
2601
+ };
2602
+ ctx: C;
2603
+ }
2604
+ interface PluginRouteOptions<S extends PluginRouteScope> {
2605
+ readonly path: string;
2606
+ readonly method: PluginRouteMethod;
2607
+ readonly scope?: S;
2608
+ }
2609
+ interface PluginRouteRegistrar<C = any, S extends PluginRouteScope = PluginRouteScope, TRequirement = never> {
2610
+ /**
2611
+ * Register an action at a route. It is callable in-process whatever the
2612
+ * route's state, and is named `<resource>.<name>` on a resource.
2613
+ */
2614
+ readonly action: {
2615
+ <I extends AnySchema | undefined = undefined, O extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, A = never, E = never, R = never, RA = never>(config: AuthorizedActionConfig<I, O, TErrors, C, A, E, R, RA> & PluginActionChecks & PluginRouteOptions<S>): Action<I, O, TErrors, A, R | RA | TRequirement>;
2616
+ <I extends AnySchema | undefined = undefined, O extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, A = never, E = never, R = never>(config: ActionConfig<I, O, TErrors, C, A, E, R> & PluginActionChecks & PluginRouteOptions<S>): Action<I, O, TErrors, A, R | TRequirement>;
2617
+ };
2618
+ /**
2619
+ * Register a raw HTTP endpoint. Its Effect's result is the response: a
2620
+ * `Response` as it is, a string as text, `undefined` as an empty 200, and
2621
+ * anything else as JSON.
2622
+ */
2623
+ endpoint<E = never, R = never>(config: PluginRouteOptions<S> & {
2624
+ name: string;
2625
+ handler: (context: PluginEndpointContext<C>) => Effect.Effect<unknown, E, R>;
2626
+ summary?: string;
2627
+ description?: string;
2628
+ tags?: string[];
2629
+ }): void;
2630
+ /**
2631
+ * Reserve a URL segment under the resource, so no resource action takes it,
2632
+ * for a route the plugin may add later. Resource-scoped routes claim their
2633
+ * first segment themselves.
2634
+ */
2635
+ claim(segment: string): void;
2636
+ }
2637
+ interface ServicePluginContext<S extends AnyService = AnyService> {
2638
+ service: S;
2639
+ routes: PluginRouteRegistrar<ContextOf<S>, "app" | "service", RequirementOf<S>>;
2640
+ }
2641
+ interface ResourcePluginContext<S extends AnyService = AnyService, R extends AnyResource = AnyResource> {
2642
+ service: S;
2643
+ resource: R;
2644
+ routes: PluginRouteRegistrar<ContextOf<S>, PluginRouteScope, RequirementOf<S>>;
2645
+ }
2646
+ /** Plugins may specialize their returned API for the installation host. */
2647
+ interface ResourcePluginTypes {
2648
+ readonly table: unknown;
2649
+ readonly context: unknown;
2650
+ readonly resource: unknown;
2651
+ readonly api: object;
2652
+ }
2653
+ type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
2654
+ readonly types: infer H extends ResourcePluginTypes;
2655
+ } ? (H & {
2656
+ readonly table: T;
2657
+ readonly context: C;
2658
+ readonly resource: R;
2659
+ })["api"] : P extends PluginInstance<infer A extends object, any> ? A : P extends ResourcePlugin<any, any, infer A> ? A : never;
2660
+ /** Which host a plugin descriptor installs on. Process-global, so descriptors survive a second copy of this package. */
2661
+ declare const PLUGIN_KIND: unique symbol;
2662
+ interface ServicePlugin<S extends AnyService, A> {
2663
+ readonly [PLUGIN_KIND]: "service" | "plugin";
2664
+ readonly name: string;
2665
+ readonly routes?: PluginRoutes<"app" | "service"> | undefined;
2666
+ readonly setup: (context: ServicePluginContext<S>) => A;
2667
+ }
2668
+ interface ResourcePlugin<S extends AnyService, R extends AnyResource, A extends object> {
2669
+ readonly [PLUGIN_KIND]: "resource" | "plugin";
2670
+ readonly name: string;
2671
+ readonly routes?: PluginRoutes | undefined;
2672
+ readonly setup: (context: ResourcePluginContext<S, R>) => A;
2673
+ }
2674
+ /** A plugin as `app.definition.plugins` lists it. */
2675
+ interface InstalledPlugin {
2676
+ readonly name: string;
2677
+ readonly brick?: string;
2678
+ readonly scope: "app" | "service" | "resource";
2679
+ readonly service?: string;
2680
+ readonly resource?: string;
2681
+ /** The plugin's dashboard extension, an absolute path. */
2682
+ readonly dashboard?: string;
2683
+ }
2684
+ /** What a tool tells MCP clients about itself. */
2685
+ interface ToolAnnotations {
2686
+ readonly title?: string;
2687
+ readonly readOnlyHint?: boolean;
2688
+ readonly destructiveHint?: boolean;
2689
+ readonly idempotentHint?: boolean;
2690
+ readonly openWorldHint?: boolean;
2691
+ }
2692
+ /** What a tool adds to an action's declaration. */
2693
+ interface ToolOptions {
2694
+ readonly title?: string;
2695
+ /** The MCP hints about what the tool does. */
2696
+ readonly annotations?: ToolAnnotations;
2697
+ /** Also serve it over HTTP and in OpenAPI, as an action (default false). */
2698
+ readonly http?: boolean;
2699
+ }
2700
+ /** The `ctx` of a tool defined outside a service, until a service takes it. */
2701
+ type ToolContext = ActionContext;
2702
+ /** A tool: an action that AI agents can call through MCP. */
2703
+ type Tool<TInput extends AnySchema | undefined = any, TOutput extends AnySchema | undefined = any, TErrors extends ErrorDefinitions = any, A = any, R = any> = Action<TInput, TOutput, TErrors, A, R> & {
2704
+ readonly kind: "tool";
2705
+ readonly config: ToolOptions;
2706
+ };
2707
+ /** Any tool, whatever its schemas. */
2708
+ type AnyTool = Tool<any, any, any, any, any>;
2709
+ /**
2710
+ * Define a tool: an action that AI agents can call through MCP. It takes the
2711
+ * same configuration as `service.action` (schemas, `authorize`, `errors`), plus
2712
+ * `title`, `annotations` and `http`. It is not an HTTP route unless `http` is
2713
+ * set. Register it with `service.tool(tool)`.
2714
+ *
2715
+ * @throws When `input` is not an object schema, since MCP passes arguments by name.
2716
+ * @example
2717
+ * export const echo = defineTool({
2718
+ * name: "echo",
2719
+ * description: "Returns the message it is given.",
2720
+ * input: Schema.Struct({ message: Schema.String }),
2721
+ * output: Schema.String,
2722
+ * execute: ({ input }) => Effect.succeed(`Echo: ${input.message}`),
2723
+ * });
2724
+ */
2725
+ declare function defineTool<TInput extends AnySchema | undefined = undefined, TOutput extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, TCtx = ToolContext, A = never, E = never, R = never, RA = never>(config: AuthorizedActionConfig<TInput, TOutput, TErrors, TCtx, A, E, R, RA> & ToolOptions): Tool<TInput, TOutput, TErrors, A, R | RA>;
2726
+ declare function defineTool<TInput extends AnySchema | undefined = undefined, TOutput extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, TCtx = ToolContext, A = never, E = never, R = never>(config: ActionConfig<TInput, TOutput, TErrors, TCtx, A, E, R> & ToolOptions): Tool<TInput, TOutput, TErrors, A, R>;
2727
+ /**
2728
+ * Whether a value was made with `defineTool`, as opposed to `service.action`.
2729
+ *
2730
+ * @returns `true` for a tool, narrowing its type.
2731
+ */
2732
+ declare function isTool(value: unknown): value is AnyTool;
2733
+ type DbPart<TDb> = [TDb] extends [undefined] ? {} : {
2734
+ db: TDb;
2735
+ };
2736
+ type DbRequirement<TDb> = [TDb] extends [undefined] ? never : DatabaseService<TDb>;
2737
+ /** What `TUser` is when a service has no `identity` hook. */
2738
+ interface NoIdentity {
2739
+ readonly "~brick/noIdentity": true;
2740
+ }
2741
+ type UserOf<TExtra, TUser> = [TUser] extends [NoIdentity] ? TExtra extends {
2742
+ user: infer U;
2743
+ } ? U : null : NonNullable<TUser> | null;
2744
+ type DepsPart<D> = [keyof D] extends [never] ? {} : {
2745
+ deps: D;
2746
+ };
2747
+ /** The `ctx` of an action: the request fields, `db` when the service has a database, `deps` when it declares some, what `context` adds, and `user`. */
2748
+ type ServiceContext<TDb, TExtra, TUser, TDeps = {}> = BaseContext & DbPart<TDb> & DepsPart<CallDeps<TDeps>> & Omit<TExtra, "user"> & {
2749
+ user: UserOf<TExtra, TUser>;
2750
+ };
2751
+ interface ServiceOptions<TDb, TExtra, RC, TUser, RI, TDeps = {}, TEvents = {}> {
2752
+ /** From `defineDatabase`. `ctx.db` is its database. */
2753
+ readonly database?: DatabaseHandle<TDb, any>;
2754
+ /**
2755
+ * The values the service's code uses, such as clients: `{ carrier: createCarrier() }`,
2756
+ * as a plain object. Actions read them as `ctx.deps`, typed from this object.
2757
+ * A `defineStorage({ driver: s3() })` file storage in it is scoped to the
2758
+ * caller's tenant (the service needs an `identity` that returns one), and is
2759
+ * the only file storage `/_brick/files` serves for the app. They are created
2760
+ * when the module is imported, so a dep should connect on first use.
2761
+ */
2762
+ readonly deps?: TDeps;
2763
+ /** Where rate limits and webhook replay keep their counts, instead of the app's `storage`. From `defineStorage`. */
2764
+ readonly storage?: KeyValueStorage;
2765
+ /** Adds fields, such as the request's session, to the `ctx` of every action. It sees the request and `db`. */
2766
+ readonly context?: (ctx: BaseContext & DbPart<TDb> & DepsPart<RawDeps<TDeps>>) => Effect.Effect<TExtra, any, RC>;
2767
+ /** Who the caller is: the user, or `null`. It becomes `ctx.user`. It sees what `context` added. */
2768
+ readonly identity?: (ctx: BaseContext & DbPart<TDb> & DepsPart<RawDeps<TDeps>> & TExtra) => Effect.Effect<TUser, any, RI>;
2769
+ /**
2770
+ * The service's event catalog: a payload schema per event name. Each becomes
2771
+ * `service.events.<name>`, recorded as `<service>.<name>`. With a catalog, the
2772
+ * service records only these events (and the CRUD events of its resources).
2773
+ */
2774
+ readonly events?: TEvents;
2775
+ }
2776
+ type InputType<S> = S extends AnySchema ? S["Type"] : undefined;
2777
+ /** The options of an action that sit beside what `ActionConfig` declares. */
2778
+ interface ActionFeatures<TInput, TOutput, TCtx> {
2779
+ /** At most `max` calls per `windowMs`, per key, counted in the service's or the app's key-value storage. A call over it fails with `RATE_LIMITED` (429). */
2780
+ readonly rateLimit?: RateLimits<InputType<TInput>, TCtx>;
2781
+ /** Whether a call may see the output's `Sensitive` fields: `true`, or a check per field. */
2782
+ readonly reveal?: Reveal<InputType<TInput>, TCtx>;
2783
+ /** What the audit row says of the call, or `false` for no row. */
2784
+ readonly audit?: false | AuditOptions<InputType<TInput>, TOutput extends AnySchema ? TOutput["Type"] : any>;
2785
+ }
2786
+ /** A named group of actions that share a database, a context and an identity. */
2787
+ interface Service<TName extends string, TCtx, TRequirement, TDeps = {}, TEvents extends Record<string, AnySchema> = any> {
2788
+ readonly name: TName;
2789
+ /** The declared events: `service.events.<name>`, for `defineListener({ on })` and `emitEvent`. */
2790
+ readonly events: EventRefs<TEvents>;
2791
+ /** Whether it declared an event catalog, so it records only events from it. */
2792
+ readonly hasCatalog: boolean;
2793
+ readonly database: DatabaseHandle<any, any> | undefined;
2794
+ /** The values the service declared as `deps`, as they were: a file storage is not yet scoped to a tenant. `useDeps(service)` returns them. */
2795
+ readonly deps: Readonly<RawDeps<TDeps>>;
2796
+ /** Its own key-value storage, if it has one; else the app's serves it. */
2797
+ readonly storage: KeyValueStorage | undefined;
2798
+ /** Whether it has a `context` hook. */
2799
+ readonly hasContext: boolean;
2800
+ /** Whether it has an `identity` hook. */
2801
+ readonly hasIdentity: boolean;
2802
+ /** Register an action made elsewhere, such as a tool, to serve it over HTTP too. */
2803
+ action(action: AnyAction): this;
2804
+ /**
2805
+ * Declare an action on the service. Its `input` and `output` come from the
2806
+ * schemas, its error codes from `errors`, and `ctx` from the service.
2807
+ */
2808
+ action<TInput extends AnySchema | undefined = undefined, TOutput extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, A = never, E = never, R = never, RA = never>(config: AuthorizedActionConfig<TInput, TOutput, TErrors, TCtx, A, E, R, RA> & ActionFeatures<TInput, TOutput, TCtx>): Action<TInput, TOutput, TErrors, A, R | RA | TRequirement>;
2809
+ action<TInput extends AnySchema | undefined = undefined, TOutput extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, A = never, E = never, R = never>(config: ActionConfig<TInput, TOutput, TErrors, TCtx, A, E, R> & ActionFeatures<TInput, TOutput, TCtx>): Action<TInput, TOutput, TErrors, A, R | TRequirement>;
2810
+ /**
2811
+ * Declare a webhook: a route a provider calls. `verify` checks the raw body
2812
+ * first and nothing else runs until it accepts; then the payload is checked
2813
+ * against `input`, a delivery already handled is answered `{ duplicate: true }`,
2814
+ * and `execute` runs. Unless `replay` is `false`, the service's or the app's key-value
2815
+ * storage remembers the event ids.
2816
+ *
2817
+ * @example
2818
+ * export const push = hooks.webhook({
2819
+ * name: "push",
2820
+ * verify: hmacSignature({ secret, header: "x-hub-signature-256", prefix: "sha256=" }),
2821
+ * eventId: ({ headers }) => Effect.succeed(headers.get("x-delivery") ?? undefined),
2822
+ * input: Schema.Struct({ action: Schema.String }),
2823
+ * execute: ({ input }) => Effect.log(input.action),
2824
+ * });
2825
+ */
2826
+ webhook<TInput extends AnySchema, const TErrors extends ErrorDefinitions = {}, A = never, E = never, R = never>(config: WebhookConfig<TInput, TErrors, TCtx, A, E, R>): Action<TInput, undefined, TErrors, A, R | TRequirement>;
2827
+ getAction(name: string): AnyAction | undefined;
2828
+ listActions(): AnyAction[];
2829
+ /**
2830
+ * Declare a WebSocket on the service, served at `/api/<service>/<socket>`
2831
+ * by `app.listen`. Its events are typed by Schemas, its handlers return Effects.
2832
+ * The result sends to rooms: `yield* live.emit("doc:1", "message", payload)`.
2833
+ */
2834
+ socket<const I extends SocketSchemas, const O extends SocketSchemas, const TErrors extends ErrorDefinitions = {}>(config: SocketConfig<I, O, TCtx, TErrors>): BrickSocketHandle<SocketPayloads<O>>;
2835
+ listSockets(): RegisteredSocket[];
2836
+ /**
2837
+ * Declare a route for a third party's WebSocket client, such as a telephony
2838
+ * media stream: a plain upgrade without `brick.v1`, with frames exactly as
2839
+ * sent. Served at `/api/<service>/<name>` by `app.listen`, and shown only by
2840
+ * `app.rawSockets()`. `ctx` is resolved once at the upgrade. Callbacks return
2841
+ * Effects, `schema` is an Effect Schema.
2842
+ */
2843
+ rawSocket<const S extends AnySchema | undefined = undefined, Parsed = never, State = {}>(config: RawSocketConfig<TCtx, State, RawSocketMessage<S, Parsed>, S, Parsed>): RawSocketHandle;
2844
+ listRawSockets(): RegisteredRawSocket[];
2845
+ /**
2846
+ * Declare a tool: an action that AI agents call through MCP. It is not an
2847
+ * HTTP route unless `http` is set or the tool is registered with `action`.
2848
+ */
2849
+ tool<TInput extends AnySchema | undefined = undefined, TOutput extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, A = never, E = never, R = never, RA = never>(config: AuthorizedActionConfig<TInput, TOutput, TErrors, TCtx, A, E, R, RA> & ToolOptions): Tool<TInput, TOutput, TErrors, A, R | RA | TRequirement>;
2850
+ tool<TInput extends AnySchema | undefined = undefined, TOutput extends AnySchema | undefined = undefined, const TErrors extends ErrorDefinitions = {}, A = never, E = never, R = never>(config: ActionConfig<TInput, TOutput, TErrors, TCtx, A, E, R> & ToolOptions): Tool<TInput, TOutput, TErrors, A, R | TRequirement>;
2851
+ /** Register a tool made with `defineTool`. */
2852
+ tool(tool: AnyTool): this;
2853
+ getTool(name: string): AnyTool | undefined;
2854
+ listTools(): AnyTool[];
2855
+ /** Declare a resource: a table and its entity, which plugins extend with `use`. */
2856
+ resource<TTable, const O extends ResourceTypeOptions>(config: ResourceConfig<TTable> & O & Record<Exclude<keyof O, keyof ResourceConfig>, never>): Resource<TTable, TCtx, ResourceIdentity<TTable, O>, EventRefs<TEvents>, TRequirement>;
2857
+ getResource(name: string): AnyResource | undefined;
2858
+ listResources(): AnyResource[];
2859
+ /** Install a plugin. It returns the API the plugin contributed. */
2860
+ use<A>(plugin: ServicePlugin<this, A>): A;
2861
+ /** Builds the `ctx` of a call: the request fields, `db`, what `context` adds, then `user`. A `ctx` this service built is returned as it is. */
2862
+ resolveContext(call?: CallContext): Effect.Effect<TCtx, unknown, any>;
2863
+ }
2864
+ type AnyService = Service<string, any, any, any>;
2865
+ /**
2866
+ * Declare a service. Its name is its segment of every action route
2867
+ * (`/api/<name>/<action>`).
2868
+ *
2869
+ * @example
2870
+ * const pages = defineService("pages", {
2871
+ * database,
2872
+ * identity: ({ request }) => readUser(request),
2873
+ * });
2874
+ * export const getPage = pages.action({
2875
+ * name: "get",
2876
+ * method: "GET",
2877
+ * input: Schema.Struct({ id: Schema.String }),
2878
+ * output: Page,
2879
+ * execute: ({ input, ctx, error }) =>
2880
+ * Effect.gen(function* () {
2881
+ * const [page] = yield* ctx.db.select().from(tables.pages).where(eq(tables.pages.id, input.id));
2882
+ * return page ?? (yield* error.NOT_FOUND());
2883
+ * }),
2884
+ * });
2885
+ */
2886
+ declare function defineService<const TName extends string, TDb = undefined, TExtra extends object = {}, RC = never, TUser = NoIdentity, RI = never, TDeps extends object = {}, const TEvents extends Record<string, AnySchema> = {}>(name: TName, options?: ServiceOptions<TDb, TExtra, RC, TUser, RI, TDeps, TEvents>): Service<TName, ServiceContext<TDb, TExtra, TUser, TDeps>, DbRequirement<TDb> | RC | RI, TDeps, TEvents>;
2887
+ /** How an action is protected: nothing checks the caller, `authorize` does, or it also limits the rows. */
2888
+ type ActionAccessPolicy = "public" | "authorized" | "scoped";
2889
+ /** What `getActionAccess` says of an action. */
2890
+ interface ActionAccessInfo {
2891
+ hasAuthorize: boolean;
2892
+ hasScope: boolean;
2893
+ policy: ActionAccessPolicy;
2894
+ }
2895
+ /** The route prefix of actions when the app sets none. */
2896
+ declare const DEFAULT_PREFIX = "/api";
2897
+ /** `orderBilling` becomes `order-billing`, `importCSV` becomes `import-csv`. Dots and dashes stay. */
2898
+ declare function kebabCase(name: string): string;
2899
+ /** What the app records about one action route, as `@brickkit/core`'s `RouteIR`, for the CLI and the dashboard. */
2900
+ interface RouteIR {
2901
+ readonly method: HttpMethod;
2902
+ readonly path: string;
2903
+ readonly service: string;
2904
+ readonly action: string;
2905
+ /** A `webhook` has a verified raw body; see `service.webhook`. */
2906
+ readonly kind: "action" | "webhook";
2907
+ /** The plugin that registered the action, if one did. */
2908
+ readonly plugin?: string;
2909
+ readonly input: boolean;
2910
+ readonly output: boolean;
2911
+ readonly context: boolean;
2912
+ readonly authorize: boolean;
2913
+ readonly inputSource: "query" | "body";
2914
+ /** The most bytes of a body, for an action with file fields (by `Content-Length`): the files' sizes and room for the form's other fields. Absent when it is not bounded. */
2915
+ readonly bodyLimit?: number;
2916
+ }
2917
+ /** Where an action is served: its method and path. */
2918
+ interface ActionRoute {
2919
+ method: HttpMethod;
2920
+ path: string;
2921
+ }
2922
+ /**
2923
+ * Where an action is served over HTTP: its method and its path
2924
+ * (`${prefix}/${service}/${action}` in kebab-case, the action's own `path`
2925
+ * under the service, or the route a plugin mounted it at).
2926
+ *
2927
+ * @param action - An action registered on a service.
2928
+ * @param prefix - The app's route prefix (default `/api`).
2929
+ * @returns `false` when a plugin switched the route off, otherwise the route.
2930
+ */
2931
+ declare function getActionRoute(action: AnyAction, prefix?: string): ActionRoute | false;
2932
+ /** The plugin and resource that own an action, for OpenAPI, introspection and the client contract. */
2933
+ declare function actionOwners(action: AnyAction): {
2934
+ plugin?: string;
2935
+ resource?: string;
2936
+ };
2937
+ /** A socket of the app, as `definition.sockets` lists it: its schema, its service and its path. */
2938
+ type AppSocket = SocketSchema & {
2939
+ service: string;
2940
+ path: string;
2941
+ };
2942
+ interface ActionSchema {
2943
+ name: string;
2944
+ /** Present only when this action has a route. */
2945
+ method?: HttpMethod;
2946
+ path?: string;
2947
+ serviceName: string;
2948
+ description?: string;
2949
+ inputSchema?: unknown;
2950
+ outputSchema?: unknown;
2951
+ hasAuthorize: boolean;
2952
+ hasScope: boolean;
2953
+ accessPolicy: ActionAccessPolicy;
2954
+ /** The plugin that registered the action, and its resource. */
2955
+ plugin?: string;
2956
+ resource?: string;
2957
+ errors?: Readonly<Record<string, ErrorDefinition>>;
2958
+ /** The events the action says it emits (documentation only). */
2959
+ emits?: readonly string[];
2960
+ tags?: readonly string[];
2961
+ }
2962
+ interface ServiceSchema {
2963
+ name: string;
2964
+ /** The service options as JSON. The functions, such as `context`, are left out. */
2965
+ options: Record<string, unknown>;
2966
+ hasDatabase: boolean;
2967
+ databaseConfig?: {
2968
+ engine: "sqlite" | "postgres";
2969
+ tables: string[];
2970
+ };
2971
+ /** Present when the application lists its sockets. */
2972
+ sockets?: AppSocket[];
2973
+ actions: ActionSchema[];
2974
+ /** The events the service declares, with their payload schemas; absent without a catalog or plugin events. */
2975
+ events?: {
2976
+ name: string;
2977
+ schema: unknown;
2978
+ plugin?: string;
2979
+ }[];
2980
+ }
2981
+ /** The shape of the app that `/_brick/services` serves, and the CLI's dashboard and client contract read. */
2982
+ interface ArchitectureSchema {
2983
+ version: string;
2984
+ services: ServiceSchema[];
2985
+ /** Present when the app has an `events` option. */
2986
+ events?: unknown;
2987
+ /** Every plugin installation, with its dashboard extension. */
2988
+ plugins?: readonly unknown[];
2989
+ }
2990
+ /** What `app.definition` holds of the app: the part the architecture is built from. */
2991
+ interface ArchitectureApplication {
2992
+ services: readonly AnyService[];
2993
+ /** The routes the app mounted. Without them, every action has its default route under `/api`. */
2994
+ routes?: readonly RouteIR[];
2995
+ sockets?: readonly AppSocket[];
2996
+ events?: unknown;
2997
+ plugins?: readonly unknown[];
2998
+ }
2999
+ /**
3000
+ * The architecture of an app: each service with its database and its actions,
3001
+ * and the method and path of every action that has a route.
3002
+ */
3003
+ declare function exportArchitecture(application: ArchitectureApplication): ArchitectureSchema;
3004
+ /**
3005
+ * Which origins may call the app: an exact origin (`"https://app.example.com"`),
3006
+ * a list of them, or a predicate. `true` allows only the app's own origin.
3007
+ */
3008
+ type CorsOrigin = true | string | readonly string[] | ((origin: string, request: Request) => boolean);
3009
+ /** `brick({ cors })`: an origin rule, or the rule plus `credentials`. */
3010
+ type CorsOptions = CorsOrigin | {
3011
+ /** Default `true`: the app's own origin only. */
3012
+ origin?: CorsOrigin;
3013
+ /** Send `Access-Control-Allow-Credentials: true` to allowed origins (cookies, auth headers). */
3014
+ credentials?: boolean;
3015
+ };
3016
+ /** What `brick({ onResponse })` receives for every response. */
3017
+ interface ResponseHookContext {
3018
+ request: Request;
3019
+ status: number;
3020
+ /** A copy of the response's headers: set, append or delete, and the response is sent with them. */
3021
+ headers: Headers;
3022
+ }
3023
+ /** What `brick({ onError })` receives for a request Brick answered with a 5xx. */
3024
+ interface ErrorHookContext {
3025
+ /** What failed: a defect, or a declared failure with a 5xx status. */
3026
+ error: unknown;
3027
+ request: Request;
3028
+ /** The response Brick built: the error JSON, with its trace headers. */
3029
+ response: Response;
3030
+ }
3031
+ type OnResponse = (context: ResponseHookContext) => Effect.Effect<unknown, unknown, any>;
3032
+ type OnError = (context: ErrorHookContext) => Effect.Effect<Response | void, unknown, any>;
3033
+ type EndpointMethod = HttpMethod;
3034
+ /** What a raw endpoint's handler receives. */
3035
+ interface EndpointContext {
3036
+ params: Record<string, string>;
3037
+ query: Record<string, string | undefined>;
3038
+ /** The JSON body, the text of any other body, or `undefined`. */
3039
+ body: unknown;
3040
+ headers: Record<string, string>;
3041
+ request: Request;
3042
+ /** Set the response's status and headers. Mutate it from the handler. */
3043
+ set: {
3044
+ status?: number;
3045
+ headers: Record<string, string>;
3046
+ };
3047
+ /** The database of `service` (or of the first service that has one); `undefined` when there is none. */
3048
+ db: any;
3049
+ logger: Logger;
3050
+ traceId: string;
3051
+ requestId: string;
3052
+ }
3053
+ /**
3054
+ * A plain route beside the actions: a page, a redirect, a webhook receiver for
3055
+ * a provider Brick has no verifier for. Mount it with `brick({ endpoints })` or
3056
+ * `app.endpoint()`. Its handler returns an Effect, which may need the services
3057
+ * of the app's `layer`; a failure becomes the same error JSON as an action's.
3058
+ */
3059
+ interface EndpointDefinition<E = any, R = any> {
3060
+ method: EndpointMethod;
3061
+ /** Path with `:name` parameters, such as `/p/:slug`. */
3062
+ path: string;
3063
+ /**
3064
+ * Its value is the response: a `Response`, text, or JSON; `undefined` is an
3065
+ * empty 200. `ctx.set` changes the status and headers of the other kinds.
3066
+ */
3067
+ handler: (ctx: EndpointContext) => Effect.Effect<unknown, E, R>;
3068
+ /** Where `ctx.db` comes from: a service, or its name. Defaults to the first service with a database. */
3069
+ service?: AnyService | string;
3070
+ /** An explicit database, independent of a service. */
3071
+ database?: AnyDatabaseHandle;
3072
+ summary?: string;
3073
+ description?: string;
3074
+ tags?: string[];
3075
+ /** The plugin that contributed it; OpenAPI labels it `x-brick-plugin`. */
3076
+ plugin?: string;
3077
+ }
3078
+ /** An OpenAPI document as plain JSON. */
3079
+ type OpenApiDocument = Record<string, unknown>;
3080
+ /** An extra OpenAPI document for the API reference, such as Better Auth's. */
3081
+ interface ReferenceDocument {
3082
+ /** Name in the reference's list of documents. */
3083
+ title: string;
3084
+ /** The document, or a function returning it; called each time the app starts. */
3085
+ document: OpenApiDocument | (() => OpenApiDocument | Promise<OpenApiDocument>);
3086
+ }
3087
+ /** A named OpenAPI document ready to render. */
3088
+ interface ApiDocument {
3089
+ title: string;
3090
+ document: OpenApiDocument;
3091
+ }
3092
+ /** Developer documentation for the `brick dev` dashboard. */
3093
+ interface DocumentationOptions {
3094
+ /**
3095
+ * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the
3096
+ * app entry, as it reads in the file that sets it.
3097
+ */
3098
+ dir: string;
3099
+ /**
3100
+ * Module whose exports are React components for MDX, added to the built-in
3101
+ * ones; a relative path starts where `dir` does. A default export or a
3102
+ * `components` export holds the name-to-component map. The dashboard bundles
3103
+ * it, so it may import anything the project has.
3104
+ */
3105
+ components?: string;
3106
+ }
3107
+ interface ReferenceOptions {
3108
+ /** Also serve a standalone Scalar page here. Without a path, no page is served. */
3109
+ path?: string;
3110
+ title?: string;
3111
+ specUrl?: string;
3112
+ /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */
3113
+ documents?: ReferenceDocument[];
3114
+ }
3115
+ /** Renders the Scalar API reference page for the given OpenAPI URL. */
3116
+ declare function scalarDocsHTML(specUrl: string, title: string): string;
3117
+ interface RequestLoggingOptions {
3118
+ /** Turn it off without removing the option (default true). */
3119
+ enabled?: boolean;
3120
+ /** Where each line goes (default: the console). */
3121
+ logger?: (message: string) => void;
3122
+ }
3123
+ type Handler = (request: Request) => Response | Promise<Response>;
3124
+ /**
3125
+ * Wraps a fetch handler so each request is logged as
3126
+ * `METHOD /path → status (Nms)`: for the routes you serve yourself around
3127
+ * `app.fetch`, as `brick` logs its own. A handler that throws is logged as 500
3128
+ * and the error goes on.
3129
+ *
3130
+ * @example
3131
+ * Bun.serve({ fetch: requestLoggingPlugin()(app.fetch) });
3132
+ */
3133
+ declare function requestLoggingPlugin(options?: RequestLoggingOptions): <F extends Handler>(handler: F) => F;
3134
+ /** A JSON Schema document, as `Schema.toJsonSchemaDocument` writes it, with its definitions under `$defs`. */
3135
+ type JsonSchema = Record<string, unknown>;
3136
+ /**
3137
+ * What the CLI's client contract is generated from: each action's route and
3138
+ * the JSON Schemas of what travels over the wire, and each socket's. The CLI
3139
+ * reads it with `app.clientContract()` and holds no copy of `effect`.
3140
+ */
3141
+ interface ClientContractSource {
3142
+ readonly actions: readonly {
3143
+ readonly service: string;
3144
+ readonly name: string;
3145
+ readonly method: HttpMethod;
3146
+ readonly path: string;
3147
+ readonly plugin?: string;
3148
+ readonly resource?: string;
3149
+ /** Where the typed client puts the action, when a plugin names it. */
3150
+ readonly clientPath?: readonly string[];
3151
+ readonly input?: JsonSchema;
3152
+ readonly output?: JsonSchema;
3153
+ /** The codes the action declares. */
3154
+ readonly errors: readonly string[];
3155
+ }[];
3156
+ readonly sockets: readonly {
3157
+ readonly service: string;
3158
+ readonly name: string;
3159
+ readonly path: string;
3160
+ readonly input: Readonly<Record<string, JsonSchema>>;
3161
+ readonly output: Readonly<Record<string, JsonSchema>>;
3162
+ readonly errors: readonly string[];
3163
+ }[];
3164
+ }
3165
+ /** Who may open the dashboard that `brick start` serves for monitoring. */
3166
+ interface DashboardAuth {
3167
+ /**
3168
+ * Secrets that let a request in. A browser asks for one in its sign-in
3169
+ * prompt (any user name, the secret as the password), and monitors and
3170
+ * scripts send `Authorization: Bearer <secret>`. Give several to rotate one
3171
+ * while the other still works. Each is at least 16 characters long;
3172
+ * `openssl rand -base64 32` makes a good one.
3173
+ */
3174
+ token?: string | readonly string[];
3175
+ /**
3176
+ * Your own check, to sign people in with the auth the app already has: read
3177
+ * a session cookie, verify a Better Auth or Clerk session, look at a header
3178
+ * a proxy adds. It receives the request (method, URL, and headers; no body)
3179
+ * and returns `true` to let it in, `false` to refuse it with 401, or a
3180
+ * `Response` to send instead, such as a redirect to your login page. If it
3181
+ * throws or takes longer than five seconds, the request is refused with 503.
3182
+ *
3183
+ * Return `{ user: { id, name } }` to let it in and say who it is: requests
3184
+ * the dashboard's pages send to the app through `/app/*` carry that user,
3185
+ * signed, which the app reads with `ctx.dashboard?.user` in an action or
3186
+ * `dashboardUser(request)` in an endpoint.
3187
+ *
3188
+ * A request is let in when it carries a valid `token`, or when this
3189
+ * returns `true`; give both to let monitors in by token and people in by
3190
+ * sign-in.
3191
+ */
3192
+ authorize?: (request: Request) => boolean | Response | {
3193
+ user: DashboardUser;
3194
+ } | Promise<boolean | Response | {
3195
+ user: DashboardUser;
3196
+ }>;
3197
+ }
3198
+ /**
3199
+ * The monitoring dashboard `brick start` serves beside the app, on a port of
3200
+ * its own: live requests, logs, errors, and the shape of the service, so it
3201
+ * stays reachable when the app's own routes are not. `brick dev` has its own
3202
+ * dashboard, set by command line options, and ignores this.
3203
+ *
3204
+ * Setting it turns on `telemetry`, since the dashboard shows what is traced.
3205
+ * While it is on, `ctx.logger` and `console` lines written during a request
3206
+ * go to the dashboard instead of the console.
3207
+ */
3208
+ interface DashboardOptions {
3209
+ /** Default 9400. */
3210
+ port?: number;
3211
+ /**
3212
+ * The address to listen on. Default `127.0.0.1`, reachable only from the same
3213
+ * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard
3214
+ * will not start on any other address without it.
3215
+ */
3216
+ host?: string;
3217
+ auth?: DashboardAuth;
3218
+ /**
3219
+ * Days of finished requests to keep on disk, in `.brick/` of the working
3220
+ * folder. Default 0: only what happened since the process started, which is
3221
+ * lost when it restarts. Needs a folder that outlives the container.
3222
+ */
3223
+ historyDays?: number;
3224
+ /**
3225
+ * Show the Schedules and Workflows views, which `brick dev` always has: each
3226
+ * schedule's next run and last runs, and the workflow inspector with every
3227
+ * run's steps. A signed-in user (one `auth.authorize` returned as
3228
+ * `{ user }`) can also run a schedule now, cancel or replay a run, and
3229
+ * resume a hook; anyone else the dashboard lets in (by token, or by
3230
+ * `authorize` returning `true`) can only look.
3231
+ *
3232
+ * Default: on when this process dispatches events (`events.dispatch` is not
3233
+ * false), off when it only records them, since another process runs its
3234
+ * schedules and workflows. Set `true` on such a process to see them anyway:
3235
+ * they are read-only there, for everyone, with a note that another process
3236
+ * runs them.
3237
+ */
3238
+ inspector?: boolean;
3239
+ /**
3240
+ * Let a coding agent (Claude Code, Cursor, Codex) read the dashboard's data
3241
+ * over MCP at `/mcp`, while it debugs: requests, traces, logs, errors and the
3242
+ * app's architecture. Default false; `brick dev` always has it, since it only
3243
+ * listens on this machine. Its own tools only read, even for a signed-in
3244
+ * user, and it passes the same checks as the rest of the dashboard: the agent sends
3245
+ * `Authorization: Bearer <token>` with one of `auth.token`.
3246
+ *
3247
+ * What the agent reads goes to its model provider: request paths and
3248
+ * messages, log lines (which can hold what your users typed), error stacks,
3249
+ * and span attributes such as SQL text. Turn it on only for a dashboard
3250
+ * whose data you are willing to send there.
3251
+ *
3252
+ * A tool marked `dashboard: true` is offered there too, through
3253
+ * `DASHBOARD_MCP_ROUTE`.
3254
+ */
3255
+ mcp?: boolean;
3256
+ /**
3257
+ * How this instance's requests and logs are tagged once it copies its
3258
+ * peers' history (`peers`). Default `"local"`.
3259
+ */
3260
+ name?: string;
3261
+ /**
3262
+ * Other instances of the same app whose request history this dashboard
3263
+ * copies into its own, every `peerSyncMinutes`, so its history views show
3264
+ * all of them, each request tagged with its instance. It asks each peer's
3265
+ * dashboard for its requests with the peer's token, and only reads. A peer
3266
+ * that does not answer is shown as failing, and caught up on the next copy.
3267
+ * Needs `historyDays`: the copies are kept on disk with this instance's
3268
+ * own. The live view, Errors, Schedules and Workflows stay this
3269
+ * instance's own.
3270
+ */
3271
+ peers?: readonly DashboardPeer[];
3272
+ /** Minutes between copies of the peers' history. Default 5. */
3273
+ peerSyncMinutes?: number;
3274
+ }
3275
+ /** Another instance's dashboard, which `dashboard.peers` reads. */
3276
+ interface DashboardPeer {
3277
+ /** How its rows are tagged, such as `"india"`. Letters, digits, `-` and `_`. */
3278
+ name: string;
3279
+ /** The address its dashboard is served at, such as `https://brick-in.example.com`. */
3280
+ url: string;
3281
+ /** One of the peer's `dashboard.auth.token`, sent as `Authorization: Bearer`. */
3282
+ token: string;
3283
+ }
3284
+ /** Where the app answers MCP for the dashboard's `/mcp`, to a request the dashboard signed. */
3285
+ declare const DASHBOARD_MCP_ROUTE = "/_brick/dashboard/mcp";
3286
+ /** The dashboard's own MCP tools. */
3287
+ declare const DASHBOARD_MCP_TOOLS: readonly ["summary", "list_requests", "get_trace", "list_errors", "app_overview", "search_logs", "list_reloads", "list_schedules", "list_runs", "get_run", "get_openapi", "list_docs", "read_doc"];
3288
+ /**
3289
+ * Check what `brick()` was given, and freeze it. The secrets sit behind a getter
3290
+ * that is not enumerable, so logging or serializing the application definition
3291
+ * does not print them.
3292
+ */
3293
+ declare function normalizeDashboard(options: DashboardOptions | undefined): DashboardOptions | undefined;
3294
+ type SpanAttributes = Record<string, unknown>;
3295
+ interface SpanEventRecord {
3296
+ name: string;
3297
+ timeMs: number;
3298
+ attributes: SpanAttributes;
3299
+ }
3300
+ /** A span began. The dashboard shows it as a request in flight. */
3301
+ interface SpanStartRecord {
3302
+ phase: "start";
3303
+ traceId: string;
3304
+ spanId: string;
3305
+ parentSpanId?: string;
3306
+ name: string;
3307
+ startMs: number;
3308
+ attributes: SpanAttributes;
3309
+ }
3310
+ /** A span ended, with everything the dashboard shows of it. */
3311
+ interface SpanEndRecord {
3312
+ phase: "end";
3313
+ traceId: string;
3314
+ spanId: string;
3315
+ name: string;
3316
+ endMs: number;
3317
+ status: "unset" | "ok" | "error";
3318
+ statusMessage?: string;
3319
+ attributes: SpanAttributes;
3320
+ events: SpanEventRecord[];
3321
+ }
3322
+ /** What the dashboard reads: the records of the CLI's own tracer, in the same shape. */
3323
+ type TelemetryRecord = SpanStartRecord | SpanEndRecord;
3324
+ /** A span that ended, whole. */
3325
+ interface FinishedSpan {
3326
+ traceId: string;
3327
+ spanId: string;
3328
+ parentSpanId?: string;
3329
+ name: string;
3330
+ kind: Tracer.SpanKind;
3331
+ startMs: number;
3332
+ endMs: number;
3333
+ status: "unset" | "error";
3334
+ statusMessage?: string;
3335
+ attributes: SpanAttributes;
3336
+ events: SpanEventRecord[];
3337
+ }
3338
+ /**
3339
+ * The spans of this process, in memory: the finished ones (the newest 10,000)
3340
+ * for whoever reads them, and a feed of start and end records for a dashboard.
3341
+ */
3342
+ declare class SpanStore {
3343
+ #private;
3344
+ /** The finished spans, oldest first. */
3345
+ spans(): readonly FinishedSpan[];
3346
+ clear(): void;
3347
+ /** Call `listener` with each record as it happens. Returns the function that stops it. */
3348
+ subscribe(listener: (records: TelemetryRecord[]) => void): () => void;
3349
+ /** @internal */
3350
+ start(record: SpanStartRecord): void;
3351
+ /** @internal */
3352
+ finish(span: FinishedSpan): void;
3353
+ }
3354
+ /** Shared through `globalThis`, because the CLI and the app may each hold their own copy of Brick. */
3355
+ declare const spanStore: SpanStore;
3356
+ declare const Telemetry_base: Context.ServiceClass<Telemetry, "@brickkit/effect/Telemetry", SpanStore>;
3357
+ /** Provided when the app has `telemetry`: what the stages check before they add a span. */
3358
+ declare class Telemetry extends Telemetry_base {}
3359
+ /**
3360
+ * Turns the app's tracing on: its tracer, the span store, and SQL statements
3361
+ * named `SQL <OPERATION>` with `db.system`, `db.operation` and `db.statement`.
3362
+ */
3363
+ declare const telemetryLayer: Layer.Layer<Telemetry>;
3364
+ /** Where `brick({ telemetry: { otlp } })` sends spans, over OTLP/HTTP as JSON. */
3365
+ interface OtlpOptions {
3366
+ /** The traces endpoint, such as `http://localhost:4318/v1/traces`. */
3367
+ url: string;
3368
+ /** Request headers, such as an API key. */
3369
+ headers?: Record<string, string>;
3370
+ /** Names the service in the backend. */
3371
+ resource?: {
3372
+ serviceName?: string;
3373
+ serviceVersion?: string;
3374
+ attributes?: Record<string, unknown>;
3375
+ };
3376
+ /** How often a batch is sent, as a Duration (default `"5 seconds"`). */
3377
+ exportInterval?: Parameters<typeof OtlpTracer.layer>[0]["exportInterval"];
3378
+ }
3379
+ /** The `telemetry` option's object form. */
3380
+ interface TelemetryOptions {
3381
+ /**
3382
+ * Also export spans over OTLP/HTTP (JSON). An object names the endpoint; `true`
3383
+ * reads the standard `OTEL_EXPORTER_OTLP_ENDPOINT` (or `_TRACES_ENDPOINT`),
3384
+ * `OTEL_EXPORTER_OTLP_HEADERS` and `OTEL_SDK_DISABLED`, and exports only when
3385
+ * `OTEL_TRACES_EXPORTER=otlp`, an endpoint and `OTEL_SERVICE_NAME` are all
3386
+ * set. Spans still go to Brick's store too.
3387
+ */
3388
+ otlp?: true | OtlpOptions;
3389
+ }
3390
+ /**
3391
+ * Wrap a raw route handler so each of its requests gets a server span in
3392
+ * Brick's span store (`spanStore`, which `brick dev` and the dashboard read).
3393
+ * For routes you serve yourself around `app.fetch`: they are outside actions
3394
+ * and endpoints, so `brick({ telemetry })` does not reach them. The span
3395
+ * continues the caller's `traceparent`.
3396
+ *
3397
+ * @param route - The route as it should read in the trace, such as `/raw/:id`.
3398
+ * @example
3399
+ * Bun.serve({ routes: { "/hook": traceRoute("/hook", (request) => new Response("ok")) } });
3400
+ */
3401
+ declare function traceRoute(route: string, handler: (request: Request) => Response | Promise<Response>): (request: Request) => Promise<Response>;
3402
+ /**
3403
+ * Run one try of a schedule as a root span, `schedule <name>`, so the SQL,
3404
+ * fetch calls and log lines of the run share its trace. Never a child of
3405
+ * whatever started the tick, such as the request that triggered it.
3406
+ */
3407
+ declare function traceScheduleRun<A, E, R>(run: {
3408
+ schedule: string;
3409
+ trigger: string;
3410
+ attempt: number;
3411
+ slot: string;
3412
+ }, effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R>;
3413
+ /** Note on the running span which webhook delivered, its event id and what became of it. Never the body or the signature. */
3414
+ declare const recordWebhook: (name: string, eventId: string | undefined, outcome: string) => Effect.Effect<void, never, never>;
3415
+ /** One finished run of a schedule, as the schedule table keeps it. */
3416
+ interface ScheduleRunRecord {
3417
+ /** The time the run was due, as an ISO timestamp. */
3418
+ slot: string;
3419
+ trigger: "schedule" | "manual";
3420
+ attempt: number;
3421
+ startedAt: string;
3422
+ finishedAt: string;
3423
+ /** `skipped`: a slot missed while no process ran, with `catchUp: "skip"`. */
3424
+ outcome: "succeeded" | "failed" | "skipped";
3425
+ error?: string;
3426
+ }
3427
+ declare function sqliteSchedules(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
3428
+ name: string;
3429
+ schema: undefined;
3430
+ columns: {
3431
+ name: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3432
+ name: string;
3433
+ tableName: string;
3434
+ dataType: "string";
3435
+ data: string;
3436
+ driverParam: string;
3437
+ notNull: true;
3438
+ hasDefault: false;
3439
+ isPrimaryKey: true;
3440
+ isAutoincrement: false;
3441
+ hasRuntimeDefault: false;
3442
+ enumValues: [string, ...string[]];
3443
+ baseColumn: never;
3444
+ identity: undefined;
3445
+ generated: undefined;
3446
+ }, {}>;
3447
+ spec: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3448
+ name: string;
3449
+ tableName: string;
3450
+ dataType: "string";
3451
+ data: string;
3452
+ driverParam: string;
3453
+ notNull: true;
3454
+ hasDefault: false;
3455
+ isPrimaryKey: false;
3456
+ isAutoincrement: false;
3457
+ hasRuntimeDefault: false;
3458
+ enumValues: [string, ...string[]];
3459
+ baseColumn: never;
3460
+ identity: undefined;
3461
+ generated: undefined;
3462
+ }, {}>;
3463
+ slot: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3464
+ name: string;
3465
+ tableName: string;
3466
+ dataType: "object date";
3467
+ data: Date;
3468
+ driverParam: number;
3469
+ notNull: true;
3470
+ hasDefault: false;
3471
+ isPrimaryKey: false;
3472
+ isAutoincrement: false;
3473
+ hasRuntimeDefault: false;
3474
+ enumValues: undefined;
3475
+ baseColumn: never;
3476
+ identity: undefined;
3477
+ generated: undefined;
3478
+ }, {}>;
3479
+ nextAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3480
+ name: string;
3481
+ tableName: string;
3482
+ dataType: "object date";
3483
+ data: Date;
3484
+ driverParam: number;
3485
+ notNull: true;
3486
+ hasDefault: false;
3487
+ isPrimaryKey: false;
3488
+ isAutoincrement: false;
3489
+ hasRuntimeDefault: false;
3490
+ enumValues: undefined;
3491
+ baseColumn: never;
3492
+ identity: undefined;
3493
+ generated: undefined;
3494
+ }, {}>;
3495
+ attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3496
+ name: string;
3497
+ tableName: string;
3498
+ dataType: "number int53";
3499
+ data: number;
3500
+ driverParam: number;
3501
+ notNull: true;
3502
+ hasDefault: true;
3503
+ isPrimaryKey: false;
3504
+ isAutoincrement: false;
3505
+ hasRuntimeDefault: false;
3506
+ enumValues: undefined;
3507
+ baseColumn: never;
3508
+ identity: undefined;
3509
+ generated: undefined;
3510
+ }, {}>;
3511
+ trigger: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3512
+ name: string;
3513
+ tableName: string;
3514
+ dataType: "string";
3515
+ data: "manual" | "schedule";
3516
+ driverParam: string;
3517
+ notNull: true;
3518
+ hasDefault: false;
3519
+ isPrimaryKey: false;
3520
+ isAutoincrement: false;
3521
+ hasRuntimeDefault: false;
3522
+ enumValues: [string, ...string[]];
3523
+ baseColumn: never;
3524
+ identity: undefined;
3525
+ generated: undefined;
3526
+ }, {}>;
3527
+ runId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3528
+ name: string;
3529
+ tableName: string;
3530
+ dataType: "string";
3531
+ data: string;
3532
+ driverParam: string;
3533
+ notNull: false;
3534
+ hasDefault: false;
3535
+ isPrimaryKey: false;
3536
+ isAutoincrement: false;
3537
+ hasRuntimeDefault: false;
3538
+ enumValues: [string, ...string[]];
3539
+ baseColumn: never;
3540
+ identity: undefined;
3541
+ generated: undefined;
3542
+ }, {}>;
3543
+ startedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3544
+ name: string;
3545
+ tableName: string;
3546
+ dataType: "object date";
3547
+ data: Date;
3548
+ driverParam: number;
3549
+ notNull: false;
3550
+ hasDefault: false;
3551
+ isPrimaryKey: false;
3552
+ isAutoincrement: false;
3553
+ hasRuntimeDefault: false;
3554
+ enumValues: undefined;
3555
+ baseColumn: never;
3556
+ identity: undefined;
3557
+ generated: undefined;
3558
+ }, {}>;
3559
+ leaseUntil: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3560
+ name: string;
3561
+ tableName: string;
3562
+ dataType: "object date";
3563
+ data: Date;
3564
+ driverParam: number;
3565
+ notNull: false;
3566
+ hasDefault: false;
3567
+ isPrimaryKey: false;
3568
+ isAutoincrement: false;
3569
+ hasRuntimeDefault: false;
3570
+ enumValues: undefined;
3571
+ baseColumn: never;
3572
+ identity: undefined;
3573
+ generated: undefined;
3574
+ }, {}>;
3575
+ lastSuccessAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3576
+ name: string;
3577
+ tableName: string;
3578
+ dataType: "object date";
3579
+ data: Date;
3580
+ driverParam: number;
3581
+ notNull: false;
3582
+ hasDefault: false;
3583
+ isPrimaryKey: false;
3584
+ isAutoincrement: false;
3585
+ hasRuntimeDefault: false;
3586
+ enumValues: undefined;
3587
+ baseColumn: never;
3588
+ identity: undefined;
3589
+ generated: undefined;
3590
+ }, {}>;
3591
+ runs: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3592
+ name: string;
3593
+ tableName: string;
3594
+ dataType: "object json";
3595
+ data: ScheduleRunRecord[];
3596
+ driverParam: string;
3597
+ notNull: true;
3598
+ hasDefault: false;
3599
+ isPrimaryKey: false;
3600
+ isAutoincrement: false;
3601
+ hasRuntimeDefault: false;
3602
+ enumValues: undefined;
3603
+ baseColumn: never;
3604
+ identity: undefined;
3605
+ generated: undefined;
3606
+ }, {}>;
3607
+ };
3608
+ dialect: 'sqlite';
3609
+ isAlias: false;
3610
+ }>;
3611
+ declare function postgresSchedules(name: string): import("drizzle-orm/pg-core").PgTableWithColumns<{
3612
+ name: string;
3613
+ schema: undefined;
3614
+ columns: {
3615
+ name: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
3616
+ name: string;
3617
+ tableName: string;
3618
+ dataType: "string";
3619
+ data: string;
3620
+ driverParam: string;
3621
+ notNull: true;
3622
+ hasDefault: false;
3623
+ isPrimaryKey: false;
3624
+ isAutoincrement: false;
3625
+ hasRuntimeDefault: false;
3626
+ enumValues: undefined;
3627
+ identity: undefined;
3628
+ generated: undefined;
3629
+ }>;
3630
+ spec: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
3631
+ name: string;
3632
+ tableName: string;
3633
+ dataType: "string";
3634
+ data: string;
3635
+ driverParam: string;
3636
+ notNull: true;
3637
+ hasDefault: false;
3638
+ isPrimaryKey: false;
3639
+ isAutoincrement: false;
3640
+ hasRuntimeDefault: false;
3641
+ enumValues: undefined;
3642
+ identity: undefined;
3643
+ generated: undefined;
3644
+ }>;
3645
+ slot: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>, {
3646
+ name: string;
3647
+ tableName: string;
3648
+ dataType: "object date";
3649
+ data: Date;
3650
+ driverParam: string;
3651
+ notNull: true;
3652
+ hasDefault: false;
3653
+ isPrimaryKey: false;
3654
+ isAutoincrement: false;
3655
+ hasRuntimeDefault: false;
3656
+ enumValues: undefined;
3657
+ identity: undefined;
3658
+ generated: undefined;
3659
+ }>;
3660
+ nextAt: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>, {
3661
+ name: string;
3662
+ tableName: string;
3663
+ dataType: "object date";
3664
+ data: Date;
3665
+ driverParam: string;
3666
+ notNull: true;
3667
+ hasDefault: false;
3668
+ isPrimaryKey: false;
3669
+ isAutoincrement: false;
3670
+ hasRuntimeDefault: false;
3671
+ enumValues: undefined;
3672
+ identity: undefined;
3673
+ generated: undefined;
3674
+ }>;
3675
+ attempts: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgIntegerBuilder>>, {
3676
+ name: string;
3677
+ tableName: string;
3678
+ dataType: "number int32";
3679
+ data: number;
3680
+ driverParam: string | number;
3681
+ notNull: true;
3682
+ hasDefault: true;
3683
+ isPrimaryKey: false;
3684
+ isAutoincrement: false;
3685
+ hasRuntimeDefault: false;
3686
+ enumValues: undefined;
3687
+ identity: undefined;
3688
+ generated: undefined;
3689
+ }>;
3690
+ trigger: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").Set$Type<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, "manual" | "schedule">>, {
3691
+ name: string;
3692
+ tableName: string;
3693
+ dataType: "string";
3694
+ data: "manual" | "schedule";
3695
+ driverParam: string;
3696
+ notNull: true;
3697
+ hasDefault: false;
3698
+ isPrimaryKey: false;
3699
+ isAutoincrement: false;
3700
+ hasRuntimeDefault: false;
3701
+ enumValues: undefined;
3702
+ identity: undefined;
3703
+ generated: undefined;
3704
+ }>;
3705
+ runId: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
3706
+ name: string;
3707
+ tableName: string;
3708
+ dataType: "string";
3709
+ data: string;
3710
+ driverParam: string;
3711
+ notNull: false;
3712
+ hasDefault: false;
3713
+ isPrimaryKey: false;
3714
+ isAutoincrement: false;
3715
+ hasRuntimeDefault: false;
3716
+ enumValues: undefined;
3717
+ identity: undefined;
3718
+ generated: undefined;
3719
+ }>;
3720
+ startedAt: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTimestampBuilder, {
3721
+ name: string;
3722
+ tableName: string;
3723
+ dataType: "object date";
3724
+ data: Date;
3725
+ driverParam: string;
3726
+ notNull: false;
3727
+ hasDefault: false;
3728
+ isPrimaryKey: false;
3729
+ isAutoincrement: false;
3730
+ hasRuntimeDefault: false;
3731
+ enumValues: undefined;
3732
+ identity: undefined;
3733
+ generated: undefined;
3734
+ }>;
3735
+ leaseUntil: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTimestampBuilder, {
3736
+ name: string;
3737
+ tableName: string;
3738
+ dataType: "object date";
3739
+ data: Date;
3740
+ driverParam: string;
3741
+ notNull: false;
3742
+ hasDefault: false;
3743
+ isPrimaryKey: false;
3744
+ isAutoincrement: false;
3745
+ hasRuntimeDefault: false;
3746
+ enumValues: undefined;
3747
+ identity: undefined;
3748
+ generated: undefined;
3749
+ }>;
3750
+ lastSuccessAt: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTimestampBuilder, {
3751
+ name: string;
3752
+ tableName: string;
3753
+ dataType: "object date";
3754
+ data: Date;
3755
+ driverParam: string;
3756
+ notNull: false;
3757
+ hasDefault: false;
3758
+ isPrimaryKey: false;
3759
+ isAutoincrement: false;
3760
+ hasRuntimeDefault: false;
3761
+ enumValues: undefined;
3762
+ identity: undefined;
3763
+ generated: undefined;
3764
+ }>;
3765
+ runs: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").Set$Type<import("drizzle-orm/pg-core").PgJsonbBuilder, ScheduleRunRecord[]>>, {
3766
+ name: string;
3767
+ tableName: string;
3768
+ dataType: "object json";
3769
+ data: ScheduleRunRecord[];
3770
+ driverParam: unknown;
3771
+ notNull: true;
3772
+ hasDefault: false;
3773
+ isPrimaryKey: false;
3774
+ isAutoincrement: false;
3775
+ hasRuntimeDefault: false;
3776
+ enumValues: undefined;
3777
+ identity: undefined;
3778
+ generated: undefined;
3779
+ }>;
3780
+ };
3781
+ dialect: 'pg';
3782
+ isAlias: false;
3783
+ }>;
3784
+ /** The schedule table of a SQLite database. */
3785
+ type SQLiteScheduleTable = ReturnType<typeof sqliteSchedules>;
3786
+ /** The schedule table of a Postgres database. */
3787
+ type PostgresScheduleTable = ReturnType<typeof postgresSchedules>;
3788
+ /** A schedule table, made by `scheduleTable`. */
3789
+ type ScheduleTable = SQLiteScheduleTable | PostgresScheduleTable;
3790
+ /**
3791
+ * The schedule table: one row per schedule, holding when it is next due, which
3792
+ * process is running it, and its last runs. Processes that share the table
3793
+ * share the schedules: each due time runs once among them, and a restart
3794
+ * picks up where the last process stopped.
3795
+ *
3796
+ * Brick does not create tables for you. Put it in the tables of one of the
3797
+ * app's databases, and your migration tool (such as drizzle-kit) creates it.
3798
+ *
3799
+ * @param engine - The database engine, `"sqlite"` or `"postgres"`.
3800
+ * @param options - `name` to call the table something other than `brick_schedules`.
3801
+ * @returns A Drizzle table.
3802
+ * @example
3803
+ * import { defineDatabase, scheduleTable } from "@brickkit/effect";
3804
+ *
3805
+ * export const schedules = scheduleTable("postgres");
3806
+ * export const database = defineDatabase({
3807
+ * postgres: process.env.DATABASE_URL!,
3808
+ * tables: { users, schedules },
3809
+ * });
3810
+ */
3811
+ declare function scheduleTable(engine: "sqlite", options?: {
3812
+ name?: string;
3813
+ }): SQLiteScheduleTable;
3814
+ declare function scheduleTable(engine: "postgres", options?: {
3815
+ name?: string;
3816
+ }): PostgresScheduleTable;
3817
+ /** A schedule as `schedules.list()` reports it. */
3818
+ interface ScheduleState {
3819
+ name: string;
3820
+ kind: "handler" | "workflow";
3821
+ cron?: string;
3822
+ timeZone?: string;
3823
+ /** The interval, in milliseconds. */
3824
+ every?: number;
3825
+ enabled: boolean;
3826
+ /** When it is next due (a retry included), as an ISO timestamp; `null` before a process first started the schedules. */
3827
+ nextRunAt: string | null;
3828
+ /** Whether a process is running it now. */
3829
+ running: boolean;
3830
+ /** Tries of the current due time so far. */
3831
+ attempts: number;
3832
+ lastSuccessAt: string | null;
3833
+ /** The last runs, newest first. */
3834
+ runs: ScheduleRunRecord[];
3835
+ }
3836
+ /** What `app.events.schedules` offers: see and trigger the app's schedules. */
3837
+ interface Scheduler {
3838
+ readonly start: Effect.Effect<void>;
3839
+ /** Stop the timer and wait for the runs in progress. */
3840
+ readonly stop: Effect.Effect<void>;
3841
+ /** Every schedule, with when it is next due and its last runs. */
3842
+ readonly list: Effect.Effect<ScheduleState[]>;
3843
+ /**
3844
+ * Make a schedule due now, as a manual run. Whichever process runs the
3845
+ * schedules picks it up; this one at once if it does. Works with
3846
+ * `enabled: false` too.
3847
+ *
3848
+ * @returns `false` when the schedule is running now, so nothing was started.
3849
+ * @throws (as a defect) When no schedule has that name.
3850
+ */
3851
+ readonly trigger: (name: string) => Effect.Effect<boolean>;
3852
+ /**
3853
+ * Run what is due now and wait for it. Retries that are not due yet are not
3854
+ * waited for. For tests and for workers driven by hand.
3855
+ *
3856
+ * @returns How many runs it started.
3857
+ */
3858
+ readonly drain: Effect.Effect<number>;
3859
+ }
3860
+ declare const OUTBOX_STATUSES: readonly ["pending", "claimed", "delivered", "dead"];
3861
+ /** What the outbox rows are in, by state. */
3862
+ type OutboxStatus = (typeof OUTBOX_STATUSES)[number];
3863
+ declare function sqliteOutbox(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
3864
+ name: string;
3865
+ schema: undefined;
3866
+ columns: {
3867
+ seq: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3868
+ name: string;
3869
+ tableName: string;
3870
+ dataType: "number int53";
3871
+ data: number;
3872
+ driverParam: number;
3873
+ notNull: true;
3874
+ hasDefault: true;
3875
+ isPrimaryKey: true;
3876
+ isAutoincrement: false;
3877
+ hasRuntimeDefault: false;
3878
+ enumValues: undefined;
3879
+ baseColumn: never;
3880
+ identity: undefined;
3881
+ generated: undefined;
3882
+ }, {}>;
3883
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3884
+ name: string;
3885
+ tableName: string;
3886
+ dataType: "string";
3887
+ data: string;
3888
+ driverParam: string;
3889
+ notNull: true;
3890
+ hasDefault: false;
3891
+ isPrimaryKey: false;
3892
+ isAutoincrement: false;
3893
+ hasRuntimeDefault: false;
3894
+ enumValues: [string, ...string[]];
3895
+ baseColumn: never;
3896
+ identity: undefined;
3897
+ generated: undefined;
3898
+ }, {}>;
3899
+ eventId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3900
+ name: string;
3901
+ tableName: string;
3902
+ dataType: "string";
3903
+ data: string;
3904
+ driverParam: string;
3905
+ notNull: true;
3906
+ hasDefault: false;
3907
+ isPrimaryKey: false;
3908
+ isAutoincrement: false;
3909
+ hasRuntimeDefault: false;
3910
+ enumValues: [string, ...string[]];
3911
+ baseColumn: never;
3912
+ identity: undefined;
3913
+ generated: undefined;
3914
+ }, {}>;
3915
+ listener: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3916
+ name: string;
3917
+ tableName: string;
3918
+ dataType: "string";
3919
+ data: string;
3920
+ driverParam: string;
3921
+ notNull: true;
3922
+ hasDefault: false;
3923
+ isPrimaryKey: false;
3924
+ isAutoincrement: false;
3925
+ hasRuntimeDefault: false;
3926
+ enumValues: [string, ...string[]];
3927
+ baseColumn: never;
3928
+ identity: undefined;
3929
+ generated: undefined;
3930
+ }, {}>;
3931
+ name: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3932
+ name: string;
3933
+ tableName: string;
3934
+ dataType: "string";
3935
+ data: string;
3936
+ driverParam: string;
3937
+ notNull: true;
3938
+ hasDefault: false;
3939
+ isPrimaryKey: false;
3940
+ isAutoincrement: false;
3941
+ hasRuntimeDefault: false;
3942
+ enumValues: [string, ...string[]];
3943
+ baseColumn: never;
3944
+ identity: undefined;
3945
+ generated: undefined;
3946
+ }, {}>;
3947
+ payload: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3948
+ name: string;
3949
+ tableName: string;
3950
+ dataType: "object json";
3951
+ data: unknown;
3952
+ driverParam: string;
3953
+ notNull: true;
3954
+ hasDefault: false;
3955
+ isPrimaryKey: false;
3956
+ isAutoincrement: false;
3957
+ hasRuntimeDefault: false;
3958
+ enumValues: undefined;
3959
+ baseColumn: never;
3960
+ identity: undefined;
3961
+ generated: undefined;
3962
+ }, {}>;
3963
+ traceId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3964
+ name: string;
3965
+ tableName: string;
3966
+ dataType: "string";
3967
+ data: string;
3968
+ driverParam: string;
3969
+ notNull: false;
3970
+ hasDefault: false;
3971
+ isPrimaryKey: false;
3972
+ isAutoincrement: false;
3973
+ hasRuntimeDefault: false;
3974
+ enumValues: [string, ...string[]];
3975
+ baseColumn: never;
3976
+ identity: undefined;
3977
+ generated: undefined;
3978
+ }, {}>;
3979
+ source: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3980
+ name: string;
3981
+ tableName: string;
3982
+ dataType: "string";
3983
+ data: string;
3984
+ driverParam: string;
3985
+ notNull: false;
3986
+ hasDefault: false;
3987
+ isPrimaryKey: false;
3988
+ isAutoincrement: false;
3989
+ hasRuntimeDefault: false;
3990
+ enumValues: [string, ...string[]];
3991
+ baseColumn: never;
3992
+ identity: undefined;
3993
+ generated: undefined;
3994
+ }, {}>;
3995
+ occurredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
3996
+ name: string;
3997
+ tableName: string;
3998
+ dataType: "object date";
3999
+ data: Date;
4000
+ driverParam: number;
4001
+ notNull: true;
4002
+ hasDefault: false;
4003
+ isPrimaryKey: false;
4004
+ isAutoincrement: false;
4005
+ hasRuntimeDefault: false;
4006
+ enumValues: undefined;
4007
+ baseColumn: never;
4008
+ identity: undefined;
4009
+ generated: undefined;
4010
+ }, {}>;
4011
+ status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
4012
+ name: string;
4013
+ tableName: string;
4014
+ dataType: "string";
4015
+ data: "claimed" | "dead" | "delivered" | "pending";
4016
+ driverParam: string;
4017
+ notNull: true;
4018
+ hasDefault: false;
4019
+ isPrimaryKey: false;
4020
+ isAutoincrement: false;
4021
+ hasRuntimeDefault: false;
4022
+ enumValues: [string, ...string[]];
4023
+ baseColumn: never;
4024
+ identity: undefined;
4025
+ generated: undefined;
4026
+ }, {}>;
4027
+ attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
4028
+ name: string;
4029
+ tableName: string;
4030
+ dataType: "number int53";
4031
+ data: number;
4032
+ driverParam: number;
4033
+ notNull: true;
4034
+ hasDefault: true;
4035
+ isPrimaryKey: false;
4036
+ isAutoincrement: false;
4037
+ hasRuntimeDefault: false;
4038
+ enumValues: undefined;
4039
+ baseColumn: never;
4040
+ identity: undefined;
4041
+ generated: undefined;
4042
+ }, {}>;
4043
+ lastError: import("drizzle-orm/sqlite-core").SQLiteColumn<{
4044
+ name: string;
4045
+ tableName: string;
4046
+ dataType: "string";
4047
+ data: string;
4048
+ driverParam: string;
4049
+ notNull: false;
4050
+ hasDefault: false;
4051
+ isPrimaryKey: false;
4052
+ isAutoincrement: false;
4053
+ hasRuntimeDefault: false;
4054
+ enumValues: [string, ...string[]];
4055
+ baseColumn: never;
4056
+ identity: undefined;
4057
+ generated: undefined;
4058
+ }, {}>;
4059
+ availableAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
4060
+ name: string;
4061
+ tableName: string;
4062
+ dataType: "object date";
4063
+ data: Date;
4064
+ driverParam: number;
4065
+ notNull: true;
4066
+ hasDefault: false;
4067
+ isPrimaryKey: false;
4068
+ isAutoincrement: false;
4069
+ hasRuntimeDefault: false;
4070
+ enumValues: undefined;
4071
+ baseColumn: never;
4072
+ identity: undefined;
4073
+ generated: undefined;
4074
+ }, {}>;
4075
+ claimedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
4076
+ name: string;
4077
+ tableName: string;
4078
+ dataType: "object date";
4079
+ data: Date;
4080
+ driverParam: number;
4081
+ notNull: false;
4082
+ hasDefault: false;
4083
+ isPrimaryKey: false;
4084
+ isAutoincrement: false;
4085
+ hasRuntimeDefault: false;
4086
+ enumValues: undefined;
4087
+ baseColumn: never;
4088
+ identity: undefined;
4089
+ generated: undefined;
4090
+ }, {}>;
4091
+ deliveredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
4092
+ name: string;
4093
+ tableName: string;
4094
+ dataType: "object date";
4095
+ data: Date;
4096
+ driverParam: number;
4097
+ notNull: false;
4098
+ hasDefault: false;
4099
+ isPrimaryKey: false;
4100
+ isAutoincrement: false;
4101
+ hasRuntimeDefault: false;
4102
+ enumValues: undefined;
4103
+ baseColumn: never;
4104
+ identity: undefined;
4105
+ generated: undefined;
4106
+ }, {}>;
4107
+ };
4108
+ dialect: 'sqlite';
4109
+ isAlias: false;
4110
+ }>;
4111
+ declare function postgresOutbox(name: string): import("drizzle-orm/pg-core").PgTableWithColumns<{
4112
+ name: string;
4113
+ schema: undefined;
4114
+ columns: {
4115
+ seq: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgBigSerial53Builder>, {
4116
+ name: string;
4117
+ tableName: string;
4118
+ dataType: "number int53";
4119
+ data: number;
4120
+ driverParam: number;
4121
+ notNull: true;
4122
+ hasDefault: true;
4123
+ isPrimaryKey: false;
4124
+ isAutoincrement: false;
4125
+ hasRuntimeDefault: false;
4126
+ enumValues: undefined;
4127
+ identity: undefined;
4128
+ generated: undefined;
4129
+ }>;
4130
+ id: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
4131
+ name: string;
4132
+ tableName: string;
4133
+ dataType: "string";
4134
+ data: string;
4135
+ driverParam: string;
4136
+ notNull: true;
4137
+ hasDefault: false;
4138
+ isPrimaryKey: false;
4139
+ isAutoincrement: false;
4140
+ hasRuntimeDefault: false;
4141
+ enumValues: undefined;
4142
+ identity: undefined;
4143
+ generated: undefined;
4144
+ }>;
4145
+ eventId: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
4146
+ name: string;
4147
+ tableName: string;
4148
+ dataType: "string";
4149
+ data: string;
4150
+ driverParam: string;
4151
+ notNull: true;
4152
+ hasDefault: false;
4153
+ isPrimaryKey: false;
4154
+ isAutoincrement: false;
4155
+ hasRuntimeDefault: false;
4156
+ enumValues: undefined;
4157
+ identity: undefined;
4158
+ generated: undefined;
4159
+ }>;
4160
+ listener: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
4161
+ name: string;
4162
+ tableName: string;
4163
+ dataType: "string";
4164
+ data: string;
4165
+ driverParam: string;
4166
+ notNull: true;
4167
+ hasDefault: false;
4168
+ isPrimaryKey: false;
4169
+ isAutoincrement: false;
4170
+ hasRuntimeDefault: false;
4171
+ enumValues: undefined;
4172
+ identity: undefined;
4173
+ generated: undefined;
4174
+ }>;
4175
+ name: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
4176
+ name: string;
4177
+ tableName: string;
4178
+ dataType: "string";
4179
+ data: string;
4180
+ driverParam: string;
4181
+ notNull: true;
4182
+ hasDefault: false;
4183
+ isPrimaryKey: false;
4184
+ isAutoincrement: false;
4185
+ hasRuntimeDefault: false;
4186
+ enumValues: undefined;
4187
+ identity: undefined;
4188
+ generated: undefined;
4189
+ }>;
4190
+ payload: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgJsonbBuilder>, {
4191
+ name: string;
4192
+ tableName: string;
4193
+ dataType: "object json";
4194
+ data: unknown;
4195
+ driverParam: unknown;
4196
+ notNull: true;
4197
+ hasDefault: false;
4198
+ isPrimaryKey: false;
4199
+ isAutoincrement: false;
4200
+ hasRuntimeDefault: false;
4201
+ enumValues: undefined;
4202
+ identity: undefined;
4203
+ generated: undefined;
4204
+ }>;
4205
+ traceId: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
4206
+ name: string;
4207
+ tableName: string;
4208
+ dataType: "string";
4209
+ data: string;
4210
+ driverParam: string;
4211
+ notNull: false;
4212
+ hasDefault: false;
4213
+ isPrimaryKey: false;
4214
+ isAutoincrement: false;
4215
+ hasRuntimeDefault: false;
4216
+ enumValues: undefined;
4217
+ identity: undefined;
4218
+ generated: undefined;
4219
+ }>;
4220
+ source: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
4221
+ name: string;
4222
+ tableName: string;
4223
+ dataType: "string";
4224
+ data: string;
4225
+ driverParam: string;
4226
+ notNull: false;
4227
+ hasDefault: false;
4228
+ isPrimaryKey: false;
4229
+ isAutoincrement: false;
4230
+ hasRuntimeDefault: false;
4231
+ enumValues: undefined;
4232
+ identity: undefined;
4233
+ generated: undefined;
4234
+ }>;
4235
+ occurredAt: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>, {
4236
+ name: string;
4237
+ tableName: string;
4238
+ dataType: "object date";
4239
+ data: Date;
4240
+ driverParam: string;
4241
+ notNull: true;
4242
+ hasDefault: false;
4243
+ isPrimaryKey: false;
4244
+ isAutoincrement: false;
4245
+ hasRuntimeDefault: false;
4246
+ enumValues: undefined;
4247
+ identity: undefined;
4248
+ generated: undefined;
4249
+ }>;
4250
+ status: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").Set$Type<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, "claimed" | "dead" | "delivered" | "pending">>, {
4251
+ name: string;
4252
+ tableName: string;
4253
+ dataType: "string";
4254
+ data: "claimed" | "dead" | "delivered" | "pending";
4255
+ driverParam: string;
4256
+ notNull: true;
4257
+ hasDefault: false;
4258
+ isPrimaryKey: false;
4259
+ isAutoincrement: false;
4260
+ hasRuntimeDefault: false;
4261
+ enumValues: undefined;
4262
+ identity: undefined;
4263
+ generated: undefined;
4264
+ }>;
4265
+ attempts: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgIntegerBuilder>>, {
4266
+ name: string;
4267
+ tableName: string;
4268
+ dataType: "number int32";
4269
+ data: number;
4270
+ driverParam: string | number;
4271
+ notNull: true;
4272
+ hasDefault: true;
4273
+ isPrimaryKey: false;
4274
+ isAutoincrement: false;
4275
+ hasRuntimeDefault: false;
4276
+ enumValues: undefined;
4277
+ identity: undefined;
4278
+ generated: undefined;
4279
+ }>;
4280
+ lastError: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
4281
+ name: string;
4282
+ tableName: string;
4283
+ dataType: "string";
4284
+ data: string;
4285
+ driverParam: string;
4286
+ notNull: false;
4287
+ hasDefault: false;
4288
+ isPrimaryKey: false;
4289
+ isAutoincrement: false;
4290
+ hasRuntimeDefault: false;
4291
+ enumValues: undefined;
4292
+ identity: undefined;
4293
+ generated: undefined;
4294
+ }>;
4295
+ availableAt: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>, {
4296
+ name: string;
4297
+ tableName: string;
4298
+ dataType: "object date";
4299
+ data: Date;
4300
+ driverParam: string;
4301
+ notNull: true;
4302
+ hasDefault: false;
4303
+ isPrimaryKey: false;
4304
+ isAutoincrement: false;
4305
+ hasRuntimeDefault: false;
4306
+ enumValues: undefined;
4307
+ identity: undefined;
4308
+ generated: undefined;
4309
+ }>;
4310
+ claimedAt: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTimestampBuilder, {
4311
+ name: string;
4312
+ tableName: string;
4313
+ dataType: "object date";
4314
+ data: Date;
4315
+ driverParam: string;
4316
+ notNull: false;
4317
+ hasDefault: false;
4318
+ isPrimaryKey: false;
4319
+ isAutoincrement: false;
4320
+ hasRuntimeDefault: false;
4321
+ enumValues: undefined;
4322
+ identity: undefined;
4323
+ generated: undefined;
4324
+ }>;
4325
+ deliveredAt: import("drizzle-orm/pg-core").PgBuildColumn<string, import("drizzle-orm/pg-core").PgTimestampBuilder, {
4326
+ name: string;
4327
+ tableName: string;
4328
+ dataType: "object date";
4329
+ data: Date;
4330
+ driverParam: string;
4331
+ notNull: false;
4332
+ hasDefault: false;
4333
+ isPrimaryKey: false;
4334
+ isAutoincrement: false;
4335
+ hasRuntimeDefault: false;
4336
+ enumValues: undefined;
4337
+ identity: undefined;
4338
+ generated: undefined;
4339
+ }>;
4340
+ };
4341
+ dialect: 'pg';
4342
+ isAlias: false;
4343
+ }>;
4344
+ /** The outbox table of a SQLite database. */
4345
+ type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;
4346
+ /** The outbox table of a Postgres database. */
4347
+ type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;
4348
+ /** An outbox table, made by `outboxTable`. */
4349
+ type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;
4350
+ /**
4351
+ * The outbox table: where recorded events wait, one row per listener, until they
4352
+ * are delivered. A write and the events it causes are inserted in one transaction,
4353
+ * so an event is neither lost when the process dies after the write nor sent for a
4354
+ * write that was rolled back.
4355
+ *
4356
+ * Brick does not create tables for you. Put this in the tables of the database
4357
+ * whose writes emit events, and your migration tool (such as drizzle-kit) creates
4358
+ * it. A service whose database holds the table records events; one without it does
4359
+ * not.
4360
+ *
4361
+ * @param engine - The database engine, `"sqlite"` or `"postgres"`.
4362
+ * @param options - `name` to call the table something other than `brick_outbox`.
4363
+ * @returns A Drizzle table.
4364
+ * @example
4365
+ * import { defineDatabase, outboxTable } from "@brickkit/effect";
4366
+ *
4367
+ * export const outbox = outboxTable("postgres");
4368
+ * export const database = defineDatabase({
4369
+ * postgres: process.env.DATABASE_URL!,
4370
+ * tables: { users, outbox },
4371
+ * });
4372
+ */
4373
+ declare function outboxTable(engine: "sqlite", options?: {
4374
+ name?: string;
4375
+ }): SQLiteOutboxTable;
4376
+ declare function outboxTable(engine: "postgres", options?: {
4377
+ name?: string;
4378
+ }): PostgresOutboxTable;
4379
+ type OutboxRow = OutboxTable["$inferSelect"];
4380
+ /** How many outbox rows are in each state. */
4381
+ type OutboxCounts = Record<OutboxStatus, number>;
4382
+ /**
4383
+ * Records an event inside the transaction it was given. The event is committed
4384
+ * with the write, or not at all. A service with an event catalog records only
4385
+ * events from it, and checks their payloads; `encoded` says the payload is JSON
4386
+ * already.
4387
+ */
4388
+ type EventRecorder = (name: string, payload: unknown, options?: {
4389
+ readonly encoded?: boolean;
4390
+ }) => Effect.Effect<void>;
4391
+ /** Who and what an event is recorded for. */
4392
+ interface EventContext {
4393
+ readonly traceId?: string | undefined;
4394
+ readonly source?: string | undefined;
4395
+ /** The service whose catalog checks the event. Defaults to the one that owns the database. */
4396
+ readonly service?: EventChecker | undefined;
4397
+ }
4398
+ /**
4399
+ * The events of a running app: who listens, where events are recorded, and the
4400
+ * dispatchers that deliver them. It is the `Events` service of the app's
4401
+ * runtime, which `emitEvent` and CRUD writes record through.
4402
+ */
4403
+ interface EventsHub {
4404
+ /** Whether any listener wants the event, so a write can skip recording one. */
4405
+ readonly wants: (name: string) => boolean;
4406
+ /** Whether `db` is the database of a service with an outbox table. */
4407
+ readonly records: (db: unknown) => boolean;
4408
+ /**
4409
+ * Run `fn` in a database transaction on `db`. Events it records are committed
4410
+ * with whatever else it wrote, or not at all, and delivered after the commit.
4411
+ * Inside an open transaction it joins that one, and delivery follows the
4412
+ * outer commit.
4413
+ */
4414
+ readonly transaction: <A, E, R>(db: unknown, context: EventContext, fn: (tx: any, record: EventRecorder) => Effect.Effect<A, E, R>) => Effect.Effect<A, E | unknown, R>;
4415
+ readonly start: Effect.Effect<void>;
4416
+ readonly stop: Effect.Effect<void>;
4417
+ readonly drain: Effect.Effect<number>;
4418
+ readonly counts: Effect.Effect<OutboxCounts>;
4419
+ readonly retryDead: (deliveryId?: string) => Effect.Effect<number>;
4420
+ readonly scheduler: Scheduler | undefined;
4421
+ }
4422
+ declare const Events_base: Context.ServiceClass<Events, "@brickkit/effect/Events", EventsHub>;
4423
+ /** The events of the app, as an Effect service. */
4424
+ declare class Events extends Events_base {}
4425
+ /**
4426
+ * Stop every events hub started in this process, by any copy of Brick, and
4427
+ * wait for their deliveries. A hub that fails to stop does not cut the wait for
4428
+ * the others: the first failure is thrown once every hub is done.
4429
+ */
4430
+ declare function stopAllEvents(): Promise<void>;
4431
+ /**
4432
+ * What an app's `events` option describes, as plain data. It goes in the app
4433
+ * definition, which is sent to the dev dashboard, so it holds no functions.
4434
+ */
4435
+ interface EventsDefinition {
4436
+ listeners: {
4437
+ name: string;
4438
+ on: string[];
4439
+ kind: "handler" | "workflow";
4440
+ }[];
4441
+ dispatch: boolean;
4442
+ /** Names of the services whose writes record events. */
4443
+ recorders: string[];
4444
+ /** The app's schedules; absent when it has none. */
4445
+ schedules?: {
4446
+ name: string;
4447
+ kind: "handler" | "workflow";
4448
+ cron?: string;
4449
+ timeZone?: string;
4450
+ every?: number;
4451
+ enabled: boolean;
4452
+ }[];
4453
+ }
4454
+ /** What `app.events.schedules` offers: see and trigger the app's schedules. */
4455
+ interface ScheduleControl {
4456
+ /** Every schedule, with when it is next due and its last runs. */
4457
+ list(): Promise<ScheduleState[]>;
4458
+ /**
4459
+ * Run a schedule now, once, in whichever process runs the schedules. It
4460
+ * works with `enabled: false` too.
4461
+ *
4462
+ * @returns `false` when the schedule is running now, so nothing was started.
4463
+ * @throws When no schedule has that name.
4464
+ */
4465
+ trigger(name: string): Promise<boolean>;
4466
+ /** Run what is due now, and wait for it. For tests and workers driven by hand. @returns How many runs started. */
4467
+ drain(): Promise<number>;
4468
+ }
4469
+ /** `app.events`: the hub, as Promises on the app's runtime. */
4470
+ interface AppEvents {
4471
+ /**
4472
+ * Start delivering recorded events and running schedules from this process.
4473
+ * Does nothing if this process only records events (`dispatch: false`),
4474
+ * already started, or a stop is still waiting.
4475
+ */
4476
+ start(): Promise<void>;
4477
+ /** Stop delivering, and wait for the deliveries and runs that are going on. */
4478
+ stop(): Promise<void>;
4479
+ /**
4480
+ * Deliver everything that is due now and wait for it. For tests and for
4481
+ * workers that drive delivery themselves.
4482
+ *
4483
+ * @returns How many deliveries ran.
4484
+ */
4485
+ drain(): Promise<number>;
4486
+ /** How many rows are in each state, across the app's outbox tables. */
4487
+ counts(): Promise<OutboxCounts>;
4488
+ /**
4489
+ * Put parked deliveries back in line.
4490
+ *
4491
+ * @param deliveryId - One delivery. Omit it to retry every dead one.
4492
+ * @returns How many deliveries were put back.
4493
+ */
4494
+ retryDead(deliveryId?: string): Promise<number>;
4495
+ /** The app's schedules, when it has any. Running them follows `start()` and `stop()`. */
4496
+ readonly schedules: ScheduleControl | undefined;
4497
+ /** The listeners and settings of `events`, as plain data: what `app.definition.events` holds. */
4498
+ describe(): EventsDefinition;
4499
+ }
4500
+ /** The table the database-backed workflow engine keeps its state in. It creates it when missing. */
4501
+ declare const WORKFLOW_TABLE = "brick_workflow_state";
4502
+ /** What `workflowEngine` takes besides the database. */
4503
+ interface WorkflowEngineOptions {
4504
+ /**
4505
+ * How long finished runs are kept, and how often the sweep that deletes the
4506
+ * older ones runs. `false` keeps them for ever. A run's activity results,
4507
+ * deferreds and clocks go with it. Defaults: `doneDays` 7, `failedDays` 30,
4508
+ * `intervalMs` one hour.
4509
+ */
4510
+ readonly retention?: false | {
4511
+ readonly doneDays?: number;
4512
+ readonly failedDays?: number;
4513
+ readonly intervalMs?: number;
4514
+ };
4515
+ /**
4516
+ * How long a process holds the runs it started, in milliseconds. It renews
4517
+ * them every third of this while it lives; the runs of a process that died are
4518
+ * taken by another once this has passed. Default 30000. Keep it far above the
4519
+ * clock difference between your processes.
4520
+ */
4521
+ readonly leaseMs?: number;
4522
+ }
4523
+ /**
4524
+ * A workflow engine that keeps its state in the app's database, so a run
4525
+ * survives a restart. It runs workflows as the in-memory engine of
4526
+ * `effect/workflow` does, and writes through what a restart needs:
4527
+ *
4528
+ * - each execution with its payload, until it finishes, and then its result;
4529
+ * - the result of each activity attempt that finished;
4530
+ * - each durable deferred that completed;
4531
+ * - the wake time of each durable clock.
4532
+ *
4533
+ * A run ends `done`, or `failed` when it fails (its handler fails or dies, or an
4534
+ * activity's retries run out and the failure escapes). The `status` column and
4535
+ * the run's value hold which, and the cause.
4536
+ *
4537
+ * One process runs a run at a time. A process takes a run by writing its own
4538
+ * `owner` and a `lease_until` on it, and renews that while the run lives; other
4539
+ * processes leave it alone. When a workflow registers (its `toLayer`), and then
4540
+ * on every renewal, the process takes the unfinished runs of its workflows that
4541
+ * nobody holds: ones a process released when it stopped, or whose lease ran out
4542
+ * because it died. They replay, reading the saved results, so an activity that
4543
+ * finished does not run twice; a durable clock sleeps only what was left. Run
4544
+ * workflows only in the processes that should run them: a process that does not
4545
+ * register a workflow never takes its runs.
4546
+ *
4547
+ * Finished runs are deleted by a periodic sweep: see `retention`.
4548
+ *
4549
+ * It creates the `brick_workflow_state` table on first use, and adds the columns
4550
+ * it needs to one an older version made. Put it in the app's `layer`, with the
4551
+ * workflows' `toLayer` layers provided by it.
4552
+ *
4553
+ * @example
4554
+ * const engine = workflowEngine(database, { retention: { doneDays: 3 } });
4555
+ * brick({ services, layer: Layer.mergeAll(engine, Layer.provide(OrderFlow.toLayer(run), engine)) });
4556
+ */
4557
+ declare function workflowEngine(database: AnyDatabaseHandle, options?: WorkflowEngineOptions): Layer.Layer<WorkflowEngine$1.WorkflowEngine, SqlError>;
4558
+ /**
4559
+ * What the dashboard's Workflows view reads of a Workflow SDK `World`, made from
4560
+ * `workflowEngine`'s state. Read-only: the view lists runs, shows one with its
4561
+ * steps (an activity attempt is a step) and its events, and follows it as it
4562
+ * goes. Cancelling, replaying and waking a run, and hooks and streams, are not
4563
+ * offered, so those are empty or refused.
4564
+ */
4565
+ interface WorkflowWorld {
4566
+ readonly runs: {
4567
+ list(options?: ListOptions & {
4568
+ workflowName?: string;
4569
+ status?: string;
4570
+ }): Promise<Page<Run>>;
4571
+ get(runId: string, options?: Resolve): Promise<Run>;
4572
+ };
4573
+ readonly steps: {
4574
+ get(runId: string, stepId: string, options?: Resolve): Promise<Step>;
4575
+ };
4576
+ readonly events: {
4577
+ list(options: ListOptions & {
4578
+ runId: string;
4579
+ }): Promise<Page<WorldEvent>>;
4580
+ get(runId: string, eventId: string, options?: Resolve): Promise<WorldEvent>;
4581
+ listByCorrelationId(options: ListOptions & {
4582
+ correlationId: string;
4583
+ runId?: string;
4584
+ }): Promise<Page<WorldEvent>>;
4585
+ };
4586
+ readonly hooks: {
4587
+ list(options?: ListOptions): Promise<Page<never>>;
4588
+ get(hookId: string): Promise<never>;
4589
+ };
4590
+ readonly streams: {
4591
+ list(runId: string): Promise<string[]>;
4592
+ getChunks(runId: string, name: string): Promise<Page<never> & {
4593
+ done: true;
4594
+ }>;
4595
+ };
4596
+ }
4597
+ interface Resolve {
4598
+ resolveData?: "none" | "all";
4599
+ }
4600
+ interface ListOptions extends Resolve {
4601
+ pagination?: {
4602
+ cursor?: string;
4603
+ limit?: number;
4604
+ sortOrder?: "asc" | "desc";
4605
+ };
4606
+ }
4607
+ interface Page<T> {
4608
+ data: T[];
4609
+ cursor: string | null;
4610
+ hasMore: boolean;
4611
+ }
4612
+ type Status = "running" | "completed" | "failed";
4613
+ interface Run {
4614
+ runId: string;
4615
+ status: Status;
4616
+ deploymentId: string;
4617
+ workflowName: string;
4618
+ input?: unknown;
4619
+ output?: unknown;
4620
+ error?: unknown;
4621
+ attributes: Record<string, string>;
4622
+ createdAt: Date;
4623
+ updatedAt: Date;
4624
+ startedAt: Date;
4625
+ completedAt?: Date;
4626
+ }
4627
+ interface Step {
4628
+ runId: string;
4629
+ stepId: string;
4630
+ stepName: string;
4631
+ status: "completed" | "failed";
4632
+ output?: unknown;
4633
+ error?: unknown;
4634
+ attempt: number;
4635
+ createdAt: Date;
4636
+ updatedAt: Date;
4637
+ startedAt: Date;
4638
+ completedAt: Date;
4639
+ }
4640
+ interface WorldEvent {
4641
+ eventId: string;
4642
+ runId: string;
4643
+ eventType: string;
4644
+ correlationId?: string;
4645
+ eventData?: Record<string, unknown>;
4646
+ createdAt: Date;
4647
+ }
4648
+ interface BrickOptions {
4649
+ /** The services to serve. Default: every service `defineService` registered, from the global registry. */
4650
+ services?: readonly AnyService[];
4651
+ /**
4652
+ * The Effect layer that provides the services the callbacks use. It is built
4653
+ * with the services' databases, once, on the first request, and released when the app stops.
4654
+ */
4655
+ layer?: Layer.Layer<never, any, never>;
4656
+ /** The route prefix of actions (default `/api`). */
4657
+ prefix?: string;
4658
+ /** `title`, `version` and `description` go in the OpenAPI document. */
4659
+ title?: string;
4660
+ version?: string;
4661
+ description?: string;
4662
+ /** Serve the OpenAPI document, Scalar and Swagger UI (default true). */
4663
+ docs?: boolean;
4664
+ /** Where the OpenAPI document is served (default `/openapi.json`). */
4665
+ openApiPath?: string;
4666
+ /** Where the Scalar page is served (default `/docs`). */
4667
+ docsPath?: string;
4668
+ /** Where the Swagger UI page is served (default `/swagger`). */
4669
+ swaggerPath?: string;
4670
+ /**
4671
+ * `true` serves a Scalar page at `/reference`. Options serve one only with a
4672
+ * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.
4673
+ */
4674
+ reference?: boolean | ReferenceOptions;
4675
+ /**
4676
+ * Developer documentation for the `brick dev` dashboard (its Docs tab): a
4677
+ * folder of `.md`/`.mdx` pages. A string is the folder. It is kept in
4678
+ * `app.definition` for the dashboard to read.
4679
+ */
4680
+ documentation?: string | DocumentationOptions;
4681
+ /** Raw endpoints (plain routes, not actions), mounted at startup. `app.endpoint()` adds more later. */
4682
+ endpoints?: readonly EndpointDefinition[];
4683
+ /**
4684
+ * CORS for browser callers on other origins. `true` allows the app's own
4685
+ * origin; a string, list or predicate names the allowed origins, compared
4686
+ * exactly. `{ origin, credentials }` adds `credentials: true` for cookies.
4687
+ * Other origins get no `Access-Control-Allow-Origin`. Preflights are answered.
4688
+ */
4689
+ cors?: false | CorsOptions;
4690
+ /**
4691
+ * Runs on every response the app sends, last, after the CORS headers: its
4692
+ * own routes, `/_health`, docs, errors, preflights and what plugin middleware
4693
+ * answers. Change `headers` to add, replace or remove a header (security
4694
+ * headers, say). A failure in it is logged and the response goes out as it was.
4695
+ *
4696
+ * @example
4697
+ * onResponse: ({ headers }) => Effect.sync(() => headers.set("x-frame-options", "DENY"))
4698
+ */
4699
+ onResponse?: OnResponse;
4700
+ /**
4701
+ * Runs when a request ends in a 5xx Brick built from a defect or a failure,
4702
+ * to report it. The response keeps its hidden message; succeed with a
4703
+ * `Response` to send that one instead (it keeps `x-trace-id` and
4704
+ * `x-request-id` unless it sets them). A failure in it is logged and the
4705
+ * response goes out as it was. A 5xx a handler returned itself has no error
4706
+ * and does not run it.
4707
+ *
4708
+ * @example
4709
+ * onError: ({ error }) => Effect.sync(() => report(error))
4710
+ */
4711
+ onError?: OnError;
4712
+ /** Log `METHOD /path → status (Nms)` per request (default true). */
4713
+ requestLogging?: boolean | RequestLoggingOptions;
4714
+ /**
4715
+ * Listeners, schedules and delivery. Events are recorded in the same
4716
+ * transaction as the writes that cause them once a service's database holds
4717
+ * an `outboxTable()`.
4718
+ */
4719
+ events?: EventsOptions;
4720
+ /**
4721
+ * Where the client address of a request comes from, for `rateLimit` per
4722
+ * `"ip"`: the socket peer (what `listen` knows) by default. Behind a proxy,
4723
+ * read the header the proxy sets, and only after checking the request came
4724
+ * from it. It must not be async.
4725
+ *
4726
+ * @example
4727
+ * clientIp: ({ request, peer }) => request.headers.get("x-real-ip") ?? peer
4728
+ */
4729
+ clientIp?: ClientIp;
4730
+ /** Where the services' sockets deliver: a broker to reach other processes, and the secret that signs replay sequences. `listen` serves the sockets. */
4731
+ sockets?: SocketsOptions;
4732
+ /**
4733
+ * How long `app.drain()` waits for open raw sockets to close, before it
4734
+ * closes them with 1001 (default 30 000). `stop()` and `shutdown()` drain
4735
+ * first. Brick `brick.v1` sockets are not drained: they close when the
4736
+ * server stops.
4737
+ */
4738
+ drainTimeoutMs?: number;
4739
+ /**
4740
+ * The key-value storage of the app, from `defineStorage`: where `rateLimit`
4741
+ * and webhook replay count, for the services that have no `storage` of their own.
4742
+ * The app closes it when it stops.
4743
+ */
4744
+ storage?: KeyValueStorage;
4745
+ /**
4746
+ * App-wide plugins from `definePlugin`, in install order: their `app` part
4747
+ * adds start/stop lifecycle and middleware. Plugins installed with
4748
+ * `service.use()` or `resource.use()` run their `app` part too.
4749
+ */
4750
+ plugins?: readonly PluginInstance<any, any>[];
4751
+ /**
4752
+ * Record a span for each request, action, outbound `fetch` and SQL
4753
+ * statement (default false). `brick dev` and the dashboard read them from
4754
+ * `spanStore`.
4755
+ */
4756
+ telemetry?: boolean | TelemetryOptions;
4757
+ /**
4758
+ * Monitoring dashboard for `brick start`, on a port of its own and behind
4759
+ * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.
4760
+ */
4761
+ dashboard?: DashboardOptions;
4762
+ /** Where `defineSecret` reads from, and whether to check every secret at startup (default true). */
4763
+ secrets?: {
4764
+ source?: SecretSource;
4765
+ validate?: boolean;
4766
+ };
4767
+ }
4768
+ interface ListeningServer {
4769
+ readonly port: number | undefined;
4770
+ readonly url: URL;
4771
+ }
4772
+ /** The app `brick` returns: a fetch handler, a server, and a description of what it serves. */
4773
+ interface BrickApp {
4774
+ /** A plain fetch handler: `Bun.serve({ fetch: app.fetch })`. */
4775
+ readonly fetch: (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
4776
+ /** `fetch` under the name `@brickkit/core`'s app has. */
4777
+ readonly handle: (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
4778
+ /**
4779
+ * Serve over HTTP with `Bun.serve`. Requests wait for the plugins to start;
4780
+ * if one fails, the failure is logged and the server stops.
4781
+ */
4782
+ listen(port: number): ListeningServer;
4783
+ /** Start the plugins, in install order, once. A failed start stops those before it and rejects. */
4784
+ start(): Promise<void>;
4785
+ /**
4786
+ * Drain, then stop the server, then the plugins in reverse order, then
4787
+ * release the layer and the databases. `force` skips the drain and closes
4788
+ * every connection at once.
4789
+ */
4790
+ stop(force?: boolean): Promise<void>;
4791
+ /**
4792
+ * Stop accepting raw socket upgrades (503) and wait until the open ones close,
4793
+ * then close what is left with 1001. Other routes keep serving. Resolves at
4794
+ * once without raw sockets. Shared: later calls return the first one's
4795
+ * promise. `stop()` and `shutdown()` call it unless `force` is true.
4796
+ * `timeoutMs` defaults to `drainTimeoutMs`.
4797
+ */
4798
+ drain(timeoutMs?: number): Promise<void>;
4799
+ /** The raw socket routes of this app: connections open now and whether it is draining. */
4800
+ rawSockets(): RawSocketStats;
4801
+ /** Drive delivery by hand: `drain()`, `start()`, `stop()`. `undefined` without the `events` option. */
4802
+ readonly events: AppEvents | undefined;
4803
+ /**
4804
+ * Run `effect` in the app's runtime, with the services its layer, databases,
4805
+ * events and storage provide: for code that runs outside a request, such as
4806
+ * a callback a library calls. Inside it `emitEvent` finds the app's events,
4807
+ * and `runInTransaction` opens a transaction that `emitEvent` joins. Works as
4808
+ * soon as the app is built, as `fetch` does, and rejects after `stop()`.
4809
+ * @example
4810
+ * const queueEmail = (to: string) =>
4811
+ * app.runPromise(
4812
+ * Effect.gen(function* () {
4813
+ * const db = yield* database.Database;
4814
+ * yield* emitEvent({ db }, "email.queued", { to });
4815
+ * }),
4816
+ * );
4817
+ */
4818
+ runPromise<A, E>(effect: Effect.Effect<A, E, any>): Promise<A>;
4819
+ /** `runPromise` for a fiber you control: interrupt it, or join it later. Throws after `stop()`. */
4820
+ runFork<A, E>(effect: Effect.Effect<A, E, any>): Fiber.Fiber<A, E>;
4821
+ /** The server `listen` or `serve` opened, until the app stops. */
4822
+ readonly server: ListeningServer | undefined;
4823
+ /** Start serving on `port`: what `brick start` and the CLI's workers call. */
4824
+ serve(options: {
4825
+ port: number;
4826
+ }): Promise<BrickApp>;
4827
+ /** Stop for good: what the CLI calls at SIGINT and SIGTERM. `force` is passed to `stop()`. */
4828
+ shutdown(force?: boolean): Promise<void>;
4829
+ /** The OpenAPI document `/openapi.json` serves (also when `docs` is false). */
4830
+ openApiDocument(): Record<string, any>;
4831
+ /** The OpenAPI documents the dashboard's APIs view shows: the app's own, when `docs` is on, and `reference.documents`. */
4832
+ referenceDocuments(): Promise<ApiDocument[]>;
4833
+ /** Register a raw endpoint (a plain route, not an action). One that a built-in route, an action or an earlier endpoint already holds is listed but not served. */
4834
+ endpoint(def: EndpointDefinition): void;
4835
+ /** Every endpoint registered, plugins' first, in declaration order. */
4836
+ listEndpoints(): EndpointDefinition[];
4837
+ /** The architecture `/_brick/services` serves: what the CLI's dashboard and `brick info` read. */
4838
+ architecture(): ArchitectureSchema;
4839
+ /** What the CLI generates the client contract from: each route and socket with the JSON Schemas of what travels. */
4840
+ clientContract(): ClientContractSource;
4841
+ /**
4842
+ * The runs of the app's `workflowEngine`, as the part of a Workflow SDK world
4843
+ * the dashboard's Workflows view reads. `undefined` when the app's layer has
4844
+ * no engine. It builds the app's layer if nothing has yet.
4845
+ */
4846
+ workflowWorld(): Promise<WorkflowWorld | undefined>;
4847
+ readonly definition: {
4848
+ readonly services: readonly AnyService[];
4849
+ readonly prefix: string;
4850
+ readonly routes: readonly RouteIR[];
4851
+ readonly documentation?: DocumentationOptions;
4852
+ /** The sockets the services declare, each at the path `listen` serves it on. */
4853
+ readonly sockets: readonly AppSocket[];
4854
+ readonly events?: EventsDefinition;
4855
+ readonly plugins: readonly InstalledPlugin[];
4856
+ /** Whether spans are recorded: `telemetry`, or a `dashboard`. */
4857
+ readonly telemetry: boolean;
4858
+ readonly dashboard: DashboardOptions | undefined;
4859
+ };
4860
+ }
4861
+ /**
4862
+ * Create the app: a fetch handler that serves every service's actions, plus
4863
+ * `/_health`, an OpenAPI document at `/openapi.json` and Scalar at `/docs`.
4864
+ * Routes, success bodies and error JSON are the same as `@brickkit/core`'s, so
4865
+ * its typed client works against it.
4866
+ *
4867
+ * @throws When two services share a name, or two actions share a URL segment.
4868
+ * @example
4869
+ * export default brick({ services: [pages], layer: Mailer.layer });
4870
+ */
4871
+ declare function brick(options?: BrickOptions): BrickApp;
4872
+ export { ApiDocument as $, DatabaseHandle as $i, WorkflowScheduleRun as $n, runStages as $r, ResourcePluginTypes as $t, FinishedSpan as A, StandardErrorCode as Aa, CallFiles as Ai, Resource as An, crudEventName as Ar, Service as At, recordWebhook as B, StorageUnavailableError as Bi, loadRecord as Bn, AnySchema as Br, isTool as Bt, OutboxStatus as C, markDashboardArrival as Ca, StorageOf as Ci, ChildChanges as Cn, WebhookConfig as Cr, getActionRoute as Ct, ScheduleRunRecord as D, DuplicateNameError as Da, redis as Di, CommandDecision as Dn, CrudEventOperation as Dr, ActionFeatures as Dt, ScheduleState as E, BrickError as Ea, memory as Ei, CommandConfig as En, isWebhook as Er, ActionAccessPolicy as Et, SpanStartRecord as F, toWireError as Fa, S3StorageOptions as Fi, ResourceConfig as Fn, ActionConfig as Fr, Tool as Ft, DASHBOARD_MCP_ROUTE as G, defineSecret as Gi, EventListener as Gn, ErrorHelpers as Gr, PluginRouteMethod as Gt, telemetryLayer as H, SecretRef as Hi, DispatchOptions as Hn, Call as Hr, InstalledPlugin as Ht, SpanStore as I, ScopedFiles as Ii, ResourceIdentity as In, ActionConfigBase as Ir, ToolAnnotations as It, DashboardOptions as J, overrideSecret as Ji, RetryDecision as Jn, HttpMethod as Jr, PluginRoutes as Jt, DASHBOARD_MCP_TOOLS as K, envSource as Ki, EventsOptions as Kn, ExecuteParams as Kr, PluginRouteRegistrar as Kt, Telemetry as L, StoredFile as Li, ResourceTypeOptions as Ln, ActionContext as Lr, ToolContext as Lt, SpanAttributes as M, ValidationIssue as Ma, FileStorage as Mi, ResourceActionConfig as Mn, defineEvents as Mr, ServiceOptions as Mt, SpanEndRecord as N, WireError as Na, LOCAL_FILES_ROUTE as Ni, ResourceActionInput as Nn, isCrudEvent as Nr, defineService as Nt, ScheduleTable as O, ErrorEnvelope as Oa, storageKey as Oi, CommandErrors as On, EventRef as Or, AnyService as Ot, SpanEventRecord as P, toErrorResponse as Pa, RawDeps as Pi, ResourceChild as Pn, Action as Pr, AnyTool as Pt, requestLoggingPlugin as Q, DatabaseConnection as Qi, ScheduleRun as Qn, Wire as Qr, ResourcePluginContext as Qt, TelemetryOptions as R, s3 as Ri, defineResource as Rn, ActionParams as Rr, ToolOptions as Rt, OutboxRow as S, dashboardUser as Sa, StorageDriver as Si, AnyResource as Sn, SocketSchemas as Sr, actionOwners as St, outboxTable as T, signDashboardMcp as Ta, frameworkStorage as Ti, CommandChildren as Tn, WebhookVerifier as Tr, ActionAccessInfo as Tt, traceRoute as U, SecretSource as Ui, EventDelivery as Un, ErrorDefinition as Ur, PLUGIN_KIND as Ut, spanStore as V, SecretOptions as Vi, CrudEventPayload as Vn, AuthorizedActionConfig as Vr, ContextOf as Vt, traceScheduleRun as W, SecretValidator as Wi, EventEnvelope as Wn, ErrorDefinitions as Wr, PluginEndpointContext as Wt, normalizeDashboard as X, resolveSecrets as Xi, Schedule as Xn, PluginActionChecks as Xr, ResourcePlugin as Xt, DashboardPeer as Y, resetSecrets as Yi, WorkflowEvent as Yn, Next as Yr, RequirementOf as Yt, RequestLoggingOptions as Z, AnyDatabaseHandle as Zi, ScheduleConfig as Zn, Stage as Zr, ResourcePluginAPI as Zt, EventsDefinition as _, DashboardMcpCaller as _a, FrameworkStorage as _i, HostHooks as _n, SocketEmitOptions as _r, ServiceSchema as _t, Activity as a, createPostgresDatabase as aa, ClientIp as ai, PluginInfo as an, RawSocketHandle as ar, EndpointContext as at, stopAllEvents as b, dashboardKey as ba, PutIfAbsentResult as bi, addHostHooks as bn, SocketReplay as br, DEFAULT_PREFIX as bt, Workflow as c, isDatabaseHandle as ca, clientAddress as ci, PluginLifecycleContext as cn, RawSocketStats as cr, ErrorHookContext as ct, workflowEngine as d, CallContext as da, PostgresAuditTable as di, PluginSetupContext as dn, BrickSocketSender as dr, ResponseHookContext as dt, DatabaseService as ea, stagesOf as ei, ServicePlugin as en, defineSchedule as er, DocumentationOptions as et, WORKFLOW_TABLE as f, Logger as fa, SQLiteAuditTable as fi, definePlugin as fn, RegisteredSocket as fr, CorsOptions as ft, Events as g, DashboardIdentity as ga, Counter as gi, HookResult as gn, SocketEmitArgs as gr, ArchitectureSchema as gt, EventRecorder as h, DASHBOARD_KEY_ENV as ha, recordAudit as hi, HOOK_NAMES as hn, SocketConfig as hr, ArchitectureApplication as ht, brick as i, SQLiteOptions as ia, redact as ii, PluginFactory as in, RawSocketFrame as ir, scalarDocsHTML as it, OtlpOptions as j, ValidationError as ja, FileDriver as ji, ResourceActionAccess as jn, crudEventSource as jr, ServiceContext as jt, scheduleTable as k, STANDARD_ERRORS as ka, CallDeps as ki, CommandRow as kn, EventRefs as kr, NoIdentity as kt, WorkflowEngine as l, timestamptzText as la, AuditOptions as li, PluginManifest as ln, SocketsOptions as lr, OnError as lt, EventContext as m, DASHBOARD_IDENTITY_HEADER as ma, isAuditTable as mi, pluginOwner as mn, SocketBrokerMessage as mr, ActionSchema as mt, BrickOptions as n, PostgresOptions as na, Sensitive as ni, PluginAppContext as nn, RawSocket as nr, ReferenceDocument as nt, DurableClock as o, createSQLiteDatabase as oa, RateLimit as oi, PluginInstallOptions as on, RawSocketMessage as or, EndpointDefinition as ot, AppEvents as p, createLogger as pa, auditTable as pi, PluginTableBuilders as pn, SocketBroker as pr, CorsOrigin as pt, DashboardAuth as q, listSecrets as qi, ListenerFailure as qn, HTTP_METHODS as qr, PluginRouteScope as qt, ListeningServer as r, SQLiteDatabaseConfig as ra, hasSensitive as ri, PluginContext as rn, RawSocketConfig as rr, ReferenceOptions as rt, DurableDeferred as s, defineDatabase as sa, RateLimits as si, PluginInstance as sn, RawSocketPhase as sr, EndpointMethod as st, BrickApp as t, PostgresDatabaseConfig as ta, Reveal as ti, ServicePluginContext as tn, CronExpression as tr, OpenApiDocument as tt, WorkflowEngineOptions as u, BaseContext as ua, AuditTable as ui, PluginServiceContext as un, BrickSocketHandle as ur, OnResponse as ut, EventsHub as v, DashboardUser as va, KeyValueDriver as vi, PluginHookArgs as vn, SocketEventArgs as vr, exportArchitecture as vt, OutboxTable as w, signDashboardIdentity as wa, defineStorage as wi, Command as wn, WebhookRequest as wr, kebabCase as wt, OutboxCounts as x, dashboardMcpCaller as xa, RedisStorageOptions as xi, getHostHooks as xn, SocketSchema as xr, RouteIR as xt, ScheduleControl as y, dashboardIdentity as ya, KeyValueStorage as yi, PluginHooks as yn, SocketPayloads as yr, ActionRoute as yt, TelemetryRecord as z, StorageError as zi, idSchema as zn, AnyAction as zr, defineTool as zt };
4873
+ //# sourceMappingURL=server-Cj74lTGa.d.ts.map