@classytic/cart 0.1.3 → 0.2.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.
Files changed (31) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +12 -2
  3. package/dist/{clock.port-BUe6Dk_M.d.mts → clock.port-CNu2wgdA.d.mts} +13 -1
  4. package/dist/{create-cart-4wql1XGi.mjs → create-cart-BeW0xAqD.mjs} +302 -30
  5. package/dist/domain/errors/index.d.mts +2 -2
  6. package/dist/domain/errors/index.mjs +2 -2
  7. package/dist/domain/index.d.mts +7 -7
  8. package/dist/domain/index.mjs +4 -4
  9. package/dist/domain/ports/index.d.mts +1 -1
  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 +12 -2
  14. package/dist/engine/index.d.mts +1 -1
  15. package/dist/engine/index.mjs +1 -1
  16. package/dist/{index-qfN8dZN9.d.mts → index-BB0XzkXF.d.mts} +45 -2
  17. package/dist/index.d.mts +52 -15
  18. package/dist/index.mjs +83 -26
  19. package/dist/{internal-event-bus-DhSLiZHi.d.mts → internal-event-bus-DhQKi9KS.d.mts} +104 -6
  20. package/dist/{kind-registry-D03c2VV5.d.mts → kind-registry-DG2iCCH1.d.mts} +1 -1
  21. package/dist/kinds/index.d.mts +1 -1
  22. package/dist/kinds/index.mjs +1 -1
  23. package/dist/{line-kind-CKOWafK0.d.mts → line-kind-B1mU1iJp.d.mts} +1 -1
  24. package/dist/{reservation.entity-WdaZCJg9.d.mts → reservation.entity-DLMxgpLE.d.mts} +3 -3
  25. package/dist/{state-transitions-D8CRykBv.d.mts → state-transitions-D19wZe-w.d.mts} +2 -2
  26. package/dist/{stale-quote.error-BkFLXWo5.mjs → unmanaged-session.error-C9Z1Yh9j.mjs} +31 -1
  27. package/dist/{variant.kind-z2gwH9Vo.mjs → variant.kind-BHiivO9B.mjs} +2 -1
  28. package/dist/{variant.kind-Cpo_Hh7G.d.mts → variant.kind-q-yv-vnQ.d.mts} +1 -1
  29. package/package.json +6 -6
  30. /package/dist/{kind-registry-C99h_-8t.mjs → kind-registry-Bvrj3P1Q.mjs} +0 -0
  31. /package/dist/{state-transitions-Bm3lC2Uv.mjs → state-transitions-Defw8gAt.mjs} +0 -0
@@ -1,14 +1,79 @@
1
- import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "./stale-quote.error-BkFLXWo5.mjs";
1
+ import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-C9Z1Yh9j.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
- import { t as createKindRegistry } from "./kind-registry-C99h_-8t.mjs";
6
- import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-Bm3lC2Uv.mjs";
5
+ import { t as createKindRegistry } from "./kind-registry-Bvrj3P1Q.mjs";
6
+ import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-Defw8gAt.mjs";
7
7
  import { money } from "@classytic/primitives/money";
8
8
  import { matchEventPattern } from "@classytic/primitives/events";
9
+ import { Repository, customIdPlugin, isDuplicateKeyError, multiTenantPlugin, prefixedId, withTransaction } from "@classytic/mongokit";
10
+ import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
9
11
  import mongoose, { Schema } from "mongoose";
10
12
  import { resolveTenantConfig } from "@classytic/repo-core/tenant";
