@classytic/cart 0.2.1 → 1.0.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +75 -21
  3. package/dist/{cart-event-catalog-BxDJhtTM.d.mts → cart-event-catalog-Cokx0iOw.d.mts} +1 -2
  4. package/dist/cart.error-xi5OT4Sz.mjs +52 -0
  5. package/dist/{clock.port-CNu2wgdA.d.mts → clock.port-DrSBrsit.d.mts} +9 -5
  6. package/dist/{create-cart-BeW0xAqD.mjs → define-cart-BPq2kb_V.mjs} +344 -224
  7. package/dist/domain/errors/index.d.mts +2 -2
  8. package/dist/domain/errors/index.mjs +6 -6
  9. package/dist/domain/events/index.d.mts +2 -2
  10. package/dist/domain/events/index.mjs +2 -2
  11. package/dist/domain/index.d.mts +14 -11
  12. package/dist/domain/index.mjs +12 -12
  13. package/dist/domain/ports/index.d.mts +3 -3
  14. package/dist/domain/ports/index.mjs +1 -1
  15. package/dist/domain/saga/index.d.mts +1 -1
  16. package/dist/domain/saga/index.mjs +1 -1
  17. package/dist/engine/cart-config.schema.d.mts +3 -4
  18. package/dist/engine/cart-config.schema.mjs +7 -7
  19. package/dist/engine/index.d.mts +3 -3
  20. package/dist/engine/index.mjs +3 -3
  21. package/dist/{errors-7Pd0yATM.mjs → errors-Dj8itvAh.mjs} +1 -4
  22. package/dist/{id.port-BhbFZJPm.mjs → id.port-DYAnXbfV.mjs} +1 -1
  23. package/dist/{index-BB0XzkXF.d.mts → index-BTSo-RLv.d.mts} +41 -4
  24. package/dist/index.d.mts +75 -17
  25. package/dist/index.mjs +180 -15
  26. package/dist/{internal-event-bus-DhQKi9KS.d.mts → internal-event-bus-Bu7Xj7j6.d.mts} +203 -170
  27. package/dist/{kind-registry-DG2iCCH1.d.mts → kind-registry-DFvNDb81.d.mts} +3 -5
  28. package/dist/{kind-registry-Bvrj3P1Q.mjs → kind-registry-DQYqRQZU.mjs} +1 -1
  29. package/dist/{kind.error-DIaJpdUb.mjs → kind.error-BoyoVjKx.mjs} +1 -1
  30. package/dist/kinds/index.d.mts +1 -1
  31. package/dist/kinds/index.mjs +1 -1
  32. package/dist/{line-kind-B1mU1iJp.d.mts → line-kind-BW2zLNSr.d.mts} +3 -4
  33. package/dist/line-total-6VJQMjGV.mjs +24 -0
  34. package/dist/{outbox-store-CBt9fSYh.d.mts → outbox-store-Br7MHuOz.d.mts} +3 -18
  35. package/dist/{outbox-store-CWW8ppxS.mjs → outbox-store-DLxCPOUN.mjs} +2 -30
  36. package/dist/{reservation.entity-DLMxgpLE.d.mts → reservation.entity-BEeYbRUY.d.mts} +4 -5
  37. package/dist/{state-transition.error-2fRLh3p0.mjs → state-transition.error-BssJiRoW.mjs} +1 -1
  38. package/dist/{state-transitions-D19wZe-w.d.mts → state-transitions-BQ2Nhxnb.d.mts} +14 -11
  39. package/dist/{state-transitions-Defw8gAt.mjs → state-transitions-wunwhjap.mjs} +1 -1
  40. package/dist/{unmanaged-session.error-C9Z1Yh9j.mjs → unmanaged-session.error-DIRT2PR3.mjs} +31 -2
  41. package/dist/{variant.kind-q-yv-vnQ.d.mts → variant.kind-CClf8MTF.d.mts} +3 -3
  42. package/dist/{variant.kind-BHiivO9B.mjs → variant.kind-NmWSslu-.mjs} +23 -32
  43. package/package.json +10 -9
  44. package/dist/cart.error-BwWy4RlY.mjs +0 -27
  45. package/dist/index-2Ag-54t8.d.mts +0 -1
  46. /package/dist/{cart-status.vo-CNJw4aaB.d.mts → cart-status.vo-BoVPaSXX.d.mts} +0 -0
  47. /package/dist/{domain-event-CIEORKF6.mjs → domain-event-DBFsiHNJ.mjs} +0 -0
  48. /package/dist/{id.port-DitjeoHg.d.mts → id.port-DzgWy8sy.d.mts} +0 -0
  49. /package/dist/{idempotency-key.vo-D0lJsvGn.mjs → idempotency-key.vo-BoRvSIxx.mjs} +0 -0
