@classytic/cart 0.2.1 → 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/CHANGELOG.md CHANGED
@@ -1,137 +1,157 @@
1
- # Changelog
2
-
3
- Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
4
- adhering to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
-
6
- ## [0.2.1] - 2026-07-02
7
-
8
- ### Changed (behavioral) — 2026-07-05 addendum
9
-
10
- - **`commit()` is crash-retry convergent.** The finalize CAS runs first and
11
- its tail (`markConverted` on the draft + the `cart.checkout.committed`
12
- event) is non-atomic — a crash in between left the draft looking live
13
- (re-checkout → duplicate order risk) with NO retry path, because a second
14
- `commit()` failed the `finalized → finalized` state assertion. A retry
15
- with the SAME `externalRef` (or none) now re-runs both idempotent tails
16
- and returns the finalized checkout; a DIFFERENT `externalRef` throws
17
- `ConcurrencyError`. `cart.checkout.committed` delivery is at-least-once —
18
- subscribers must already dedupe by `checkoutId`.
19
-
20
- ### Added
21
-
22
- - **`engine.withTransaction(ctx, body)`** — unit-of-work wrapper (transaction
23
- + post-commit event publish), the contract shared with `@classytic/refit`
24
- and `@classytic/review`. Events emitted inside the unit are queued under
25
- `ctx[PENDING_EVENTS]` and flushed to the in-process transport only AFTER
26
- commit — a rollback or retry can't leak ghost events. New exports:
27
- `PENDING_EVENTS`, `flushPending`, `UnmanagedSessionError`; new config:
28
- `allowNonTransactional` (standalone-Mongo dev fallback, explicit opt-in).
29
- - **Boot capability gate** — `createCart` (full mode) asserts the backend
30
- declares `capabilities.upsert` (idempotency lease pattern) at engine
31
- creation instead of failing on the first checkout.
32
- - **Event-catalog no-drift test** (rule 18) — every `CartEvents` constant
33
- must have a Zod definition; orphan definitions also fail.
34
- - **Compensation scenario test** — proves the documented
35
- `cart.checkout.canceled` → `inventory.release()` host wiring end-to-end.
36
- - `PriceChangedErrorContext` — formal type for the error's structured
37
- context (current pricing payload), previously an untyped inline shape.
38
-
39
- ### Changed
40
-
41
- - **`CartEventPublisher`**: a host-owned `ctx.session` without an outbox now
42
- throws typed `UnmanagedSessionError` (was a plain `Error`) unless a
43
- `PENDING_EVENTS` queue is attached; transport publish failures on the
44
- no-session path are now swallowed and logged per P8 (the domain verb no
45
- longer fails after its write landed because a transport hiccuped).
46
- - Safe-integer guard on line-total arithmetic (`unitPrice × quantity`);
47
- idempotency repo now uses mongokit's `isDuplicateKeyError`; `cancel()`
48
- and the timeslot kind's `revalidate` carry explicit contracts (host owns
49
- hold release; validity-window-only revalidation — real slot-locking via
50
- `@classytic/order`'s `BookingBridge`).
51
-
52
- ## [0.2.0]
53
-
54
- ### Changed
55
-
56
- - **`pricingHash` is now hex SHA-256** over the same canonical sorted
57
- line string (was the raw concatenation). The hash is opaque — compare,
58
- never parse. **Migration:** drafts priced before 0.2.0 carry old-format
59
- hashes; the first checkout attempt against them raises
60
- `PriceChangedError` once and the client re-fetches/re-confirms.
61
- Accepted clean break.
62
- - **Guest→user merge is now double-CAS atomic.** `mergeDrafts` retires the
63
- source with a version CAS, then writes the target with a version CAS
64
- (bounded retries) — a concurrent add-to-cart on either draft is retried
65
- into the result instead of silently lost. `DraftRepository.markAbandoned`
66
- gains an optional `{ expectedVersion }`; `replaceLines` gains an
67
- optional `expectedVersion` input.
68
- - **Zombie open checkouts self-heal.** `createFromDraft` CAS-expires an
69
- open checkout older than `checkout.staleOpenCheckoutMs` (new config,
70
- default 10 min) and creates a fresh one; fresh open checkouts are still
71
- returned idempotently. `expireStaleOpenCheckouts` remains the bulk cron
72
- sweep. No TTL deletes — checkout rows stay as audit history.
73
- - **`PriceChangedError` context now includes `currentPricing`** (per-line
74
- `lineId`/`quantity`/`unitPrice`/`subtotals` + `totals`) so hosts render
75
- a price diff without re-fetching the draft.
76
- - **`ctx.signal` is threaded to every mongokit call** — cancelled requests
77
- stop at the driver-call boundary (repo-core 0.6 `QueryOptions.signal`).
78
- - Peer deps: `@classytic/mongokit >= 3.16`, `@classytic/repo-core >= 0.6`.
79
-
80
- ### Added
81
-
82
- - `checkoutConfigSchema` / `CartConfig.checkout.staleOpenCheckoutMs` and
83
- `DEFAULT_STALE_OPEN_CHECKOUT_MS` export.
84
- - Documented host contract: checkout → order → `inventory.commit()`
85
- (CLAUDE.md "Host responsibilities") — `commit()` intentionally does not
86
- commit inventory holds.
87
- - Scenario 10: stale quote → `revalidate()` reprice path (`bundle` kind).
88
-
89
- ## [0.1.0]
90
-
91
- Initial release. Framework-agnostic universal cart engine — mutable drafts,
92
- locked checkout snapshots, composable pricing, and the **LineKind** strategy
93
- that handles every business variation. Zero framework dependencies.
94
-
95
- ### Exports
96
-
97
- - **`.`** (root) — `createCart(config)` engine factory, re-exports of the
98
- most-used services and types.
99
- - **`./domain`** — pure domain types: `Draft`, `Checkout`, `Line`, `Money`,
100
- validity/staleness, idempotency key shapes.
101
- - **`./kinds`** — built-in `sku` LineKind + the generic `LineKind<T>` contract.
102
- - **`./ports`** — 5 bridge ports: `CatalogBridge` (required), `InventoryBridge`,
103
- `PromotionsBridge`, `TaxBridge`, `ShippingBridge`.
104
- - **`./errors`** — typed error classes (`DraftNotFoundError`,
105
- `PriceChangedError`, `InventoryReservationError`, etc.).
106
- - **`./events`** — `cartEventDefinitions`, `OutboxRepository`, payload map;
107
- arc-compatible structural types (no arc import).
108
- - **`./saga`** — checkout state machine (`open → finalized | canceled`),
109
- transition helpers.
110
- - **`./engine`** — engine internals for hosts that want to reach past the
111
- factory.
112
- - **`./schemas`** — Zod schemas for `createCart()` config; exported for hosts
113
- that validate config from env or a database.
114
-
115
- ### Peer dependencies
116
-
117
- - `@classytic/mongokit >= 3.11` — repositories extend `Repository<T>` directly.
118
- - `@classytic/primitives >= 0.1` — `Money`, `OperationContext`, events.
119
- - `@classytic/repo-core >= 0.2` — shared repository abstractions.
120
- - `mongoose >= 9.4` · `zod >= 4`.
121
-
122
- ### Design
123
-
124
- - **No modes / no tiers.** Features light up based on which bridges the host
125
- passes to `createCart()`. Catalog bridge is required; inventory, promo, tax,
126
- shipping are opt-in.
127
- - **Denormalized display snapshot** on every line (`display.name`,
128
- `imageUrl`, `variantLabel`, `compareAtPrice`, `capturedAt`) captured at
129
- add-time by `kind.displayOf()`. UI reads the cart with zero `.populate()`
130
- calls. Drift is cosmetic; price drift is caught via `pricingHash` at checkout.
131
- - **Checkout state machine: 3 states, 2 transitions.** `open → finalized`
132
- (host called `commit`) or `open → canceled`. No payment state inside cart.
133
- - **Idempotent + typed.** Every mutation accepts an idempotency key.
134
- Operations are pure async functions with serializable inputs — agent-ready.
135
- - **Arc-compatible events.** `cartEventDefinitions` are structurally
136
- compatible with arc's `EventDefinitionOutput`; `OutboxRepository` implements
137
- arc's `OutboxStore` without importing arc.
1
+ # Changelog
2
+
3
+ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
4
+ adhering to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
+
6
+ ## [0.3.1] — 2026-07-16
7
+
8
+ ### Fixed
9
+
10
+ - injectTenantField no longer force-indexes the tenant field: the compound
11
+ prepend makes the tenant the leading key of every index, so the bare single
12
+ was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
13
+ index audit). A dedicated tenant index is still created when a schema
14
+ declares no compounds to prepend. Index-declaration change only.
15
+
16
+ ## [0.3.0] — unpublished (2026-07-15)
17
+
18
+ ### Changed — kit refresh (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
19
+
20
+ - Verified against the mongokit 3.22 sweep. DEFERRED (design note, not a
21
+ drive-by): checkout `finalize`/`cancel` are assert-then-`updateWithVersion`
22
+ — the version CAS serializes writers, so the window is narrow; converting
23
+ to `applyTransition` (state+version compound CAS) needs a pass that
24
+ preserves the updateWithVersion helper's semantics.
25
+
26
+ ## [0.2.1] - 2026-07-02
27
+
28
+ ### Changed (behavioral) — 2026-07-05 addendum
29
+
30
+ - **`commit()` is crash-retry convergent.** The finalize CAS runs first and
31
+ its tail (`markConverted` on the draft + the `cart.checkout.committed`
32
+ event) is non-atomic — a crash in between left the draft looking live
33
+ (re-checkout → duplicate order risk) with NO retry path, because a second
34
+ `commit()` failed the `finalized → finalized` state assertion. A retry
35
+ with the SAME `externalRef` (or none) now re-runs both idempotent tails
36
+ and returns the finalized checkout; a DIFFERENT `externalRef` throws
37
+ `ConcurrencyError`. `cart.checkout.committed` delivery is at-least-once —
38
+ subscribers must already dedupe by `checkoutId`.
39
+
40
+ ### Added
41
+
42
+ - **`engine.withTransaction(ctx, body)`** — unit-of-work wrapper (transaction
43
+ + post-commit event publish), the contract shared with `@classytic/refit`
44
+ and `@classytic/review`. Events emitted inside the unit are queued under
45
+ `ctx[PENDING_EVENTS]` and flushed to the in-process transport only AFTER
46
+ commit — a rollback or retry can't leak ghost events. New exports:
47
+ `PENDING_EVENTS`, `flushPending`, `UnmanagedSessionError`; new config:
48
+ `allowNonTransactional` (standalone-Mongo dev fallback, explicit opt-in).
49
+ - **Boot capability gate** — `createCart` (full mode) asserts the backend
50
+ declares `capabilities.upsert` (idempotency lease pattern) at engine
51
+ creation instead of failing on the first checkout.
52
+ - **Event-catalog no-drift test** (rule 18) — every `CartEvents` constant
53
+ must have a Zod definition; orphan definitions also fail.
54
+ - **Compensation scenario test** — proves the documented
55
+ `cart.checkout.canceled` → `inventory.release()` host wiring end-to-end.
56
+ - `PriceChangedErrorContext` — formal type for the error's structured
57
+ context (current pricing payload), previously an untyped inline shape.
58
+
59
+ ### Changed
60
+
61
+ - **`CartEventPublisher`**: a host-owned `ctx.session` without an outbox now
62
+ throws typed `UnmanagedSessionError` (was a plain `Error`) unless a
63
+ `PENDING_EVENTS` queue is attached; transport publish failures on the
64
+ no-session path are now swallowed and logged per P8 (the domain verb no
65
+ longer fails after its write landed because a transport hiccuped).
66
+ - Safe-integer guard on line-total arithmetic (`unitPrice × quantity`);
67
+ idempotency repo now uses mongokit's `isDuplicateKeyError`; `cancel()`
68
+ and the timeslot kind's `revalidate` carry explicit contracts (host owns
69
+ hold release; validity-window-only revalidation — real slot-locking via
70
+ `@classytic/order`'s `BookingBridge`).
71
+
72
+ ## [0.2.0]
73
+
74
+ ### Changed
75
+
76
+ - **`pricingHash` is now hex SHA-256** over the same canonical sorted
77
+ line string (was the raw concatenation). The hash is opaque — compare,
78
+ never parse. **Migration:** drafts priced before 0.2.0 carry old-format
79
+ hashes; the first checkout attempt against them raises
80
+ `PriceChangedError` once and the client re-fetches/re-confirms.
81
+ Accepted clean break.
82
+ - **Guest→user merge is now double-CAS atomic.** `mergeDrafts` retires the
83
+ source with a version CAS, then writes the target with a version CAS
84
+ (bounded retries) — a concurrent add-to-cart on either draft is retried
85
+ into the result instead of silently lost. `DraftRepository.markAbandoned`
86
+ gains an optional `{ expectedVersion }`; `replaceLines` gains an
87
+ optional `expectedVersion` input.
88
+ - **Zombie open checkouts self-heal.** `createFromDraft` CAS-expires an
89
+ open checkout older than `checkout.staleOpenCheckoutMs` (new config,
90
+ default 10 min) and creates a fresh one; fresh open checkouts are still
91
+ returned idempotently. `expireStaleOpenCheckouts` remains the bulk cron
92
+ sweep. No TTL deletes — checkout rows stay as audit history.
93
+ - **`PriceChangedError` context now includes `currentPricing`** (per-line
94
+ `lineId`/`quantity`/`unitPrice`/`subtotals` + `totals`) so hosts render
95
+ a price diff without re-fetching the draft.
96
+ - **`ctx.signal` is threaded to every mongokit call** — cancelled requests
97
+ stop at the driver-call boundary (repo-core 0.6 `QueryOptions.signal`).
98
+ - Peer deps: `@classytic/mongokit >= 3.16`, `@classytic/repo-core >= 0.6`.
99
+
100
+ ### Added
101
+
102
+ - `checkoutConfigSchema` / `CartConfig.checkout.staleOpenCheckoutMs` and
103
+ `DEFAULT_STALE_OPEN_CHECKOUT_MS` export.
104
+ - Documented host contract: checkout → order → `inventory.commit()`
105
+ (CLAUDE.md "Host responsibilities") — `commit()` intentionally does not
106
+ commit inventory holds.
107
+ - Scenario 10: stale quote → `revalidate()` reprice path (`bundle` kind).
108
+
109
+ ## [0.1.0]
110
+
111
+ Initial release. Framework-agnostic universal cart engine — mutable drafts,
112
+ locked checkout snapshots, composable pricing, and the **LineKind** strategy
113
+ that handles every business variation. Zero framework dependencies.
114
+
115
+ ### Exports
116
+
117
+ - **`.`** (root) — `createCart(config)` engine factory, re-exports of the
118
+ most-used services and types.
119
+ - **`./domain`** — pure domain types: `Draft`, `Checkout`, `Line`, `Money`,
120
+ validity/staleness, idempotency key shapes.
121
+ - **`./kinds`** — built-in `sku` LineKind + the generic `LineKind<T>` contract.
122
+ - **`./ports`** — 5 bridge ports: `CatalogBridge` (required), `InventoryBridge`,
123
+ `PromotionsBridge`, `TaxBridge`, `ShippingBridge`.
124
+ - **`./errors`** — typed error classes (`DraftNotFoundError`,
125
+ `PriceChangedError`, `InventoryReservationError`, etc.).
126
+ - **`./events`** — `cartEventDefinitions`, `OutboxRepository`, payload map;
127
+ arc-compatible structural types (no arc import).
128
+ - **`./saga`** — checkout state machine (`open → finalized | canceled`),
129
+ transition helpers.
130
+ - **`./engine`** — engine internals for hosts that want to reach past the
131
+ factory.
132
+ - **`./schemas`** — Zod schemas for `createCart()` config; exported for hosts
133
+ that validate config from env or a database.
134
+
135
+ ### Peer dependencies
136
+
137
+ - `@classytic/mongokit >= 3.11` — repositories extend `Repository<T>` directly.
138
+ - `@classytic/primitives >= 0.1` — `Money`, `OperationContext`, events.
139
+ - `@classytic/repo-core >= 0.2` — shared repository abstractions.
140
+ - `mongoose >= 9.4` · `zod >= 4`.
141
+
142
+ ### Design
143
+
144
+ - **No modes / no tiers.** Features light up based on which bridges the host
145
+ passes to `createCart()`. Catalog bridge is required; inventory, promo, tax,
146
+ shipping are opt-in.
147
+ - **Denormalized display snapshot** on every line (`display.name`,
148
+ `imageUrl`, `variantLabel`, `compareAtPrice`, `capturedAt`) captured at
149
+ add-time by `kind.displayOf()`. UI reads the cart with zero `.populate()`
150
+ calls. Drift is cosmetic; price drift is caught via `pricingHash` at checkout.
151
+ - **Checkout state machine: 3 states, 2 transitions.** `open → finalized`
152
+ (host called `commit`) or `open → canceled`. No payment state inside cart.
153
+ - **Idempotent + typed.** Every mutation accepts an idempotency key.
154
+ Operations are pure async functions with serializable inputs — agent-ready.
155
+ - **Arc-compatible events.** `cartEventDefinitions` are structurally
156
+ compatible with arc's `EventDefinitionOutput`; `OutboxRepository` implements
157
+ arc's `OutboxStore` without importing arc.
@@ -160,7 +160,7 @@ function createCheckoutModel(connection, opts = {}) {
160
160
  draftId: 1,
161
161
  state: 1
162
162
  });
