@classytic/cart 1.1.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/{cart-event-catalog-Cokx0iOw.d.mts → cart-event-catalog-DZvoNVek.d.mts} +1 -1
  3. package/dist/{clock.port-DrSBrsit.d.mts → clock.port-BFg5X92u.d.mts} +5 -0
  4. package/dist/{define-cart-CYkjJdC7.mjs → define-cart-CxIG6Omt.mjs} +87 -18
  5. package/dist/domain/events/index.d.mts +2 -2
  6. package/dist/domain/index.d.mts +7 -7
  7. package/dist/domain/ports/index.d.mts +1 -1
  8. package/dist/domain/ports/index.mjs +1 -2
  9. package/dist/domain/saga/index.d.mts +1 -1
  10. package/dist/domain/saga/index.mjs +1 -2
  11. package/dist/engine/cart-config.schema.d.mts +10 -9
  12. package/dist/engine/cart-config.schema.mjs +9 -3
  13. package/dist/engine/index.d.mts +1 -1
  14. package/dist/engine/index.mjs +1 -1
  15. package/dist/index.d.mts +18 -18
  16. package/dist/index.mjs +2 -2
  17. package/dist/{internal-event-bus-Ci5Zpoqu.d.mts → internal-event-bus-BfC4OKwH.d.mts} +29 -5
  18. package/dist/{kind-registry-BkYl0cjc.d.mts → kind-registry-Cb50lwpo.d.mts} +9 -3
  19. package/dist/kinds/index.d.mts +1 -1
  20. package/dist/kinds/index.mjs +1 -2
  21. package/dist/{line-kind-kYeQzpCy.d.mts → line-kind-CY7cabbf.d.mts} +7 -1
  22. package/dist/line-total-CHnkZ3nH.mjs +25 -0
  23. package/dist/{outbox-store-Br7MHuOz.d.mts → outbox-store-Cq7K0Lo6.d.mts} +11 -11
  24. package/dist/{reservation.entity-CLRqLD6X.d.mts → reservation.entity-9V2i4i1l.d.mts} +5 -5
  25. package/dist/{state-transitions-B_ozUaqV.d.mts → state-transitions-B3EPuOae.d.mts} +2 -2
  26. package/dist/{variant.kind-BVmeGR6G.d.mts → variant.kind-DQxxcsib.d.mts} +1 -1
  27. package/dist/{variant.kind-CquIUes6.mjs → variant.kind-_LIXlTwp.mjs} +13 -3
  28. package/package.json +29 -20
  29. package/dist/line-total-6VJQMjGV.mjs +0 -24
package/CHANGELOG.md CHANGED
@@ -3,6 +3,54 @@
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
+ ## 1.3.0 — 2026-10-14
7
+
8
+ ### Added — fractional lines on the product's step
9
+ - `ProductSummary.quantityStep` (optional, absent = 1) and an optional `LineKind.quantityStepOf`,
10
+ implemented by `sku` and `variant`. The draft repository checks every add, merge and quantity
11
+ update against the line's step and stores it on `LineItem.quantityStep` (absent = 1). A kind that
12
+ declares no step keeps the positive-integer rule.
13
+ - `lineTotal` extends a fractional quantity exactly on the 6-dp grid, rounded once half-even; a
14
+ merge adds on the grid (`1.2 + 1.15` kg is 2.35).
15
+ - `updateItemQuantity` removes the line at `quantity <= 0` (was `< 1`, which would have removed a
16
+ 0.5 kg line); a whole-unit line given 0.5 is now refused rather than removed.
17
+ - The draft and reservation models accept any positive quantity (was `min: 1`).
18
+ - Bundle component quantities stay whole numbers (a component carries no step yet).
19
+ - The package's own copy of the quantity grid is gone: it uses `@classytic/primitives/quantity` and `price-basis` (`>=0.31.0`). `lineTotal` adds the sign for a negative unit price; an off-grid quantity throws primitives' `PriceBasisError` (was `RangeError`).
20
+ ### Changed — draft retention is enforced (`draftRetentionSeconds`, default 90 days)
21
+
22
+ Every draft write (create, line change, abandon, convert) stamps `expiresAt = now + draftRetentionSeconds`; `expiresAt` is now REQUIRED on the model, so the existing TTL index removes idle and finished drafts. Before, every draft carried `expiresAt: null` and the TTL never fired. The unread `draftTtlSeconds` option is removed. Existing rows: `be-prod/scripts/migrations/stamp-cart-draft-expiry.mjs`. Pinned by `tests/integration/draft-retention.integration.test.ts`.
23
+
24
+ ### Changed — peer floors
25
+
26
+ `@classytic/mongokit` `>=3.41.0`, `@classytic/primitives` `>=0.32.0`, `@classytic/repo-core` `>=0.31.0`, `mongoose` `>=9.11.0`.
27
+
28
+ ## 1.2.0 — 2026-09-04
29
+
30
+ ### Added — `DraftRepository.markActiveConvertedForActor`
31
+
32
+ Hosts that place an order without freezing a checkout first have no `checkout.draftId` for `markConverted` to key on, leaving the draft `active` with lines intact — exactly the shape the abandonment sweep selects. `markActiveConvertedForActor(actorRef, ctx)` looks up the actor's active draft and converts it in one call. Returns `false` if no active draft exists or `actorRef` is empty (guard against broad-match on empty string). Best-effort like `markConverted`: a miss does not fail the order.
33
+
34
+ ## 1.1.1 — 2026-08-26
35
+
36
+ ### Fixed
37
+
38
+ - **`LineDisplay.weightGrams` captured from catalog bridge snapshot** — both
39
+ `skuKind` and `variantKind` now emit `weightGrams` when the bridge supplies it
40
+ (real and positive only; absent stays absent so weight-tiered delivery zones
41
+ fall back to the flat charge rather than pricing the cheapest step). The field
42
+ was already in the bridge's product shape; the snapshot simply never forwarded
43
+ it, so every weight-tiered checkout fell back to flat.
44
+ - **`draft.model.ts` declares `weightGrams`** — Mongoose strips unknown paths
45
+ silently; without the schema declaration the field would be dropped on every
46
+ write. `default: null` preserves the absent/unweighed distinction (no `0`
47
+ default).
48
+
49
+ ### Changed
50
+
51
+ - **Peer floors raised** — mongokit `>=3.35.0`, primitives `>=0.25.0`,
52
+ repo-core `>=0.25.0`.
53
+
6
54
  ## 1.1.0 - 2026-08-17
7
55
 
8
56
  ### Changed
@@ -1,4 +1,4 @@
1
- import { _ as CartEventMeta, b as CartEventName, h as CartDomainEvent } from "./outbox-store-Br7MHuOz.mjs";
1
+ import { _ as CartEventMeta, b as CartEventName, h as CartDomainEvent } from "./outbox-store-Cq7K0Lo6.mjs";
2
2
  //#region src/domain/events/event-schema.d.ts
3
3
  /**
4
4
  * EventSchema — minimal JSON-schema-like shape for event payload validation.
@@ -334,6 +334,11 @@ interface ProductSummary {
334
334
  name: string;
335
335
  /** Unit price in minor units. Used by the `sku` and `variant` kinds. */
336
336
  unitPrice: Money;
337
+ /**
338
+ * The quantity increment the product sells in, in the unit `unitPrice` is per (`0.001` kg).
339
+ * Absent = 1, whole units. The catalog's `resolveSalesUnit(...).quantityStep`.
340
+ */
341
+ quantityStep?: number;
337
342
  /** Optional compare-at price for showing strikethrough in the UI. */
338
343
  compareAtPrice?: Money;
