@classytic/cart 0.1.2 → 0.1.3

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 (28) hide show
  1. package/dist/{shipping.bridge-CmQFTgSE.d.mts → clock.port-BUe6Dk_M.d.mts} +27 -10
  2. package/dist/{create-cart-B4l61iKT.mjs → create-cart-4wql1XGi.mjs} +27 -9
  3. package/dist/domain/errors/index.d.mts +1 -1
  4. package/dist/domain/errors/index.mjs +2 -2
  5. package/dist/domain/index.d.mts +7 -7
  6. package/dist/domain/index.mjs +3 -3
  7. package/dist/domain/ports/index.d.mts +2 -2
  8. package/dist/domain/saga/index.d.mts +1 -1
  9. package/dist/domain/saga/index.mjs +1 -1
  10. package/dist/engine/index.d.mts +1 -1
  11. package/dist/engine/index.mjs +1 -1
  12. package/dist/{errors-DzR7Pipp.mjs → errors-7Pd0yATM.mjs} +1 -26
  13. package/dist/{id.port-C7ygWLRU.d.mts → id.port-DitjeoHg.d.mts} +1 -19
  14. package/dist/{index-BFBUk6qT.d.mts → index-qfN8dZN9.d.mts} +6 -5
  15. package/dist/index.d.mts +11 -11
  16. package/dist/index.mjs +7 -7
  17. package/dist/{internal-event-bus-DKcDteh-.d.mts → internal-event-bus-DhSLiZHi.d.mts} +4 -4
  18. package/dist/{kind-registry-C1n47C7h.d.mts → kind-registry-D03c2VV5.d.mts} +1 -1
  19. package/dist/kinds/index.d.mts +2 -2
  20. package/dist/kinds/index.mjs +2 -2
  21. package/dist/{line-kind-Ck3fVXzG.d.mts → line-kind-CKOWafK0.d.mts} +11 -6
  22. package/dist/{reservation.entity-b5cZ1ojx.d.mts → reservation.entity-WdaZCJg9.d.mts} +3 -3
  23. package/dist/{price-changed.error-C-wGVcfc.mjs → stale-quote.error-BkFLXWo5.mjs} +30 -4
  24. package/dist/{state-transitions-e4z3Yhxb.mjs → state-transitions-Bm3lC2Uv.mjs} +2 -2
  25. package/dist/{state-transitions-X_Eix5Iw.d.mts → state-transitions-D8CRykBv.d.mts} +7 -7
  26. package/dist/{variant.kind-9P1DXdXu.d.mts → variant.kind-Cpo_Hh7G.d.mts} +65 -2
  27. package/dist/{variant.kind-DfEh2oku.mjs → variant.kind-z2gwH9Vo.mjs} +92 -10
  28. package/package.json +8 -6
