@classytic/cart 0.1.3 → 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.
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
 
@@ -9,6 +9,7 @@ import { matchEventPattern } from "@classytic/primitives/events";
9
9
  import mongoose, { Schema } from "mongoose";
10
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({
@@ -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));
@@ -613,12 +623,26 @@ var CheckoutRepository = class extends Repository {
613
623
  const pricingSnapshot = draft.pricing;
614
624
  assertSnapshotNotExpired(pricingSnapshot, draft.lines, () => this.clock.now());
615
625
  const draftPricingHash = pricingSnapshot.pricingHash;
616
- if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", { draftPublicId: input.draftPublicId });
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
+ });
617
638
  const existing = await this.findOpenByDraft(draft._id, ctx);
618
- if (existing) return existing;
639
+ if (existing) {
640
+ if (!this.isStaleOpen(existing)) return existing;
641
+ await this.expireZombie(existing, ctx);
642
+ }
619
643
  const nowIso = this.clock.now().toISOString();
620
644
  let created;
621
- try {
645
+ for (let attempt = 0;; attempt++) try {
622
646
  created = await this.create({
623
647
  draftId: draft._id,
624
648
  actorRef: draft.actorRef,
@@ -639,10 +663,17 @@ var CheckoutRepository = class extends Repository {
639
663
  metadata: null,
640
664
  privateMetadata: null
641
665
  }, this.writeOptions(ctx));
666
+ break;
642
667
  } catch (err) {
643
668
  if (isDuplicateKeyError(err)) {
644
669
  const winner = await this.findOpenByDraft(draft._id, ctx);
645
- 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
+ }
646
677
  }
647
678
  throw err;
648
679
  }
@@ -671,6 +702,7 @@ var CheckoutRepository = class extends Repository {
671
702
  organizationId: ctx.organizationId,
672
703
  skipTenant: ctx.skipTenant,
673
704
  session: ctx.session,
705
+ signal: ctx.signal,
674
706
  lean: true,
675
707
  throwOnNotFound: false
676
708
  });
@@ -758,6 +790,13 @@ var CheckoutRepository = class extends Repository {
758
790
  * call this from a periodic job (cron, Streamline, etc.) at whatever
759
791
  * cadence matches their checkout completion SLA.
760
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
+ *
761
800
  * Returns the count of rows expired. Caller scopes the operation via
762
801
  * `ctx` — pass `ctx.organizationId` to scope to one tenant, or use
763
802
  * `skipTenant: true` to expire across the board (only safe for the
@@ -781,11 +820,54 @@ var CheckoutRepository = class extends Repository {
781
820
  } }, this.writeOptions(ctx));
782
821
  return { count: result?.modifiedCount ?? result?.matchedCount ?? 0 };