339
344
  /**
@@ -4,12 +4,14 @@ import { n as CartEvents, t as createCartEvent } from "./domain-event-DBFsiHNJ.m
4
4
  import { n as cryptoIdPort, r as systemClock } from "./id.port-DYAnXbfV.mjs";
5
5
  import { t as createKindRegistry } from "./kind-registry-DQYqRQZU.mjs";
6
6
  import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-wunwhjap.mjs";
7
- import { t as lineTotal } from "./line-total-6VJQMjGV.mjs";
7
+ import { t as lineTotal } from "./line-total-CHnkZ3nH.mjs";
8
+ import "./engine/cart-config.schema.mjs";
8
9
  import { money } from "@classytic/primitives/money";
9
10
  import { Repository, customIdPlugin, defineModels, isDuplicateKeyError, multiTenantPlugin, prefixedId, withTransaction } from "@classytic/mongokit";
10
11
  import { CURRENCY_PATTERN, currencyCode } from "@classytic/primitives/currency";
11
12
  import mongoose, { Schema } from "mongoose";
12
13
  import { assertNoLegacyTenantKeys, resolveTenantConfig } from "@classytic/repo-core/tenant";
14
+ import { addQuantity, isOnQuantityGrid, isOnStepStrict, isQuantityStep } from "@classytic/primitives/quantity";
13
15
  import { createHash } from "node:crypto";
14
16
  import { InProcessEventBus } from "@classytic/primitives/event-infra";
15
17
  //#region src/domain/ports/common.ts
@@ -223,8 +225,12 @@ const lineItemSubSchema = new Schema({
223
225
  quantity: {
224
226
  type: Number,
225
227
  required: true,
226
- min: 1
228
+ validate: {
229
+ validator: (v) => v > 0,
230
+ message: "quantity must be > 0"
231
+ }
227
232
  },
233
+ quantityStep: { type: Number },
228
234
  overrideUnitPrice: {
229
235
  type: Schema.Types.Mixed,
230
236
  default: null
@@ -341,7 +347,7 @@ function buildDraftSchema() {
341
347
  },
342
348
  expiresAt: {
343
349
  type: Date,
344
- default: null
350
+ required: true
345
351
  },
346
352
  lastIdempotencyKey: {
347
353
  type: String,
@@ -527,7 +533,10 @@ function buildReservationSchema() {
527
533
  quantity: {
528
534
  type: Number,
529
535
  required: true,
530
- min: 1
536
+ validate: {
537
+ validator: (v) => v > 0,
538
+ message: "quantity must be > 0"
539
+ }
531
540
  },
532
541
  status: {
533
542
  type: String,
@@ -1318,6 +1327,7 @@ var DraftRepository = class extends Repository {
1318
1327
  clock;
1319
1328
  id;
1320
1329
  defaultCurrency;
1330
+ draftRetentionMs;
1321
1331
  eventPublisher;
1322
1332
  constructor(model, plugins, deps) {
1323
1333
  super(model, plugins);
@@ -1326,6 +1336,7 @@ var DraftRepository = class extends Repository {
1326
1336
  this.clock = deps.clock;
1327
1337
  this.id = deps.id;
1328
1338
  this.defaultCurrency = deps.defaultCurrency;
1339
+ this.draftRetentionMs = deps.draftRetentionSeconds * 1e3;
1329
1340
  this.eventPublisher = deps.eventPublisher;
1330
1341
  }
1331
1342
  async findActiveByActor(actorRef, ctx) {
@@ -1362,18 +1373,20 @@ var DraftRepository = class extends Repository {
1362
1373
  async addItem(input, ctx) {
1363
1374
  const draft = await this.getOrCreateDraft(ctx);
1364
1375
  const kind = this.kinds.get(input.kind);
1365
- const quantity = assertPositiveInteger(input.quantity, input.kind);
1376
+ assertPositiveQuantity(input.quantity, input.kind);
1366
1377
  const parsedPayload = kind.payloadSchema.safeParse(input.payload);
1367
1378
  if (!parsedPayload.success) throw new KindError(input.kind, "invalid payload shape", { details: { issues: parsedPayload.error.issues } });
1368
1379
  const newLine = {
1369
1380
  lineId: `line_${this.id.newId()}`,
1370
1381
  kind: input.kind,
1371
- quantity,
1382
+ quantity: input.quantity,
1372
1383
  payload: parsedPayload.data,
1373
1384
  currency: draft.currency,
1374
1385
  overrideUnitPrice: input.overrideUnitPrice
1375
1386
  };
1376
1387
  const kindCtx = this.kindContextFor(ctx);
1388
+ const quantityStep = await resolveQuantityStep(kind.quantityStepOf?.(newLine, kindCtx), input.kind);
1389
+ assertOnStep(newLine.quantity, quantityStep, input.kind);
1377
1390
  await kind.validate(newLine, kindCtx);
1378
1391
  const display = input.display !== void 0 ? input.display : kind.displayOf ? await kind.displayOf(newLine, kindCtx) : null;
1379
1392
  const persistedLine = {
@@ -1381,6 +1394,7 @@ var DraftRepository = class extends Repository {
1381
1394
  kind: newLine.kind,
1382
1395
  payload: newLine.payload,
1383
1396
  quantity: newLine.quantity,
1397
+ ...quantityStep !== 1 ? { quantityStep } : {},
1384
1398
  overrideUnitPrice: newLine.overrideUnitPrice,
1385
1399
  display: display ?? void 0,
1386
1400
  addedAt: this.clock.now()
@@ -1407,7 +1421,7 @@ var DraftRepository = class extends Repository {
1407
1421
  return updated;
1408
1422
  }
1409
1423
  async updateItemQuantity(input, ctx) {
1410
- if (input.quantity < 1) return this.removeItem({
1424
+ if (input.quantity <= 0) return this.removeItem({
1411
1425
  draftPublicId: input.draftPublicId,
1412
1426
  lineId: input.lineId
1413
1427
  }, ctx);
@@ -1415,7 +1429,9 @@ var DraftRepository = class extends Repository {
1415
1429
  const currentLines = draft.lines;
1416
1430
  const existingLine = currentLines.find((l) => l.lineId === input.lineId);
1417
1431
  if (!existingLine) throw new NotFoundError("line", input.lineId, ctx.organizationId);
1418
- const quantity = assertPositiveInteger(input.quantity, existingLine.kind);
1432
+ const quantity = input.quantity;
1433
+ assertPositiveQuantity(quantity, existingLine.kind);
1434
+ assertOnStep(quantity, existingLine.quantityStep ?? 1, existingLine.kind);
1419
1435
  if (existingLine.quantity === quantity) return draft;
1420
1436
  const nextLines = currentLines.map((l) => l.lineId === input.lineId ? {
1421
1437
  ...l,
@@ -1490,7 +1506,8 @@ var DraftRepository = class extends Repository {
1490
1506
  async createForActor(data, ctx) {
1491
1507
  return await this.create({
1492
1508
  ...data,
1493
- version: 0
1509
+ version: 0,
1510
+ expiresAt: this.nextExpiry()
1494
1511
  }, this.writeOptions(ctx));
1495
1512
  }
1496
1513
  /**
@@ -1502,7 +1519,10 @@ var DraftRepository = class extends Repository {
1502
1519
  async updateWithVersion(draftId, expectedVersion, updates, ctx) {
1503
1520
  try {
1504
1521
  return await this.update(draftId, {
1505
- $set: updates,
1522
+ $set: {
1523
+ ...updates,
1524
+ expiresAt: this.nextExpiry()
1525
+ },
1506
1526
  $inc: { version: 1 }
1507
1527
  }, {
1508
1528
  ...this.writeOptions(ctx),
@@ -1528,7 +1548,10 @@ var DraftRepository = class extends Repository {
1528
1548
  async markAbandoned(draftId, ctx, opts = {}) {
1529
1549
  try {
1530
1550
  const updated = await this.update(draftId, {
1531
- $set: { status: "abandoned" },
1551
+ $set: {
1552
+ status: "abandoned",
1553
+ expiresAt: this.nextExpiry()
1554
+ },
1532
1555
  $inc: { version: 1 }
1533
1556
  }, {
1534
1557
  ...this.writeOptions(ctx),
@@ -1564,13 +1587,36 @@ var DraftRepository = class extends Repository {
1564
1587
  }
1565
1588
  }
1566
1589
  /**
1590
+ * Mark this ACTOR's active draft converted, if they have one.
1591
+ *
1592
+ * For hosts that place an order without freezing a checkout first — there is
1593
+ * then no `checkout.draftId` for `markConverted` to key on, and the draft
1594
+ * stays `active` with its lines intact. The abandonment sweep selects exactly
1595
+ * that shape (`status: 'active'` + `lines.0` exists), so a purchased cart
1596
+ * becomes an abandoned-cart email.
1597
+ *
1598
+ * Returns whether anything was converted, so a caller can log the miss rather
1599
+ * than assume. Best-effort like `markConverted`: the order is already placed
1600
+ * and nothing here may fail it.
1601
+ */
1602
+ async markActiveConvertedForActor(actorRef, ctx) {
1603
+ if (!actorRef) return false;
1604
+ const draft = await this.findActiveByActor(actorRef, ctx);
1605
+ if (!draft) return false;
1606
+ await this.markConverted(draft._id, ctx);
1607
+ return true;
1608
+ }
1609
+ /**
1567
1610
  * Mark a draft as converted (called from CheckoutRepository.commit).
1568
1611
  * Best-effort: a missed update is reconciled by the next getOrCreate.
1569
1612
  */