@@ -1,14 +1,15 @@
1
- import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-CBt9fSYh.mjs";
2
- import { C as OperationContext, c as TaxBridge, d as InventoryBridge, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-CNu2wgdA.mjs";
3
- import { l as LineDisplay, r as LineKind } from "./line-kind-B1mU1iJp.mjs";
4
- import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-DG2iCCH1.mjs";
5
- import { t as IdPort } from "./id.port-DitjeoHg.mjs";
1
+ import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-Br7MHuOz.mjs";
2
+ import { C as OperationContext, c as TaxBridge, d as InventoryBridge, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-DrSBrsit.mjs";
3
+ import { l as LineDisplay, r as LineKind } from "./line-kind-BW2zLNSr.mjs";
4
+ import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-DFvNDb81.mjs";
5
+ import { t as IdPort } from "./id.port-DzgWy8sy.mjs";
6
6
  import { CartConfigShape } from "./engine/cart-config.schema.mjs";
7
7
  import { Money } from "@classytic/primitives/money";
8
- import { DomainEvent, EventHandler, EventTransport, PublishManyResult } from "@classytic/primitives/events";
9
- import { PluginType, Repository } from "@classytic/mongokit";
10
- import { Connection, Document, Model, Types } from "mongoose";
11
-
8
+ import { EventTransport } from "@classytic/primitives/events";
9
+ import { ModelBlueprint, PluginType, Repository } from "@classytic/mongokit";
10
+ import { CurrencyCode } from "@classytic/primitives/currency";
11
+ import { Connection, Document, Model, Schema, Types } from "mongoose";
12
+ import { InProcessEventBus } from "@classytic/primitives/event-infra";
12
13
  //#region src/models/checkout.model.d.ts
13
14
  /**
14
15
  * CheckoutDocument — locked snapshot with a minimal state field.
@@ -27,7 +28,14 @@ interface CheckoutDocument extends Document {
27
28
  flowState: Record<string, unknown>;
28
29
  lines: Array<Record<string, unknown>>;
29
30
  adjustments: Array<Record<string, unknown>>;
30
- currency: string;
31
+ /**
32
+ * Branded {@link CurrencyCode}. The brand is EARNED by the schema path
33
+ * below: `match: [CURRENCY_PATTERN]` + `uppercase` + `required` is exactly
34
+ * the predicate `toCurrencyCode` applies, so nothing invalid can be
35
+ * persisted through this model. If that validator is ever removed, this
36
+ * type becomes a lie — they are one mechanism, keep them together.
37
+ */
38
+ currency: CurrencyCode;
31
39
  pricing: Record<string, unknown>;
32
40
  externalRef?: string | null;
33
41
  canceledReason?: string | null;
@@ -37,9 +45,11 @@ interface CheckoutDocument extends Document {
37
45
  createdAt: Date;
38
46
  updatedAt: Date;
39
47
  }
40
- declare function createCheckoutModel(connection: Connection, opts?: {
41
- collectionPrefix?: string | undefined;
42
- }): Model<CheckoutDocument>;
48
+ /**
49
+ * Build the Checkout schema — pure, connection-free. Registration + collection
50
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
51
+ */
52
+ declare function buildCheckoutSchema(): Schema<CheckoutDocument>;
43
53
  //#endregion
44
54
  //#region src/models/draft.model.d.ts
45
55
  /**
@@ -58,7 +68,14 @@ interface DraftDocument extends Document {
58
68
  status: 'active' | 'abandoned' | 'converted' | 'expired';
59
69
  lines: Array<Record<string, unknown>>;
60
70
  adjustments: Array<Record<string, unknown>>;
61
- currency: string;
71
+ /**
72
+ * Branded {@link CurrencyCode}. The brand is EARNED by the schema path
73
+ * below: `match: [CURRENCY_PATTERN]` + `uppercase` + `required` is exactly
74
+ * the predicate `toCurrencyCode` applies, so nothing invalid can be
75
+ * persisted through this model. If that validator is ever removed, this
76
+ * type becomes a lie — they are one mechanism, keep them together.
77
+ */
78
+ currency: CurrencyCode;
62
79
  pricing: Record<string, unknown> | null;
63
80
  version: number;
64
81
  expiresAt?: Date | null;
@@ -68,9 +85,11 @@ interface DraftDocument extends Document {
68
85
  createdAt: Date;
69
86
  updatedAt: Date;
70
87
  }
71
- declare function createDraftModel(connection: Connection, opts?: {
72
- collectionPrefix?: string | undefined;
73
- }): Model<DraftDocument>;
88
+ /**
89
+ * Build the Draft schema — pure, connection-free. Registration + collection
90
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
91
+ */
92
+ declare function buildDraftSchema(): Schema<DraftDocument>;
74
93
  //#endregion
75
94
  //#region src/models/idempotency.model.d.ts
76
95
  /**
@@ -100,9 +119,11 @@ interface IdempotencyDocument extends Document {
100
119
  createdAt: Date;
101
120
  completedAt?: Date | null;
102
121
  }
103
- declare function createIdempotencyModel(connection: Connection, opts?: {
104
- collectionPrefix?: string | undefined;
105
- }): Model<IdempotencyDocument>;
122
+ /**
123
+ * Build the Idempotency schema — pure, connection-free. Registration + collection
124
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
125
+ */
126
+ declare function buildIdempotencySchema(): Schema<IdempotencyDocument>;
106
127
  //#endregion
107
128
  //#region src/models/reservation.model.d.ts
108
129
  /**
@@ -133,14 +154,16 @@ interface ReservationDocument extends Document {
133
154
  createdAt: Date;
134
155
  updatedAt: Date;
135
156
  }
136
- declare function createReservationModel(connection: Connection, opts?: {
137
- collectionPrefix?: string | undefined;
138
- }): Model<ReservationDocument>;
157
+ /**
158
+ * Build the Reservation schema — pure, connection-free. Registration + collection
159
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
160
+ */
161
+ declare function buildReservationSchema(): Schema<ReservationDocument>;
139
162
  //#endregion
140
163
  //#region src/models/index.d.ts
141
164
  /** Union of all cart model names used as keys in `CartModels`. */
142
165
  type CartModelName = 'Draft' | 'Checkout' | 'Reservation' | 'Idempotency';
143
- interface CreateCartModelsOptions {
166
+ interface DefineCartModelsConfig {
144
167
  tenantFieldType?: 'objectId' | 'string';
145
168
  multiTenant?: boolean;
146
169
  autoIndex?: boolean | Partial<Record<CartModelName, boolean>>;
@@ -152,19 +175,19 @@ interface CreateCartModelsOptions {
152
175
  */
153
176
  collectionPrefix?: string | undefined;
154
177
  /**
155
- * When true, existing Mongoose models with this package's names are deleted
156
- * from the connection before re-registering. Hot-reload / test fixtures
157
- * only. Default `false` — collision throws `CartModelCollisionError`.
158
- * See PACKAGE_RULES.md §21.
178
+ * On a model-name collision: default (`false`) throws mongokit's
179
+ * `ModelCollisionError`; `true` re-registers (test/dev fixtures only). Maps
180
+ * to mongokit's `replace` policy, which itself throws under
181
+ * `NODE_ENV=production`. See PACKAGE_RULES.md §21.
159
182
  */
160
183
  forceRecreate?: boolean;
161
184
  }
162
185
  /**
163
- * CartModels — the bundle returned by `createCartModels()`.
186
+ * CartModels — the typed bundle a bound blueprint assembles.
164
187
  *
165
- * Every model is scoped to the supplied `Connection`, so engines bound to
188
+ * Every model is scoped to the supplied `Connection`, so blueprints bound to
166
189
  * different Mongoose connections get their own model instances without
167
- * collisions. This mirrors the @classytic/catalog pattern exactly.
190
+ * collisions.
168
191
  */
169
192
  interface CartModels {
170
193
  Draft: Model<DraftDocument>;
@@ -172,7 +195,11 @@ interface CartModels {
172
195
  Reservation: Model<ReservationDocument>;
173
196
  Idempotency: Model<IdempotencyDocument>;
174
197
  }
175
- declare function createCartModels(connection: Connection, options?: CreateCartModelsOptions): CartModels;
198
+ /**
199
+ * Describe the cart model set as a connection-free blueprint. Pure — builds no
200
+ * schema and registers nothing until `.bind(connection)`.
201
+ */
202
+ declare function defineCartModels(config?: DefineCartModelsConfig): ModelBlueprint<CartModels>;
176
203
  //#endregion
177
204
  //#region src/engine/cart-event-publisher.d.ts
178
205
  interface EmitOptions {
@@ -203,7 +230,7 @@ interface DraftRepositoryDeps {
203
230
  bridges: CartBridges;
204
231
  clock: ClockPort;
205
232
  id: IdPort;
206
- defaultCurrency: string;
233
+ defaultCurrency: CurrencyCode;
207
234
  eventPublisher: CartEventPublisher;
208
235
  }
209
236
  /**
@@ -506,7 +533,6 @@ declare class IdempotencyRepository extends Repository<IdempotencyDocument> {
506
533
  * sweeper drives the active release loop via `findExpiredHeld`.
507
534
  */
508
535
  declare class ReservationRepository extends Repository<ReservationDocument> {
509
- constructor(model: Model<ReservationDocument>, plugins: PluginType[]);
510
536
  /** All reservations belonging to a checkout. */
511
537
  findByCheckout(checkoutId: Types.ObjectId | string, ctx: OperationContext): Promise<ReservationDocument[]>;
512
538
  /**
@@ -553,7 +579,8 @@ interface CreateCartRepositoriesConfig {
553
579
  bridges: CartBridges;
554
580
  clock: ClockPort;
555
581
  id: IdPort;
556
- defaultCurrency: string;
582
+ /** Validated + branded once at the config edge in `defineCart`. */
583
+ defaultCurrency: CurrencyCode;
557
584
  events: EventTransport;
558
585
  tenantFieldType?: 'objectId' | 'string';
559
586
  /**
@@ -589,196 +616,202 @@ interface CartBridges {
589
616
  tax?: TaxBridge | undefined;
590
617
  shipping?: ShippingBridge | undefined;
591
618
  }
619
+ /** Minimal logger surface cart uses (post-commit publish failures). */
620
+ interface CartLogger {
621
+ error(message: string, ...args: unknown[]): void;
622
+ }
592
623
  /**
593
- * CartConfig — the single argument to `createCart()`.
624
+ * DESCRIBE-time shape — everything that determines the persistence SHAPE or the
625
+ * immutable domain configuration and needs no connection or I/O to inspect.
626
+ * Nothing here opens a socket or reads a secret. Passed to `defineCart(shape)`
627
+ * (and `createCartDomain(shape)` for the connectionless domain-only surface).
594
628
  */
595
- interface CartConfig extends Partial<CartConfigShape> {
596
- /**
597
- * Mongoose connection. Required when the engine will create
598
- * models/repositories. Scenario tests that only exercise the LineKind
599
- * contract can pass a placeholder — the engine detects whether the
600
- * connection is a real Mongoose instance and skips model creation if
601
- * not, staying in `phase: 'contracts'`.
602
- */
603
- connection: Connection;
629
+ interface CartShape extends Partial<CartConfigShape> {
604
630
  /** LineKinds to register. At least one required. */
605
631
  kinds: readonly LineKind[];
606
- /** External-domain bridges. Only `catalog` is required. */
607
- bridges: CartBridges;
608
632
  /**
609
- * Optional host-supplied event transport. Default: `InProcessCartEventBus`.
610
- *
611
- * **Structurally compatible with Arc's `EventTransport`** — pass Arc's
612
- * Redis / Kafka / Outbox transport directly, zero adapter needed:
613
- *
614
- * ```ts
615
- * import { RedisEventTransport } from '@classytic/arc/events';
616
- * const cart = await createCart({ eventTransport: new RedisEventTransport(ioredis), ... });
617
- * ```
618
- */
619
- eventTransport?: EventTransport | undefined;
620
- /** Optional clock override. Default: `systemClock`. */
621
- clock?: ClockPort | undefined;
622
- /**
623
- * Optional id generator. Default: `cryptoIdPort`. Override for
624
- * deterministic tests, Temporal workflow replay safety, or host-
625
- * specific id formats.
626
- */
627
- id?: IdPort | undefined;
628
- /**
629
- * Optional host-owned durable outbox store.
633
+ * Whether cart is branch/tenant-scoped. Default `true`.
630
634
  *
631
- * Cart no longer provisions its own Mongo outbox by default. Hosts that
632
- * need durable event persistence should inject their app-level outbox store
633
- * here. When omitted, cart still publishes to `eventTransport`, but
634
- * session-bound writes cannot persist events durably.
635
- */
636
- outbox?: OutboxStore | undefined;
637
- /**
638
- * Optional per-repository plugin bundle.
635
+ * - `true` (default): `organizationId` is required on every document and
636
+ * prepended to every index. Use for multi-tenant SaaS or branch-scoped
637
+ * cart stacks (POS-first, etc.).
638
+ * - `false`: `organizationId` is left optional and excluded from indexes.
639
+ * Use when cart is company-wide — a customer's cart follows them across
640
+ * branches and no tenant filter applies.
639
641
  */
640
- repositoryPlugins?: CartRepositoryPluginBundle | undefined;
642
+ multiTenant?: boolean | undefined;
641
643
  /**
642
644
  * Mongoose schema type for the `organizationId` field on all models.
643
645
  *
644
646
  * - `'objectId'` (default): `Schema.Types.ObjectId` + `ref: 'organization'`
645
647
  * - `'string'`: plain `String` — for UUID/slug-based auth
646
- *
647
- * Passed to model factories (schema) and multiTenantPlugin (query casting).
648
648
  */
649
649
  tenantFieldType?: 'objectId' | 'string' | undefined;
650
- /**
651
- * Whether cart is branch/tenant-scoped. Default `true`.
652
- *
653
- * - `true` (default): `organizationId` is required on every document and
654
- * prepended to every index. Use for multi-tenant SaaS or
655
- * branch-scoped cart stacks (POS-first, etc.).
656
- * - `false`: `organizationId` is left optional and excluded from indexes.
657
- * Use when cart is company-wide — a customer's cart follows them across
658
- * branches and no tenant filter applies.
659
- */
660
- multiTenant?: boolean | undefined;
661
650
  /**
662
651
  * Control Mongoose `autoIndex` per model or globally.
663
652
  *
664
653
  * - `true` / `false` — applied to every cart model.
665
654
  * - `Partial<Record<CartModelName, boolean>>` — per-model override.
666
655
  * - `undefined` (default) — leave Mongoose defaults untouched.
667
- *
668
- * Mongoose 9 defers `Model.init()` until the first query, so setting
669
- * `schema.autoIndex` after `connection.model()` is safe.
670
656
  */
671
- autoIndex?: CreateCartModelsOptions['autoIndex'] | undefined;
657
+ autoIndex?: DefineCartModelsConfig['autoIndex'] | undefined;
672
658
  /**
673
659
  * Optional prefix prepended to every physical collection this package
674
- * creates (see PACKAGE_RULES.md §20.1). Unset → default names
675
- * (`cart_drafts`, `cart_checkouts`, `cart_reservations`,
676
- * `cart_idempotency`). Set e.g. `'commerce_'` to get `commerce_cart_drafts`,
677
- * etc. Model names and `ref:` populate are unaffected.
660
+ * creates (see PACKAGE_RULES.md §20.1). Unset → default names.
678
661
  */
679
662
  collectionPrefix?: string | undefined;
680
663
  /**
681
- * When true, existing Mongoose models with cart's names are deleted from
682
- * the connection before re-registering. Hot-reload / test fixtures only.
683
- * Default `false` — collision throws `CartModelCollisionError`. Hosts
684
- * that need two cart engines should use two Mongoose connections
685
- * (`mongoose.createConnection(...)`). See PACKAGE_RULES.md §21.
664
+ * When true, existing Mongoose models with cart's names are deleted from the
665
+ * connection before re-registering. Hot-reload / test fixtures only. Default
666
+ * `false` — collision throws mongokit's `ModelCollisionError`. Hosts that need
667
+ * two cart engines should use two Mongoose connections.
686
668
  */
687
669
  forceRecreate?: boolean | undefined;
670
+ }
671
+ /**
672
+ * BIND-time runtime collaborators — the live connection is the first `bind`
673
+ * arg; these are the rest. Provider clients, transports, loggers and bridges
674
+ * belong here, not in the shape.
675
+ */
676
+ interface CartRuntime {
677
+ /** External-domain bridges. Only `catalog` is required. */
678
+ bridges: CartBridges;
688
679
  /**
689
- * Allow `engine.withTransaction` to fall back to non-transactional
690
- * execution on standalone Mongo (local dev). Partial-write risk across
691
- * the wrapped writes — explicit opt-in only.
680
+ * Optional host-supplied event transport. Default: `InProcessCartEventBus`.
681
+ * Structurally compatible with Arc's `EventTransport` — pass Arc's transport
682
+ * directly, zero adapter needed. A SUPPLIED transport is never closed by
683
+ * `engine.close()` (shared host infrastructure).
684
+ */
685
+ eventTransport?: EventTransport | undefined;
686
+ /**
687
+ * Optional host-owned durable outbox store. When omitted, cart still
688
+ * publishes to `eventTransport`, but session-bound writes cannot persist
689
+ * events durably.
690
+ *
691
+ * A supplied store MUST declare `transactionalSave: true` — cart saves the event
692
+ * row under `ctx.session`, and `OutboxWriteOptions.session` is best-effort by
693
+ * contract, so only the store can promise it commits with the write. `bind`
694
+ * refuses one that does not; `MemoryOutboxStore` correctly does not declare it
695
+ * (an in-memory row survives a rollback), so tests that need one wire a
696
+ * session-honouring double instead.
697
+ */
698
+ outbox?: OutboxStore | undefined;
699
+ /** Optional clock override. Default: `systemClock`. */
700
+ clock?: ClockPort | undefined;
701
+ /** Optional id generator. Default: `cryptoIdPort`. */
702
+ id?: IdPort | undefined;
703
+ /** Optional logger for post-commit publish failures. Default: `console`. */
704
+ logger?: CartLogger | undefined;
705
+ /** Optional per-repository plugin bundle appended after cart's defaults. */
706
+ repositoryPlugins?: CartRepositoryPluginBundle | undefined;
707
+ /**
708
+ * Allow `engine.withTransaction` to fall back to non-transactional execution
709
+ * on standalone Mongo (local dev). Partial-write risk — explicit opt-in only.
692
710
  */
693
711
  allowNonTransactional?: boolean | undefined;
694
712
  }
713
+ /** Resolved configuration captured on the bound engine (frozen). */
714
+ interface ResolvedCartConfig {
715
+ multiTenant: boolean;
716
+ tenantFieldType: 'objectId' | 'string';
717
+ forceRecreate: boolean;
718
+ /** Validated + branded once at the config edge in `defineCart`. */
719
+ defaultCurrency: CurrencyCode;
720
+ collectionPrefix?: string;
721
+ allowNonTransactional: boolean;
722
+ staleOpenCheckoutMs?: number;
723
+ }
695
724
  /**
696
- * CartEngine — the result of `createCart()`.
725
+ * CartDomain — the connectionless, domain-only surface (STANDARDIZATION-PLAN
726
+ * §Phase 5). Kinds/events/clock/id WITHOUT persistence: no models, no
727
+ * repositories, no `withTransaction`. Use it to exercise the LineKind contract
728
+ * or emit events without a Mongoose connection. For persistence use
729
+ * `defineCart(shape).bind(connection, runtime)`.
730
+ */
731
+ interface CartDomain {
732
+ /** Registered LineKinds. */
733
+ readonly kinds: KindRegistry;
734
+ /** Event transport — host-supplied or the default `InProcessCartEventBus`. */
735
+ readonly events: EventTransport;
736
+ /** Clock source. */
737
+ readonly clock: ClockPort;
738
+ /** Id generator. */
739
+ readonly id: IdPort;
740
+ /** Release resources owned by this domain (only a self-created bus). Idempotent. */
741
+ close(): Promise<void>;
742
+ }
743
+ /**
744
+ * CartEngine — the frozen result of `defineCart(shape).bind(connection, runtime)`.
697
745
  */
698
746
  interface CartEngine {
699
- readonly config: Readonly<CartConfig>;
747
+ /** Resolved configuration (frozen). */
748
+ readonly config: Readonly<ResolvedCartConfig>;
700
749
  /** Registered LineKinds. */
701
750
  readonly kinds: KindRegistry;
702
- /**
703
- * Event transport — host-supplied or the default `InProcessCartEventBus`.
704
- *
705
- * ```ts
706
- * // Subscribe to all cart events via glob
707
- * await cart.events.subscribe?.('cart.*', async (event) => {
708
- * console.log(event.type, event.meta.organizationId);
709
- * });
710
- * ```
711
- */
751
+ /** Event transport — host-supplied or the default `InProcessCartEventBus`. */
712
752
  readonly events: EventTransport;
713
753
  /** Clock source. */
714
754
  readonly clock: ClockPort;
715
755
  /** Id generator. */
716
756
  readonly id: IdPort;
757
+ /** Mongoose models bound to the supplied connection. */
758
+ readonly models: CartModels;
717
759
  /**
718
- * Mongoose models bound to the engine's connection. Empty in
719
- * contracts-only mode.
720
- */
721
- readonly models: CartModels | Record<string, never>;
722
- /**
723
- * mongokit repositories — the primary CRUD + domain API. All domain
724
- * logic (addItem, checkout, commit, cancel) lives directly on the
725
- * repository classes. Empty in contracts-only mode.
726
- */
727
- readonly repositories: CartRepositories | Record<string, never>;
728
- /**
729
- * `'lite'` — no real Mongoose connection; kinds/events/clock/id are
730
- * populated but models/repositories are empty. Used by scenario tests
731
- * that only exercise the LineKind contract.
732
- *
733
- * `'full'` — real Mongoose connection detected; models and
734
- * repositories are populated.
760
+ * mongokit repositories — the primary CRUD + domain API. All domain logic
761
+ * (addItem, checkout, commit, cancel) lives directly on the repository classes.
735
762
  */
736
- readonly mode: 'lite' | 'full';
763
+ readonly repositories: CartRepositories;
737
764
  /**
738
765
  * Run cart writes in one atomic unit-of-work: transaction + post-commit
739
766
  * event publish. Events emitted inside the unit are queued and flushed to
740
- * the in-process transport only AFTER commit — a rollback can't leak
741
- * ghost events. Outbox rows (when wired) commit with the transaction.
742
- *
743
- * ```ts
744
- * await cart.withTransaction(ctx, (txCtx) =>
745
- * cart.repositories.checkout.createFromDraft(input, txCtx));
746
- * ```
747
- *
748
- * Full mode only — throws in `'lite'` mode (no real connection).
767
+ * the transport only AFTER commit — a rollback can't leak ghost events.
749
768
  */
750
769
  withTransaction<T>(ctx: OperationContext, body: (txCtx: OperationContext) => Promise<T>): Promise<T>;
751
- /**
752
- * Explicitly create indexes on all cart models.
753
- *
754
- * Useful when `autoIndex` is disabled in production — call once during
755
- * deployment or migration scripts.
756
- */
770
+ /** Build/align indexes. Call once per deploy when booted `autoIndex: false`. */
757
771
  syncIndexes(): Promise<void>;
758
- /** Shut down cleanly. */
759
- destroy(): Promise<void>;
772
+ /** Release resources owned by this engine (only a self-created bus). Idempotent. */
773
+ close(): Promise<void>;
760
774
  }
761
775
  //#endregion
762
- //#region src/engine/create-cart.d.ts
776
+ //#region src/engine/define-cart.d.ts
777
+ interface CartBlueprint {
778
+ readonly id: 'cart';
779
+ /** The model names this blueprint registers — known without a connection. */
780
+ readonly modelNames: readonly string[];
781
+ /**
782
+ * Compile + register the models on `connection`, wire the engine, verify
783
+ * capabilities. `bind` MAY be async (the `KernelBlueprint` contract permits
784
+ * it); cart's construction is synchronous today.
785
+ */
786
+ bind(connection: Connection, runtime: CartRuntime): CartEngine;
787
+ }
763
788
  /**
764
- * createCart() — build a cart engine.
765
- *
766
- * Repositories are the primary API. All domain logic (addItem, checkout,
767
- * commit, cancel) lives directly on the repository classes. Multi-tenant
768
- * scoping and `publicId` generation are handled by mongokit plugins wired
769
- * inside `createCartRepositories`, so callers just pass the connection
770
- * and bridges.
789
+ * Describe the cart engine. Pure — registers no model, builds no schema,
790
+ * performs no I/O.
791
+ */
792
+ declare function defineCart(shape: CartShape): CartBlueprint;
793
+ /**
794
+ * Domain-only runtime — the subset of collaborators the connectionless surface
795
+ * can use. No bridges, connection, outbox or plugins (those need persistence).
771
796
  */
772
- declare function createCart(config: CartConfig): Promise<CartEngine>;
797
+ interface CartDomainRuntime {
798
+ eventTransport?: EventTransport | undefined;
799
+ clock?: ClockPort | undefined;
800
+ id?: IdPort | undefined;
801
+ }
802
+ /**
803
+ * `createCartDomain(shape, runtime?)` — the EXPLICIT connectionless domain-only
804
+ * surface (STANDARDIZATION-PLAN §Phase 5). Builds the kind registry, event
805
+ * transport, clock and id WITHOUT touching a connection, registering a model,
806
+ * or wiring a repository. Use it to exercise the LineKind contract or emit
807
+ * events without persistence. It is NOT a degraded engine — it deliberately
808
+ * exposes no `models`/`repositories`/`withTransaction`.
809
+ */
810
+ declare function createCartDomain(shape: CartShape, runtime?: CartDomainRuntime): CartDomain;
773
811
  //#endregion
774
812
  //#region src/engine/internal-event-bus.d.ts
775
- declare class InProcessCartEventBus implements EventTransport {
776
- readonly name = "in-process-cart";
777
- private subs;
778
- publish(event: DomainEvent): Promise<void>;
779
- publishMany(events: readonly DomainEvent[]): Promise<PublishManyResult>;
780
- subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
781
- close(): Promise<void>;
813
+ declare class InProcessCartEventBus extends InProcessEventBus {
814
+ constructor();
782
815
  }
783
816
  //#endregion
784
- export { createReservationModel as C, createDraftModel as D, DraftDocument as E, CheckoutDocument as O, ReservationDocument as S, createIdempotencyModel as T, CartEventPublisherDeps as _, CartEngine as a, CreateCartModelsOptions as b, CreateCartRepositoriesConfig as c, IdempotencyRepository as d, CheckoutRepository as f, DraftRepositoryDeps as g, DraftRepository as h, CartConfig as i, createCheckoutModel as k, createCartRepositories as l, DEFAULT_STALE_OPEN_CHECKOUT_MS as m, createCart as n, CartRepositories as o, CheckoutRepositoryDeps as p, CartBridges as r, CartRepositoryPluginBundle as s, InProcessCartEventBus as t, ReservationRepository as u, CartModelName as v, IdempotencyDocument as w, createCartModels as x, CartModels as y };
817
+ export { buildReservationSchema as A, DraftRepositoryDeps as C, DefineCartModelsConfig as D, CartModels as E, CheckoutDocument as F, buildCheckoutSchema as I, buildIdempotencySchema as M, DraftDocument as N, defineCartModels as O, buildDraftSchema as P, DraftRepository as S, CartModelName as T, ReservationRepository as _, defineCart as a, CheckoutRepositoryDeps as b, CartEngine as c, CartShape as d, ResolvedCartConfig as f, createCartRepositories as g, CreateCartRepositoriesConfig as h, createCartDomain as i, IdempotencyDocument as j, ReservationDocument as k, CartLogger as l, CartRepositoryPluginBundle as m, CartBlueprint as n, CartBridges as o, CartRepositories as p, CartDomainRuntime as r, CartDomain as s, InProcessCartEventBus as t, CartRuntime as u, IdempotencyRepository as v, CartEventPublisherDeps as w, DEFAULT_STALE_OPEN_CHECKOUT_MS as x, CheckoutRepository as y };
@@ -1,7 +1,5 @@
1
- import { l as LineDisplay, r as LineKind } from "./line-kind-B1mU1iJp.mjs";
2
- import * as _$_classytic_primitives_money0 from "@classytic/primitives/money";
1
+ import { l as LineDisplay, r as LineKind } from "./line-kind-BW2zLNSr.mjs";
3
2
  import { Money } from "@classytic/primitives/money";
4
-
5
3
  //#region src/domain/entities/line-item.entity.d.ts
6
4
  /**
7
5
  * LineItem — a single row inside a Draft or Checkout.
@@ -38,7 +36,7 @@ interface LineItem<TPayload = unknown> {
38
36
  * special-deal flows. Kinds that honor overrides do so in their price()
39
37
  * implementation; kinds that reject overrides throw KindError.
40
38
  */
41
- overrideUnitPrice?: _$_classytic_primitives_money0.Money;
39
+ overrideUnitPrice?: import('@classytic/primitives/money').Money;
42
40
  /**
43
41
  * Denormalized display snapshot for UI rendering. Populated by the
44
42
  * kind's `displayOf()` method at add-time. Kept fresh via
@@ -129,7 +127,7 @@ interface TotalsSnapshot {
129
127
  /**
130
128
  * KindRegistry — the engine's lookup table of registered LineKinds.
131
129
  *
132
- * Built once at `createCart()` time from `config.kinds` and treated as
130
+ * Built once at `defineCart()` time from `shape.kinds` and treated as
133
131
  * immutable thereafter. Looking up an unknown kind throws UnknownKindError.
134
132
  *
135
133
  * Not a class — a frozen object literal — so it can be tree-shaken and so
@@ -1,4 +1,4 @@
1
- import { n as UnknownKindError } from "./kind.error-DIaJpdUb.mjs";
1
+ import { n as UnknownKindError } from "./kind.error-BoyoVjKx.mjs";
2
2
  //#region src/domain/kinds/kind-registry.ts
3
3
  /**
4
4
  * Build a KindRegistry from a list of LineKind implementations.
@@ -1,4 +1,4 @@
1
- import { t as CartError } from "./cart.error-BwWy4RlY.mjs";
1
+ import { t as CartError } from "./cart.error-xi5OT4Sz.mjs";
2
2
  //#region src/domain/errors/kind.error.ts
3
3
  /**
4
4
  * A LineKind rejected a line during validate() or price().
@@ -1,2 +1,2 @@
1
- import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "../variant.kind-q-yv-vnQ.mjs";
1
+ import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "../variant.kind-CClf8MTF.mjs";
2
2
  export { type BundleComponent, type BundlePayload, type ServiceFeePayload, type SkuPayload, type TimeslotPayload, type VariantPayload, bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
@@ -1,2 +1,2 @@
1
- import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "../variant.kind-BHiivO9B.mjs";
1
+ import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "../variant.kind-NmWSslu-.mjs";
2
2
  export { bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
@@ -1,7 +1,6 @@
1
- import { C as OperationContext, T as PricedLine, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-CNu2wgdA.mjs";
1
+ import { C as OperationContext, T as PricedLine, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-DrSBrsit.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  import { z } from "zod";
4
-
5
4
  //#region src/domain/value-objects/line-display.vo.d.ts
6
5
  /**
7
6
  * LineDisplay — the denormalized snapshot stored on each cart line for
@@ -193,7 +192,7 @@ interface KindContext extends OperationContext {
193
192
  */
194
193
  readonly clock?: ClockPort;
195
194
  /**
196
- * Bridge registry. Keys match the bridge names in CartConfig. Values are
195
+ * Bridge registry. Keys match the bridge names in CartRuntime.bridges. Values are
197
196
  * typed via the interface augmentation in `engine-types.ts`.
198
197
  */
199
198
  readonly bridges: KindBridges;
@@ -203,7 +202,7 @@ interface KindContext extends OperationContext {
203
202
  * than a typed interface so custom kinds can access host-registered bridges
204
203
  * via string keys without forcing every kind to know the full bridge surface.
205
204
  *
206
- * The engine populates this at construction time from CartConfig.bridges.
205
+ * The engine populates this at bind time from CartRuntime.bridges.
207
206
  */
208
207
  interface KindBridges {
209
208
  readonly catalog: CatalogBridge;
@@ -0,0 +1,24 @@
1
+ //#region src/domain/value-objects/line-total.ts
2
+ /**
3
+ * Multiply a unit price by a line quantity, guarding the safe-integer range.
4
+ *
5
+ * Minor-unit money must stay within `Number.MAX_SAFE_INTEGER` — past 2^53 the
6
+ * multiplication silently loses precision, which is worse than failing loud.
7
+ * Both the fresh `kind.price()` path and the incremental reprice path
8
+ * (`rebuildSubtotals`) route their `unitPrice × quantity` through here, so a
9
+ * huge quantity throws on the FIRST add, not only when a later reprice happens
10
+ * to re-multiply it.
11
+ *
12
+ * Throws `RangeError` (same shape/message as the pre-existing reprice guard)
13
+ * so both paths fail identically.
14
+ */
15
+ function lineTotal(unitPrice, quantity) {
16
+ const amount = unitPrice.amount * quantity;
17
+ if (!Number.isSafeInteger(amount)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${quantity} exceeds Number.MAX_SAFE_INTEGER`);
18
+ return {
19
+ amount,
20
+ currency: unitPrice.currency
21
+ };
22
+ }
23
+ //#endregion
24
+ export { lineTotal as t };