@classytic/cart 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,246 +1,9 @@
1
1
  # Changelog
2
2
 
3
- Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
4
- adhering to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
3
+ ## Unreleased
5
4
 
6
- ## 1.3.0 — 2026-10-14
5
+ ## 1.3.1 — 2026-11-28
7
6
 
8
- ### Added — fractional lines on the product's step
9
- - `ProductSummary.quantityStep` (optional, absent = 1) and an optional `LineKind.quantityStepOf`,
10
- implemented by `sku` and `variant`. The draft repository checks every add, merge and quantity
11
- update against the line's step and stores it on `LineItem.quantityStep` (absent = 1). A kind that
12
- declares no step keeps the positive-integer rule.
13
- - `lineTotal` extends a fractional quantity exactly on the 6-dp grid, rounded once half-even; a
14
- merge adds on the grid (`1.2 + 1.15` kg is 2.35).
15
- - `updateItemQuantity` removes the line at `quantity <= 0` (was `< 1`, which would have removed a
16
- 0.5 kg line); a whole-unit line given 0.5 is now refused rather than removed.
17
- - The draft and reservation models accept any positive quantity (was `min: 1`).
18
- - Bundle component quantities stay whole numbers (a component carries no step yet).
19
- - The package's own copy of the quantity grid is gone: it uses `@classytic/primitives/quantity` and `price-basis` (`>=0.31.0`). `lineTotal` adds the sign for a negative unit price; an off-grid quantity throws primitives' `PriceBasisError` (was `RangeError`).
20
- ### Changed — draft retention is enforced (`draftRetentionSeconds`, default 90 days)
7
+ Peers raised to the latest published: `@classytic/mongokit >=3.47.0`, `@classytic/primitives >=0.39.0`, `@classytic/repo-core >=0.39.0`, `mongoose >=9.13.1`.
21
8
 