1570
1613
  async markConverted(draftId, ctx) {
1571
1614
  try {
1572
1615
  await this.update(draftId, {
1573
- $set: { status: "converted" },
1616
+ $set: {
1617
+ status: "converted",
1618
+ expiresAt: this.nextExpiry()
1619
+ },
1574
1620
  $inc: { version: 1 }
1575
1621
  }, this.writeOptions(ctx));
1576
1622
  } catch {}
@@ -1599,6 +1645,10 @@ var DraftRepository = class extends Repository {
1599
1645
  mergeLines(existing, incoming) {
1600
1646
  return incoming.reduce((acc, line) => this.mergeLine(acc, { ...line }), [...existing]);
1601
1647
  }
1648
+ /** The retention deadline every write stamps — the TTL index deletes past it. */
1649
+ nextExpiry() {
1650
+ return new Date(this.clock.now().getTime() + this.draftRetentionMs);
1651
+ }
1602
1652
  readOptions(ctx) {
1603
1653
  return {
1604
1654
  organizationId: ctx.organizationId,
@@ -1651,9 +1701,13 @@ var DraftRepository = class extends Repository {
1651
1701
  if (key === null) return [...existing, incoming];
1652
1702
  const idx = existing.findIndex((l) => this.computeMergeKey(l) === key);
1653
1703
  if (idx === -1) return [...existing, incoming];
1704
+ const quantity = addQuantity(existing[idx].quantity, incoming.quantity);
1705
+ assertOnStep(quantity, incoming.quantityStep ?? 1, incoming.kind);
1706
+ const { quantityStep: _previous, ...base } = existing[idx];
1654
1707
  const merged = {
1655
- ...existing[idx],
1656
- quantity: existing[idx].quantity + incoming.quantity
1708
+ ...base,
1709
+ quantity,
1710
+ ...incoming.quantityStep !== void 0 ? { quantityStep: incoming.quantityStep } : {}
1657
1711
  };
1658
1712
  return existing.map((l, i) => i === idx ? merged : l);
1659
1713
  }
@@ -1690,9 +1744,19 @@ var DraftRepository = class extends Repository {
1690
1744
  function isNotFound$1(err) {
1691
1745
  return typeof err === "object" && err !== null && err.status === 404;
1692
1746
  }
1693
- function assertPositiveInteger(quantity, kind) {
1694
- if (!Number.isInteger(quantity) || quantity < 1) throw new KindError(kind, `quantity must be a positive integer, got ${quantity}`);
1695
- return quantity;
1747
+ function assertPositiveQuantity(quantity, kind) {
1748
+ if (typeof quantity !== "number" || !(quantity > 0) || !isOnQuantityGrid(quantity)) throw new KindError(kind, `quantity must be a positive number with at most 6 decimals, got ${quantity}`);
1749
+ }
1750
+ /** A whole multiple of the line's step; step 1 (no step declared) means a positive integer. */
1751
+ function assertOnStep(quantity, step, kind) {
1752
+ if (!isOnStepStrict(quantity, step)) throw new KindError(kind, step === 1 ? `quantity must be a positive integer, got ${quantity}` : `quantity ${quantity} is not a multiple of the line's step ${step}`);
1753
+ }
1754
+ /** The kind's declared step, absent = 1. A malformed step is the kind's fault and refuses the add. */
1755
+ async function resolveQuantityStep(pending, kind) {
1756
+ const step = pending === void 0 ? void 0 : await pending;
1757
+ if (step === void 0) return 1;
1758
+ if (!isQuantityStep(step)) throw new KindError(kind, `quantityStepOf returned an invalid step: ${String(step)}`);
1759
+ return step;
1696
1760
  }
1697
1761
  //#endregion
1698
1762
  //#region src/repositories/idempotency.repository.ts
@@ -1953,7 +2017,7 @@ function tenantPlugin(tenant) {
1953
2017
  });
1954
2018
  }
1955
2019
  function createCartRepositories(models, config) {
1956
- const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {}, tenant, staleOpenCheckoutMs } = config;
2020
+ const { kinds, bridges, clock, id, defaultCurrency, draftRetentionSeconds, events, outbox, plugins = {}, tenant, staleOpenCheckoutMs } = config;
1957
2021
  const eventPublisher = new CartEventPublisher({
1958
2022
  events,
1959
2023
  outbox,
@@ -1977,6 +2041,7 @@ function createCartRepositories(models, config) {
1977
2041
  clock,
1978
2042
  id,
1979
2043
  defaultCurrency,
2044
+ draftRetentionSeconds,
1980
2045
  eventPublisher
1981
2046
  });
1982
2047
  return {
@@ -2096,6 +2161,8 @@ function defineCart(shape) {
2096
2161
  requireKinds(shape);
2097
2162
  const tenant = resolveCartTenant(shape.tenant ?? true);
2098
2163
  const defaultCurrency = currencyCode(shape.defaultCurrency ?? "USD");
2164
+ const draftRetentionSeconds = shape.draftRetentionSeconds ?? 7776e3;
2165
+ if (!Number.isInteger(draftRetentionSeconds) || draftRetentionSeconds <= 0) throw new Error(`defineCart: draftRetentionSeconds must be a positive integer, got ${draftRetentionSeconds}`);
2099
2166
  const modelBlueprint = defineCartModels({
2100
2167
  tenant,
2101
2168
  ...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
@@ -2142,6 +2209,7 @@ function defineCart(shape) {
2142
2209
  clock,
2143
2210
  id,
2144
2211
  defaultCurrency,
2212
+ draftRetentionSeconds,
2145
2213
  events,
2146
2214
  ...runtime.outbox !== void 0 ? { outbox: runtime.outbox } : {},
2147
2215
  ...runtime.repositoryPlugins !== void 0 ? { plugins: runtime.repositoryPlugins } : {},
@@ -2154,6 +2222,7 @@ function defineCart(shape) {
2154
2222
  tenant,
2155
2223
  forceRecreate: shape.forceRecreate ?? false,
2156
2224
  defaultCurrency,
2225
+ draftRetentionSeconds,
2157
2226
  allowNonTransactional,
2158
2227
  ...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
2159
2228
  ...staleOpenCheckoutMs !== void 0 ? { staleOpenCheckoutMs } : {}
@@ -1,3 +1,3 @@
1
- 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-Br7MHuOz.mjs";
2
- 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-Cokx0iOw.mjs";
1
+ 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-Cq7K0Lo6.mjs";
2
+ 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-DZvoNVek.mjs";
3
3
  export { type CartAggregateType, type CartDomainEvent, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventRegistry, CartEvents, type EventSchema, type EventSchemaProperty, type EventValidationResult, type EventValidator, InvalidOutboxEventError, MemoryOutboxStore, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, type PayloadOf, cartEventDefinitions, cartEventsByName, createCartEvent, createCartEventRegistry, defineCartEvent };
@@ -1,13 +1,13 @@
1
1
  import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, g as CartErrorCategory, h as CartError, i as IdempotencyBusyError, l as PriceChangedError, m as ConcurrencyError, n as StateTransitionError, o as SagaError, p as CurrencyMismatchError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "../index-BTSo-RLv.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "../cart-status.vo-BoVPaSXX.mjs";
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-Br7MHuOz.mjs";
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-Cokx0iOw.mjs";
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-Cq7K0Lo6.mjs";
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-DZvoNVek.mjs";
5
5
  import "./events/index.mjs";
6
- 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-DrSBrsit.mjs";
7
- import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-CLRqLD6X.mjs";
8
- 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-B_ozUaqV.mjs";
9
- 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-kYeQzpCy.mjs";
10
- 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-BkYl0cjc.mjs";
6
+ 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-BFg5X92u.mjs";
7
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-9V2i4i1l.mjs";
8
+ 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-B3EPuOae.mjs";
9
+ 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-CY7cabbf.mjs";
10
+ 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-Cb50lwpo.mjs";
11
11
  import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../id.port-DzgWy8sy.mjs";
12
12
  import "./ports/index.mjs";
13
13
  import "./saga/index.mjs";
@@ -1,3 +1,3 @@
1
- import { C as OperationContext, S as BridgeStatus, _ 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-DrSBrsit.mjs";
1
+ import { C as OperationContext, S as BridgeStatus, _ 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-BFg5X92u.mjs";
2
2
  import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../../id.port-DzgWy8sy.mjs";
3
3
  export { type AdjustmentSpec, type BridgeRef, type BridgeStatus, type CartSnapshot, type CatalogBridge, type ClockPort, type IdPort, type InventoryBridge, type OperationContext, type ProductSummary, type PromotionResult, type PromotionsBridge, type ReservationRef, type ReservationRequest, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, createCounterIdPort, cryptoIdPort, systemClock };
@@ -1,2 +1 @@
1
- import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "../../id.port-DYAnXbfV.mjs";
2
- export { createCounterIdPort, cryptoIdPort, systemClock };
1
+ export { t as createCounterIdPort, n as cryptoIdPort, r as systemClock } from "../../id.port-DYAnXbfV.mjs";
@@ -1,2 +1,2 @@
1
- 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-B_ozUaqV.mjs";
1
+ 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-B3EPuOae.mjs";
2
2
  export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, type CheckoutFlowState, CheckoutStep, type CheckoutStepNumber, type SagaDependencies, type SagaStepFn, isLegalCheckoutTransition };
@@ -1,2 +1 @@
1
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../../state-transitions-wunwhjap.mjs";
2
- export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CheckoutStep, isLegalCheckoutTransition };
1
+ export { t as CHECKOUT_MACHINE, n as CHECKOUT_STATE_TRANSITIONS, i as CheckoutStep, r as isLegalCheckoutTransition } from "../../state-transitions-wunwhjap.mjs";
@@ -5,21 +5,23 @@ import { z } from "zod";
5
5
  * fields (kinds, bridges) carry functions and class instances and are validated
6
6
  * structurally by `defineCart` / its bind runtime.
7
7
  */
8
- declare const idempotencyConfigSchema: z.ZodObject<{
8
+ /** Default draft retention: 90 days after the last write. */
9
+ export declare const DEFAULT_DRAFT_RETENTION_SECONDS: number;
10
+ export declare const idempotencyConfigSchema: z.ZodObject<{
9
11
  inlineThresholdBytes: z.ZodDefault<z.ZodNumber>;
10
12
  leaseMs: z.ZodDefault<z.ZodNumber>;
11
13
  retentionSeconds: z.ZodDefault<z.ZodNumber>;
12
14
  }, z.core.$strip>;
13
- declare const reservationConfigSchema: z.ZodObject<{
15
+ export declare const reservationConfigSchema: z.ZodObject<{
14
16
  defaultTtlSeconds: z.ZodDefault<z.ZodNumber>;
15
17
  }, z.core.$strip>;
16
- declare const checkoutConfigSchema: z.ZodObject<{
18
+ export declare const checkoutConfigSchema: z.ZodObject<{
17
19
  staleOpenCheckoutMs: z.ZodDefault<z.ZodNumber>;
18
20
  }, z.core.$strip>;
19
- declare const scopeConfigSchema: z.ZodObject<{
21
+ export declare const scopeConfigSchema: z.ZodObject<{
20
22
  contextKey: z.ZodDefault<z.ZodString>;
21
23
  }, z.core.$strip>;
22
- declare const cartConfigSchema: z.ZodObject<{
24
+ export declare const cartConfigSchema: z.ZodObject<{
23
25
  scope: z.ZodDefault<z.ZodObject<{
24
26
  contextKey: z.ZodDefault<z.ZodString>;
25
27
  }, z.core.$strip>>;
@@ -35,12 +37,11 @@ declare const cartConfigSchema: z.ZodObject<{
35
37
  checkout: z.ZodDefault<z.ZodObject<{
36
38
  staleOpenCheckoutMs: z.ZodDefault<z.ZodNumber>;
37
39
  }, z.core.$strip>>;
38
- draftTtlSeconds: z.ZodOptional<z.ZodNumber>;
40
+ draftRetentionSeconds: z.ZodDefault<z.ZodNumber>;
39
41
  }, z.core.$strip>;
40
42
  /**
41
43
  * The strict config type inferred from the schema. Used for runtime
42
44
  * validation of user-supplied config from env/YAML.
43
45
  */
44
- type CartConfigShape = z.infer<typeof cartConfigSchema>;
45
- //#endregion
46
- export { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
46
+ export type CartConfigShape = z.infer<typeof cartConfigSchema>;
47
+ //#endregion
@@ -6,6 +6,8 @@ import { z } from "zod";
6
6
  * fields (kinds, bridges) carry functions and class instances and are validated
7
7
  * structurally by `defineCart` / its bind runtime.
8
8
  */
9
+ /** Default draft retention: 90 days after the last write. */
10
+ const DEFAULT_DRAFT_RETENTION_SECONDS = 7776e3;
9
11
  const idempotencyConfigSchema = z.object({
10
12
  /** Inline replay payload byte threshold. Default 12KB. */
11
13
  inlineThresholdBytes: z.number().int().positive().default(12288),
@@ -43,8 +45,12 @@ const cartConfigSchema = z.object({
43
45
  }),
44
46
  reservation: reservationConfigSchema.default({ defaultTtlSeconds: 600 }),
45
47
  checkout: checkoutConfigSchema.default({ staleOpenCheckoutMs: 6e5 }),
46
- /** Whether drafts auto-expire via TTL. Default off. */
47
- draftTtlSeconds: z.number().int().positive().optional()
48
+ /**
49
+ * Draft retention: every draft write stamps `expiresAt = now + this`, and the
50
+ * TTL index deletes the draft once it passes. Idle active carts, abandoned and
51
+ * converted drafts all expire. Default 90 days.
52
+ */
53
+ draftRetentionSeconds: z.number().int().positive().default(DEFAULT_DRAFT_RETENTION_SECONDS)
48
54
  });
49
55
  //#endregion
50
- export { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
56
+ export { DEFAULT_DRAFT_RETENTION_SECONDS, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -1,3 +1,3 @@
1
1
  import { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
2
- import { a as defineCart, c as CartEngine, d as CartShape, f as ResolvedCartConfig, i as createCartDomain, l as CartLogger, n as CartBlueprint, o as CartBridges, r as CartDomainRuntime, s as CartDomain, t as InProcessCartEventBus, u as CartRuntime } from "../internal-event-bus-Ci5Zpoqu.mjs";
2
+ import { a as defineCart, c as CartEngine, d as CartShape, f as ResolvedCartConfig, i as createCartDomain, l as CartLogger, n as CartBlueprint, o as CartBridges, r as CartDomainRuntime, s as CartDomain, t as InProcessCartEventBus, u as CartRuntime } from "../internal-event-bus-BfC4OKwH.mjs";
3
3
  export { type CartBlueprint, type CartBridges, type CartConfigShape, type CartDomain, type CartDomainRuntime, type CartEngine, type CartLogger, type CartRuntime, type CartShape, InProcessCartEventBus, type ResolvedCartConfig, cartConfigSchema, checkoutConfigSchema, createCartDomain, defineCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -1,3 +1,3 @@
1
- import { n as defineCart, r as InProcessCartEventBus, t as createCartDomain } from "../define-cart-CYkjJdC7.mjs";
1
+ import { n as defineCart, r as InProcessCartEventBus, t as createCartDomain } from "../define-cart-CxIG6Omt.mjs";
2
2
  import { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
3
3
  export { InProcessCartEventBus, cartConfigSchema, checkoutConfigSchema, createCartDomain, defineCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
package/dist/index.d.mts CHANGED
@@ -1,16 +1,16 @@
1
1
  import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, g as CartErrorCategory, h as CartError, i as IdempotencyBusyError, l as PriceChangedError, m as ConcurrencyError, n as StateTransitionError, o as SagaError, p as CurrencyMismatchError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "./index-BTSo-RLv.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-BoVPaSXX.mjs";
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-Br7MHuOz.mjs";
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-Cokx0iOw.mjs";
5
- import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ as CartSnapshot, a as ShippingQuote, b as Address, 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 PENDING_EVENTS, x as BridgeRef, y as PromotionsBridge } from "./clock.port-DrSBrsit.mjs";
6
- import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-CLRqLD6X.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 } from "./state-transitions-B_ozUaqV.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-kYeQzpCy.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-BkYl0cjc.mjs";
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-Cq7K0Lo6.mjs";
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-DZvoNVek.mjs";
5
+ import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ as CartSnapshot, a as ShippingQuote, b as Address, 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 PENDING_EVENTS, x as BridgeRef, y as PromotionsBridge } from "./clock.port-BFg5X92u.mjs";
6
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-9V2i4i1l.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 } from "./state-transitions-B3EPuOae.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-CY7cabbf.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-Cb50lwpo.mjs";
10
10
  import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-DzgWy8sy.mjs";
11
11
  import { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
12
- import { A as buildReservationSchema, C as DraftRepositoryDeps, D as DefineCartModelsConfig, E as CartModels, F as CheckoutDocument, I as buildCheckoutSchema, M as buildIdempotencySchema, N as DraftDocument, O as defineCartModels, P as buildDraftSchema, S as DraftRepository, T as CartModelName, _ as ReservationRepository, a as defineCart, b as CheckoutRepositoryDeps, c as CartEngine, d as CartShape, f as ResolvedCartConfig, g as createCartRepositories, h as CreateCartRepositoriesConfig, i as createCartDomain, j as IdempotencyDocument, k as ReservationDocument, l as CartLogger, m as CartRepositoryPluginBundle, n as CartBlueprint, o as CartBridges, p as CartRepositories, r as CartDomainRuntime, s as CartDomain, t as InProcessCartEventBus, u as CartRuntime, v as IdempotencyRepository, w as CartEventPublisherDeps, x as DEFAULT_STALE_OPEN_CHECKOUT_MS, y as CheckoutRepository } from "./internal-event-bus-Ci5Zpoqu.mjs";
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-BVmeGR6G.mjs";
12
+ import { A as buildReservationSchema, C as DraftRepositoryDeps, D as DefineCartModelsConfig, E as CartModels, F as CheckoutDocument, I as buildCheckoutSchema, M as buildIdempotencySchema, N as DraftDocument, O as defineCartModels, P as buildDraftSchema, S as DraftRepository, T as CartModelName, _ as ReservationRepository, a as defineCart, b as CheckoutRepositoryDeps, c as CartEngine, d as CartShape, f as ResolvedCartConfig, g as createCartRepositories, h as CreateCartRepositoriesConfig, i as createCartDomain, j as IdempotencyDocument, k as ReservationDocument, l as CartLogger, m as CartRepositoryPluginBundle, n as CartBlueprint, o as CartBridges, p as CartRepositories, r as CartDomainRuntime, s as CartDomain, t as InProcessCartEventBus, u as CartRuntime, v as IdempotencyRepository, w as CartEventPublisherDeps, x as DEFAULT_STALE_OPEN_CHECKOUT_MS, y as CheckoutRepository } from "./internal-event-bus-BfC4OKwH.mjs";
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-DQxxcsib.mjs";
14
14
  import { Money, Money as Money$1, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
15
15
  import { DomainEvent, EventHandler, EventTransport, EventTransport as EventTransport$1, PublishManyResult } from "@classytic/primitives/events";
16
16
  import { CurrencyCode } from "@classytic/primitives/currency";
@@ -24,7 +24,7 @@ import { CleanupStep } from "@classytic/repo-core/cleanup";
24
24
  * Hosts composing their own outer transaction call this after commit;
25
25
  * most should use `engine.withTransaction(ctx, fn)` instead.
26
26
  */
27
- declare function flushPending(eventTransport: EventTransport$1 | undefined, events: DomainEvent[], logger?: {
27
+ export declare function flushPending(eventTransport: EventTransport$1 | undefined, events: DomainEvent[], logger?: {
28
28
  error(message: string, ...args: unknown[]): void;
29
29
  }): Promise<void>;
30
30
  //#endregion
@@ -40,7 +40,7 @@ declare function flushPending(eventTransport: EventTransport$1 | undefined, even
40
40
  * scopes the query at POLICY priority — pass `skipTenant: true` on `ctx`
41
41
  * for cross-tenant admin sweeps.
42
42
  */
43
- declare function findAbandonedDrafts(opts: {
43
+ export declare function findAbandonedDrafts(opts: {
44
44
  repo: DraftRepository;
45
45
  cutoff: Date;
46
46
  limit?: number;
@@ -50,7 +50,7 @@ declare function findAbandonedDrafts(opts: {
50
50
  * Mark a batch of drafts as abandoned. Returns the count of drafts
51
51
  * successfully transitioned.
52
52
  */
53
- declare function markAbandoned(opts: {
53
+ export declare function markAbandoned(opts: {
54
54
  repo: DraftRepository;
55
55
  draftIds: string[];
56
56
  ctx: OperationContext;
@@ -95,7 +95,7 @@ declare function markAbandoned(opts: {
95
95
  * After merging, the source draft is marked `abandoned` so it's no
96
96
  * longer active.
97
97
  */
98
- declare function mergeDrafts(opts: {
98
+ export declare function mergeDrafts(opts: {
99
99
  repo: DraftRepository;
100
100
  sourcePublicId: string;
101
101
  targetActorRef: string;
@@ -127,7 +127,7 @@ declare function mergeDrafts(opts: {
127
127
  * Unit prices can drift between caches — the pricing hash interlock at
128
128
  * checkout-freeze still catches drift, so reuse here is safe.
129
129
  */
130
- declare function runPricing(opts: {
130
+ export declare function runPricing(opts: {
131
131
  lines: readonly LineItem[];
132
132
  currency: CurrencyCode;
133
133
  kinds: KindRegistry;
@@ -181,7 +181,7 @@ type ResolvedTenant = ResolvedTenantConfig;
181
181
  * A `CartError` subclass so hosts catch cleanup failures with the same
182
182
  * `instanceof CartError` net as every other cart error.
183
183
  */
184
- declare class CleanupError extends CartError {
184
+ export declare class CleanupError extends CartError {
185
185
  readonly code: string;
186
186
  readonly category: CartErrorCategory;
187
187
  readonly retryable: boolean;
@@ -199,7 +199,7 @@ declare class CleanupError extends CartError {
199
199
  * module's docblock. `active` (live) and `converted` (became an order —
200
200
  * business history) are never included.
201
201
  */
202
- declare const DISPOSABLE_DRAFT_STATUSES: readonly DraftStatus[];
202
+ export declare const DISPOSABLE_DRAFT_STATUSES: readonly DraftStatus[];
203
203
  /**
204
204
  * The repository surface the step drives — a structural subset of a
205
205
  * `CartEngine` (`engine.repositories`), so a host can pass the engine's
@@ -214,6 +214,6 @@ interface CartCleanupSteps {
214
214
  /** §4.1 remove-abandoned-carts provider — destructive (hard-delete). */
215
215
  removeAbandonedCarts: CleanupStep;
216
216
  }
217
- declare function createCartCleanupSteps(source: CartCleanupSource): CartCleanupSteps;
217
+ export declare function createCartCleanupSteps(source: CartCleanupSource): CartCleanupSteps;
218
218
  //#endregion
219
- export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBlueprint, type CartBridges, type CartCleanupSource, type CartCleanupSteps, type CartConfigShape, type CartDomain, type CartDomainEvent, type CartDomainRuntime, 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 CartLogger, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartRuntime, type CartShape, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, CleanupError, type ClockPort, ConcurrencyError, type CreateCartRepositoriesConfig, CurrencyMismatchError, DEFAULT_STALE_OPEN_CHECKOUT_MS, DISPOSABLE_DRAFT_STATUSES, type DefineCartModelsConfig, 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, PENDING_EVENTS, 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 ResolvedCartConfig, 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, UnmanagedSessionError, type ValidityPolicy, type VariantPayload, addMoney, buildCheckoutSchema, buildDraftSchema, buildIdempotencySchema, buildReservationSchema, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCartCleanupSteps, createCartDomain, createCartEvent, createCartEventRegistry, createCartRepositories, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCart, defineCartEvent, defineCartModels, findAbandonedDrafts, flushPending, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
219
+ export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBlueprint, type CartBridges, type CartCleanupSource, type CartCleanupSteps, type CartConfigShape, type CartDomain, type CartDomainEvent, type CartDomainRuntime, 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 CartLogger, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartRuntime, type CartShape, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartRepositoriesConfig, CurrencyMismatchError, DEFAULT_STALE_OPEN_CHECKOUT_MS, type DefineCartModelsConfig, 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, PENDING_EVENTS, 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 ResolvedCartConfig, 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, UnmanagedSessionError, type ValidityPolicy, type VariantPayload, addMoney, buildCheckoutSchema, buildDraftSchema, buildIdempotencySchema, buildReservationSchema, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCartDomain, createCartEvent, createCartEventRegistry, createCartRepositories, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCart, defineCartEvent, defineCartModels, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, money, multiplyMoney, reservationConfigSchema, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
package/dist/index.mjs CHANGED
@@ -7,10 +7,10 @@ import { t as StateTransitionError } from "./state-transition.error-BssJiRoW.mjs
7
7
  import { n as CartEvents, t as createCartEvent } from "./domain-event-DBFsiHNJ.mjs";
8
8
  import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "./outbox-store-DLxCPOUN.mjs";
9
9
  import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-DYAnXbfV.mjs";
10
- import { _ as PENDING_EVENTS, a as ReservationRepository, c as runPricing, d as defineCartModels, f as buildReservationSchema, g as flushPending, h as buildCheckoutSchema, i as createCartRepositories, l as CheckoutRepository, m as buildDraftSchema, n as defineCart, o as IdempotencyRepository, p as buildIdempotencySchema, r as InProcessCartEventBus, s as DraftRepository, t as createCartDomain, u as DEFAULT_STALE_OPEN_CHECKOUT_MS } from "./define-cart-CYkjJdC7.mjs";
10
+ import { _ as PENDING_EVENTS, a as ReservationRepository, c as runPricing, d as defineCartModels, f as buildReservationSchema, g as flushPending, h as buildCheckoutSchema, i as createCartRepositories, l as CheckoutRepository, m as buildDraftSchema, n as defineCart, o as IdempotencyRepository, p as buildIdempotencySchema, r as InProcessCartEventBus, s as DraftRepository, t as createCartDomain, u as DEFAULT_STALE_OPEN_CHECKOUT_MS } from "./define-cart-CxIG6Omt.mjs";
11
11
  import { t as createKindRegistry } from "./kind-registry-DQYqRQZU.mjs";
12
12
  import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-wunwhjap.mjs";
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-CquIUes6.mjs";
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-_LIXlTwp.mjs";
14
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
@@ -1,7 +1,7 @@
1
- import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-Br7MHuOz.mjs";
2
- import { C as OperationContext, c as TaxBridge, d as InventoryBridge, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-DrSBrsit.mjs";
3
- import { l as LineDisplay, r as LineKind } from "./line-kind-kYeQzpCy.mjs";
4
- import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-BkYl0cjc.mjs";
1
+ import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-Cq7K0Lo6.mjs";
2
+ import { C as OperationContext, c as TaxBridge, d as InventoryBridge, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-BFg5X92u.mjs";
3
+ import { l as LineDisplay, r as LineKind } from "./line-kind-CY7cabbf.mjs";
4
+ import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-Cb50lwpo.mjs";
5
5
  import { t as IdPort } from "./id.port-DzgWy8sy.mjs";
6
6
  import { CartConfigShape } from "./engine/cart-config.schema.mjs";
7
7
  import { Money } from "@classytic/primitives/money";
@@ -79,7 +79,8 @@ interface DraftDocument extends Document {
79
79
  currency: CurrencyCode;
80
80
  pricing: Record<string, unknown> | null;
81
81
  version: number;
82
- expiresAt?: Date | null;
82
+ /** Retention deadline, stamped by every repository write; the TTL index deletes past it. */
83
+ expiresAt: Date;
83
84
  lastIdempotencyKey?: string;
84
85
  metadata?: Record<string, unknown>;
85
86
  privateMetadata?: Record<string, unknown>;
@@ -231,6 +232,8 @@ interface DraftRepositoryDeps {
231
232
  clock: ClockPort;
232
233
  id: IdPort;
233
234
  defaultCurrency: CurrencyCode;
235
+ /** Every draft write stamps `expiresAt = now + this` (seconds). */
236
+ draftRetentionSeconds: number;
234
237
  eventPublisher: CartEventPublisher;
235
238
  }
236
239
  /**
@@ -261,6 +264,7 @@ declare class DraftRepository extends Repository<DraftDocument> {
261
264
  private readonly clock;
262
265
  private readonly id;
263
266
  private readonly defaultCurrency;
267
+ private readonly draftRetentionMs;
264
268
  private readonly eventPublisher;
265
269
  constructor(model: Model<DraftDocument>, plugins: PluginType[], deps: DraftRepositoryDeps);
266
270
  findActiveByActor(actorRef: string, ctx: OperationContext): Promise<DraftDocument | null>;
@@ -321,6 +325,20 @@ declare class DraftRepository extends Repository<DraftDocument> {
321
325
  markAbandoned(draftId: Types.ObjectId | string, ctx: OperationContext, opts?: {
322
326
  expectedVersion?: number;
323
327
  }): Promise<DraftDocument | null>;
328
+ /**
329
+ * Mark this ACTOR's active draft converted, if they have one.
330
+ *
331
+ * For hosts that place an order without freezing a checkout first — there is
332
+ * then no `checkout.draftId` for `markConverted` to key on, and the draft
333
+ * stays `active` with its lines intact. The abandonment sweep selects exactly
334
+ * that shape (`status: 'active'` + `lines.0` exists), so a purchased cart
335
+ * becomes an abandoned-cart email.
336
+ *
337
+ * Returns whether anything was converted, so a caller can log the miss rather
338
+ * than assume. Best-effort like `markConverted`: the order is already placed
339
+ * and nothing here may fail it.
340
+ */
341
+ markActiveConvertedForActor(actorRef: string, ctx: OperationContext): Promise<boolean>;
324
342
  /**
325
343
  * Mark a draft as converted (called from CheckoutRepository.commit).
326
344
  * Best-effort: a missed update is reconciled by the next getOrCreate.
@@ -344,6 +362,8 @@ declare class DraftRepository extends Repository<DraftDocument> {
344
362
  expectedVersion?: number;
345
363
  }, ctx: OperationContext): Promise<DraftDocument>;
346
364
  mergeLines(existing: readonly LineItem[], incoming: readonly LineItem[]): LineItem[];
365
+ /** The retention deadline every write stamps — the TTL index deletes past it. */
366
+ private nextExpiry;
347
367
  private readOptions;
348
368
  private writeOptions;
349
369
  private price;
@@ -581,6 +601,8 @@ interface CreateCartRepositoriesConfig {
581
601
  id: IdPort;
582
602
  /** Validated + branded once at the config edge in `defineCart`. */
583
603
  defaultCurrency: CurrencyCode;
604
+ /** Seconds after a draft's last write before its TTL removes it. */
605
+ draftRetentionSeconds: number;
584
606
  events: EventTransport;
585
607
  tenant: ResolvedTenantConfig;
586
608
  outbox?: OutboxStore;
@@ -704,6 +726,8 @@ interface ResolvedCartConfig {
704
726
  forceRecreate: boolean;
705
727
  /** Validated + branded once at the config edge in `defineCart`. */
706
728
  defaultCurrency: CurrencyCode;
729
+ /** Seconds after a draft's last write before its TTL removes it. */
730
+ draftRetentionSeconds: number;
707
731
  collectionPrefix?: string;
708
732
  allowNonTransactional: boolean;
709
733
  staleOpenCheckoutMs?: number;
@@ -1,4 +1,4 @@
1
- import { l as LineDisplay, r as LineKind } from "./line-kind-kYeQzpCy.mjs";
1
+ import { l as LineDisplay, r as LineKind } from "./line-kind-CY7cabbf.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  //#region src/domain/entities/line-item.entity.d.ts
4
4
  /**
@@ -28,8 +28,14 @@ interface LineItem<TPayload = unknown> {
28
28
  * the draft service boundary.
29
29
  */
30
30
  payload: TPayload;
31
- /** Units. Always a positive integer. */
31
+ /** Quantity in the item's unit: a positive multiple of `quantityStep`. */
32
32
  quantity: number;
33
+ /**
34
+ * The increment the line sells in (`0.001` for rice by the kg), from the kind's
35
+ * `quantityStepOf` at add time. Absent = 1: whole units, the rule for every kind that
36
+ * declares no step.
37
+ */
38
+ quantityStep?: number;
33
39
  /**
34
40
  * Optional unit-price override — when the host wants to force a price
35
41
  * regardless of what the kind would compute. Used by admin tools and
@@ -109,7 +115,7 @@ interface IdempotencyReplay {
109
115
  * Using a literal rather than null keeps the composite index unique-safe
110
116
  * under MongoDB semantics (nulls are considered equal by the unique index).
111
117
  */
112
- declare const CART_REF_NEW: "new";
118
+ declare const CART_REF_NEW: 'new';
113
119
  /**
114
120
  * Convenience type — the pricing totals referenced from an idempotency record
115
121
  * for fast UI display on replay hits. Not part of the replay payload itself;
@@ -1,2 +1,2 @@
1
- import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "../variant.kind-BVmeGR6G.mjs";
1
+ import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "../variant.kind-DQxxcsib.mjs";
2
2
  export { type BundleComponent, type BundlePayload, type ServiceFeePayload, type SkuPayload, type TimeslotPayload, type VariantPayload, bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
@@ -1,2 +1 @@
1
- import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "../variant.kind-CquIUes6.mjs";
2
- export { bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
1
+ export { l as bundleKind, u as bundlePayloadSchema, s as serviceFeeKind, c as serviceFeePayloadSchema, a as skuKind, o as skuPayloadSchema, r as timeslotKind, i as timeslotPayloadSchema, t as variantKind, n as variantPayloadSchema } from "../variant.kind-_LIXlTwp.mjs";
@@ -1,4 +1,4 @@
1
- import { C as OperationContext, T as PricedLine, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-DrSBrsit.mjs";
1
+ import { C as OperationContext, T as PricedLine, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-BFg5X92u.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  import { z } from "zod";
4
4
  //#region src/domain/value-objects/line-display.vo.d.ts
@@ -178,6 +178,12 @@ interface LineKind<TPayload = unknown> {
178
178
  * previous behavior.
179
179
  */
180
180
  mergeKey?(line: LineLike<TPayload>): string | null;
181
+ /**
182
+ * Optional — the quantity increment this line sells in (`0.001` for rice by the kg). The draft
183
+ * repository checks every quantity against it and stores it on the line. Omitted, or
184
+ * `undefined`, means 1: whole units only.
185
+ */
186
+ quantityStepOf?(line: LineLike<TPayload>, ctx: KindContext): Promise<number | undefined>;
181
187
  }
182
188
  /**
183
189
  * The minimal shape the kind receives. Deliberately not the full LineItem
@@ -0,0 +1,25 @@
1
+ import { resolvePriceBasisTotal } from "@classytic/primitives/price-basis";
2
+ //#region src/domain/value-objects/line-total.ts
3
+ /**
4
+ * `unitPrice × quantity` in minor units — the one multiply both the fresh `kind.price()` path and
5
+ * the incremental reprice (`rebuildSubtotals`) use. A fractional quantity (2.35 kg) is extended
6
+ * exactly on the 6-dp grid and rounded once, half-even.
7
+ *
8
+ * Throws `RangeError` past `Number.MAX_SAFE_INTEGER` (on the FIRST add, not a later reprice), and
9
+ * primitives' `PriceBasisError` for a quantity off the grid.
10
+ */
11
+ /** A fractional `unitPrice × quantity`, exact on the 6-dp grid; a negative price keeps its sign. */
12
+ function extendMinor(unitPrice, quantity) {
13
+ const magnitude = resolvePriceBasisTotal(Math.abs(unitPrice), quantity);
14
+ return unitPrice < 0 && magnitude !== 0 ? -magnitude : magnitude;
15
+ }
16
+ function lineTotal(unitPrice, quantity) {
17
+ const amount = Number.isInteger(quantity) ? unitPrice.amount * quantity : extendMinor(unitPrice.amount, quantity);
18
+ if (!Number.isSafeInteger(amount)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${quantity} exceeds Number.MAX_SAFE_INTEGER`);
19
+ return {
20
+ amount,
21
+ currency: unitPrice.currency
22
+ };
23
+ }
24
+ //#endregion
25
+ export { lineTotal as t };
@@ -16,17 +16,17 @@ import { MemoryOutboxStore } from "@classytic/primitives/memory-outbox";
16
16
  * as a `CartEventDefinition` via `defineCartEvent()`.
17
17
  */
18
18
  declare const CartEvents: {
19
- readonly DRAFT_CREATED: "cart.draft.created";
20
- readonly DRAFT_ITEM_ADDED: "cart.draft.item_added";
21
- readonly DRAFT_ITEM_UPDATED: "cart.draft.item_updated";
22
- readonly DRAFT_ITEM_REMOVED: "cart.draft.item_removed";
23
- readonly DRAFT_PROMO_APPLIED: "cart.draft.promo_applied";
24
- readonly DRAFT_MERGED: "cart.draft.merged";
25
- readonly DRAFT_ABANDONED: "cart.draft.abandoned";
26
- readonly DRAFT_EXPIRED: "cart.draft.expired";
27
- readonly CHECKOUT_CREATED: "cart.checkout.created";
28
- readonly CHECKOUT_COMMITTED: "cart.checkout.committed";
29
- readonly CHECKOUT_CANCELED: "cart.checkout.canceled";
19
+ readonly DRAFT_CREATED: 'cart.draft.created';
20
+ readonly DRAFT_ITEM_ADDED: 'cart.draft.item_added';
21
+ readonly DRAFT_ITEM_UPDATED: 'cart.draft.item_updated';
22
+ readonly DRAFT_ITEM_REMOVED: 'cart.draft.item_removed';
23
+ readonly DRAFT_PROMO_APPLIED: 'cart.draft.promo_applied';
24
+ readonly DRAFT_MERGED: 'cart.draft.merged';
25
+ readonly DRAFT_ABANDONED: 'cart.draft.abandoned';
26
+ readonly DRAFT_EXPIRED: 'cart.draft.expired';
27
+ readonly CHECKOUT_CREATED: 'cart.checkout.created';
28
+ readonly CHECKOUT_COMMITTED: 'cart.checkout.committed';
29
+ readonly CHECKOUT_CANCELED: 'cart.checkout.canceled';
30
30
  };
31
31
  type CartEventName = (typeof CartEvents)[keyof typeof CartEvents];
32
32
  interface CartEventPayloadBase {
@@ -1,7 +1,7 @@
1
1
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-BoVPaSXX.mjs";
2
- import { E as PricingSnapshot, g as AdjustmentSpec } from "./clock.port-DrSBrsit.mjs";
3
- import { o as CheckoutFlowState } from "./state-transitions-B_ozUaqV.mjs";
4
- import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-BkYl0cjc.mjs";
2
+ import { E as PricingSnapshot, g as AdjustmentSpec } from "./clock.port-BFg5X92u.mjs";
3
+ import { o as CheckoutFlowState } from "./state-transitions-B3EPuOae.mjs";
4
+ import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-Cb50lwpo.mjs";
5
5
  import { Money } from "@classytic/primitives/money";
6
6
  //#region src/domain/entities/adjustment.entity.d.ts
7
7
  /**
@@ -124,8 +124,8 @@ interface Draft {
124
124
  pricing: PricingSnapshot | null;
125
125
  /** Optimistic-lock version. Incremented on every write. */
126
126
  version: number;
127
- /** Optional TTL — opt-in per plan Open Question #4. */
128
- expiresAt?: Date;
127
+ /** Retention deadline, restamped on every write; the TTL index deletes past it. */
128
+ expiresAt: Date;
129
129
  /** Idempotency key of the operation that last mutated this draft. */
130
130
  lastIdempotencyKey?: string;
131
131
  /** Public metadata bag for host extensibility. */
@@ -1,6 +1,6 @@
1
1
  import { t as CheckoutState } from "./cart-status.vo-BoVPaSXX.mjs";
2
- import { C as OperationContext, t as ClockPort } from "./clock.port-DrSBrsit.mjs";
3
- import { t as KindBridges } from "./line-kind-kYeQzpCy.mjs";
2
+ import { C as OperationContext, t as ClockPort } from "./clock.port-BFg5X92u.mjs";
3
+ import { t as KindBridges } from "./line-kind-CY7cabbf.mjs";
4
4
  import { t as IdPort } from "./id.port-DzgWy8sy.mjs";
5
5
  //#region src/domain/saga/saga-steps.d.ts
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { r as LineKind } from "./line-kind-kYeQzpCy.mjs";
1
+ import { r as LineKind } from "./line-kind-CY7cabbf.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  import { CurrencyCode } from "@classytic/primitives/currency";
4
4
  import { z } from "zod";
@@ -1,5 +1,5 @@
1
1
  import { t as KindError } from "./kind.error-BoyoVjKx.mjs";
2
- import { t as lineTotal } from "./line-total-6VJQMjGV.mjs";
2
+ import { t as lineTotal } from "./line-total-CHnkZ3nH.mjs";
3
3
  import { isCurrencyCode } from "@classytic/primitives/currency";
4
4
  import { z } from "zod";
5
5
  //#region src/kinds/bundle.kind.ts
@@ -198,7 +198,7 @@ const skuKind = {
198
198
  async validate(line, ctx) {
199
199
  const parsed = skuPayloadSchema.safeParse(line.payload);
200
200
  if (!parsed.success) throw new KindError(this.name, "invalid payload shape", { details: { issues: parsed.error.issues } });
201
- if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
201
+ if (!(line.quantity > 0)) throw new KindError(this.name, `quantity must be > 0, got ${line.quantity}`);
202
202
  if (line.overrideUnitPrice && line.overrideUnitPrice.currency !== line.currency) throw new KindError(this.name, `override unit price currency ${line.overrideUnitPrice.currency} does not match cart currency ${line.currency}`);
203
203
  const product = await ctx.bridges.catalog.resolve(parsed.data.skuRef, ctx);
204
204
  if (!product) throw new KindError(this.name, `unknown skuRef: ${parsed.data.skuRef}`);
@@ -236,6 +236,11 @@ const skuKind = {
236
236
  priced
237
237
  };
238
238
  },
239
+ /** The product's step (`0.001` kg for loose rice); the draft repository checks quantities against it. */
240
+ async quantityStepOf(line, ctx) {
241
+ const typed = line;
242
+ return (await ctx.bridges.catalog.resolve(typed.payload.skuRef, ctx))?.quantityStep;
243
+ },
239
244
  mergeKey(line) {
240
245
  const typed = line;
241
246
  if (!typed.payload?.skuRef) return null;
@@ -384,7 +389,7 @@ const variantKind = {
384
389
  async validate(line, ctx) {
385
390
  const parsed = variantPayloadSchema.safeParse(line.payload);
386
391
  if (!parsed.success) throw new KindError(this.name, "invalid variant payload", { details: { issues: parsed.error.issues } });
387
- if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
392
+ if (!(line.quantity > 0)) throw new KindError(this.name, `quantity must be > 0, got ${line.quantity}`);
388
393
  if (line.overrideUnitPrice && line.overrideUnitPrice.currency !== line.currency) throw new KindError(this.name, `override unit price currency ${line.overrideUnitPrice.currency} does not match cart currency ${line.currency}`);
389
394
  const product = await ctx.bridges.catalog.resolve(parsed.data.variantSku, ctx);
390
395
  if (!product) throw new KindError(this.name, `unknown variant SKU: ${parsed.data.variantSku}`);
@@ -422,6 +427,11 @@ const variantKind = {
422
427
  priced
423
428
  };
424
429
  },
430
+ /** The product's step (`0.001` kg for loose rice); the draft repository checks quantities against it. */
431
+ async quantityStepOf(line, ctx) {
432
+ const typed = line;
433
+ return (await ctx.bridges.catalog.resolve(typed.payload.variantSku, ctx))?.quantityStep;
434
+ },
425
435
  mergeKey(line) {
426
436
  const { productRef, variantSku } = line.payload ?? {};
427
437
  if (!productRef || !variantSku) return null;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@classytic/cart",
3
- "version": "1.1.1",
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.",
3
+ "version": "1.3.0",
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",
7
7
  "sideEffects": false,
@@ -13,38 +13,47 @@
13
13
  },
14
14
  "exports": {
15
15
  ".": {
16
+ "@classytic/source": "./src/index.ts",
16
17
  "types": "./dist/index.d.mts",
17
18
  "default": "./dist/index.mjs"
18
19
  },
19
20
  "./domain": {
21
+ "@classytic/source": "./src/domain/index.ts",
20
22
  "types": "./dist/domain/index.d.mts",
21
23
  "default": "./dist/domain/index.mjs"
22
24
  },
23
25
  "./kinds": {
26
+ "@classytic/source": "./src/kinds/index.ts",
24
27
  "types": "./dist/kinds/index.d.mts",
25
28
  "default": "./dist/kinds/index.mjs"
26
29
  },
27
30
  "./ports": {
31
+ "@classytic/source": "./src/domain/ports/index.ts",
28
32
  "types": "./dist/domain/ports/index.d.mts",
29
33
  "default": "./dist/domain/ports/index.mjs"
30
34
  },
31
35
  "./errors": {
36
+ "@classytic/source": "./src/domain/errors/index.ts",
32
37
  "types": "./dist/domain/errors/index.d.mts",
33
38
  "default": "./dist/domain/errors/index.mjs"
34
39
  },
35
40
  "./events": {
41
+ "@classytic/source": "./src/domain/events/index.ts",
36
42
  "types": "./dist/domain/events/index.d.mts",
37
43
  "default": "./dist/domain/events/index.mjs"
38
44
  },
39
45
  "./saga": {
46
+ "@classytic/source": "./src/domain/saga/index.ts",
40
47
  "types": "./dist/domain/saga/index.d.mts",
41
48
  "default": "./dist/domain/saga/index.mjs"
42
49
  },
43
50
  "./engine": {
51
+ "@classytic/source": "./src/engine/index.ts",
44
52
  "types": "./dist/engine/index.d.mts",
45
53
  "default": "./dist/engine/index.mjs"
46
54
  },
47
55
  "./schemas": {
56
+ "@classytic/source": "./src/engine/cart-config.schema.ts",
48
57
  "types": "./dist/engine/cart-config.schema.d.mts",
49
58
  "default": "./dist/engine/cart-config.schema.mjs"
50
59
  }
@@ -83,27 +92,27 @@
83
92
  "release": "npm run push -- main && npm run release:tag && npm publish"
84
93
  },
85
94
  "peerDependencies": {
86
- "@classytic/mongokit": ">=3.33.0",
87
- "@classytic/primitives": ">=0.23.0",
88
- "@classytic/repo-core": ">=0.24.0",
89
- "mongoose": ">=9.4.1",
95
+ "@classytic/mongokit": ">=3.41.0",
96
+ "@classytic/primitives": ">=0.32.0",
97
+ "@classytic/repo-core": ">=0.31.0",
98
+ "mongoose": ">=9.11.0",
90
99
  "zod": ">=4.0.0"
91
100
  },
92
101
  "devDependencies": {
93
- "@biomejs/biome": "^2.4.13",
94
- "@classytic/dev-tools": "^0.2.0",
95
- "@classytic/mongokit": "^3.33.0",
96
- "@classytic/primitives": ">=0.23.0",
97
- "@classytic/repo-core": ">=0.24.0",
98
- "@types/node": "^25.5.0",
99
- "knip": "^6.7.0",
100
- "mongodb-memory-server": "^10.2.3",
101
- "mongoose": "^9.4.1",
102
- "publint": "^0.3.23",
103
- "tsdown": "^0.22.14",
104
- "typescript": "^5.7.0",
105
- "vitest": "^3.0.0",
106
- "zod": "^4.3.6"
102
+ "@biomejs/biome": "^2.5.15",
103
+ "@classytic/dev-tools": "^0.2.1",
104
+ "@classytic/mongokit": "^3.42.0",
105
+ "@classytic/primitives": "^0.33.0",
106
+ "@classytic/repo-core": "^0.31.1",
107
+ "@types/node": "^26.6.5",
108
+ "knip": "^6.41.0",
109
+ "mongodb-memory-server": "^11.3.0",
110
+ "mongoose": "^9.11.2",
111
+ "publint": "^0.3.25",
112
+ "tsdown": "^0.23.1",
113
+ "typescript": "^7.0.2",
114
+ "vitest": "^5.0.4",
115
+ "zod": "^4.6.7"
107
116
  },
108
117
  "keywords": [
109
118
  "cart",
@@ -1,24 +0,0 @@
1
- //#region src/domain/value-objects/line-total.ts
2
- /**
3
- * Multiply a unit price by a line quantity, guarding the safe-integer range.
4
- *
5
- * Minor-unit money must stay within `Number.MAX_SAFE_INTEGER` — past 2^53 the
6
- * multiplication silently loses precision, which is worse than failing loud.
7
- * Both the fresh `kind.price()` path and the incremental reprice path
8
- * (`rebuildSubtotals`) route their `unitPrice × quantity` through here, so a
9
- * huge quantity throws on the FIRST add, not only when a later reprice happens
10
- * to re-multiply it.
11
- *
12
- * Throws `RangeError` (same shape/message as the pre-existing reprice guard)
13
- * so both paths fail identically.
14
- */
15
- function lineTotal(unitPrice, quantity) {
16
- const amount = unitPrice.amount * quantity;
17
- if (!Number.isSafeInteger(amount)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${quantity} exceeds Number.MAX_SAFE_INTEGER`);
18
- return {
19
- amount,
20
- currency: unitPrice.currency
21
- };
22
- }
23
- //#endregion
24
- export { lineTotal as t };