11
- import { Repository, customIdPlugin, isDuplicateKeyError, multiTenantPlugin, prefixedId } from "@classytic/mongokit";
13
+ import { createHash } from "node:crypto";
14
+ //#region src/domain/ports/common.ts
15
+ /**
16
+ * Internal: key under which the post-commit event-publish queue is threaded
17
+ * through the context. When set, `CartEventPublisher.emit` APPENDS the event
18
+ * instead of publishing to the transport — the unit-of-work owner flushes
19
+ * the queue after its transaction commits, so a rollback can't leak ghost
20
+ * events to in-process subscribers. Outbox rows stay inside the transaction
21
+ * (the relay reads only committed rows). Same contract as
22
+ * `@classytic/refit` / `@classytic/review`.
23
+ *
24
+ * A Symbol so it never collides with host context fields.
25
+ */
26
+ const PENDING_EVENTS = Symbol.for("@classytic/cart:pendingEvents");
27
+ //#endregion
28
+ //#region src/engine/run-unit.ts
29
+ /**
30
+ * runUnit — transaction + post-commit-publish discipline for hosts composing
31
+ * multiple cart writes into one atomic unit. Same contract as
32
+ * `@classytic/refit` / `@classytic/review`:
33
+ *
34
+ * 1. Events emitted inside the unit are QUEUED (`ctx[PENDING_EVENTS]`),
35
+ * not published — the queue flushes only after the transaction commits
36
+ * (and resets on retry attempts), so a rollback can't leak ghost events
37
+ * to in-process subscribers. Outbox rows stay inside the transaction —
38
+ * the relay reads only committed rows.
39
+ * 2. A caller-owned `ctx.session` must arrive WITH a queue (or an outbox
40
+ * wired on the engine) — `CartEventPublisher.emit` enforces this.
41
+ */
42
+ async function runUnit(config, ctx, body) {
43
+ const internalCtx = ctx;
44
+ const externalQueue = internalCtx[PENDING_EVENTS];
45
+ if (ctx.session) return body(externalQueue ? {
46
+ ...internalCtx,
47
+ [PENDING_EVENTS]: externalQueue
48
+ } : internalCtx);
49
+ const pending = [];
50
+ const result = await withTransaction(config.connection, async (session) => {
51
+ pending.length = 0;
52
+ return body({
53
+ ...internalCtx,
54
+ session,
55
+ [PENDING_EVENTS]: pending
56
+ });
57
+ }, config.allowNonTransactional ? { allowFallback: true } : {});
58
+ await flushPending(config.eventTransport, pending, config.logger);
59
+ return result;
60
+ }
61
+ /**
62
+ * Drain a `[PENDING_EVENTS]` queue through a transport after commit,
63
+ * swallowing per-event errors (durable delivery is the outbox's job).
64
+ * Hosts composing their own outer transaction call this after commit;
65
+ * most should use `engine.withTransaction(ctx, fn)` instead.
66
+ */
67
+ async function flushPending(eventTransport, events, logger) {
68
+ if (!eventTransport || events.length === 0) return;
69
+ const log = logger ?? console;
70
+ for (const event of events) try {
71
+ await eventTransport.publish(event);
72
+ } catch (err) {
73
+ log.error(`[cart] publish failed for ${event.type}:`, err);
74
+ }
75
+ }
76
+ //#endregion
12
77
  //#region src/models/checkout.model.ts
