@brickkit/core 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  import { Static, TSchema } from "@sinclair/typebox";
2
- import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
+ import { Table } from "drizzle-orm";
3
+ import { blob, foreignKey, index as index$1, integer as integer$1, primaryKey, real, sqliteTable as sqliteTable$1, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
3
4
  import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
4
5
  import { Sql } from "postgres";
5
6
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
6
- import { Table } from "drizzle-orm";
7
7
  import { Database } from "bun:sqlite";
8
8
  //#region src/plugin.d.ts
9
9
  type PluginRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
@@ -390,6 +390,955 @@ declare function defineDatabase<TSchema extends Record<string, unknown> = Record
390
390
  $client: Sql;
391
391
  }, TSchema>;
392
392
  //#endregion
393
+ //#region src/events/outbox.d.ts
394
+ /** What the outbox rows are in, by state. */
395
+ type OutboxStatus = "pending" | "claimed" | "delivered" | "dead";
396
+ declare function sqliteOutbox(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
397
+ name: string;
398
+ schema: undefined;
399
+ columns: {
400
+ seq: import("drizzle-orm/sqlite-core").SQLiteColumn<{
401
+ name: "seq";
402
+ tableName: string;
403
+ dataType: "number";
404
+ columnType: "SQLiteInteger";
405
+ data: number;
406
+ driverParam: number;
407
+ notNull: true;
408
+ hasDefault: true;
409
+ isPrimaryKey: true;
410
+ isAutoincrement: false;
411
+ hasRuntimeDefault: false;
412
+ enumValues: undefined;
413
+ baseColumn: never;
414
+ identity: undefined;
415
+ generated: undefined;
416
+ }, {}, {}>;
417
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
418
+ name: "id";
419
+ tableName: string;
420
+ dataType: "string";
421
+ columnType: "SQLiteText";
422
+ data: string;
423
+ driverParam: string;
424
+ notNull: true;
425
+ hasDefault: false;
426
+ isPrimaryKey: false;
427
+ isAutoincrement: false;
428
+ hasRuntimeDefault: false;
429
+ enumValues: [string, ...string[]];
430
+ baseColumn: never;
431
+ identity: undefined;
432
+ generated: undefined;
433
+ }, {}, {
434
+ length: number | undefined;
435
+ }>;
436
+ eventId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
437
+ name: "event_id";
438
+ tableName: string;
439
+ dataType: "string";
440
+ columnType: "SQLiteText";
441
+ data: string;
442
+ driverParam: string;
443
+ notNull: true;
444
+ hasDefault: false;
445
+ isPrimaryKey: false;
446
+ isAutoincrement: false;
447
+ hasRuntimeDefault: false;
448
+ enumValues: [string, ...string[]];
449
+ baseColumn: never;
450
+ identity: undefined;
451
+ generated: undefined;
452
+ }, {}, {
453
+ length: number | undefined;
454
+ }>;
455
+ listener: import("drizzle-orm/sqlite-core").SQLiteColumn<{
456
+ name: "listener";
457
+ tableName: string;
458
+ dataType: "string";
459
+ columnType: "SQLiteText";
460
+ data: string;
461
+ driverParam: string;
462
+ notNull: true;
463
+ hasDefault: false;
464
+ isPrimaryKey: false;
465
+ isAutoincrement: false;
466
+ hasRuntimeDefault: false;
467
+ enumValues: [string, ...string[]];
468
+ baseColumn: never;
469
+ identity: undefined;
470
+ generated: undefined;
471
+ }, {}, {
472
+ length: number | undefined;
473
+ }>;
474
+ name: import("drizzle-orm/sqlite-core").SQLiteColumn<{
475
+ name: "name";
476
+ tableName: string;
477
+ dataType: "string";
478
+ columnType: "SQLiteText";
479
+ data: string;
480
+ driverParam: string;
481
+ notNull: true;
482
+ hasDefault: false;
483
+ isPrimaryKey: false;
484
+ isAutoincrement: false;
485
+ hasRuntimeDefault: false;
486
+ enumValues: [string, ...string[]];
487
+ baseColumn: never;
488
+ identity: undefined;
489
+ generated: undefined;
490
+ }, {}, {
491
+ length: number | undefined;
492
+ }>;
493
+ payload: import("drizzle-orm/sqlite-core").SQLiteColumn<{
494
+ name: "payload";
495
+ tableName: string;
496
+ dataType: "json";
497
+ columnType: "SQLiteTextJson";
498
+ data: unknown;
499
+ driverParam: string;
500
+ notNull: true;
501
+ hasDefault: false;
502
+ isPrimaryKey: false;
503
+ isAutoincrement: false;
504
+ hasRuntimeDefault: false;
505
+ enumValues: undefined;
506
+ baseColumn: never;
507
+ identity: undefined;
508
+ generated: undefined;
509
+ }, {}, {}>;
510
+ traceId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
511
+ name: "trace_id";
512
+ tableName: string;
513
+ dataType: "string";
514
+ columnType: "SQLiteText";
515
+ data: string;
516
+ driverParam: string;
517
+ notNull: false;
518
+ hasDefault: false;
519
+ isPrimaryKey: false;
520
+ isAutoincrement: false;
521
+ hasRuntimeDefault: false;
522
+ enumValues: [string, ...string[]];
523
+ baseColumn: never;
524
+ identity: undefined;
525
+ generated: undefined;
526
+ }, {}, {
527
+ length: number | undefined;
528
+ }>;
529
+ source: import("drizzle-orm/sqlite-core").SQLiteColumn<{
530
+ name: "source";
531
+ tableName: string;
532
+ dataType: "string";
533
+ columnType: "SQLiteText";
534
+ data: string;
535
+ driverParam: string;
536
+ notNull: false;
537
+ hasDefault: false;
538
+ isPrimaryKey: false;
539
+ isAutoincrement: false;
540
+ hasRuntimeDefault: false;
541
+ enumValues: [string, ...string[]];
542
+ baseColumn: never;
543
+ identity: undefined;
544
+ generated: undefined;
545
+ }, {}, {
546
+ length: number | undefined;
547
+ }>;
548
+ occurredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
549
+ name: string;
550
+ tableName: string;
551
+ dataType: "date";
552
+ columnType: "SQLiteTimestamp";
553
+ data: Date;
554
+ driverParam: number;
555
+ notNull: true;
556
+ hasDefault: false;
557
+ isPrimaryKey: false;
558
+ isAutoincrement: false;
559
+ hasRuntimeDefault: false;
560
+ enumValues: undefined;
561
+ baseColumn: never;
562
+ identity: undefined;
563
+ generated: undefined;
564
+ }, {}, {}>;
565
+ status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
566
+ name: "status";
567
+ tableName: string;
568
+ dataType: "string";
569
+ columnType: "SQLiteText";
570
+ data: OutboxStatus;
571
+ driverParam: string;
572
+ notNull: true;
573
+ hasDefault: false;
574
+ isPrimaryKey: false;
575
+ isAutoincrement: false;
576
+ hasRuntimeDefault: false;
577
+ enumValues: [string, ...string[]];
578
+ baseColumn: never;
579
+ identity: undefined;
580
+ generated: undefined;
581
+ }, {}, {
582
+ length: number | undefined;
583
+ $type: OutboxStatus;
584
+ }>;
585
+ attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
586
+ name: "attempts";
587
+ tableName: string;
588
+ dataType: "number";
589
+ columnType: "SQLiteInteger";
590
+ data: number;
591
+ driverParam: number;
592
+ notNull: true;
593
+ hasDefault: true;
594
+ isPrimaryKey: false;
595
+ isAutoincrement: false;
596
+ hasRuntimeDefault: false;
597
+ enumValues: undefined;
598
+ baseColumn: never;
599
+ identity: undefined;
600
+ generated: undefined;
601
+ }, {}, {}>;
602
+ lastError: import("drizzle-orm/sqlite-core").SQLiteColumn<{
603
+ name: "last_error";
604
+ tableName: string;
605
+ dataType: "string";
606
+ columnType: "SQLiteText";
607
+ data: string;
608
+ driverParam: string;
609
+ notNull: false;
610
+ hasDefault: false;
611
+ isPrimaryKey: false;
612
+ isAutoincrement: false;
613
+ hasRuntimeDefault: false;
614
+ enumValues: [string, ...string[]];
615
+ baseColumn: never;
616
+ identity: undefined;
617
+ generated: undefined;
618
+ }, {}, {
619
+ length: number | undefined;
620
+ }>;
621
+ availableAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
622
+ name: string;
623
+ tableName: string;
624
+ dataType: "date";
625
+ columnType: "SQLiteTimestamp";
626
+ data: Date;
627
+ driverParam: number;
628
+ notNull: true;
629
+ hasDefault: false;
630
+ isPrimaryKey: false;
631
+ isAutoincrement: false;
632
+ hasRuntimeDefault: false;
633
+ enumValues: undefined;
634
+ baseColumn: never;
635
+ identity: undefined;
636
+ generated: undefined;
637
+ }, {}, {}>;
638
+ claimedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
639
+ name: string;
640
+ tableName: string;
641
+ dataType: "date";
642
+ columnType: "SQLiteTimestamp";
643
+ data: Date;
644
+ driverParam: number;
645
+ notNull: false;
646
+ hasDefault: false;
647
+ isPrimaryKey: false;
648
+ isAutoincrement: false;
649
+ hasRuntimeDefault: false;
650
+ enumValues: undefined;
651
+ baseColumn: never;
652
+ identity: undefined;
653
+ generated: undefined;
654
+ }, {}, {}>;
655
+ deliveredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
656
+ name: string;
657
+ tableName: string;
658
+ dataType: "date";
659
+ columnType: "SQLiteTimestamp";
660
+ data: Date;
661
+ driverParam: number;
662
+ notNull: false;
663
+ hasDefault: false;
664
+ isPrimaryKey: false;
665
+ isAutoincrement: false;
666
+ hasRuntimeDefault: false;
667
+ enumValues: undefined;
668
+ baseColumn: never;
669
+ identity: undefined;
670
+ generated: undefined;
671
+ }, {}, {}>;
672
+ };
673
+ dialect: "sqlite";
674
+ }>;
675
+ declare function postgresOutbox(name: string): import("drizzle-orm/pg-core").PgTableWithColumns<{
676
+ name: string;
677
+ schema: undefined;
678
+ columns: {
679
+ seq: import("drizzle-orm/pg-core").PgColumn<{
680
+ name: "seq";
681
+ tableName: string;
682
+ dataType: "number";
683
+ columnType: "PgBigSerial53";
684
+ data: number;
685
+ driverParam: number;
686
+ notNull: true;
687
+ hasDefault: true;
688
+ isPrimaryKey: true;
689
+ isAutoincrement: false;
690
+ hasRuntimeDefault: false;
691
+ enumValues: undefined;
692
+ baseColumn: never;
693
+ identity: undefined;
694
+ generated: undefined;
695
+ }, {}, {}>;
696
+ id: import("drizzle-orm/pg-core").PgColumn<{
697
+ name: "id";
698
+ tableName: string;
699
+ dataType: "string";
700
+ columnType: "PgText";
701
+ data: string;
702
+ driverParam: string;
703
+ notNull: true;
704
+ hasDefault: false;
705
+ isPrimaryKey: false;
706
+ isAutoincrement: false;
707
+ hasRuntimeDefault: false;
708
+ enumValues: [string, ...string[]];
709
+ baseColumn: never;
710
+ identity: undefined;
711
+ generated: undefined;
712
+ }, {}, {}>;
713
+ eventId: import("drizzle-orm/pg-core").PgColumn<{
714
+ name: "event_id";
715
+ tableName: string;
716
+ dataType: "string";
717
+ columnType: "PgText";
718
+ data: string;
719
+ driverParam: string;
720
+ notNull: true;
721
+ hasDefault: false;
722
+ isPrimaryKey: false;
723
+ isAutoincrement: false;
724
+ hasRuntimeDefault: false;
725
+ enumValues: [string, ...string[]];
726
+ baseColumn: never;
727
+ identity: undefined;
728
+ generated: undefined;
729
+ }, {}, {}>;
730
+ listener: import("drizzle-orm/pg-core").PgColumn<{
731
+ name: "listener";
732
+ tableName: string;
733
+ dataType: "string";
734
+ columnType: "PgText";
735
+ data: string;
736
+ driverParam: string;
737
+ notNull: true;
738
+ hasDefault: false;
739
+ isPrimaryKey: false;
740
+ isAutoincrement: false;
741
+ hasRuntimeDefault: false;
742
+ enumValues: [string, ...string[]];
743
+ baseColumn: never;
744
+ identity: undefined;
745
+ generated: undefined;
746
+ }, {}, {}>;
747
+ name: import("drizzle-orm/pg-core").PgColumn<{
748
+ name: "name";
749
+ tableName: string;
750
+ dataType: "string";
751
+ columnType: "PgText";
752
+ data: string;
753
+ driverParam: string;
754
+ notNull: true;
755
+ hasDefault: false;
756
+ isPrimaryKey: false;
757
+ isAutoincrement: false;
758
+ hasRuntimeDefault: false;
759
+ enumValues: [string, ...string[]];
760
+ baseColumn: never;
761
+ identity: undefined;
762
+ generated: undefined;
763
+ }, {}, {}>;
764
+ payload: import("drizzle-orm/pg-core").PgColumn<{
765
+ name: "payload";
766
+ tableName: string;
767
+ dataType: "json";
768
+ columnType: "PgJsonb";
769
+ data: unknown;
770
+ driverParam: unknown;
771
+ notNull: true;
772
+ hasDefault: false;
773
+ isPrimaryKey: false;
774
+ isAutoincrement: false;
775
+ hasRuntimeDefault: false;
776
+ enumValues: undefined;
777
+ baseColumn: never;
778
+ identity: undefined;
779
+ generated: undefined;
780
+ }, {}, {}>;
781
+ traceId: import("drizzle-orm/pg-core").PgColumn<{
782
+ name: "trace_id";
783
+ tableName: string;
784
+ dataType: "string";
785
+ columnType: "PgText";
786
+ data: string;
787
+ driverParam: string;
788
+ notNull: false;
789
+ hasDefault: false;
790
+ isPrimaryKey: false;
791
+ isAutoincrement: false;
792
+ hasRuntimeDefault: false;
793
+ enumValues: [string, ...string[]];
794
+ baseColumn: never;
795
+ identity: undefined;
796
+ generated: undefined;
797
+ }, {}, {}>;
798
+ source: import("drizzle-orm/pg-core").PgColumn<{
799
+ name: "source";
800
+ tableName: string;
801
+ dataType: "string";
802
+ columnType: "PgText";
803
+ data: string;
804
+ driverParam: string;
805
+ notNull: false;
806
+ hasDefault: false;
807
+ isPrimaryKey: false;
808
+ isAutoincrement: false;
809
+ hasRuntimeDefault: false;
810
+ enumValues: [string, ...string[]];
811
+ baseColumn: never;
812
+ identity: undefined;
813
+ generated: undefined;
814
+ }, {}, {}>;
815
+ occurredAt: import("drizzle-orm/pg-core").PgColumn<{
816
+ name: string;
817
+ tableName: string;
818
+ dataType: "date";
819
+ columnType: "PgTimestamp";
820
+ data: Date;
821
+ driverParam: string;
822
+ notNull: true;
823
+ hasDefault: false;
824
+ isPrimaryKey: false;
825
+ isAutoincrement: false;
826
+ hasRuntimeDefault: false;
827
+ enumValues: undefined;
828
+ baseColumn: never;
829
+ identity: undefined;
830
+ generated: undefined;
831
+ }, {}, {}>;
832
+ status: import("drizzle-orm/pg-core").PgColumn<{
833
+ name: "status";
834
+ tableName: string;
835
+ dataType: "string";
836
+ columnType: "PgText";
837
+ data: OutboxStatus;
838
+ driverParam: string;
839
+ notNull: true;
840
+ hasDefault: false;
841
+ isPrimaryKey: false;
842
+ isAutoincrement: false;
843
+ hasRuntimeDefault: false;
844
+ enumValues: [string, ...string[]];
845
+ baseColumn: never;
846
+ identity: undefined;
847
+ generated: undefined;
848
+ }, {}, {
849
+ $type: OutboxStatus;
850
+ }>;
851
+ attempts: import("drizzle-orm/pg-core").PgColumn<{
852
+ name: "attempts";
853
+ tableName: string;
854
+ dataType: "number";
855
+ columnType: "PgInteger";
856
+ data: number;
857
+ driverParam: string | number;
858
+ notNull: true;
859
+ hasDefault: true;
860
+ isPrimaryKey: false;
861
+ isAutoincrement: false;
862
+ hasRuntimeDefault: false;
863
+ enumValues: undefined;
864
+ baseColumn: never;
865
+ identity: undefined;
866
+ generated: undefined;
867
+ }, {}, {}>;
868
+ lastError: import("drizzle-orm/pg-core").PgColumn<{
869
+ name: "last_error";
870
+ tableName: string;
871
+ dataType: "string";
872
+ columnType: "PgText";
873
+ data: string;
874
+ driverParam: string;
875
+ notNull: false;
876
+ hasDefault: false;
877
+ isPrimaryKey: false;
878
+ isAutoincrement: false;
879
+ hasRuntimeDefault: false;
880
+ enumValues: [string, ...string[]];
881
+ baseColumn: never;
882
+ identity: undefined;
883
+ generated: undefined;
884
+ }, {}, {}>;
885
+ availableAt: import("drizzle-orm/pg-core").PgColumn<{
886
+ name: string;
887
+ tableName: string;
888
+ dataType: "date";
889
+ columnType: "PgTimestamp";
890
+ data: Date;
891
+ driverParam: string;
892
+ notNull: true;
893
+ hasDefault: false;
894
+ isPrimaryKey: false;
895
+ isAutoincrement: false;
896
+ hasRuntimeDefault: false;
897
+ enumValues: undefined;
898
+ baseColumn: never;
899
+ identity: undefined;
900
+ generated: undefined;
901
+ }, {}, {}>;
902
+ claimedAt: import("drizzle-orm/pg-core").PgColumn<{
903
+ name: string;
904
+ tableName: string;
905
+ dataType: "date";
906
+ columnType: "PgTimestamp";
907
+ data: Date;
908
+ driverParam: string;
909
+ notNull: false;
910
+ hasDefault: false;
911
+ isPrimaryKey: false;
912
+ isAutoincrement: false;
913
+ hasRuntimeDefault: false;
914
+ enumValues: undefined;
915
+ baseColumn: never;
916
+ identity: undefined;
917
+ generated: undefined;
918
+ }, {}, {}>;
919
+ deliveredAt: import("drizzle-orm/pg-core").PgColumn<{
920
+ name: string;
921
+ tableName: string;
922
+ dataType: "date";
923
+ columnType: "PgTimestamp";
924
+ data: Date;
925
+ driverParam: string;
926
+ notNull: false;
927
+ hasDefault: false;
928
+ isPrimaryKey: false;
929
+ isAutoincrement: false;
930
+ hasRuntimeDefault: false;
931
+ enumValues: undefined;
932
+ baseColumn: never;
933
+ identity: undefined;
934
+ generated: undefined;
935
+ }, {}, {}>;
936
+ };
937
+ dialect: "pg";
938
+ }>;
939
+ /** The outbox table of a SQLite database. */
940
+ type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;
941
+ /** The outbox table of a Postgres database. */
942
+ type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;
943
+ /** An outbox table, made by `outboxTable`. */
944
+ type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;
945
+ /**
946
+ * The outbox table: where recorded events wait, one row per listener, until they
947
+ * are delivered. A write and the events it causes are inserted in one transaction,
948
+ * so an event is neither lost when the process dies after the write nor sent for a
949
+ * write that was rolled back.
950
+ *
951
+ * Brick does not create tables for you. Put this in the schema of the database
952
+ * whose writes emit events, and your migration tool (such as drizzle-kit) creates
953
+ * it. A service whose database holds the table records events; one without it does
954
+ * not.
955
+ *
956
+ * @param engine - The database engine, `"sqlite"` or `"postgres"`.
957
+ * @param options - `name` to call the table something other than `brick_outbox`.
958
+ * @returns A Drizzle table.
959
+ * @example
960
+ * import { defineDatabase, outboxTable } from "@brickkit/core";
961
+ *
962
+ * export const outbox = outboxTable("postgres");
963
+ * export const database = defineDatabase({
964
+ * engine: "postgres",
965
+ * tables: { users, outbox },
966
+ * });
967
+ */
968
+ declare function outboxTable(engine: "sqlite", options?: {
969
+ name?: string;
970
+ }): SQLiteOutboxTable;
971
+ declare function outboxTable(engine: "postgres", options?: {
972
+ name?: string;
973
+ }): PostgresOutboxTable;
974
+ /**
975
+ * Whether a value is an outbox table made by `outboxTable`.
976
+ *
977
+ * @param value - Anything.
978
+ * @returns `true` for an outbox table, narrowing its type.
979
+ */
980
+ declare function isOutboxTable(value: unknown): value is OutboxTable;
981
+ //#endregion
982
+ //#region src/events/types.d.ts
983
+ /**
984
+ * An event, as it was recorded. It is the same for every listener of it.
985
+ */
986
+ interface EventEnvelope<TPayload = unknown> {
987
+ /** Unique per event. Every listener's delivery of the event shares it. */
988
+ id: string;
989
+ /** The event name, such as `user.create`. */
990
+ name: string;
991
+ /** What happened. JSON data. */
992
+ payload: TPayload;
993
+ /** When it happened, as an ISO timestamp. */
994
+ occurredAt: string;
995
+ /** The trace of the request that caused it, so a listener continues the same trace. */
996
+ traceId?: string;
997
+ /** What emitted it, such as `identity.user` for a generated CRUD write. */
998
+ source?: string;
999
+ }
1000
+ /**
1001
+ * One listener's delivery of an event: the envelope, plus which listener it is for
1002
+ * and which attempt this is.
1003
+ */
1004
+ interface EventDelivery<TPayload = unknown> extends EventEnvelope<TPayload> {
1005
+ /** The name of the listener this delivery is for. */
1006
+ listener: string;
1007
+ /**
1008
+ * `<event id>:<listener>`. It is the same on every retry, so a listener can use
1009
+ * it to avoid doing the work twice: delivery is at least once.
1010
+ */
1011
+ deliveryId: string;
1012
+ /** 1 on the first try, 2 on the first retry, and so on. */
1013
+ attempt: number;
1014
+ }
1015
+ /**
1016
+ * The CRUD events of a resource called `user`, by operation. Listeners of
1017
+ * `user.create`, `user.update` and `user.delete` receive these payloads.
1018
+ */
1019
+ type CrudEventPayload<TRow = Record<string, unknown>> = {
1020
+ id: unknown;
1021
+ row: TRow;
1022
+ } | {
1023
+ id: unknown;
1024
+ before: TRow;
1025
+ after: TRow;
1026
+ };
1027
+ /**
1028
+ * A listener: code that runs when an event it listens for has been recorded.
1029
+ */
1030
+ interface EventListener<TPayload = any> {
1031
+ /** Unique among the app's listeners. It is part of each delivery's id. */
1032
+ readonly name: string;
1033
+ /**
1034
+ * The event names to listen for. A trailing `*` matches a prefix (`user.*`),
1035
+ * and `*` alone matches every event.
1036
+ */
1037
+ readonly on: readonly string[];
1038
+ /**
1039
+ * A handler that runs in the dispatching process for each delivery. Throwing
1040
+ * retries the delivery with a growing delay. A listener has this or `workflow`.
1041
+ */
1042
+ readonly run?: (delivery: EventDelivery<TPayload>) => void | Promise<void>;
1043
+ /**
1044
+ * A durable workflow that runs for each delivery, on the app's `events.world`.
1045
+ * The delivery counts as done once its run has started; the workflow retries
1046
+ * its own steps from there. A listener has this or `run`.
1047
+ */
1048
+ readonly workflow?: EventWorkflow<TPayload>;
1049
+ /** Attempts before the delivery is parked as dead. Defaults to the dispatcher's. */
1050
+ readonly maxAttempts?: number;
1051
+ }
1052
+ /**
1053
+ * What a workflow listener's workflow receives: the event and which listener it
1054
+ * is for. It has no `attempt`, because one delivery starts one run however many
1055
+ * times it is tried.
1056
+ */
1057
+ type WorkflowEvent<TPayload = any> = Omit<EventDelivery<TPayload>, "attempt">;
1058
+ /**
1059
+ * A function marked `"use workflow"`, run once per delivery of the listener it is
1060
+ * given to.
1061
+ */
1062
+ type EventWorkflow<TPayload = any> = (event: WorkflowEvent<TPayload>) => Promise<unknown>;
1063
+ /**
1064
+ * The world workflow listeners run on: the queue and storage behind the Workflow
1065
+ * SDK. `createWorld()` from `@brickkit/redis-world` or `@brickkit/bullmq-world`
1066
+ * makes one. Brick starts it with the app's events and closes it when they stop.
1067
+ */
1068
+ interface EventsWorld {
1069
+ /**
1070
+ * Names a run after its key so that starting it twice makes one run. A world
1071
+ * without it would start a second run when an event is delivered again, so
1072
+ * Brick refuses such a world.
1073
+ */
1074
+ createRunId?(options?: Readonly<Record<string, unknown>>): string;
1075
+ start?(): Promise<void>;
1076
+ close?(): Promise<void>;
1077
+ registerHandler?(prefix: any, handler: (request: Request) => Promise<Response>): void;
1078
+ }
1079
+ /**
1080
+ * Where the workflows of an app are built from. The CLI (`brick dev`,
1081
+ * `brick start`) writes the bundle to `<root>/.well-known/workflow/v1` before
1082
+ * events start, and events read it from there.
1083
+ */
1084
+ interface WorkflowsOptions {
1085
+ /** The project root: where the Workflow SDK is installed. Default: the working directory. */
1086
+ root?: string;
1087
+ }
1088
+ /**
1089
+ * How the dispatcher delivers recorded events.
1090
+ */
1091
+ interface DispatchOptions {
1092
+ /**
1093
+ * Whether to look for due deliveries on a timer, and right after a commit.
1094
+ * Default `true`. With `false`, deliveries run only when something calls
1095
+ * `app.events.drain()`: a cron job, a worker you drive yourself, or a test.
1096
+ */
1097
+ timer?: boolean;
1098
+ /** How often to look for deliveries that are due, in milliseconds. Default 1000. */
1099
+ intervalMs?: number;
1100
+ /** Most deliveries claimed at once. Default 50. */
1101
+ batchSize?: number;
1102
+ /** Attempts before a delivery is parked as dead. Default 8. */
1103
+ maxAttempts?: number;
1104
+ /** How long a claimed delivery may run before another dispatcher takes it, in milliseconds. Default 60000. */
1105
+ claimTimeoutMs?: number;
1106
+ /** Longest wait before a retry, in milliseconds. Default 300000. */
1107
+ maxBackoffMs?: number;
1108
+ /** How long delivered rows are kept, in milliseconds. Default 86400000 (one day). 0 keeps none. */
1109
+ retainDeliveredMs?: number;
1110
+ }
1111
+ /**
1112
+ * The `events` option of `brick()`.
1113
+ */
1114
+ interface EventsOptions {
1115
+ /** The listeners of the app. */
1116
+ listeners?: readonly EventListener[];
1117
+ /**
1118
+ * Whether this process delivers recorded events. `true` (the default) starts a
1119
+ * dispatcher with the default settings, an object tunes it, and `false` only
1120
+ * records events, for an app whose events are delivered by another process.
1121
+ */
1122
+ dispatch?: boolean | DispatchOptions;
1123
+ /**
1124
+ * The world that runs `workflow` listeners. Required when any listener has one.
1125
+ * Brick starts it when the app's events start and closes it when they stop.
1126
+ */
1127
+ world?: EventsWorld;
1128
+ /** Where the workflow bundle lives. Only used with workflow listeners. */
1129
+ workflows?: WorkflowsOptions;
1130
+ }
1131
+ /**
1132
+ * Records an event inside the transaction it was given. The event is committed
1133
+ * with the write, or not at all.
1134
+ */
1135
+ type EventRecorder = (name: string, payload: unknown) => Promise<void>;
1136
+ /**
1137
+ * What a service with events offers the code that writes to its database. A
1138
+ * service has it once `brick({ events })` is set up and its database holds an
1139
+ * outbox table.
1140
+ */
1141
+ interface ServiceEvents {
1142
+ /** Whether any listener wants the event, so a write can skip recording one. */
1143
+ wants(name: string): boolean;
1144
+ /**
1145
+ * Run `fn` in a database transaction. Events it records are committed with
1146
+ * whatever else it wrote, or not at all, and are delivered after the commit.
1147
+ */
1148
+ transaction<T>(db: unknown, context: {
1149
+ traceId?: string;
1150
+ source?: string;
1151
+ }, fn: (tx: any, record: EventRecorder) => Promise<T>): Promise<T>;
1152
+ /**
1153
+ * Record an event in a transaction the caller already has open. It is
1154
+ * committed with that transaction. Nothing tells Brick when the caller commits,
1155
+ * so delivery waits for the dispatcher's next poll.
1156
+ */
1157
+ record(tx: unknown, context: {
1158
+ traceId?: string;
1159
+ source?: string;
1160
+ }, name: string, payload: unknown): Promise<void>;
1161
+ }
1162
+ //#endregion
1163
+ //#region src/events/dispatcher.d.ts
1164
+ /** How many outbox rows are in each state. */
1165
+ type OutboxCounts = Record<OutboxStatus, number>;
1166
+ /**
1167
+ * Delivers the events recorded in one outbox table to the app's listeners.
1168
+ *
1169
+ * It claims a batch of due rows, runs each listener, and marks the row delivered.
1170
+ * A listener that throws is retried later with a growing delay, and parked as
1171
+ * dead after its attempts run out. Several dispatchers can share a table: on
1172
+ * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
1173
+ * finished within `claimTimeoutMs` (the process died) is taken by another.
1174
+ * Delivery is at least once, so a listener should tolerate running twice for the
1175
+ * same `deliveryId`.
1176
+ */
1177
+ declare class Dispatcher {
1178
+ private readonly db;
1179
+ private readonly table;
1180
+ private readonly listeners;
1181
+ private readonly onError;
1182
+ private readonly engine;
1183
+ private readonly options;
1184
+ private readonly inFlight;
1185
+ private timer?;
1186
+ private tickQueue?;
1187
+ private lastPurge;
1188
+ constructor(db: any, table: OutboxTable, listeners: (name: string) => Deliverable | undefined, options?: DispatchOptions, onError?: (error: unknown) => void);
1189
+ /** Whether the dispatcher is looking for work on a timer. */
1190
+ get running(): boolean;
1191
+ /** Start looking for due deliveries on a timer. Does nothing if it already is. */
1192
+ start(): void;
1193
+ /**
1194
+ * Stop the timer and wait for the deliveries that are running to finish.
1195
+ */
1196
+ stop(): Promise<void>;
1197
+ /** Look for work soon, without waiting for the timer. Safe to call often. */
1198
+ notify(): void;
1199
+ /**
1200
+ * Claim what is due and run it, once. Used by the timer, and by tests and
1201
+ * workers that drive delivery themselves.
1202
+ *
1203
+ * @returns How many deliveries it started.
1204
+ */
1205
+ tick(): Promise<number>;
1206
+ /**
1207
+ * Deliver everything that is due now and wait until those deliveries are done.
1208
+ * Deliveries that fail and are rescheduled are not waited for again.
1209
+ *
1210
+ * @returns How many deliveries it ran.
1211
+ */
1212
+ drain(): Promise<number>;
1213
+ /**
1214
+ * How many rows are in each state.
1215
+ */
1216
+ counts(): Promise<OutboxCounts>;
1217
+ /**
1218
+ * Put parked deliveries back in line, with their attempts reset.
1219
+ *
1220
+ * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
1221
+ * @returns How many deliveries were put back.
1222
+ */
1223
+ retryDead(deliveryId?: string): Promise<number>;
1224
+ private claimAndRun;
1225
+ private claim;
1226
+ private deliver;
1227
+ private markDelivered;
1228
+ private fail;
1229
+ private park;
1230
+ private purgeDelivered;
1231
+ }
1232
+ //#endregion
1233
+ //#region src/events/hub.d.ts
1234
+ interface EventsHost {
1235
+ readonly name: string;
1236
+ getDb(): unknown;
1237
+ getOutbox?(): OutboxTable | undefined;
1238
+ setEvents?(events: ServiceEvents | undefined): void;
1239
+ }
1240
+ /**
1241
+ * Stop every events hub started in this process, by any copy of `@brickkit/core`,
1242
+ * and wait for their deliveries. A hub that fails to stop does not cut the wait
1243
+ * for the others: the first failure is thrown once every hub is done.
1244
+ */
1245
+ declare function stopAllEvents(): Promise<void>;
1246
+ /**
1247
+ * What an app's `events` option describes, as plain data. It goes in the app
1248
+ * definition, which is sent to the dev dashboard, so it holds no functions.
1249
+ */
1250
+ interface EventsDefinition {
1251
+ listeners: {
1252
+ name: string;
1253
+ on: string[];
1254
+ kind: "handler" | "workflow";
1255
+ }[];
1256
+ dispatch: boolean;
1257
+ /** Names of the services whose writes record events. */
1258
+ recorders: string[];
1259
+ }
1260
+ /** What the dispatcher runs for a delivery. */
1261
+ interface Deliverable {
1262
+ readonly maxAttempts?: number;
1263
+ run(delivery: EventDelivery): void | Promise<void>;
1264
+ }
1265
+ /**
1266
+ * The events of one app: who listens, where events are recorded, and the
1267
+ * dispatchers that deliver them. `brick({ events })` makes one and puts it on
1268
+ * `app.events`.
1269
+ */
1270
+ declare class EventsHub {
1271
+ private readonly byName;
1272
+ private readonly dispatchers;
1273
+ private readonly deliverables;
1274
+ private readonly dispatchOptions;
1275
+ private readonly runtime;
1276
+ private readonly recorderNames;
1277
+ private started;
1278
+ private stopping;
1279
+ constructor(options: EventsOptions);
1280
+ /**
1281
+ * Give each service whose database holds an outbox table a recorder, and a
1282
+ * dispatcher for that table. Call it before the first request: a service has no
1283
+ * recorder until then.
1284
+ *
1285
+ * @param services - The app's services.
1286
+ * @returns The hub, for chaining.
1287
+ */
1288
+ attach(services: readonly EventsHost[]): this;
1289
+ /** The listeners that want an event. */
1290
+ matching(name: string): EventListener[];
1291
+ /** The listeners and settings, as plain data. */
1292
+ describe(): EventsDefinition;
1293
+ /**
1294
+ * Where the workflow bundle is read from, the project it is built from, and
1295
+ * the world the workflows run on. Only set when a listener runs a workflow.
1296
+ * The CLI builds the bundle there before events start, and shows the world's
1297
+ * runs in the dev dashboard.
1298
+ */
1299
+ get workflows(): {
1300
+ root: string;
1301
+ dir: string;
1302
+ world: EventsWorld;
1303
+ } | undefined;
1304
+ /**
1305
+ * Resume the workflow that waits on a webhook. The server mounts this on the
1306
+ * route the Workflow SDK puts in webhook URLs.
1307
+ */
1308
+ webhook(request: Request): Promise<Response>;
1309
+ /**
1310
+ * Start delivering recorded events from this process, and start the world that
1311
+ * runs workflow listeners. Does nothing if this process only records events
1312
+ * (`dispatch: false`), already started, or a stop is still waiting.
1313
+ */
1314
+ start(): void;
1315
+ /**
1316
+ * Stop delivering, wait for the deliveries that are running, and close the
1317
+ * world. A world cannot be started again, so workflow listeners stop for good.
1318
+ * A stop that arrives while another runs waits for that one.
1319
+ */
1320
+ stop(): Promise<void>;
1321
+ private shutDown;
1322
+ /**
1323
+ * Deliver everything that is due now and wait for it. For tests and for
1324
+ * workers that drive delivery themselves.
1325
+ *
1326
+ * @returns How many deliveries ran.
1327
+ */
1328
+ drain(): Promise<number>;
1329
+ /** How many rows are in each state, across the app's outbox tables. */
1330
+ counts(): Promise<OutboxCounts>;
1331
+ /**
1332
+ * Put parked deliveries back in line.
1333
+ *
1334
+ * @param deliveryId - One delivery. Omit it to retry every dead one.
1335
+ * @returns How many deliveries were put back.
1336
+ */
1337
+ retryDead(deliveryId?: string): Promise<number>;
1338
+ private deliverable;
1339
+ private bind;
1340
+ }
1341
+ //#endregion
393
1342
  //#region src/types.d.ts
