@relaybus/core 0.3.0 → 0.3.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.
package/dist/index.d.cts CHANGED
@@ -1,15 +1,5 @@
1
- import { E as EventEnvelope, D as DomainEvent, S as StandardSchemaV1, P as PayloadOf, a as EventHeaders, b as EventReference, C as Clock, c as EventClass } from './event-DCRTuYKI.cjs';
2
- export { d as DefineEventKeyOptions, e as DefineEventOptions, f as EventKeyFunction, g as assertEventType, h as defineEvent, s as systemClock, v as validatePayload } from './event-DCRTuYKI.cjs';
3
-
4
- /**
5
- * A duration in milliseconds, or a string such as `'250ms'`, `'30s'`, `'5m'`,
6
- * `'1h'` or `'7d'`.
7
- */
8
- type Duration = number | `${number}${DurationUnit}`;
9
- type DurationUnit = 'ms' | 's' | 'm' | 'h' | 'd';
10
- declare function toMilliseconds(value: Duration, name: string): number;
11
- /** Largest delay Node.js timers support. Longer values fire after 1ms instead. */
12
- declare const MAX_TIMER_DELAY_MS = 2147483647;
1
+ import { D as Duration, E as EventEnvelope, a as DomainEvent, S as StandardSchemaV1, P as PayloadOf, C as ClaimedDelivery, b as EventHeaders, c as EventStoreStatistics, d as ErrorInfo, e as PurgeResult, f as EventStore, T as Transport, g as EventReference, h as Clock, A as AppendEntry, i as AppendResult, j as ClaimRequest, L as LeaseReference, k as DeliveryQuery, l as DeliveryRecord, m as PurgeRequest, n as EventClass } from './transport-BlfzIBZD.cjs';
2
+ export { o as AttemptsExhaustedError, p as CloseOptions, q as ConfigurationError, r as DELIVERY_STATUSES, s as DefineEventKeyOptions, t as DefineEventOptions, u as DeliveryStatus, v as DispatcherStoppedError, w as DrainIncompleteError, x as EventKeyFunction, y as EventStoreTransactionOptions, z as EventValidationError, H as HandlerTimeoutError, I as InvalidEnvelopeError, B as InvalidTransportMessage, F as LeaseLostError, G as LifecycleError, M as MAX_TIMER_DELAY_MS, N as NewDelivery, J as NonRetryableError, R as RelayBusError, K as TransactionRequiredError, O as TransactionTimeoutError, Q as TransportMessage, U as TransportMessageHandler, V as TransportSubscriptionHooks, W as ValidationIssue, X as assertEventType, Y as defineEvent, Z as systemClock, _ as toErrorInfo, $ as toMilliseconds, a0 as validatePayload } from './transport-BlfzIBZD.cjs';
13
3
 
14
4
  /**
15
5
  * How the delay between attempts is randomized.
@@ -358,326 +348,6 @@ declare function consume<TCatalog extends Catalog, const TName extends keyof TCa
358
348
  */
359
349
  declare function produce<TCatalog extends Catalog, const TName extends keyof TCatalog = keyof TCatalog>(catalog: TCatalog, options?: CatalogEventSelection<TName>): CatalogDeclaration<TCatalog, TName>;
360
350
 