163
- const collection = (opts.collectionPrefix ?? "") + "cart_checkouts";
163
+ const collection = `${opts.collectionPrefix ?? ""}cart_checkouts`;
164
164
  return connection.model("CartCheckout", schema, collection);
165
165
  }
166
166
  //#endregion
@@ -348,7 +348,7 @@ function createDraftModel(connection, opts = {}) {
348
348
  expireAfterSeconds: 0,
349
349
  partialFilterExpression: { expiresAt: { $exists: true } }
350
350
  });
351
- const collection = (opts.collectionPrefix ?? "") + "cart_drafts";
351
+ const collection = `${opts.collectionPrefix ?? ""}cart_drafts`;
352
352
  return connection.model("CartDraft", schema, collection);
353
353
  }
354
354
  //#endregion
@@ -427,7 +427,7 @@ function createIdempotencyModel(connection, opts = {}) {
427
427
  idempotencyKey: 1
428
428
  }, { unique: true });
429
429
  schema.index({ createdAt: 1 }, { expireAfterSeconds: 1440 * 60 });
430
- const collection = (opts.collectionPrefix ?? "") + "cart_idempotency";
430
+ const collection = `${opts.collectionPrefix ?? ""}cart_idempotency`;
431
431
  return connection.model("CartIdempotency", schema, collection);
