@classytic/cart 0.1.2 → 0.2.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 (32) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +12 -2
  3. package/dist/{shipping.bridge-CmQFTgSE.d.mts → clock.port-BUe6Dk_M.d.mts} +27 -10
  4. package/dist/{create-cart-B4l61iKT.mjs → create-cart-Iqvlv0V2.mjs} +183 -24
  5. package/dist/domain/errors/index.d.mts +1 -1
  6. package/dist/domain/errors/index.mjs +2 -2
  7. package/dist/domain/index.d.mts +7 -7
  8. package/dist/domain/index.mjs +3 -3
  9. package/dist/domain/ports/index.d.mts +2 -2
  10. package/dist/domain/saga/index.d.mts +1 -1
  11. package/dist/domain/saga/index.mjs +1 -1
  12. package/dist/engine/cart-config.schema.d.mts +7 -1
  13. package/dist/engine/cart-config.schema.mjs +10 -1
  14. package/dist/engine/index.d.mts +1 -1
  15. package/dist/engine/index.mjs +1 -1
  16. package/dist/{errors-DzR7Pipp.mjs → errors-7Pd0yATM.mjs} +1 -26
  17. package/dist/{id.port-C7ygWLRU.d.mts → id.port-DitjeoHg.d.mts} +1 -19
  18. package/dist/{index-BFBUk6qT.d.mts → index-qfN8dZN9.d.mts} +6 -5
  19. package/dist/index.d.mts +41 -15
  20. package/dist/index.mjs +84 -27
  21. package/dist/{internal-event-bus-DKcDteh-.d.mts → internal-event-bus-vMG6v-e6.d.mts} +71 -6
  22. package/dist/{kind-registry-C1n47C7h.d.mts → kind-registry-D03c2VV5.d.mts} +1 -1
  23. package/dist/kinds/index.d.mts +2 -2
  24. package/dist/kinds/index.mjs +2 -2
  25. package/dist/{line-kind-Ck3fVXzG.d.mts → line-kind-CKOWafK0.d.mts} +11 -6
  26. package/dist/{reservation.entity-b5cZ1ojx.d.mts → reservation.entity-WdaZCJg9.d.mts} +3 -3
  27. package/dist/{price-changed.error-C-wGVcfc.mjs → stale-quote.error-BkFLXWo5.mjs} +30 -4
  28. package/dist/{state-transitions-e4z3Yhxb.mjs → state-transitions-Bm3lC2Uv.mjs} +2 -2
  29. package/dist/{state-transitions-X_Eix5Iw.d.mts → state-transitions-D8CRykBv.d.mts} +7 -7
  30. package/dist/{variant.kind-9P1DXdXu.d.mts → variant.kind-Cpo_Hh7G.d.mts} +65 -2
  31. package/dist/{variant.kind-DfEh2oku.mjs → variant.kind-z2gwH9Vo.mjs} +92 -10
  32. package/package.json +8 -6
package/CHANGELOG.md CHANGED
@@ -3,6 +3,43 @@
3
3
  Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
4
4
  adhering to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
5
 
6
+ ## [0.2.0]
7
+
8
+ ### Changed
9
+
10
+ - **`pricingHash` is now hex SHA-256** over the same canonical sorted
11
+ line string (was the raw concatenation). The hash is opaque — compare,
12
+ never parse. **Migration:** drafts priced before 0.2.0 carry old-format
13
+ hashes; the first checkout attempt against them raises
14
+ `PriceChangedError` once and the client re-fetches/re-confirms.
15
+ Accepted clean break.
16
+ - **Guest→user merge is now double-CAS atomic.** `mergeDrafts` retires the
17
+ source with a version CAS, then writes the target with a version CAS
18
+ (bounded retries) — a concurrent add-to-cart on either draft is retried
19
+ into the result instead of silently lost. `DraftRepository.markAbandoned`
20
+ gains an optional `{ expectedVersion }`; `replaceLines` gains an
21
+ optional `expectedVersion` input.
22
+ - **Zombie open checkouts self-heal.** `createFromDraft` CAS-expires an
23
+ open checkout older than `checkout.staleOpenCheckoutMs` (new config,
24
+ default 10 min) and creates a fresh one; fresh open checkouts are still
25
+ returned idempotently. `expireStaleOpenCheckouts` remains the bulk cron
26
+ sweep. No TTL deletes — checkout rows stay as audit history.
27
+ - **`PriceChangedError` context now includes `currentPricing`** (per-line
28
+ `lineId`/`quantity`/`unitPrice`/`subtotals` + `totals`) so hosts render
29
+ a price diff without re-fetching the draft.
30
+ - **`ctx.signal` is threaded to every mongokit call** — cancelled requests
31
+ stop at the driver-call boundary (repo-core 0.6 `QueryOptions.signal`).
32
+ - Peer deps: `@classytic/mongokit >= 3.16`, `@classytic/repo-core >= 0.6`.
33
+
34
+ ### Added
35
+
36
+ - `checkoutConfigSchema` / `CartConfig.checkout.staleOpenCheckoutMs` and
37
+ `DEFAULT_STALE_OPEN_CHECKOUT_MS` export.
38
+ - Documented host contract: checkout → order → `inventory.commit()`
39
+ (CLAUDE.md "Host responsibilities") — `commit()` intentionally does not
40
+ commit inventory holds.
41
+ - Scenario 10: stale quote → `revalidate()` reprice path (`bundle` kind).
42
+
6
43
  ## [0.1.0]