13
78
  function createCheckoutModel(connection, opts = {}) {
14
79
  const schema = new Schema({
@@ -54,7 +119,9 @@ function createCheckoutModel(connection, opts = {}) {
54
119
  currency: {
55
120
  type: String,
56
121
  required: true,
57
- length: 3
122
+ uppercase: true,
123
+ trim: true,
124
+ match: [CURRENCY_PATTERN, "ISO 4217 (3 uppercase letters)"]
58
125
  },
59
126
  pricing: {
60
127
  type: Schema.Types.Mixed,
@@ -240,7 +307,9 @@ function createDraftModel(connection, opts = {}) {
240
307
  currency: {
241
308
  type: String,
242
309
  required: true,
243
- length: 3
310
+ uppercase: true,
311
+ trim: true,
312
+ match: [CURRENCY_PATTERN, "ISO 4217 (3 uppercase letters)"]
244
313
  },
245
314
  pricing: {
246
315
  type: Schema.Types.Mixed,
@@ -540,10 +609,12 @@ var CartEventPublisher = class {
540
609
  events;
541
610
  outbox;
542
611
  clock;
612
+ logger;
543
613
  constructor(deps) {
544
614
  this.events = deps.events;
545
615
  this.outbox = deps.outbox;
546
616
  this.clock = deps.clock;
617
+ this.logger = deps.logger ?? console;
547
618
  }
548
619
  async emit(type, payload, ctx, options = {}) {
549
620
  const event = createCartEvent(type, {
@@ -561,14 +632,30 @@ var CartEventPublisher = class {
561
632
  correlationId: ctx.correlationId,
562
633
  aggregate: options.aggregate
563
634
  });
635
+ const pending = ctx[PENDING_EVENTS];
564
636
  if (this.outbox) await this.outbox.save(event, { session: ctx.session });
565
- else if (ctx.session) throw new Error("CartEventPublisher.emit: ctx.session requires a host-provided outbox for durable event writes");
566
- if (!ctx.session) await this.events.publish(event);
637
+ else if (ctx.session && !pending) throw new UnmanagedSessionError();
638
+ if (pending) {
639
+ pending.push(event);
640
+ return;
641
+ }
642
+ if (!ctx.session) try {
643
+ await this.events.publish(event);
644
+ } catch (err) {
645
+ this.logger.error(`[cart] transport publish failed for ${event.type}:`, err);
646
+ }
567
647
  }
568
648
  };
569
649
  //#endregion
570
650
  //#region src/repositories/checkout.repository.ts
571
651
  /**
652
+ * Default zombie window for open checkouts — matches the package's
653
+ * existing expiry default (`reservationConfigSchema.defaultTtlSeconds`,
654
+ * 600s): once any reservation hold backing the checkout has lapsed, the
655
+ * open snapshot has no claim on anything and is safe to self-expire.
656
+ */
657
+ const DEFAULT_STALE_OPEN_CHECKOUT_MS = 6e5;
658
+ /**
572
659
  * CheckoutRepository — extends mongokit's `Repository<CheckoutDocument>`.
573
660
  *
574
661
  * All domain logic (createFromDraft with hash interlock, commit, cancel)
@@ -580,11 +667,13 @@ var CheckoutRepository = class extends Repository {
580
667
  draftRepo;
581
668
  clock;
582
669
  eventPublisher;
670
+ staleOpenCheckoutMs;
583
671
  constructor(model, plugins, deps) {
584
672
  super(model, plugins);
585
673
  this.draftRepo = deps.draftRepo;
586
674
  this.clock = deps.clock;
587
675
  this.eventPublisher = deps.eventPublisher;
676
+ this.staleOpenCheckoutMs = deps.staleOpenCheckoutMs ?? 6e5;
588
677
  }
589
678
  async findByPublicId(publicId, ctx) {
590
679
  return await this.getByQuery({ publicId }, this.readOptions(ctx));
@@ -613,12 +702,26 @@ var CheckoutRepository = class extends Repository {
613
702
  const pricingSnapshot = draft.pricing;
614
703
  assertSnapshotNotExpired(pricingSnapshot, draft.lines, () => this.clock.now());
615
704
  const draftPricingHash = pricingSnapshot.pricingHash;
616
- if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", { draftPublicId: input.draftPublicId });
705
+ if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", {
706
+ draftPublicId: input.draftPublicId,
707
+ currentPricing: {
708
+ lines: (pricingSnapshot.lines ?? []).map((l) => ({
709
+ lineId: l.lineId,
710
+ quantity: l.quantity,
711
+ unitPrice: l.unitPrice,
712
+ subtotals: l.subtotals
713
+ })),
714
+ totals: pricingSnapshot.totals
715
+ }
716
+ });
617
717
  const existing = await this.findOpenByDraft(draft._id, ctx);
618
- if (existing) return existing;
718
+ if (existing) {
719
+ if (!this.isStaleOpen(existing)) return existing;
720
+ await this.expireZombie(existing, ctx);
721
+ }
619
722
  const nowIso = this.clock.now().toISOString();
620
723
  let created;
621
- try {
724
+ for (let attempt = 0;; attempt++) try {
622
725
  created = await this.create({
623
726
  draftId: draft._id,
624
727
  actorRef: draft.actorRef,
@@ -639,10 +742,17 @@ var CheckoutRepository = class extends Repository {
639
742
  metadata: null,
640
743
  privateMetadata: null
641
744
  }, this.writeOptions(ctx));
745
+ break;
642
746
  } catch (err) {
643
747
  if (isDuplicateKeyError(err)) {
644
748
  const winner = await this.findOpenByDraft(draft._id, ctx);
645
- if (winner) return winner;
749
+ if (winner) {
750
+ if (!this.isStaleOpen(winner)) return winner;
751
+ if (attempt === 0) {
752
+ await this.expireZombie(winner, ctx);
753
+ continue;
754
+ }
755
+ }
646
756
  }
647
757
  throw err;
648
758
  }
@@ -671,9 +781,32 @@ var CheckoutRepository = class extends Repository {
671
781
  organizationId: ctx.organizationId,
672
782
  skipTenant: ctx.skipTenant,
673
783
  session: ctx.session,
784
+ signal: ctx.signal,
674
785
  lean: true,
675
786
  throwOnNotFound: false
676
787
  });
788
+ if (checkout.state === "finalized") {
789
+ if (!(input.externalRef === void 0 || (checkout.externalRef ?? null) === input.externalRef)) throw new ConcurrencyError("checkout", checkout.version, checkout.publicId);
790
+ await this.draftRepo.markConverted(checkout.draftId, ctx);
791
+ const pricingPrev = checkout.pricing;
792
+ await this.eventPublisher.emit(CartEvents.CHECKOUT_COMMITTED, {
793
+ checkoutId: checkout.publicId,
794
+ draftId: draft?.publicId ?? String(checkout.draftId),
795
+ externalRef: checkout.externalRef ?? null,
796
+ grandTotal: pricingPrev.totals?.grandTotal ?? {
797
+ amount: 0,
798
+ currency: checkout.currency
799
+ }
800
+ }, ctx, {
801
+ resource: "checkout",
802
+ resourceId: checkout.publicId,
803
+ aggregate: {
804
+ type: "checkout",
805
+ id: checkout.publicId
806
+ }
807
+ });
808
+ return checkout;
809
+ }
677
810
  CHECKOUT_MACHINE.assertTransition(checkout.publicId, checkout.state, "finalized");
678
811
  const nowIso = this.clock.now().toISOString();
679
812
  const updated = await this.updateWithVersion(checkout._id, checkout.version, {
@@ -705,6 +838,15 @@ var CheckoutRepository = class extends Repository {
705
838
  });
706
839
  return updated;
707
840
  }
841
+ /**
842
+ * Transition open → canceled and record the reason.
843
+ *
844
+ * ⚠ Cart does NOT release inventory holds here — the HOST owns that
845
+ * compensation (it owns the reserve/commit sequencing too). Subscribe to
846
+ * `cart.checkout.canceled` and call `inventory.release(reservationRefs)`,
847
+ * or call it inline right after this method. Forgetting this strands
848
+ * holds until their TTL backstop — the classic integration leak.
849
+ */
708
850
  async cancel(input, ctx) {
709
851
  const checkout = await this.requireCheckout(input.checkoutPublicId, ctx);
710
852
  CHECKOUT_MACHINE.assertTransition(checkout.publicId, checkout.state, "canceled");
@@ -758,6 +900,13 @@ var CheckoutRepository = class extends Repository {
758
900
  * call this from a periodic job (cron, Streamline, etc.) at whatever
759
901
  * cadence matches their checkout completion SLA.
760
902
  *
903
+ * This is the BULK sweep. `createFromDraft` additionally self-heals
904
+ * lazily: when it finds an open checkout older than
905
+ * `staleOpenCheckoutMs`, it CAS-expires that one zombie inline and
906
+ * creates a fresh checkout — so a customer is never stuck waiting for
907
+ * the next cron tick. Keep both: lazy healing fixes the active
908
+ * customer's path; the cron reclaims abandoned rows nobody revisits.
909
+ *
761
910
  * Returns the count of rows expired. Caller scopes the operation via
762
911
  * `ctx` — pass `ctx.organizationId` to scope to one tenant, or use
763
912
  * `skipTenant: true` to expire across the board (only safe for the
@@ -781,11 +930,54 @@ var CheckoutRepository = class extends Repository {
781
930
  } }, this.writeOptions(ctx));
782
931
  return { count: result?.modifiedCount ?? result?.matchedCount ?? 0 };
783
932
  }
933
+ /** Is this open checkout past the zombie window? */
934
+ isStaleOpen(checkout) {
935
+ const createdAt = checkout.createdAt ? new Date(checkout.createdAt).getTime() : NaN;
936
+ if (Number.isNaN(createdAt)) return false;
937
+ return this.clock.now().getTime() - createdAt >= this.staleOpenCheckoutMs;
938
+ }
939
+ /**
940
+ * CAS-expire a zombie open checkout: `open → canceled` with
941
+ * `canceledReason: 'expired'` — same terminal shape the cron
942
+ * (`expireStaleOpenCheckouts`) writes, so audit history is uniform.
943
+ * The `{ state: 'open', version }` filter makes the transition atomic:
944
+ * a concurrent commit/cancel/expiry wins and this call is a no-op
945
+ * (returns false). No CHECKOUT_CANCELED event — expiry is janitorial,
946
+ * matching the cron method's contract.
947
+ */
948
+ async expireZombie(checkout, ctx) {
949
+ try {
950
+ await this.update(checkout._id, {
951
+ $set: {
952
+ state: "canceled",
953
+ canceledReason: "expired",
954
+ flowState: {
955
+ ...checkout.flowState,
956
+ updatedAt: this.clock.now().toISOString()
957
+ }
958
+ },
959
+ $inc: { version: 1 }
960
+ }, {
961
+ ...this.writeOptions(ctx),
962
+ query: {
963
+ state: "open",
964
+ version: checkout.version
965
+ },
966
+ throwOnNotFound: true,
967
+ lean: true
968
+ });
969
+ return true;
970
+ } catch (err) {
971
+ if (isNotFound$2(err)) return false;
972
+ throw err;
973
+ }
974
+ }
784
975
  readOptions(ctx) {
785
976
  return {
786
977
  organizationId: ctx.organizationId,
787
978
  skipTenant: ctx.skipTenant,
788
979
  session: ctx.session,
980
+ signal: ctx.signal,
789
981
  lean: true,
790
982
  throwOnNotFound: false
791
983
  };
@@ -794,7 +986,8 @@ var CheckoutRepository = class extends Repository {
794
986
  return {
795
987
  organizationId: ctx.organizationId,
796
988
  skipTenant: ctx.skipTenant,
797
- session: ctx.session
989
+ session: ctx.session,
990
+ signal: ctx.signal
798
991
  };
799
992
  }
800
993
  async requireCheckout(publicId, ctx) {
@@ -1013,8 +1206,10 @@ function canReuse(line, prior) {
1013
1206
  */
1014
1207
  function rebuildSubtotals(prior, line, currency) {
1015
1208
  const unitPrice = prior.unitPrice;
1209
+ const rawTotal = unitPrice.amount * line.quantity;
1210
+ if (!Number.isSafeInteger(rawTotal)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${line.quantity} exceeds Number.MAX_SAFE_INTEGER`);
1016
1211
  const lineTotal = {
1017
- amount: unitPrice.amount * line.quantity,
1212
+ amount: rawTotal,
1018
1213
  currency
1019
1214
  };
1020
1215
  return {
@@ -1038,8 +1233,27 @@ function rebuildSubtotals(prior, line, currency) {
1038
1233
  kindMeta: prior.kindMeta
1039
1234
  };
1040
1235
  }
1236
+ /**
1237
+ * Pricing hash — SHA-256 over a canonical string of the priced lines.
1238
+ *
1239
+ * Canonical string assumptions (do not change without a version bump):
1240
+ * - One member per line: `lineId:quantity:postPromoPostTax.amount:currency`.
1241
+ * The post-promo-post-tax subtotal is the value the customer confirmed,
1242
+ * so promo and tax drift both invalidate the hash; shipping and
1243
+ * order-level adjustments are NOT hashed (they are order-scoped, not
1244
+ * line-scoped, and the host re-displays them from totals).
1245
+ * - Members are sorted lexicographically so line ORDER never affects the
1246
+ * hash — merges and re-reads that reorder lines stay hash-stable.
1247
+ * - Members are `|`-delimited; `lineId`s are engine-generated
1248
+ * (`line_<id>`) and never contain `:` or `|`, so the encoding is
1249
+ * unambiguous.
1250
+ *
1251
+ * The digest is hex-encoded SHA-256 — opaque to clients. Treat it as a
1252
+ * token: compare for equality, never parse.
1253
+ */
1041
1254
  function buildPricingHash(lines) {
1042
- return lines.map((l) => `${l.lineId}:${l.quantity}:${l.subtotals.postPromoPostTax.amount}:${l.subtotals.postPromoPostTax.currency}`).sort().join("|");
1255
+ const canonical = lines.map((l) => `${l.lineId}:${l.quantity}:${l.subtotals.postPromoPostTax.amount}:${l.subtotals.postPromoPostTax.currency}`).sort().join("|");
1256
+ return createHash("sha256").update(canonical).digest("hex");
1043
1257
  }
1044
1258
  function computeAdjustmentAmount(result, lines, currency) {
1045
1259
  const spec = result.adjustment;
@@ -1069,6 +1283,20 @@ function computeAdjustmentAmount(result, lines, currency) {
1069
1283
  * Multi-tenant scoping is enforced by `multiTenantPlugin` at POLICY priority;
1070
1284
  * `publicId` is generated by `customIdPlugin`. Optimistic concurrency runs
1071
1285
  * through mongokit's `update()` so all hooks (audit, observability) fire.
1286
+ *
1287
+ * ## Concurrency invariant — read-modify-write on `lines` is CAS-safe
1288
+ *
1289
+ * Every line mutation (addItem, updateItemQuantity, removeItem, clear,
1290
+ * replaceLines) rebuilds the FULL `lines` array in memory from a single
1291
+ * read and persists it via `updateWithVersion`, which only matches when
1292
+ * the stored `version` still equals the version of that read. Any
1293
+ * concurrent mutation bumps `version`, so the stale rebuild can never
1294
+ * land — the loser gets a typed `ConcurrencyError` and retries from a
1295
+ * fresh read. Do NOT "optimize" these paths into positional `$push` /
1296
+ * `$set('lines.$')` array operators: pricing snapshots are derived from
1297
+ * the whole line set, so a partial array write would let `lines` and
1298
+ * `pricing` drift apart. The version CAS is what makes the in-memory
1299
+ * rebuild safe; the rebuild is what keeps pricing consistent.
1072
1300
  */
1073
1301
  var DraftRepository = class extends Repository {
1074
1302
  kinds;
@@ -1276,15 +1504,24 @@ var DraftRepository = class extends Repository {
1276
1504
  /**
1277
1505
  * Atomic transition `active → abandoned`. Returns null if the draft was
1278
1506
  * already in a non-active state.
1507
+ *
1508
+ * Pass `opts.expectedVersion` to ALSO compare-and-set on `version` —
1509
+ * the merge service uses this to guarantee the source draft's line set
1510
+ * it captured is exactly the line set being retired (a concurrent
1511
+ * add-to-cart bumps `version`, the CAS misses, and the merge retries
1512
+ * from a fresh read instead of silently dropping the new line).
1279
1513
  */
1280
- async markAbandoned(draftId, ctx) {
1514
+ async markAbandoned(draftId, ctx, opts = {}) {
1281
1515
  try {
1282
1516
  const updated = await this.update(draftId, {
1283
1517
  $set: { status: "abandoned" },
1284
1518
  $inc: { version: 1 }
1285
1519
  }, {
1286
1520
  ...this.writeOptions(ctx),
1287
- query: { status: "active" },
1521
+ query: {
1522
+ status: "active",
1523
+ ...opts.expectedVersion !== void 0 ? { version: opts.expectedVersion } : {}
1524
+ },
1288
1525
  lean: true
1289
1526
  });
1290
1527
  if (!updated) return null;
@@ -1328,12 +1565,19 @@ var DraftRepository = class extends Repository {
1328
1565
  * Replace the line collection atomically and refresh the pricing snapshot.
1329
1566
  * Internal services use this to keep merge-like flows inside repository
1330
1567
  * concurrency + pricing rules instead of hand-writing persistence logic.
1568
+ *
1569
+ * Pass `expectedVersion` when `lines` was computed from an EARLIER read
1570
+ * of the draft: the CAS then pins to that read's version, so any
1571
+ * mutation that landed in between (concurrent add-to-cart during a
1572
+ * merge) surfaces as `ConcurrencyError` instead of being overwritten.
1573
+ * Without it, the CAS pins to this method's own fresh read — safe for
1574
+ * callers whose `lines` doesn't derive from draft state.
1331
1575
  */
1332
1576
  async replaceLines(input, ctx) {
1333
1577
  const draft = await this.requireDraft(input.draftPublicId, ctx);
1334
1578
  const nextLines = input.lines.map((line) => ({ ...line }));
1335
1579
  const pricing = nextLines.length === 0 ? null : (await this.price(nextLines, draft.currency, ctx, draft.pricing)).snapshot;
1336
- return this.updateWithVersion(draft._id, draft.version, {
1580
+ return this.updateWithVersion(draft._id, input.expectedVersion ?? draft.version, {
1337
1581
  lines: nextLines,
1338
1582
  pricing
1339
1583
  }, ctx);
@@ -1346,6 +1590,7 @@ var DraftRepository = class extends Repository {
1346
1590
  organizationId: ctx.organizationId,
1347
1591
  skipTenant: ctx.skipTenant,
1348
1592
  session: ctx.session,
1593
+ signal: ctx.signal,
1349
1594
  lean: true,
1350
1595
  throwOnNotFound: false
1351
1596
  };
@@ -1354,7 +1599,8 @@ var DraftRepository = class extends Repository {
1354
1599
  return {
1355
1600
  organizationId: ctx.organizationId,
1356
1601
  skipTenant: ctx.skipTenant,
1357
- session: ctx.session
1602
+ session: ctx.session,
1603
+ signal: ctx.signal
1358
1604
  };
1359
1605
  }
1360
1606
  async price(lines, currency, ctx, previous) {
@@ -1482,7 +1728,7 @@ var IdempotencyRepository = class extends Repository {
1482
1728
  leaseExpiresAt
1483
1729
  }], { session }))[0];
1484
1730
  } catch (err) {
1485
- if (isDuplicateKeyError$1(err)) return null;
1731
+ if (isDuplicateKeyError(err)) return null;
1486
1732
  throw err;
1487
1733
  }
1488
1734
  }
@@ -1508,6 +1754,7 @@ var IdempotencyRepository = class extends Repository {
1508
1754
  } }, {
1509
1755
  returnDocument: "after",
1510
1756
  session: ctx.session,
1757
+ signal: ctx.signal,
1511
1758
  lean: true
1512
1759
  }) ?? null;
1513
1760
  }
@@ -1526,6 +1773,7 @@ var IdempotencyRepository = class extends Repository {
1526
1773
  } }, {
1527
1774
  returnDocument: "after",
1528
1775
  session: ctx.session,
1776
+ signal: ctx.signal,
1529
1777
  lean: true
1530
1778
  }) ?? null;
1531
1779
  }
@@ -1544,15 +1792,11 @@ var IdempotencyRepository = class extends Repository {
1544
1792
  } }, {
1545
1793
  returnDocument: "after",
1546
1794
  session: ctx.session,
1795
+ signal: ctx.signal,
1547
1796
  lean: true
1548
1797
  }) ?? null;
1549
1798
  }
1550
1799
  };
1551
- function isDuplicateKeyError$1(err) {
1552
- if (!err || typeof err !== "object") return false;
1553
- const code = err.code;
1554
- return code === 11e3 || code === 11001;
1555
- }
1556
1800
  //#endregion
1557
1801
  //#region src/repositories/reservation.repository.ts
1558
1802
  /**
@@ -1627,6 +1871,7 @@ var ReservationRepository = class extends Repository {
1627
1871
  organizationId: ctx.organizationId,
1628
1872
  skipTenant: ctx.skipTenant,
1629
1873
  session: ctx.session,
1874
+ signal: ctx.signal,
1630
1875
  lean: true
1631
1876
  };
1632
1877
  }
@@ -1634,7 +1879,8 @@ var ReservationRepository = class extends Repository {
1634
1879
  return {
1635
1880
  organizationId: ctx.organizationId,
1636
1881
  skipTenant: ctx.skipTenant,
1637
- session: ctx.session
1882
+ session: ctx.session,
1883
+ signal: ctx.signal
1638
1884
  };
1639
1885
  }
1640
1886
  };
@@ -1653,7 +1899,7 @@ function tenantPlugin(fieldType = "objectId") {
1653
1899
  });
1654
1900
  }
1655
1901
  function createCartRepositories(models, config) {
1656
- const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {}, tenantFieldType = "objectId", multiTenant = true } = config;
1902
+ const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {}, tenantFieldType = "objectId", multiTenant = true, staleOpenCheckoutMs } = config;
1657
1903
  const eventPublisher = new CartEventPublisher({
1658
1904
  events,
1659
1905
  outbox,
@@ -1695,7 +1941,8 @@ function createCartRepositories(models, config) {
1695
1941
  ], {
1696
1942
  draftRepo: draft,
1697
1943
  clock,
1698
- eventPublisher
1944
+ eventPublisher,
1945
+ staleOpenCheckoutMs
1699
1946
  }),
1700
1947
  reservation: new ReservationRepository(models.Reservation, [
1701
1948
  ...tenantPlugins,
@@ -1749,6 +1996,19 @@ var InProcessCartEventBus = class {
1749
1996
  };
1750
1997
  //#endregion
1751
1998
  //#region src/engine/create-cart.ts
1999
+ /** Runtime capabilities cart's atomic paths require at boot (full mode). */
2000
+ const REQUIRED_CAPABILITIES = ["upsert"];
2001
+ /**
2002
+ * Boot gate (PACKAGE_RULES "Runtime capabilities") — the idempotency store's
2003
+ * insert-in-flight/lease pattern needs atomic upserts; fail loud at engine
2004
+ * creation, not with a cryptic driver error on the first checkout.
2005
+ */
2006
+ function assertCartCapabilities(repositories) {
2007
+ const caps = repositories.draft.capabilities;
2008
+ if (!caps) throw new Error("createCart: the wired repository backend declares no `capabilities` descriptor (repo-core 0.6 / mongokit 3.16+). Upgrade the kit.");
2009
+ const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
2010
+ if (missing.length > 0) throw new Error(`createCart: backend missing required capabilities: ${missing.join(", ")}. The idempotency lease pattern needs atomic upserts.`);
2011
+ }
1752
2012
  /**
1753
2013
  * createCart() — build a cart engine.
1754
2014
  *
@@ -1792,10 +2052,13 @@ async function createCart(config) {
1792
2052
  outbox: config.outbox,
1793
2053
  plugins: config.repositoryPlugins,
1794
2054
  tenantFieldType,
1795
- multiTenant
2055
+ multiTenant,
2056
+ staleOpenCheckoutMs: config.checkout?.staleOpenCheckoutMs
1796
2057
  });
2058
+ assertCartCapabilities(repositories);
1797
2059
  mode = "full";
1798
2060
  }
2061
+ const allowNonTransactional = config.allowNonTransactional ?? false;
1799
2062
  return {
1800
2063
  config: Object.freeze({ ...config }),
1801
2064
  kinds,
@@ -1805,6 +2068,15 @@ async function createCart(config) {
1805
2068
  models,
1806
2069
  repositories,
1807
2070
  mode,
2071
+ withTransaction(ctx, body) {
2072
+ if (mode !== "full") throw new Error("cart.withTransaction requires full mode (a real Mongoose connection)");
2073
+ return runUnit({
2074
+ connection: config.connection,
2075
+ eventTransport: events,
2076
+ logger: console,
2077
+ allowNonTransactional
2078
+ }, ctx, body);
2079
+ },
1808
2080
  async syncIndexes() {
1809
2081
  await Promise.all(Object.values(models).map((m) => m.createIndexes()));
1810
2082
  },
@@ -1812,4 +2084,4 @@ async function createCart(config) {
1812
2084
  };
1813
2085
  }
1814
2086
  //#endregion
1815
- 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 };
2087
+ export { IdempotencyRepository as a, CheckoutRepository as c, createReservationModel as d, createIdempotencyModel as f, PENDING_EVENTS as g, flushPending as h, 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-qfN8dZN9.mjs";
2
- export { CartError, CartErrorCategory, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, SagaFailurePhase, StaleQuoteError, StateTransitionError, UnknownKindError };
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";
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
- import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "../../stale-quote.error-BkFLXWo5.mjs";
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
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
- export { CartError, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError };
6
+ export { CartError, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError };
@@ -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-qfN8dZN9.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-BB0XzkXF.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 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";
5
+ import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ 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, x as BridgeRef, y as PromotionsBridge } from "../clock.port-CNu2wgdA.mjs";
6
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-DLMxgpLE.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-D19wZe-w.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-B1mU1iJp.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-DG2iCCH1.mjs";
10
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
- 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 };
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, UnmanagedSessionError, type ValidityPolicy, addMoney, cartEventDefinitions, cartEventsByName, createCartEvent, createCartEventRegistry, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCartEvent, fromMajor, isLegalCheckoutTransition, money, multiplyMoney, subtractMoney, sumMoney, systemClock, toMajor };