@classytic/cart 0.1.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 (47) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +21 -0
  3. package/README.md +109 -0
  4. package/dist/bundle.kind-BdgnyKZt.d.mts +114 -0
  5. package/dist/bundle.kind-DFydSxV_.mjs +362 -0
  6. package/dist/cart-event-catalog-BIbi2Q_n.d.mts +109 -0
  7. package/dist/cart-event-catalog-BOP9aDhL.mjs +301 -0
  8. package/dist/cart-status.vo-2iisZGhb.d.mts +46 -0
  9. package/dist/create-cart-q3CXxPP7.mjs +1751 -0
  10. package/dist/domain/errors/index.d.mts +2 -0
  11. package/dist/domain/errors/index.mjs +4 -0
  12. package/dist/domain/events/index.d.mts +3 -0
  13. package/dist/domain/events/index.mjs +3 -0
  14. package/dist/domain/index.d.mts +12 -0
  15. package/dist/domain/index.mjs +15 -0
  16. package/dist/domain/ports/index.d.mts +3 -0
  17. package/dist/domain/ports/index.mjs +2 -0
  18. package/dist/domain/saga/index.d.mts +2 -0
  19. package/dist/domain/saga/index.mjs +3 -0
  20. package/dist/domain-event-DHNkz15G.mjs +57 -0
  21. package/dist/engine/cart-config.schema.d.mts +41 -0
  22. package/dist/engine/cart-config.schema.mjs +40 -0
  23. package/dist/engine/index.d.mts +3 -0
  24. package/dist/engine/index.mjs +3 -0
  25. package/dist/errors-CHR9RlbY.mjs +97 -0
  26. package/dist/id.port-C3rlDAKP.mjs +29 -0
  27. package/dist/id.port-DPXLrqb2.d.mts +64 -0
  28. package/dist/idempotency-key.vo-D0lJsvGn.mjs +9 -0
  29. package/dist/idempotency-record.entity-DIFXjN1V.d.mts +221 -0
  30. package/dist/index-DEHBdV_z.d.mts +1 -0
  31. package/dist/index-Doi5uzux.d.mts +231 -0
  32. package/dist/index.d.mts +103 -0
  33. package/dist/index.mjs +92 -0
  34. package/dist/internal-event-bus-IkUfQJxn.d.mts +661 -0
  35. package/dist/kind-registry-Ba4PO4WC.mjs +35 -0
  36. package/dist/kind.error-CCjTB6kW.mjs +69 -0
  37. package/dist/kinds/index.d.mts +2 -0
  38. package/dist/kinds/index.mjs +2 -0
  39. package/dist/line-item.entity-B3M_i-pw.d.mts +157 -0
  40. package/dist/line-kind-Bndo6IS8.d.mts +231 -0
  41. package/dist/not-found.error-B6WYnAjX.mjs +95 -0
  42. package/dist/outbox-store-CTWz9pvG.d.mts +155 -0
  43. package/dist/saga-step-fn-Cyob38iU.d.mts +135 -0
  44. package/dist/saga-steps-B27LI7xp.mjs +27 -0
  45. package/dist/shipping.bridge-DD4A_O0O.d.mts +538 -0
  46. package/dist/state-transitions-CpJpZZTK.mjs +21 -0
  47. package/package.json +114 -0