394
1343
  /**
395
1344
  * The logger on action, tool, and endpoint contexts. While a dashboard is on
@@ -723,6 +1672,8 @@ interface ServiceSchema {
723
1672
  interface ArchitectureSchema {
724
1673
  version: string;
725
1674
  services: ServiceSchema[];
1675
+ /** Present when the app has an `events` option. */
1676
+ events?: EventsDefinition;
726
1677
  }
727
1678
  interface CompiledRoutePlan {
728
1679
  service: Service<any, any>;
@@ -787,6 +1738,11 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
787
1738
  listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
788
1739
  getDb(): TDb | undefined;
789
1740
  setDb(database: DatabaseHandle<TDb>): void;
1741
+ /** The outbox table of this service's database, if it holds one (see `outboxTable`). */
1742
+ getOutbox?(): OutboxTable | undefined;
1743
+ /** What a write needs to record events. Set by `brick({ events })`; absent otherwise. */
1744
+ readonly events?: ServiceEvents;
1745
+ setEvents?(events: ServiceEvents | undefined): void;
790
1746
  resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
791
1747
  introspect(): ServiceSchema;
792
1748
  }
@@ -1017,5 +1973,5 @@ declare function createBrickClient<TApp extends Record<string, any>>(options: Br
1017
1973
  }): BrickClient<TApp>;
