@classytic/cart 0.3.1 → 1.1.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 +188 -147
  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-zgAh3UVt.mjs → define-cart-Cr9VMeVc.mjs} +362 -236
  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-BNPgUilS.mjs → errors-Dj8itvAh.mjs} +1 -1
  22. package/dist/{id.port-BhbFZJPm.mjs → id.port-DYAnXbfV.mjs} +1 -1
  23. package/dist/{index-wh5Q7UY1.d.mts → index-BTSo-RLv.d.mts} +41 -3
  24. package/dist/index.d.mts +88 -24
  25. package/dist/index.mjs +195 -14
  26. package/dist/{internal-event-bus-DFcwV79F.d.mts → internal-event-bus-BA-WrtE0.d.mts} +200 -179
  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,16 @@
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 { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
13
+ import { InProcessEventBus } from "@classytic/primitives/event-infra";
12
14
  //#region src/models/checkout.model.d.ts
13
15
  /**
14
16
  * CheckoutDocument — locked snapshot with a minimal state field.
@@ -27,7 +29,14 @@ interface CheckoutDocument extends Document {
27
29
  flowState: Record<string, unknown>;
28
30
  lines: Array<Record<string, unknown>>;
29
31
  adjustments: Array<Record<string, unknown>>;
30
- currency: string;
32
+ /**
33
+ * Branded {@link CurrencyCode}. The brand is EARNED by the schema path
34
+ * below: `match: [CURRENCY_PATTERN]` + `uppercase` + `required` is exactly
35
+ * the predicate `toCurrencyCode` applies, so nothing invalid can be
36
+ * persisted through this model. If that validator is ever removed, this
37
+ * type becomes a lie — they are one mechanism, keep them together.
38
+ */
39
+ currency: CurrencyCode;
31
40
  pricing: Record<string, unknown>;
32
41
  externalRef?: string | null;
33
42
  canceledReason?: string | null;
@@ -37,9 +46,11 @@ interface CheckoutDocument extends Document {
37
46
  createdAt: Date;
38
47
  updatedAt: Date;
39
48
  }
40
- declare function createCheckoutModel(connection: Connection, opts?: {
41
- collectionPrefix?: string | undefined;
42
- }): Model<CheckoutDocument>;
49
+ /**
50
+ * Build the Checkout schema — pure, connection-free. Registration + collection
51
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
52
+ */
53
+ declare function buildCheckoutSchema(): Schema<CheckoutDocument>;
43
54
  //#endregion
44
55
  //#region src/models/draft.model.d.ts
45
56
  /**
@@ -58,7 +69,14 @@ interface DraftDocument extends Document {
58
69
  status: 'active' | 'abandoned' | 'converted' | 'expired';
59
70
  lines: Array<Record<string, unknown>>;
60
71
  adjustments: Array<Record<string, unknown>>;
61
- currency: string;
72
+ /**
73
+ * Branded {@link CurrencyCode}. The brand is EARNED by the schema path
74
+ * below: `match: [CURRENCY_PATTERN]` + `uppercase` + `required` is exactly
75
+ * the predicate `toCurrencyCode` applies, so nothing invalid can be
76
+ * persisted through this model. If that validator is ever removed, this
77
+ * type becomes a lie — they are one mechanism, keep them together.
78
+ */
79
+ currency: CurrencyCode;
62
80
  pricing: Record<string, unknown> | null;
63
81
  version: number;
64
82
  expiresAt?: Date | null;
@@ -68,9 +86,11 @@ interface DraftDocument extends Document {
68
86
  createdAt: Date;
69
87
  updatedAt: Date;
70
88
  }
71
- declare function createDraftModel(connection: Connection, opts?: {
72
- collectionPrefix?: string | undefined;
73
- }): Model<DraftDocument>;
89
+ /**
90
+ * Build the Draft schema — pure, connection-free. Registration + collection
91
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
92
+ */
93
+ declare function buildDraftSchema(): Schema<DraftDocument>;
74
94
  //#endregion
75
95
  //#region src/models/idempotency.model.d.ts
76
96
  /**
@@ -100,9 +120,11 @@ interface IdempotencyDocument extends Document {
100
120
  createdAt: Date;
101
121
  completedAt?: Date | null;
102
122
  }
103
- declare function createIdempotencyModel(connection: Connection, opts?: {
104
- collectionPrefix?: string | undefined;
105
- }): Model<IdempotencyDocument>;
123
+ /**
124
+ * Build the Idempotency schema — pure, connection-free. Registration + collection
125
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
126
+ */
127
+ declare function buildIdempotencySchema(): Schema<IdempotencyDocument>;
106
128
  //#endregion
107
129
  //#region src/models/reservation.model.d.ts
108
130
  /**
@@ -133,16 +155,17 @@ interface ReservationDocument extends Document {
133
155
  createdAt: Date;
134
156
  updatedAt: Date;
135
157
  }
136
- declare function createReservationModel(connection: Connection, opts?: {
137
- collectionPrefix?: string | undefined;
138
- }): Model<ReservationDocument>;
158
+ /**
159
+ * Build the Reservation schema — pure, connection-free. Registration + collection
160
+ * naming + tenant injection are performed by `defineCartModels` at bind time.
161
+ */
162
+ declare function buildReservationSchema(): Schema<ReservationDocument>;
139
163
  //#endregion
140
164
  //#region src/models/index.d.ts
141
165
  /** Union of all cart model names used as keys in `CartModels`. */
142
166
  type CartModelName = 'Draft' | 'Checkout' | 'Reservation' | 'Idempotency';
143
- interface CreateCartModelsOptions {
144
- tenantFieldType?: 'objectId' | 'string';
145
- multiTenant?: boolean;
167
+ interface DefineCartModelsConfig {
168
+ tenant?: ResolvedTenantConfig;
146
169
  autoIndex?: boolean | Partial<Record<CartModelName, boolean>>;
147
170
  /**
148
171
  * Optional prefix prepended to every physical collection this package
@@ -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
  /**
@@ -552,14 +579,10 @@ interface CreateCartRepositoriesConfig {
552
579
  bridges: CartBridges;
553
580
  clock: ClockPort;
554
581
  id: IdPort;
555
- defaultCurrency: string;
582
+ /** Validated + branded once at the config edge in `defineCart`. */
583
+ defaultCurrency: CurrencyCode;
556
584
  events: EventTransport;
557
- tenantFieldType?: 'objectId' | 'string';
558
- /**
559
- * When `false`, the tenant plugin is omitted entirely — cart is
560
- * company-wide. Default `true` keeps branch scoping.
561
- */
562
- multiTenant?: boolean;
585
+ tenant: ResolvedTenantConfig;
563
586
  outbox?: OutboxStore;
564
587
  plugins?: CartRepositoryPluginBundle;
565
588
  /** Zombie window for lazy open-checkout expiry. See `CheckoutRepositoryDeps`. */
@@ -588,196 +611,194 @@ interface CartBridges {
588
611
  tax?: TaxBridge | undefined;
589
612
  shipping?: ShippingBridge | undefined;
590
613
  }
614
+ /** Minimal logger surface cart uses (post-commit publish failures). */
615
+ interface CartLogger {
616
+ error(message: string, ...args: unknown[]): void;
617
+ }
591
618
  /**
592
- * CartConfig — the single argument to `createCart()`.
619
+ * DESCRIBE-time shape — everything that determines the persistence SHAPE or the
620
+ * immutable domain configuration and needs no connection or I/O to inspect.
621
+ * Nothing here opens a socket or reads a secret. Passed to `defineCart(shape)`
622
+ * (and `createCartDomain(shape)` for the connectionless domain-only surface).
593
623
  */
594
- interface CartConfig extends Partial<CartConfigShape> {
595
- /**
596
- * Mongoose connection. Required when the engine will create
597
- * models/repositories. Scenario tests that only exercise the LineKind
598
- * contract can pass a placeholder — the engine detects whether the
599
- * connection is a real Mongoose instance and skips model creation if
600
- * not, staying in `phase: 'contracts'`.
601
- */
602
- connection: Connection;
624
+ interface CartShape extends Partial<CartConfigShape> {
603
625
  /** LineKinds to register. At least one required. */
604
626
  kinds: readonly LineKind[];
605
- /** External-domain bridges. Only `catalog` is required. */
606
- bridges: CartBridges;
607
- /**
608
- * Optional host-supplied event transport. Default: `InProcessCartEventBus`.
609
- *
610
- * **Structurally compatible with Arc's `EventTransport`** — pass Arc's
611
- * Redis / Kafka / Outbox transport directly, zero adapter needed:
612
- *
613
- * ```ts
614
- * import { RedisEventTransport } from '@classytic/arc/events';
615
- * const cart = await createCart({ eventTransport: new RedisEventTransport(ioredis), ... });
616
- * ```
617
- */
618
- eventTransport?: EventTransport | undefined;
619
- /** Optional clock override. Default: `systemClock`. */
620
- clock?: ClockPort | undefined;
621
- /**
622
- * Optional id generator. Default: `cryptoIdPort`. Override for
623
- * deterministic tests, Temporal workflow replay safety, or host-
624
- * specific id formats.
625
- */
626
- id?: IdPort | undefined;
627
- /**
628
- * Optional host-owned durable outbox store.
629
- *
630
- * Cart no longer provisions its own Mongo outbox by default. Hosts that
631
- * need durable event persistence should inject their app-level outbox store
632
- * here. When omitted, cart still publishes to `eventTransport`, but
633
- * session-bound writes cannot persist events durably.
634
- */
635
- outbox?: OutboxStore | undefined;
636
- /**
637
- * Optional per-repository plugin bundle.
638
- */
639
- repositoryPlugins?: CartRepositoryPluginBundle | undefined;
640
- /**
641
- * Mongoose schema type for the `organizationId` field on all models.
642
- *
643
- * - `'objectId'` (default): `Schema.Types.ObjectId` + `ref: 'organization'`
644
- * - `'string'`: plain `String` — for UUID/slug-based auth
645
- *
646
- * Passed to model factories (schema) and multiTenantPlugin (query casting).
647
- */
648
- tenantFieldType?: 'objectId' | 'string' | undefined;
649
627
  /**
650
628
  * Whether cart is branch/tenant-scoped. Default `true`.
651
629
  *
652
630
  * - `true` (default): `organizationId` is required on every document and
653
- * prepended to every index. Use for multi-tenant SaaS or
654
- * branch-scoped cart stacks (POS-first, etc.).
631
+ * prepended to every index. Use for multi-tenant SaaS or branch-scoped
632
+ * cart stacks (POS-first, etc.).
655
633
  * - `false`: `organizationId` is left optional and excluded from indexes.
656
634
  * Use when cart is company-wide — a customer's cart follows them across
657
635
  * branches and no tenant filter applies.
658
636
  */
659
- multiTenant?: boolean | undefined;
637
+ tenant?: boolean | TenantConfig | undefined;
660
638
  /**
661
639
  * Control Mongoose `autoIndex` per model or globally.
662
640
  *
663
641
  * - `true` / `false` — applied to every cart model.
664
642
  * - `Partial<Record<CartModelName, boolean>>` — per-model override.
665
643
  * - `undefined` (default) — leave Mongoose defaults untouched.
666
- *
667
- * Mongoose 9 defers `Model.init()` until the first query, so setting
668
- * `schema.autoIndex` after `connection.model()` is safe.
669
644
  */
670
- autoIndex?: CreateCartModelsOptions['autoIndex'] | undefined;
645
+ autoIndex?: DefineCartModelsConfig['autoIndex'] | undefined;
671
646
  /**
672
647
  * Optional prefix prepended to every physical collection this package
673
- * creates (see PACKAGE_RULES.md §20.1). Unset → default names
674
- * (`cart_drafts`, `cart_checkouts`, `cart_reservations`,
675
- * `cart_idempotency`). Set e.g. `'commerce_'` to get `commerce_cart_drafts`,
676
- * etc. Model names and `ref:` populate are unaffected.
648
+ * creates (see PACKAGE_RULES.md §20.1). Unset → default names.
677
649
  */
678
650
  collectionPrefix?: string | undefined;
679
651
  /**
680
- * When true, existing Mongoose models with cart's names are deleted from
681
- * the connection before re-registering. Hot-reload / test fixtures only.
682
- * Default `false` — collision throws `CartModelCollisionError`. Hosts
683
- * that need two cart engines should use two Mongoose connections
684
- * (`mongoose.createConnection(...)`). See PACKAGE_RULES.md §21.
652
+ * When true, existing Mongoose models with cart's names are deleted from the
653
+ * connection before re-registering. Hot-reload / test fixtures only. Default
654
+ * `false` — collision throws mongokit's `ModelCollisionError`. Hosts that need
655
+ * two cart engines should use two Mongoose connections.
685
656
  */
686
657
  forceRecreate?: boolean | undefined;
658
+ }
659
+ /**
660
+ * BIND-time runtime collaborators — the live connection is the first `bind`
661
+ * arg; these are the rest. Provider clients, transports, loggers and bridges
662
+ * belong here, not in the shape.
663
+ */
664
+ interface CartRuntime {
665
+ /** External-domain bridges. Only `catalog` is required. */
666
+ bridges: CartBridges;
667
+ /**
668
+ * Optional host-supplied event transport. Default: `InProcessCartEventBus`.
669
+ * Structurally compatible with Arc's `EventTransport` — pass Arc's transport
670
+ * directly, zero adapter needed. A SUPPLIED transport is never closed by
671
+ * `engine.close()` (shared host infrastructure).
672
+ */
673
+ eventTransport?: EventTransport | undefined;
674
+ /**
675
+ * Optional host-owned durable outbox store. When omitted, cart still
676
+ * publishes to `eventTransport`, but session-bound writes cannot persist
677
+ * events durably.
678
+ *
679
+ * A supplied store MUST declare `transactionalSave: true` — cart saves the event
680
+ * row under `ctx.session`, and `OutboxWriteOptions.session` is best-effort by
681
+ * contract, so only the store can promise it commits with the write. `bind`
682
+ * refuses one that does not; `MemoryOutboxStore` correctly does not declare it
683
+ * (an in-memory row survives a rollback), so tests that need one wire a
684
+ * session-honouring double instead.
685
+ */
686
+ outbox?: OutboxStore | undefined;
687
+ /** Optional clock override. Default: `systemClock`. */
688
+ clock?: ClockPort | undefined;
689
+ /** Optional id generator. Default: `cryptoIdPort`. */
690
+ id?: IdPort | undefined;
691
+ /** Optional logger for post-commit publish failures. Default: `console`. */
692
+ logger?: CartLogger | undefined;
693
+ /** Optional per-repository plugin bundle appended after cart's defaults. */
694
+ repositoryPlugins?: CartRepositoryPluginBundle | undefined;
687
695
  /**
688
- * Allow `engine.withTransaction` to fall back to non-transactional
689
- * execution on standalone Mongo (local dev). Partial-write risk across
690
- * the wrapped writes — explicit opt-in only.
696
+ * Allow `engine.withTransaction` to fall back to non-transactional execution
697
+ * on standalone Mongo (local dev). Partial-write risk — explicit opt-in only.
691
698
  */
692
699
  allowNonTransactional?: boolean | undefined;
693
700
  }
701
+ /** Resolved configuration captured on the bound engine (frozen). */
702
+ interface ResolvedCartConfig {
703
+ tenant: ResolvedTenantConfig;
704
+ forceRecreate: boolean;
705
+ /** Validated + branded once at the config edge in `defineCart`. */
706
+ defaultCurrency: CurrencyCode;
707
+ collectionPrefix?: string;
708
+ allowNonTransactional: boolean;
709
+ staleOpenCheckoutMs?: number;
710
+ }
694
711
  /**
695
- * CartEngine — the result of `createCart()`.
712
+ * CartDomain — the connectionless, domain-only surface (STANDARDIZATION-PLAN
713
+ * §Phase 5). Kinds/events/clock/id WITHOUT persistence: no models, no
714
+ * repositories, no `withTransaction`. Use it to exercise the LineKind contract
715
+ * or emit events without a Mongoose connection. For persistence use
716
+ * `defineCart(shape).bind(connection, runtime)`.
717
+ */
718
+ interface CartDomain {
719
+ /** Registered LineKinds. */
720
+ readonly kinds: KindRegistry;
721
+ /** Event transport — host-supplied or the default `InProcessCartEventBus`. */
722
+ readonly events: EventTransport;
723
+ /** Clock source. */
724
+ readonly clock: ClockPort;
725
+ /** Id generator. */
726
+ readonly id: IdPort;
727
+ /** Release resources owned by this domain (only a self-created bus). Idempotent. */
728
+ close(): Promise<void>;
729
+ }
730
+ /**
731
+ * CartEngine — the frozen result of `defineCart(shape).bind(connection, runtime)`.
696
732
  */
697
733
  interface CartEngine {
698
- readonly config: Readonly<CartConfig>;
734
+ /** Resolved configuration (frozen). */
735
+ readonly config: Readonly<ResolvedCartConfig>;
699
736
  /** Registered LineKinds. */
700
737
  readonly kinds: KindRegistry;
701
- /**
702
- * Event transport — host-supplied or the default `InProcessCartEventBus`.
703
- *
704
- * ```ts
705
- * // Subscribe to all cart events via glob
706
- * await cart.events.subscribe?.('cart.*', async (event) => {
707
- * console.log(event.type, event.meta.organizationId);
708
- * });
709
- * ```
710
- */
738
+ /** Event transport — host-supplied or the default `InProcessCartEventBus`. */
711
739
  readonly events: EventTransport;
712
740
  /** Clock source. */
713
741
  readonly clock: ClockPort;
714
742
  /** Id generator. */
715
743
  readonly id: IdPort;
744
+ /** Mongoose models bound to the supplied connection. */
745
+ readonly models: CartModels;
716
746
  /**
717
- * Mongoose models bound to the engine's connection. Empty in
718
- * contracts-only mode.
719
- */
720
- readonly models: CartModels | Record<string, never>;
721
- /**
722
- * mongokit repositories — the primary CRUD + domain API. All domain
723
- * logic (addItem, checkout, commit, cancel) lives directly on the
724
- * repository classes. Empty in contracts-only mode.
725
- */
726
- readonly repositories: CartRepositories | Record<string, never>;
727
- /**
728
- * `'lite'` — no real Mongoose connection; kinds/events/clock/id are
729
- * populated but models/repositories are empty. Used by scenario tests
730
- * that only exercise the LineKind contract.
731
- *
732
- * `'full'` — real Mongoose connection detected; models and
733
- * repositories are populated.
747
+ * mongokit repositories — the primary CRUD + domain API. All domain logic
748
+ * (addItem, checkout, commit, cancel) lives directly on the repository classes.
734
749
  */
735
- readonly mode: 'lite' | 'full';
750
+ readonly repositories: CartRepositories;
736
751
  /**
737
752
  * Run cart writes in one atomic unit-of-work: transaction + post-commit
738
753
  * event publish. Events emitted inside the unit are queued and flushed to
739
- * the in-process transport only AFTER commit — a rollback can't leak
740
- * ghost events. Outbox rows (when wired) commit with the transaction.
741
- *
742
- * ```ts
743
- * await cart.withTransaction(ctx, (txCtx) =>
744
- * cart.repositories.checkout.createFromDraft(input, txCtx));
745
- * ```
746
- *
747
- * Full mode only — throws in `'lite'` mode (no real connection).
754
+ * the transport only AFTER commit — a rollback can't leak ghost events.
748
755
  */
749
756
  withTransaction<T>(ctx: OperationContext, body: (txCtx: OperationContext) => Promise<T>): Promise<T>;
750
- /**
751
- * Explicitly create indexes on all cart models.
752
- *
753
- * Useful when `autoIndex` is disabled in production — call once during
754
- * deployment or migration scripts.
755
- */
757
+ /** Build/align indexes. Call once per deploy when booted `autoIndex: false`. */
756
758
  syncIndexes(): Promise<void>;
757
- /** Shut down cleanly. */
758
- destroy(): Promise<void>;
759
+ /** Release resources owned by this engine (only a self-created bus). Idempotent. */
760
+ close(): Promise<void>;
759
761
  }
760
762
  //#endregion
761
- //#region src/engine/create-cart.d.ts
763
+ //#region src/engine/define-cart.d.ts
764
+ interface CartBlueprint {
765
+ readonly id: 'cart';
766
+ /** The model names this blueprint registers — known without a connection. */
767
+ readonly modelNames: readonly string[];
768
+ /**
769
+ * Compile + register the models on `connection`, wire the engine, verify
770
+ * capabilities. `bind` MAY be async (the `KernelBlueprint` contract permits
771
+ * it); cart's construction is synchronous today.
772
+ */
773
+ bind(connection: Connection, runtime: CartRuntime): CartEngine;
774
+ }
762
775
  /**
763
- * createCart() — build a cart engine.
764
- *
765
- * Repositories are the primary API. All domain logic (addItem, checkout,
766
- * commit, cancel) lives directly on the repository classes. Multi-tenant
767
- * scoping and `publicId` generation are handled by mongokit plugins wired
768
- * inside `createCartRepositories`, so callers just pass the connection
769
- * and bridges.
776
+ * Describe the cart engine. Pure — registers no model, builds no schema,
777
+ * performs no I/O.
770
778
  */
771
- declare function createCart(config: CartConfig): Promise<CartEngine>;
779
+ declare function defineCart(shape: CartShape): CartBlueprint;
780
+ /**
781
+ * Domain-only runtime — the subset of collaborators the connectionless surface
782
+ * can use. No bridges, connection, outbox or plugins (those need persistence).
783
+ */
784
+ interface CartDomainRuntime {
785
+ eventTransport?: EventTransport | undefined;
786
+ clock?: ClockPort | undefined;
787
+ id?: IdPort | undefined;
788
+ }
789
+ /**
790
+ * `createCartDomain(shape, runtime?)` — the EXPLICIT connectionless domain-only
791
+ * surface (STANDARDIZATION-PLAN §Phase 5). Builds the kind registry, event
792
+ * transport, clock and id WITHOUT touching a connection, registering a model,
793
+ * or wiring a repository. Use it to exercise the LineKind contract or emit
794
+ * events without persistence. It is NOT a degraded engine — it deliberately
795
+ * exposes no `models`/`repositories`/`withTransaction`.
796
+ */
797
+ declare function createCartDomain(shape: CartShape, runtime?: CartDomainRuntime): CartDomain;
772
798
  //#endregion
773
799
  //#region src/engine/internal-event-bus.d.ts
774
- declare class InProcessCartEventBus implements EventTransport {
775
- readonly name = "in-process-cart";
776
- private subs;
777
- publish(event: DomainEvent): Promise<void>;
778
- publishMany(events: readonly DomainEvent[]): Promise<PublishManyResult>;
779
- subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
780
- close(): Promise<void>;
800
+ declare class InProcessCartEventBus extends InProcessEventBus {
801
+ constructor();
781
802
  }
782
803
  //#endregion
783
- 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 };
804
+ 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 };