@@ -41,10 +41,9 @@ interface PricedLine {
41
41
  /** Accumulated tax applied to this line by the tax step. */
42
42
  taxTotal: Money;
43
43
  /**
44
- * Validity window for this priced line. The saga's step 2
45
- * (revalidation) compares this against the clock and triggers
46
- * LineKind.revalidate() on expiry according to the kind's StaleBehavior.
47
- * `null` means no expiry (e.g., hard-priced SKUs).
44
+ * Validity window for this priced line. Checkout compares this against
45
+ * the engine clock and rejects expired snapshots without extra bridge
46
+ * reads. `null` means no expiry (e.g., hard-priced SKUs).
48
47
  */
49
48
  validUntil: Date | null;
50
49
  /**
@@ -58,10 +57,10 @@ interface PricedLine {
58
57
  /**
59
58
  * Whole-cart pricing snapshot — the output of running the full pipeline.
60
59
  *
61
- * Written to the draft on every mutation and frozen onto the checkout on saga
62
- * step 4. Drives idempotent revalidation: saga step 3 compares
63
- * `snapshot.pricingHash` against the client-supplied expectedPricingHash and
64
- * aborts with PriceChangedError if they differ.
60
+ * Written to the draft on every mutation and frozen onto the checkout. Drives
61
+ * cheap checkout freshness: first reject expired `pricingValidUntil`, then
62
+ * compare `snapshot.pricingHash` against the client-supplied
63
+ * expectedPricingHash and abort with PriceChangedError if they differ.
65
64
  */
66
65
  interface PricingSnapshot {
67
66
  /** Per-line priced rows, one entry per LineItem in draft order. */
@@ -92,7 +91,7 @@ interface PricingSnapshot {
92
91
  pricingValidUntil: Date | null;
93
92
  /**
94
93
  * Content hash of the priced snapshot. Computed from the sorted line array,
95
- * adjustments, and totals. Used by the finalize saga step 3 to detect
94
+ * adjustments, and totals. Used by checkout's hash check to detect
96
95
  * "price changed since the client confirmed" and abort with
97
96
  * PriceChangedError so the client can re-display and re-confirm.
98
97
  */
@@ -535,4 +534,22 @@ interface ShippingMethod {
535
534
  };
536
535
  }
537
536
  //#endregion
538
- export { PricingSnapshot as C, PricedLine as S, PromotionsBridge as _, TaxBreakdown as a, BridgeStatus as b, TaxCalculationResult as c, ReservationRequest as d, CatalogBridge as f, PromotionResult as g, CartSnapshot as h, ShippingQuoteRequest as i, InventoryBridge as l, AdjustmentSpec as m, ShippingMethod as n, TaxBridge as o, ProductSummary as p, ShippingQuote as r, TaxCalculationRequest as s, ShippingBridge as t, ReservationRef as u, Address as v, OperationContext$1 as x, BridgeRef as y };
537
+ //#region src/domain/ports/clock.port.d.ts
538
+ /**
539
+ * Clock port — the one source of "now" in the cart engine.
540
+ *
541
+ * Injected through config so tests can install a fake clock and fast-forward
542
+ * through TTLs, validity windows, and saga lease expirations. Production
543
+ * hosts pass nothing and get a default `systemClock` that calls `new Date()`.
544
+ *
545
+ * Never read `Date.now()` or `new Date()` directly in cart code. Always use
546
+ * `engine.clock.now()`. Integration tests assert this via ESLint rule.
547
+ */
548
+ interface ClockPort {
549
+ /** Wall clock — used for timestamps, TTL expiry, idempotency leases. */
550
+ now(): Date;
551
+ }
552
+ /** Default system clock — passes straight through to `new Date()`. */
553
+ declare const systemClock: ClockPort;
554
+ //#endregion
555
+ export { OperationContext$1 as C, BridgeStatus as S, PricingSnapshot as T, CartSnapshot as _, ShippingQuote as a, Address as b, TaxBridge as c, InventoryBridge as d, ReservationRef as f, AdjustmentSpec as g, ProductSummary as h, ShippingMethod as i, TaxCalculationRequest as l, CatalogBridge as m, systemClock as n, ShippingQuoteRequest as o, ReservationRequest as p, ShippingBridge as r, TaxBreakdown as s, ClockPort as t, TaxCalculationResult as u, PromotionResult as v, PricedLine as w, BridgeRef as x, PromotionsBridge as y };
@@ -1,13 +1,13 @@
1
- import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "./price-changed.error-C-wGVcfc.mjs";
1
+ import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "./stale-quote.error-BkFLXWo5.mjs";
2
2
  import { t as KindError } from "./kind.error-DIaJpdUb.mjs";
3
3
  import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
4
4
  import { n as cryptoIdPort, r as systemClock } from "./id.port-BhbFZJPm.mjs";
5
5
  import { t as createKindRegistry } from "./kind-registry-C99h_-8t.mjs";
6
- import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-e4z3Yhxb.mjs";
6
+ import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-Bm3lC2Uv.mjs";
7
7
  import { money } from "@classytic/primitives/money";
8
8
  import { matchEventPattern } from "@classytic/primitives/events";
9
9
  import mongoose, { Schema } from "mongoose";
10
- import { resolveTenantConfig } from "@classytic/primitives/tenant";
10
+ import { resolveTenantConfig } from "@classytic/repo-core/tenant";
11
11
  import { Repository, customIdPlugin, isDuplicateKeyError, multiTenantPlugin, prefixedId } from "@classytic/mongokit";
12
12
  //#region src/models/checkout.model.ts
13
13
  function createCheckoutModel(connection, opts = {}) {
@@ -365,7 +365,7 @@ function createIdempotencyModel(connection, opts = {}) {
365
365
  //#region src/models/inject-tenant.ts
366
366
  /**
367
367
  * Mongoose-specific adapter around `resolveTenantConfig()` from
368
- * `@classytic/primitives/tenant`. The pure resolution lives in primitives
368
+ * `@classytic/repo-core/tenant`. The pure resolution lives in primitives
369
369
  * (zero runtime deps) — this file only handles the Mongoose schema
370
370
  * mutations (add field, prepend tenant to indexes) that primitives can't
371
371
  * own without a mongoose dependency.
@@ -610,7 +610,9 @@ var CheckoutRepository = class extends Repository {
610
610
  if (draft.status !== "active") throw new Error(`Cannot create checkout from draft in status '${draft.status}'`);
611
611
  if (draft.lines.length === 0) throw new Error("Cannot create checkout from an empty draft");
612
612
  if (!draft.pricing) throw new Error("Cannot create checkout from a draft with no priced snapshot — call addItem first");
613
- const draftPricingHash = draft.pricing.pricingHash;
613
+ const pricingSnapshot = draft.pricing;
614
+ assertSnapshotNotExpired(pricingSnapshot, draft.lines, () => this.clock.now());
615
+ const draftPricingHash = pricingSnapshot.pricingHash;
614
616
  if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", { draftPublicId: input.draftPublicId });
615
617
  const existing = await this.findOpenByDraft(draft._id, ctx);
616
618
  if (existing) return existing;
@@ -801,6 +803,19 @@ var CheckoutRepository = class extends Repository {
801
803
  return checkout;
802
804
  }
803
805
  };
806
+ function assertSnapshotNotExpired(pricing, draftLines, now) {
807
+ if (!pricing.pricingValidUntil) return;
808
+ const expiresAt = new Date(pricing.pricingValidUntil);
809
+ const currentTime = now();
810
+ if (Number.isNaN(expiresAt.getTime()) || expiresAt > currentTime) return;
811
+ const expired = pricing.lines?.find((pricedLine) => {
812
+ if (!pricedLine.validUntil) return false;
813
+ const validUntil = new Date(pricedLine.validUntil);
814
+ return !Number.isNaN(validUntil.getTime()) && validUntil <= currentTime;
815
+ });
816
+ const line = draftLines.find((item) => item.lineId === expired?.lineId);
817
+ throw new StaleQuoteError(expired?.lineId ?? "<cart>", typeof line?.kind === "string" ? line.kind : "<unknown>", "pricing snapshot expired; refresh the draft before checkout", { pricingValidUntil: expiresAt.toISOString() });
818
+ }
804
819
  function isNotFound$2(err) {
805
820
  return typeof err === "object" && err !== null && err.status === 404;
806
821
  }
@@ -831,8 +846,10 @@ function isNotFound$2(err) {
831
846
  * checkout-freeze still catches drift, so reuse here is safe.
832
847
  */
833
848
  async function runPricing(opts) {
849
+ const computedAt = opts.clock.now();
834
850
  const kindCtx = {
835
851
  ...opts.ctx,
852
+ clock: opts.clock,
836
853
  bridges: {
837
854
  catalog: opts.bridges.catalog,
838
855
  inventory: opts.bridges.inventory,
@@ -872,7 +889,7 @@ async function runPricing(opts) {
872
889
  for (const result of promoResults.sort((a, b) => b.priority - a.priority)) {
873
890
  const appliedAmount = computeAdjustmentAmount(result, pricedLines, opts.currency);
874
891
  adjustments.push({
875
- adjustmentId: `adj_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
892
+ adjustmentId: `adj_${computedAt.getTime()}_${adjustments.length + 1}`,
876
893
  source: "promotion",
877
894
  ruleRef: result.ruleRef,
878
895
  spec: result.adjustment,
@@ -880,7 +897,7 @@ async function runPricing(opts) {
880
897
  appliedAmount,
881
898
  explanation: result.explanation,
882
899
  priority: result.priority,
883
- appliedAt: opts.clock.now()
900
+ appliedAt: computedAt
884
901
  });
885
902
  if (result.targetLineId) {
886
903
  const target = pricedLines.find((l) => l.lineId === result.targetLineId);
@@ -960,7 +977,7 @@ async function runPricing(opts) {
960
977
  },
961
978
  pricingValidUntil,
962
979
  pricingHash: buildPricingHash(pricedLines),
963
- computedAt: opts.clock.now()
980
+ computedAt
964
981
  },
965
982
  adjustments
966
983
  };
@@ -1359,6 +1376,7 @@ var DraftRepository = class extends Repository {
1359
1376
  kindContextFor(ctx) {
1360
1377
  return {
1361
1378
  ...ctx,
1379
+ clock: this.clock,
1362
1380
  bridges: {
1363
1381
  catalog: this.bridges.catalog,
1364
1382
  inventory: this.bridges.inventory,
@@ -1566,7 +1584,7 @@ var ReservationRepository = class extends Repository {
1566
1584
  page: 1,
1567
1585
  limit,
1568
1586
  countStrategy: "none"
1569
- }, this.readOptions(ctx))).docs;
1587
+ }, this.readOptions(ctx))).data;
1570
1588
  }
1571
1589
  /** Atomic transition `held → released` via version check. */
1572
1590
  async markReleased(reservationId, expectedVersion, reason, ctx) {
@@ -1,2 +1,2 @@
1
- import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "../../index-BFBUk6qT.mjs";
1
+ import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "../../index-qfN8dZN9.mjs";
2
2
  export { CartError, CartErrorCategory, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, SagaFailurePhase, StaleQuoteError, StateTransitionError, UnknownKindError };
@@ -1,6 +1,6 @@
1
1
  import { t as CartError } from "../../cart.error-BwWy4RlY.mjs";
2
- import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "../../price-changed.error-C-wGVcfc.mjs";
2
+ import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "../../stale-quote.error-BkFLXWo5.mjs";
3
3
  import { n as UnknownKindError, t as KindError } from "../../kind.error-DIaJpdUb.mjs";
4
- import { a as ReservationError, i as SagaError, n as IdempotencyBusyError, r as IdempotencyStorageError, t as StaleQuoteError } from "../../errors-DzR7Pipp.mjs";
4
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../../errors-7Pd0yATM.mjs";
5
5
  import { t as StateTransitionError } from "../../state-transition.error-2fRLh3p0.mjs";
6
6
  export { CartError, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError };
@@ -1,12 +1,12 @@
1
- import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "../index-BFBUk6qT.mjs";
1
+ import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "../index-qfN8dZN9.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "../cart-status.vo-CNJw4aaB.mjs";
3
3
  import { S as CartEvents, _ as CartEventMeta, a as OutboxErrorInfo, b as CartEventName, c as OutboxFailureDecision, d as OutboxStore, f as OutboxStoreWriteOptions, g as CartEventAggregate, h as CartDomainEvent, i as OutboxClaimOptions, l as OutboxFailurePolicy, m as CartAggregateType, n as MemoryOutboxStore, o as OutboxFailOptions, p as OutboxWriteOptions, r as OutboxAcknowledgeOptions, s as OutboxFailureContext, t as InvalidOutboxEventError, u as OutboxOwnershipError, v as createCartEvent, x as CartEventPayload, y as CartEventMap } from "../outbox-store-CBt9fSYh.mjs";
4
4
  import { a as CartEventRegistry, c as defineCartEvent, d as EventValidationResult, f as EventValidator, i as CartEventDefinitionInput, l as EventSchema, n as cartEventsByName, o as PayloadOf, r as CartEventDefinition, s as createCartEventRegistry, t as cartEventDefinitions, u as EventSchemaProperty } from "../cart-event-catalog-BxDJhtTM.mjs";
5
- import { C as PricingSnapshot, S as PricedLine, _ as PromotionsBridge, a as TaxBreakdown, b as BridgeStatus, c as TaxCalculationResult, d as ReservationRequest, f as CatalogBridge, g as PromotionResult, h as CartSnapshot, i as ShippingQuoteRequest, l as InventoryBridge, m as AdjustmentSpec, n as ShippingMethod, o as TaxBridge, p as ProductSummary, r as ShippingQuote, s as TaxCalculationRequest, t as ShippingBridge, u as ReservationRef, x as OperationContext, y as BridgeRef } from "../shipping.bridge-CmQFTgSE.mjs";
6
- import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-b5cZ1ojx.mjs";
7
- import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../state-transitions-X_Eix5Iw.mjs";
8
- import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "../line-kind-Ck3fVXzG.mjs";
9
- import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "../kind-registry-C1n47C7h.mjs";
10
- import { a as systemClock, i as ClockPort, n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../id.port-C7ygWLRU.mjs";
5
+ import { C as OperationContext, S as BridgeStatus, T as PricingSnapshot, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, w as PricedLine, x as BridgeRef, y as PromotionsBridge } from "../clock.port-BUe6Dk_M.mjs";
6
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-WdaZCJg9.mjs";
7
+ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep, t as CHECKOUT_MACHINE } from "../state-transitions-D8CRykBv.mjs";
8
+ import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "../line-kind-CKOWafK0.mjs";
9
+ import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "../kind-registry-D03c2VV5.mjs";
10
+ import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../id.port-DitjeoHg.mjs";
11
11
  import { Money, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
12
12
  export { type Adjustment, AdjustmentSpec, BridgeRef, BridgeStatus, CART_REF_NEW, CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CartAggregateType, CartDomainEvent, CartError, CartErrorCategory, CartEventAggregate, CartEventDefinition, CartEventDefinitionInput, CartEventMap, CartEventMeta, CartEventName, CartEventPayload, CartEventRegistry, CartEvents, CartSnapshot, CatalogBridge, type Checkout, CheckoutFlowState, type CheckoutState, CheckoutStep, CheckoutStepNumber, ClockPort, ConcurrencyError, type Draft, type DraftStatus, EventSchema, EventSchemaProperty, EventValidationResult, EventValidator, IdPort, IdempotencyBusyError, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyStorageError, InvalidOutboxEventError, InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, OperationContext, type OperationName, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxErrorInfo, OutboxFailOptions, OutboxFailureContext, OutboxFailureDecision, OutboxFailurePolicy, OutboxOwnershipError, OutboxStore, OutboxStoreWriteOptions, OutboxWriteOptions, PayloadOf, PriceChangedError, type PricedLine, type PricingSnapshot, ProductSummary, PromotionResult, PromotionsBridge, type Reservation, ReservationError, ReservationRef, ReservationRequest, type ReservationStatus, type RevalidationResult, SagaDependencies, SagaError, SagaFailurePhase, SagaStepFn, ShippingBridge, ShippingMethod, ShippingQuote, ShippingQuoteRequest, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, TaxBreakdown, TaxBridge, TaxCalculationRequest, TaxCalculationResult, type TotalsSnapshot, UnknownKindError, type ValidityPolicy, addMoney, cartEventDefinitions, cartEventsByName, createCartEvent, createCartEventRegistry, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCartEvent, fromMajor, isLegalCheckoutTransition, money, multiplyMoney, subtractMoney, sumMoney, systemClock, toMajor };
@@ -1,14 +1,14 @@
1
1
  import { t as CART_REF_NEW } from "../idempotency-key.vo-D0lJsvGn.mjs";
2
2
  import { t as CartError } from "../cart.error-BwWy4RlY.mjs";
3
- import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "../price-changed.error-C-wGVcfc.mjs";
3
+ import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "../stale-quote.error-BkFLXWo5.mjs";
4
4
  import { n as UnknownKindError, t as KindError } from "../kind.error-DIaJpdUb.mjs";
5
- import { a as ReservationError, i as SagaError, n as IdempotencyBusyError, r as IdempotencyStorageError, t as StaleQuoteError } from "../errors-DzR7Pipp.mjs";
5
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../errors-7Pd0yATM.mjs";
6
6
  import { t as StateTransitionError } from "../state-transition.error-2fRLh3p0.mjs";
7
7
  import { n as CartEvents, t as createCartEvent } from "../domain-event-CIEORKF6.mjs";
8
8
  import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "../outbox-store-CWW8ppxS.mjs";
9
9
  import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "../id.port-BhbFZJPm.mjs";
10
10
  import { t as createKindRegistry } from "../kind-registry-C99h_-8t.mjs";
11
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../state-transitions-e4z3Yhxb.mjs";
11
+ import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../state-transitions-Bm3lC2Uv.mjs";
12
12
  import "./events/index.mjs";
13
13
  import "./ports/index.mjs";
14
14
  import "./saga/index.mjs";
@@ -1,3 +1,3 @@
1
- import { _ as PromotionsBridge, a as TaxBreakdown, b as BridgeStatus, c as TaxCalculationResult, d as ReservationRequest, f as CatalogBridge, g as PromotionResult, h as CartSnapshot, i as ShippingQuoteRequest, l as InventoryBridge, m as AdjustmentSpec, n as ShippingMethod, o as TaxBridge, p as ProductSummary, r as ShippingQuote, s as TaxCalculationRequest, t as ShippingBridge, u as ReservationRef, x as OperationContext, y as BridgeRef } from "../../shipping.bridge-CmQFTgSE.mjs";
2
- import { a as systemClock, i as ClockPort, n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../../id.port-C7ygWLRU.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-BUe6Dk_M.mjs";
2
+ import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "../../id.port-DitjeoHg.mjs";
3
3
  export { AdjustmentSpec, BridgeRef, BridgeStatus, CartSnapshot, CatalogBridge, ClockPort, IdPort, InventoryBridge, OperationContext, ProductSummary, PromotionResult, PromotionsBridge, ReservationRef, ReservationRequest, ShippingBridge, ShippingMethod, ShippingQuote, ShippingQuoteRequest, TaxBreakdown, TaxBridge, TaxCalculationRequest, TaxCalculationResult, createCounterIdPort, cryptoIdPort, systemClock };
@@ -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-X_Eix5Iw.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-D8CRykBv.mjs";
2
2
  export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, type CheckoutFlowState, CheckoutStep, type CheckoutStepNumber, type SagaDependencies, type SagaStepFn, isLegalCheckoutTransition };
@@ -1,2 +1,2 @@
1
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../../state-transitions-e4z3Yhxb.mjs";
1
+ import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../../state-transitions-Bm3lC2Uv.mjs";
2
2
  export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CheckoutStep, isLegalCheckoutTransition };
@@ -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-DKcDteh-.mjs";
2
+ import { a as CartEngine, i as CartConfig, n as createCart, r as CartBridges, t as InProcessCartEventBus } from "../internal-event-bus-DhSLiZHi.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-B4l61iKT.mjs";
1
+ import { n as InProcessCartEventBus, t as createCart } from "../create-cart-4wql1XGi.mjs";
2
2
  import { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
3
3
  export { InProcessCartEventBus, cartConfigSchema, createCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
@@ -69,29 +69,4 @@ var IdempotencyStorageError = class extends CartError {
69
69
  }
70
70
  };
71
71
  //#endregion
72
- //#region src/domain/errors/stale-quote.error.ts
73
- /**
74
- * A priced line's validity window has elapsed and its LineKind's revalidate()
75
- * returned `invalid`. Fired from the saga's step 2 (revalidation).
76
- *
77
- * Example: a bid line whose underlying auction moved to a new highest bid
78
- * while the user was reviewing the cart.
79
- *
80
- * Clients should re-read the cart, show the updated state, and confirm again.
81
- * Retryable with a new idempotency key.
82
- */
83
- var StaleQuoteError = class extends CartError {
84
- code = "cart/stale_quote";
85
- category = "validation";
86
- retryable = true;
87
- constructor(lineId, kind, reason, details) {
88
- super(`Line ${lineId} (${kind}) is no longer valid: ${reason}`, {
89
- lineId,
90
- kind,
91
- reason,
92
- ...details
93
- });
94
- }
95
- };
96
- //#endregion
97
- export { ReservationError as a, SagaError as i, IdempotencyBusyError as n, IdempotencyStorageError as r, StaleQuoteError as t };
72
+ export { ReservationError as i, IdempotencyStorageError as n, SagaError as r, IdempotencyBusyError as t };
@@ -1,21 +1,3 @@
1
- //#region src/domain/ports/clock.port.d.ts
2
- /**
3
- * Clock port — the one source of "now" in the cart engine.
4
- *
5
- * Injected through config so tests can install a fake clock and fast-forward
6
- * through TTLs, validity windows, and saga lease expirations. Production
7
- * hosts pass nothing and get a default `systemClock` that calls `new Date()`.
8
- *
9
- * Never read `Date.now()` or `new Date()` directly in cart code. Always use
10
- * `engine.clock.now()`. Integration tests assert this via ESLint rule.
11
- */
12
- interface ClockPort {
13
- /** Wall clock — used for timestamps, TTL expiry, idempotency leases. */
14
- now(): Date;
15
- }
16
- /** Default system clock — passes straight through to `new Date()`. */
17
- declare const systemClock: ClockPort;
18
- //#endregion
19
1
  //#region src/domain/ports/id.port.d.ts
20
2
  /**
21
3
  * IdPort — a swappable source of unique identifiers.
@@ -61,4 +43,4 @@ declare const cryptoIdPort: IdPort;
61
43
  */
62
44
  declare function createCounterIdPort(prefix?: string): IdPort;
63
45
  //#endregion
64
- export { systemClock as a, ClockPort as i, createCounterIdPort as n, cryptoIdPort as r, IdPort as t };
46
+ export { createCounterIdPort as n, cryptoIdPort as r, IdPort as t };
@@ -103,11 +103,12 @@ declare class NotFoundError extends CartError {
103
103
  //#endregion
104
104
  //#region src/domain/errors/price-changed.error.d.ts
105
105
  /**
106
- * The re-run pricing snapshot's hash does not match the `expectedPricingHash`
107
- * the client supplied when initiating finalize. Fired from saga step 3.
106
+ * The stored pricing snapshot's hash does not match the `expectedPricingHash`
107
+ * the client supplied when initiating checkout. Fired from the cheap hash
108
+ * check before the checkout snapshot is frozen.
108
109
  *
109
110
  * This is a safety interlock: the client saw totals X, but by the time the
110
- * saga ran, totals are now Y. Rather than silently charging a different
111
+ * checkout ran, totals are now Y. Rather than silently charging a different
111
112
  * amount, the saga aborts with this error so the client re-displays and
112
113
  * re-confirms.
113
114
  *
@@ -194,8 +195,8 @@ declare class IdempotencyStorageError extends CartError {
194
195
  //#endregion
195
196
  //#region src/domain/errors/stale-quote.error.d.ts
196
197
  /**
197
- * A priced line's validity window has elapsed and its LineKind's revalidate()
198
- * returned `invalid`. Fired from the saga's step 2 (revalidation).
198
+ * A priced line's validity window has elapsed. Fired during checkout's
199
+ * freshness check before the snapshot is frozen.
199
200
  *
200
201
  * Example: a bid line whose underlying auction moved to a new highest bid
201
202
  * while the user was reviewing the cart.
package/dist/index.d.mts CHANGED
@@ -1,20 +1,20 @@
1
- import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "./index-BFBUk6qT.mjs";
1
+ import { a as SagaError, c as PriceChangedError, d as UnknownKindError, f as ConcurrencyError, i as IdempotencyStorageError, l as NotFoundError, m as CartErrorCategory, n as StaleQuoteError, o as SagaFailurePhase, p as CartError, r as IdempotencyBusyError, s as ReservationError, t as StateTransitionError, u as KindError } from "./index-qfN8dZN9.mjs";
2
2
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
3
3
  import { S as CartEvents, _ as CartEventMeta, a as OutboxErrorInfo, b as CartEventName, c as OutboxFailureDecision, d as OutboxStore, f as OutboxStoreWriteOptions, g as CartEventAggregate, h as CartDomainEvent, i as OutboxClaimOptions, l as OutboxFailurePolicy, m as CartAggregateType, n as MemoryOutboxStore, o as OutboxFailOptions, p as OutboxWriteOptions, r as OutboxAcknowledgeOptions, s as OutboxFailureContext, t as InvalidOutboxEventError, u as OutboxOwnershipError, v as createCartEvent, x as CartEventPayload, y as CartEventMap } from "./outbox-store-CBt9fSYh.mjs";
4
4
  import { a as CartEventRegistry, c as defineCartEvent, d as EventValidationResult, f as EventValidator, i as CartEventDefinitionInput, l as EventSchema, n as cartEventsByName, o as PayloadOf, r as CartEventDefinition, s as createCartEventRegistry, t as cartEventDefinitions, u as EventSchemaProperty } from "./cart-event-catalog-BxDJhtTM.mjs";
5
- import { C as PricingSnapshot, S as PricedLine, _ as PromotionsBridge, a as TaxBreakdown, b as BridgeStatus, c as TaxCalculationResult, d as ReservationRequest, f as CatalogBridge, g as PromotionResult, h as CartSnapshot, i as ShippingQuoteRequest, l as InventoryBridge, m as AdjustmentSpec, n as ShippingMethod, o as TaxBridge, p as ProductSummary, r as ShippingQuote, s as TaxCalculationRequest, t as ShippingBridge, u as ReservationRef, v as Address, x as OperationContext, y as BridgeRef } from "./shipping.bridge-CmQFTgSE.mjs";
6
- import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-b5cZ1ojx.mjs";
7
- import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep } from "./state-transitions-X_Eix5Iw.mjs";
8
- import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "./line-kind-Ck3fVXzG.mjs";
9
- import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "./kind-registry-C1n47C7h.mjs";
10
- import { a as systemClock, i as ClockPort, n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-C7ygWLRU.mjs";
5
+ import { C as OperationContext, S as BridgeStatus, T as PricingSnapshot, _ as CartSnapshot, a as ShippingQuote, 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 PricedLine, x as BridgeRef, y as PromotionsBridge } from "./clock.port-BUe6Dk_M.mjs";
6
+ import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-WdaZCJg9.mjs";
7
+ import { a as SagaStepFn, c as CheckoutStepNumber, i as SagaDependencies, n as CHECKOUT_STATE_TRANSITIONS, o as CheckoutFlowState, r as isLegalCheckoutTransition, s as CheckoutStep } from "./state-transitions-D8CRykBv.mjs";
8
+ import { a as RevalidationResult, c as ValidityPolicy, i as LineLike, l as LineDisplay, n as KindContext, o as StaleBehavior, r as LineKind, s as StaleTrigger, t as KindBridges } from "./line-kind-CKOWafK0.mjs";
9
+ import { a as IdempotencyReplay, c as LineItem, i as IdempotencyIdentity, n as createKindRegistry, o as OperationName, r as CART_REF_NEW, s as TotalsSnapshot, t as KindRegistry } from "./kind-registry-D03c2VV5.mjs";
10
+ import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-DitjeoHg.mjs";
11
11
  import { 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-DKcDteh-.mjs";
13
- import { a as timeslotKind, c as skuKind, d as BundlePayload, f as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, n as variantKind, o as timeslotPayloadSchema, p as bundlePayloadSchema, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as BundleComponent } from "./variant.kind-9P1DXdXu.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";
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";
16
16
  import { Schema } from "mongoose";
17
- import { ResolvedTenantConfig, TenantConfig } from "@classytic/primitives/tenant";
17
+ import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
18
18
 
19
19
  //#region src/services/abandonment.service.d.ts
20
20
  /**
@@ -115,4 +115,4 @@ type CartTenantInput = TenantConfig | boolean | {
115
115
  /** Re-export of primitives' resolved shape under the legacy name. */
116
116
  type ResolvedTenant = ResolvedTenantConfig;
117
117
  //#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 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, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
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 };
package/dist/index.mjs CHANGED
@@ -1,16 +1,16 @@
1
1
  import { t as CART_REF_NEW } from "./idempotency-key.vo-D0lJsvGn.mjs";
2
2
  import { t as CartError } from "./cart.error-BwWy4RlY.mjs";
3
- import { n as NotFoundError, r as ConcurrencyError, t as PriceChangedError } from "./price-changed.error-C-wGVcfc.mjs";
3
+ import { i as ConcurrencyError, n as PriceChangedError, r as NotFoundError, t as StaleQuoteError } from "./stale-quote.error-BkFLXWo5.mjs";
4
4
  import { n as UnknownKindError, t as KindError } from "./kind.error-DIaJpdUb.mjs";
5
- import { a as ReservationError, i as SagaError, n as IdempotencyBusyError, r as IdempotencyStorageError, t as StaleQuoteError } from "./errors-DzR7Pipp.mjs";
5
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-7Pd0yATM.mjs";
6
6
  import { t as StateTransitionError } from "./state-transition.error-2fRLh3p0.mjs";
7
7
  import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
8
8
  import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "./outbox-store-CWW8ppxS.mjs";
9
9
  import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-BhbFZJPm.mjs";
10
10
  import { t as createKindRegistry } from "./kind-registry-C99h_-8t.mjs";
11
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-e4z3Yhxb.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-B4l61iKT.mjs";
13
- import { a as skuKind, c as bundlePayloadSchema, i as timeslotPayloadSchema, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as bundleKind, t as variantKind } from "./variant.kind-DfEh2oku.mjs";
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";
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
14
  import { cartConfigSchema, 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
@@ -41,7 +41,7 @@ async function findAbandonedDrafts(opts) {
41
41
  organizationId: ctx.organizationId,
42
42
  skipTenant: ctx.skipTenant,
43
43
  lean: true
44
- })).docs;
44
+ })).data;
45
45
  }
46
46
  /**
47
47
  * Mark a batch of drafts as abandoned. Returns the count of drafts
@@ -90,4 +90,4 @@ async function mergeDrafts(opts) {
90
90
  return updated;
91
91
  }
92
92
  //#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, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
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 };
@@ -1,8 +1,8 @@
1
1
  import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-CBt9fSYh.mjs";
2
- import { _ as PromotionsBridge, f as CatalogBridge, l as InventoryBridge, o as TaxBridge, t as ShippingBridge, x as OperationContext } from "./shipping.bridge-CmQFTgSE.mjs";
3
- import { l as LineDisplay, r as LineKind } from "./line-kind-Ck3fVXzG.mjs";
4
- import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-C1n47C7h.mjs";
5
- import { i as ClockPort, t as IdPort } from "./id.port-C7ygWLRU.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-BUe6Dk_M.mjs";
3
+ import { l as LineDisplay, r as LineKind } from "./line-kind-CKOWafK0.mjs";
4
+ import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-D03c2VV5.mjs";
5
+ import { t as IdPort } from "./id.port-DitjeoHg.mjs";
6
6
  import { CartConfigShape } from "./engine/cart-config.schema.mjs";
7
7
  import { Money } from "@classytic/primitives/money";
8
8
  import { DomainEvent, EventHandler, EventTransport, PublishManyResult } from "@classytic/primitives/events";
@@ -1,4 +1,4 @@
1
- import { l as LineDisplay, r as LineKind } from "./line-kind-Ck3fVXzG.mjs";
1
+ import { l as LineDisplay, r as LineKind } from "./line-kind-CKOWafK0.mjs";
2
2
  import * as _$_classytic_primitives_money0 from "@classytic/primitives/money";
3
3
  import { Money } from "@classytic/primitives/money";
4
4
 
@@ -1,2 +1,2 @@
1
- import { a as timeslotKind, c as skuKind, d as BundlePayload, f as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, n as variantKind, o as timeslotPayloadSchema, p as bundlePayloadSchema, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as BundleComponent } from "../variant.kind-9P1DXdXu.mjs";
2
- export { type BundleComponent, type BundlePayload, type SkuPayload, type TimeslotPayload, type VariantPayload, bundleKind, bundlePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
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-Cpo_Hh7G.mjs";
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,2 @@
1
- import { a as skuKind, c as bundlePayloadSchema, i as timeslotPayloadSchema, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as bundleKind, t as variantKind } from "../variant.kind-DfEh2oku.mjs";
2
- export { bundleKind, bundlePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
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-z2gwH9Vo.mjs";
2
+ export { bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
@@ -1,4 +1,4 @@
1
- import { S as PricedLine, _ as PromotionsBridge, f as CatalogBridge, l as InventoryBridge, o as TaxBridge, t as ShippingBridge, u as ReservationRef, x as OperationContext } from "./shipping.bridge-CmQFTgSE.mjs";
1
+ import { C as OperationContext, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, w as PricedLine, y as PromotionsBridge } from "./clock.port-BUe6Dk_M.mjs";
2
2
  import { Money } from "@classytic/primitives/money";
3
3
  import { z } from "zod";
4
4
 
@@ -19,10 +19,10 @@ import { z } from "zod";
19
19
  * cache to manage.
20
20
  *
21
21
  * **Staleness.** The snapshot can drift from the live catalog (product
22
- * renamed, image updated). Revalidation at finalize catches price drift
23
- * via `LineKind.revalidate()`. Display drift is almost always acceptable
24
- * — the user already saw the name + image they wanted — but hosts that
25
- * care about absolute freshness can refresh by calling `displayOf()`
22
+ * renamed, image updated). Checkout's pricingHash and expiry checks catch
23
+ * price drift. Display drift is almost always acceptable — the user already
24
+ * saw the name + image they wanted — but hosts that care about absolute
25
+ * freshness can refresh by calling `displayOf()`
26
26
  * again from their own cron or webhook consumer.
27
27
  *
28
28
  * All fields are optional so hosts can populate only what they need.
@@ -70,7 +70,7 @@ interface ValidityPolicy {
70
70
  /**
71
71
  * reprice — silently re-run price() and continue. Suitable for bundles,
72
72
  * group-buy, and other cases where drift is acceptable.
73
- * error — abort finalize with StaleQuoteError; the client must
73
+ * error — abort checkout with StaleQuoteError; the client must
74
74
  * re-display and re-confirm. Required for bids, timeslots,
75
75
  * rentals, and anything auction-like.
76
76
  * extend — treat as indefinitely valid. Only for catalog SKUs where
@@ -187,6 +187,11 @@ interface LineLike<TPayload = unknown> {
187
187
  * one type; adding a new bridge to the engine does not break existing kinds.
188
188
  */
189
189
  interface KindContext extends OperationContext {
190
+ /**
191
+ * Engine clock for deterministic validity windows. Older direct kind tests
192
+ * may omit it; engine-created contexts always provide it.
193
+ */
194
+ readonly clock?: ClockPort;
190
195
  /**
191
196
  * Bridge registry. Keys match the bridge names in CartConfig. Values are
192
197
  * typed via the interface augmentation in `engine-types.ts`.
@@ -1,7 +1,7 @@
1
1
  import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
2
- import { C as PricingSnapshot, m as AdjustmentSpec } from "./shipping.bridge-CmQFTgSE.mjs";
3
- import { o as CheckoutFlowState } from "./state-transitions-X_Eix5Iw.mjs";
4
- import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-C1n47C7h.mjs";
2
+ import { T as PricingSnapshot, g as AdjustmentSpec } from "./clock.port-BUe6Dk_M.mjs";
3
+ import { o as CheckoutFlowState } from "./state-transitions-D8CRykBv.mjs";
4
+ import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-D03c2VV5.mjs";
5
5
  import { Money } from "@classytic/primitives/money";
6
6
 
7
7
  //#region src/domain/entities/adjustment.entity.d.ts
@@ -44,11 +44,12 @@ var NotFoundError = class extends CartError {
44
44
  //#endregion
45
45
  //#region src/domain/errors/price-changed.error.ts
46
46
  /**
47
- * The re-run pricing snapshot's hash does not match the `expectedPricingHash`
48
- * the client supplied when initiating finalize. Fired from saga step 3.
47
+ * The stored pricing snapshot's hash does not match the `expectedPricingHash`
48
+ * the client supplied when initiating checkout. Fired from the cheap hash
49
+ * check before the checkout snapshot is frozen.
49
50
  *
50
51
  * This is a safety interlock: the client saw totals X, but by the time the
51
- * saga ran, totals are now Y. Rather than silently charging a different
52
+ * checkout ran, totals are now Y. Rather than silently charging a different
52
53
  * amount, the saga aborts with this error so the client re-displays and
53
54
  * re-confirms.
54
55
  *
@@ -68,4 +69,29 @@ var PriceChangedError = class extends CartError {
68
69
  }
69
70
  };
70
71
  //#endregion
71
- export { NotFoundError as n, ConcurrencyError as r, PriceChangedError as t };
72
+ //#region src/domain/errors/stale-quote.error.ts
73
+ /**
74
+ * A priced line's validity window has elapsed. Fired during checkout's
75
+ * freshness check before the snapshot is frozen.
76
+ *
77
+ * Example: a bid line whose underlying auction moved to a new highest bid
78
+ * while the user was reviewing the cart.
79
+ *
80
+ * Clients should re-read the cart, show the updated state, and confirm again.
81
+ * Retryable with a new idempotency key.
82
+ */
83
+ var StaleQuoteError = class extends CartError {
84
+ code = "cart/stale_quote";
85
+ category = "validation";
86
+ retryable = true;
87
+ constructor(lineId, kind, reason, details) {
88
+ super(`Line ${lineId} (${kind}) is no longer valid: ${reason}`, {
89
+ lineId,
90
+ kind,
91
+ reason,
92
+ ...details
93
+ });
94
+ }
95
+ };
96
+ //#endregion
97
+ export { ConcurrencyError as i, PriceChangedError as n, NotFoundError as r, StaleQuoteError as t };
@@ -15,9 +15,9 @@ import { defineStateMachine } from "@classytic/primitives/state-machine";
15
15
  const CheckoutStep = {
16
16
  /** Step 1 — load draft + validate status + version. */
17
17
  LoadDraft: 1,
18
- /** Step 2 — re-run kind.revalidate() on stale lines. */
18
+ /** Step 2 — enforce stored snapshot freshness without extra bridge reads. */
19
19
  Revalidate: 2,
20
- /** Step 3 — re-run pricing pipeline, compare expectedPricingHash. */
20
+ /** Step 3 — compare stored pricingHash with expectedPricingHash. */
21
21
  Reprice: 3,
22
22
  /** Step 4 — create the checkout document with the frozen snapshot. */
23
23
  CreateCheckout: 4,
@@ -1,7 +1,7 @@
1
1
  import { t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
2
- import { x as OperationContext } from "./shipping.bridge-CmQFTgSE.mjs";
3
- import { t as KindBridges } from "./line-kind-Ck3fVXzG.mjs";
4
- import { i as ClockPort, t as IdPort } from "./id.port-C7ygWLRU.mjs";
2
+ import { C as OperationContext, t as ClockPort } from "./clock.port-BUe6Dk_M.mjs";
3
+ import { t as KindBridges } from "./line-kind-CKOWafK0.mjs";
4
+ import { t as IdPort } from "./id.port-DitjeoHg.mjs";
5
5
  import * as _$_classytic_primitives_state_machine0 from "@classytic/primitives/state-machine";
6
6
 
7
7
  //#region src/domain/saga/saga-steps.d.ts
@@ -17,8 +17,8 @@ import * as _$_classytic_primitives_state_machine0 from "@classytic/primitives/s
17
17
  * than a reverse walk of a multi-step chain.
18
18
  */
19
19
  declare const CheckoutStep: {
20
- /** Step 1 — load draft + validate status + version. */readonly LoadDraft: 1; /** Step 2 — re-run kind.revalidate() on stale lines. */
21
- readonly Revalidate: 2; /** Step 3 — re-run pricing pipeline, compare expectedPricingHash. */
20
+ /** Step 1 — load draft + validate status + version. */readonly LoadDraft: 1; /** Step 2 — enforce stored snapshot freshness without extra bridge reads. */
21
+ readonly Revalidate: 2; /** Step 3 — compare stored pricingHash with expectedPricingHash. */
22
22
  readonly Reprice: 3; /** Step 4 — create the checkout document with the frozen snapshot. */
23
23
  readonly CreateCheckout: 4; /** Step 5 — commit (host-called after its own external work succeeds). */
24
24
  readonly Commit: 5;
@@ -29,8 +29,8 @@ type CheckoutStepNumber = (typeof CheckoutStep)[keyof typeof CheckoutStep];
29
29
  /**
30
30
  * Transient checkout flow state stored on the Checkout document.
31
31
  *
32
- * In the simplified later model, the flow is short (load → revalidate →
33
- * reprice → create → commit/cancel) and each method is an atomic service
32
+ * In the simplified later model, the flow is short (load → freshness check →
33
+ * hash check → create → commit/cancel) and each method is an atomic service
34
34
  * call. There is no long-running saga, so this state is almost
35
35
  * decorative — it records the last successful step for diagnostics.
36
36
  *
@@ -1,4 +1,5 @@
1
- import { r as LineKind } from "./line-kind-Ck3fVXzG.mjs";
1
+ import { r as LineKind } from "./line-kind-CKOWafK0.mjs";
2
+ import { Money } from "@classytic/primitives/money";
2
3
  import { z } from "zod";
3
4
 
4
5
  //#region src/kinds/bundle.kind.d.ts
@@ -31,6 +32,68 @@ declare const bundlePayloadSchema: z.ZodObject<{
31
32
  }, z.core.$strip>;
32
33
  declare const bundleKind: LineKind<BundlePayload>;
33
34
  //#endregion
35
+ //#region src/kinds/service-fee.kind.d.ts
36
+ /**
37
+ * `service-fee` — non-product upsell line for cart-wide add-ons.
38
+ *
39
+ * Models the per-order fees a host wants to surface as first-class line
40
+ * items: gift wrap, paper bag, rush handling, card-payment surcharge,
41
+ * cleaning fee on bookings, etc. Distinct from a product line because:
42
+ *
43
+ * - There is NO catalog SKU behind it. The line carries its own
44
+ * code + label + unit price; the host's "services" config table is
45
+ * the source of truth for valid codes (a 5-10 row JSON or collection
46
+ * in the host, not a catalog product).
47
+ * - It does NOT reserve inventory. There is nothing to ship; the fee
48
+ * ships with the products it accompanies (gift wrap goes in the same
49
+ * box as the gift).
50
+ * - It is NOT product-specific. One toggle on the cart adds the fee to
51
+ * the whole order; no need to attach a `modifierGroup` to every
52
+ * product the way catalog modifiers work.
53
+ *
54
+ * Use a catalog `modifierGroup` instead when the upsell is genuinely
55
+ * per-product (espresso → +decaf shot). Use this kind when the upsell is
56
+ * per-order (any cart → +gift wrap).
57
+ *
58
+ * Survives the cart → checkout snapshot → order trail naturally because
59
+ * `@classytic/order`'s OrderLine carries a free-form `kind: string` and
60
+ * the snapshot fields this kind populates (`sku`, `name`, `unitPrice`,
61
+ * `currency`, `requiresShipping: false`) are exactly the fields the
62
+ * order kernel persists. The order's `kind: 'service-fee'` discriminator
63
+ * lets refund / RMA / fulfillment handlers branch on the line type
64
+ * without inferring from the SKU shape.
65
+ */
66
+ interface ServiceFeePayload {
67
+ /**
68
+ * Stable code for the service the host bills (`gift-wrap`, `paper-bag`,
69
+ * `rush-handling`, `card-surcharge`). The host's services config
70
+ * resolves the code to a price + label; this kind takes both as
71
+ * payload so the cart line carries the full pricing surface
72
+ * end-to-end (no per-render bridge call).
73
+ */
74
+ code: string;
75
+ /**
76
+ * User-facing label rendered on the cart, receipt, and order detail
77
+ * (`Gift wrap`, `Paper bag`). Localized at call-site by the host.
78
+ */
79
+ label: string;
80
+ /**
81
+ * Per-unit price for the service in minor units of the cart's
82
+ * currency (e.g. paisa for BDT). Multiplied by `quantity` for the
83
+ * line total.
84
+ */
85
+ unitPrice: Money;
86
+ }
87
+ declare const serviceFeePayloadSchema: z.ZodObject<{
88
+ code: z.ZodString;
89
+ label: z.ZodString;
90
+ unitPrice: z.ZodObject<{
91
+ amount: z.ZodNumber;
92
+ currency: z.ZodString;
93
+ }, z.core.$strip>;
94
+ }, z.core.$strip>;
95
+ declare const serviceFeeKind: LineKind<ServiceFeePayload>;
96
+ //#endregion
34
97
  //#region src/kinds/sku.kind.d.ts
35
98
  /**
36
99
  * `sku` — the plain retail LineKind.
@@ -111,4 +174,4 @@ declare const variantPayloadSchema: z.ZodObject<{
111
174
  }, z.core.$strip>;
112
175
  declare const variantKind: LineKind<VariantPayload>;
113
176
  //#endregion
114
- export { timeslotKind as a, skuKind as c, BundlePayload as d, bundleKind as f, TimeslotPayload as i, skuPayloadSchema as l, variantKind as n, timeslotPayloadSchema as o, bundlePayloadSchema as p, variantPayloadSchema as r, SkuPayload as s, VariantPayload as t, BundleComponent as u };
177
+ export { timeslotKind as a, skuKind as c, serviceFeeKind as d, serviceFeePayloadSchema as f, bundlePayloadSchema as g, bundleKind as h, TimeslotPayload as i, skuPayloadSchema as l, BundlePayload as m, variantKind as n, timeslotPayloadSchema as o, BundleComponent as p, variantPayloadSchema as r, SkuPayload as s, VariantPayload as t, ServiceFeePayload as u };
@@ -49,7 +49,7 @@ const bundleKind = {
49
49
  amount: 0,
50
50
  currency: unitPrice.currency
51
51
  },
52
- validUntil: new Date(Date.now() + 900 * 1e3),
52
+ validUntil: new Date((ctx.clock?.now() ?? /* @__PURE__ */ new Date()).getTime() + 900 * 1e3),
53
53
  kindMeta: {
54
54
  bundleRef: typed.payload.bundleRef,
55
55
  componentCount: typed.payload.components.length
@@ -87,7 +87,7 @@ const bundleKind = {
87
87
  postPromo: newTotal,
88
88
  postPromoPostTax: newTotal
89
89
  },
90
- validUntil: new Date(Date.now() + 900 * 1e3)
90
+ validUntil: new Date((ctx.clock?.now() ?? /* @__PURE__ */ new Date()).getTime() + 900 * 1e3)
91
91
  },
92
92
  delta
93
93
  };
@@ -106,7 +106,89 @@ const bundleKind = {
106
106
  imageUrl: bundle.primaryImage,
107
107
  slug: bundle.slug,
108
108
  variantLabel: `${typed.payload.components.length} items`,
109
- capturedAt: /* @__PURE__ */ new Date()
109
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
110
+ };
111
+ }
112
+ };
113
+ //#endregion
114
+ //#region src/kinds/service-fee.kind.ts
115
+ const serviceFeePayloadSchema = z.object({
116
+ code: z.string().min(1).max(64),
117
+ label: z.string().min(1).max(120),
118
+ unitPrice: z.object({
119
+ amount: z.number().int().nonnegative(),
120
+ currency: z.string().length(3)
121
+ })
122
+ });
123
+ const serviceFeeKind = {
124
+ name: "service-fee",
125
+ payloadSchema: serviceFeePayloadSchema,
126
+ validity: { onStale: "extend" },
127
+ async validate(line) {
128
+ const parsed = serviceFeePayloadSchema.safeParse(line.payload);
129
+ if (!parsed.success) throw new KindError(this.name, "invalid payload shape", { details: { issues: parsed.error.issues } });
130
+ if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
131
+ if (line.currency !== parsed.data.unitPrice.currency) throw new KindError(this.name, `service fee currency ${parsed.data.unitPrice.currency} does not match cart currency ${line.currency}`);
132
+ },
133
+ async price(line) {
134
+ const typed = line;
135
+ const unitPrice = typed.overrideUnitPrice ?? typed.payload.unitPrice;
136
+ const lineTotal = {
137
+ amount: unitPrice.amount * typed.quantity,
138
+ currency: unitPrice.currency
139
+ };
140
+ return {
141
+ lineId: typed.lineId,
142
+ unitPrice,
143
+ quantity: typed.quantity,
144
+ subtotals: {
145
+ prePromo: lineTotal,
146
+ postPromo: lineTotal,
147
+ postPromoPostTax: lineTotal
148
+ },
149
+ discountTotal: {
150
+ amount: 0,
151
+ currency: unitPrice.currency
152
+ },
153
+ taxTotal: {
154
+ amount: 0,
155
+ currency: unitPrice.currency
156
+ },
157
+ validUntil: null
158
+ };
159
+ },
160
+ async revalidate(_line, priced) {
161
+ return {
162
+ status: "unchanged",
163
+ priced
164
+ };
165
+ },
166
+ /**
167
+ * Two adds of the same service code merge by default (gift wrap +
168
+ * gift wrap = qty 2 of gift wrap). Hosts that want each add to stay
169
+ * separate (e.g. distinct rationale per fee) should call addItem with
170
+ * a custom note in the line metadata to differentiate.
171
+ */
172
+ mergeKey(line) {
173
+ const typed = line;
174
+ if (!typed.payload?.code) return null;
175
+ return `service-fee:${typed.payload.code}`;
176
+ },
177
+ /**
178
+ * Display snapshot for the cart UI — there is no catalog product
179
+ * behind a fee, so we synthesize from the payload directly (no
180
+ * bridge call). The receipt / order detail render path uses these
181
+ * fields verbatim.
182
+ */
183
+ async displayOf(line, ctx) {
184
+ const typed = line;
185
+ return {
186
+ name: typed.payload.label,
187
+ imageUrl: void 0,
188
+ slug: typed.payload.code,
189
+ variantLabel: void 0,
190
+ compareAtPrice: void 0,
191
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
110
192
  };
111
193
  }
112
194
  };
@@ -180,7 +262,7 @@ const skuKind = {
180
262
  slug: product.slug,
181
263
  variantLabel: product.variantLabel,
182
264
  compareAtPrice: product.compareAtPrice,
183
- capturedAt: ctx.bridges ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date()
265
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
184
266
  };
185
267
  }
186
268
  };
@@ -234,7 +316,7 @@ const timeslotKind = {
234
316
  amount: 0,
235
317
  currency: unitPrice.currency
236
318
  },
237
- validUntil: new Date(Date.now() + TIMESLOT_VALIDITY_MS),
319
+ validUntil: new Date((ctx.clock?.now() ?? /* @__PURE__ */ new Date()).getTime() + TIMESLOT_VALIDITY_MS),
238
320
  kindMeta: {
239
321
  startsAt: typed.payload.startsAt,
240
322
  endsAt: typed.payload.endsAt,
@@ -242,8 +324,8 @@ const timeslotKind = {
242
324
  }
243
325
  };
244
326
  },
245
- async revalidate(line, priced, _ctx) {
246
- if (priced.validUntil && priced.validUntil.getTime() <= Date.now()) return {
327
+ async revalidate(_line, priced, ctx) {
328
+ if (priced.validUntil && priced.validUntil.getTime() <= (ctx.clock?.now() ?? /* @__PURE__ */ new Date()).getTime()) return {
247
329
  status: "invalid",
248
330
  reason: "timeslot hold expired — the slot may no longer be available"
249
331
  };
@@ -282,7 +364,7 @@ const timeslotKind = {
282
364
  hour: "2-digit",
283
365
  minute: "2-digit"
284
366
  })}`,
285
- capturedAt: /* @__PURE__ */ new Date()
367
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
286
368
  };
287
369
  }
288
370
  };
@@ -354,9 +436,9 @@ const variantKind = {
354
436
  slug: product.slug,
355
437
  variantLabel: product.variantLabel,
356
438
  compareAtPrice: product.compareAtPrice,
357
- capturedAt: /* @__PURE__ */ new Date()
439
+ capturedAt: ctx.clock?.now() ?? /* @__PURE__ */ new Date()
358
440
  };
359
441
  }
360
442
  };
361
443
  //#endregion
362
- export { skuKind as a, bundlePayloadSchema as c, timeslotPayloadSchema as i, variantPayloadSchema as n, skuPayloadSchema as o, timeslotKind as r, bundleKind as s, variantKind as t };
444
+ export { skuKind as a, serviceFeePayloadSchema as c, timeslotPayloadSchema as i, bundleKind as l, variantPayloadSchema as n, skuPayloadSchema as o, timeslotKind as r, serviceFeeKind as s, variantKind as t, bundlePayloadSchema as u };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@classytic/cart",
3
- "version": "0.1.2",
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": "0.1.3",
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,
@@ -83,16 +83,18 @@
83
83
  "release": "npm run push -- main && npm run release:tag && npm publish"
84
84
  },
85
85
  "peerDependencies": {
86
- "@classytic/mongokit": ">=3.11.0",
87
- "@classytic/primitives": ">=0.2.0",
86
+ "@classytic/mongokit": ">=3.13.0",
87
+ "@classytic/primitives": ">=0.5.0",
88
+ "@classytic/repo-core": ">=0.4.0",
88
89
  "mongoose": ">=9.4.1",
89
90
  "zod": ">=4.0.0"
90
91
  },
91
92
  "devDependencies": {
92
93
  "@biomejs/biome": "^2.4.13",
93
94
  "@classytic/dev-tools": "^0.2.0",
94
- "@classytic/mongokit": "^3.11.0",
95
- "@classytic/primitives": ">=0.2.0",
95
+ "@classytic/mongokit": ">=3.13.0",
96
+ "@classytic/primitives": ">=0.5.0",
97
+ "@classytic/repo-core": ">=0.4.0",
96
98
  "@types/node": "^25.5.0",
97
99
  "knip": "^6.7.0",
98
100
  "mongodb-memory-server": "^10.2.3",