@classytic/cart 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +21 -0
  3. package/README.md +109 -0
  4. package/dist/bundle.kind-BdgnyKZt.d.mts +114 -0
  5. package/dist/bundle.kind-DFydSxV_.mjs +362 -0
  6. package/dist/cart-event-catalog-BIbi2Q_n.d.mts +109 -0
  7. package/dist/cart-event-catalog-BOP9aDhL.mjs +301 -0
  8. package/dist/cart-status.vo-2iisZGhb.d.mts +46 -0
  9. package/dist/create-cart-q3CXxPP7.mjs +1751 -0
  10. package/dist/domain/errors/index.d.mts +2 -0
  11. package/dist/domain/errors/index.mjs +4 -0
  12. package/dist/domain/events/index.d.mts +3 -0
  13. package/dist/domain/events/index.mjs +3 -0
  14. package/dist/domain/index.d.mts +12 -0
  15. package/dist/domain/index.mjs +15 -0
  16. package/dist/domain/ports/index.d.mts +3 -0
  17. package/dist/domain/ports/index.mjs +2 -0
  18. package/dist/domain/saga/index.d.mts +2 -0
  19. package/dist/domain/saga/index.mjs +3 -0
  20. package/dist/domain-event-DHNkz15G.mjs +57 -0
  21. package/dist/engine/cart-config.schema.d.mts +41 -0
  22. package/dist/engine/cart-config.schema.mjs +40 -0
  23. package/dist/engine/index.d.mts +3 -0
  24. package/dist/engine/index.mjs +3 -0
  25. package/dist/errors-CHR9RlbY.mjs +97 -0
  26. package/dist/id.port-C3rlDAKP.mjs +29 -0
  27. package/dist/id.port-DPXLrqb2.d.mts +64 -0
  28. package/dist/idempotency-key.vo-D0lJsvGn.mjs +9 -0
  29. package/dist/idempotency-record.entity-DIFXjN1V.d.mts +221 -0
  30. package/dist/index-DEHBdV_z.d.mts +1 -0
  31. package/dist/index-Doi5uzux.d.mts +231 -0
  32. package/dist/index.d.mts +103 -0
  33. package/dist/index.mjs +92 -0
  34. package/dist/internal-event-bus-IkUfQJxn.d.mts +661 -0
  35. package/dist/kind-registry-Ba4PO4WC.mjs +35 -0
  36. package/dist/kind.error-CCjTB6kW.mjs +69 -0
  37. package/dist/kinds/index.d.mts +2 -0
  38. package/dist/kinds/index.mjs +2 -0
  39. package/dist/line-item.entity-B3M_i-pw.d.mts +157 -0
  40. package/dist/line-kind-Bndo6IS8.d.mts +231 -0
  41. package/dist/not-found.error-B6WYnAjX.mjs +95 -0
  42. package/dist/outbox-store-CTWz9pvG.d.mts +155 -0
  43. package/dist/saga-step-fn-Cyob38iU.d.mts +135 -0
  44. package/dist/saga-steps-B27LI7xp.mjs +27 -0
  45. package/dist/shipping.bridge-DD4A_O0O.d.mts +538 -0
  46. package/dist/state-transitions-CpJpZZTK.mjs +21 -0
  47. package/package.json +114 -0