1018
1974
  declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
1019
1975
  //#endregion
1020
- export { ToolConfigWithoutAuthorize as $, ErrorBuilder as A, index as At, Resource as B, PluginRouteScope as Bt, ActionSchema as C, secret as Ct, CacheOptions as D, blob as Dt, BaseContext as E, SQLiteDatabaseConfig as Et, NarrowAuthorizedContext as F, text as Ft, ServiceAuthOptions as G, ResourcePluginTypes as Gt, ResourceIdentity as H, ResourcePlugin as Ht, PreparationContribution as I, uniqueIndex as It, StandardErrorMap as J, defineResourcePlugin as Jt, ServiceOptions as K, ServicePlugin as Kt, ProxyOptions as L, PluginEndpointContext as Lt, InferTableRow as M, primaryKey as Mt, LifecycleOptions as N, real as Nt, CompiledRoutePlan as O, createSQLiteDatabase as Ot, Logger as P, sqliteTable as Pt, ToolConfigWithAuthorize as Q, RateLimitOptions as R, PluginRouteMethod as Rt, ActionExecutionError as S, resolveSecrets as St, BaseActionConfig as T, BunSQLiteDatabase$1 as Tt, ResourceTypeOptions as U, ResourcePluginAPI as Ut, ResourceConfig as V, PluginRoutes as Vt, Service as W, ResourcePluginContext as Wt, Tool as X, getPluginActionRoute as Xt, TelemetryOptions as Y, defineServicePlugin as Yt, ToolAnnotations as Z, getPluginEndpoints as Zt, ActionConfig as _, envSource as _t, BrickClientOptions as a, EnvInput as at, ActionContext as b, overrideSecrets as bt, InferActionErrorCodes as c, defineDatabase as ct, InferActionOutput as d, PostgresDatabase as dt, ToolOptions as et, createBrickClient as f, PostgresDatabaseConfig as ft, ActionAccessPolicy as g, SecretSource as gt, Action as h, SecretRef as ht, BrickClientAction as i, DatabaseHandle as it, InferTableInsert as j, integer as jt, DefaultServiceContext as k, foreignKey as kt, InferActionFailure as l, isDatabaseHandle as lt, isBrickTransportError as m, SecretOptions as mt, BrickCallOptions as n, ValidationErrorItem as nt, BrickServerError as o, PostgresDefinition as ot, isBrickServerError as p, createPostgresDatabase as pt, ServiceSchema as q, ServicePluginContext as qt, BrickClient as r, DatabaseDefinition as rt, BrickTransportError as s, SQLiteDefinition as st, BrickActionCaller as t, ValidationError as tt, InferActionInput as u, DatabaseAdapter as ut, ActionConfigWithAuthorize as v, listSecrets as vt, ArchitectureSchema as w, BrickSQLiteDatabase as wt, ActionErrorDefinition as x, resetSecrets as xt, ActionConfigWithoutAuthorize as y, overrideSecret as yt, ResilienceOptions as z, PluginRouteRegistrar as zt };
1976
+ export { ToolConfigWithoutAuthorize as $, index$1 as $t, ErrorBuilder as A, SQLiteDefinition as At, Resource as B, envSource as Bt, ActionSchema as C, SQLiteOutboxTable as Ct, CacheOptions as D, DatabaseHandle as Dt, BaseContext as E, DatabaseDefinition as Et, NarrowAuthorizedContext as F, PostgresDatabaseConfig as Ft, ServiceAuthOptions as G, resolveSecrets as Gt, ResourceIdentity as H, overrideSecret as Ht, PreparationContribution as I, createPostgresDatabase as It, StandardErrorMap as J, BunSQLiteDatabase$1 as Jt, ServiceOptions as K, secret as Kt, ProxyOptions as L, SecretOptions as Lt, InferTableRow as M, isDatabaseHandle as Mt, LifecycleOptions as N, DatabaseAdapter as Nt, CompiledRoutePlan as O, EnvInput as Ot, Logger as P, PostgresDatabase as Pt, ToolConfigWithAuthorize as Q, foreignKey as Qt, RateLimitOptions as R, SecretRef as Rt, ActionExecutionError as S, PostgresOutboxTable as St, BaseActionConfig as T, outboxTable as Tt, ResourceTypeOptions as U, overrideSecrets as Ut, ResourceConfig as V, listSecrets as Vt, Service as W, resetSecrets as Wt, Tool as X, blob as Xt, TelemetryOptions as Y, SQLiteDatabaseConfig as Yt, ToolAnnotations as Z, createSQLiteDatabase as Zt, ActionConfig as _, defineResourcePlugin as _n, ServiceEvents as _t, BrickClientOptions as a, uniqueIndex as an, stopAllEvents as at, ActionContext as b, getPluginEndpoints as bn, OutboxStatus as bt, InferActionErrorCodes as c, PluginRouteRegistrar as cn, CrudEventPayload as ct, InferActionOutput as d, ResourcePlugin as dn, EventEnvelope as dt, integer$1 as en, ToolOptions as et, createBrickClient as f, ResourcePluginAPI as fn, EventListener as ft, ActionAccessPolicy as g, ServicePluginContext as gn, EventsWorld as gt, Action as h, ServicePlugin as hn, EventsOptions as ht, BrickClientAction as i, text$1 as in, EventsHub as it, InferTableInsert as j, defineDatabase as jt, DefaultServiceContext as k, PostgresDefinition as kt, InferActionFailure as l, PluginRouteScope as ln, DispatchOptions as lt, isBrickTransportError as m, ResourcePluginTypes as mn, EventWorkflow as mt, BrickCallOptions as n, real as nn, ValidationErrorItem as nt, BrickServerError as o, PluginEndpointContext as on, Dispatcher as ot, isBrickServerError as p, ResourcePluginContext as pn, EventRecorder as pt, ServiceSchema as q, BrickSQLiteDatabase as qt, BrickClient as r, sqliteTable$1 as rn, EventsDefinition as rt, BrickTransportError as s, PluginRouteMethod as sn, OutboxCounts as st, BrickActionCaller as t, primaryKey as tn, ValidationError as tt, InferActionInput as u, PluginRoutes as un, EventDelivery as ut, ActionConfigWithAuthorize as v, defineServicePlugin as vn, WorkflowEvent as vt, ArchitectureSchema as w, isOutboxTable as wt, ActionErrorDefinition as x, OutboxTable as xt, ActionConfigWithoutAuthorize as y, getPluginActionRoute as yn, WorkflowsOptions as yt, ResilienceOptions as z, SecretSource as zt };
1021
1977
  //# sourceMappingURL=client.d.ts.map