@classytic/cart 0.2.0 → 0.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 +154 -88
- package/dist/{clock.port-BUe6Dk_M.d.mts → clock.port-CNu2wgdA.d.mts} +13 -1
- package/dist/{create-cart-Iqvlv0V2.mjs → create-cart-zgAh3UVt.mjs} +152 -24
- package/dist/domain/errors/index.d.mts +2 -2
- package/dist/domain/errors/index.mjs +3 -3
- package/dist/domain/index.d.mts +7 -7
- package/dist/domain/index.mjs +5 -5
- package/dist/domain/ports/index.d.mts +1 -1
- package/dist/domain/saga/index.d.mts +1 -1
- package/dist/domain/saga/index.mjs +1 -1
- package/dist/engine/cart-config.schema.mjs +2 -1
- package/dist/engine/index.d.mts +1 -1
- package/dist/engine/index.mjs +1 -1
- package/dist/{errors-7Pd0yATM.mjs → errors-BNPgUilS.mjs} +0 -3
- package/dist/{index-qfN8dZN9.d.mts → index-wh5Q7UY1.d.mts} +45 -3
- package/dist/index.d.mts +22 -11
- package/dist/index.mjs +8 -8
- package/dist/{internal-event-bus-vMG6v-e6.d.mts → internal-event-bus-DFcwV79F.d.mts} +37 -5
- package/dist/{kind-registry-D03c2VV5.d.mts → kind-registry-DG2iCCH1.d.mts} +1 -1
- package/dist/kinds/index.d.mts +1 -1
- package/dist/kinds/index.mjs +1 -1
- package/dist/{line-kind-CKOWafK0.d.mts → line-kind-B1mU1iJp.d.mts} +1 -1
- package/dist/{reservation.entity-WdaZCJg9.d.mts → reservation.entity-DLMxgpLE.d.mts} +3 -3
- package/dist/{state-transitions-D8CRykBv.d.mts → state-transitions-D19wZe-w.d.mts} +2 -2
- package/dist/{stale-quote.error-BkFLXWo5.mjs → unmanaged-session.error-C9Z1Yh9j.mjs} +31 -1
- package/dist/{variant.kind-z2gwH9Vo.mjs → variant.kind-BHiivO9B.mjs} +2 -1
- package/dist/{variant.kind-Cpo_Hh7G.d.mts → variant.kind-q-yv-vnQ.d.mts} +1 -1
- package/package.json +7 -7
- /package/dist/{kind-registry-C99h_-8t.mjs → kind-registry-Bvrj3P1Q.mjs} +0 -0
- /package/dist/{state-transitions-Bm3lC2Uv.mjs → state-transitions-Defw8gAt.mjs} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,91 +1,157 @@
|
|
|
1
|
-
# Changelog
|
|
1
|
+
# Changelog
|
|
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).
|
|
5
|
+
|
|
6
|
+
## [0.3.1] — 2026-07-16
|
|
2
7
|
|
|
3
|
-
|
|
4
|
-
adhering to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
8
|
+
### Fixed
|
|
5
9
|
|
|
6
|
-
|
|
10
|
+
- injectTenantField no longer force-indexes the tenant field: the compound
|
|
11
|
+
prepend makes the tenant the leading key of every index, so the bare single
|
|
12
|
+
was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
|
|
13
|
+
index audit). A dedicated tenant index is still created when a schema
|
|
14
|
+
declares no compounds to prepend. Index-declaration change only.
|
|
7
15
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
`
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
-
|
|
57
|
-
|
|
58
|
-
-
|
|
59
|
-
`
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
-
|
|
90
|
-
|
|
91
|
-
|
|
16
|
+
## [0.3.0] — unpublished (2026-07-15)
|
|
17
|
+
|
|
18
|
+
### Changed — kit refresh (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
|
|
19
|
+
|
|
20
|
+
- Verified against the mongokit 3.22 sweep. DEFERRED (design note, not a
|
|
21
|
+
drive-by): checkout `finalize`/`cancel` are assert-then-`updateWithVersion`
|
|
22
|
+
— the version CAS serializes writers, so the window is narrow; converting
|
|
23
|
+
to `applyTransition` (state+version compound CAS) needs a pass that
|
|
24
|
+
preserves the updateWithVersion helper's semantics.
|
|
25
|
+
|
|
26
|
+
## [0.2.1] - 2026-07-02
|
|
27
|
+
|
|
28
|
+
### Changed (behavioral) — 2026-07-05 addendum
|
|
29
|
+
|
|
30
|
+
- **`commit()` is crash-retry convergent.** The finalize CAS runs first and
|
|
31
|
+
its tail (`markConverted` on the draft + the `cart.checkout.committed`
|
|
32
|
+
event) is non-atomic — a crash in between left the draft looking live
|
|
33
|
+
(re-checkout → duplicate order risk) with NO retry path, because a second
|
|
34
|
+
`commit()` failed the `finalized → finalized` state assertion. A retry
|
|
35
|
+
with the SAME `externalRef` (or none) now re-runs both idempotent tails
|
|
36
|
+
and returns the finalized checkout; a DIFFERENT `externalRef` throws
|
|
37
|
+
`ConcurrencyError`. `cart.checkout.committed` delivery is at-least-once —
|
|
38
|
+
subscribers must already dedupe by `checkoutId`.
|
|
39
|
+
|
|
40
|
+
### Added
|
|
41
|
+
|
|
42
|
+
- **`engine.withTransaction(ctx, body)`** — unit-of-work wrapper (transaction
|
|
43
|
+
+ post-commit event publish), the contract shared with `@classytic/refit`
|
|
44
|
+
and `@classytic/review`. Events emitted inside the unit are queued under
|
|
45
|
+
`ctx[PENDING_EVENTS]` and flushed to the in-process transport only AFTER
|
|
46
|
+
commit — a rollback or retry can't leak ghost events. New exports:
|
|
47
|
+
`PENDING_EVENTS`, `flushPending`, `UnmanagedSessionError`; new config:
|
|
48
|
+
`allowNonTransactional` (standalone-Mongo dev fallback, explicit opt-in).
|
|
49
|
+
- **Boot capability gate** — `createCart` (full mode) asserts the backend
|
|
50
|
+
declares `capabilities.upsert` (idempotency lease pattern) at engine
|
|
51
|
+
creation instead of failing on the first checkout.
|
|
52
|
+
- **Event-catalog no-drift test** (rule 18) — every `CartEvents` constant
|
|
53
|
+
must have a Zod definition; orphan definitions also fail.
|
|
54
|
+
- **Compensation scenario test** — proves the documented
|
|
55
|
+
`cart.checkout.canceled` → `inventory.release()` host wiring end-to-end.
|
|
56
|
+
- `PriceChangedErrorContext` — formal type for the error's structured
|
|
57
|
+
context (current pricing payload), previously an untyped inline shape.
|
|
58
|
+
|
|
59
|
+
### Changed
|
|
60
|
+
|
|
61
|
+
- **`CartEventPublisher`**: a host-owned `ctx.session` without an outbox now
|
|
62
|
+
throws typed `UnmanagedSessionError` (was a plain `Error`) unless a
|
|
63
|
+
`PENDING_EVENTS` queue is attached; transport publish failures on the
|
|
64
|
+
no-session path are now swallowed and logged per P8 (the domain verb no
|
|
65
|
+
longer fails after its write landed because a transport hiccuped).
|
|
66
|
+
- Safe-integer guard on line-total arithmetic (`unitPrice × quantity`);
|
|
67
|
+
idempotency repo now uses mongokit's `isDuplicateKeyError`; `cancel()`
|
|
68
|
+
and the timeslot kind's `revalidate` carry explicit contracts (host owns
|
|
69
|
+
hold release; validity-window-only revalidation — real slot-locking via
|
|
70
|
+
`@classytic/order`'s `BookingBridge`).
|
|
71
|
+
|
|
72
|
+
## [0.2.0]
|
|
73
|
+
|
|
74
|
+
### Changed
|
|
75
|
+
|
|
76
|
+
- **`pricingHash` is now hex SHA-256** over the same canonical sorted
|
|
77
|
+
line string (was the raw concatenation). The hash is opaque — compare,
|
|
78
|
+
never parse. **Migration:** drafts priced before 0.2.0 carry old-format
|
|
79
|
+
hashes; the first checkout attempt against them raises
|
|
80
|
+
`PriceChangedError` once and the client re-fetches/re-confirms.
|
|
81
|
+
Accepted clean break.
|
|
82
|
+
- **Guest→user merge is now double-CAS atomic.** `mergeDrafts` retires the
|
|
83
|
+
source with a version CAS, then writes the target with a version CAS
|
|
84
|
+
(bounded retries) — a concurrent add-to-cart on either draft is retried
|
|
85
|
+
into the result instead of silently lost. `DraftRepository.markAbandoned`
|
|
86
|
+
gains an optional `{ expectedVersion }`; `replaceLines` gains an
|
|
87
|
+
optional `expectedVersion` input.
|
|
88
|
+
- **Zombie open checkouts self-heal.** `createFromDraft` CAS-expires an
|
|
89
|
+
open checkout older than `checkout.staleOpenCheckoutMs` (new config,
|
|
90
|
+
default 10 min) and creates a fresh one; fresh open checkouts are still
|
|
91
|
+
returned idempotently. `expireStaleOpenCheckouts` remains the bulk cron
|
|
92
|
+
sweep. No TTL deletes — checkout rows stay as audit history.
|
|
93
|
+
- **`PriceChangedError` context now includes `currentPricing`** (per-line
|
|
94
|
+
`lineId`/`quantity`/`unitPrice`/`subtotals` + `totals`) so hosts render
|
|
95
|
+
a price diff without re-fetching the draft.
|
|
96
|
+
- **`ctx.signal` is threaded to every mongokit call** — cancelled requests
|
|
97
|
+
stop at the driver-call boundary (repo-core 0.6 `QueryOptions.signal`).
|
|
98
|
+
- Peer deps: `@classytic/mongokit >= 3.16`, `@classytic/repo-core >= 0.6`.
|
|
99
|
+
|
|
100
|
+
### Added
|
|
101
|
+
|
|
102
|
+
- `checkoutConfigSchema` / `CartConfig.checkout.staleOpenCheckoutMs` and
|
|
103
|
+
`DEFAULT_STALE_OPEN_CHECKOUT_MS` export.
|
|
104
|
+
- Documented host contract: checkout → order → `inventory.commit()`
|
|
105
|
+
(CLAUDE.md "Host responsibilities") — `commit()` intentionally does not
|
|
106
|
+
commit inventory holds.
|
|
107
|
+
- Scenario 10: stale quote → `revalidate()` reprice path (`bundle` kind).
|
|
108
|
+
|
|
109
|
+
## [0.1.0]
|
|
110
|
+
|
|
111
|
+
Initial release. Framework-agnostic universal cart engine — mutable drafts,
|
|
112
|
+
locked checkout snapshots, composable pricing, and the **LineKind** strategy
|
|
113
|
+
that handles every business variation. Zero framework dependencies.
|
|
114
|
+
|
|
115
|
+
### Exports
|
|
116
|
+
|
|
117
|
+
- **`.`** (root) — `createCart(config)` engine factory, re-exports of the
|
|
118
|
+
most-used services and types.
|
|
119
|
+
- **`./domain`** — pure domain types: `Draft`, `Checkout`, `Line`, `Money`,
|
|
120
|
+
validity/staleness, idempotency key shapes.
|
|
121
|
+
- **`./kinds`** — built-in `sku` LineKind + the generic `LineKind<T>` contract.
|
|
122
|
+
- **`./ports`** — 5 bridge ports: `CatalogBridge` (required), `InventoryBridge`,
|
|
123
|
+
`PromotionsBridge`, `TaxBridge`, `ShippingBridge`.
|
|
124
|
+
- **`./errors`** — typed error classes (`DraftNotFoundError`,
|
|
125
|
+
`PriceChangedError`, `InventoryReservationError`, etc.).
|
|
126
|
+
- **`./events`** — `cartEventDefinitions`, `OutboxRepository`, payload map;
|
|
127
|
+
arc-compatible structural types (no arc import).
|
|
128
|
+
- **`./saga`** — checkout state machine (`open → finalized | canceled`),
|
|
129
|
+
transition helpers.
|
|
130
|
+
- **`./engine`** — engine internals for hosts that want to reach past the
|
|
131
|
+
factory.
|
|
132
|
+
- **`./schemas`** — Zod schemas for `createCart()` config; exported for hosts
|
|
133
|
+
that validate config from env or a database.
|
|
134
|
+
|
|
135
|
+
### Peer dependencies
|
|
136
|
+
|
|
137
|
+
- `@classytic/mongokit >= 3.11` — repositories extend `Repository<T>` directly.
|
|
138
|
+
- `@classytic/primitives >= 0.1` — `Money`, `OperationContext`, events.
|
|
139
|
+
- `@classytic/repo-core >= 0.2` — shared repository abstractions.
|
|
140
|
+
- `mongoose >= 9.4` · `zod >= 4`.
|
|
141
|
+
|
|
142
|
+
### Design
|
|
143
|
+
|
|
144
|
+
- **No modes / no tiers.** Features light up based on which bridges the host
|
|
145
|
+
passes to `createCart()`. Catalog bridge is required; inventory, promo, tax,
|
|
146
|
+
shipping are opt-in.
|
|
147
|
+
- **Denormalized display snapshot** on every line (`display.name`,
|
|
148
|
+
`imageUrl`, `variantLabel`, `compareAtPrice`, `capturedAt`) captured at
|
|
149
|
+
add-time by `kind.displayOf()`. UI reads the cart with zero `.populate()`
|
|
150
|
+
calls. Drift is cosmetic; price drift is caught via `pricingHash` at checkout.
|
|
151
|
+
- **Checkout state machine: 3 states, 2 transitions.** `open → finalized`
|
|
152
|
+
(host called `commit`) or `open → canceled`. No payment state inside cart.
|
|
153
|
+
- **Idempotent + typed.** Every mutation accepts an idempotency key.
|
|
154
|
+
Operations are pure async functions with serializable inputs — agent-ready.
|
|
155
|
+
- **Arc-compatible events.** `cartEventDefinitions` are structurally
|
|
156
|
+
compatible with arc's `EventDefinitionOutput`; `OutboxRepository` implements
|
|
157
|
+
arc's `OutboxStore` without importing arc.
|
|
@@ -163,6 +163,18 @@ interface OperationContext$1 extends Omit<OperationContext, 'organizationId' | '
|
|
|
163
163
|
*/
|
|
164
164
|
[key: string]: unknown;
|
|
165
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* Internal: key under which the post-commit event-publish queue is threaded
|
|
168
|
+
* through the context. When set, `CartEventPublisher.emit` APPENDS the event
|
|
169
|
+
* instead of publishing to the transport — the unit-of-work owner flushes
|
|
170
|
+
* the queue after its transaction commits, so a rollback can't leak ghost
|
|
171
|
+
* events to in-process subscribers. Outbox rows stay inside the transaction
|
|
172
|
+
* (the relay reads only committed rows). Same contract as
|
|
173
|
+
* `@classytic/refit` / `@classytic/review`.
|
|
174
|
+
*
|
|
175
|
+
* A Symbol so it never collides with host context fields.
|
|
176
|
+
*/
|
|
177
|
+
declare const PENDING_EVENTS: unique symbol;
|
|
166
178
|
/**
|
|
167
179
|
* Standard status vocabulary returned by every bridge's `status()` probe.
|
|
168
180
|
* See plan §3 — Saga Recovery Contract.
|
|
@@ -552,4 +564,4 @@ interface ClockPort {
|
|
|
552
564
|
/** Default system clock — passes straight through to `new Date()`. */
|
|
553
565
|
declare const systemClock: ClockPort;
|
|
554
566
|
//#endregion
|
|
555
|
-
export { OperationContext$1 as C, BridgeStatus as S,
|
|
567
|
+
export { OperationContext$1 as C, PricingSnapshot as E, BridgeStatus as S, PricedLine 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, PENDING_EVENTS as w, BridgeRef as x, PromotionsBridge as y };
|
|
@@ -1,15 +1,79 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-C9Z1Yh9j.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
|
-
import { t as createKindRegistry } from "./kind-registry-
|
|
6
|
-
import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-
|
|
5
|
+
import { t as createKindRegistry } from "./kind-registry-Bvrj3P1Q.mjs";
|
|
6
|
+
import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-Defw8gAt.mjs";
|
|
7
7
|
import { money } from "@classytic/primitives/money";
|
|
8
8
|
import { matchEventPattern } from "@classytic/primitives/events";
|
|
9
|
+
import { Repository, customIdPlugin, isDuplicateKeyError, multiTenantPlugin, prefixedId, withTransaction } from "@classytic/mongokit";
|
|
10
|
+
import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
|
|
9
11
|
import mongoose, { Schema } from "mongoose";
|
|
10
12
|
import { resolveTenantConfig } from "@classytic/repo-core/tenant";
|
|
11
|
-
import { Repository, customIdPlugin, isDuplicateKeyError, multiTenantPlugin, prefixedId } from "@classytic/mongokit";
|
|
12
13
|
import { createHash } from "node:crypto";
|
|
14
|
+
//#region src/domain/ports/common.ts
|
|
15
|
+
/**
|
|
16
|
+
* Internal: key under which the post-commit event-publish queue is threaded
|
|
17
|
+
* through the context. When set, `CartEventPublisher.emit` APPENDS the event
|
|
18
|
+
* instead of publishing to the transport — the unit-of-work owner flushes
|
|
19
|
+
* the queue after its transaction commits, so a rollback can't leak ghost
|
|
20
|
+
* events to in-process subscribers. Outbox rows stay inside the transaction
|
|
21
|
+
* (the relay reads only committed rows). Same contract as
|
|
22
|
+
* `@classytic/refit` / `@classytic/review`.
|
|
23
|
+
*
|
|
24
|
+
* A Symbol so it never collides with host context fields.
|
|
25
|
+
*/
|
|
26
|
+
const PENDING_EVENTS = Symbol.for("@classytic/cart:pendingEvents");
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/engine/run-unit.ts
|
|
29
|
+
/**
|
|
30
|
+
* runUnit — transaction + post-commit-publish discipline for hosts composing
|
|
31
|
+
* multiple cart writes into one atomic unit. Same contract as
|
|
32
|
+
* `@classytic/refit` / `@classytic/review`:
|
|
33
|
+
*
|
|
34
|
+
* 1. Events emitted inside the unit are QUEUED (`ctx[PENDING_EVENTS]`),
|
|
35
|
+
* not published — the queue flushes only after the transaction commits
|
|
36
|
+
* (and resets on retry attempts), so a rollback can't leak ghost events
|
|
37
|
+
* to in-process subscribers. Outbox rows stay inside the transaction —
|
|
38
|
+
* the relay reads only committed rows.
|
|
39
|
+
* 2. A caller-owned `ctx.session` must arrive WITH a queue (or an outbox
|
|
40
|
+
* wired on the engine) — `CartEventPublisher.emit` enforces this.
|
|
41
|
+
*/
|
|
42
|
+
async function runUnit(config, ctx, body) {
|
|
43
|
+
const internalCtx = ctx;
|
|
44
|
+
const externalQueue = internalCtx[PENDING_EVENTS];
|
|
45
|
+
if (ctx.session) return body(externalQueue ? {
|
|
46
|
+
...internalCtx,
|
|
47
|
+
[PENDING_EVENTS]: externalQueue
|
|
48
|
+
} : internalCtx);
|
|
49
|
+
const pending = [];
|
|
50
|
+
const result = await withTransaction(config.connection, async (session) => {
|
|
51
|
+
pending.length = 0;
|
|
52
|
+
return body({
|
|
53
|
+
...internalCtx,
|
|
54
|
+
session,
|
|
55
|
+
[PENDING_EVENTS]: pending
|
|
56
|
+
});
|
|
57
|
+
}, config.allowNonTransactional ? { allowFallback: true } : {});
|
|
58
|
+
await flushPending(config.eventTransport, pending, config.logger);
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Drain a `[PENDING_EVENTS]` queue through a transport after commit,
|
|
63
|
+
* swallowing per-event errors (durable delivery is the outbox's job).
|
|
64
|
+
* Hosts composing their own outer transaction call this after commit;
|
|
65
|
+
* most should use `engine.withTransaction(ctx, fn)` instead.
|
|
66
|
+
*/
|
|
67
|
+
async function flushPending(eventTransport, events, logger) {
|
|
68
|
+
if (!eventTransport || events.length === 0) return;
|
|
69
|
+
const log = logger ?? console;
|
|
70
|
+
for (const event of events) try {
|
|
71
|
+
await eventTransport.publish(event);
|
|
72
|
+
} catch (err) {
|
|
73
|
+
log.error(`[cart] publish failed for ${event.type}:`, err);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
13
77
|
//#region src/models/checkout.model.ts
|
|
14
78
|
function createCheckoutModel(connection, opts = {}) {
|
|
15
79
|
const schema = new Schema({
|
|
@@ -55,7 +119,9 @@ function createCheckoutModel(connection, opts = {}) {
|
|
|
55
119
|
currency: {
|
|
56
120
|
type: String,
|
|
57
121
|
required: true,
|
|
58
|
-
|
|
122
|
+
uppercase: true,
|
|
123
|
+
trim: true,
|
|
124
|
+
match: [CURRENCY_PATTERN, "ISO 4217 (3 uppercase letters)"]
|
|
59
125
|
},
|
|
60
126
|
pricing: {
|
|
61
127
|
type: Schema.Types.Mixed,
|
|
@@ -94,7 +160,7 @@ function createCheckoutModel(connection, opts = {}) {
|
|
|
94
160
|
draftId: 1,
|
|
95
161
|
state: 1
|
|
96
162
|
});
|
|
97
|
-
const collection =
|
|
163
|
+
const collection = `${opts.collectionPrefix ?? ""}cart_checkouts`;
|
|
98
164
|
return connection.model("CartCheckout", schema, collection);
|
|
99
165
|
}
|
|
100
166
|
//#endregion
|
|
@@ -241,7 +307,9 @@ function createDraftModel(connection, opts = {}) {
|
|
|
241
307
|
currency: {
|
|
242
308
|
type: String,
|
|
243
309
|
required: true,
|
|
244
|
-
|
|
310
|
+
uppercase: true,
|
|
311
|
+
trim: true,
|
|
312
|
+
match: [CURRENCY_PATTERN, "ISO 4217 (3 uppercase letters)"]
|
|
245
313
|
},
|
|
246
314
|
pricing: {
|
|
247
315
|
type: Schema.Types.Mixed,
|
|
@@ -280,7 +348,7 @@ function createDraftModel(connection, opts = {}) {
|
|
|
280
348
|
expireAfterSeconds: 0,
|
|
281
349
|
partialFilterExpression: { expiresAt: { $exists: true } }
|
|
282
350
|
});
|
|
283
|
-
const collection =
|
|
351
|
+
const collection = `${opts.collectionPrefix ?? ""}cart_drafts`;
|
|
284
352
|
return connection.model("CartDraft", schema, collection);
|
|
285
353
|
}
|
|
286
354
|
//#endregion
|
|
@@ -359,7 +427,7 @@ function createIdempotencyModel(connection, opts = {}) {
|
|
|
359
427
|
idempotencyKey: 1
|
|
360
428
|
}, { unique: true });
|
|
361
429
|
schema.index({ createdAt: 1 }, { expireAfterSeconds: 1440 * 60 });
|
|
362
|
-
const collection =
|
|
430
|
+
const collection = `${opts.collectionPrefix ?? ""}cart_idempotency`;
|
|
363
431
|
return connection.model("CartIdempotency", schema, collection);
|
|
364
432
|
}
|
|
365
433
|
//#endregion
|
|
@@ -393,7 +461,6 @@ function injectTenantField(schema, tenant) {
|
|
|
393
461
|
schema.add({ [tenant.tenantField]: {
|
|
394
462
|
type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
|
|
395
463
|
...tenant.enabled && tenant.required ? { required: true } : {},
|
|
396
|
-
index: true,
|
|
397
464
|
...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
|
|
398
465
|
} });
|
|
399
466
|
if (!tenant.enabled || !isFieldStrategy) return;
|
|
@@ -405,6 +472,7 @@ function injectTenantField(schema, tenant) {
|
|
|
405
472
|
for (const [key, val] of Object.entries(fields)) newFields[key] = val;
|
|
406
473
|
indexEntry[0] = newFields;
|
|
407
474
|
}
|
|
475
|
+
if (!(existingIndexes ?? []).some(([fields]) => Object.keys(fields)[0] === tenant.tenantField)) schema.index({ [tenant.tenantField]: 1 });
|
|
408
476
|
}
|
|
409
477
|
//#endregion
|
|
410
478
|
//#region src/models/reservation.model.ts
|
|
@@ -489,7 +557,7 @@ function createReservationModel(connection, opts = {}) {
|
|
|
489
557
|
expiresAt: 1
|
|
490
558
|
});
|
|
491
559
|
schema.index({ checkoutId: 1 });
|
|
492
|
-
const collection =
|
|
560
|
+
const collection = `${opts.collectionPrefix ?? ""}cart_reservations`;
|
|
493
561
|
return connection.model("CartReservation", schema, collection);
|
|
494
562
|
}
|
|
495
563
|
//#endregion
|
|
@@ -541,10 +609,12 @@ var CartEventPublisher = class {
|
|
|
541
609
|
events;
|
|
542
610
|
outbox;
|
|
543
611
|
clock;
|
|
612
|
+
logger;
|
|
544
613
|
constructor(deps) {
|
|
545
614
|
this.events = deps.events;
|
|
546
615
|
this.outbox = deps.outbox;
|
|
547
616
|
this.clock = deps.clock;
|
|
617
|
+
this.logger = deps.logger ?? console;
|
|
548
618
|
}
|
|
549
619
|
async emit(type, payload, ctx, options = {}) {
|
|
550
620
|
const event = createCartEvent(type, {
|
|
@@ -562,9 +632,18 @@ var CartEventPublisher = class {
|
|
|
562
632
|
correlationId: ctx.correlationId,
|
|
563
633
|
aggregate: options.aggregate
|
|
564
634
|
});
|
|
635
|
+
const pending = ctx[PENDING_EVENTS];
|
|
565
636
|
if (this.outbox) await this.outbox.save(event, { session: ctx.session });
|
|
566
|
-
else if (ctx.session) throw new
|
|
567
|
-
if (
|
|
637
|
+
else if (ctx.session && !pending) throw new UnmanagedSessionError();
|
|
638
|
+
if (pending) {
|
|
639
|
+
pending.push(event);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
if (!ctx.session) try {
|
|
643
|
+
await this.events.publish(event);
|
|
644
|
+
} catch (err) {
|
|
645
|
+
this.logger.error(`[cart] transport publish failed for ${event.type}:`, err);
|
|
646
|
+
}
|
|
568
647
|
}
|
|
569
648
|
};
|
|
570
649
|
//#endregion
|
|
@@ -706,6 +785,28 @@ var CheckoutRepository = class extends Repository {
|
|
|
706
785
|
lean: true,
|
|
707
786
|
throwOnNotFound: false
|
|
708
787
|
});
|
|
788
|
+
if (checkout.state === "finalized") {
|
|
789
|
+
if (!(input.externalRef === void 0 || (checkout.externalRef ?? null) === input.externalRef)) throw new ConcurrencyError("checkout", checkout.version, checkout.publicId);
|
|
790
|
+
await this.draftRepo.markConverted(checkout.draftId, ctx);
|
|
791
|
+
const pricingPrev = checkout.pricing;
|
|
792
|
+
await this.eventPublisher.emit(CartEvents.CHECKOUT_COMMITTED, {
|
|
793
|
+
checkoutId: checkout.publicId,
|
|
794
|
+
draftId: draft?.publicId ?? String(checkout.draftId),
|
|
795
|
+
externalRef: checkout.externalRef ?? null,
|
|
796
|
+
grandTotal: pricingPrev.totals?.grandTotal ?? {
|
|
797
|
+
amount: 0,
|
|
798
|
+
currency: checkout.currency
|
|
799
|
+
}
|
|
800
|
+
}, ctx, {
|
|
801
|
+
resource: "checkout",
|
|
802
|
+
resourceId: checkout.publicId,
|
|
803
|
+
aggregate: {
|
|
804
|
+
type: "checkout",
|
|
805
|
+
id: checkout.publicId
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
return checkout;
|
|
809
|
+
}
|
|
709
810
|
CHECKOUT_MACHINE.assertTransition(checkout.publicId, checkout.state, "finalized");
|
|
710
811
|
const nowIso = this.clock.now().toISOString();
|
|
711
812
|
const updated = await this.updateWithVersion(checkout._id, checkout.version, {
|
|
@@ -737,6 +838,15 @@ var CheckoutRepository = class extends Repository {
|
|
|
737
838
|
});
|
|
738
839
|
return updated;
|
|
739
840
|
}
|
|
841
|
+
/**
|
|
842
|
+
* Transition open → canceled and record the reason.
|
|
843
|
+
*
|
|
844
|
+
* ⚠ Cart does NOT release inventory holds here — the HOST owns that
|
|
845
|
+
* compensation (it owns the reserve/commit sequencing too). Subscribe to
|
|
846
|
+
* `cart.checkout.canceled` and call `inventory.release(reservationRefs)`,
|
|
847
|
+
* or call it inline right after this method. Forgetting this strands
|
|
848
|
+
* holds until their TTL backstop — the classic integration leak.
|
|
849
|
+
*/
|
|
740
850
|
async cancel(input, ctx) {
|
|
741
851
|
const checkout = await this.requireCheckout(input.checkoutPublicId, ctx);
|
|
742
852
|
CHECKOUT_MACHINE.assertTransition(checkout.publicId, checkout.state, "canceled");
|
|
@@ -1096,8 +1206,10 @@ function canReuse(line, prior) {
|
|
|
1096
1206
|
*/
|
|
1097
1207
|
function rebuildSubtotals(prior, line, currency) {
|
|
1098
1208
|
const unitPrice = prior.unitPrice;
|
|
1209
|
+
const rawTotal = unitPrice.amount * line.quantity;
|
|
1210
|
+
if (!Number.isSafeInteger(rawTotal)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${line.quantity} exceeds Number.MAX_SAFE_INTEGER`);
|
|
1099
1211
|
const lineTotal = {
|
|
1100
|
-
amount:
|
|
1212
|
+
amount: rawTotal,
|
|
1101
1213
|
currency
|
|
1102
1214
|
};
|
|
1103
1215
|
return {
|
|
@@ -1616,7 +1728,7 @@ var IdempotencyRepository = class extends Repository {
|
|
|
1616
1728
|
leaseExpiresAt
|
|
1617
1729
|
}], { session }))[0];
|
|
1618
1730
|
} catch (err) {
|
|
1619
|
-
if (isDuplicateKeyError
|
|
1731
|
+
if (isDuplicateKeyError(err)) return null;
|
|
1620
1732
|
throw err;
|
|
1621
1733
|
}
|
|
1622
1734
|
}
|
|
@@ -1685,11 +1797,6 @@ var IdempotencyRepository = class extends Repository {
|
|
|
1685
1797
|
}) ?? null;
|
|
1686
1798
|
}
|
|
1687
1799
|
};
|
|
1688
|
-
function isDuplicateKeyError$1(err) {
|
|
1689
|
-
if (!err || typeof err !== "object") return false;
|
|
1690
|
-
const code = err.code;
|
|
1691
|
-
return code === 11e3 || code === 11001;
|
|
1692
|
-
}
|
|
1693
1800
|
//#endregion
|
|
1694
1801
|
//#region src/repositories/reservation.repository.ts
|
|
1695
1802
|
/**
|
|
@@ -1700,9 +1807,6 @@ function isDuplicateKeyError$1(err) {
|
|
|
1700
1807
|
* sweeper drives the active release loop via `findExpiredHeld`.
|
|
1701
1808
|
*/
|
|
1702
1809
|
var ReservationRepository = class extends Repository {
|
|
1703
|
-
constructor(model, plugins) {
|
|
1704
|
-
super(model, plugins);
|
|
1705
|
-
}
|
|
1706
1810
|
/** All reservations belonging to a checkout. */
|
|
1707
1811
|
async findByCheckout(checkoutId, ctx) {
|
|
1708
1812
|
return await this.findAll({ checkoutId }, this.readOptions(ctx));
|
|
@@ -1889,6 +1993,19 @@ var InProcessCartEventBus = class {
|
|
|
1889
1993
|
};
|
|
1890
1994
|
//#endregion
|
|
1891
1995
|
//#region src/engine/create-cart.ts
|
|
1996
|
+
/** Runtime capabilities cart's atomic paths require at boot (full mode). */
|
|
1997
|
+
const REQUIRED_CAPABILITIES = ["upsert"];
|
|
1998
|
+
/**
|
|
1999
|
+
* Boot gate (PACKAGE_RULES "Runtime capabilities") — the idempotency store's
|
|
2000
|
+
* insert-in-flight/lease pattern needs atomic upserts; fail loud at engine
|
|
2001
|
+
* creation, not with a cryptic driver error on the first checkout.
|
|
2002
|
+
*/
|
|
2003
|
+
function assertCartCapabilities(repositories) {
|
|
2004
|
+
const caps = repositories.draft.capabilities;
|
|
2005
|
+
if (!caps) throw new Error("createCart: the wired repository backend declares no `capabilities` descriptor (repo-core 0.6 / mongokit 3.16+). Upgrade the kit.");
|
|
2006
|
+
const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
|
|
2007
|
+
if (missing.length > 0) throw new Error(`createCart: backend missing required capabilities: ${missing.join(", ")}. The idempotency lease pattern needs atomic upserts.`);
|
|
2008
|
+
}
|
|
1892
2009
|
/**
|
|
1893
2010
|
* createCart() — build a cart engine.
|
|
1894
2011
|
*
|
|
@@ -1935,8 +2052,10 @@ async function createCart(config) {
|
|
|
1935
2052
|
multiTenant,
|
|
1936
2053
|
staleOpenCheckoutMs: config.checkout?.staleOpenCheckoutMs
|
|
1937
2054
|
});
|
|
2055
|
+
assertCartCapabilities(repositories);
|
|
1938
2056
|
mode = "full";
|
|
1939
2057
|
}
|
|
2058
|
+
const allowNonTransactional = config.allowNonTransactional ?? false;
|
|
1940
2059
|
return {
|
|
1941
2060
|
config: Object.freeze({ ...config }),
|
|
1942
2061
|
kinds,
|
|
@@ -1946,6 +2065,15 @@ async function createCart(config) {
|
|
|
1946
2065
|
models,
|
|
1947
2066
|
repositories,
|
|
1948
2067
|
mode,
|
|
2068
|
+
withTransaction(ctx, body) {
|
|
2069
|
+
if (mode !== "full") throw new Error("cart.withTransaction requires full mode (a real Mongoose connection)");
|
|
2070
|
+
return runUnit({
|
|
2071
|
+
connection: config.connection,
|
|
2072
|
+
eventTransport: events,
|
|
2073
|
+
logger: console,
|
|
2074
|
+
allowNonTransactional
|
|
2075
|
+
}, ctx, body);
|
|
2076
|
+
},
|
|
1949
2077
|
async syncIndexes() {
|
|
1950
2078
|
await Promise.all(Object.values(models).map((m) => m.createIndexes()));
|
|
1951
2079
|
},
|
|
@@ -1953,4 +2081,4 @@ async function createCart(config) {
|
|
|
1953
2081
|
};
|
|
1954
2082
|
}
|
|
1955
2083
|
//#endregion
|
|
1956
|
-
export { IdempotencyRepository as a, CheckoutRepository as c, createReservationModel as d, createIdempotencyModel as f, ReservationRepository as i, DEFAULT_STALE_OPEN_CHECKOUT_MS as l, createCheckoutModel as m, InProcessCartEventBus as n, DraftRepository as o, createDraftModel as p, createCartRepositories as r, runPricing as s, createCart as t, createCartModels as u };
|
|
2084
|
+
export { IdempotencyRepository as a, CheckoutRepository as c, createReservationModel as d, createIdempotencyModel as f, PENDING_EVENTS as g, flushPending as h, ReservationRepository as i, DEFAULT_STALE_OPEN_CHECKOUT_MS as l, createCheckoutModel as m, InProcessCartEventBus as n, DraftRepository as o, createDraftModel as p, createCartRepositories as r, runPricing as s, createCart as t, createCartModels as u };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
export { CartError, CartErrorCategory, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, SagaFailurePhase, StaleQuoteError, StateTransitionError, UnknownKindError };
|
|
1
|
+
import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "../../index-wh5Q7UY1.mjs";
|
|
2
|
+
export { CartError, CartErrorCategory, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, SagaFailurePhase, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as CartError } from "../../cart.error-BwWy4RlY.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "../../unmanaged-session.error-C9Z1Yh9j.mjs";
|
|
3
3
|
import { n as UnknownKindError, t as KindError } from "../../kind.error-DIaJpdUb.mjs";
|
|
4
|
-
import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../../errors-
|
|
4
|
+
import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../../errors-BNPgUilS.mjs";
|
|
5
5
|
import { t as StateTransitionError } from "../../state-transition.error-2fRLh3p0.mjs";
|
|
6
|
-
export { CartError, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError };
|
|
6
|
+
export { CartError, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, KindError, NotFoundError, PriceChangedError, ReservationError, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError };
|
package/dist/domain/index.d.mts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "../index-wh5Q7UY1.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 OperationContext, S as BridgeStatus, T as
|
|
6
|
-
import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-
|
|
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-
|
|
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-
|
|
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-
|
|
5
|
+
import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, x as BridgeRef, y as PromotionsBridge } from "../clock.port-CNu2wgdA.mjs";
|
|
6
|
+
import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "../reservation.entity-DLMxgpLE.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-D19wZe-w.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-B1mU1iJp.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-DG2iCCH1.mjs";
|
|
10
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
|
-
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 };
|
|
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, UnmanagedSessionError, type ValidityPolicy, addMoney, cartEventDefinitions, cartEventsByName, createCartEvent, createCartEventRegistry, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCartEvent, fromMajor, isLegalCheckoutTransition, money, multiplyMoney, subtractMoney, sumMoney, systemClock, toMajor };
|
package/dist/domain/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 {
|
|
3
|
+
import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "../unmanaged-session.error-C9Z1Yh9j.mjs";
|
|
4
4
|
import { n as UnknownKindError, t as KindError } from "../kind.error-DIaJpdUb.mjs";
|
|
5
|
-
import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../errors-
|
|
5
|
+
import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "../errors-BNPgUilS.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
|
-
import { t as createKindRegistry } from "../kind-registry-
|
|
11
|
-
import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../state-transitions-
|
|
10
|
+
import { t as createKindRegistry } from "../kind-registry-Bvrj3P1Q.mjs";
|
|
11
|
+
import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../state-transitions-Defw8gAt.mjs";
|
|
12
12
|
import "./events/index.mjs";
|
|
13
13
|
import "./ports/index.mjs";
|
|
14
14
|
import "./saga/index.mjs";
|
|
15
15
|
import { addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
|
|
16
|
-
export { CART_REF_NEW, CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutStep, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PriceChangedError, ReservationError, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, addMoney, cartEventDefinitions, cartEventsByName, createCartEvent, createCartEventRegistry, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCartEvent, fromMajor, isLegalCheckoutTransition, money, multiplyMoney, subtractMoney, sumMoney, systemClock, toMajor };
|
|
16
|
+
export { CART_REF_NEW, CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutStep, ConcurrencyError, IdempotencyBusyError, IdempotencyStorageError, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PriceChangedError, ReservationError, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError, addMoney, cartEventDefinitions, cartEventsByName, createCartEvent, createCartEventRegistry, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCartEvent, fromMajor, isLegalCheckoutTransition, money, multiplyMoney, subtractMoney, sumMoney, systemClock, toMajor };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { C as OperationContext, S as BridgeStatus, _ as CartSnapshot, a as ShippingQuote, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, x as BridgeRef, y as PromotionsBridge } from "../../clock.port-
|
|
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-CNu2wgdA.mjs";
|
|
2
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-
|
|
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-D19wZe-w.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-
|
|
1
|
+
import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition, t as CHECKOUT_MACHINE } from "../../state-transitions-Defw8gAt.mjs";
|
|
2
2
|
export { CHECKOUT_MACHINE, CHECKOUT_STATE_TRANSITIONS, CheckoutStep, isLegalCheckoutTransition };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
|
|
1
2
|
import { z } from "zod";
|
|
2
3
|
//#region src/engine/cart-config.schema.ts
|
|
3
4
|
/**
|
|
@@ -34,7 +35,7 @@ contextKey: z.string().default("organizationId") });
|
|
|
34
35
|
const cartConfigSchema = z.object({
|
|
35
36
|
scope: scopeConfigSchema.default({ contextKey: "organizationId" }),
|
|
36
37
|
/** Default currency if a draft is created with no currency set. */
|
|
37
|
-
defaultCurrency: z.string().
|
|
38
|
+
defaultCurrency: z.string().regex(CURRENCY_PATTERN, "ISO 4217 (3 uppercase letters)").default("USD"),
|
|
38
39
|
idempotency: idempotencyConfigSchema.default({
|
|
39
40
|
inlineThresholdBytes: 12 * 1024,
|
|
40
41
|
leaseMs: 3e4,
|
package/dist/engine/index.d.mts
CHANGED
|
@@ -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-
|
|
2
|
+
import { a as CartEngine, i as CartConfig, n as createCart, r as CartBridges, t as InProcessCartEventBus } from "../internal-event-bus-DFcwV79F.mjs";
|
|
3
3
|
export { type CartBridges, type CartConfig, type CartConfigShape, type CartEngine, InProcessCartEventBus, cartConfigSchema, createCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
|
package/dist/engine/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as InProcessCartEventBus, t as createCart } from "../create-cart-
|
|
1
|
+
import { n as InProcessCartEventBus, t as createCart } from "../create-cart-zgAh3UVt.mjs";
|
|
2
2
|
import { cartConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./cart-config.schema.mjs";
|
|
3
3
|
export { InProcessCartEventBus, cartConfigSchema, createCart, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema };
|
|
@@ -64,9 +64,6 @@ var IdempotencyStorageError = class extends CartError {
|
|
|
64
64
|
code = "cart/idempotency_storage_corruption";
|
|
65
65
|
category = "system";
|
|
66
66
|
retryable = false;
|
|
67
|
-
constructor(message, context) {
|
|
68
|
-
super(message, context);
|
|
69
|
-
}
|
|
70
67
|
};
|
|
71
68
|
//#endregion
|
|
72
69
|
export { ReservationError as i, IdempotencyStorageError as n, SagaError as r, IdempotencyBusyError as t };
|
|
@@ -102,6 +102,21 @@ declare class NotFoundError extends CartError {
|
|
|
102
102
|
}
|
|
103
103
|
//#endregion
|
|
104
104
|
//#region src/domain/errors/price-changed.error.d.ts
|
|
105
|
+
/**
|
|
106
|
+
* Structured context carried on `PriceChangedError` — includes the CURRENT
|
|
107
|
+
* pricing so hosts re-display without another fetch. Formalized so a
|
|
108
|
+
* refactor of the shape is a compile error here instead of a silent client
|
|
109
|
+
* break.
|
|
110
|
+
*/
|
|
111
|
+
interface PriceChangedErrorContext extends Record<string, unknown> {
|
|
112
|
+
expectedHash: string;
|
|
113
|
+
actualHash: string;
|
|
114
|
+
draftPublicId?: string;
|
|
115
|
+
currentPricing?: {
|
|
116
|
+
lines: ReadonlyArray<Record<string, unknown>>;
|
|
117
|
+
totals: Record<string, unknown>;
|
|
118
|
+
};
|
|
119
|
+
}
|
|
105
120
|
/**
|
|
106
121
|
* The stored pricing snapshot's hash does not match the `expectedPricingHash`
|
|
107
122
|
* the client supplied when initiating checkout. Fired from the cheap hash
|
|
@@ -119,7 +134,7 @@ declare class PriceChangedError extends CartError {
|
|
|
119
134
|
readonly code = "cart/price_changed";
|
|
120
135
|
readonly category: CartErrorCategory;
|
|
121
136
|
readonly retryable = true;
|
|
122
|
-
constructor(expectedHash: string, actualHash: string, context?:
|
|
137
|
+
constructor(expectedHash: string, actualHash: string, context?: Omit<PriceChangedErrorContext, 'expectedHash' | 'actualHash'>);
|
|
123
138
|
}
|
|
124
139
|
//#endregion
|
|
125
140
|
//#region src/domain/errors/reservation.error.d.ts
|
|
@@ -190,7 +205,6 @@ declare class IdempotencyStorageError extends CartError {
|
|
|
190
205
|
readonly code = "cart/idempotency_storage_corruption";
|
|
191
206
|
readonly category: CartErrorCategory;
|
|
192
207
|
readonly retryable = false;
|
|
193
|
-
constructor(message: string, context: Record<string, unknown>);
|
|
194
208
|
}
|
|
195
209
|
//#endregion
|
|
196
210
|
//#region src/domain/errors/stale-quote.error.d.ts
|
|
@@ -229,4 +243,32 @@ declare class StateTransitionError extends CartError {
|
|
|
229
243
|
constructor(checkoutId: string, from: CheckoutState, to: CheckoutState);
|
|
230
244
|
}
|
|
231
245
|
//#endregion
|
|
232
|
-
|
|
246
|
+
//#region src/domain/errors/unmanaged-session.error.d.ts
|
|
247
|
+
/**
|
|
248
|
+
* The caller owns the outer transaction (`ctx.session`) but gave cart no way
|
|
249
|
+
* to coordinate event publishing:
|
|
250
|
+
*
|
|
251
|
+
* - no `OutboxStore` (durable row that commits WITH the transaction), AND
|
|
252
|
+
* - no `[PENDING_EVENTS]` queue (post-commit in-process flush).
|
|
253
|
+
*
|
|
254
|
+
* Publishing to in-process subscribers mid-transaction would leak ghost
|
|
255
|
+
* events on rollback, and silently dropping the event loses it entirely —
|
|
256
|
+
* both are worse than failing fast. Safe patterns:
|
|
257
|
+
*
|
|
258
|
+
* 1. `engine.withTransaction(ctx, (txCtx) => …)` — cart owns the unit of
|
|
259
|
+
* work, queues events, and flushes them after commit.
|
|
260
|
+
* 2. Wire an `outbox` — the row commits with your transaction and the
|
|
261
|
+
* host relay delivers post-commit.
|
|
262
|
+
* 3. Manage it yourself: attach `{ ...ctx, [PENDING_EVENTS]: queue }` and
|
|
263
|
+
* call `flushPending(transport, queue)` after your commit.
|
|
264
|
+
*
|
|
265
|
+
* `PENDING_EVENTS` and `flushPending` are exported from '@classytic/cart'.
|
|
266
|
+
*/
|
|
267
|
+
declare class UnmanagedSessionError extends CartError {
|
|
268
|
+
readonly code = "cart/transaction_unmanaged_session";
|
|
269
|
+
readonly category: CartErrorCategory;
|
|
270
|
+
readonly retryable = false;
|
|
271
|
+
constructor();
|
|
272
|
+
}
|
|
273
|
+
//#endregion
|
|
274
|
+
export { IdempotencyStorageError as a, ReservationError as c, KindError as d, UnknownKindError as f, CartErrorCategory as h, IdempotencyBusyError as i, PriceChangedError as l, CartError as m, StateTransitionError as n, SagaError as o, ConcurrencyError as p, StaleQuoteError as r, SagaFailurePhase as s, UnmanagedSessionError as t, NotFoundError as u };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,21 +1,32 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as IdempotencyStorageError, c as ReservationError, d as KindError, f as UnknownKindError, h as CartErrorCategory, i as IdempotencyBusyError, l as PriceChangedError, m as CartError, n as StateTransitionError, o as SagaError, p as ConcurrencyError, r as StaleQuoteError, s as SagaFailurePhase, t as UnmanagedSessionError, u as NotFoundError } from "./index-wh5Q7UY1.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 OperationContext, S as BridgeStatus, T as
|
|
6
|
-
import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-
|
|
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-
|
|
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-
|
|
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-
|
|
5
|
+
import { C as OperationContext, E as PricingSnapshot, S as BridgeStatus, T as PricedLine, _ as CartSnapshot, a as ShippingQuote, b as Address, c as TaxBridge, d as InventoryBridge, f as ReservationRef, g as AdjustmentSpec, h as ProductSummary, i as ShippingMethod, l as TaxCalculationRequest, m as CatalogBridge, n as systemClock, o as ShippingQuoteRequest, p as ReservationRequest, r as ShippingBridge, s as TaxBreakdown, t as ClockPort, u as TaxCalculationResult, v as PromotionResult, w as PENDING_EVENTS, x as BridgeRef, y as PromotionsBridge } from "./clock.port-CNu2wgdA.mjs";
|
|
6
|
+
import { a as Adjustment, i as Checkout, n as IdempotencyRecord, r as Draft, t as Reservation } from "./reservation.entity-DLMxgpLE.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-D19wZe-w.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-B1mU1iJp.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-DG2iCCH1.mjs";
|
|
10
10
|
import { n as createCounterIdPort, r as cryptoIdPort, t as IdPort } from "./id.port-DitjeoHg.mjs";
|
|
11
11
|
import { CartConfigShape, cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
|
|
12
|
-
import { C as createReservationModel, D as createDraftModel, E as DraftDocument, O as CheckoutDocument, S as ReservationDocument, T as createIdempotencyModel, _ as CartEventPublisherDeps, a as CartEngine, b as CreateCartModelsOptions, c as CreateCartRepositoriesConfig, d as IdempotencyRepository, f as CheckoutRepository, g as DraftRepositoryDeps, h as DraftRepository, i as CartConfig, k as createCheckoutModel, l as createCartRepositories, m as DEFAULT_STALE_OPEN_CHECKOUT_MS, n as createCart, o as CartRepositories, p as CheckoutRepositoryDeps, r as CartBridges, s as CartRepositoryPluginBundle, t as InProcessCartEventBus, u as ReservationRepository, v as CartModelName, w as IdempotencyDocument, x as createCartModels, y as CartModels } from "./internal-event-bus-
|
|
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-
|
|
12
|
+
import { C as createReservationModel, D as createDraftModel, E as DraftDocument, O as CheckoutDocument, S as ReservationDocument, T as createIdempotencyModel, _ as CartEventPublisherDeps, a as CartEngine, b as CreateCartModelsOptions, c as CreateCartRepositoriesConfig, d as IdempotencyRepository, f as CheckoutRepository, g as DraftRepositoryDeps, h as DraftRepository, i as CartConfig, k as createCheckoutModel, l as createCartRepositories, m as DEFAULT_STALE_OPEN_CHECKOUT_MS, n as createCart, o as CartRepositories, p as CheckoutRepositoryDeps, r as CartBridges, s as CartRepositoryPluginBundle, t as InProcessCartEventBus, u as ReservationRepository, v as CartModelName, w as IdempotencyDocument, x as createCartModels, y as CartModels } from "./internal-event-bus-DFcwV79F.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-q-yv-vnQ.mjs";
|
|
14
14
|
import { Money, addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
|
|
15
|
-
import { EventHandler, EventTransport, PublishManyResult } from "@classytic/primitives/events";
|
|
16
|
-
import { Schema } from "mongoose";
|
|
15
|
+
import { DomainEvent, EventHandler, EventTransport, EventTransport as EventTransport$1, PublishManyResult } from "@classytic/primitives/events";
|
|
16
|
+
import { Connection, Schema } from "mongoose";
|
|
17
17
|
import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
|
|
18
18
|
|
|
19
|
+
//#region src/engine/run-unit.d.ts
|
|
20
|
+
/**
|
|
21
|
+
* Drain a `[PENDING_EVENTS]` queue through a transport after commit,
|
|
22
|
+
* swallowing per-event errors (durable delivery is the outbox's job).
|
|
23
|
+
* Hosts composing their own outer transaction call this after commit;
|
|
24
|
+
* most should use `engine.withTransaction(ctx, fn)` instead.
|
|
25
|
+
*/
|
|
26
|
+
declare function flushPending(eventTransport: EventTransport$1 | undefined, events: DomainEvent[], logger?: {
|
|
27
|
+
error(message: string, ...args: unknown[]): void;
|
|
28
|
+
}): Promise<void>;
|
|
29
|
+
//#endregion
|
|
19
30
|
//#region src/services/abandonment.service.d.ts
|
|
20
31
|
/**
|
|
21
32
|
* Abandonment query primitives. Hosts call these from their own cron
|
|
@@ -141,4 +152,4 @@ type CartTenantInput = TenantConfig | boolean | {
|
|
|
141
152
|
/** Re-export of primitives' resolved shape under the legacy name. */
|
|
142
153
|
type ResolvedTenant = ResolvedTenantConfig;
|
|
143
154
|
//#endregion
|
|
144
|
-
export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBridges, type CartConfig, type CartConfigShape, type CartDomainEvent, type CartEngine, CartError, type CartErrorCategory, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventPublisherDeps, type CartEventRegistry, CartEvents, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartModelsOptions, type CreateCartRepositoriesConfig, DEFAULT_STALE_OPEN_CHECKOUT_MS, type Draft, type DraftDocument, DraftRepository, type DraftRepositoryDeps, type DraftStatus, type EventHandler, type EventSchema, type EventSchemaProperty, type EventTransport, type EventValidationResult, type EventValidator, type IdPort, IdempotencyBusyError, type IdempotencyDocument, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, type InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, type OperationContext, type OperationName, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, type PayloadOf, PriceChangedError, type PricedLine, type PricingSnapshot, type ProductSummary, type PromotionResult, type PromotionsBridge, type PublishManyResult, type Reservation, type ReservationDocument, ReservationError, type ReservationRef, ReservationRepository, type ReservationRequest, type ReservationStatus, type ResolvedTenant, type RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaStepFn, type ServiceFeePayload, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type SkuPayload, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, type TimeslotPayload, type TotalsSnapshot, UnknownKindError, type ValidityPolicy, type VariantPayload, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
|
|
155
|
+
export { type Address, type Adjustment, type AdjustmentSpec, type BridgeRef, type BridgeStatus, type BundleComponent, type BundlePayload, CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, type CartAggregateType, type CartBridges, type CartConfig, type CartConfigShape, type CartDomainEvent, type CartEngine, CartError, type CartErrorCategory, type CartEventAggregate, type CartEventDefinition, type CartEventDefinitionInput, type CartEventMap, type CartEventMeta, type CartEventName, type CartEventPayload, type CartEventPublisherDeps, type CartEventRegistry, CartEvents, type CartModelName, type CartModels, type CartRepositories, type CartRepositoryPluginBundle, type CartSnapshot, type CartTenantInput, type CatalogBridge, type Checkout, type CheckoutDocument, type CheckoutFlowState, CheckoutRepository, type CheckoutRepositoryDeps, type CheckoutState, CheckoutStep, type CheckoutStepNumber, type ClockPort, ConcurrencyError, type CreateCartModelsOptions, type CreateCartRepositoriesConfig, DEFAULT_STALE_OPEN_CHECKOUT_MS, type Draft, type DraftDocument, DraftRepository, type DraftRepositoryDeps, type DraftStatus, type EventHandler, type EventSchema, type EventSchemaProperty, type EventTransport, type EventValidationResult, type EventValidator, type IdPort, IdempotencyBusyError, type IdempotencyDocument, type IdempotencyIdentity, type IdempotencyRecord, type IdempotencyReplay, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, type InventoryBridge, type KindBridges, type KindContext, KindError, type KindRegistry, type LineDisplay, type LineItem, type LineKind, type LineLike, MemoryOutboxStore, type Money, NotFoundError, type OperationContext, type OperationName, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxErrorInfo, type OutboxFailOptions, type OutboxFailureContext, type OutboxFailureDecision, type OutboxFailurePolicy, OutboxOwnershipError, type OutboxStore, type OutboxStoreWriteOptions, type OutboxWriteOptions, PENDING_EVENTS, type PayloadOf, PriceChangedError, type PricedLine, type PricingSnapshot, type ProductSummary, type PromotionResult, type PromotionsBridge, type PublishManyResult, type Reservation, type ReservationDocument, ReservationError, type ReservationRef, ReservationRepository, type ReservationRequest, type ReservationStatus, type ResolvedTenant, type RevalidationResult, type SagaDependencies, SagaError, type SagaFailurePhase, type SagaStepFn, type ServiceFeePayload, type ShippingBridge, type ShippingMethod, type ShippingQuote, type ShippingQuoteRequest, type SkuPayload, type StaleBehavior, StaleQuoteError, type StaleTrigger, StateTransitionError, type TaxBreakdown, type TaxBridge, type TaxCalculationRequest, type TaxCalculationResult, type TimeslotPayload, type TotalsSnapshot, UnknownKindError, UnmanagedSessionError, type ValidityPolicy, type VariantPayload, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, flushPending, 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 {
|
|
3
|
+
import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-C9Z1Yh9j.mjs";
|
|
4
4
|
import { n as UnknownKindError, t as KindError } from "./kind.error-DIaJpdUb.mjs";
|
|
5
|
-
import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-
|
|
5
|
+
import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-BNPgUilS.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
|
-
import { t as
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
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-
|
|
10
|
+
import { a as IdempotencyRepository, c as CheckoutRepository, d as createReservationModel, f as createIdempotencyModel, g as PENDING_EVENTS, h as flushPending, i as ReservationRepository, l as DEFAULT_STALE_OPEN_CHECKOUT_MS, m as createCheckoutModel, n as InProcessCartEventBus, o as DraftRepository, p as createDraftModel, r as createCartRepositories, s as runPricing, t as createCart, u as createCartModels } from "./create-cart-zgAh3UVt.mjs";
|
|
11
|
+
import { t as createKindRegistry } from "./kind-registry-Bvrj3P1Q.mjs";
|
|
12
|
+
import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-Defw8gAt.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-BHiivO9B.mjs";
|
|
14
14
|
import { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
|
|
15
15
|
import { addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
|
|
16
16
|
//#region src/services/abandonment.service.ts
|
|
@@ -105,7 +105,7 @@ async function mergeDrafts(opts) {
|
|
|
105
105
|
let lastError;
|
|
106
106
|
for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {
|
|
107
107
|
const source = await repo.findByPublicId(sourcePublicId, ctx);
|
|
108
|
-
if (
|
|
108
|
+
if (source?.status !== "active") throw new Error(`Source draft '${sourcePublicId}' not found or not active`);
|
|
109
109
|
if (!await repo.findActiveByActor(targetActorRef, targetCtx)) try {
|
|
110
110
|
return await repo.updateWithVersion(source._id, source.version, {
|
|
111
111
|
actorRef: targetActorRef,
|
|
@@ -147,4 +147,4 @@ async function mergeDrafts(opts) {
|
|
|
147
147
|
throw lastError;
|
|
148
148
|
}
|
|
149
149
|
//#endregion
|
|
150
|
-
export { CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutRepository, CheckoutStep, ConcurrencyError, DEFAULT_STALE_OPEN_CHECKOUT_MS, DraftRepository, IdempotencyBusyError, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PriceChangedError, ReservationError, ReservationRepository, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
|
|
150
|
+
export { CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutRepository, CheckoutStep, ConcurrencyError, DEFAULT_STALE_OPEN_CHECKOUT_MS, DraftRepository, IdempotencyBusyError, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PENDING_EVENTS, PriceChangedError, ReservationError, ReservationRepository, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, flushPending, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-CBt9fSYh.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-
|
|
3
|
-
import { l as LineDisplay, r as LineKind } from "./line-kind-
|
|
4
|
-
import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-
|
|
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-CNu2wgdA.mjs";
|
|
3
|
+
import { l as LineDisplay, r as LineKind } from "./line-kind-B1mU1iJp.mjs";
|
|
4
|
+
import { c as LineItem, i as IdempotencyIdentity, t as KindRegistry } from "./kind-registry-DG2iCCH1.mjs";
|
|
5
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";
|
|
9
|
-
import { Connection, Document, Model, Types } from "mongoose";
|
|
10
9
|
import { PluginType, Repository } from "@classytic/mongokit";
|
|
10
|
+
import { Connection, Document, Model, Types } from "mongoose";
|
|
11
11
|
|
|
12
12
|
//#region src/models/checkout.model.d.ts
|
|
13
13
|
/**
|
|
@@ -184,11 +184,15 @@ interface CartEventPublisherDeps {
|
|
|
184
184
|
events: EventTransport;
|
|
185
185
|
outbox?: OutboxStore;
|
|
186
186
|
clock: ClockPort;
|
|
187
|
+
logger?: {
|
|
188
|
+
error(message: string, ...args: unknown[]): void;
|
|
189
|
+
} | undefined;
|
|
187
190
|
}
|
|
188
191
|
declare class CartEventPublisher {
|
|
189
192
|
private readonly events;
|
|
190
193
|
private readonly outbox?;
|
|
191
194
|
private readonly clock;
|
|
195
|
+
private readonly logger;
|
|
192
196
|
constructor(deps: CartEventPublisherDeps);
|
|
193
197
|
emit<E extends CartEventName>(type: E, payload: Omit<CartEventPayload<E>, 'emittedAt' | 'correlationId' | 'organizationId' | 'actorRef'>, ctx: OperationContext, options?: EmitOptions): Promise<void>;
|
|
194
198
|
}
|
|
@@ -384,6 +388,15 @@ declare class CheckoutRepository extends Repository<CheckoutDocument> {
|
|
|
384
388
|
checkoutPublicId: string;
|
|
385
389
|
externalRef?: string;
|
|
386
390
|
}, ctx: OperationContext): Promise<CheckoutDocument>;
|
|
391
|
+
/**
|
|
392
|
+
* Transition open → canceled and record the reason.
|
|
393
|
+
*
|
|
394
|
+
* ⚠ Cart does NOT release inventory holds here — the HOST owns that
|
|
395
|
+
* compensation (it owns the reserve/commit sequencing too). Subscribe to
|
|
396
|
+
* `cart.checkout.canceled` and call `inventory.release(reservationRefs)`,
|
|
397
|
+
* or call it inline right after this method. Forgetting this strands
|
|
398
|
+
* holds until their TTL backstop — the classic integration leak.
|
|
399
|
+
*/
|
|
387
400
|
cancel(input: {
|
|
388
401
|
checkoutPublicId: string;
|
|
389
402
|
reason: string;
|
|
@@ -493,7 +506,6 @@ declare class IdempotencyRepository extends Repository<IdempotencyDocument> {
|
|
|
493
506
|
* sweeper drives the active release loop via `findExpiredHeld`.
|
|
494
507
|
*/
|
|
495
508
|
declare class ReservationRepository extends Repository<ReservationDocument> {
|
|
496
|
-
constructor(model: Model<ReservationDocument>, plugins: PluginType[]);
|
|
497
509
|
/** All reservations belonging to a checkout. */
|
|
498
510
|
findByCheckout(checkoutId: Types.ObjectId | string, ctx: OperationContext): Promise<ReservationDocument[]>;
|
|
499
511
|
/**
|
|
@@ -672,6 +684,12 @@ interface CartConfig extends Partial<CartConfigShape> {
|
|
|
672
684
|
* (`mongoose.createConnection(...)`). See PACKAGE_RULES.md §21.
|
|
673
685
|
*/
|
|
674
686
|
forceRecreate?: boolean | undefined;
|
|
687
|
+
/**
|
|
688
|
+
* Allow `engine.withTransaction` to fall back to non-transactional
|
|
689
|
+
* execution on standalone Mongo (local dev). Partial-write risk across
|
|
690
|
+
* the wrapped writes — explicit opt-in only.
|
|
691
|
+
*/
|
|
692
|
+
allowNonTransactional?: boolean | undefined;
|
|
675
693
|
}
|
|
676
694
|
/**
|
|
677
695
|
* CartEngine — the result of `createCart()`.
|
|
@@ -715,6 +733,20 @@ interface CartEngine {
|
|
|
715
733
|
* repositories are populated.
|
|
716
734
|
*/
|
|
717
735
|
readonly mode: 'lite' | 'full';
|
|
736
|
+
/**
|
|
737
|
+
* Run cart writes in one atomic unit-of-work: transaction + post-commit
|
|
738
|
+
* event publish. Events emitted inside the unit are queued and flushed to
|
|
739
|
+
* the in-process transport only AFTER commit — a rollback can't leak
|
|
740
|
+
* ghost events. Outbox rows (when wired) commit with the transaction.
|
|
741
|
+
*
|
|
742
|
+
* ```ts
|
|
743
|
+
* await cart.withTransaction(ctx, (txCtx) =>
|
|
744
|
+
* cart.repositories.checkout.createFromDraft(input, txCtx));
|
|
745
|
+
* ```
|
|
746
|
+
*
|
|
747
|
+
* Full mode only — throws in `'lite'` mode (no real connection).
|
|
748
|
+
*/
|
|
749
|
+
withTransaction<T>(ctx: OperationContext, body: (txCtx: OperationContext) => Promise<T>): Promise<T>;
|
|
718
750
|
/**
|
|
719
751
|
* Explicitly create indexes on all cart models.
|
|
720
752
|
*
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { l as LineDisplay, r as LineKind } from "./line-kind-
|
|
1
|
+
import { l as LineDisplay, r as LineKind } from "./line-kind-B1mU1iJp.mjs";
|
|
2
2
|
import * as _$_classytic_primitives_money0 from "@classytic/primitives/money";
|
|
3
3
|
import { Money } from "@classytic/primitives/money";
|
|
4
4
|
|
package/dist/kinds/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as timeslotKind, c as skuKind, d as serviceFeeKind, f as serviceFeePayloadSchema, g as bundlePayloadSchema, h as bundleKind, i as TimeslotPayload, l as skuPayloadSchema, m as BundlePayload, n as variantKind, o as timeslotPayloadSchema, p as BundleComponent, r as variantPayloadSchema, s as SkuPayload, t as VariantPayload, u as ServiceFeePayload } from "../variant.kind-
|
|
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-q-yv-vnQ.mjs";
|
|
2
2
|
export { type BundleComponent, type BundlePayload, type ServiceFeePayload, type SkuPayload, type TimeslotPayload, type VariantPayload, bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
|
package/dist/kinds/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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-
|
|
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-BHiivO9B.mjs";
|
|
2
2
|
export { bundleKind, bundlePayloadSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, timeslotKind, timeslotPayloadSchema, variantKind, variantPayloadSchema };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as OperationContext, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort,
|
|
1
|
+
import { C as OperationContext, T as PricedLine, c as TaxBridge, d as InventoryBridge, f as ReservationRef, m as CatalogBridge, r as ShippingBridge, t as ClockPort, y as PromotionsBridge } from "./clock.port-CNu2wgdA.mjs";
|
|
2
2
|
import { Money } from "@classytic/primitives/money";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as DraftStatus, r as ReservationStatus, t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { o as CheckoutFlowState } from "./state-transitions-
|
|
4
|
-
import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-
|
|
2
|
+
import { E as PricingSnapshot, g as AdjustmentSpec } from "./clock.port-CNu2wgdA.mjs";
|
|
3
|
+
import { o as CheckoutFlowState } from "./state-transitions-D19wZe-w.mjs";
|
|
4
|
+
import { a as IdempotencyReplay, c as LineItem, o as OperationName } from "./kind-registry-DG2iCCH1.mjs";
|
|
5
5
|
import { Money } from "@classytic/primitives/money";
|
|
6
6
|
|
|
7
7
|
//#region src/domain/entities/adjustment.entity.d.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as CheckoutState } from "./cart-status.vo-CNJw4aaB.mjs";
|
|
2
|
-
import { C as OperationContext, t as ClockPort } from "./clock.port-
|
|
3
|
-
import { t as KindBridges } from "./line-kind-
|
|
2
|
+
import { C as OperationContext, t as ClockPort } from "./clock.port-CNu2wgdA.mjs";
|
|
3
|
+
import { t as KindBridges } from "./line-kind-B1mU1iJp.mjs";
|
|
4
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
|
|
|
@@ -94,4 +94,34 @@ var StaleQuoteError = class extends CartError {
|
|
|
94
94
|
}
|
|
95
95
|
};
|
|
96
96
|
//#endregion
|
|
97
|
-
|
|
97
|
+
//#region src/domain/errors/unmanaged-session.error.ts
|
|
98
|
+
/**
|
|
99
|
+
* The caller owns the outer transaction (`ctx.session`) but gave cart no way
|
|
100
|
+
* to coordinate event publishing:
|
|
101
|
+
*
|
|
102
|
+
* - no `OutboxStore` (durable row that commits WITH the transaction), AND
|
|
103
|
+
* - no `[PENDING_EVENTS]` queue (post-commit in-process flush).
|
|
104
|
+
*
|
|
105
|
+
* Publishing to in-process subscribers mid-transaction would leak ghost
|
|
106
|
+
* events on rollback, and silently dropping the event loses it entirely —
|
|
107
|
+
* both are worse than failing fast. Safe patterns:
|
|
108
|
+
*
|
|
109
|
+
* 1. `engine.withTransaction(ctx, (txCtx) => …)` — cart owns the unit of
|
|
110
|
+
* work, queues events, and flushes them after commit.
|
|
111
|
+
* 2. Wire an `outbox` — the row commits with your transaction and the
|
|
112
|
+
* host relay delivers post-commit.
|
|
113
|
+
* 3. Manage it yourself: attach `{ ...ctx, [PENDING_EVENTS]: queue }` and
|
|
114
|
+
* call `flushPending(transport, queue)` after your commit.
|
|
115
|
+
*
|
|
116
|
+
* `PENDING_EVENTS` and `flushPending` are exported from '@classytic/cart'.
|
|
117
|
+
*/
|
|
118
|
+
var UnmanagedSessionError = class extends CartError {
|
|
119
|
+
code = "cart/transaction_unmanaged_session";
|
|
120
|
+
category = "system";
|
|
121
|
+
retryable = false;
|
|
122
|
+
constructor() {
|
|
123
|
+
super("ctx.session was provided without an outbox or a PENDING_EVENTS queue — cart cannot publish events safely inside a transaction it does not own. Use engine.withTransaction(ctx, fn), wire an OutboxStore, or attach a PENDING_EVENTS queue and flushPending() after commit.");
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
//#endregion
|
|
127
|
+
export { ConcurrencyError as a, NotFoundError as i, StaleQuoteError as n, PriceChangedError as r, UnmanagedSessionError as t };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { t as KindError } from "./kind.error-DIaJpdUb.mjs";
|
|
2
|
+
import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
//#region src/kinds/bundle.kind.ts
|
|
4
5
|
const bundlePayloadSchema = z.object({
|
|
@@ -117,7 +118,7 @@ const serviceFeePayloadSchema = z.object({
|
|
|
117
118
|
label: z.string().min(1).max(120),
|
|
118
119
|
unitPrice: z.object({
|
|
119
120
|
amount: z.number().int().nonnegative(),
|
|
120
|
-
currency: z.string().
|
|
121
|
+
currency: z.string().regex(CURRENCY_PATTERN, "ISO 4217 (3 uppercase letters)")
|
|
121
122
|
})
|
|
122
123
|
});
|
|
123
124
|
const serviceFeeKind = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@classytic/cart",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.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",
|
|
@@ -83,18 +83,18 @@
|
|
|
83
83
|
"release": "npm run push -- main && npm run release:tag && npm publish"
|
|
84
84
|
},
|
|
85
85
|
"peerDependencies": {
|
|
86
|
-
"@classytic/mongokit": ">=3.
|
|
87
|
-
"@classytic/primitives": ">=0.
|
|
88
|
-
"@classytic/repo-core": ">=0.
|
|
86
|
+
"@classytic/mongokit": ">=3.22.0",
|
|
87
|
+
"@classytic/primitives": ">=0.11.0",
|
|
88
|
+
"@classytic/repo-core": ">=0.13.0",
|
|
89
89
|
"mongoose": ">=9.4.1",
|
|
90
90
|
"zod": ">=4.0.0"
|
|
91
91
|
},
|
|
92
92
|
"devDependencies": {
|
|
93
93
|
"@biomejs/biome": "^2.4.13",
|
|
94
94
|
"@classytic/dev-tools": "^0.2.0",
|
|
95
|
-
"@classytic/mongokit": "^3.
|
|
96
|
-
"@classytic/primitives": "
|
|
97
|
-
"@classytic/repo-core": "^0.
|
|
95
|
+
"@classytic/mongokit": "^3.22.1",
|
|
96
|
+
"@classytic/primitives": "^0.11.0",
|
|
97
|
+
"@classytic/repo-core": "^0.13.0",
|
|
98
98
|
"@types/node": "^25.5.0",
|
|
99
99
|
"knip": "^6.7.0",
|
|
100
100
|
"mongodb-memory-server": "^10.2.3",
|
|
File without changes
|
|
File without changes
|