361
- /**
362
- * Base class of every error thrown by relaybus.
363
- */
364
- declare class RelayBusError extends Error {
365
- name: string;
366
- /**
367
- * Stable, machine-readable identifier of the error class, such as `RELAYBUS_LEASE_LOST`.
368
- * Unlike `name` and `message`, a code is never renamed once released; branch on it in
369
- * alerts and dashboards. Subclasses declared outside relaybus inherit `RELAYBUS_ERROR`.
370
- */
371
- readonly code: string;
372
- }
373
- /** Invalid options passed to a relaybus component. */
374
- declare class ConfigurationError extends RelayBusError {
375
- name: string;
376
- readonly code: string;
377
- }
378
- /**
379
- * Thrown by `publish` when no transaction can be found and the bus runs with
380
- * `transactionMode: 'required'` (the default). Publishing outside a transaction
381
- * would reintroduce the dual-write problem the outbox exists to prevent.
382
- */
383
- declare class TransactionRequiredError extends RelayBusError {
384
- name: string;
385
- readonly code: string;
386
- }
387
- /**
388
- * A `bus.transaction` (or `@RelayBusTransaction()` method) ran past its `transactionTimeout` and
389
- * was rolled back. Its `cause` is the error the database raised when it ended the transaction,
390
- * when there was one. Usually a slow call to another service made inside the transaction.
391
- */
392
- declare class TransactionTimeoutError extends RelayBusError {
393
- name: string;
394
- readonly code: string;
395
- }
396
- /**
397
- * Throw from a handler to dead-letter the delivery immediately, skipping the
398
- * remaining retry attempts.
399
- */
400
- declare class NonRetryableError extends RelayBusError {
401
- name: string;
402
- readonly code: string;
403
- }
404
- /** A payload failed its event schema. Never retried: the payload will not change. */
405
- declare class EventValidationError extends NonRetryableError {
406
- readonly issues: readonly ValidationIssue[];
407
- name: string;
408
- readonly code: string;
409
- constructor(message: string, issues: readonly ValidationIssue[]);
410
- }
411
- /**
412
- * A message received from a broker is not a valid event. Never retried:
413
- * transports should dead-letter it instead of redelivering it forever.
414
- */
415
- declare class InvalidEnvelopeError extends NonRetryableError {
416
- name: string;
417
- readonly code: string;
418
- }
419
- /** The worker no longer owns the delivery it was processing. */
420
- declare class LeaseLostError extends RelayBusError {
421
- name: string;
422
- readonly code: string;
423
- /**
424
- * Whether the store said so (a fenced write returned false). A worker that only noticed
425
- * locally that its lease ran out may still own the delivery in the store and has to give it back.
426
- */
427
- readonly storeConfirmed: boolean;
428
- constructor(message: string, options?: {
429
- readonly storeConfirmed?: boolean;
430
- });
431
- }
432
- /** A handler did not settle within its configured timeout. Retried like any failure. */
433
- declare class HandlerTimeoutError extends RelayBusError {
434
- name: string;
435
- readonly code: string;
436
- }
437
- /**
438
- * Reason of a handler's abort signal when the bus stops before the handler
439
- * finished. The delivery is released and runs again without losing an attempt.
440
- */
441
- declare class DispatcherStoppedError extends RelayBusError {
442
- name: string;
443
- readonly code: string;
444
- }
445
- /**
446
- * A delivery came back after its lease expired on its last attempt, so it is
447
- * dead-lettered without running its handler again.
448
- */
449
- declare class AttemptsExhaustedError extends RelayBusError {
450
- name: string;
451
- readonly code: string;
452
- }
453
- /** A lifecycle method was called in a state that does not allow it, such as starting a bus twice. */
454
- declare class LifecycleError extends RelayBusError {
455
- name: string;
456
- readonly code: string;
457
- }
458
- /** `drain` still found due deliveries after its maximum number of batches. */
459
- declare class DrainIncompleteError extends RelayBusError {
460
- name: string;
461
- readonly code: string;
462
- }
463
- interface ValidationIssue {
464
- readonly message: string;
465
- readonly path?: readonly PropertyKey[] | undefined;
466
- }
467
- /** Serializable snapshot of an error, stored with failed deliveries. */
468
- interface ErrorInfo {
469
- readonly name: string;
470
- readonly message: string;
471
- readonly stack?: string | undefined;
472
- /** The {@link RelayBusError.code} of a relaybus error; absent for any other error. */
473
- readonly code?: string | undefined;
474
- }
475
- declare function toErrorInfo(error: unknown): ErrorInfo;
476
-
477
- /**
478
- * Lifecycle of one handler's delivery of one event.
479
- * `pending` (waiting or scheduled for retry) -> `processing` (leased by a worker)
480
- * -> `completed` | `pending` (retry) | `dead` (exhausted or non-retryable).
481
- * `dead` -> `pending` only through an explicit requeue.
482
- *
483
- * A completed delivery is deleted. `completed` records exist only in stores
484
- * configured to keep a completion history (`retainCompleted` /
485
- * `completionHistory`), where they are listed, counted and purged like before.
486
- */
487
- type DeliveryStatus = 'pending' | 'processing' | 'completed' | 'dead';
488
- declare const DELIVERY_STATUSES: readonly DeliveryStatus[];
489
- interface NewDelivery {
490
- readonly id: string;
491
- /** Stable handler id. Together with the event id it is unique. */
492
- readonly handler: string;
493
- readonly availableAt: Date;
494
- }
495
- interface AppendEntry {
496
- readonly event: EventEnvelope;
497
- readonly deliveries: readonly NewDelivery[];
498
- }
499
- interface AppendResult {
500
- /** Events written by this call. */
501
- readonly appendedEventIds: readonly string[];
502
- /** Events that already existed. Their missing deliveries were still added. */
503
- readonly duplicateEventIds: readonly string[];
504
- /** Deliveries written by this call. Existing (event, handler) pairs are skipped. */
505
- readonly appendedDeliveryCount: number;
506
- }
507
- /**
508
- * Lease expiry is compared with the `now` the caller passes, taken from the
509
- * bus clock. Keep worker clocks synchronized (NTP): a skew larger than a third
510
- * of the lease duration lets another worker reclaim a delivery that is still running.
511
- *
512
- * Stores may grant the lease on a group of deliveries (a lane) instead of on
513
- * each delivery. The group is exclusive to `leaseOwner` while the lease is
514
- * live, so other owners do not see its pending deliveries until it expires or
515
- * is relinquished; every delivery of the group carries the group's fencing token.
516
- */
517
- interface ClaimRequest {
518
- /** Only deliveries of these handlers are claimed. */
519
- readonly handlers: readonly string[];
520
- readonly limit: number;
521
- readonly leaseOwner: string;
522
- readonly leaseExpiresAt: Date;
523
- readonly now: Date;
524
- }
525
- /**
526
- * Proof of ownership. Every state change after a claim must present it
527
- * (fencing). A lease stays valid until another claim replaces it, even after
528
- * its expiry time; expiry only makes the delivery claimable again.
529
- */
530
- interface LeaseReference {
531
- readonly deliveryId: string;
532
- readonly leaseToken: string;
533
- }
534
- interface ClaimedDelivery extends LeaseReference {
535
- readonly handler: string;
536
- /** Attempt number of this claim, starting at 1. */
537
- readonly attempt: number;
538
- readonly leaseExpiresAt: Date;
539
- readonly event: EventEnvelope;
540
- }
541
- interface DeliveryRecord {
542
- readonly id: string;
543
- readonly handler: string;
544
- readonly status: DeliveryStatus;
545
- readonly attempts: number;
546
- readonly availableAt: Date;
547
- readonly leaseOwner: string | null;
548
- readonly leaseExpiresAt: Date | null;
549
- readonly lastError: ErrorInfo | null;
550
- readonly createdAt: Date;
551
- readonly updatedAt: Date;
552
- readonly completedAt: Date | null;
553
- readonly event: EventEnvelope;
554
- }
555
- interface DeliveryQuery {
556
- readonly status?: DeliveryStatus;
557
- readonly handler?: string;
558
- readonly eventType?: string;
559
- readonly eventId?: string;
560
- /** Default 100. */
561
- readonly limit?: number;
562
- }
563
- interface PurgeRequest {
564
- /** Delete completed deliveries completed before this instant. */
565
- readonly completedBefore?: Date;
566
- /** Delete dead deliveries last updated before this instant. */
567
- readonly deadBefore?: Date;
568
- }
569
- interface PurgeResult {
570
- readonly deletedDeliveries: number;
571
- /** Events deleted because no delivery referenced them any more. */
572
- readonly deletedEvents: number;
573
- }
574
- interface EventStoreStatistics {
575
- readonly pending: number;
576
- readonly processing: number;
577
- readonly completed: number;
578
- readonly dead: number;
579
- /** `availableAt` of the oldest delivery that is due but not yet processed. */
580
- readonly oldestDueAt: Date | null;
581
- }
582
- /** How `stop` closes a transport or a store. */
583
- interface CloseOptions {
584
- /**
585
- * Aborted when the shutdown deadline passes (`bus.stop({ timeout })`), possibly before `close` is
586
- * called. From then on, close what you opened yourself at once (destroy connections, cancel
587
- * running queries) instead of waiting for it to finish; the bus no longer waits for `close`.
588
- * Leave alone what the application passed in.
589
- */
590
- readonly signal?: AbortSignal;
591
- }
592
- /** How a store runs one transaction of `bus.transaction`. */
593
- interface EventStoreTransactionOptions {
594
- /**
595
- * Time budget of the whole transaction, in milliseconds. A store makes the database enforce it
596
- * where it can (for example a statement or idle-in-transaction timeout), so a transaction that
597
- * waits on something slow is ended by the server and its locks are released. The bus rolls back
598
- * a transaction that still ran past the budget, so a store may also ignore it.
599
- */
600
- readonly timeoutMs: number;
601
- }
602
- /**
603
- * Storage port. Implementations persist events and deliveries in the same
604
- * database as the application's business data so that both commit atomically.
605
- *
606
- * Every implementation must pass the contract suite in `@relaybus/testing`.
607
- */
608
- interface EventStore<TTransaction = unknown> {
609
- /** Creates tables, collections and indexes when they do not exist. */
610
- setup?(): Promise<void>;
611
- /**
612
- * Runs `work` inside a new database transaction and commits when it resolves. `options` come
613
- * from `bus.transaction`; the store's own transactions and the dispatcher's pass none.
614
- */
615
- transaction<T>(work: (transaction: TTransaction) => Promise<T>, options?: EventStoreTransactionOptions): Promise<T>;
616
- /**
617
- * Writes events and their deliveries inside `transaction`. Idempotent on
618
- * event id and on (event id, handler). Assigns a per-key sequence to keyed
619
- * events in commit order.
620
- */
621
- append(transaction: TTransaction, entries: readonly AppendEntry[], now: Date): Promise<AppendResult>;
622
- /**
623
- * Leases up to `limit` deliveries that are due: pending with `availableAt <= now`,
624
- * or processing with an expired lease. A keyed delivery is only claimable when
625
- * no earlier delivery of the same handler and key is pending or processing.
626
- * Counts the attempt (`attempt` of the result; a store may persist the count
627
- * only when the attempt fails or its lease is lost). Safe to call from many
628
- * processes at once.
629
- */
630
- claim(request: ClaimRequest): Promise<ClaimedDelivery[]>;
631
- /** Extends a lease the caller still holds. Returns false when the lease was lost. */
632
- extendLease(lease: LeaseReference, leaseExpiresAt: Date, now: Date): Promise<boolean>;
633
- /**
634
- * Marks a leased delivery completed by deleting it (or moving it to the
635
- * completion history, when the store keeps one). With `transaction` the change
636
- * commits together with the handler's own writes. Returns false when the lease
637
- * was lost.
638
- */
639
- complete(lease: LeaseReference, now: Date, transaction?: TTransaction): Promise<boolean>;
640
- /** Returns a leased delivery to pending, due at `availableAt`. */
641
- reschedule(lease: LeaseReference, availableAt: Date, error: ErrorInfo, now: Date): Promise<boolean>;
642
- /**
643
- * Gives a leased delivery back without counting the attempt: pending, due
644
- * now, attempts decremented. Used when a handler is aborted at shutdown.
645
- */
646
- release(lease: LeaseReference, now: Date): Promise<boolean>;
647
- /**
648
- * Marks many leased deliveries completed with one round trip. Returns, for
649
- * every lease in the same order, whether it was completed (false: lease lost
650
- * or already finished). Each lease is fenced individually, exactly as in
651
- * {@link EventStore.complete}. Optional: the dispatcher falls back to
652
- * `complete` when a store does not implement it.
653
- */
654
- completeMany?(leases: readonly LeaseReference[], now: Date): Promise<boolean[]>;
655
- /** Moves a leased delivery to dead. */
656
- bury(lease: LeaseReference, error: ErrorInfo, now: Date): Promise<boolean>;
657
- listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]>;
658
- /** Moves dead deliveries back to pending with a fresh attempt budget. Returns how many moved. */
659
- requeue(deliveryIds: readonly string[], now: Date): Promise<number>;
660
- purge(request: PurgeRequest): Promise<PurgeResult>;
661
- statistics(now: Date): Promise<EventStoreStatistics>;
662
- /**
663
- * Hands back every lease group that `leaseOwner` holds without running work,
664
- * so other workers can take them at once instead of after lease expiry.
665
- * Called at graceful shutdown after the owner's deliveries settled. Groups
666
- * with running deliveries stay leased. Optional.
667
- */
668
- relinquish?(leaseOwner: string, now: Date): Promise<void>;
669
- /**
670
- * Calls `listener` soon after a transaction that added deliveries due at once has committed, in this
671
- * process or in any other one, so an idle dispatcher claims them without waiting for its next poll.
672
- * A hint, never a guarantee: a report may be late, merged with others, or lost (while a connection
673
- * is re-established, for instance), and polling still finds every delivery. Resolves with a function
674
- * that stops listening, or with `undefined` when this store cannot listen. Optional.
675
- */
676
- watchNewDeliveries?(listener: () => void): Promise<(() => Promise<void>) | undefined>;
677
- /** Releases connections the store opened itself; forced once `options.signal` aborts. */
678
- close?(options?: CloseOptions): Promise<void>;
679
- }
680
-
681
351
  /**
682
352
  * RFC 9562 UUID version 7: 48-bit Unix millisecond timestamp followed by random
683
353
  * bits. Time-ordered, so it keeps B-tree indexes compact, and globally unique,
@@ -915,69 +585,6 @@ interface RelayBusLogger {
915
585
  error(message: string): void;
916
586
  }
917
587
 
918
- /** Where an incoming message came from, for observers and traces. */
919
- interface TransportMessage {
920
- /** Topic, routing key or queue the message arrived on. */
921
- readonly destination: string;
922
- }
923
- /** A message the transport could not turn into an event, so it never reaches the bus. */
924
- interface InvalidTransportMessage {
925
- /** Topic, routing key or queue the message arrived on. */
926
- readonly destination: string;
927
- /** What the codec or decoder threw. */
928
- readonly error: unknown;
929
- }
930
- /**
931
- * What the bus offers a transport at `subscribe`, beyond the message handler. Present only when
932
- * an observer implements the matching hook, so a transport can skip the work otherwise.
933
- */
934
- interface TransportSubscriptionHooks {
935
- /**
936
- * Call once for each inbound message the transport rejected as undecodable (dead-lettered or
937
- * skipped) before it reached `onMessage`. Messages the bus rejected itself are reported by
938
- * `onReceiveFinished` and must not be reported here. Never throws.
939
- */
940
- readonly onInvalidMessage: (message: InvalidTransportMessage) => void;
941
- }
942
- /**
943
- * Receives an event from a broker. Resolve only after it is durably stored. Transports pass
944
- * `message` to tell where the event arrived; it is optional for transports written before it.
945
- */
946
- type TransportMessageHandler = (envelope: EventEnvelope, message?: TransportMessage) => Promise<void>;
947
- /**
948
- * Broker port used to exchange events between services.
949
- *
950
- * Outbound: the bus calls `publish` from a delivery, so a broker outage only
951
- * delays events; the outbox keeps them. `publish` must resolve only after the
952
- * broker acknowledged the message.
953
- *
954
- * Inbound: `subscribe` must acknowledge a message only after `onMessage`
955
- * resolved, and redeliver it when `onMessage` rejects (at-least-once).
956
- */
957
- interface Transport {
958
- /** Unique name referenced by routes and subscriptions. */
959
- readonly name: string;
960
- /**
961
- * The messaging system, as OpenTelemetry names it (`kafka`, `rabbitmq`), reported to observers
962
- * and traces. Default: the transport's name.
963
- */
964
- readonly system?: string;
965
- connect?(): Promise<void>;
966
- publish(envelope: EventEnvelope, destination: string): Promise<void>;
967
- subscribe?(destinations: readonly string[], onMessage: TransportMessageHandler, hooks?: TransportSubscriptionHooks): Promise<void>;
968
- /**
969
- * Whether the transport can currently publish and, when subscribed, is
970
- * consuming. Health checks use it to report a dead consumer or a lost
971
- * connection. Transports without it count as ready.
972
- */
973
- isReady?(): boolean;
974
- /**
975
- * Releases connections. A closed transport is not reopened. Once `options.signal` aborts (the
976
- * shutdown deadline passed), stop waiting and drop the connections it opened itself.
977
- */
978
- close(options?: CloseOptions): Promise<void>;
979
- }
980
-
981
588
  /**
982
589
  * - `required`: `publish` throws {@link TransactionRequiredError} when it finds no transaction.
983
590
  * - `optional`: `publish` opens its own transaction instead. The event is still durable,
@@ -1152,6 +759,85 @@ interface PublishOneOptions<TTransaction = unknown> extends PublishOptions<TTran
1152
759
  }
1153
760
  type ReceiveStatus = 'accepted' | 'duplicate' | 'ignored';
1154
761
 
762
+ /** The publishing half of a bus, which a {@link CatalogPublisher} delegates to. */
763
+ interface PublishTarget<TTransaction> {
764
+ publish<TPayload>(event: DomainEvent<TPayload>, options?: PublishOneOptions<TTransaction>): Promise<EventEnvelope<TPayload>>;
765
+ publishAll(events: readonly DomainEvent[], options?: PublishOptions<TTransaction>): Promise<EventEnvelope[]>;
766
+ }
767
+ /**
768
+ * A view of a bus that publishes only the events of one catalog, or only the
769
+ * events a service produces from it. Obtain it with `bus.forCatalog(catalog)`
770
+ * or `bus.forCatalog(catalog, { events: ['OrderPlaced'] })`. Publishing an
771
+ * event outside the view fails to compile; a mistyped event that gets past the
772
+ * compiler (a cast, plain JavaScript, or a class with a structurally identical
773
+ * payload) is rejected with a {@link ConfigurationError} before anything is stored.
774
+ *
775
+ * ```ts
776
+ * const orders = bus.forCatalog(OrderEvents);
777
+ * await orders.publish(new OrderPlaced({ orderId }));
778
+ * await orders.publish(new UserRegistered({ userId })); // compile error
779
+ * ```
780
+ */
781
+ declare class CatalogPublisher<TCatalog extends Catalog, TTransaction = unknown, TName extends keyof TCatalog = keyof TCatalog> {
782
+ #private;
783
+ /**
784
+ * Throws {@link ConfigurationError} when `catalog` was not created with
785
+ * `defineCatalog` or `options.events` names no event, an unknown event or
786
+ * the same event twice.
787
+ */
788
+ constructor(catalog: TCatalog, target: PublishTarget<TTransaction>, options?: CatalogEventSelection<TName>);
789
+ /** Same as `bus.publish`, limited to the events of the view. */
790
+ publish<TEvent extends CatalogEvents<TCatalog, TName>>(event: TEvent, options?: PublishOneOptions<TTransaction>): Promise<EventEnvelope<TEvent['payload']>>;
791
+ /** Same as `bus.publishAll`, limited to the events of the view. Nothing is stored unless every event belongs to it. */
792
+ publishAll(events: readonly CatalogEvents<TCatalog, TName>[], options?: PublishOptions<TTransaction>): Promise<EventEnvelope[]>;
793
+ }
794
+
795
+ /** Transaction handle of {@link InMemoryEventStore}. Writes apply on commit only. */
796
+ declare class InMemoryTransaction {
797
+ #private;
798
+ get state(): 'open' | 'committed' | 'rolled-back';
799
+ enqueue(operation: () => void): void;
800
+ /** Runs `finisher` once the transaction commits or rolls back, like a lock release. */
801
+ onFinish(finisher: () => void): void;
802
+ commit(): void;
803
+ rollback(): void;
804
+ }
805
+
806
+ interface InMemoryEventStoreOptions {
807
+ /** Allow use when `NODE_ENV` is `production`. Data is lost on restart. Default false. */
808
+ readonly allowInProduction?: boolean;
809
+ readonly generateIdentifier?: IdentifierGenerator;
810
+ /**
811
+ * Keep a record of completed deliveries (status `completed`, listed, counted
812
+ * and purged by `retention.completed`). Default false: a completed delivery
813
+ * is deleted, like in the database stores.
814
+ */
815
+ readonly retainCompleted?: boolean;
816
+ }
817
+ /**
818
+ * Event store kept in process memory, with the same semantics as the database
819
+ * stores: transactional appends, leases, fencing and per-key ordering. Payloads
820
+ * are round-tripped through JSON exactly like a database would store them.
821
+ * Meant for tests and local development.
822
+ */
823
+ declare class InMemoryEventStore implements EventStore<InMemoryTransaction> {
824
+ #private;
825
+ constructor(options?: InMemoryEventStoreOptions);
826
+ transaction<T>(work: (transaction: InMemoryTransaction) => Promise<T>): Promise<T>;
827
+ append(transaction: InMemoryTransaction, entries: readonly AppendEntry[], now: Date): Promise<AppendResult>;
828
+ claim(request: ClaimRequest): Promise<ClaimedDelivery[]>;
829
+ extendLease(lease: LeaseReference, leaseExpiresAt: Date, now: Date): Promise<boolean>;
830
+ complete(lease: LeaseReference, now: Date, transaction?: InMemoryTransaction): Promise<boolean>;
831
+ completeMany(leases: readonly LeaseReference[], now: Date): Promise<boolean[]>;
832
+ reschedule(lease: LeaseReference, availableAt: Date, error: ErrorInfo, now: Date): Promise<boolean>;
833
+ release(lease: LeaseReference, now: Date): Promise<boolean>;
834
+ bury(lease: LeaseReference, error: ErrorInfo, now: Date): Promise<boolean>;
835
+ listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]>;
836
+ requeue(deliveryIds: readonly string[], now: Date): Promise<number>;
837
+ purge(request: PurgeRequest): Promise<PurgeResult>;
838
+ statistics(now: Date): Promise<EventStoreStatistics>;
839
+ }
840
+
1155
841
  interface StopOptions {
1156
842
  /**
1157
843
  * Longest the whole `stop` may take. Default: `dispatcher.shutdownTimeout`. Keep it below the time
@@ -1286,83 +972,4 @@ declare class RelayBus<TTransaction = unknown> {
1286
972
  purgeExpired(): Promise<PurgeResult>;
1287
973
  }
1288
974
 
1289
- /** The publishing half of a bus, which a {@link CatalogPublisher} delegates to. */
1290
- interface PublishTarget<TTransaction> {
1291
- publish<TPayload>(event: DomainEvent<TPayload>, options?: PublishOneOptions<TTransaction>): Promise<EventEnvelope<TPayload>>;
1292
- publishAll(events: readonly DomainEvent[], options?: PublishOptions<TTransaction>): Promise<EventEnvelope[]>;
1293
- }
1294
- /**
1295
- * A view of a bus that publishes only the events of one catalog, or only the
1296
- * events a service produces from it. Obtain it with `bus.forCatalog(catalog)`
1297
- * or `bus.forCatalog(catalog, { events: ['OrderPlaced'] })`. Publishing an
1298
- * event outside the view fails to compile; a mistyped event that gets past the
1299
- * compiler (a cast, plain JavaScript, or a class with a structurally identical
1300
- * payload) is rejected with a {@link ConfigurationError} before anything is stored.
1301
- *
1302
- * ```ts
1303
- * const orders = bus.forCatalog(OrderEvents);
1304
- * await orders.publish(new OrderPlaced({ orderId }));
1305
- * await orders.publish(new UserRegistered({ userId })); // compile error
1306
- * ```
1307
- */
1308
- declare class CatalogPublisher<TCatalog extends Catalog, TTransaction = unknown, TName extends keyof TCatalog = keyof TCatalog> {
1309
- #private;
1310
- /**
1311
- * Throws {@link ConfigurationError} when `catalog` was not created with
1312
- * `defineCatalog` or `options.events` names no event, an unknown event or
1313
- * the same event twice.
1314
- */
1315
- constructor(catalog: TCatalog, target: PublishTarget<TTransaction>, options?: CatalogEventSelection<TName>);
1316
- /** Same as `bus.publish`, limited to the events of the view. */
1317
- publish<TEvent extends CatalogEvents<TCatalog, TName>>(event: TEvent, options?: PublishOneOptions<TTransaction>): Promise<EventEnvelope<TEvent['payload']>>;
1318
- /** Same as `bus.publishAll`, limited to the events of the view. Nothing is stored unless every event belongs to it. */
1319
- publishAll(events: readonly CatalogEvents<TCatalog, TName>[], options?: PublishOptions<TTransaction>): Promise<EventEnvelope[]>;
1320
- }
1321
-
1322
- /** Transaction handle of {@link InMemoryEventStore}. Writes apply on commit only. */
1323
- declare class InMemoryTransaction {
1324
- #private;
1325
- get state(): 'open' | 'committed' | 'rolled-back';
1326
- enqueue(operation: () => void): void;
1327
- /** Runs `finisher` once the transaction commits or rolls back, like a lock release. */
1328
- onFinish(finisher: () => void): void;
1329
- commit(): void;
1330
- rollback(): void;
1331
- }
1332
-
1333
- interface InMemoryEventStoreOptions {
1334
- /** Allow use when `NODE_ENV` is `production`. Data is lost on restart. Default false. */
1335
- readonly allowInProduction?: boolean;
1336
- readonly generateIdentifier?: IdentifierGenerator;
1337
- /**
1338
- * Keep a record of completed deliveries (status `completed`, listed, counted
1339
- * and purged by `retention.completed`). Default false: a completed delivery
1340
- * is deleted, like in the database stores.
1341
- */
1342
- readonly retainCompleted?: boolean;
1343
- }
1344
- /**
1345
- * Event store kept in process memory, with the same semantics as the database
1346
- * stores: transactional appends, leases, fencing and per-key ordering. Payloads
1347
- * are round-tripped through JSON exactly like a database would store them.
1348
- * Meant for tests and local development.
1349
- */
1350
- declare class InMemoryEventStore implements EventStore<InMemoryTransaction> {
1351
- #private;
1352
- constructor(options?: InMemoryEventStoreOptions);
1353
- transaction<T>(work: (transaction: InMemoryTransaction) => Promise<T>): Promise<T>;
1354
- append(transaction: InMemoryTransaction, entries: readonly AppendEntry[], now: Date): Promise<AppendResult>;
1355
- claim(request: ClaimRequest): Promise<ClaimedDelivery[]>;
1356
- extendLease(lease: LeaseReference, leaseExpiresAt: Date, now: Date): Promise<boolean>;
1357
- complete(lease: LeaseReference, now: Date, transaction?: InMemoryTransaction): Promise<boolean>;
1358
- completeMany(leases: readonly LeaseReference[], now: Date): Promise<boolean[]>;
1359
- reschedule(lease: LeaseReference, availableAt: Date, error: ErrorInfo, now: Date): Promise<boolean>;
1360
- release(lease: LeaseReference, now: Date): Promise<boolean>;
1361
- bury(lease: LeaseReference, error: ErrorInfo, now: Date): Promise<boolean>;
1362
- listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]>;
1363
- requeue(deliveryIds: readonly string[], now: Date): Promise<number>;
1364
- purge(request: PurgeRequest): Promise<PurgeResult>;
1365
- statistics(now: Date): Promise<EventStoreStatistics>;
1366
- }
1367
-
1368
- export { type AppendEntry, type AppendResult, AttemptsExhaustedError, type BacklogEvent, type Catalog, type CatalogDeclaration, type CatalogDescription, type CatalogEntry, type CatalogEventClass, type CatalogEventName, type CatalogEventSelection, type CatalogEvents, CatalogPublisher, type CatalogRole, type ClaimFinishedEvent, type ClaimRequest, type ClaimedDelivery, Clock, type CloseOptions, ConfigurationError, DEFAULT_RETRY_POLICY, DEFAULT_ROUTE_RETRY_POLICY, DELIVERY_STATUSES, type DefineCatalogOptions, type DeliveryKind, type DeliveryQuery, type DeliveryRecord, type DeliveryStatus, type DispatcherOptions, DispatcherStoppedError, DomainEvent, DrainIncompleteError, type Duration, type ErrorInfo, EventClass, EventEnvelope, type EventHandler, EventHeaders, type EventOf, EventReference, type EventStore, type EventStoreStatistics, type EventStoreTransactionOptions, EventValidationError, type FailureStage, type HandlerContext, type HandlerDescriptor, type HandlerFinishedEvent, type HandlerShapeOf, type HandlerStartedEvent, HandlerTimeoutError, type HandlersOf, type IdentifierGenerator, InMemoryEventStore, type InMemoryEventStoreOptions, InMemoryTransaction, type InboundSubscriptionOptions, InvalidEnvelopeError, type InvalidMessageEvent, type InvalidTransportMessage, type JitterStrategy, LeaseLostError, type LeaseReference, LifecycleError, MAX_TIMER_DELAY_MS, type MatchingHandlers, type NewDelivery, type NoExtraHandlers, NonRetryableError, type OperationOutcome, type PartialHandlersOf, PayloadOf, type ProcessTraceInput, type PublishFinishedEvent, type PublishOneOptions, type PublishOptions, type PublishTarget, type PublishTraceInput, type PurgeRequest, type PurgeResult, type ReceiveFinishedEvent, type ReceiveOutcome, type ReceiveStatus, RelayBus, RelayBusError, type RelayBusLogger, type RelayBusObserver, type RelayBusOptions, type RelayBusTracer, type RetentionOptions, type RetryPolicy, type RetryPolicyOptions, type RouteOptions, type SendTraceInput, StandardSchemaV1, type StopOptions, type StopResult, type SubscribeCatalogOptions, type SubscribeOptions, TRACEPARENT_HEADER, TRACESTATE_HEADER, type TraceContext, type TransactionMode, TransactionRequiredError, TransactionTimeoutError, type Transport, type TransportMessage, type TransportMessageHandler, type TransportSentEvent, type TransportSubscriptionHooks, type UnroutedEventPolicy, type ValidationIssue, computeRetryDelay, consume, createRetryPolicy, createUuidV7, defineCatalog, defineHandlers, describeCatalog, isRetryableError, produce, toErrorInfo, toMilliseconds, traceContextOf };
975
+ export { AppendEntry, AppendResult, type BacklogEvent, type Catalog, type CatalogDeclaration, type CatalogDescription, type CatalogEntry, type CatalogEventClass, type CatalogEventName, type CatalogEventSelection, type CatalogEvents, CatalogPublisher, type CatalogRole, type ClaimFinishedEvent, ClaimRequest, ClaimedDelivery, Clock, DEFAULT_RETRY_POLICY, DEFAULT_ROUTE_RETRY_POLICY, type DefineCatalogOptions, type DeliveryKind, DeliveryQuery, DeliveryRecord, type DispatcherOptions, DomainEvent, Duration, ErrorInfo, EventClass, EventEnvelope, type EventHandler, EventHeaders, type EventOf, EventReference, EventStore, EventStoreStatistics, type FailureStage, type HandlerContext, type HandlerDescriptor, type HandlerFinishedEvent, type HandlerShapeOf, type HandlerStartedEvent, type HandlersOf, type IdentifierGenerator, InMemoryEventStore, type InMemoryEventStoreOptions, InMemoryTransaction, type InboundSubscriptionOptions, type InvalidMessageEvent, type JitterStrategy, LeaseReference, type MatchingHandlers, type NoExtraHandlers, type OperationOutcome, type PartialHandlersOf, PayloadOf, type ProcessTraceInput, type PublishFinishedEvent, type PublishOneOptions, type PublishOptions, type PublishTarget, type PublishTraceInput, PurgeRequest, PurgeResult, type ReceiveFinishedEvent, type ReceiveOutcome, type ReceiveStatus, RelayBus, type RelayBusLogger, type RelayBusObserver, type RelayBusOptions, type RelayBusTracer, type RetentionOptions, type RetryPolicy, type RetryPolicyOptions, type RouteOptions, type SendTraceInput, StandardSchemaV1, type StopOptions, type StopResult, type SubscribeCatalogOptions, type SubscribeOptions, TRACEPARENT_HEADER, TRACESTATE_HEADER, type TraceContext, type TransactionMode, Transport, type TransportSentEvent, type UnroutedEventPolicy, computeRetryDelay, consume, createRetryPolicy, createUuidV7, defineCatalog, defineHandlers, describeCatalog, isRetryableError, produce, traceContextOf };