7
44
 
8
45
  Initial release. Framework-agnostic universal cart engine — mutable drafts,
package/README.md CHANGED
@@ -70,9 +70,19 @@ No modes. No tiers. Pass the bridges you need:
70
70
  - **Display snapshots** — denormalized on every line at add-time. UI
71
71
  reads `line.display.name` directly. Zero `.populate()` calls.
72
72
  - **Optimistic concurrency** — `version` field + `ConcurrencyError` on
73
- stale writes.
73
+ stale writes. Guest→user merge is double-CAS guarded (source retired
74
+ with a version check, target written with a version check, bounded
75
+ retries) so concurrent add-to-carts are never lost.
76
+ - **Pricing hash interlock** — `pricingHash` is an opaque hex SHA-256
77
+ digest of the priced lines; `createFromDraft` rejects a mismatch with
78
+ `PriceChangedError`, whose context carries the current per-line prices
79
+ and totals so the host can render a diff without re-fetching.
74
80
  - **Checkout state** — `open → finalized | canceled`. Cart snapshots;
75
- host commits.
81
+ host commits (and then commits inventory holds — see CLAUDE.md "Host
82
+ responsibilities"). Zombie `open` checkouts self-heal: `createFromDraft`
83
+ CAS-expires any open checkout older than `checkout.staleOpenCheckoutMs`
84
+ (default 10 min) and creates a fresh one; `expireStaleOpenCheckouts`
85
+ remains the bulk cron sweep.
76
86
  - **Arc-compatible** — event definitions match Arc structurally, and hosts
77
87
  can inject their app-level outbox store for durable event persistence.
78
88
 
@@ -41,10 +41,9 @@ interface PricedLine {
41
41
  /** Accumulated tax applied to this line by the tax step. */
42
42
  taxTotal: Money;
43
43
  /**
44
- * Validity window for this priced line. The saga's step 2
45
- * (revalidation) compares this against the clock and triggers
46
- * LineKind.revalidate() on expiry according to the kind's StaleBehavior.
47
- * `null` means no expiry (e.g., hard-priced SKUs).
44
+ * Validity window for this priced line. Checkout compares this against
45
+ * the engine clock and rejects expired snapshots without extra bridge
46
+ * reads. `null` means no expiry (e.g., hard-priced SKUs).
48
47
  */
49
48
  validUntil: Date | null;
50
49
  /**
@@ -58,10 +57,10 @@ interface PricedLine {
58
57
  /**
59
58
  * Whole-cart pricing snapshot — the output of running the full pipeline.
60
59
  *
61
- * Written to the draft on every mutation and frozen onto the checkout on saga
62
- * step 4. Drives idempotent revalidation: saga step 3 compares
63
- * `snapshot.pricingHash` against the client-supplied expectedPricingHash and
64
- * aborts with PriceChangedError if they differ.
60
+ * Written to the draft on every mutation and frozen onto the checkout. Drives
61
+ * cheap checkout freshness: first reject expired `pricingValidUntil`, then
62
+ * compare `snapshot.pricingHash` against the client-supplied
63
+ * expectedPricingHash and abort with PriceChangedError if they differ.
65
64
  */
66
65
  interface PricingSnapshot {
67
66
  /** Per-line priced rows, one entry per LineItem in draft order. */
@@ -92,7 +91,7 @@ interface PricingSnapshot {
92
91
  pricingValidUntil: Date | null;
93
92
  /**
94
93
  * Content hash of the priced snapshot. Computed from the sorted line array,
95
- * adjustments, and totals. Used by the finalize saga step 3 to detect
94
+ * adjustments, and totals. Used by checkout's hash check to detect
96
95
  * "price changed since the client confirmed" and abort with
97
96
  * PriceChangedError so the client can re-display and re-confirm.
98
97
  */
@@ -535,4 +534,22 @@ interface ShippingMethod {
535
534
  };
536
535
  }
537
536
  //#endregion
538
- export { PricingSnapshot as C, PricedLine as S, PromotionsBridge as _, TaxBreakdown as a, BridgeStatus as b, TaxCalculationResult as c, ReservationRequest as d, CatalogBridge as f, PromotionResult as g, CartSnapshot as h, ShippingQuoteRequest as i, InventoryBridge as l, AdjustmentSpec as m, ShippingMethod as n, TaxBridge as o, ProductSummary as p, ShippingQuote as r, TaxCalculationRequest as s, ShippingBridge as t, ReservationRef as u, Address as v, OperationContext$1 as x, BridgeRef as y };
537
+ //#region src/domain/ports/clock.port.d.ts
538
+ /**
539
+ * Clock port — the one source of "now" in the cart engine.
540
+ *
541
+ * Injected through config so tests can install a fake clock and fast-forward
542
+ * through TTLs, validity windows, and saga lease expirations. Production
543
+ * hosts pass nothing and get a default `systemClock` that calls `new Date()`.
544
+ *
545
+ * Never read `Date.now()` or `new Date()` directly in cart code. Always use
546
+ * `engine.clock.now()`. Integration tests assert this via ESLint rule.
547
+ */
548
+ interface ClockPort {
549
+ /** Wall clock — used for timestamps, TTL expiry, idempotency leases. */
550
+ now(): Date;
551
+ }
552
+ /** Default system clock — passes straight through to `new Date()`. */
553
+ declare const systemClock: ClockPort;
554
+ //#endregion
555
+ export { OperationContext$1 as C, BridgeStatus as S, PricingSnapshot as T, CartSnapshot as _, ShippingQuote as a, Address as b, TaxBridge as c, InventoryBridge as d, ReservationRef as f, AdjustmentSpec as g, ProductSummary as h, ShippingMethod as i, TaxCalculationRequest as l, CatalogBridge as m, systemClock as n, ShippingQuoteRequest as o, ReservationRequest as p, ShippingBridge as r, TaxBreakdown as s, ClockPort as t, TaxCalculationResult as u, PromotionResult as v, PricedLine as w, BridgeRef as x, PromotionsBridge as y };
@@ -1,14 +1,15 @@
1
- import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "./price-changed.error-C-wGVcfc.mjs";
1
+ import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "./stale-quote.error-BkFLXWo5.mjs";
2
2
  import { t as KindError } from "./kind.error-DIaJpdUb.mjs";
3
3
  import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
4
4
  import { n as cryptoIdPort, r as systemClock } from "./id.port-BhbFZJPm.mjs";
5
5
  import { t as createKindRegistry } from "./kind-registry-C99h_-8t.mjs";
6
- import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-e4z3Yhxb.mjs";
6
+ import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-Bm3lC2Uv.mjs";
7
7
  import { money } from "@classytic/primitives/money";
8
8
  import { matchEventPattern } from "@classytic/primitives/events";
9
9
  import mongoose, { Schema } from "mongoose";
10
- import { resolveTenantConfig } from "@classytic/primitives/tenant";
10
+ import { resolveTenantConfig } from "@classytic/repo-core/tenant";
11
11
  import { Repository, customIdPlugin, isDuplicateKeyError, multiTenantPlugin, prefixedId } from "@classytic/mongokit";
12
+ import { createHash } from "node:crypto";
12
13
  //#region src/models/checkout.model.ts
13
14
  function createCheckoutModel(connection, opts = {}) {
14
15
  const schema = new Schema({
@@ -365,7 +366,7 @@ function createIdempotencyModel(connection, opts = {}) {
365
366
  //#region src/models/inject-tenant.ts
366
367
  /**
367
368
  * Mongoose-specific adapter around `resolveTenantConfig()` from
368
- * `@classytic/primitives/tenant`. The pure resolution lives in primitives
369
+ * `@classytic/repo-core/tenant`. The pure resolution lives in primitives
369
370
  * (zero runtime deps) — this file only handles the Mongoose schema
370
371
  * mutations (add field, prepend tenant to indexes) that primitives can't
371
372
  * own without a mongoose dependency.
@@ -569,6 +570,13 @@ var CartEventPublisher = class {
569
570
  //#endregion
570
571
  //#region src/repositories/checkout.repository.ts
571
572
  /**
573
+ * Default zombie window for open checkouts — matches the package's
574
+ * existing expiry default (`reservationConfigSchema.defaultTtlSeconds`,
575
+ * 600s): once any reservation hold backing the checkout has lapsed, the
576
+ * open snapshot has no claim on anything and is safe to self-expire.
577
+ */
578
+ const DEFAULT_STALE_OPEN_CHECKOUT_MS = 6e5;
579
+ /**
572
580
  * CheckoutRepository — extends mongokit's `Repository<CheckoutDocument>`.
573
581
  *
574
582
  * All domain logic (createFromDraft with hash interlock, commit, cancel)
@@ -580,11 +588,13 @@ var CheckoutRepository = class extends Repository {
580
588
  draftRepo;
581
589
  clock;
582
590
  eventPublisher;
591
+ staleOpenCheckoutMs;
583
592
  constructor(model, plugins, deps) {
584
593
  super(model, plugins);
585
594
  this.draftRepo = deps.draftRepo;
586
595
  this.clock = deps.clock;
587
596
  this.eventPublisher = deps.eventPublisher;
597
+ this.staleOpenCheckoutMs = deps.staleOpenCheckoutMs ?? 6e5;
588
598
  }
589
599
  async findByPublicId(publicId, ctx) {
590
600
  return await this.getByQuery({ publicId }, this.readOptions(ctx));
@@ -610,13 +620,29 @@ var CheckoutRepository = class extends Repository {
610
620
  if (draft.status !== "active") throw new Error(`Cannot create checkout from draft in status '${draft.status}'`);
611
621
  if (draft.lines.length === 0) throw new Error("Cannot create checkout from an empty draft");
612
622
  if (!draft.pricing) throw new Error("Cannot create checkout from a draft with no priced snapshot — call addItem first");
613
- const draftPricingHash = draft.pricing.pricingHash;
614
- if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", { draftPublicId: input.draftPublicId });
623
+ const pricingSnapshot = draft.pricing;
624
+ assertSnapshotNotExpired(pricingSnapshot, draft.lines, () => this.clock.now());
625
+ const draftPricingHash = pricingSnapshot.pricingHash;
626
+ if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", {
627
+ draftPublicId: input.draftPublicId,
628
+ currentPricing: {
629
+ lines: (pricingSnapshot.lines ?? []).map((l) => ({
630
+ lineId: l.lineId,
631
+ quantity: l.quantity,
632
+ unitPrice: l.unitPrice,
633
+ subtotals: l.subtotals
634
+ })),
635
+ totals: pricingSnapshot.totals
636
+ }
637
+ });
615
638
  const existing = await this.findOpenByDraft(draft._id, ctx);
616
- if (existing) return existing;
639
+ if (existing) {
640
+ if (!this.isStaleOpen(existing)) return existing;
641
+ await this.expireZombie(existing, ctx);
642
+ }
617
643
  const nowIso = this.clock.now().toISOString();
618
644
  let created;
619
- try {
645
+ for (let attempt = 0;; attempt++) try {
620
646
  created = await this.create({
621
647
  draftId: draft._id,
622
648
  actorRef: draft.actorRef,
@@ -637,10 +663,17 @@ var CheckoutRepository = class extends Repository {
637
663
  metadata: null,
638
664
  privateMetadata: null
639
665
  }, this.writeOptions(ctx));
666
+ break;
640
667
  } catch (err) {
641
668
  if (isDuplicateKeyError(err)) {
642
669
  const winner = await this.findOpenByDraft(draft._id, ctx);
643
- if (winner) return winner;
670
+ if (winner) {
671
+ if (!this.isStaleOpen(winner)) return winner;
672
+ if (attempt === 0) {
673
+ await this.expireZombie(winner, ctx);
674
+ continue;
675
+ }
676
+ }
644
677
  }
645
678
  throw err;
646
679
  }
@@ -669,6 +702,7 @@ var CheckoutRepository = class extends Repository {
669
702
  organizationId: ctx.organizationId,
670
703
  skipTenant: ctx.skipTenant,
671
704
  session: ctx.session,
705
+ signal: ctx.signal,
672
706
  lean: true,
673
707
  throwOnNotFound: false
674
708
  });
@@ -756,6 +790,13 @@ var CheckoutRepository = class extends Repository {
756
790
  * call this from a periodic job (cron, Streamline, etc.) at whatever
757
791
  * cadence matches their checkout completion SLA.
758
792
  *
793
+ * This is the BULK sweep. `createFromDraft` additionally self-heals
794
+ * lazily: when it finds an open checkout older than
795
+ * `staleOpenCheckoutMs`, it CAS-expires that one zombie inline and
796
+ * creates a fresh checkout — so a customer is never stuck waiting for
797
+ * the next cron tick. Keep both: lazy healing fixes the active
798
+ * customer's path; the cron reclaims abandoned rows nobody revisits.
799
+ *
759
800
  * Returns the count of rows expired. Caller scopes the operation via
760
801
  * `ctx` — pass `ctx.organizationId` to scope to one tenant, or use
761
802
  * `skipTenant: true` to expire across the board (only safe for the
@@ -779,11 +820,54 @@ var CheckoutRepository = class extends Repository {
779
820
  } }, this.writeOptions(ctx));
780
821
  return { count: result?.modifiedCount ?? result?.matchedCount ?? 0 };
781
822
  }
823
+ /** Is this open checkout past the zombie window? */
824
+ isStaleOpen(checkout) {
825
+ const createdAt = checkout.createdAt ? new Date(checkout.createdAt).getTime() : NaN;
826
+ if (Number.isNaN(createdAt)) return false;
827
+ return this.clock.now().getTime() - createdAt >= this.staleOpenCheckoutMs;
828
+ }
829
+ /**
830
+ * CAS-expire a zombie open checkout: `open → canceled` with
831
+ * `canceledReason: 'expired'` — same terminal shape the cron
832
+ * (`expireStaleOpenCheckouts`) writes, so audit history is uniform.
833
+ * The `{ state: 'open', version }` filter makes the transition atomic:
834
+ * a concurrent commit/cancel/expiry wins and this call is a no-op
835
+ * (returns false). No CHECKOUT_CANCELED event — expiry is janitorial,
836
+ * matching the cron method's contract.
837
+ */
838
+ async expireZombie(checkout, ctx) {
839
+ try {
840
+ await this.update(checkout._id, {
841
+ $set: {
842
+ state: "canceled",
843
+ canceledReason: "expired",
844
+ flowState: {
845
+ ...checkout.flowState,
846
+ updatedAt: this.clock.now().toISOString()
847
+ }
848
+ },
849
+ $inc: { version: 1 }
850
+ }, {
851
+ ...this.writeOptions(ctx),
852
+ query: {
853
+ state: "open",
854
+ version: checkout.version
855
+ },
856
+ throwOnNotFound: true,
857
+ lean: true
858
+ });
859
+ return true;
860
+ } catch (err) {
861
+ if (isNotFound$2(err)) return false;
862
+ throw err;
863
+ }
864
+ }
782
865
  readOptions(ctx) {
783
866
  return {
784
867
  organizationId: ctx.organizationId,
785
868
  skipTenant: ctx.skipTenant,
786
869
  session: ctx.session,
870
+ signal: ctx.signal,
787
871
  lean: true,
788
872
  throwOnNotFound: false
789
873
  };
@@ -792,7 +876,8 @@ var CheckoutRepository = class extends Repository {
792
876
  return {
793
877
  organizationId: ctx.organizationId,
794
878
  skipTenant: ctx.skipTenant,
795
- session: ctx.session
879
+ session: ctx.session,
880
+ signal: ctx.signal
796
881
  };
797
882
  }
798
883
  async requireCheckout(publicId, ctx) {
@@ -801,6 +886,19 @@ var CheckoutRepository = class extends Repository {
801
886
  return checkout;
802
887
  }
803
888
  };
889
+ function assertSnapshotNotExpired(pricing, draftLines, now) {
890
+ if (!pricing.pricingValidUntil) return;
891
+ const expiresAt = new Date(pricing.pricingValidUntil);
892
+ const currentTime = now();
893
+ if (Number.isNaN(expiresAt.getTime()) || expiresAt > currentTime) return;
894
+ const expired = pricing.lines?.find((pricedLine) => {
895
+ if (!pricedLine.validUntil) return false;
896
+ const validUntil = new Date(pricedLine.validUntil);
897
+ return !Number.isNaN(validUntil.getTime()) && validUntil <= currentTime;
898
+ });
899
+ const line = draftLines.find((item) => item.lineId === expired?.lineId);
900
+ throw new StaleQuoteError(expired?.lineId ?? "<cart>", typeof line?.kind === "string" ? line.kind : "<unknown>", "pricing snapshot expired; refresh the draft before checkout", { pricingValidUntil: expiresAt.toISOString() });
901
+ }
804
902
  function isNotFound$2(err) {
805
903
  return typeof err === "object" && err !== null && err.status === 404;
806
904
  }
@@ -831,8 +929,10 @@ function isNotFound$2(err) {
831
929
  * checkout-freeze still catches drift, so reuse here is safe.
832
930
  */
833
931
  async function runPricing(opts) {
932
+ const computedAt = opts.clock.now();
834
933
  const kindCtx = {
835
934
  ...opts.ctx,
935
+ clock: opts.clock,
836
936
  bridges: {
837
937
  catalog: opts.bridges.catalog,
838
938
  inventory: opts.bridges.inventory,
@@ -872,7 +972,7 @@ async function runPricing(opts) {
872
972
  for (const result of promoResults.sort((a, b) => b.priority - a.priority)) {
873
973
  const appliedAmount = computeAdjustmentAmount(result, pricedLines, opts.currency);
874
974
  adjustments.push({
875
- adjustmentId: `adj_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
975
+ adjustmentId: `adj_${computedAt.getTime()}_${adjustments.length + 1}`,
876
976
  source: "promotion",
877
977
  ruleRef: result.ruleRef,
878
978
  spec: result.adjustment,
@@ -880,7 +980,7 @@ async function runPricing(opts) {
880
980
  appliedAmount,
881
981
  explanation: result.explanation,
882
982
  priority: result.priority,
883
- appliedAt: opts.clock.now()
983
+ appliedAt: computedAt
884
984
  });
885
985
  if (result.targetLineId) {
886
986
  const target = pricedLines.find((l) => l.lineId === result.targetLineId);
@@ -960,7 +1060,7 @@ async function runPricing(opts) {
960
1060
  },
961
1061
  pricingValidUntil,
962
1062
  pricingHash: buildPricingHash(pricedLines),
963
- computedAt: opts.clock.now()
1063
+ computedAt
964
1064
  },
965
1065
  adjustments
966
1066
  };
@@ -1021,8 +1121,27 @@ function rebuildSubtotals(prior, line, currency) {
1021
1121
  kindMeta: prior.kindMeta
1022
1122
  };
1023
1123
  }
1124
+ /**
1125
+ * Pricing hash — SHA-256 over a canonical string of the priced lines.
1126
+ *
1127
+ * Canonical string assumptions (do not change without a version bump):
1128
+ * - One member per line: `lineId:quantity:postPromoPostTax.amount:currency`.
1129
+ * The post-promo-post-tax subtotal is the value the customer confirmed,
1130
+ * so promo and tax drift both invalidate the hash; shipping and
1131
+ * order-level adjustments are NOT hashed (they are order-scoped, not
1132
+ * line-scoped, and the host re-displays them from totals).
1133
+ * - Members are sorted lexicographically so line ORDER never affects the
1134
+ * hash — merges and re-reads that reorder lines stay hash-stable.
1135
+ * - Members are `|`-delimited; `lineId`s are engine-generated
1136
+ * (`line_<id>`) and never contain `:` or `|`, so the encoding is
1137
+ * unambiguous.
1138
+ *
1139
+ * The digest is hex-encoded SHA-256 — opaque to clients. Treat it as a
1140
+ * token: compare for equality, never parse.
1141
+ */
1024
1142
  function buildPricingHash(lines) {
1025
- return lines.map((l) => `${l.lineId}:${l.quantity}:${l.subtotals.postPromoPostTax.amount}:${l.subtotals.postPromoPostTax.currency}`).sort().join("|");
1143
+ const canonical = lines.map((l) => `${l.lineId}:${l.quantity}:${l.subtotals.postPromoPostTax.amount}:${l.subtotals.postPromoPostTax.currency}`).sort().join("|");
1144
+ return createHash("sha256").update(canonical).digest("hex");
1026
1145
  }
1027
1146
  function computeAdjustmentAmount(result, lines, currency) {
1028
1147
  const spec = result.adjustment;
@@ -1052,6 +1171,20 @@ function computeAdjustmentAmount(result, lines, currency) {
1052
1171
  * Multi-tenant scoping is enforced by `multiTenantPlugin` at POLICY priority;
1053
1172
  * `publicId` is generated by `customIdPlugin`. Optimistic concurrency runs
1054
1173
  * through mongokit's `update()` so all hooks (audit, observability) fire.
1174
+ *
1175
+ * ## Concurrency invariant — read-modify-write on `lines` is CAS-safe
1176
+ *
1177
+ * Every line mutation (addItem, updateItemQuantity, removeItem, clear,
1178
+ * replaceLines) rebuilds the FULL `lines` array in memory from a single
1179
+ * read and persists it via `updateWithVersion`, which only matches when
1180
+ * the stored `version` still equals the version of that read. Any
1181
+ * concurrent mutation bumps `version`, so the stale rebuild can never
1182
+ * land — the loser gets a typed `ConcurrencyError` and retries from a
1183
+ * fresh read. Do NOT "optimize" these paths into positional `$push` /
1184
+ * `$set('lines.$')` array operators: pricing snapshots are derived from
1185
+ * the whole line set, so a partial array write would let `lines` and
1186
+ * `pricing` drift apart. The version CAS is what makes the in-memory
1187
+ * rebuild safe; the rebuild is what keeps pricing consistent.
1055
1188
  */
1056
1189
  var DraftRepository = class extends Repository {
1057
1190
  kinds;
@@ -1259,15 +1392,24 @@ var DraftRepository = class extends Repository {
1259
1392
  /**
1260
1393
  * Atomic transition `active → abandoned`. Returns null if the draft was
1261
1394
  * already in a non-active state.
1395
+ *
1396
+ * Pass `opts.expectedVersion` to ALSO compare-and-set on `version` —
1397
+ * the merge service uses this to guarantee the source draft's line set
1398
+ * it captured is exactly the line set being retired (a concurrent
1399
+ * add-to-cart bumps `version`, the CAS misses, and the merge retries
1400
+ * from a fresh read instead of silently dropping the new line).
1262
1401
  */
1263
- async markAbandoned(draftId, ctx) {
1402
+ async markAbandoned(draftId, ctx, opts = {}) {
1264
1403
  try {
1265
1404
  const updated = await this.update(draftId, {
1266
1405
  $set: { status: "abandoned" },
1267
1406
  $inc: { version: 1 }
1268
1407
  }, {
1269
1408
  ...this.writeOptions(ctx),
1270
- query: { status: "active" },
1409
+ query: {
1410
+ status: "active",
1411
+ ...opts.expectedVersion !== void 0 ? { version: opts.expectedVersion } : {}
1412
+ },
1271
1413
  lean: true
1272
1414
  });
1273
1415
  if (!updated) return null;
@@ -1311,12 +1453,19 @@ var DraftRepository = class extends Repository {
1311
1453
  * Replace the line collection atomically and refresh the pricing snapshot.
1312
1454
  * Internal services use this to keep merge-like flows inside repository
1313
1455
  * concurrency + pricing rules instead of hand-writing persistence logic.
1456
+ *
1457
+ * Pass `expectedVersion` when `lines` was computed from an EARLIER read
1458
+ * of the draft: the CAS then pins to that read's version, so any
1459
+ * mutation that landed in between (concurrent add-to-cart during a
1460
+ * merge) surfaces as `ConcurrencyError` instead of being overwritten.
1461
+ * Without it, the CAS pins to this method's own fresh read — safe for
1462
+ * callers whose `lines` doesn't derive from draft state.
1314
1463
  */
1315
1464
  async replaceLines(input, ctx) {
1316
1465
  const draft = await this.requireDraft(input.draftPublicId, ctx);
1317
1466
  const nextLines = input.lines.map((line) => ({ ...line }));
1318
1467
  const pricing = nextLines.length === 0 ? null : (await this.price(nextLines, draft.currency, ctx, draft.pricing)).snapshot;
1319
- return this.updateWithVersion(draft._id, draft.version, {
1468
+ return this.updateWithVersion(draft._id, input.expectedVersion ?? draft.version, {
1320
1469
  lines: nextLines,
1321
1470
  pricing
1322
1471
  }, ctx);
@@ -1329,6 +1478,7 @@ var DraftRepository = class extends Repository {
1329
1478
  organizationId: ctx.organizationId,
1330
1479
  skipTenant: ctx.skipTenant,
1331
1480
  session: ctx.session,
1481
+ signal: ctx.signal,
1332
1482
  lean: true,
1333
1483
  throwOnNotFound: false
1334
1484
  };
@@ -1337,7 +1487,8 @@ var DraftRepository = class extends Repository {
1337
1487
  return {
1338
1488
  organizationId: ctx.organizationId,
1339
1489
  skipTenant: ctx.skipTenant,
1340
- session: ctx.session
1490
+ session: ctx.session,
1491
+ signal: ctx.signal
1341
1492
  };
1342
1493
  }
1343
1494
  async price(lines, currency, ctx, previous) {
@@ -1359,6 +1510,7 @@ var DraftRepository = class extends Repository {
1359
1510
  kindContextFor(ctx) {
1360
1511
  return {
1361
1512
  ...ctx,
1513
+ clock: this.clock,
1362
1514
  bridges: {
1363
1515
  catalog: this.bridges.catalog,
1364
1516
  inventory: this.bridges.inventory,
@@ -1490,6 +1642,7 @@ var IdempotencyRepository = class extends Repository {
1490
1642
  } }, {
1491
1643
  returnDocument: "after",
1492
1644
  session: ctx.session,
1645
+ signal: ctx.signal,
1493
1646
  lean: true
1494
1647
  }) ?? null;
1495
1648
  }
@@ -1508,6 +1661,7 @@ var IdempotencyRepository = class extends Repository {
1508
1661
  } }, {
1509
1662
  returnDocument: "after",
1510
1663
  session: ctx.session,
1664
+ signal: ctx.signal,
1511
1665
  lean: true
1512
1666
  }) ?? null;
1513
1667
  }
@@ -1526,6 +1680,7 @@ var IdempotencyRepository = class extends Repository {
1526
1680
  } }, {
1527
1681
  returnDocument: "after",
1528
1682
  session: ctx.session,
1683
+ signal: ctx.signal,
1529
1684
  lean: true
1530
1685
  }) ?? null;
1531
1686
  }
@@ -1566,7 +1721,7 @@ var ReservationRepository = class extends Repository {
1566
1721
  page: 1,
1567
1722
  limit,
1568
1723
  countStrategy: "none"
1569
- }, this.readOptions(ctx))).docs;
1724
+ }, this.readOptions(ctx))).data;
1570
1725
  }
1571
1726
  /** Atomic transition `held → released` via version check. */
1572
1727
  async markReleased(reservationId, expectedVersion, reason, ctx) {
@@ -1609,6 +1764,7 @@ var ReservationRepository = class extends Repository {
1609
1764
  organizationId: ctx.organizationId,
1610
1765
  skipTenant: ctx.skipTenant,
1611
1766
  session: ctx.session,
1767
+ signal: ctx.signal,
1612
1768
  lean: true
1613
1769
  };
1614
1770
  }
@@ -1616,7 +1772,8 @@ var ReservationRepository = class extends Repository {
1616
1772
  return {
1617
1773
  organizationId: ctx.organizationId,
1618
1774
  skipTenant: ctx.skipTenant,
1619
- session: ctx.session
1775
+ session: ctx.session,
1776
+ signal: ctx.signal
1620
1777
  };
1621
1778
  }
1622
1779
  };
@@ -1635,7 +1792,7 @@ function tenantPlugin(fieldType = "objectId") {
1635
1792
  });
1636
1793
  }
1637
1794
  function createCartRepositories(models, config) {
1638
- const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {}, tenantFieldType = "objectId", multiTenant = true } = config;
1795
+ const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {}, tenantFieldType = "objectId", multiTenant = true, staleOpenCheckoutMs } = config;
1639
1796
  const eventPublisher = new CartEventPublisher({
1640
1797
  events,
1641
1798
  outbox,
@@ -1677,7 +1834,8 @@ function createCartRepositories(models, config) {
1677
1834
  ], {
1678
1835
  draftRepo: draft,
1679
1836
  clock,
1680
- eventPublisher
1837
+ eventPublisher,
1838
+ staleOpenCheckoutMs
1681
1839
  }),
1682
1840
  reservation: new ReservationRepository(models.Reservation, [
1683
1841
  ...tenantPlugins,
@@ -1774,7 +1932,8 @@ async function createCart(config) {
1774
1932
  outbox: config.outbox,
1775
1933
  plugins: config.repositoryPlugins,
1776
1934
  tenantFieldType,
1777
- multiTenant
1935
+ multiTenant,
1936
+ staleOpenCheckoutMs: config.checkout?.staleOpenCheckoutMs
1778
1937
  });
1779
1938
  mode = "full";
1780
1939
  }
@@ -1794,4 +1953,4 @@ async function createCart(config) {
1794
1953
  };
1795
1954
  }
1796
1955
  //#endregion
1797
- export { IdempotencyRepository as a, CheckoutRepository as c, createIdempotencyModel as d, createDraftModel as f, ReservationRepository as i, createCartModels as l, InProcessCartEventBus as n, DraftRepository as o, createCheckoutModel as p, createCartRepositories as r, runPricing as s, createCart as t, createReservationModel as u };
1956
+ export { IdempotencyRepository as a, CheckoutRepository as c, createReservationModel as d, createIdempotencyModel as f, ReservationRepository as i, DEFAULT_STALE_OPEN_CHECKOUT_MS as l, createCheckoutModel as m, InProcessCartEventBus as n, DraftRepository as o, createDraftModel as p, createCartRepositories as r, runPricing as s, createCart as t, createCartModels as u };
@@ -1,2 +1,2 @@
1
- import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "../../index-BFBUk6qT.mjs";
1
+ import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "../../index-qfN8dZN9.mjs";
2
2
  export { CartError, CartErrorCategory, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, SagaFailurePhase, StaleQuoteError, StateTransitionError, UnknownKindError };
@@ -1,6 +1,6 @@
1
1
  import { t as CartError } from "../../cart.error-BwWy4RlY.mjs";
2
- import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "../../price-changed.error-C-wGVcfc.mjs";
2
+ import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "../../stale-quote.error-BkFLXWo5.mjs";
3
3
  import { n as UnknownKindError, t as KindError } from "../../kind.error-DIaJpdUb.mjs";
4
- import { a as ReservationError, i as SagaError, n as IdempotencyBusyError, r as IdempotencyStorageError, t as StaleQuoteError } from "../../errors-DzR7Pipp.mjs";
4
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../../errors-7Pd0yATM.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 };
@@ -1,12 +1,12 @@
1
- import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "../index-BFBUk6qT.mjs";
1
+ import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "../index-qfN8dZN9.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";
5
- import { C as PricingSnapshot, S as PricedLine, _ as PromotionsBridge, a as TaxBreakdown, b as BridgeStatus, c as TaxCalculationResult, d as ReservationRequest, f as CatalogBridge, g as PromotionResult, h as CartSnapshot, i as ShippingQuoteRequest, l as InventoryBridge, m as AdjustmentSpec, n as ShippingMethod, o as TaxBridge, p as ProductSummary, r as ShippingQuote, s as TaxCalculationRequest, t as ShippingBridge, u as ReservationRef, x as OperationContext, y as BridgeRef } from "../shipping.bridge-CmQFTgSE.mjs";
6
- import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-b5cZ1ojx.mjs";
7
- import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../state-transitions-X_Eix5Iw.mjs";
8
- import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "../line-kind-Ck3fVXzG.mjs";
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-C1n47C7h.mjs";
10
- import { a as systemClock, i as ClockPort, n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../id.port-C7ygWLRU.mjs";
5
+ import { C as OperationContext, S as BridgeStatus, T as PricingSnapshot, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, w as PricedLine, x as BridgeRef, y as PromotionsBridge } from "../clock.port-BUe6Dk_M.mjs";
6
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-WdaZCJg9.mjs";
7
+ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../state-transitions-D8CRykBv.mjs";
8
+ import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "../line-kind-CKOWafK0.mjs";
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-D03c2VV5.mjs";
10
+ import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../id.port-DitjeoHg.mjs";
11
11
  import { Money, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
12
12
  export { type Adjustment, AdjustmentSpec, BridgeRef, BridgeStatus, CART_REF_NEW, CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CartAggregateType, CartDomainEvent, CartError, CartErrorCategory, CartEventAggregate, CartEventDefinition, CartEventDefinitionInput, CartEventMap, CartEventMeta, CartEventName, CartEventPayload, CartEventRegistry, CartEvents, CartSnapshot, CatalogBridge, type Checkout, CheckoutFlowState, type CheckoutState, CheckoutStep, CheckoutStepNumber, ClockPort, ConcurrencyError, type Draft, type DraftStatus, EventSchema, EventSchemaProperty, EventValidationResult, EventValidator, IdPort, IdempotencyBusyError, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyStorageError, InvalidOutboxEventError, InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, OperationContext, type OperationName, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxErrorInfo, OutboxFailOptions, OutboxFailureContext, OutboxFailureDecision, OutboxFailurePolicy, OutboxOwnershipError, OutboxStore, OutboxStoreWriteOptions, OutboxWriteOptions, PayloadOf, PriceChangedError, type PricedLine, type PricingSnapshot, ProductSummary, PromotionResult, PromotionsBridge, type Reservation, ReservationError, ReservationRef, ReservationRequest, type ReservationStatus, type RevalidationResult, SagaDependencies, SagaError, SagaFailurePhase, SagaStepFn, ShippingBridge, ShippingMethod, ShippingQuote, ShippingQuoteRequest, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, TaxBreakdown, TaxBridge, TaxCalculationRequest, TaxCalculationResult, type TotalsSnapshot, UnknownKindError, type ValidityPolicy, addMoney, cartEventDefinitions, cartEventsByName, createCartEvent, createCartEventRegistry, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCartEvent, fromMajor, isLegalCheckoutTransition, money, multiplyMoney, subtractMoney, sumMoney, systemClock, toMajor };
@@ -1,14 +1,14 @@
1
1
  import { t as CART_REF_NEW } from "../idempotency-key.vo-D0lJsvGn.mjs";
2
2
  import { t as CartError } from "../cart.error-BwWy4RlY.mjs";
3
- import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "../price-changed.error-C-wGVcfc.mjs";
3
+ import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "../stale-quote.error-BkFLXWo5.mjs";
4
4
  import { n as UnknownKindError, t as KindError } from "../kind.error-DIaJpdUb.mjs";
5
- import { a as ReservationError, i as SagaError, n as IdempotencyBusyError, r as IdempotencyStorageError, t as StaleQuoteError } from "../errors-DzR7Pipp.mjs";
5
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../errors-7Pd0yATM.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
10
  import { t as createKindRegistry } from "../kind-registry-C99h_-8t.mjs";
11
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../state-transitions-e4z3Yhxb.mjs";
11
+ import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../state-transitions-Bm3lC2Uv.mjs";
12
12
  import "./events/index.mjs";
13
13
  import "./ports/index.mjs";
14
14
  import "./saga/index.mjs";