432
432
  }
433
433
  //#endregion
@@ -461,7 +461,6 @@ function injectTenantField(schema, tenant) {
461
461
  schema.add({ [tenant.tenantField]: {
462
462
  type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
463
463
  ...tenant.enabled && tenant.required ? { required: true } : {},
464
- index: true,
465
464
  ...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
466
465
  } });
467
466
  if (!tenant.enabled || !isFieldStrategy) return;
@@ -473,6 +472,7 @@ function injectTenantField(schema, tenant) {
473
472
  for (const [key, val] of Object.entries(fields)) newFields[key] = val;
474
473
  indexEntry[0] = newFields;
475
474
  }
475
+ if (!(existingIndexes ?? []).some(([fields]) => Object.keys(fields)[0] === tenant.tenantField)) schema.index({ [tenant.tenantField]: 1 });
476
476
  }
477
477
  //#endregion
478
478
  //#region src/models/reservation.model.ts
@@ -557,7 +557,7 @@ function createReservationModel(connection, opts = {}) {
557
557
  expiresAt: 1
558
558
  });
559
559
  schema.index({ checkoutId: 1 });
560
- const collection = (opts.collectionPrefix ?? "") + "cart_reservations";
560
+ const collection = `${opts.collectionPrefix ?? ""}cart_reservations`;
561
561
  return connection.model("CartReservation", schema, collection);
