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

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