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