562
562
  }
563
563
  //#endregion
@@ -1807,9 +1807,6 @@ var IdempotencyRepository = class extends Repository {
1807
1807
  * sweeper drives the active release loop via `findExpiredHeld`.
1808
1808
  */
1809
1809
  var ReservationRepository = class extends Repository {
1810
- constructor(model, plugins) {
1811
- super(model, plugins);
1812
- }
1813
1810
  /** All reservations belonging to a checkout. */
1814
1811
  async findByCheckout(checkoutId, ctx) {
1815
1812
  return await this.findAll({ checkoutId }, this.readOptions(ctx));
@@ -1,2 +1,2 @@
1
- import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "../../index-BB0XzkXF.mjs";
1
+ import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "../../index-wh5Q7UY1.mjs";
2
2
  export { CartError, CartErrorCategory, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, SagaFailurePhase, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError };
@@ -1,6 +1,6 @@
1
1
  import { t as CartError } from "../../cart.error-BwWy4RlY.mjs";
2
2
  import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "../../unmanaged-session.error-C9Z1Yh9j.mjs";
3
3
  import { n as UnknownKindError, t as KindError } from "../../kind.error-DIaJpdUb.mjs";
4
- import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../../errors-7Pd0yATM.mjs";
4
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../../errors-BNPgUilS.mjs";
5
5
  import { t as StateTransitionError } from "../../state-transition.error-2fRLh3p0.mjs";
6
6
  export { CartError, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError };
@@ -1,4 +1,4 @@
1
- import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "../index-BB0XzkXF.mjs";
1
+ import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "../index-wh5Q7UY1.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "../cart-status.vo-CNJw4aaB.mjs";
3
3
  import { S as CartEvents, _ as CartEventMeta, a as OutboxErrorInfo, b as CartEventName, c as OutboxFailureDecision, d as OutboxStore, f as OutboxStoreWriteOptions, g as CartEventAggregate, h as CartDomainEvent, i as OutboxClaimOptions, l as OutboxFailurePolicy, m as CartAggregateType, n as MemoryOutboxStore, o as OutboxFailOptions, p as OutboxWriteOptions, r as OutboxAcknowledgeOptions, s as OutboxFailureContext, t as InvalidOutboxEventError, u as OutboxOwnershipError, v as createCartEvent, x as CartEventPayload, y as CartEventMap } from "../outbox-store-CBt9fSYh.mjs";
4
4
  import { a as CartEventRegistry, c as defineCartEvent, d as EventValidationResult, f as EventValidator, i as CartEventDefinitionInput, l as EventSchema, n as cartEventsByName, o as PayloadOf, r as CartEventDefinition, s as createCartEventRegistry, t as cartEventDefinitions, u as EventSchemaProperty } from "../cart-event-catalog-BxDJhtTM.mjs";
@@ -2,7 +2,7 @@ import { t as CART_REF_NEW } from "../idempotency-key.vo-D0lJsvGn.mjs";
2
2
  import { t as CartError } from "../cart.error-BwWy4RlY.mjs";
3
3
  import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "../unmanaged-session.error-C9Z1Yh9j.mjs";
4
4
  import { n as UnknownKindError, t as KindError } from "../kind.error-DIaJpdUb.mjs";
5
- import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../errors-7Pd0yATM.mjs";
5
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../errors-BNPgUilS.mjs";
6
6
  import { t as StateTransitionError } from "../state-transition.error-2fRLh3p0.mjs";
7
7
  import { n as CartEvents, t as createCartEvent } from "../domain-event-CIEORKF6.mjs";
8
8
  import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "../outbox-store-CWW8ppxS.mjs";
@@ -1,3 +1,3 @@
1
1
  import { CartConfigShape, cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
2
- import { a as CartEngine, i as CartConfig, n as createCart, r as CartBridges, t as InProcessCartEventBus } from "../internal-event-bus-DhQKi9KS.mjs";
2
+ import { a as CartEngine, i as CartConfig, n as createCart, r as CartBridges, t as InProcessCartEventBus } from "../internal-event-bus-DFcwV79F.mjs";
3
3
  export { type CartBridges, type CartConfig, type CartConfigShape, type CartEngine, InProcessCartEventBus, cartConfigSchema, createCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -1,3 +1,3 @@
1
- import { n as InProcessCartEventBus, t as createCart } from "../create-cart-BeW0xAqD.mjs";
1
+ import { n as InProcessCartEventBus, t as createCart } from "../create-cart-zgAh3UVt.mjs";
2
2
  import { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
3
3
  export { InProcessCartEventBus, cartConfigSchema, createCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -64,9 +64,6 @@ var IdempotencyStorageError = class extends CartError {
64
64
  code = "cart/idempotency_storage_corruption";
65
65
  category = "system";
66
66
  retryable = false;
67
- constructor(message, context) {
68
- super(message, context);
69
- }
70
67
  };
71
68
  //#endregion
72
69
  export { ReservationError as i, IdempotencyStorageError as n, SagaError as r, IdempotencyBusyError as t };
@@ -205,7 +205,6 @@ declare class IdempotencyStorageError extends CartError {
205
205
  readonly code = "cart/idempotency_storage_corruption";
206
206
  readonly category: CartErrorCategory;
207
207
  readonly retryable = false;
208
- constructor(message: string, context: Record<string, unknown>);
209
208
  }
210
209
  //#endregion
211
210
  //#region src/domain/errors/stale-quote.error.d.ts
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "./index-BB0XzkXF.mjs";
1
+ import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "./index-wh5Q7UY1.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
3
3
  import { S as CartEvents, _ as CartEventMeta, a as OutboxErrorInfo, b as CartEventName, c as OutboxFailureDecision, d as OutboxStore, f as OutboxStoreWriteOptions, g as CartEventAggregate, h as CartDomainEvent, i as OutboxClaimOptions, l as OutboxFailurePolicy, m as CartAggregateType, n as MemoryOutboxStore, o as OutboxFailOptions, p as OutboxWriteOptions, r as OutboxAcknowledgeOptions, s as OutboxFailureContext, t as InvalidOutboxEventError, u as OutboxOwnershipError, v as createCartEvent, x as CartEventPayload, y as CartEventMap } from "./outbox-store-CBt9fSYh.mjs";
4
4
  import { a as CartEventRegistry, c as defineCartEvent, d as EventValidationResult, f as EventValidator, i as CartEventDefinitionInput, l as EventSchema, n as cartEventsByName, o as PayloadOf, r as CartEventDefinition, s as createCartEventRegistry, t as cartEventDefinitions, u as EventSchemaProperty } from "./cart-event-catalog-BxDJhtTM.mjs";
@@ -9,7 +9,7 @@ import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineD
9
9
  import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "./kind-registry-DG2iCCH1.mjs";
10
10
  import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-DitjeoHg.mjs";
11
11
  import { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
12
- import { C as createReservationModel, D as createDraftModel, E as DraftDocument, O as CheckoutDocument, S as ReservationDocument, T as createIdempotencyModel, _ as CartEventPublisherDeps, a as CartEngine, b as CreateCartModelsOptions, c as CreateCartRepositoriesConfig, d as IdempotencyRepository, f as CheckoutRepository, g as DraftRepositoryDeps, h as DraftRepository, i as CartConfig, k as createCheckoutModel, l as createCartRepositories, m as DEFAULT_STALE_OPEN_CHECKOUT_MS, n as createCart, o as CartRepositories, p as CheckoutRepositoryDeps, r as CartBridges, s as CartRepositoryPluginBundle, t as InProcessCartEventBus, u as ReservationRepository, v as CartModelName, w as IdempotencyDocument, x as createCartModels, y as CartModels } from "./internal-event-bus-DhQKi9KS.mjs";
12
+ import { C as createReservationModel, D as createDraftModel, E as DraftDocument, O as CheckoutDocument, S as ReservationDocument, T as createIdempotencyModel, _ as CartEventPublisherDeps, a as CartEngine, b as CreateCartModelsOptions, c as CreateCartRepositoriesConfig, d as IdempotencyRepository, f as CheckoutRepository, g as DraftRepositoryDeps, h as DraftRepository, i as CartConfig, k as createCheckoutModel, l as createCartRepositories, m as DEFAULT_STALE_OPEN_CHECKOUT_MS, n as createCart, o as CartRepositories, p as CheckoutRepositoryDeps, r as CartBridges, s as CartRepositoryPluginBundle, t as InProcessCartEventBus, u as ReservationRepository, v as CartModelName, w as IdempotencyDocument, x as createCartModels, y as CartModels } from "./internal-event-bus-DFcwV79F.mjs";
13
13
  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";
14
14
  import { Money, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
15
15
  import { DomainEvent, EventHandler, EventTransport, EventTransport as EventTransport$1, PublishManyResult } from "@classytic/primitives/events";
package/dist/index.mjs CHANGED
@@ -2,12 +2,12 @@ import { t as CART_REF_NEW } from "./idempotency-key.vo-D0lJsvGn.mjs";
2
2
  import { t as CartError } from "./cart.error-BwWy4RlY.mjs";
3
3
  import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-C9Z1Yh9j.mjs";
4
4
  import { n as UnknownKindError, t as KindError } from "./kind.error-DIaJpdUb.mjs";
5
- import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-7Pd0yATM.mjs";
5
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-BNPgUilS.mjs";
6
6
  import { t as StateTransitionError } from "./state-transition.error-2fRLh3p0.mjs";
7
7
  import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
8
8
  import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "./outbox-store-CWW8ppxS.mjs";
9
9
  import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-BhbFZJPm.mjs";
10
- import { a as IdempotencyRepository, c as CheckoutRepository, d as createReservationModel, f as createIdempotencyModel, g as PENDING_EVENTS, h as flushPending, i as ReservationRepository, l as DEFAULT_STALE_OPEN_CHECKOUT_MS, m as createCheckoutModel, n as InProcessCartEventBus, o as DraftRepository, p as createDraftModel, r as createCartRepositories, s as runPricing, t as createCart, u as createCartModels } from "./create-cart-BeW0xAqD.mjs";
10
+ import { a as IdempotencyRepository, c as CheckoutRepository, d as createReservationModel, f as createIdempotencyModel, g as PENDING_EVENTS, h as flushPending, i as ReservationRepository, l as DEFAULT_STALE_OPEN_CHECKOUT_MS, m as createCheckoutModel, n as InProcessCartEventBus, o as DraftRepository, p as createDraftModel, r as createCartRepositories, s as runPricing, t as createCart, u as createCartModels } from "./create-cart-zgAh3UVt.mjs";
11
11
  import { t as createKindRegistry } from "./kind-registry-Bvrj3P1Q.mjs";
12
12
  import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-Defw8gAt.mjs";
13
13
  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";
@@ -105,7 +105,7 @@ async function mergeDrafts(opts) {
105
105
  let lastError;
106
106
  for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {
107
107
  const source = await repo.findByPublicId(sourcePublicId, ctx);
108
- if (!source || source.status !== "active") throw new Error(`Source draft '${sourcePublicId}' not found or not active`);
108
+ if (source?.status !== "active") throw new Error(`Source draft '${sourcePublicId}' not found or not active`);
109
109
  if (!await repo.findActiveByActor(targetActorRef, targetCtx)) try {
110
110
  return await repo.updateWithVersion(source._id, source.version, {
111
111
  actorRef: targetActorRef,
@@ -506,7 +506,6 @@ declare class IdempotencyRepository extends Repository<IdempotencyDocument> {
506
506
  * sweeper drives the active release loop via `findExpiredHeld`.
507
507
  */
508
508
  declare class ReservationRepository extends Repository<ReservationDocument> {
509
- constructor(model: Model<ReservationDocument>, plugins: PluginType[]);
510
509
  /** All reservations belonging to a checkout. */
511
510
  findByCheckout(checkoutId: Types.ObjectId | string, ctx: OperationContext): Promise<ReservationDocument[]>;
512
511
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/cart",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Framework-agnostic universal cart engine for commerce — drafts, checkouts, reservations, the LineKind strategy, and a disciplined finalization saga. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
5
5
  "author": "Classytic",
6
6
  "type": "module",
@@ -83,18 +83,18 @@
83
83
  "release": "npm run push -- main && npm run release:tag && npm publish"
84
84
  },
85
85
  "peerDependencies": {
86
- "@classytic/mongokit": ">=3.18.0",
87
- "@classytic/primitives": ">=0.9.1",
88
- "@classytic/repo-core": ">=0.7.0",
86
+ "@classytic/mongokit": ">=3.22.0",
87
+ "@classytic/primitives": ">=0.11.0",
88
+ "@classytic/repo-core": ">=0.13.0",
89
89
  "mongoose": ">=9.4.1",
90
90
  "zod": ">=4.0.0"
91
91
  },
92
92
  "devDependencies": {
93
93
  "@biomejs/biome": "^2.4.13",
94
94
  "@classytic/dev-tools": "^0.2.0",
95
- "@classytic/mongokit": "^3.18.0",
96
- "@classytic/primitives": ">=0.5.0",
97
- "@classytic/repo-core": "^0.7.0",
95
+ "@classytic/mongokit": "^3.22.1",
96
+ "@classytic/primitives": "^0.11.0",
97
+ "@classytic/repo-core": "^0.13.0",
98
98
  "@types/node": "^25.5.0",
99
99
  "knip": "^6.7.0",
100
100
  "mongodb-memory-server": "^10.2.3",