783
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
+ }
784
865
  readOptions(ctx) {
785
866
  return {
786
867
  organizationId: ctx.organizationId,
787
868
  skipTenant: ctx.skipTenant,
788
869
  session: ctx.session,
870
+ signal: ctx.signal,
789
871
  lean: true,
790
872
  throwOnNotFound: false
791
873
  };
@@ -794,7 +876,8 @@ var CheckoutRepository = class extends Repository {
794
876
  return {
795
877
  organizationId: ctx.organizationId,
796
878
  skipTenant: ctx.skipTenant,
797
- session: ctx.session
879
+ session: ctx.session,
880
+ signal: ctx.signal
798
881
  };
799
882
  }
800
883
  async requireCheckout(publicId, ctx) {
@@ -1038,8 +1121,27 @@ function rebuildSubtotals(prior, line, currency) {
1038
1121
  kindMeta: prior.kindMeta
1039
1122
  };
1040
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
+ */
1041
1142
  function buildPricingHash(lines) {
1042
- 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");
1043
1145
  }
1044
1146
  function computeAdjustmentAmount(result, lines, currency) {
1045
1147
  const spec = result.adjustment;
@@ -1069,6 +1171,20 @@ function computeAdjustmentAmount(result, lines, currency) {
1069
1171
  * Multi-tenant scoping is enforced by `multiTenantPlugin` at POLICY priority;
1070
1172
  * `publicId` is generated by `customIdPlugin`. Optimistic concurrency runs
1071
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.
1072
1188
  */
1073
1189
  var DraftRepository = class extends Repository {
1074
1190
  kinds;
@@ -1276,15 +1392,24 @@ var DraftRepository = class extends Repository {
1276
1392
  /**
1277
1393
  * Atomic transition `active → abandoned`. Returns null if the draft was
1278
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).
1279
1401
  */
1280
- async markAbandoned(draftId, ctx) {
1402
+ async markAbandoned(draftId, ctx, opts = {}) {
1281
1403
  try {
1282
1404
  const updated = await this.update(draftId, {
1283
1405
  $set: { status: "abandoned" },
1284
1406
  $inc: { version: 1 }
1285
1407
  }, {
1286
1408
  ...this.writeOptions(ctx),
1287
- query: { status: "active" },
1409
+ query: {
1410
+ status: "active",
1411
+ ...opts.expectedVersion !== void 0 ? { version: opts.expectedVersion } : {}
1412
+ },
1288
1413
  lean: true
1289
1414
  });
1290
1415
  if (!updated) return null;
@@ -1328,12 +1453,19 @@ var DraftRepository = class extends Repository {
1328
1453
  * Replace the line collection atomically and refresh the pricing snapshot.
1329
1454
  * Internal services use this to keep merge-like flows inside repository
1330
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.
1331
1463
  */
1332
1464
  async replaceLines(input, ctx) {
1333
1465
  const draft = await this.requireDraft(input.draftPublicId, ctx);
1334
1466
  const nextLines = input.lines.map((line) => ({ ...line }));
1335
1467
  const pricing = nextLines.length === 0 ? null : (await this.price(nextLines, draft.currency, ctx, draft.pricing)).snapshot;
1336
- return this.updateWithVersion(draft._id, draft.version, {
1468
+ return this.updateWithVersion(draft._id, input.expectedVersion ?? draft.version, {
1337
1469
  lines: nextLines,
1338
1470
  pricing
1339
1471
  }, ctx);
@@ -1346,6 +1478,7 @@ var DraftRepository = class extends Repository {
1346
1478
  organizationId: ctx.organizationId,
1347
1479
  skipTenant: ctx.skipTenant,
1348
1480
  session: ctx.session,
1481
+ signal: ctx.signal,
1349
1482
  lean: true,
1350
1483
  throwOnNotFound: false
1351
1484
  };
@@ -1354,7 +1487,8 @@ var DraftRepository = class extends Repository {
1354
1487
  return {
1355
1488
  organizationId: ctx.organizationId,
1356
1489
  skipTenant: ctx.skipTenant,
1357
- session: ctx.session
1490
+ session: ctx.session,
1491
+ signal: ctx.signal
1358
1492
  };
1359
1493
  }
1360
1494
  async price(lines, currency, ctx, previous) {
@@ -1508,6 +1642,7 @@ var IdempotencyRepository = class extends Repository {
1508
1642
  } }, {
1509
1643
  returnDocument: "after",
1510
1644
  session: ctx.session,
1645
+ signal: ctx.signal,
1511
1646
  lean: true
1512
1647
  }) ?? null;
1513
1648
  }
@@ -1526,6 +1661,7 @@ var IdempotencyRepository = class extends Repository {
1526
1661
  } }, {
1527
1662
  returnDocument: "after",
1528
1663
  session: ctx.session,
1664
+ signal: ctx.signal,
1529
1665
  lean: true
1530
1666
  }) ?? null;
1531
1667
  }
@@ -1544,6 +1680,7 @@ var IdempotencyRepository = class extends Repository {
1544
1680
  } }, {
1545
1681
  returnDocument: "after",
1546
1682
  session: ctx.session,
1683
+ signal: ctx.signal,
1547
1684
  lean: true
1548
1685
  }) ?? null;
1549
1686
  }
@@ -1627,6 +1764,7 @@ var ReservationRepository = class extends Repository {
1627
1764
  organizationId: ctx.organizationId,
1628
1765
  skipTenant: ctx.skipTenant,
1629
1766
  session: ctx.session,
1767
+ signal: ctx.signal,
1630
1768
  lean: true
1631
1769
  };
1632
1770
  }
@@ -1634,7 +1772,8 @@ var ReservationRepository = class extends Repository {
1634
1772
  return {
1635
1773
  organizationId: ctx.organizationId,
1636
1774
  skipTenant: ctx.skipTenant,
1637
- session: ctx.session
1775
+ session: ctx.session,
1776
+ signal: ctx.signal
1638
1777
  };
1639
1778
  }
1640
1779
  };
@@ -1653,7 +1792,7 @@ function tenantPlugin(fieldType = "objectId") {
1653
1792
  });
1654
1793
  }
1655
1794
  function createCartRepositories(models, config) {
1656
- 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;
1657
1796
  const eventPublisher = new CartEventPublisher({
1658
1797
  events,
1659
1798
  outbox,
@@ -1695,7 +1834,8 @@ function createCartRepositories(models, config) {
1695
1834
  ], {
1696
1835
  draftRepo: draft,
1697
1836
  clock,
1698
- eventPublisher
1837
+ eventPublisher,
1838
+ staleOpenCheckoutMs
1699
1839
  }),
1700
1840
  reservation: new ReservationRepository(models.Reservation, [
1701
1841
  ...tenantPlugins,
@@ -1792,7 +1932,8 @@ async function createCart(config) {
1792
1932
  outbox: config.outbox,
1793
1933
  plugins: config.repositoryPlugins,
1794
1934
  tenantFieldType,
1795
- multiTenant
1935
+ multiTenant,
1936
+ staleOpenCheckoutMs: config.checkout?.staleOpenCheckoutMs
1796
1937
  });
1797
1938
  mode = "full";
1798
1939
  }
@@ -1812,4 +1953,4 @@ async function createCart(config) {
1812
1953
  };
1813
1954
  }
1814
1955
  //#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 };
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 };
@@ -14,6 +14,9 @@ declare const idempotencyConfigSchema: z.ZodObject<{
14
14
  declare const reservationConfigSchema: z.ZodObject<{
15
15
  defaultTtlSeconds: z.ZodDefault<z.ZodNumber>;
16
16
  }, z.core.$strip>;
17
+ declare const checkoutConfigSchema: z.ZodObject<{
18
+ staleOpenCheckoutMs: z.ZodDefault<z.ZodNumber>;
19
+ }, z.core.$strip>;
17
20
  declare const scopeConfigSchema: z.ZodObject<{
18
21
  contextKey: z.ZodDefault<z.ZodString>;
19
22
  }, z.core.$strip>;
@@ -30,6 +33,9 @@ declare const cartConfigSchema: z.ZodObject<{
30
33
  reservation: z.ZodDefault<z.ZodObject<{
31
34
  defaultTtlSeconds: z.ZodDefault<z.ZodNumber>;
32
35
  }, z.core.$strip>>;
36
+ checkout: z.ZodDefault<z.ZodObject<{
37
+ staleOpenCheckoutMs: z.ZodDefault<z.ZodNumber>;
38
+ }, z.core.$strip>>;
33
39
  draftTtlSeconds: z.ZodOptional<z.ZodNumber>;
34
40
  }, z.core.$strip>;
35
41
  /**
@@ -38,4 +44,4 @@ declare const cartConfigSchema: z.ZodObject<{
38
44
  */
39
45
  type CartConfigShape = z.infer<typeof cartConfigSchema>;
40
46
  //#endregion
41
- export { CartConfigShape, cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
47
+ export { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -16,6 +16,14 @@ const idempotencyConfigSchema = z.object({
16
16
  const reservationConfigSchema = z.object({
17
17
  /** Default TTL for reservations in seconds. Default 10 minutes. */
18
18
  defaultTtlSeconds: z.number().int().positive().default(600) });
19
+ const checkoutConfigSchema = z.object({
20
+ /**
21
+ * Age (ms) past which an `open` checkout counts as a zombie and is
22
+ * lazily expired by `createFromDraft` (CAS `open → canceled`, reason
23
+ * `'expired'`) so a fresh checkout can be created. Default 10 minutes —
24
+ * matches `reservationConfigSchema.defaultTtlSeconds`.
25
+ */
26
+ staleOpenCheckoutMs: z.number().int().positive().default(6e5) });
19
27
  const scopeConfigSchema = z.object({
20
28
  /**
21
29
  * Optional context key name. The STORAGE FIELD is always
@@ -33,8 +41,9 @@ const cartConfigSchema = z.object({
33
41
  retentionSeconds: 1440 * 60
34
42
  }),
35
43
  reservation: reservationConfigSchema.default({ defaultTtlSeconds: 600 }),
44
+ checkout: checkoutConfigSchema.default({ staleOpenCheckoutMs: 6e5 }),
36
45
  /** Whether drafts auto-expire via TTL. Default off. */
37
46
  draftTtlSeconds: z.number().int().positive().optional()
38
47
  });
39
48
  //#endregion
40
- export { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
49
+ export { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -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-DhSLiZHi.mjs";
2
+ import { a as CartEngine, i as CartConfig, n as createCart, r as CartBridges, t as InProcessCartEventBus } from "../internal-event-bus-vMG6v-e6.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-4wql1XGi.mjs";
1
+ import { n as InProcessCartEventBus, t as createCart } from "../create-cart-Iqvlv0V2.mjs";
2
2
  import { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
3
3
  export { InProcessCartEventBus, cartConfigSchema, createCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
package/dist/index.d.mts CHANGED
@@ -8,8 +8,8 @@ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as C
8
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
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
10
  import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-DitjeoHg.mjs";
11
- import { CartConfigShape, cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
12
- import { C as IdempotencyDocument, D as CheckoutDocument, E as createDraftModel, O as createCheckoutModel, S as createReservationModel, T as DraftDocument, _ as CartModelName, a as CartEngine, b as createCartModels, c as CreateCartRepositoriesConfig, d as IdempotencyRepository, f as CheckoutRepository, g as CartEventPublisherDeps, h as DraftRepositoryDeps, i as CartConfig, l as createCartRepositories, m as DraftRepository, n as createCart, o as CartRepositories, p as CheckoutRepositoryDeps, r as CartBridges, s as CartRepositoryPluginBundle, t as InProcessCartEventBus, u as ReservationRepository, v as CartModels, w as createIdempotencyModel, x as ReservationDocument, y as CreateCartModelsOptions } from "./internal-event-bus-DhSLiZHi.mjs";
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-vMG6v-e6.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-Cpo_Hh7G.mjs";
14
14
  import { Money, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
15
15
  import { EventHandler, EventTransport, PublishManyResult } from "@classytic/primitives/events";
@@ -50,9 +50,35 @@ declare function markAbandoned(opts: {
50
50
  * active draft on login.
51
51
  *
52
52
  * Merge strategy: iterate the source's lines. For each line, if a line
53
- * with the same `(kind, skuRef)` exists in the target, increment the
54
- * target's quantity. Otherwise, append. Display snapshots carry over
55
- * from the source since they're already captured.
53
+ * with the same merge key (kind-defined, `(kind, skuRef)` fallback)
54
+ * exists in the target, increment the target's quantity. Otherwise,
55
+ * append. Display snapshots carry over from the source since they're
56
+ * already captured.
57
+ *
58
+ * ## Concurrency — double-CAS, no lost updates
59
+ *
60
+ * Both drafts can be mutated concurrently (guest tab still open, user
61
+ * adding from another device). The merge is therefore guarded by TWO
62
+ * compare-and-set writes, ordered so a retry can never double-apply:
63
+ *
64
+ * 1. The SOURCE is retired first — `markAbandoned` with
65
+ * `expectedVersion` CAS-pinned to the read that captured its lines.
66
+ * A concurrent add-to-cart on the source bumps `version`, the CAS
67
+ * misses, and the whole merge retries from a fresh read (bounded).
68
+ * Once this write lands, the captured source line set is final.
69
+ * 2. The TARGET write — `replaceLines` CAS-pinned (`expectedVersion`)
70
+ * to the target read the merged line set was computed from. A
71
+ * concurrent add-to-cart on the target surfaces as
72
+ * `ConcurrencyError`; the merge re-reads the target, re-merges the
73
+ * (already-frozen) source lines, and retries — so the concurrent
74
+ * line survives. Because the source was retired exactly once in
75
+ * step 1, target retries can never double-count source quantities.
76
+ *
77
+ * Hosts that need the two writes to be all-or-nothing (no
78
+ * retired-source/unmerged-lines window on a crash between steps) can
79
+ * pass a Mongoose `ctx.session` opened on a transaction — both writes
80
+ * thread it — at the cost of requiring a replica set and a configured
81
+ * outbox (see docs/host-integration.md).
56
82
  *
57
83
  * After merging, the source draft is marked `abandoned` so it's no
58
84
  * longer active.
@@ -115,4 +141,4 @@ type CartTenantInput = TenantConfig | boolean | {
115
141
  /** Re-export of primitives' resolved shape under the legacy name. */
116
142
  type ResolvedTenant = ResolvedTenantConfig;
117
143
  //#endregion
118
- export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBridges, type CartConfig, type CartConfigShape, type CartDomainEvent, type CartEngine, CartError, type CartErrorCategory, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventPublisherDeps, type CartEventRegistry, CartEvents, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartModelsOptions, type CreateCartRepositoriesConfig, type Draft, type DraftDocument, DraftRepository, type DraftRepositoryDeps, type DraftStatus, type EventHandler, type EventSchema, type EventSchemaProperty, type EventTransport, type EventValidationResult, type EventValidator, type IdPort, IdempotencyBusyError, type IdempotencyDocument, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, type InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, type OperationContext, type OperationName, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, type PayloadOf, PriceChangedError, type PricedLine, type PricingSnapshot, type ProductSummary, type PromotionResult, type PromotionsBridge, type PublishManyResult, type Reservation, type ReservationDocument, ReservationError, type ReservationRef, ReservationRepository, type ReservationRequest, type ReservationStatus, type ResolvedTenant, type RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaStepFn, type ServiceFeePayload, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type SkuPayload, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, type TimeslotPayload, type TotalsSnapshot, UnknownKindError, type ValidityPolicy, type VariantPayload, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
144
+ export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBridges, type CartConfig, type CartConfigShape, type CartDomainEvent, type CartEngine, CartError, type CartErrorCategory, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventPublisherDeps, type CartEventRegistry, CartEvents, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartModelsOptions, type CreateCartRepositoriesConfig, DEFAULT_STALE_OPEN_CHECKOUT_MS, type Draft, type DraftDocument, DraftRepository, type DraftRepositoryDeps, type DraftStatus, type EventHandler, type EventSchema, type EventSchemaProperty, type EventTransport, type EventValidationResult, type EventValidator, type IdPort, IdempotencyBusyError, type IdempotencyDocument, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, type InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, type OperationContext, type OperationName, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, type PayloadOf, PriceChangedError, type PricedLine, type PricingSnapshot, type ProductSummary, type PromotionResult, type PromotionsBridge, type PublishManyResult, type Reservation, type ReservationDocument, ReservationError, type ReservationRef, ReservationRepository, type ReservationRequest, type ReservationStatus, type ResolvedTenant, type RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaStepFn, type ServiceFeePayload, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type SkuPayload, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, type TimeslotPayload, type TotalsSnapshot, UnknownKindError, type ValidityPolicy, type VariantPayload, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
package/dist/index.mjs CHANGED
@@ -9,9 +9,9 @@ import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStor
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
11
  import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-Bm3lC2Uv.mjs";
12
- import { a as IdempotencyRepository, c as CheckoutRepository, d as createIdempotencyModel, f as createDraftModel, i as ReservationRepository, l as createCartModels, n as InProcessCartEventBus, o as DraftRepository, p as createCheckoutModel, r as createCartRepositories, s as runPricing, t as createCart, u as createReservationModel } from "./create-cart-4wql1XGi.mjs";
12
+ import { a as IdempotencyRepository, c as CheckoutRepository, d as createReservationModel, f as createIdempotencyModel, 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-Iqvlv0V2.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-z2gwH9Vo.mjs";
14
- import { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
14
+ import { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
15
15
  import { addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
16
16
  //#region src/services/abandonment.service.ts
17
17
  /**
@@ -40,6 +40,7 @@ async function findAbandonedDrafts(opts) {
40
40
  }, {
41
41
  organizationId: ctx.organizationId,
42
42
  skipTenant: ctx.skipTenant,
43
+ signal: ctx.signal,
43
44
  lean: true
44
45
  })).data;
45
46
  }
@@ -54,40 +55,96 @@ async function markAbandoned(opts) {
54
55
  }
55
56
  //#endregion
56
57
  //#region src/services/merge.service.ts
58
+ /** Bounded retries for each CAS-guarded phase of the merge. */
59
+ const MAX_MERGE_ATTEMPTS = 3;
57
60
  /**
58
61
  * Merge a guest (session-scoped) draft into an authenticated user's
59
62
  * active draft on login.
60
63
  *
61
64
  * Merge strategy: iterate the source's lines. For each line, if a line
62
- * with the same `(kind, skuRef)` exists in the target, increment the
63
- * target's quantity. Otherwise, append. Display snapshots carry over
64
- * from the source since they're already captured.
65
+ * with the same merge key (kind-defined, `(kind, skuRef)` fallback)
66
+ * exists in the target, increment the target's quantity. Otherwise,
67
+ * append. Display snapshots carry over from the source since they're
68
+ * already captured.
69
+ *
70
+ * ## Concurrency — double-CAS, no lost updates
71
+ *
72
+ * Both drafts can be mutated concurrently (guest tab still open, user
73
+ * adding from another device). The merge is therefore guarded by TWO
74
+ * compare-and-set writes, ordered so a retry can never double-apply:
75
+ *
76
+ * 1. The SOURCE is retired first — `markAbandoned` with
77
+ * `expectedVersion` CAS-pinned to the read that captured its lines.
78
+ * A concurrent add-to-cart on the source bumps `version`, the CAS
79
+ * misses, and the whole merge retries from a fresh read (bounded).
80
+ * Once this write lands, the captured source line set is final.
81
+ * 2. The TARGET write — `replaceLines` CAS-pinned (`expectedVersion`)
82
+ * to the target read the merged line set was computed from. A
83
+ * concurrent add-to-cart on the target surfaces as
84
+ * `ConcurrencyError`; the merge re-reads the target, re-merges the
85
+ * (already-frozen) source lines, and retries — so the concurrent
86
+ * line survives. Because the source was retired exactly once in
87
+ * step 1, target retries can never double-count source quantities.
88
+ *
89
+ * Hosts that need the two writes to be all-or-nothing (no
90
+ * retired-source/unmerged-lines window on a crash between steps) can
91
+ * pass a Mongoose `ctx.session` opened on a transaction — both writes
92
+ * thread it — at the cost of requiring a replica set and a configured
93
+ * outbox (see docs/host-integration.md).
65
94
  *
66
95
  * After merging, the source draft is marked `abandoned` so it's no
67
96
  * longer active.
68
97
  */
69
98
  async function mergeDrafts(opts) {
70
99
  const { repo, sourcePublicId, targetActorRef, ctx } = opts;
71
- const source = await repo.findByPublicId(sourcePublicId, ctx);
72
- if (!source || source.status !== "active") throw new Error(`Source draft '${sourcePublicId}' not found or not active`);
73
100
  const targetCtx = {
74
101
  ...ctx,
75
102
  actorRef: targetActorRef
76
103
  };
77
- const target = await repo.findActiveByActor(targetActorRef, targetCtx);
78
- if (!target) return repo.updateWithVersion(source._id, source.version, {
79
- actorRef: targetActorRef,
80
- actorKind: "user"
81
- }, ctx);
82
- const sourceLines = source.lines;
83
- const currentTargetLines = target.lines;
84
- const mergedLines = repo.mergeLines(currentTargetLines, sourceLines);
85
- const updated = await repo.replaceLines({
86
- draftPublicId: target.publicId,
87
- lines: mergedLines
88
- }, targetCtx);
89
- await repo.markAbandoned(source._id, ctx);
90
- return updated;
104
+ let sourceLines = null;
105
+ let lastError;
106
+ for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {
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`);
109
+ if (!await repo.findActiveByActor(targetActorRef, targetCtx)) try {
110
+ return await repo.updateWithVersion(source._id, source.version, {
111
+ actorRef: targetActorRef,
112
+ actorKind: "user"
113
+ }, ctx);
114
+ } catch (err) {
115
+ if (err instanceof ConcurrencyError) {
116
+ lastError = err;
117
+ continue;
118
+ }
119
+ throw err;
120
+ }
121
+ if (!await repo.markAbandoned(source._id, ctx, { expectedVersion: source.version })) {
122
+ lastError = new ConcurrencyError("draft", source.version, String(source._id));
123
+ continue;
124
+ }
125
+ sourceLines = source.lines;
126
+ break;
127
+ }
128
+ if (!sourceLines) throw lastError;
129
+ for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {
130
+ const target = await repo.findActiveByActor(targetActorRef, targetCtx);
131
+ if (!target) throw new Error(`Target draft for actor '${targetActorRef}' disappeared during merge of '${sourcePublicId}'`);
132
+ const mergedLines = repo.mergeLines(target.lines, sourceLines);
133
+ try {
134
+ return await repo.replaceLines({
135
+ draftPublicId: target.publicId,
136
+ lines: mergedLines,
137
+ expectedVersion: target.version
138
+ }, targetCtx);
139
+ } catch (err) {
140
+ if (err instanceof ConcurrencyError) {
141
+ lastError = err;
142
+ continue;
143
+ }
144
+ throw err;
145
+ }
146
+ }
147
+ throw lastError;
91
148
  }
92
149
  //#endregion
93
- export { CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutRepository, CheckoutStep, ConcurrencyError, DraftRepository, IdempotencyBusyError, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PriceChangedError, ReservationError, ReservationRepository, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
150
+ export { CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutRepository, CheckoutStep, ConcurrencyError, DEFAULT_STALE_OPEN_CHECKOUT_MS, DraftRepository, IdempotencyBusyError, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PriceChangedError, ReservationError, ReservationRepository, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
@@ -209,6 +209,20 @@ interface DraftRepositoryDeps {
209
209
  * Multi-tenant scoping is enforced by `multiTenantPlugin` at POLICY priority;
210
210
  * `publicId` is generated by `customIdPlugin`. Optimistic concurrency runs
211
211
  * through mongokit's `update()` so all hooks (audit, observability) fire.
212
+ *
213
+ * ## Concurrency invariant — read-modify-write on `lines` is CAS-safe
214
+ *
215
+ * Every line mutation (addItem, updateItemQuantity, removeItem, clear,
216
+ * replaceLines) rebuilds the FULL `lines` array in memory from a single
217
+ * read and persists it via `updateWithVersion`, which only matches when
218
+ * the stored `version` still equals the version of that read. Any
219
+ * concurrent mutation bumps `version`, so the stale rebuild can never
220
+ * land — the loser gets a typed `ConcurrencyError` and retries from a
221
+ * fresh read. Do NOT "optimize" these paths into positional `$push` /
222
+ * `$set('lines.$')` array operators: pricing snapshots are derived from
223
+ * the whole line set, so a partial array write would let `lines` and
224
+ * `pricing` drift apart. The version CAS is what makes the in-memory
225
+ * rebuild safe; the rebuild is what keeps pricing consistent.
212
226
  */
213
227
  declare class DraftRepository extends Repository<DraftDocument> {
214
228
  private readonly kinds;
@@ -266,8 +280,16 @@ declare class DraftRepository extends Repository<DraftDocument> {
266
280
  /**
267
281
  * Atomic transition `active → abandoned`. Returns null if the draft was
268
282
  * already in a non-active state.
283
+ *
284
+ * Pass `opts.expectedVersion` to ALSO compare-and-set on `version` —
285
+ * the merge service uses this to guarantee the source draft's line set
286
+ * it captured is exactly the line set being retired (a concurrent
287
+ * add-to-cart bumps `version`, the CAS misses, and the merge retries
288
+ * from a fresh read instead of silently dropping the new line).
269
289
  */
270
- markAbandoned(draftId: Types.ObjectId | string, ctx: OperationContext): Promise<DraftDocument | null>;
290
+ markAbandoned(draftId: Types.ObjectId | string, ctx: OperationContext, opts?: {
291
+ expectedVersion?: number;
292
+ }): Promise<DraftDocument | null>;
271
293
  /**
272
294
  * Mark a draft as converted (called from CheckoutRepository.commit).
273
295
  * Best-effort: a missed update is reconciled by the next getOrCreate.
@@ -277,10 +299,18 @@ declare class DraftRepository extends Repository<DraftDocument> {
277
299
  * Replace the line collection atomically and refresh the pricing snapshot.
278
300
  * Internal services use this to keep merge-like flows inside repository
279
301
  * concurrency + pricing rules instead of hand-writing persistence logic.
302
+ *
303
+ * Pass `expectedVersion` when `lines` was computed from an EARLIER read
304
+ * of the draft: the CAS then pins to that read's version, so any
305
+ * mutation that landed in between (concurrent add-to-cart during a
306
+ * merge) surfaces as `ConcurrencyError` instead of being overwritten.
307
+ * Without it, the CAS pins to this method's own fresh read — safe for
308
+ * callers whose `lines` doesn't derive from draft state.
280
309
  */
281
310
  replaceLines(input: {
282
311
  draftPublicId: string;
283
312
  lines: readonly LineItem[];
313
+ expectedVersion?: number;
284
314
  }, ctx: OperationContext): Promise<DraftDocument>;
285
315
  mergeLines(existing: readonly LineItem[], incoming: readonly LineItem[]): LineItem[];
286
316
  private readOptions;
@@ -309,7 +339,20 @@ interface CheckoutRepositoryDeps {
309
339
  draftRepo: DraftRepository;
310
340
  clock: ClockPort;
311
341
  eventPublisher: CartEventPublisher;
342
+ /**
343
+ * Age (ms) past which an `open` checkout is considered a zombie and is
344
+ * lazily expired by `createFromDraft` instead of being returned as the
345
+ * idempotent dedup hit. Default: `DEFAULT_STALE_OPEN_CHECKOUT_MS`.
346
+ */
347
+ staleOpenCheckoutMs?: number | undefined;
312
348
  }
349
+ /**
350
+ * Default zombie window for open checkouts — matches the package's
351
+ * existing expiry default (`reservationConfigSchema.defaultTtlSeconds`,
352
+ * 600s): once any reservation hold backing the checkout has lapsed, the
353
+ * open snapshot has no claim on anything and is safe to self-expire.
354
+ */
355
+ declare const DEFAULT_STALE_OPEN_CHECKOUT_MS = 600000;
313
356
  /**
314
357
  * CheckoutRepository — extends mongokit's `Repository<CheckoutDocument>`.
315
358
  *
@@ -322,6 +365,7 @@ declare class CheckoutRepository extends Repository<CheckoutDocument> {
322
365
  private readonly draftRepo;
323
366
  private readonly clock;
324
367
  private readonly eventPublisher;
368
+ private readonly staleOpenCheckoutMs;
325
369
  constructor(model: Model<CheckoutDocument>, plugins: PluginType[], deps: CheckoutRepositoryDeps);
326
370
  findByPublicId(publicId: string, ctx: OperationContext): Promise<CheckoutDocument | null>;
327
371
  findByDraft(draftId: Types.ObjectId | string, ctx: OperationContext): Promise<CheckoutDocument | null>;
@@ -357,6 +401,13 @@ declare class CheckoutRepository extends Repository<CheckoutDocument> {
357
401
  * call this from a periodic job (cron, Streamline, etc.) at whatever
358
402
  * cadence matches their checkout completion SLA.
359
403
  *
404
+ * This is the BULK sweep. `createFromDraft` additionally self-heals
405
+ * lazily: when it finds an open checkout older than
406
+ * `staleOpenCheckoutMs`, it CAS-expires that one zombie inline and
407
+ * creates a fresh checkout — so a customer is never stuck waiting for
408
+ * the next cron tick. Keep both: lazy healing fixes the active
409
+ * customer's path; the cron reclaims abandoned rows nobody revisits.
410
+ *
360
411
  * Returns the count of rows expired. Caller scopes the operation via
361
412
  * `ctx` — pass `ctx.organizationId` to scope to one tenant, or use
362
413
  * `skipTenant: true` to expire across the board (only safe for the
@@ -370,6 +421,18 @@ declare class CheckoutRepository extends Repository<CheckoutDocument> {
370
421
  expireStaleOpenCheckouts(maxAgeMs: number, ctx: OperationContext): Promise<{
371
422
  count: number;
372
423
  }>;
424
+ /** Is this open checkout past the zombie window? */
425
+ private isStaleOpen;
426
+ /**
427
+ * CAS-expire a zombie open checkout: `open → canceled` with
428
+ * `canceledReason: 'expired'` — same terminal shape the cron
429
+ * (`expireStaleOpenCheckouts`) writes, so audit history is uniform.
430
+ * The `{ state: 'open', version }` filter makes the transition atomic:
431
+ * a concurrent commit/cancel/expiry wins and this call is a no-op
432
+ * (returns false). No CHECKOUT_CANCELED event — expiry is janitorial,
433
+ * matching the cron method's contract.
434
+ */
435
+ private expireZombie;
373
436
  private readOptions;
374
437
  private writeOptions;
375
438
  private requireCheckout;
@@ -487,6 +550,8 @@ interface CreateCartRepositoriesConfig {
487
550
  multiTenant?: boolean;
488
551
  outbox?: OutboxStore;
489
552
  plugins?: CartRepositoryPluginBundle;
553
+ /** Zombie window for lazy open-checkout expiry. See `CheckoutRepositoryDeps`. */
554
+ staleOpenCheckoutMs?: number;
490
555
  }
491
556
  declare function createCartRepositories(models: CartModels, config: CreateCartRepositoriesConfig): CartRepositories;
492
557
  //#endregion
@@ -683,4 +748,4 @@ declare class InProcessCartEventBus implements EventTransport {
683
748
  close(): Promise<void>;
684
749
  }
685
750
  //#endregion
686
- export { IdempotencyDocument as C, CheckoutDocument as D, createDraftModel as E, createCheckoutModel as O, createReservationModel as S, DraftDocument as T, CartModelName as _, CartEngine as a, createCartModels as b, CreateCartRepositoriesConfig as c, IdempotencyRepository as d, CheckoutRepository as f, CartEventPublisherDeps as g, DraftRepositoryDeps as h, CartConfig as i, createCartRepositories as l, DraftRepository as m, createCart as n, CartRepositories as o, CheckoutRepositoryDeps as p, CartBridges as r, CartRepositoryPluginBundle as s, InProcessCartEventBus as t, ReservationRepository as u, CartModels as v, createIdempotencyModel as w, ReservationDocument as x, CreateCartModelsOptions as y };
751
+ export { createReservationModel as C, createDraftModel as D, DraftDocument as E, CheckoutDocument as O, ReservationDocument as S, createIdempotencyModel as T, CartEventPublisherDeps as _, CartEngine as a, CreateCartModelsOptions as b, CreateCartRepositoriesConfig as c, IdempotencyRepository as d, CheckoutRepository as f, DraftRepositoryDeps as g, DraftRepository as h, CartConfig as i, createCheckoutModel as k, createCartRepositories as l, DEFAULT_STALE_OPEN_CHECKOUT_MS as m, createCart as n, CartRepositories as o, CheckoutRepositoryDeps as p, CartBridges as r, CartRepositoryPluginBundle as s, InProcessCartEventBus as t, ReservationRepository as u, CartModelName as v, IdempotencyDocument as w, createCartModels as x, CartModels as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/cart",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
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.13.0",
86
+ "@classytic/mongokit": ">=3.16.0",
87
87
  "@classytic/primitives": ">=0.5.0",
88
- "@classytic/repo-core": ">=0.4.0",
88
+ "@classytic/repo-core": ">=0.6.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.13.0",
95
+ "@classytic/mongokit": "^3.16.0",
96
96
  "@classytic/primitives": ">=0.5.0",
97
- "@classytic/repo-core": ">=0.4.0",
97
+ "@classytic/repo-core": "^0.6.0",
98
98
  "@types/node": "^25.5.0",
99
99
  "knip": "^6.7.0",
100
100
  "mongodb-memory-server": "^10.2.3",