@brickkit/core 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,13 @@
1
1
  import { Static, TIntersect, TNumber, TObject, TSchema, TString, TUnion } from "@sinclair/typebox";
2
2
  import { Table } from "drizzle-orm";
3
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
4
  import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
6
5
  import { Sql } from "postgres";
7
6
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
8
7
  import { Database } from "bun:sqlite";
8
+ /** The HTTP methods an action, endpoint or plugin route can use. */
9
+ declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE"];
10
+ type HttpMethod = (typeof HTTP_METHODS)[number];
9
11
  declare const portType: unique symbol;
10
12
  /** A typed dependency slot, declared with `port<T>()` and filled by `brick({ deps })`. */
11
13
  interface Port<T> {
@@ -73,7 +75,15 @@ interface EventRef<TPayload = unknown> {
73
75
  }
74
76
  /** `service.events`: one `EventRef` per catalog entry. */
75
77
  type EventRefs<C extends EventCatalog> = { readonly [K in keyof C & string]: EventRef<Static<C[K]>>; };
76
- declare function isEventRef(value: unknown): value is EventRef;
78
+ /** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
79
+ declare const CRUD_EVENT_OPERATIONS: readonly ["create", "update", "delete"];
80
+ type CrudEventOperation = (typeof CRUD_EVENT_OPERATIONS)[number];
81
+ /** The event a CRUD write records: `<resource>.<operation>`. */
82
+ declare const crudEventName: (resource: string, operation: CrudEventOperation) => string;
83
+ /** The `source` of a resource's events: `<service>.<resource>`. */
84
+ declare const crudEventSource: (service: string, resource: string) => string;
85
+ /** Whether `name` is the CRUD event of one of `resources`. */
86
+ declare function isCrudEvent(name: string, resources: readonly string[]): boolean;
77
87
  /**
78
88
  * An event, as it was recorded. It is the same for every listener of it.
79
89
  */
@@ -149,12 +159,13 @@ interface EventListener<TPayload = any> {
149
159
  * retries the delivery with a growing delay. A listener has this or `workflow`.
150
160
  */
151
161
  readonly run?: (delivery: EventDelivery<TPayload>) => void | Promise<void>;
162
+ /** The typed errors a handler can fail with; `retry` receives them as a `ListenerFailure`. */
163
+ readonly errors?: Record<string, ActionErrorDefinition>;
152
164
  /**
153
165
  * Decides what a failed delivery does next. Without it, every failure retries
154
166
  * until `maxAttempts`. It cannot extend the attempts: `"retry"` still parks the
155
167
  * delivery as dead once they run out.
156
168
  */
157
- readonly errors?: Record<string, ActionErrorDefinition>;
158
169
  readonly retry?: (error: ListenerFailure<any>) => RetryDecision;
159
170
  /**
160
171
  * A durable workflow that runs for each delivery, on the app's `events.world`.
@@ -275,98 +286,49 @@ interface ServiceEvents {
275
286
  source?: string;
276
287
  }, name: string, payload: unknown): Promise<void>;
277
288
  }
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;
289
+ interface HookBase<C> {
290
+ ctx: C;
291
+ /** The write's open transaction: write other tables through it. */
292
+ tx: any;
306
293
  }
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;
294
+ /** The arguments each host CRUD hook receives, by hook name. */
295
+ interface PluginHookArgs<C = ActionContext> {
296
+ beforeCreate: HookBase<C> & {
297
+ data: Record<string, unknown>;
298
+ };
299
+ afterCreate: HookBase<C> & {
300
+ row: Record<string, unknown>;
301
+ };
302
+ beforeUpdate: HookBase<C> & {
303
+ id: unknown;
304
+ data: Record<string, unknown>;
305
+ };
306
+ afterUpdate: HookBase<C> & {
307
+ id: unknown;
308
+ row: Record<string, unknown>;
309
+ };
310
+ beforeDelete: HookBase<C> & {
311
+ id: unknown;
312
+ };
313
+ afterDelete: HookBase<C> & {
314
+ id: unknown;
315
+ };
316
+ afterCommit: {
317
+ operation: "create" | "update" | "delete";
318
+ id: unknown;
319
+ row?: Record<string, unknown>;
320
+ ctx: C;
321
+ };
336
322
  }
337
323
  /**
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.
324
+ * Subscribe to the host's CRUD writes (resources with `crud()`). `before*` and
325
+ * `after*` run inside the write's transaction, after the host's own crud hooks;
326
+ * a hook that throws rolls the write back. `afterCommit` runs after the commit.
368
327
  */
369
- declare function satisfiesRange(version: string, range: string): boolean;
328
+ type PluginHooks<C = ActionContext> = { [K in keyof PluginHookArgs<C>]: (hook: (args: PluginHookArgs<C>[K]) => unknown) => void; };
329
+ type HostHooks = { [K in keyof PluginHookArgs]?: ((args: PluginHookArgs[K]) => unknown)[]; };
330
+ /** The plugin hooks installed on a service or resource, by hook name. */
331
+ declare function getHostHooks(host: object): HostHooks | undefined;
370
332
  declare const sqliteBuilders: {
371
333
  /** A table. Its name gets the plugin's prefix (`page_comments`). */
372
334
  table: <C extends Record<string, SQLiteColumnBuilderBase>>(name: string, columns: C) => import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
@@ -512,44 +474,90 @@ type PluginTableBuilders = typeof sqliteBuilders & {
512
474
  /** The host database's engine. */
513
475
  readonly engine: "sqlite" | "postgres";
514
476
  };
515
- interface HookBase<C> {
516
- ctx: C;
517
- /** The write's open transaction: write other tables through it. */
518
- tx: any;
519
- }
520
477
  /**
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.
478
+ * Type-safe secrets & environment variables.
479
+ *
480
+ * Declare each secret once at module scope instead of scattering untyped
481
+ * `process.env.FOO` reads:
482
+ *
483
+ * const port = defineSecret("PORT").default("3333").transform(Number).require();
484
+ * const baseUrl = defineSecret("BASE_URL").url().require();
485
+ * const key = defineSecret("STRIPE_KEY").validate((v) =>
486
+ * v.startsWith("sk_") || "must start with sk_"
487
+ * ).require();
488
+ *
489
+ * Values resolve from the environment (Bun populates `process.env` from
490
+ * `.env` locally; in prod the same env source applies — a future
491
+ * `SecretSource` such as AWS can slot in without touching call sites).
492
+ *
493
+ * Resolution order per secret: test/session override → source (`process.env`
494
+ * by default) → declared `default`. `resolveSecrets()` validates every
495
+ * registered secret at boot and throws listing all missing required ones.
524
496
  */
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;
497
+ interface SecretSource {
498
+ get(name: string): string | undefined;
499
+ }
500
+ /** Default source: `process.env` (Bun loads `.env` into it automatically). */
501
+ declare const envSource: SecretSource;
502
+ interface SecretOptions {
503
+ /** Fallback when the source has no value. Secrets without a default are required. */
504
+ default?: string;
552
505
  }
506
+ /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
507
+ type SecretValidator<T> = (value: T) => void | boolean | string;
508
+ declare class SecretRef<T = string> {
509
+ readonly name: string;
510
+ readonly options: SecretOptions;
511
+ private transformFn?;
512
+ private validators;
513
+ constructor(name: string, options?: SecretOptions);
514
+ /** True when a default was declared (i.e. the secret is optional). */
515
+ get hasDefault(): boolean;
516
+ /** Fallback used when the source has no value. Makes the secret optional. */
517
+ default(value: string): this;
518
+ /**
519
+ * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
520
+ * Runs before validators; a throwing transform fails resolution.
521
+ */
522
+ transform<U>(fn: (raw: string) => U): SecretRef<U>;
523
+ /** Run a custom check on the (transformed) value at every resolution. */
524
+ validate(fn: SecretValidator<T>): this;
525
+ /** Shorthand validator: value must parse as a URL. String refs only. */
526
+ url(this: SecretRef<string>): SecretRef<string>;
527
+ private resolveRaw;
528
+ private coerce;
529
+ /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
530
+ value(source?: SecretSource): T | undefined;
531
+ /** Resolved value, or throws naming the missing/invalid secret. */
532
+ require(source?: SecretSource): T;
533
+ /** True when a value would resolve (override, source, or default). */
534
+ isSet(source?: SecretSource): boolean;
535
+ }
536
+ /**
537
+ * Declare a secret. Calling it again for the name returns the same ref. From
538
+ * the same line (a module evaluated again) it starts the declaration over, so
539
+ * its builder calls replace the earlier ones instead of adding to them.
540
+ */
541
+ declare function defineSecret(name: string, options?: SecretOptions): SecretRef<string>;
542
+ /**
543
+ * Validate every registered secret at boot. Throws a single error listing
544
+ * all missing required secrets. Returns the resolved values.
545
+ */
546
+ declare function resolveSecrets(opts?: {
547
+ source?: SecretSource;
548
+ }): Record<string, unknown>;
549
+ /** Metadata for introspection (values never exposed — future dashboard use). */
550
+ declare function listSecrets(opts?: {
551
+ source?: SecretSource;
552
+ }): Array<{
553
+ name: string;
554
+ hasDefault: boolean;
555
+ isSet: boolean;
556
+ }>;
557
+ /** Test/session override for one secret (`undefined` clears the override). */
558
+ declare function overrideSecret(name: string, value: string | undefined): void;
559
+ /** Clear registry and overrides. Test-only. */
560
+ declare function resetSecrets(): void;
553
561
  type Secrets = Record<string, SecretRef<any>>;
554
562
  type OptionsOf<O> = O extends TSchema ? Static<O> : {};
555
563
  /**
@@ -619,7 +627,7 @@ interface PluginManifest<O extends TSchema | undefined = undefined, S extends Se
619
627
  /** The npm package name, scoped: `@acme/brick-comments`. */
620
628
  name: string;
621
629
  description?: string;
622
- /** The Brick versions it supports, as a semver range: `^0.11.0`. */
630
+ /** The Brick versions it supports, as a semver range: `^0.12.0`. */
623
631
  brick?: string;
624
632
  /** Plugins that must be installed on the same host first, by name. */
625
633
  requires?: readonly string[];
@@ -702,7 +710,7 @@ type PluginFactory<O extends TSchema | undefined, RA extends object, SA, P exten
702
710
  * @example
703
711
  * export const audit = definePlugin({
704
712
  * name: "@acme/brick-audit",
705
- * brick: "^0.11.0",
713
+ * brick: "^0.12.0",
706
714
  * requires: ["@brickkit/crud"],
707
715
  * options: t.Object({ table: t.String({ default: "audit" }) }),
708
716
  * tables: ({ table, text, timestamp }) => ({
@@ -718,136 +726,9 @@ type PluginFactory<O extends TSchema | undefined, RA extends object, SA, P exten
718
726
  * page.use(audit());
719
727
  */
720
728
  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>;
729
+ declare const OUTBOX_STATUSES: readonly ["pending", "claimed", "delivered", "dead"];
849
730
  /** What the outbox rows are in, by state. */
850
- type OutboxStatus = "pending" | "claimed" | "delivered" | "dead";
731
+ type OutboxStatus = (typeof OUTBOX_STATUSES)[number];
851
732
  declare function sqliteOutbox(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
852
733
  name: string;
853
734
  schema: undefined;
@@ -1022,7 +903,7 @@ declare function sqliteOutbox(name: string): import("drizzle-orm/sqlite-core").S
1022
903
  tableName: string;
1023
904
  dataType: "string";
1024
905
  columnType: "SQLiteText";
1025
- data: OutboxStatus;
906
+ data: "claimed" | "dead" | "delivered" | "pending";
1026
907
  driverParam: string;
1027
908
  notNull: true;
1028
909
  hasDefault: false;
@@ -1035,7 +916,7 @@ declare function sqliteOutbox(name: string): import("drizzle-orm/sqlite-core").S
1035
916
  generated: undefined;
1036
917
  }, {}, {
1037
918
  length: number | undefined;
1038
- $type: OutboxStatus;
919
+ $type: "claimed" | "dead" | "delivered" | "pending";
1039
920
  }>;
1040
921
  attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1041
922
  name: "attempts";
@@ -1289,7 +1170,7 @@ declare function postgresOutbox(name: string): import("drizzle-orm/pg-core").PgT
1289
1170
  tableName: string;
1290
1171
  dataType: "string";
1291
1172
  columnType: "PgText";
1292
- data: OutboxStatus;
1173
+ data: "claimed" | "dead" | "delivered" | "pending";
1293
1174
  driverParam: string;
1294
1175
  notNull: true;
1295
1176
  hasDefault: false;
@@ -1301,7 +1182,7 @@ declare function postgresOutbox(name: string): import("drizzle-orm/pg-core").PgT
1301
1182
  identity: undefined;
1302
1183
  generated: undefined;
1303
1184
  }, {}, {
1304
- $type: OutboxStatus;
1185
+ $type: "claimed" | "dead" | "delivered" | "pending";
1305
1186
  }>;
1306
1187
  attempts: import("drizzle-orm/pg-core").PgColumn<{
1307
1188
  name: "attempts";
@@ -1427,211 +1308,56 @@ declare function outboxTable(engine: "postgres", options?: {
1427
1308
  name?: string;
1428
1309
  }): PostgresOutboxTable;
1429
1310
  /**
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.
1311
+ * What core's own modules use of a service, beyond the public `Service`. Every
1312
+ * service `defineService` makes is one.
1434
1313
  */
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;
1314
+ interface ServicePort<TDb = any, TServiceContext extends Record<string, any> = Record<string, any>> extends Service<TDb, TServiceContext> {
1315
+ /** The values of this service's `deps`. Set by `brick({ deps })`. */
1316
+ readonly deps?: Readonly<Record<string, unknown>>;
1317
+ /** Whether the service declares an event catalog. */
1318
+ readonly hasCatalog: boolean;
1319
+ setDeps(deps: Readonly<Record<string, unknown>>): void;
1320
+ /** `resolveContext`, for an action or socket a plugin install created: it sees `pluginDeps`. */
1321
+ resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>, pluginDeps?: Readonly<Record<string, unknown>>): Promise<BaseContext<TDb> & TServiceContext>;
1322
+ setRecorder(recorder: ServiceEvents | undefined): void;
1323
+ getOutbox(): OutboxTable | undefined;
1324
+ /** @throws When the event is not in the catalog or its payload does not match. */
1325
+ checkEvent(name: string, payload: unknown): void;
1326
+ /** Adds events to the catalog (a plugin's). */
1327
+ addEvents(refs: Readonly<Record<string, EventRef>>): void;
1328
+ registerTable(table: unknown): this;
1329
+ listPreparations(): PreparationContribution[];
1330
+ prepareContributions(): void;
1331
+ /** Records the declarations; the returned function puts them back (plugin rollback). */
1332
+ snapshot(): () => void;
1333
+ /** Marks the definitions changed, so cached architecture and OpenAPI are rebuilt. */
1334
+ touch(): void;
1335
+ }
1336
+ /** Set on actions declared with `resource.action(...)`. */
1337
+ interface ResourceActionInfo {
1338
+ resource: string;
1339
+ /** The declared name, without the `resource.` prefix. */
1340
+ name: string;
1341
+ record: boolean;
1342
+ /** A record action's own access rule. */
1343
+ access?: ResourceActionAccess;
1620
1344
  }
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";
1345
+ interface ActionAccessInfo {
1346
+ hasAuthorize: boolean;
1347
+ hasScope: boolean;
1348
+ policy: ActionAccessPolicy;
1349
+ }
1350
+ /** What a plugin action adds to the validation of `routes.action`. */
1351
+ interface PluginActionChecks {
1352
+ /** Checked instead of `output` at runtime, while `output` stays the published contract (client types, OpenAPI). */
1353
+ runtimeOutput?: TSchema;
1354
+ /** Runs before input validation, in-process and over HTTP; the errors it returns reject the input with a 400. */
1355
+ checkInput?: (input: unknown) => ValidationErrorItem[] | undefined;
1356
+ }
1357
+ type PluginRouteMethod = HttpMethod;
1358
+ /** Where a plugin route mounts: under the app prefix, its service, or its resource. */
1359
+ declare const PLUGIN_ROUTE_SCOPES: readonly ["app", "service", "resource"];
1360
+ type PluginRouteScope = (typeof PLUGIN_ROUTE_SCOPES)[number];
1635
1361
  type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> = false | Readonly<Record<string, false | {
1636
1362
  path?: string;
1637
1363
  scope?: S;
@@ -1650,12 +1376,12 @@ interface PluginEndpointContext<C extends ActionContext = ActionContext> {
1650
1376
  ctx: C;
1651
1377
  }
1652
1378
  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> & {
1379
+ 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> & PluginActionChecks & {
1654
1380
  path: string;
1655
1381
  method: PluginRouteMethod;
1656
1382
  scope?: S;
1657
1383
  }): 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> & {
1384
+ 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> & PluginActionChecks & {
1659
1385
  path: string;
1660
1386
  method: PluginRouteMethod;
1661
1387
  scope?: S;
@@ -1670,6 +1396,12 @@ interface PluginRouteRegistrar<C extends ActionContext = ActionContext, S extend
1670
1396
  description?: string;
1671
1397
  tags?: string[];
1672
1398
  }): void;
1399
+ /**
1400
+ * Reserve a URL segment under the resource, so no resource action takes it,
1401
+ * for a route the plugin may add later. Resource-scoped routes claim their
1402
+ * first segment themselves.
1403
+ */
1404
+ claim(segment: string): void;
1673
1405
  }
1674
1406
  interface ServicePluginContext<S extends Service<any, any> = Service<any, any>> {
1675
1407
  service: S;
@@ -1694,103 +1426,30 @@ type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
1694
1426
  readonly context: C;
1695
1427
  readonly resource: R;
1696
1428
  })["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;
1429
+ /** Which host a plugin descriptor installs on. Process-global, so descriptors survive a second core copy. */
1430
+ declare const PLUGIN_KIND: unique symbol;
1698
1431
  interface ServicePlugin<S extends Service<any, any>, A> {
1699
- readonly [pluginKind]: "service" | "plugin";
1432
+ readonly [PLUGIN_KIND]: "service" | "plugin";
1700
1433
  readonly name: string;
1701
1434
  readonly routes?: PluginRoutes<"app" | "service">;
1702
1435
  readonly setup: (context: ServicePluginContext<S>) => A;
1703
1436
  }
1704
1437
  interface ResourcePlugin<S extends Service<any, any>, R extends Resource<any, any, any>, A extends object> {
1705
- readonly [pluginKind]: "resource" | "plugin";
1438
+ readonly [PLUGIN_KIND]: "resource" | "plugin";
1706
1439
  readonly name: string;
1707
1440
  readonly routes?: PluginRoutes;
1708
1441
  readonly setup: (context: ResourcePluginContext<S, R>) => A;
1709
1442
  }
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
- }[];
1443
+ /** A plugin as `app.definition.plugins` lists it. */
1444
+ interface InstalledPlugin {
1445
+ readonly name: string;
1446
+ readonly brick?: string;
1447
+ readonly scope: "app" | "service" | "resource";
1448
+ readonly service?: string;
1449
+ readonly resource?: string;
1450
+ /** The plugin's dashboard extension, an absolute path. */
1451
+ readonly dashboard?: string;
1452
+ }
1794
1453
  interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
1795
1454
  /** Database file path or ':memory:' (default: ':memory:') */
1796
1455
  path?: string;
@@ -1843,14 +1502,10 @@ interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Recor
1843
1502
  schemaName?: string;
1844
1503
  }
1845
1504
  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
1505
  /**
1850
1506
  * 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.
1507
+ * Static imports so bundlers (Nitro/Rollup) trace and ship the driver.
1508
+ * `bun:sqlite` stays lazy in `sqlite.ts` since it only exists under Bun.
1854
1509
  */
1855
1510
  declare function createPostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: PostgresDatabaseConfig<TSchema>): PostgresDatabase<TSchema>;
1856
1511
  type EnvInput<T> = T | SecretRef<T>;
@@ -1926,6 +1581,208 @@ declare function defineDatabase<TSchema extends Record<string, unknown> = Record
1926
1581
  declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
1927
1582
  $client: Sql;
1928
1583
  }, TSchema>;
1584
+ /** The codes every action, listener and socket handler can raise, with their status and default message. */
1585
+ declare const STANDARD_ERRORS: {
1586
+ readonly BAD_REQUEST: {
1587
+ readonly status: 400;
1588
+ readonly message: "Bad Request";
1589
+ };
1590
+ readonly UNAUTHORIZED: {
1591
+ readonly status: 401;
1592
+ readonly message: "Unauthorized";
1593
+ };
1594
+ readonly FORBIDDEN: {
1595
+ readonly status: 403;
1596
+ readonly message: "Forbidden";
1597
+ };
1598
+ readonly NOT_FOUND: {
1599
+ readonly status: 404;
1600
+ readonly message: "Not Found";
1601
+ };
1602
+ readonly CONFLICT: {
1603
+ readonly status: 409;
1604
+ readonly message: "Conflict";
1605
+ };
1606
+ readonly INTERNAL_SERVER_ERROR: {
1607
+ readonly status: 500;
1608
+ readonly message: "Internal Server Error";
1609
+ };
1610
+ };
1611
+ type StandardErrorCode = keyof typeof STANDARD_ERRORS;
1612
+ /** An error as JSON: the body of a failed HTTP call, and the data of a socket `$error` (with its `event`). */
1613
+ interface WireError {
1614
+ name: string;
1615
+ code: string;
1616
+ message: string;
1617
+ status: number;
1618
+ details?: unknown;
1619
+ errors?: ValidationErrorItem[];
1620
+ }
1621
+ /** Event names starting with `$` are reserved for control messages. */
1622
+ declare const isControlEvent: (event: string) => boolean;
1623
+ /** How many outbox rows are in each state. */
1624
+ type OutboxCounts = Record<OutboxStatus, number>;
1625
+ /**
1626
+ * Delivers the events recorded in one outbox table to the app's listeners.
1627
+ *
1628
+ * It claims a batch of due rows, runs each listener, and marks the row delivered.
1629
+ * A listener that throws is retried later with a growing delay, and parked as
1630
+ * dead after its attempts run out. Several dispatchers can share a table: on
1631
+ * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
1632
+ * finished within `claimTimeoutMs` (the process died) is taken by another.
1633
+ * Delivery is at least once, so a listener should tolerate running twice for the
1634
+ * same `deliveryId`.
1635
+ */
1636
+ declare class Dispatcher {
1637
+ private readonly db;
1638
+ private readonly table;
1639
+ private readonly listeners;
1640
+ private readonly engine;
1641
+ private readonly options;
1642
+ private readonly inFlight;
1643
+ private timer?;
1644
+ private tickQueue?;
1645
+ private lastPurge;
1646
+ constructor(db: any, table: OutboxTable, listeners: (name: string) => Deliverable | undefined, options?: DispatchOptions);
1647
+ /** Start looking for due deliveries on a timer. Does nothing if it already is. */
1648
+ start(): void;
1649
+ /** Stop the timer and wait for the deliveries that are running to finish. */
1650
+ stop(): Promise<void>;
1651
+ /** Look for work soon, without waiting for the timer. Safe to call often. */
1652
+ notify(): void;
1653
+ /** Claim what is due and run it, once. @returns How many deliveries it started. */
1654
+ private tick;
1655
+ /**
1656
+ * Deliver everything that is due now and wait until those deliveries are done.
1657
+ * Deliveries that fail and are rescheduled are not waited for again.
1658
+ *
1659
+ * @returns How many deliveries it ran.
1660
+ */
1661
+ drain(): Promise<number>;
1662
+ counts(): Promise<OutboxCounts>;
1663
+ /**
1664
+ * Put parked deliveries back in line, with their attempts reset.
1665
+ *
1666
+ * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
1667
+ * @returns How many deliveries were put back.
1668
+ */
1669
+ retryDead(deliveryId?: string): Promise<number>;
1670
+ private claimAndRun;
1671
+ private claim;
1672
+ private deliver;
1673
+ private markDelivered;
1674
+ private fail;
1675
+ private park;
1676
+ private logError;
1677
+ private purgeDelivered;
1678
+ }
1679
+ /**
1680
+ * Stop every events hub started in this process, by any copy of `@brickkit/core`,
1681
+ * and wait for their deliveries. A hub that fails to stop does not cut the wait
1682
+ * for the others: the first failure is thrown once every hub is done.
1683
+ */
1684
+ declare function stopAllEvents(): Promise<void>;
1685
+ /**
1686
+ * What an app's `events` option describes, as plain data. It goes in the app
1687
+ * definition, which is sent to the dev dashboard, so it holds no functions.
1688
+ */
1689
+ interface EventsDefinition {
1690
+ listeners: {
1691
+ name: string;
1692
+ on: string[];
1693
+ kind: "handler" | "workflow";
1694
+ }[];
1695
+ dispatch: boolean;
1696
+ /** Names of the services whose writes record events. */
1697
+ recorders: string[];
1698
+ }
1699
+ /** What the dispatcher runs for a delivery. */
1700
+ interface Deliverable {
1701
+ readonly maxAttempts?: number;
1702
+ readonly errors?: EventListener["errors"];
1703
+ readonly retry?: EventListener["retry"];
1704
+ run(delivery: EventDelivery): void | Promise<void>;
1705
+ }
1706
+ /**
1707
+ * The events of one app: who listens, where events are recorded, and the
1708
+ * dispatchers that deliver them. `brick({ events })` makes one and puts it on
1709
+ * `app.events`.
1710
+ */
1711
+ declare class EventsHub {
1712
+ private readonly deps;
1713
+ private readonly byName;
1714
+ private readonly dispatchers;
1715
+ private readonly deliverables;
1716
+ private readonly dispatchOptions;
1717
+ private readonly runtime;
1718
+ private readonly recorderNames;
1719
+ private started;
1720
+ private stopping;
1721
+ /**
1722
+ * @param options - The `events` option.
1723
+ * @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
1724
+ * listeners and workflow steps.
1725
+ */
1726
+ constructor(options: EventsOptions, deps?: Record<string, unknown>);
1727
+ /**
1728
+ * Give each service whose database holds an outbox table a recorder, and a
1729
+ * dispatcher for that table. Call it before the first request: a service has no
1730
+ * recorder until then.
1731
+ *
1732
+ * @param services - The app's services.
1733
+ * @returns The hub, for chaining.
1734
+ */
1735
+ attach(services: readonly Service<any, any>[]): this;
1736
+ matching(name: string): EventListener[];
1737
+ describe(): EventsDefinition;
1738
+ /**
1739
+ * Where the workflow bundle is read from, the project it is built from, and
1740
+ * the world the workflows run on. Only set when a listener runs a workflow.
1741
+ * The CLI builds the bundle there before events start, and shows the world's
1742
+ * runs in the dev dashboard.
1743
+ */
1744
+ get workflows(): {
1745
+ root: string;
1746
+ dir: string;
1747
+ world: EventsWorld;
1748
+ } | undefined;
1749
+ /**
1750
+ * Resume the workflow that waits on a webhook. The server mounts this on the
1751
+ * route the Workflow SDK puts in webhook URLs.
1752
+ */
1753
+ webhook(request: Request): Promise<Response>;
1754
+ /**
1755
+ * Start delivering recorded events from this process, and start the world that
1756
+ * runs workflow listeners. Does nothing if this process only records events
1757
+ * (`dispatch: false`), already started, or a stop is still waiting.
1758
+ */
1759
+ start(): void;
1760
+ /**
1761
+ * Stop delivering, wait for the deliveries that are running, and close the
1762
+ * world. A world cannot be started again, so workflow listeners stop for good.
1763
+ * A stop that arrives while another runs waits for that one.
1764
+ */
1765
+ stop(): Promise<void>;
1766
+ private shutDown;
1767
+ /**
1768
+ * Deliver everything that is due now and wait for it. For tests and for
1769
+ * workers that drive delivery themselves.
1770
+ *
1771
+ * @returns How many deliveries ran.
1772
+ */
1773
+ drain(): Promise<number>;
1774
+ /** How many rows are in each state, across the app's outbox tables. */
1775
+ counts(): Promise<OutboxCounts>;
1776
+ /**
1777
+ * Put parked deliveries back in line.
1778
+ *
1779
+ * @param deliveryId - One delivery. Omit it to retry every dead one.
1780
+ * @returns How many deliveries were put back.
1781
+ */
1782
+ retryDead(deliveryId?: string): Promise<number>;
1783
+ private deliverable;
1784
+ private bind;
1785
+ }
1929
1786
  type SocketSchemas = Record<string, TSchema>;
1930
1787
  type SocketPayloads<S extends SocketSchemas> = { [K in keyof S]: Static<S[K]>; };
1931
1788
  type SocketEventArgs<Events> = { [K in keyof Events & string]: [event: K, payload: Events[K]]; }[keyof Events & string];
@@ -2057,12 +1914,10 @@ declare class BrickSocketError extends Error {
2057
1914
  readonly kind: "connection" | "protocol" | "backpressure" | "refused";
2058
1915
  constructor(kind: "connection" | "protocol" | "backpressure" | "refused", message: string, options?: ErrorOptions);
2059
1916
  }
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
1917
  /** An error a socket handler raised with `error.CODE()`, for the message `event` it was handling. */
2063
1918
  type BrickSocketHandlerError<Input = unknown, Errors = {}> = ActionExecutionError & {
2064
1919
  event: keyof Input & string;
2065
- code: Extract<keyof Errors, string> | StandardSocketErrorCode;
1920
+ code: Extract<keyof Errors, string> | StandardErrorCode;
2066
1921
  };
2067
1922
  interface BrickSocketClient<Input, Output, Errors = {}> extends BrickSocketSender<Input> {
2068
1923
  /** Resolves on the first open; rejects if the client closes before it. */
@@ -2139,6 +1994,8 @@ interface RegisteredSocket {
2139
1994
  topicPrefix: string;
2140
1995
  topic(room: string): string;
2141
1996
  connect(request: Request): Promise<SocketSession>;
1997
+ /** A plugin's deps, for a socket its setup declared. */
1998
+ deps?: Readonly<Record<string, unknown>>;
2142
1999
  }
2143
2000
  /**
2144
2001
  * The logger on action, tool, and endpoint contexts. While a dashboard is on
@@ -2230,6 +2087,14 @@ declare class ActionExecutionError extends Error {
2230
2087
  details: unknown;
2231
2088
  };
2232
2089
  }
2090
+ /**
2091
+ * Two declarations claim one name or URL segment. Startup throws it; `brick lint`
2092
+ * reports it as `unique-names`. Compare `name`, since a second copy of core
2093
+ * throws its own class.
2094
+ */
2095
+ declare class DuplicateNameError extends Error {
2096
+ constructor(message: string);
2097
+ }
2233
2098
  interface StandardErrorMap {
2234
2099
  BAD_REQUEST: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2235
2100
  UNAUTHORIZED: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
@@ -2253,7 +2118,7 @@ interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined,
2253
2118
  */
2254
2119
  path?: string;
2255
2120
  /** Single HTTP method exposed for this action (default POST). */
2256
- method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
2121
+ method?: HttpMethod;
2257
2122
  input?: TInputSchema;
2258
2123
  output?: TOutputSchema;
2259
2124
  errors?: TErrors;
@@ -2290,28 +2155,12 @@ interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema e
2290
2155
  }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2291
2156
  name: string;
2292
2157
  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
2158
  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
2159
  run(input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: Partial<TContext>): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2307
2160
  execute(params: {
2308
2161
  input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2309
2162
  ctx?: Partial<TContext>;
2310
2163
  }): 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
2164
  validateInput(input: unknown): {
2316
2165
  success: true;
2317
2166
  data: any;
@@ -2348,7 +2197,7 @@ interface Tool<I extends TSchema | undefined = any, O extends TSchema | undefine
2348
2197
  readonly kind: "tool";
2349
2198
  config: ToolConfigWithAuthorize<I, O, E, C> | ToolConfigWithoutAuthorize<I, O, E, C>;
2350
2199
  }
2351
- /** A resource declares identity and a table; plugins supply behavior. */
2200
+ /** A resource declares identity and a table; plugins and its own `action`/`command` supply behavior. */
2352
2201
  interface ResourceConfig<TTable = any, _TCtx = any> {
2353
2202
  name: string;
2354
2203
  table: TTable;
@@ -2454,7 +2303,6 @@ interface CommandDecision<TRow = any, TChildren = {}, TEvents extends EventCatal
2454
2303
  * rejection instead of throwing, so `decide` stays a pure function.
2455
2304
  */
2456
2305
  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
2306
  /** `resource.command(name, config)`. */
2459
2307
  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
2308
  description?: string;
@@ -2559,12 +2407,12 @@ type ActionAccessPolicy = "public" | "authorized" | "scoped";
2559
2407
  interface ActionSchema {
2560
2408
  name: string;
2561
2409
  /** Present only when this action has a registered HTTP route. */
2562
- method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
2410
+ method?: HttpMethod;
2563
2411
  path?: string;
2564
2412
  serviceName?: string;
2565
2413
  /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
2566
2414
  plugin?: string;
2567
- /** Owning resource name for resource-plugin actions (e.g. `page`). */
2415
+ /** Owning resource name for resource actions (e.g. `page`). */
2568
2416
  resource?: string;
2569
2417
  description?: string;
2570
2418
  inputSchema?: unknown;
@@ -2612,47 +2460,13 @@ interface ArchitectureSchema {
2612
2460
  /** Every `definePlugin` installation, with its dashboard extension. */
2613
2461
  plugins?: InstalledPlugin[];
2614
2462
  }
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
2463
  interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>, TEvents extends EventCatalog = EventCatalog> {
2648
2464
  readonly name: string;
2649
2465
  /** The declared events, as handles for `defineListener` and `emitEvent`. */
2650
2466
  readonly events: EventRefs<TEvents>;
2651
2467
  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>>;
2468
+ /** The tables of the service's resources and plugins, by table name. */
2654
2469
  readonly tables: Map<string, any>;
2655
- readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext>>;
2656
2470
  readonly db?: TDb;
2657
2471
  readonly isBuilt?: boolean;
2658
2472
  use<A>(plugin: ServicePlugin<this, A>): A;
@@ -2666,11 +2480,7 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
2666
2480
  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
2481
  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
2482
  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
2483
  contributePreparation(contribution: PreparationContribution): void;
2671
- listPreparations(): PreparationContribution[];
2672
- prepareContributions(): void;
2673
- registerTable(table: any): this;
2674
2484
  getAction(name: string): Action<any, any, any, any> | undefined;
2675
2485
  listActions(): Action<any, any, any, any>[];
2676
2486
  getTool(name: string): Tool<any, any, any, any> | undefined;
@@ -2679,16 +2489,10 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
2679
2489
  listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
2680
2490
  getDb(): TDb | undefined;
2681
2491
  /** The handle from `defineDatabase`, without connecting. */
2682
- getDatabaseHandle?(): DatabaseHandle<TDb> | undefined;
2492
+ getDatabaseHandle(): DatabaseHandle<TDb> | undefined;
2683
2493
  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
2494
  /** What a write needs to record events. Set by `brick({ events })`; absent otherwise. */
2687
2495
  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
2496
  resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
2693
2497
  introspect(): ServiceSchema;
2694
2498
  }
@@ -2697,5 +2501,5 @@ interface ProxyOptions {
2697
2501
  from?: string;
2698
2502
  context?: Partial<ActionContext>;
2699
2503
  }
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 };
2504
+ export { BrickSocketError as $, CrudEventOperation as $n, PluginRoutes as $t, Resource as A, listSecrets as An, PostgresDatabase as At, ServiceSchema as B, DispatchOptions as Bn, integer$1 as Bt, ErrorDetails as C, PluginSetupContext as Cn, DatabaseDefinition as Ct, NarrowAuthorizedContext as D, SecretSource as Dn, SQLiteDefinition as Dt, Logger as E, SecretRef as En, PostgresDefinition as Et, ResourceConfig as F, HostHooks as Fn, SQLiteDatabaseConfig as Ft, ToolConfigWithoutAuthorize as G, EventWorkflow as Gn, uniqueIndex as Gt, Tool as H, EventEnvelope as Hn, real$1 as Ht, ResourceIdentity as I, PluginHookArgs as In, blob as It, ValidationErrorItem as J, ListenerFailure as Jn, PLUGIN_KIND as Jt, ToolOptions as K, EventsOptions as Kn, ContextOf as Kt, ResourceTypeOptions as L, PluginHooks as Ln, createSQLiteDatabase as Lt, ResourceActionConfig as M, resetSecrets as Mn, createPostgresDatabase as Mt, ResourceActionInput as N, resolveSecrets as Nn, BrickSQLiteDatabase as Nt, PreparationContribution as O, defineSecret as On, defineDatabase as Ot, ResourceChild as P, PluginTableBuilders as Pn, BunSQLiteDatabase$1 as Pt, BrickSocketConnectOptions as Q, WorkflowsOptions as Qn, PluginRouteScope as Qt, Service as R, getHostHooks as Rn, foreignKey as Rt, ErrorBuilder as S, PluginServiceContext as Sn, isControlEvent as St, InferTableRow as T, SecretOptions as Tn, EnvInput as Tt, ToolAnnotations as U, EventListener as Un, sqliteTable$1 as Ut, StandardErrorMap as V, EventDelivery as Vn, primaryKey as Vt, ToolConfigWithAuthorize as W, EventRecorder as Wn, text$1 as Wt, BrickSocketClient as X, ServiceEvents as Xn, PluginRouteMethod as Xt, BrickClientSocket as Y, RetryDecision as Yn, PluginEndpointContext as Yt, BrickSocketConfig as Z, WorkflowEvent as Zn, PluginRouteRegistrar as Zt, CommandDecision as _, PluginInfo as _n, Dispatcher as _t, ActionConfigWithoutAuthorize as a, ServicePluginContext as an, isCrudEvent as ar, BrickSocketStatus as at, DefaultServiceContext as b, PluginLifecycleContext as bn, StandardErrorCode as bt, ActionExecutionError as c, ServicePort as cn, Ports as cr, SocketEmitArgs as ct, BaseActionConfig as d, PostgresOutboxTable as dn, HttpMethod as dr, SocketPayloads as dt, ResourcePlugin as en, EventCatalog as er, BrickSocketHandle as et, BaseContext as f, SQLiteOutboxTable as fn, SocketReplay as ft, CommandConfig as g, PluginFactory as gn, stopAllEvents as gt, CommandChildren as h, PluginContext as hn, EventsHub as ht, ActionConfigWithAuthorize as i, ServicePlugin as in, crudEventSource as ir, BrickSocketSender as it, ResourceActionAccess as j, overrideSecret as jn, PostgresDatabaseConfig as jt, ProxyOptions as k, envSource as kn, isDatabaseHandle as kt, ActionSchema as l, OutboxStatus as ln, port as lr, SocketEmitOptions as lt, Command as m, PluginAppContext as mn, EventsDefinition as mt, ActionAccessPolicy as n, ResourcePluginContext as nn, EventRefs as nr, BrickSocketReconnectOptions as nt, ActionContext as o, ActionAccessInfo as on, DepsOf as or, SocketBroker as ot, ChildChanges as p, outboxTable as pn, SocketSchemas as pt, ValidationError as q, EventsWorld as qn, InstalledPlugin as qt, ActionConfig as r, ResourcePluginTypes as rn, crudEventName as rr, BrickSocketSchema as rt, ActionErrorDefinition as s, ResourceActionInfo as sn, Port as sr, SocketBrokerMessage as st, Action as t, ResourcePluginAPI as tn, EventRef as tr, BrickSocketHandlerError as tt, ArchitectureSchema as u, OutboxTable as un, useDeps as ur, SocketEventArgs as ut, CommandErrors as v, PluginInstallOptions as vn, OutboxCounts as vt, InferTableInsert as w, definePlugin as wn, DatabaseHandle as wt, DuplicateNameError as x, PluginManifest as xn, WireError as xt, CommandRow as y, PluginInstance as yn, STANDARD_ERRORS as yt, ServiceOptions as z, CrudEventPayload as zn, index$1 as zt };
2701
2505
  //# sourceMappingURL=types.d.ts.map