22
- Every draft write (create, line change, abandon, convert) stamps `expiresAt = now + draftRetentionSeconds`; `expiresAt` is now REQUIRED on the model, so the existing TTL index removes idle and finished drafts. Before, every draft carried `expiresAt: null` and the TTL never fired. The unread `draftTtlSeconds` option is removed. Existing rows: `be-prod/scripts/migrations/stamp-cart-draft-expiry.mjs`. Pinned by `tests/integration/draft-retention.integration.test.ts`.
23
-
24
- ### Changed — peer floors
25
-
26
- `@classytic/mongokit` `>=3.41.0`, `@classytic/primitives` `>=0.32.0`, `@classytic/repo-core` `>=0.31.0`, `mongoose` `>=9.11.0`.
27
-
28
- ## 1.2.0 — 2026-09-04
29
-
30
- ### Added — `DraftRepository.markActiveConvertedForActor`
31
-
32
- Hosts that place an order without freezing a checkout first have no `checkout.draftId` for `markConverted` to key on, leaving the draft `active` with lines intact — exactly the shape the abandonment sweep selects. `markActiveConvertedForActor(actorRef, ctx)` looks up the actor's active draft and converts it in one call. Returns `false` if no active draft exists or `actorRef` is empty (guard against broad-match on empty string). Best-effort like `markConverted`: a miss does not fail the order.
33
-
34
- ## 1.1.1 — 2026-08-26
35
-
36
- ### Fixed
37
-
38
- - **`LineDisplay.weightGrams` captured from catalog bridge snapshot** — both
39
- `skuKind` and `variantKind` now emit `weightGrams` when the bridge supplies it
40
- (real and positive only; absent stays absent so weight-tiered delivery zones
41
- fall back to the flat charge rather than pricing the cheapest step). The field
42
- was already in the bridge's product shape; the snapshot simply never forwarded
43
- it, so every weight-tiered checkout fell back to flat.
44
- - **`draft.model.ts` declares `weightGrams`** — Mongoose strips unknown paths
45
- silently; without the schema declaration the field would be dropped on every
46
- write. `default: null` preserves the absent/unweighed distinction (no `0`
47
- default).
48
-
49
- ### Changed
50
-
51
- - **Peer floors raised** — mongokit `>=3.35.0`, primitives `>=0.25.0`,
52
- repo-core `>=0.25.0`.
53
-
54
- ## 1.1.0 - 2026-08-17
55
-
56
- ### Changed
57
- - `cleanup/steps.ts`: bare calendar-date `before` param refused — must be a full ISO instant (prevents silent UTC-midnight misfire in non-UTC deployments)
58
- - `define-cart`: `resolveCartTenant` wired; tenant injection centralised
59
- - `inject-tenant` refactored; models and repositories simplified
60
-
61
- ## 1.0.0 - 2026-07-29
62
-
63
- ### Changed
64
- - **License:** relicensed from MIT to the **Classytic Source-Available License** (Community & Commercial). Evaluation/development use remains free; production use now requires a commercial license from Classytic LLC. See `LICENSE`.
65
- - Major bump marks the license change; versions published before 1.0.0 remain under their original MIT terms.
66
-
67
- ## [0.3.3] — unpublished (2026-07-22)
68
-
69
- ### Changed — event infra consolidated onto `@classytic/primitives/event-infra`
70
-
71
- - `InProcessCartEventBus` is now a thin subclass of primitives' shared
72
- `InProcessEventBus` (name `in-process-cart`, `logger: null` — cart's
73
- silent-swallow dialect preserved: handler errors never propagate OR log).
74
- Internal delivery detail: subscriptions are now Set-deduped per handler
75
- across matching patterns (previously per-subscription array order) — no
76
- cart code subscribes one handler under multiple patterns, so delivery is
77
- unchanged in practice. `MemoryOutboxStore` is re-exported from
78
- `@classytic/primitives/event-infra` instead of a local copy (gains
79
- `all()` / `clear()` test helpers). No public API or event-shape changes.
80
- - `@classytic/primitives` peer floor raised to `>=0.13.0` (the
81
- `/event-infra` subpath).
82
-
83
- ## [0.3.2] — unpublished (2026-07-22)
84
-
85
- ### Fixed — `destroy()` was an empty no-op
86
-
87
- - **`engine.destroy()` now actually tears down**: closes the self-created
88
- `InProcessCartEventBus` (skipped when the host injected `eventTransport`).
89
- - `destroy()` follows the fleet ownsBus convention (manufacturing/purchase
90
- pattern): only what the engine itself created is closed; a host-injected
91
- transport is the host's to close. Idempotent — a second call is a no-op.
92
- Mongoose models/connection are untouched (host-owned).
93
- - Lifecycle coverage in `tests/unit/engine-lifecycle.test.ts` (lite mode).
94
-
95
- ## [0.3.1] — 2026-07-16
96
-
97
- ### Fixed
98
-
99
- - injectTenantField no longer force-indexes the tenant field: the compound
100
- prepend makes the tenant the leading key of every index, so the bare single
101
- was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
102
- index audit). A dedicated tenant index is still created when a schema
103
- declares no compounds to prepend. Index-declaration change only.
104
-
105
- ## [0.3.0] — unpublished (2026-07-15)
106
-
107
- ### Changed — kit refresh (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
108
-
109
- - Verified against the mongokit 3.22 sweep. DEFERRED (design note, not a
110
- drive-by): checkout `finalize`/`cancel` are assert-then-`updateWithVersion`
111
- — the version CAS serializes writers, so the window is narrow; converting
112
- to `applyTransition` (state+version compound CAS) needs a pass that
113
- preserves the updateWithVersion helper's semantics.
114
-
115
- ## [0.2.1] - 2026-07-02
116
-
117
- ### Changed (behavioral) — 2026-07-05 addendum
118
-
119
- - **`commit()` is crash-retry convergent.** The finalize CAS runs first and
120
- its tail (`markConverted` on the draft + the `cart.checkout.committed`
121
- event) is non-atomic — a crash in between left the draft looking live
122
- (re-checkout → duplicate order risk) with NO retry path, because a second
123
- `commit()` failed the `finalized → finalized` state assertion. A retry
124
- with the SAME `externalRef` (or none) now re-runs both idempotent tails
125
- and returns the finalized checkout; a DIFFERENT `externalRef` throws
126
- `ConcurrencyError`. `cart.checkout.committed` delivery is at-least-once —
127
- subscribers must already dedupe by `checkoutId`.
128
-
129
- ### Added
130
-
131
- - **`engine.withTransaction(ctx, body)`** — unit-of-work wrapper (transaction
132
- + post-commit event publish), the contract shared with `@classytic/refit`
133
- and `@classytic/review`. Events emitted inside the unit are queued under
134
- `ctx[PENDING_EVENTS]` and flushed to the in-process transport only AFTER
135
- commit — a rollback or retry can't leak ghost events. New exports:
136
- `PENDING_EVENTS`, `flushPending`, `UnmanagedSessionError`; new config:
137
- `allowNonTransactional` (standalone-Mongo dev fallback, explicit opt-in).
138
- - **Boot capability gate** — `createCart` (full mode) asserts the backend
139
- declares `capabilities.upsert` (idempotency lease pattern) at engine
140
- creation instead of failing on the first checkout.
141
- - **Event-catalog no-drift test** (rule 18) — every `CartEvents` constant
142
- must have a Zod definition; orphan definitions also fail.
143
- - **Compensation scenario test** — proves the documented
144
- `cart.checkout.canceled` → `inventory.release()` host wiring end-to-end.
145
- - `PriceChangedErrorContext` — formal type for the error's structured
146
- context (current pricing payload), previously an untyped inline shape.
147
-
148
- ### Changed
149
-
150
- - **`CartEventPublisher`**: a host-owned `ctx.session` without an outbox now
151
- throws typed `UnmanagedSessionError` (was a plain `Error`) unless a
152
- `PENDING_EVENTS` queue is attached; transport publish failures on the
153
- no-session path are now swallowed and logged per P8 (the domain verb no
154
- longer fails after its write landed because a transport hiccuped).
155
- - Safe-integer guard on line-total arithmetic (`unitPrice × quantity`);
156
- idempotency repo now uses mongokit's `isDuplicateKeyError`; `cancel()`
157
- and the timeslot kind's `revalidate` carry explicit contracts (host owns
158
- hold release; validity-window-only revalidation — real slot-locking via
159
- `@classytic/order`'s `BookingBridge`).
160
-
161
- ## [0.2.0]
162
-
163
- ### Changed
164
-
165
- - **`pricingHash` is now hex SHA-256** over the same canonical sorted
166
- line string (was the raw concatenation). The hash is opaque — compare,
167
- never parse. **Migration:** drafts priced before 0.2.0 carry old-format
168
- hashes; the first checkout attempt against them raises
169
- `PriceChangedError` once and the client re-fetches/re-confirms.
170
- Accepted clean break.
171
- - **Guest→user merge is now double-CAS atomic.** `mergeDrafts` retires the
172
- source with a version CAS, then writes the target with a version CAS
173
- (bounded retries) — a concurrent add-to-cart on either draft is retried
174
- into the result instead of silently lost. `DraftRepository.markAbandoned`
175
- gains an optional `{ expectedVersion }`; `replaceLines` gains an
176
- optional `expectedVersion` input.
177
- - **Zombie open checkouts self-heal.** `createFromDraft` CAS-expires an
178
- open checkout older than `checkout.staleOpenCheckoutMs` (new config,
179
- default 10 min) and creates a fresh one; fresh open checkouts are still
180
- returned idempotently. `expireStaleOpenCheckouts` remains the bulk cron
181
- sweep. No TTL deletes — checkout rows stay as audit history.
182
- - **`PriceChangedError` context now includes `currentPricing`** (per-line
183
- `lineId`/`quantity`/`unitPrice`/`subtotals` + `totals`) so hosts render
184
- a price diff without re-fetching the draft.
185
- - **`ctx.signal` is threaded to every mongokit call** — cancelled requests
186
- stop at the driver-call boundary (repo-core 0.6 `QueryOptions.signal`).
187
- - Peer deps: `@classytic/mongokit >= 3.16`, `@classytic/repo-core >= 0.6`.
188
-
189
- ### Added
190
-
191
- - `checkoutConfigSchema` / `CartConfig.checkout.staleOpenCheckoutMs` and
192
- `DEFAULT_STALE_OPEN_CHECKOUT_MS` export.
193
- - Documented host contract: checkout → order → `inventory.commit()`
194
- (CLAUDE.md "Host responsibilities") — `commit()` intentionally does not
195
- commit inventory holds.
196
- - Scenario 10: stale quote → `revalidate()` reprice path (`bundle` kind).
197
-
198
- ## [0.1.0]
199
-
200
- Initial release. Framework-agnostic universal cart engine — mutable drafts,
201
- locked checkout snapshots, composable pricing, and the **LineKind** strategy
202
- that handles every business variation. Zero framework dependencies.
203
-
204
- ### Exports
205
-
206
- - **`.`** (root) — `createCart(config)` engine factory, re-exports of the
207
- most-used services and types.
208
- - **`./domain`** — pure domain types: `Draft`, `Checkout`, `Line`, `Money`,
209
- validity/staleness, idempotency key shapes.
210
- - **`./kinds`** — built-in `sku` LineKind + the generic `LineKind<T>` contract.
211
- - **`./ports`** — 5 bridge ports: `CatalogBridge` (required), `InventoryBridge`,
212
- `PromotionsBridge`, `TaxBridge`, `ShippingBridge`.
213
- - **`./errors`** — typed error classes (`DraftNotFoundError`,
214
- `PriceChangedError`, `InventoryReservationError`, etc.).
215
- - **`./events`** — `cartEventDefinitions`, `OutboxRepository`, payload map;
216
- arc-compatible structural types (no arc import).
217
- - **`./saga`** — checkout state machine (`open → finalized | canceled`),
218
- transition helpers.
219
- - **`./engine`** — engine internals for hosts that want to reach past the
220
- factory.
221
- - **`./schemas`** — Zod schemas for `createCart()` config; exported for hosts
222
- that validate config from env or a database.
223
-
224
- ### Peer dependencies
225
-
226
- - `@classytic/mongokit >= 3.11` — repositories extend `Repository<T>` directly.
227
- - `@classytic/primitives >= 0.1` — `Money`, `OperationContext`, events.
228
- - `@classytic/repo-core >= 0.2` — shared repository abstractions.
229
- - `mongoose >= 9.4` · `zod >= 4`.
230
-
231
- ### Design
232
-
233
- - **No modes / no tiers.** Features light up based on which bridges the host
234
- passes to `createCart()`. Catalog bridge is required; inventory, promo, tax,
235
- shipping are opt-in.
236
- - **Denormalized display snapshot** on every line (`display.name`,
237
- `imageUrl`, `variantLabel`, `compareAtPrice`, `capturedAt`) captured at
238
- add-time by `kind.displayOf()`. UI reads the cart with zero `.populate()`
239
- calls. Drift is cosmetic; price drift is caught via `pricingHash` at checkout.
240
- - **Checkout state machine: 3 states, 2 transitions.** `open → finalized`
241
- (host called `commit`) or `open → canceled`. No payment state inside cart.
242
- - **Idempotent + typed.** Every mutation accepts an idempotency key.
243
- Operations are pure async functions with serializable inputs — agent-ready.
244
- - **Arc-compatible events.** `cartEventDefinitions` are structurally
245
- compatible with arc's `EventDefinitionOutput`; `OutboxRepository` implements
246
- arc's `OutboxStore` without importing arc.
9
+ - Idempotency and reservation repositories read through typed `lean<T>()` results and the id port reads `globalThis.crypto` without a cast. No behaviour change. Consumers: none to change.
@@ -1782,7 +1782,7 @@ var IdempotencyRepository = class extends Repository {
1782
1782
  /** Look up a record by the full composite identity. */
1783
1783
  async findByIdentity(identity, ctx) {
1784
1784
  const session = ctx.session;
1785
- return await this.Model.findOne({
1785
+ return this.Model.findOne({
1786
1786
  organizationId: identity.organizationId,
1787
1787
  cartRef: identity.cartRef,
1788
1788
  operation: identity.operation,
@@ -1799,12 +1799,13 @@ var IdempotencyRepository = class extends Repository {
1799
1799
  async insertInFlight(identity, leaseToken, leaseExpiresAt, ctx) {
1800
1800
  const session = ctx.session;
1801
1801
  try {
1802
- return (await this.Model.create([{
1802
+ const [inserted] = await this.Model.create([{
1803
1803
  ...identity,
1804
1804
  status: "in_flight",
1805
1805
  leaseToken,
1806
1806
  leaseExpiresAt
1807
- }], { session }))[0];
1807
+ }], { session });
1808
+ return inserted ?? null;
1808
1809
  } catch (err) {
1809
1810
  if (isDuplicateKeyError(err)) return null;
1810
1811
  throw err;
@@ -1930,7 +1931,7 @@ var CartEventPublisher = class {
1930
1931
  var ReservationRepository = class extends Repository {
1931
1932
  /** All reservations belonging to a checkout. */
1932
1933
  async findByCheckout(checkoutId, ctx) {
1933
- return await this.findAll({ checkoutId }, this.readOptions(ctx));
1934
+ return this.findAll({ checkoutId }, this.readOptions(ctx));
1934
1935
  }
1935
1936
  /**
1936
1937
  * Expired held reservations for the sweeper. Routed through `getAll` so
@@ -1,3 +1,3 @@
1
- import { n as defineCart, r as InProcessCartEventBus, t as createCartDomain } from "../define-cart-CxIG6Omt.mjs";
1
+ import { n as defineCart, r as InProcessCartEventBus, t as createCartDomain } from "../define-cart-BKV3M4pm.mjs";
2
2
  import { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
3
3
  export { InProcessCartEventBus, cartConfigSchema, checkoutConfigSchema, createCartDomain, defineCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
package/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@ import { t as StateTransitionError } from "./state-transition.error-BssJiRoW.mjs
7
7
  import { n as CartEvents, t as createCartEvent } from "./domain-event-DBFsiHNJ.mjs";
8
8
  import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "./outbox-store-DLxCPOUN.mjs";
9
9
  import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-DYAnXbfV.mjs";
10
- import { _ as PENDING_EVENTS, a as ReservationRepository, c as runPricing, d as defineCartModels, f as buildReservationSchema, g as flushPending, h as buildCheckoutSchema, i as createCartRepositories, l as CheckoutRepository, m as buildDraftSchema, n as defineCart, o as IdempotencyRepository, p as buildIdempotencySchema, r as InProcessCartEventBus, s as DraftRepository, t as createCartDomain, u as DEFAULT_STALE_OPEN_CHECKOUT_MS } from "./define-cart-CxIG6Omt.mjs";
10
+ import { _ as PENDING_EVENTS, a as ReservationRepository, c as runPricing, d as defineCartModels, f as buildReservationSchema, g as flushPending, h as buildCheckoutSchema, i as createCartRepositories, l as CheckoutRepository, m as buildDraftSchema, n as defineCart, o as IdempotencyRepository, p as buildIdempotencySchema, r as InProcessCartEventBus, s as DraftRepository, t as createCartDomain, u as DEFAULT_STALE_OPEN_CHECKOUT_MS } from "./define-cart-BKV3M4pm.mjs";
11
11
  import { t as createKindRegistry } from "./kind-registry-DQYqRQZU.mjs";
12
12
  import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-wunwhjap.mjs";
13
13
  import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "./variant.kind-_LIXlTwp.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/cart",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Framework-agnostic universal cart engine for commerce — drafts, checkouts, reservations, the LineKind strategy, and a disciplined finalization saga. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
5
5
  "author": "Classytic",
6
6
  "type": "module",
@@ -92,22 +92,22 @@
92
92
  "release": "npm run push -- main && npm run release:tag && npm publish"
93
93
  },
94
94
  "peerDependencies": {
95
- "@classytic/mongokit": ">=3.41.0",
96
- "@classytic/primitives": ">=0.32.0",
97
- "@classytic/repo-core": ">=0.31.0",
98
- "mongoose": ">=9.11.0",
95
+ "@classytic/mongokit": ">=3.47.0",
96
+ "@classytic/primitives": ">=0.39.0",
97
+ "@classytic/repo-core": ">=0.39.0",
98
+ "mongoose": ">=9.13.1",
99
99
  "zod": ">=4.0.0"
100
100
  },
101
101
  "devDependencies": {
102
102
  "@biomejs/biome": "^2.5.15",
103
103
  "@classytic/dev-tools": "^0.2.1",
104
- "@classytic/mongokit": "^3.42.0",
105
- "@classytic/primitives": "^0.33.0",
106
- "@classytic/repo-core": "^0.31.1",
104
+ "@classytic/mongokit": "^3.47.0",
105
+ "@classytic/primitives": "^0.39.0",
106
+ "@classytic/repo-core": "^0.39.0",
107
107
  "@types/node": "^26.6.5",
108
108
  "knip": "^6.41.0",
109
- "mongodb-memory-server": "^11.3.0",
110
- "mongoose": "^9.11.2",
109
+ "mongodb-memory-server": "^11.4.0",
110
+ "mongoose": "^9.13.1",
111
111
  "publint": "^0.3.25",
112
112
  "tsdown": "^0.23.1",
113
113
  "typescript": "^7.0.2",