@@ -0,0 +1,538 @@
1
+ import { Money } from "@classytic/primitives/money";
2
+ import { ClientSession } from "mongoose";
3
+ import { OperationContext } from "@classytic/primitives/context";
4
+ import { ContactAddress as Address } from "@classytic/primitives/address";
5
+
6
+ //#region src/domain/value-objects/pricing-snapshot.vo.d.ts
7
+ /**
8
+ * A priced line — the output of the pricing pipeline for a single LineItem.
9
+ *
10
+ * Carries both the raw kind output and the accumulated effects of each
11
+ * pipeline step (promo, tax, shipping). Intermediate fields are kept so the
12
+ * shipping step — and any host inspection — can see pre-promo, post-promo,
13
+ * post-tax subtotals on a per-line basis. See plan — Pricing Pipeline Order.
14
+ *
15
+ * All money amounts are in integer minor units. Per-line rounding is
16
+ * explicitly forbidden; rounding happens once at the order level in the
17
+ * rounding step.
18
+ */
19
+ interface PricedLine {
20
+ /** Foreign key to the owning LineItem (ObjectId string form). */
21
+ lineId: string;
22
+ /** Unit price after step 1 (base-price) + step 2 (kind-price), before any promo. */
23
+ unitPrice: Money;
24
+ /** Quantity snapshot from the line — carried so the pipeline does not re-read mutably. */
25
+ quantity: number;
26
+ /**
27
+ * Line subtotal at each pipeline stage. Every field is the TOTAL FOR THE LINE
28
+ * (unitPrice × quantity), not per-unit.
29
+ *
30
+ * prePromo — after base + kind-price
31
+ * postPromo — after promo-apply
32
+ * postPromoPostTax — after tax
33
+ */
34
+ subtotals: {
35
+ prePromo: Money;
36
+ postPromo: Money;
37
+ postPromoPostTax: Money;
38
+ };
39
+ /** Accumulated discounts applied to this line by the promo step. */
40
+ discountTotal: Money;
41
+ /** Accumulated tax applied to this line by the tax step. */
42
+ taxTotal: Money;
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).
48
+ */
49
+ validUntil: Date | null;
50
+ /**
51
+ * Opaque kind-specific metadata the pricing step wants to carry forward.
52
+ * Used for things like "chosen timeslot", "winning bid amount",
53
+ * "group-buy tier applied". Not interpreted by the pipeline; written by
54
+ * kinds, read by downstream consumers.
55
+ */
56
+ kindMeta?: Record<string, unknown>;
57
+ }
58
+ /**
59
+ * Whole-cart pricing snapshot — the output of running the full pipeline.
60
+ *
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.
65
+ */
66
+ interface PricingSnapshot {
67
+ /** Per-line priced rows, one entry per LineItem in draft order. */
68
+ lines: PricedLine[];
69
+ /**
70
+ * Order-level adjustment sum — promo-apply step may emit order-level
71
+ * discounts that do not belong to any particular line (e.g., "10% off your
72
+ * whole order"). Stored separately so the display layer can show them.
73
+ */
74
+ orderDiscount: Money;
75
+ /** Order-level shipping cost from step 5. */
76
+ shipping: Money;
77
+ /** Sum of all line taxes from step 4. */
78
+ tax: Money;
79
+ /** Final post-rounding totals from step 6. */
80
+ totals: {
81
+ /** Sum of all PricedLine.subtotals.prePromo. */subtotal: Money; /** Sum of all line discounts + orderDiscount. */
82
+ discount: Money; /** Alias of `tax`. */
83
+ taxTotal: Money; /** Alias of `shipping`. */
84
+ shippingTotal: Money; /** Final order grand total after rounding. */
85
+ grandTotal: Money;
86
+ };
87
+ /**
88
+ * Tightest validity window across all lines. If any line expires sooner
89
+ * than this, this field tracks that earliest boundary. `null` if every
90
+ * line is hard-priced.
91
+ */
92
+ pricingValidUntil: Date | null;
93
+ /**
94
+ * 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
96
+ * "price changed since the client confirmed" and abort with
97
+ * PriceChangedError so the client can re-display and re-confirm.
98
+ */
99
+ pricingHash: string;
100
+ /** Wall-clock time the snapshot was computed. Used for staleness checks. */
101
+ computedAt: Date;
102
+ }
103
+ //#endregion
104
+ //#region src/domain/ports/common.d.ts
105
+ /**
106
+ * Common types shared by every bridge port.
107
+ *
108
+ * `OperationContext` is the plain object handed to every bridge call. It
109
+ * carries identity, scope, correlation, and a clock handle. Frameworks bind
110
+ * to cart by producing an OperationContext from their request context; the
111
+ * cart engine itself never reads from a framework-specific object.
112
+ *
113
+ * Extends primitives' `OperationContext` (PACKAGE_RULES §P3) — narrows
114
+ * `organizationId` + `correlationId` to required and concretizes `session` to
115
+ * Mongoose's `ClientSession` (mongoose is already a peer dep). Adds cart-specific
116
+ * `actorRef` / `actorKind` / `sagaRunId` / `skipTenant` / `signal` fields.
117
+ */
118
+ interface OperationContext$1 extends Omit<OperationContext, 'organizationId' | 'correlationId' | 'session'> {
119
+ /** Branch scope — frozen as string (§1). */
120
+ organizationId: string;
121
+ /**
122
+ * Actor identity — either a stable user ID (authenticated) or a session ID
123
+ * (guest). Never null. Used as part of the idempotency identity and for
124
+ * audit.
125
+ */
126
+ actorRef: string;
127
+ /** Was the actor authenticated or is this a guest session? */
128
+ actorKind: 'user' | 'session';
129
+ /** Optional roles snapshot for bridge-side authorization. */
130
+ roles?: readonly string[];
131
+ /**
132
+ * Stable correlation ID for this logical operation. Propagates across
133
+ * bridge calls and outbox events. Hosts typically source this from the
134
+ * incoming request trace.
135
+ */
136
+ correlationId: string;
137
+ /**
138
+ * The saga run ID, if this call is happening inside the finalization saga.
139
+ * Omitted for regular cart mutations. Used by bridge `status()` probes to
140
+ * correlate across restarts.
141
+ */
142
+ sagaRunId?: string;
143
+ /** Abort signal — hosts propagate their request-scoped signal here. */
144
+ signal?: AbortSignal;
145
+ /**
146
+ * Mongoose ClientSession for transactional writes. Typed concretely
147
+ * because mongoose is already a peer dep of this package (cart repos
148
+ * extend mongokit's `Repository<TDoc>` which is Mongoose-backed).
149
+ * The finalization saga threads its short-lived transactions through
150
+ * here.
151
+ */
152
+ session?: ClientSession;
153
+ /**
154
+ * Bypass multi-tenant scope filters. Only for admin / cross-org queries
155
+ * run from trusted code paths. Repositories check this before injecting
156
+ * the `organizationId` match. Mirrors catalog's `skipTenant` flag.
157
+ */
158
+ skipTenant?: boolean;
159
+ /**
160
+ * Extensible — plugins can read custom fields from options.
161
+ * Matches mongokit's `SessionOptions` extensibility so this context can
162
+ * be passed directly to inherited repo methods (`getAll`, `getById`,
163
+ * etc.) without a cast at the boundary.
164
+ */
165
+ [key: string]: unknown;
166
+ }
167
+ /**
168
+ * Standard status vocabulary returned by every bridge's `status()` probe.
169
+ * See plan §3 — Saga Recovery Contract.
170
+ *
171
+ * pending — the operation is known but not yet settled
172
+ * committed — the operation has been applied; the ref is valid
173
+ * canceled — the operation was applied then explicitly reversed, OR
174
+ * the ref was never valid
175
+ * unknown — the bridge cannot reliably tell. The saga treats this as
176
+ * failure and compensates forward.
177
+ */
178
+ type BridgeStatus = 'pending' | 'committed' | 'canceled' | 'unknown';
179
+ /**
180
+ * Opaque handle returned by a bridge's create/reserve/authorize call.
181
+ *
182
+ * Bridges are free to put whatever they need in `payload`; cart stores the
183
+ * whole object verbatim. The saga passes it back unchanged to subsequent
184
+ * `status`, `release`, `cancel`, or `capture` calls.
185
+ */
186
+ interface BridgeRef<TPayload = Record<string, unknown>> {
187
+ /** Human-readable ref for logs/audit. */
188
+ id: string;
189
+ /** Bridge-specific state. */
190
+ payload: TPayload;
191
+ }
192
+ //#endregion
193
+ //#region src/domain/ports/catalog.bridge.d.ts
194
+ /**
195
+ * CatalogBridge — answers product questions for the cart engine.
196
+ *
197
+ * Host apps wire this to @classytic/catalog in BigBoss, to their own
198
+ * Mongoose/Prisma product model in smaller shops, or to a remote ERP in
199
+ * B2B settings. Cart never assumes catalog exists — it only knows the
200
+ * shape of the questions it asks.
201
+ *
202
+ * All methods are read-only. Cart never writes to the catalog.
203
+ */
204
+ interface CatalogBridge {
205
+ /**
206
+ * Resolve an opaque SKU reference (variant SKU, product ID, or host-defined
207
+ * string) into a canonical product summary. Called during `LineKind.price()`
208
+ * and `LineKind.validate()`.
209
+ *
210
+ * Return `null` if the SKU is not found — cart will raise a validation
211
+ * error. Throw for system-level failures (DB unreachable, etc.).
212
+ */
213
+ resolve(skuRef: string, ctx: OperationContext$1): Promise<ProductSummary | null>;
214
+ /**
215
+ * Batch resolve. Hosts with a catalog bridge that can parallelize should
216
+ * override this; the default implementation maps over `resolve`.
217
+ */
218
+ resolveMany?(skuRefs: readonly string[], ctx: OperationContext$1): Promise<Map<string, ProductSummary>>;
219
+ }
220
+ /**
221
+ * Minimal product shape the cart pricing pipeline needs.
222
+ *
223
+ * Deliberately slim — the bridge only exposes what cart consumes. Hosts
224
+ * with richer product models surface those through their own APIs, not
225
+ * through cart.
226
+ *
227
+ * The display fields (`primaryImage`, `slug`, `variantLabel`) are used by
228
+ * the kind's optional `displayOf()` method to populate a
229
+ * `LineDisplay` snapshot on the cart line at add-time. Hosts that do not
230
+ * populate these fields get cart lines with no display snapshot — the UI
231
+ * then has to look up the product at render time (slower, but still
232
+ * supported).
233
+ */
234
+ interface ProductSummary {
235
+ /** Stable product identity across catalog + cart. */
236
+ skuRef: string;
237
+ /** Human-readable name, for display on cart + receipts. */
238
+ name: string;
239
+ /** Unit price in minor units. Used by the `sku` and `variant` kinds. */
240
+ unitPrice: Money;
241
+ /** Optional compare-at price for showing strikethrough in the UI. */
242
+ compareAtPrice?: Money;
243
+ /**
244
+ * Primary image URL for the cart line thumbnail. Hosts using a CDN
245
+ * should pre-resolve transforms here (e.g. `?w=120&h=120&format=webp`).
246
+ * Cart stores this verbatim on the line so the UI can render without
247
+ * a second catalog lookup.
248
+ */
249
+ primaryImage?: string;
250
+ /** Product detail page slug — for linking back from the cart UI. */
251
+ slug?: string;
252
+ /**
253
+ * Pre-formatted variant label for display, e.g. "Size: M, Color: Blue".
254
+ * Hosts choose the format; cart passes it through without interpretation.
255
+ */
256
+ variantLabel?: string;
257
+ /**
258
+ * Catalog-side tax class — opaque to cart, forwarded as-is to TaxBridge.
259
+ * Typical values: 'standard', 'reduced', 'zero', 'exempt'.
260
+ */
261
+ taxClass?: string;
262
+ /** Weight grams — forwarded to ShippingBridge for rate quoting. */
263
+ weightGrams?: number;
264
+ /** Whether the product is currently purchasable. */
265
+ purchasable: boolean;
266
+ /** Free-form metadata pass-through. */
267
+ metadata?: Record<string, unknown>;
268
+ }
269
+ //#endregion
270
+ //#region src/domain/ports/inventory.bridge.d.ts
271
+ /**
272
+ * InventoryBridge — holds and releases physical/logical stock.
273
+ *
274
+ * Wired to @classytic/flow in BigBoss (where reservations are Flow moves),
275
+ * to a Mongoose stock model in simpler apps, or to an external WMS via REST.
276
+ *
277
+ * MANDATORY: `status()` is required for saga recovery. See plan §3 — Saga
278
+ * Recovery Contract.
279
+ *
280
+ * Idempotency contract:
281
+ * - `reserve` with the same `ctx.idempotencyKey` MUST return the same
282
+ * reservation refs the first call returned, not new ones.
283
+ * - `release` MUST be safe to call multiple times with the same refs.
284
+ * - `status` MUST be side-effect-free.
285
+ *
286
+ * The package ships a conformance suite (`tests/conformance/`) that asserts
287
+ * these properties against any bridge implementation.
288
+ */
289
+ interface InventoryBridge {
290
+ /**
291
+ * Reserve stock for the provided requests. All-or-nothing: on any failure,
292
+ * the implementation should roll back its own partial holds and throw.
293
+ *
294
+ * The cart saga calls this at step 5. On restart, the saga calls `status()`
295
+ * first to determine whether a prior call already succeeded.
296
+ */
297
+ reserve(requests: readonly ReservationRequest[], ctx: OperationContext$1): Promise<ReservationRef[]>;
298
+ /**
299
+ * Release previously held reservations. Called by:
300
+ * - Compensation chain on saga failure
301
+ * - Explicit checkout cancel
302
+ * - The reservation sweeper for expired holds
303
+ *
304
+ * Must be idempotent — already-released refs should be treated as success,
305
+ * not error.
306
+ */
307
+ release(refs: readonly ReservationRef[], ctx: OperationContext$1): Promise<void>;
308
+ /**
309
+ * Commit reservations — transition from 'held' to 'committed' state,
310
+ * typically after the host order has been successfully created. The
311
+ * underlying inventory system may interpret this as "stock is now allocated
312
+ * to a real order" vs a transient hold.
313
+ */
314
+ commit(refs: readonly ReservationRef[], ctx: OperationContext$1): Promise<void>;
315
+ /**
316
+ * MANDATORY — saga recovery probe. Must be side-effect-free and return one
317
+ * of the standard BridgeStatus values.
318
+ */
319
+ status(ref: ReservationRef, ctx: OperationContext$1): Promise<BridgeStatus>;
320
+ }
321
+ /**
322
+ * Input to `reserve()` — what the cart wants held.
323
+ *
324
+ * `slot` is used by the timeslot/rental kinds for time-bound reservations.
325
+ * Stock-based kinds leave it undefined.
326
+ */
327
+ interface ReservationRequest {
328
+ /** Which line this reservation is for. */
329
+ lineId: string;
330
+ /** The underlying SKU or slot reference. */
331
+ skuRef: string;
332
+ /** Units. */
333
+ quantity: number;
334
+ /** Desired TTL in seconds. Bridges may enforce their own min/max. */
335
+ ttlSeconds: number;
336
+ /** Optional time window for timeslot/rental kinds. */
337
+ slot?: {
338
+ startsAt: Date;
339
+ endsAt: Date;
340
+ };
341
+ /** Free-form metadata forwarded to the underlying system. */
342
+ metadata?: Record<string, unknown>;
343
+ }
344
+ /**
345
+ * Reference returned by `reserve()` and consumed by `release`, `commit`,
346
+ * `status`. Opaque to cart.
347
+ */
348
+ type ReservationRef = BridgeRef;
349
+ //#endregion
350
+ //#region src/domain/ports/promotions.bridge.d.ts
351
+ /**
352
+ * PromotionsBridge — authoritative for promotion rule evaluation.
353
+ *
354
+ * Cart ships NO default rules engine. Every host brings its own — Shopify-
355
+ * script-like, Saleor predicates, Odoo pricelists, or a custom rules engine.
356
+ * The pricing pipeline's promo-apply step does nothing more than call
357
+ * `evaluate()`, sort the results, and turn them into adjustment line items.
358
+ *
359
+ * See plan §6 — Promotions ownership.
360
+ */
361
+ interface PromotionsBridge {
362
+ /**
363
+ * Evaluate the provided snapshot against the host's rules.
364
+ *
365
+ * Called on every pricing pipeline run — including draft mutations, not
366
+ * just finalize. Must be fast. Expensive rule engines should cache
367
+ * internally.
368
+ */
369
+ evaluate(snapshot: CartSnapshot, ctx: OperationContext$1): Promise<PromotionResult[]>;
370
+ /**
371
+ * Optional — preview a single promo code against a snapshot without
372
+ * applying it. Used by frontend widgets that want to validate a coupon
373
+ * before commit. Returning null means "does not apply".
374
+ */
375
+ preview?(code: string, snapshot: CartSnapshot, ctx: OperationContext$1): Promise<PromotionResult | null>;
376
+ }
377
+ /**
378
+ * The subset of cart state the bridge needs to evaluate rules.
379
+ *
380
+ * Deliberately decoupled from the Draft/Checkout entity types so bridges
381
+ * don't pick up schema dependencies.
382
+ */
383
+ interface CartSnapshot {
384
+ organizationId: string;
385
+ actorRef: string;
386
+ actorKind: 'user' | 'session';
387
+ currency: string;
388
+ lines: readonly PricedLine[];
389
+ subtotal: Money;
390
+ appliedPromoCodes: readonly string[];
391
+ metadata?: Record<string, unknown>;
392
+ }
393
+ /**
394
+ * A single promotion-engine verdict.
395
+ *
396
+ * Cart applies these in priority order (descending). Order-level results
397
+ * have `targetLineId: null`. Gifts are represented as a GiftRef the bridge
398
+ * returns; cart adds a corresponding line item with zero price and links it
399
+ * to the promotion rule for audit.
400
+ */
401
+ interface PromotionResult {
402
+ /** Opaque rule reference — cart does not interpret. */
403
+ ruleRef: string;
404
+ /** Optional line targeted by this discount, or null for order-level. */
405
+ targetLineId: string | null;
406
+ /** The adjustment. See AdjustmentSpec below. */
407
+ adjustment: AdjustmentSpec;
408
+ /** Stacking order. Higher runs first. */
409
+ priority: number;
410
+ /** Optional human-readable explanation — displayed in cart / receipt. */
411
+ explanation?: string;
412
+ /** Opaque metadata propagated to audit + outbox events. */
413
+ metadata?: Record<string, unknown>;
414
+ }
415
+ type AdjustmentSpec = {
416
+ type: 'percent';
417
+ value: number;
418
+ } | {
419
+ type: 'fixed';
420
+ value: Money;
421
+ } | {
422
+ type: 'gift';
423
+ skuRef: string;
424
+ quantity: number;
425
+ } | {
426
+ type: 'shipping';
427
+ mode: 'free' | 'percent' | 'fixed';
428
+ value?: number | Money;
429
+ };
430
+ //#endregion
431
+ //#region src/domain/ports/tax.bridge.d.ts
432
+ /**
433
+ * TaxBridge — compute line-level taxes from post-promo line amounts.
434
+ *
435
+ * Called by the pricing pipeline's tax step, which is always step 4 —
436
+ * discounts apply before tax. See plan — Pricing Pipeline Order.
437
+ *
438
+ * Cart ships no default tax engine. Hosts wire Avalara, TaxJar, Stripe Tax,
439
+ * or a simple per-region table of their own.
440
+ *
441
+ * Tax-inclusive regimes (EU VAT, Australia GST) are handled by the bridge
442
+ * returning a negative-delta tax line that conceptually "extracts" tax from
443
+ * the inclusive base price. The pipeline step order never changes.
444
+ */
445
+ interface TaxBridge {
446
+ calculate(request: TaxCalculationRequest, ctx: OperationContext$1): Promise<TaxCalculationResult>;
447
+ }
448
+ interface TaxCalculationRequest {
449
+ /** Currency of the cart — same across all lines. */
450
+ currency: string;
451
+ /** Pre-tax, post-promo priced lines. */
452
+ lines: readonly PricedLine[];
453
+ /** Destination for tax sourcing. Typically the shipping address. */
454
+ destination?: Address;
455
+ /** Origin (merchant address) for origin-based sourcing jurisdictions. */
456
+ origin?: Address;
457
+ /** Opaque tax-class hints from the catalog bridge, keyed by lineId. */
458
+ taxClassByLine?: Record<string, string>;
459
+ }
460
+ interface TaxCalculationResult {
461
+ /** Per-line tax amounts, keyed by lineId. */
462
+ lineTaxes: Record<string, Money>;
463
+ /** Optional bridge-specific breakdown for display on the receipt. */
464
+ breakdown?: TaxBreakdown[];
465
+ }
466
+ interface TaxBreakdown {
467
+ /** Jurisdiction or rule name — bridge-specific. */
468
+ name: string;
469
+ /** Tax amount contributed by this rule. */
470
+ amount: Money;
471
+ /** Optional percentage rate as displayed to users. */
472
+ ratePercent?: number;
473
+ }
474
+ //#endregion
475
+ //#region src/domain/ports/shipping.bridge.d.ts
476
+ /**
477
+ * ShippingBridge — quote shipping charges for a cart.
478
+ *
479
+ * Called by the pricing pipeline's shipping step (step 5), which runs AFTER
480
+ * promo (step 3) and tax (step 4). The pipeline hands the bridge a rich
481
+ * ShippingQuoteRequest containing every intermediate subtotal (pre-promo,
482
+ * post-promo, post-promo-post-tax) so bridges that need a different basis
483
+ * can read the one they care about — **but the pipeline order itself is
484
+ * frozen and the bridge cannot reorder steps**.
485
+ *
486
+ * See plan — Pricing Pipeline Order.
487
+ */
488
+ interface ShippingBridge {
489
+ quote(request: ShippingQuoteRequest, ctx: OperationContext$1): Promise<ShippingQuote>;
490
+ }
491
+ interface ShippingQuoteRequest {
492
+ currency: string;
493
+ /** Post-promo, pre-tax line snapshots. */
494
+ lines: readonly PricedLine[];
495
+ /** Where the buyer wants it shipped. */
496
+ destination: Address;
497
+ /** Merchant origin (for rate calculation). */
498
+ origin?: Address;
499
+ /**
500
+ * All relevant intermediate subtotals. The bridge picks which one it wants
501
+ * to use for its rate table; cart does not enforce.
502
+ */
503
+ subtotals: {
504
+ prePromo: Money;
505
+ postPromo: Money;
506
+ postPromoPreTax: Money;
507
+ postPromoPostTax: Money;
508
+ };
509
+ /** Optional buyer-chosen method identifier from a prior quote round. */
510
+ selectedMethodId?: string;
511
+ }
512
+ interface ShippingQuote {
513
+ /** Available methods for the buyer to choose from. */
514
+ methods: ShippingMethod[];
515
+ /**
516
+ * The default or previously-selected method the pipeline should apply
517
+ * right now. `null` means the pipeline treats shipping as zero until the
518
+ * buyer picks a method.
519
+ */
520
+ selected: ShippingMethod | null;
521
+ }
522
+ interface ShippingMethod {
523
+ /** Opaque identifier stable across quotes. */
524
+ id: string;
525
+ /** Display name. */
526
+ name: string;
527
+ /** Carrier (FedEx, DHL, "Store pickup", etc.). */
528
+ carrier: string;
529
+ /** Price to add to the cart. */
530
+ price: Money;
531
+ /** Optional delivery window for display. */
532
+ estimatedDelivery?: {
533
+ minDays: number;
534
+ maxDays: number;
535
+ };
536
+ }
537
+ //#endregion
538
+ export { PricingSnapshot as C, PricedLine as S, ProductSummary as _, TaxBreakdown as a, BridgeStatus as b, TaxCalculationResult as c, PromotionResult as d, PromotionsBridge as f, CatalogBridge as g, ReservationRequest as h, ShippingQuoteRequest as i, AdjustmentSpec as l, ReservationRef as m, ShippingMethod as n, TaxBridge as o, InventoryBridge as p, ShippingQuote as r, TaxCalculationRequest as s, ShippingBridge as t, CartSnapshot as u, Address as v, OperationContext$1 as x, BridgeRef as y };
@@ -0,0 +1,21 @@
1
+ //#region src/domain/saga/state-transitions.ts
2
+ /**
3
+ * Frozen state transitions for Checkout.state. Three states, two
4
+ * terminal outcomes — finalized (success) or canceled (failure / manual
5
+ * cancel / abandonment).
6
+ *
7
+ * Enforced by `CheckoutRepository.updateWithVersion` callers: the
8
+ * service methods pass the expected current state in the filter so
9
+ * racing writers see exactly one winner.
10
+ */
11
+ const CHECKOUT_STATE_TRANSITIONS = {
12
+ open: ["finalized", "canceled"],
13
+ finalized: [],
14
+ canceled: []
15
+ };
16
+ /** Predicate — is `to` a legal transition from `from`? */
17
+ function isLegalCheckoutTransition(from, to) {
18
+ return CHECKOUT_STATE_TRANSITIONS[from]?.includes(to) ?? false;
19
+ }
20
+ //#endregion
21
+ export { isLegalCheckoutTransition as n, CHECKOUT_STATE_TRANSITIONS as t };
package/package.json ADDED
@@ -0,0 +1,114 @@
1
+ {
2
+ "name": "@classytic/cart",
3
+ "version": "0.1.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
+ "author": "Classytic",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "engines": {
9
+ "node": ">=22"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.mts",
17
+ "default": "./dist/index.mjs"
18
+ },
19
+ "./domain": {
20
+ "types": "./dist/domain/index.d.mts",
21
+ "default": "./dist/domain/index.mjs"
22
+ },
23
+ "./kinds": {
24
+ "types": "./dist/kinds/index.d.mts",
25
+ "default": "./dist/kinds/index.mjs"
26
+ },
27
+ "./ports": {
28
+ "types": "./dist/domain/ports/index.d.mts",
29
+ "default": "./dist/domain/ports/index.mjs"
30
+ },
31
+ "./errors": {
32
+ "types": "./dist/domain/errors/index.d.mts",
33
+ "default": "./dist/domain/errors/index.mjs"
34
+ },
35
+ "./events": {
36
+ "types": "./dist/domain/events/index.d.mts",
37
+ "default": "./dist/domain/events/index.mjs"
38
+ },
39
+ "./saga": {
40
+ "types": "./dist/domain/saga/index.d.mts",
41
+ "default": "./dist/domain/saga/index.mjs"
42
+ },
43
+ "./engine": {
44
+ "types": "./dist/engine/index.d.mts",
45
+ "default": "./dist/engine/index.mjs"
46
+ },
47
+ "./schemas": {
48
+ "types": "./dist/engine/cart-config.schema.d.mts",
49
+ "default": "./dist/engine/cart-config.schema.mjs"
50
+ }
51
+ },
52
+ "main": "./dist/index.mjs",
53
+ "types": "./dist/index.d.mts",
54
+ "files": [
55
+ "dist",
56
+ "README.md",
57
+ "LICENSE",
58
+ "CHANGELOG.md"
59
+ ],
60
+ "repository": {
61
+ "type": "git",
62
+ "url": "git+https://github.com/classytic/cart.git"
63
+ },
64
+ "bugs": {
65
+ "url": "https://github.com/classytic/cart/issues"
66
+ },
67
+ "homepage": "https://github.com/classytic/cart#readme",
68
+ "scripts": {
69
+ "build": "tsdown",
70
+ "dev": "tsdown --watch",
71
+ "typecheck": "tsc --noEmit",
72
+ "test": "vitest run --project unit --project integration",
73
+ "test:unit": "vitest run --project unit",
74
+ "test:integration": "vitest run --project integration",
75
+ "test:all": "vitest run",
76
+ "test:watch": "vitest --project unit --project integration"
77
+ },
78
+ "peerDependencies": {
79
+ "@classytic/mongokit": ">=3.11.0",
80
+ "@classytic/primitives": ">=0.1.0",
81
+ "@classytic/repo-core": ">=0.2.0",
82
+ "mongoose": ">=9.4.1",
83
+ "zod": ">=4.0.0"
84
+ },
85
+ "devDependencies": {
86
+ "@classytic/mongokit": "^3.11.0",
87
+ "@classytic/primitives": "^0.1.0",
88
+ "@classytic/repo-core": ">=0.2.0",
89
+ "@types/node": "^25.5.0",
90
+ "@vitest/coverage-v8": "^3.2.4",
91
+ "mongodb-memory-server": "^10.2.3",
92
+ "mongoose": "^9.4.1",
93
+ "tsdown": "^0.21.5",
94
+ "typescript": "^5.7.0",
95
+ "vitest": "^3.0.0",
96
+ "zod": "^4.3.6"
97
+ },
98
+ "keywords": [
99
+ "cart",
100
+ "checkout",
101
+ "commerce",
102
+ "ecommerce",
103
+ "saga",
104
+ "idempotency",
105
+ "reservation",
106
+ "booking",
107
+ "auction",
108
+ "group-buy",
109
+ "subscription",
110
+ "mongodb",
111
+ "mongoose"
112
+ ],
113
+ "license": "MIT"
114
+ }