@@ -0,0 +1,661 @@
1
+ import { b as CartEventName, d as OutboxStore, h as CartDomainEvent, x as CartEventPayload } from "./outbox-store-CTWz9pvG.mjs";
2
+ import { a as IdempotencyIdentity, n as KindRegistry, t as LineItem } from "./line-item.entity-B3M_i-pw.mjs";
3
+ import { f as PromotionsBridge, g as CatalogBridge, o as TaxBridge, p as InventoryBridge, t as ShippingBridge, x as OperationContext } from "./shipping.bridge-DD4A_O0O.mjs";
4
+ import { l as LineDisplay, r as LineKind } from "./line-kind-Bndo6IS8.mjs";
5
+ import { i as ClockPort, t as IdPort } from "./id.port-DPXLrqb2.mjs";
6
+ import { CartConfigShape } from "./engine/cart-config.schema.mjs";
7
+ import { Money } from "@classytic/primitives/money";
8
+ import { DomainEvent, EventHandler, EventTransport, PublishManyResult } from "@classytic/primitives/events";
9
+ import { Connection, Document, Model, Types } from "mongoose";
10
+ import { PluginType, Repository } from "@classytic/mongokit";
11
+
12
+ //#region src/models/draft.model.d.ts
13
+ /**
14
+ * DraftDocument — Mongoose persistence shape for cart drafts.
15
+ *
16
+ * Mirrors the pure domain `Draft` entity in
17
+ * `domain/entities/draft.entity.ts` but carries Mongoose-specific details
18
+ * (subdocument schemas, indexes, defaults). Repositories return these
19
+ * lean objects; services cast to the domain type at the service boundary.
20
+ */
21
+ interface DraftDocument extends Document {
22
+ publicId: string;
23
+ organizationId: string;
24
+ actorRef: string;
25
+ actorKind: 'user' | 'session';
26
+ status: 'active' | 'abandoned' | 'converted' | 'expired';
27
+ lines: Array<Record<string, unknown>>;
28
+ adjustments: Array<Record<string, unknown>>;
29
+ currency: string;
30
+ pricing: Record<string, unknown> | null;
31
+ version: number;
32
+ expiresAt?: Date | null;
33
+ lastIdempotencyKey?: string;
34
+ metadata?: Record<string, unknown>;
35
+ privateMetadata?: Record<string, unknown>;
36
+ createdAt: Date;
37
+ updatedAt: Date;
38
+ }
39
+ declare function createDraftModel(connection: Connection, opts?: {
40
+ collectionPrefix?: string | undefined;
41
+ }): Model<DraftDocument>;
42
+ //#endregion
43
+ //#region src/models/checkout.model.d.ts
44
+ /**
45
+ * CheckoutDocument — locked snapshot with a minimal state field.
46
+ *
47
+ * Cart stores only what cart owns: the snapshot, the state, and an
48
+ * opaque `externalRef` the host sets on commit. Payment, orders,
49
+ * reservations live in the host's own collections.
50
+ */
51
+ interface CheckoutDocument extends Document {
52
+ publicId: string;
53
+ organizationId: string;
54
+ draftId: Types.ObjectId;
55
+ actorRef: string;
56
+ actorKind: 'user' | 'session';
57
+ state: 'open' | 'finalized' | 'canceled';
58
+ flowState: Record<string, unknown>;
59
+ lines: Array<Record<string, unknown>>;
60
+ adjustments: Array<Record<string, unknown>>;
61
+ currency: string;
62
+ pricing: Record<string, unknown>;
63
+ externalRef?: string | null;
64
+ canceledReason?: string | null;
65
+ version: number;
66
+ metadata?: Record<string, unknown>;
67
+ privateMetadata?: Record<string, unknown>;
68
+ createdAt: Date;
69
+ updatedAt: Date;
70
+ }
71
+ declare function createCheckoutModel(connection: Connection, opts?: {
72
+ collectionPrefix?: string | undefined;
73
+ }): Model<CheckoutDocument>;
74
+ //#endregion
75
+ //#region src/models/reservation.model.d.ts
76
+ /**
77
+ * ReservationDocument — one hold produced by InventoryBridge.reserve().
78
+ *
79
+ * Lives in its own collection so the host can run keyset-paginated
80
+ * scans without materialising the whole checkout. The TTL index is a
81
+ * garbage-collector backstop for already-released docs — the explicit
82
+ * sweeper is the release mechanism (see plan §4).
83
+ */
84
+ interface ReservationDocument extends Document {
85
+ publicId: string;
86
+ organizationId: string;
87
+ checkoutId: Types.ObjectId;
88
+ lineId: string;
89
+ bridgeRef: {
90
+ id: string;
91
+ payload: unknown;
92
+ };
93
+ skuRef: string;
94
+ quantity: number;
95
+ status: 'held' | 'committed' | 'released' | 'expired';
96
+ heldAt: Date;
97
+ expiresAt: Date;
98
+ releasedAt?: Date | null;
99
+ releaseReason?: 'compensation' | 'expired' | 'canceled' | 'manual' | null;
100
+ version: number;
101
+ createdAt: Date;
102
+ updatedAt: Date;
103
+ }
104
+ declare function createReservationModel(connection: Connection, opts?: {
105
+ collectionPrefix?: string | undefined;
106
+ }): Model<ReservationDocument>;
107
+ //#endregion
108
+ //#region src/models/idempotency.model.d.ts
109
+ /**
110
+ * IdempotencyDocument — one record per
111
+ * `(organizationId, cartRef, operation, actorRef, idempotencyKey)` attempt.
112
+ *
113
+ * Composite unique index enforces "one key = one outcome, forever".
114
+ * Replay payloads stored inline (<= 12KB) or as a pointer to
115
+ * `cart_operation_results`. See plan §2 for the full contract.
116
+ */
117
+ interface IdempotencyDocument extends Document {
118
+ organizationId: string;
119
+ cartRef: string;
120
+ operation: string;
121
+ actorRef: string;
122
+ idempotencyKey: string;
123
+ status: 'in_flight' | 'succeeded' | 'failed';
124
+ resultKind?: 'inline' | 'pointer' | null;
125
+ resultInline?: Record<string, unknown> | null;
126
+ resultPointer?: Record<string, unknown> | null;
127
+ error?: {
128
+ code: string;
129
+ message: string;
130
+ } | null;
131
+ leaseToken: string;
132
+ leaseExpiresAt: Date;
133
+ createdAt: Date;
134
+ completedAt?: Date | null;
135
+ }
136
+ declare function createIdempotencyModel(connection: Connection, opts?: {
137
+ collectionPrefix?: string | undefined;
138
+ }): Model<IdempotencyDocument>;
139
+ //#endregion
140
+ //#region src/models/index.d.ts
141
+ /** Union of all cart model names used as keys in `CartModels`. */
142
+ type CartModelName = 'Draft' | 'Checkout' | 'Reservation' | 'Idempotency';
143
+ interface CreateCartModelsOptions {
144
+ tenantFieldType?: 'objectId' | 'string';
145
+ multiTenant?: boolean;
146
+ autoIndex?: boolean | Partial<Record<CartModelName, boolean>>;
147
+ /**
148
+ * Optional prefix prepended to every physical collection this package
149
+ * creates (see PACKAGE_RULES.md §20.1). Unset → default names
150
+ * (`cart_drafts`, `cart_checkouts`, `cart_reservations`,
151
+ * `cart_idempotency`). Mongoose `ref:` populate is unaffected.
152
+ */
153
+ collectionPrefix?: string | undefined;
154
+ /**
155
+ * When true, existing Mongoose models with this package's names are deleted
156
+ * from the connection before re-registering. Hot-reload / test fixtures
157
+ * only. Default `false` — collision throws `CartModelCollisionError`.
158
+ * See PACKAGE_RULES.md §21.
159
+ */
160
+ forceRecreate?: boolean;
161
+ }
162
+ /**
163
+ * CartModels — the bundle returned by `createCartModels()`.
164
+ *
165
+ * Every model is scoped to the supplied `Connection`, so engines bound to
166
+ * different Mongoose connections get their own model instances without
167
+ * collisions. This mirrors the @classytic/catalog pattern exactly.
168
+ */
169
+ interface CartModels {
170
+ Draft: Model<DraftDocument>;
171
+ Checkout: Model<CheckoutDocument>;
172
+ Reservation: Model<ReservationDocument>;
173
+ Idempotency: Model<IdempotencyDocument>;
174
+ }
175
+ declare function createCartModels(connection: Connection, options?: CreateCartModelsOptions): CartModels;
176
+ //#endregion
177
+ //#region src/engine/cart-event-publisher.d.ts
178
+ interface EmitOptions {
179
+ resource?: string;
180
+ resourceId?: string;
181
+ aggregate?: CartDomainEvent['meta']['aggregate'];
182
+ }
183
+ interface CartEventPublisherDeps {
184
+ events: EventTransport;
185
+ outbox?: OutboxStore;
186
+ clock: ClockPort;
187
+ }
188
+ declare class CartEventPublisher {
189
+ private readonly events;
190
+ private readonly outbox?;
191
+ private readonly clock;
192
+ constructor(deps: CartEventPublisherDeps);
193
+ emit<E extends CartEventName>(type: E, payload: Omit<CartEventPayload<E>, 'emittedAt' | 'correlationId' | 'organizationId' | 'actorRef'>, ctx: OperationContext, options?: EmitOptions): Promise<void>;
194
+ }
195
+ //#endregion
196
+ //#region src/repositories/draft.repository.d.ts
197
+ interface DraftRepositoryDeps {
198
+ kinds: KindRegistry;
199
+ bridges: CartBridges;
200
+ clock: ClockPort;
201
+ id: IdPort;
202
+ defaultCurrency: string;
203
+ eventPublisher: CartEventPublisher;
204
+ }
205
+ /**
206
+ * DraftRepository — extends mongokit's `Repository<DraftDocument>` directly.
207
+ *
208
+ * All domain logic (validated addItem, merge, pricing, clear) lives here.
209
+ * Multi-tenant scoping is enforced by `multiTenantPlugin` at POLICY priority;
210
+ * `publicId` is generated by `customIdPlugin`. Optimistic concurrency runs
211
+ * through mongokit's `update()` so all hooks (audit, observability) fire.
212
+ */
213
+ declare class DraftRepository extends Repository<DraftDocument> {
214
+ private readonly kinds;
215
+ private readonly bridges;
216
+ private readonly clock;
217
+ private readonly id;
218
+ private readonly defaultCurrency;
219
+ private readonly eventPublisher;
220
+ constructor(model: Model<DraftDocument>, plugins: PluginType[], deps: DraftRepositoryDeps);
221
+ findActiveByActor(actorRef: string, ctx: OperationContext): Promise<DraftDocument | null>;
222
+ findByPublicId(publicId: string, ctx: OperationContext): Promise<DraftDocument | null>;
223
+ getOrCreateDraft(ctx: OperationContext): Promise<DraftDocument>;
224
+ addItem(input: {
225
+ kind: string;
226
+ payload: unknown;
227
+ quantity: number;
228
+ overrideUnitPrice?: Money;
229
+ /**
230
+ * Optional client-supplied display snapshot. When present, the
231
+ * repository stores it verbatim and skips `kind.displayOf()` — saving
232
+ * a catalog round-trip on every add. Use this when the frontend
233
+ * already has the product data (storefront product detail page, PDP
234
+ * add-to-cart button, etc.).
235
+ *
236
+ * Display drift is intentionally tolerated by the engine (see the
237
+ * package CLAUDE.md — price drift is caught at checkout via
238
+ * pricingHash; display drift is cosmetic). Hosts that want strict
239
+ * freshness can omit this field so the kind's `displayOf()` runs.
240
+ */
241
+ display?: LineDisplay | null;
242
+ }, ctx: OperationContext): Promise<DraftDocument>;
243
+ updateItemQuantity(input: {
244
+ draftPublicId: string;
245
+ lineId: string;
246
+ quantity: number;
247
+ }, ctx: OperationContext): Promise<DraftDocument>;
248
+ removeItem(input: {
249
+ draftPublicId: string;
250
+ lineId: string;
251
+ }, ctx: OperationContext): Promise<DraftDocument>;
252
+ clear(draftPublicId: string, ctx: OperationContext): Promise<DraftDocument>;
253
+ /**
254
+ * Create a new draft for the given actor. Tenant scoping is injected by
255
+ * `multiTenantPlugin` from `ctx.organizationId`; `publicId` is generated
256
+ * by `customIdPlugin`.
257
+ */
258
+ createForActor(data: Partial<DraftDocument>, ctx: OperationContext): Promise<DraftDocument>;
259
+ /**
260
+ * Optimistic-concurrency update: applies `$set: updates` and `$inc: version`
261
+ * only when the persisted version matches `expectedVersion`. Throws
262
+ * `ConcurrencyError` on mismatch (mongokit raises 404 when no doc matches
263
+ * `{ _id, version }` and we re-translate it).
264
+ */
265
+ updateWithVersion(draftId: Types.ObjectId | string, expectedVersion: number, updates: Record<string, unknown>, ctx: OperationContext): Promise<DraftDocument>;
266
+ /**
267
+ * Atomic transition `active → abandoned`. Returns null if the draft was
268
+ * already in a non-active state.
269
+ */
270
+ markAbandoned(draftId: Types.ObjectId | string, ctx: OperationContext): Promise<DraftDocument | null>;
271
+ /**
272
+ * Mark a draft as converted (called from CheckoutRepository.commit).
273
+ * Best-effort: a missed update is reconciled by the next getOrCreate.
274
+ */
275
+ markConverted(draftId: Types.ObjectId | string, ctx: OperationContext): Promise<void>;
276
+ /**
277
+ * Replace the line collection atomically and refresh the pricing snapshot.
278
+ * Internal services use this to keep merge-like flows inside repository
279
+ * concurrency + pricing rules instead of hand-writing persistence logic.
280
+ */
281
+ replaceLines(input: {
282
+ draftPublicId: string;
283
+ lines: readonly LineItem[];
284
+ }, ctx: OperationContext): Promise<DraftDocument>;
285
+ mergeLines(existing: readonly LineItem[], incoming: readonly LineItem[]): LineItem[];
286
+ private readOptions;
287
+ private writeOptions;
288
+ private price;
289
+ private requireDraft;
290
+ private kindContextFor;
291
+ private mergeLine;
292
+ /**
293
+ * Resolve a line's merge key.
294
+ *
295
+ * Preferred path: delegate to `LineKind.mergeKey()` — every built-in kind
296
+ * knows its own payload shape and returns a stable grouping key
297
+ * (e.g. `variant:${productRef}:${variantSku}` for the variant kind).
298
+ *
299
+ * Fallback: for kinds that don't implement `mergeKey()` (older custom
300
+ * kinds, or unregistered kinds seen on legacy drafts), check for a
301
+ * `payload.skuRef` field — the shape the repository historically
302
+ * assumed. This keeps drafts written before this change mergeable.
303
+ */
304
+ private computeMergeKey;
305
+ }
306
+ //#endregion
307
+ //#region src/repositories/checkout.repository.d.ts
308
+ interface CheckoutRepositoryDeps {
309
+ draftRepo: DraftRepository;
310
+ clock: ClockPort;
311
+ eventPublisher: CartEventPublisher;
312
+ }
313
+ /**
314
+ * CheckoutRepository — extends mongokit's `Repository<CheckoutDocument>`.
315
+ *
316
+ * All domain logic (createFromDraft with hash interlock, commit, cancel)
317
+ * lives here. Tenant scoping comes from `multiTenantPlugin`; `publicId`
318
+ * comes from `customIdPlugin`. State transitions go through mongokit's
319
+ * `update()` so all hooks fire.
320
+ */
321
+ declare class CheckoutRepository extends Repository<CheckoutDocument> {
322
+ private readonly draftRepo;
323
+ private readonly clock;
324
+ private readonly eventPublisher;
325
+ constructor(model: Model<CheckoutDocument>, plugins: PluginType[], deps: CheckoutRepositoryDeps);
326
+ findByPublicId(publicId: string, ctx: OperationContext): Promise<CheckoutDocument | null>;
327
+ findByDraft(draftId: Types.ObjectId | string, ctx: OperationContext): Promise<CheckoutDocument | null>;
328
+ /**
329
+ * Find the currently-open checkout for a draft.
330
+ * Used by `createFromDraft` dedup — terminal checkouts (canceled /
331
+ * finalized) are history, they must NOT be returned here or the host
332
+ * would try to commit a canceled snapshot on retry.
333
+ */
334
+ findOpenByDraft(draftId: Types.ObjectId | string, ctx: OperationContext): Promise<CheckoutDocument | null>;
335
+ createFromDraft(input: {
336
+ draftPublicId: string;
337
+ expectedPricingHash: string | null;
338
+ }, ctx: OperationContext): Promise<CheckoutDocument>;
339
+ commit(input: {
340
+ checkoutPublicId: string;
341
+ externalRef?: string;
342
+ }, ctx: OperationContext): Promise<CheckoutDocument>;
343
+ cancel(input: {
344
+ checkoutPublicId: string;
345
+ reason: string;
346
+ }, ctx: OperationContext): Promise<CheckoutDocument>;
347
+ updateWithVersion(checkoutId: Types.ObjectId | string, expectedVersion: number, updates: Record<string, unknown>, ctx: OperationContext): Promise<CheckoutDocument>;
348
+ private readOptions;
349
+ private writeOptions;
350
+ private requireCheckout;
351
+ }
352
+ //#endregion
353
+ //#region src/repositories/reservation.repository.d.ts
354
+ /**
355
+ * ReservationRepository — extends mongokit's `Repository<ReservationDocument>`.
356
+ *
357
+ * Tenant scoping is enforced by `multiTenantPlugin`; `publicId` comes from
358
+ * `customIdPlugin`. The TTL index on `expiresAt` is a backstop — the
359
+ * sweeper drives the active release loop via `findExpiredHeld`.
360
+ */
361
+ declare class ReservationRepository extends Repository<ReservationDocument> {
362
+ constructor(model: Model<ReservationDocument>, plugins: PluginType[]);
363
+ /** All reservations belonging to a checkout. */
364
+ findByCheckout(checkoutId: Types.ObjectId | string, ctx: OperationContext): Promise<ReservationDocument[]>;
365
+ /**
366
+ * Expired held reservations for the sweeper. Routed through `getAll` so
367
+ * the multi-tenant plugin scopes the query at POLICY priority.
368
+ */
369
+ findExpiredHeld(asOf: Date, limit: number, ctx: OperationContext): Promise<ReservationDocument[]>;
370
+ /** Atomic transition `held → released` via version check. */
371
+ markReleased(reservationId: Types.ObjectId | string, expectedVersion: number, reason: 'compensation' | 'expired' | 'canceled' | 'manual', ctx: OperationContext): Promise<ReservationDocument | null>;
372
+ /** Atomic transition `held → committed` on saga step 10. */
373
+ markCommitted(reservationId: Types.ObjectId | string, expectedVersion: number, ctx: OperationContext): Promise<ReservationDocument | null>;
374
+ private atomicTransition;
375
+ private readOptions;
376
+ private writeOptions;
377
+ }
378
+ //#endregion
379
+ //#region src/repositories/idempotency.repository.d.ts
380
+ /**
381
+ * IdempotencyRepository — the storage backing cart's composite-identity
382
+ * idempotency contract (plan §2).
383
+ *
384
+ * Provides:
385
+ * - `findByIdentity()` — look up by the full composite key
386
+ * - `insertInFlight()` — race-safe insert of a new lease
387
+ * - `claimExpiredLease()` — reclaim a crashed in_flight record whose
388
+ * lease has expired
389
+ * - `markSucceeded()` / `markFailed()` — terminal transitions
390
+ *
391
+ * Used by `idempotencyPlugin` (later+) to implement the before:create /
392
+ * before:update short-circuit. Hosts can also call these methods directly
393
+ * for custom operations outside the plugin's hook path.
394
+ */
395
+ declare class IdempotencyRepository extends Repository<IdempotencyDocument> {
396
+ constructor(model: Model<IdempotencyDocument>, plugins?: PluginType[]);
397
+ /** Look up a record by the full composite identity. */
398
+ findByIdentity(identity: IdempotencyIdentity, ctx: OperationContext): Promise<IdempotencyDocument | null>;
399
+ /**
400
+ * Race-safe insert: try to insert a new `in_flight` record. Returns the
401
+ * newly inserted record on success; returns `null` if the composite
402
+ * unique index fired (meaning another writer got there first — caller
403
+ * should then call `findByIdentity` to read the settled state).
404
+ */
405
+ insertInFlight(identity: IdempotencyIdentity, leaseToken: string, leaseExpiresAt: Date, ctx: OperationContext): Promise<IdempotencyDocument | null>;
406
+ /**
407
+ * Claim an expired lease — transition an in_flight record with a dead
408
+ * lease to a new lease token, so the caller can re-run the operation.
409
+ *
410
+ * Atomic via `findOneAndUpdate` with the prior leaseToken in the filter,
411
+ * so two concurrent reclaimers can't both win.
412
+ */
413
+ claimExpiredLease(identity: IdempotencyIdentity, priorLeaseToken: string, newLeaseToken: string, newLeaseExpiresAt: Date, ctx: OperationContext): Promise<IdempotencyDocument | null>;
414
+ markSucceeded(identity: IdempotencyIdentity, leaseToken: string, replay: {
415
+ resultKind: 'inline' | 'pointer';
416
+ resultInline?: Record<string, unknown>;
417
+ resultPointer?: Record<string, unknown>;
418
+ }, ctx: OperationContext): Promise<IdempotencyDocument | null>;
419
+ markFailed(identity: IdempotencyIdentity, leaseToken: string, error: {
420
+ code: string;
421
+ message: string;
422
+ }, ctx: OperationContext): Promise<IdempotencyDocument | null>;
423
+ }
424
+ //#endregion
425
+ //#region src/repositories/index.d.ts
426
+ /**
427
+ * CartRepositories — the bundle returned by `createCartRepositories()`.
428
+ *
429
+ * Each repository extends `Repository<T>` from mongokit directly, so every
430
+ * mongokit primitive (pagination, hooks, `withTransaction`, aggregation,
431
+ * plugins) is available unchanged on cart repos.
432
+ */
433
+ interface CartRepositories {
434
+ draft: DraftRepository;
435
+ checkout: CheckoutRepository;
436
+ reservation: ReservationRepository;
437
+ idempotency: IdempotencyRepository;
438
+ }
439
+ /**
440
+ * Per-repository plugin bundle. Hosts can install their own plugins on
441
+ * top of cart's defaults — the constructor appends to the plugin list
442
+ * without replacing anything.
443
+ */
444
+ interface CartRepositoryPluginBundle {
445
+ draft?: PluginType[];
446
+ checkout?: PluginType[];
447
+ reservation?: PluginType[];
448
+ idempotency?: PluginType[];
449
+ }
450
+ interface CreateCartRepositoriesConfig {
451
+ kinds: KindRegistry;
452
+ bridges: CartBridges;
453
+ clock: ClockPort;
454
+ id: IdPort;
455
+ defaultCurrency: string;
456
+ events: EventTransport;
457
+ tenantFieldType?: 'objectId' | 'string';
458
+ /**
459
+ * When `false`, the tenant plugin is omitted entirely — cart is
460
+ * company-wide. Default `true` keeps branch scoping.
461
+ */
462
+ multiTenant?: boolean;
463
+ outbox?: OutboxStore;
464
+ plugins?: CartRepositoryPluginBundle;
465
+ }
466
+ declare function createCartRepositories(models: CartModels, config: CreateCartRepositoriesConfig): CartRepositories;
467
+ //#endregion
468
+ //#region src/engine/engine-types.d.ts
469
+ /**
470
+ * Bridges bundle — only `catalog` is required. Everything else is
471
+ * optional, used only when the relevant kind / pipeline step runs.
472
+ *
473
+ * Cart does NOT carry a `payment` or `hostOrder` bridge. Payment
474
+ * processing and order creation live in the host — cart emits
475
+ * `cart.checkout.created` after freezing the snapshot, and the host
476
+ * does whatever it needs (charge the card, create an order row, send
477
+ * a receipt) before calling
478
+ * `cart.repositories.checkout.commit(id)` to transition the cart
479
+ * state. See CLAUDE.md "Boundary — what cart owns vs not" for the
480
+ * frozen line.
481
+ */
482
+ interface CartBridges {
483
+ catalog: CatalogBridge;
484
+ inventory?: InventoryBridge | undefined;
485
+ promotions?: PromotionsBridge | undefined;
486
+ tax?: TaxBridge | undefined;
487
+ shipping?: ShippingBridge | undefined;
488
+ }
489
+ /**
490
+ * CartConfig — the single argument to `createCart()`.
491
+ */
492
+ interface CartConfig extends Partial<CartConfigShape> {
493
+ /**
494
+ * Mongoose connection. Required when the engine will create
495
+ * models/repositories. Scenario tests that only exercise the LineKind
496
+ * contract can pass a placeholder — the engine detects whether the
497
+ * connection is a real Mongoose instance and skips model creation if
498
+ * not, staying in `phase: 'contracts'`.
499
+ */
500
+ connection: Connection;
501
+ /** LineKinds to register. At least one required. */
502
+ kinds: readonly LineKind[];
503
+ /** External-domain bridges. Only `catalog` is required. */
504
+ bridges: CartBridges;
505
+ /**
506
+ * Optional host-supplied event transport. Default: `InProcessCartEventBus`.
507
+ *
508
+ * **Structurally compatible with Arc's `EventTransport`** — pass Arc's
509
+ * Redis / Kafka / Outbox transport directly, zero adapter needed:
510
+ *
511
+ * ```ts
512
+ * import { RedisEventTransport } from '@classytic/arc/events';
513
+ * const cart = await createCart({ eventTransport: new RedisEventTransport(ioredis), ... });
514
+ * ```
515
+ */
516
+ eventTransport?: EventTransport | undefined;
517
+ /** Optional clock override. Default: `systemClock`. */
518
+ clock?: ClockPort | undefined;
519
+ /**
520
+ * Optional id generator. Default: `cryptoIdPort`. Override for
521
+ * deterministic tests, Temporal workflow replay safety, or host-
522
+ * specific id formats.
523
+ */
524
+ id?: IdPort | undefined;
525
+ /**
526
+ * Optional host-owned durable outbox store.
527
+ *
528
+ * Cart no longer provisions its own Mongo outbox by default. Hosts that
529
+ * need durable event persistence should inject their app-level outbox store
530
+ * here. When omitted, cart still publishes to `eventTransport`, but
531
+ * session-bound writes cannot persist events durably.
532
+ */
533
+ outbox?: OutboxStore | undefined;
534
+ /**
535
+ * Optional per-repository plugin bundle.
536
+ */
537
+ repositoryPlugins?: CartRepositoryPluginBundle | undefined;
538
+ /**
539
+ * Mongoose schema type for the `organizationId` field on all models.
540
+ *
541
+ * - `'objectId'` (default): `Schema.Types.ObjectId` + `ref: 'organization'`
542
+ * - `'string'`: plain `String` — for UUID/slug-based auth
543
+ *
544
+ * Passed to model factories (schema) and multiTenantPlugin (query casting).
545
+ */
546
+ tenantFieldType?: 'objectId' | 'string' | undefined;
547
+ /**
548
+ * Whether cart is branch/tenant-scoped. Default `true`.
549
+ *
550
+ * - `true` (default): `organizationId` is required on every document and
551
+ * prepended to every index. Use for multi-tenant SaaS or
552
+ * branch-scoped cart stacks (POS-first, etc.).
553
+ * - `false`: `organizationId` is left optional and excluded from indexes.
554
+ * Use when cart is company-wide — a customer's cart follows them across
555
+ * branches and no tenant filter applies.
556
+ */
557
+ multiTenant?: boolean | undefined;
558
+ /**
559
+ * Control Mongoose `autoIndex` per model or globally.
560
+ *
561
+ * - `true` / `false` — applied to every cart model.
562
+ * - `Partial<Record<CartModelName, boolean>>` — per-model override.
563
+ * - `undefined` (default) — leave Mongoose defaults untouched.
564
+ *
565
+ * Mongoose 9 defers `Model.init()` until the first query, so setting
566
+ * `schema.autoIndex` after `connection.model()` is safe.
567
+ */
568
+ autoIndex?: CreateCartModelsOptions['autoIndex'] | undefined;
569
+ /**
570
+ * Optional prefix prepended to every physical collection this package
571
+ * creates (see PACKAGE_RULES.md §20.1). Unset → default names
572
+ * (`cart_drafts`, `cart_checkouts`, `cart_reservations`,
573
+ * `cart_idempotency`). Set e.g. `'commerce_'` to get `commerce_cart_drafts`,
574
+ * etc. Model names and `ref:` populate are unaffected.
575
+ */
576
+ collectionPrefix?: string | undefined;
577
+ /**
578
+ * When true, existing Mongoose models with cart's names are deleted from
579
+ * the connection before re-registering. Hot-reload / test fixtures only.
580
+ * Default `false` — collision throws `CartModelCollisionError`. Hosts
581
+ * that need two cart engines should use two Mongoose connections
582
+ * (`mongoose.createConnection(...)`). See PACKAGE_RULES.md §21.
583
+ */
584
+ forceRecreate?: boolean | undefined;
585
+ }
586
+ /**
587
+ * CartEngine — the result of `createCart()`.
588
+ */
589
+ interface CartEngine {
590
+ readonly config: Readonly<CartConfig>;
591
+ /** Registered LineKinds. */
592
+ readonly kinds: KindRegistry;
593
+ /**
594
+ * Event transport — host-supplied or the default `InProcessCartEventBus`.
595
+ *
596
+ * ```ts
597
+ * // Subscribe to all cart events via glob
598
+ * await cart.events.subscribe?.('cart.*', async (event) => {
599
+ * console.log(event.type, event.meta.organizationId);
600
+ * });
601
+ * ```
602
+ */
603
+ readonly events: EventTransport;
604
+ /** Clock source. */
605
+ readonly clock: ClockPort;
606
+ /** Id generator. */
607
+ readonly id: IdPort;
608
+ /**
609
+ * Mongoose models bound to the engine's connection. Empty in
610
+ * contracts-only mode.
611
+ */
612
+ readonly models: CartModels | Record<string, never>;
613
+ /**
614
+ * mongokit repositories — the primary CRUD + domain API. All domain
615
+ * logic (addItem, checkout, commit, cancel) lives directly on the
616
+ * repository classes. Empty in contracts-only mode.
617
+ */
618
+ readonly repositories: CartRepositories | Record<string, never>;
619
+ /**
620
+ * `'lite'` — no real Mongoose connection; kinds/events/clock/id are
621
+ * populated but models/repositories are empty. Used by scenario tests
622
+ * that only exercise the LineKind contract.
623
+ *
624
+ * `'full'` — real Mongoose connection detected; models and
625
+ * repositories are populated.
626
+ */
627
+ readonly mode: 'lite' | 'full';
628
+ /**
629
+ * Explicitly create indexes on all cart models.
630
+ *
631
+ * Useful when `autoIndex` is disabled in production — call once during
632
+ * deployment or migration scripts.
633
+ */
634
+ syncIndexes(): Promise<void>;
635
+ /** Shut down cleanly. */
636
+ destroy(): Promise<void>;
637
+ }
638
+ //#endregion
639
+ //#region src/engine/create-cart.d.ts
640
+ /**
641
+ * createCart() — build a cart engine.
642
+ *
643
+ * Repositories are the primary API. All domain logic (addItem, checkout,
644
+ * commit, cancel) lives directly on the repository classes. Multi-tenant
645
+ * scoping and `publicId` generation are handled by mongokit plugins wired
646
+ * inside `createCartRepositories`, so callers just pass the connection
647
+ * and bridges.
648
+ */
649
+ declare function createCart(config: CartConfig): Promise<CartEngine>;
650
+ //#endregion
651
+ //#region src/engine/internal-event-bus.d.ts
652
+ declare class InProcessCartEventBus implements EventTransport {
653
+ readonly name = "in-process-cart";
654
+ private subs;
655
+ publish(event: DomainEvent): Promise<void>;
656
+ publishMany(events: readonly DomainEvent[]): Promise<PublishManyResult>;
657
+ subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
658
+ close(): Promise<void>;
659
+ }
660
+ //#endregion
661
+ export { DraftDocument as C, createCheckoutModel as S, IdempotencyDocument as _, CartEngine as a, createReservationModel as b, createCartRepositories as c, CheckoutRepository as d, DraftRepository as f, createCartModels as g, CreateCartModelsOptions as h, CartConfig as i, IdempotencyRepository as l, CartModels as m, createCart as n, CartRepositories as o, CartModelName as p, CartBridges as r, CartRepositoryPluginBundle as s, InProcessCartEventBus as t, ReservationRepository as u, createIdempotencyModel as v, createDraftModel as w, CheckoutDocument as x, ReservationDocument as y };
@@ -0,0 +1,35 @@
1
+ import { n as UnknownKindError } from "./kind.error-CCjTB6kW.mjs";
2
+ //#region src/domain/kinds/kind-registry.ts
3
+ /**
4
+ * Build a KindRegistry from a list of LineKind implementations.
5
+ *
6
+ * Throws at construction if two kinds share a name — the engine will not
7
+ * silently overwrite. Hosts that want to override a built-in kind must
8
+ * remove the built-in from their `config.kinds` array explicitly.
9
+ */
10
+ function createKindRegistry(kinds) {
11
+ const map = /* @__PURE__ */ new Map();
12
+ for (const kind of kinds) {
13
+ if (map.has(kind.name)) throw new Error(`createKindRegistry: duplicate LineKind name '${kind.name}'. Each kind name must be unique. Remove the duplicate from config.kinds.`);
14
+ map.set(kind.name, kind);
15
+ }
16
+ const names = Object.freeze(Array.from(map.keys()));
17
+ return Object.freeze({
18
+ get(name) {
19
+ const found = map.get(name);
20
+ if (!found) throw new UnknownKindError(name, Array.from(map.keys()));
21
+ return found;
22
+ },
23
+ tryGet(name) {
24
+ return map.get(name);
25
+ },
26
+ list() {
27
+ return names;
28
+ },
29
+ get size() {
30
+ return map.size;
31
+ }
32
+ });
33
+ }
34
+ //#endregion
35
+ export { createKindRegistry as t };