@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,1751 @@
1
+ import { t as KindError } from "./kind.error-CCjTB6kW.mjs";
2
+ import { i as ConcurrencyError, n as StateTransitionError, r as PriceChangedError, t as NotFoundError } from "./not-found.error-B6WYnAjX.mjs";
3
+ import { n as CartEvents, t as createCartEvent } from "./domain-event-DHNkz15G.mjs";
4
+ import { n as cryptoIdPort, r as systemClock } from "./id.port-C3rlDAKP.mjs";
5
+ import { t as createKindRegistry } from "./kind-registry-Ba4PO4WC.mjs";
6
+ import { t as CheckoutStep } from "./saga-steps-B27LI7xp.mjs";
7
+ import { money } from "@classytic/primitives/money";
8
+ import { matchEventPattern } from "@classytic/primitives/events";
9
+ import mongoose, { Schema } from "mongoose";
10
+ import { resolveTenantConfig } from "@classytic/primitives/tenant";
11
+ import { Repository, customIdPlugin, multiTenantPlugin, prefixedId } from "@classytic/mongokit";
12
+ //#region src/models/draft.model.ts
13
+ const lineDisplaySubSchema = new Schema({
14
+ name: {
15
+ type: String,
16
+ default: null
17
+ },
18
+ imageUrl: {
19
+ type: String,
20
+ default: null
21
+ },
22
+ slug: {
23
+ type: String,
24
+ default: null
25
+ },
26
+ variantLabel: {
27
+ type: String,
28
+ default: null
29
+ },
30
+ compareAtPrice: {
31
+ type: Schema.Types.Mixed,
32
+ default: null
33
+ },
34
+ capturedAt: {
35
+ type: Date,
36
+ default: () => /* @__PURE__ */ new Date()
37
+ }
38
+ }, { _id: false });
39
+ const lineItemSubSchema = new Schema({
40
+ lineId: {
41
+ type: String,
42
+ required: true
43
+ },
44
+ kind: {
45
+ type: String,
46
+ required: true,
47
+ trim: true
48
+ },
49
+ payload: {
50
+ type: Schema.Types.Mixed,
51
+ required: true
52
+ },
53
+ quantity: {
54
+ type: Number,
55
+ required: true,
56
+ min: 1
57
+ },
58
+ overrideUnitPrice: {
59
+ type: Schema.Types.Mixed,
60
+ default: null
61
+ },
62
+ display: {
63
+ type: lineDisplaySubSchema,
64
+ default: null
65
+ },
66
+ addedAt: {
67
+ type: Date,
68
+ default: () => /* @__PURE__ */ new Date()
69
+ },
70
+ metadata: {
71
+ type: Schema.Types.Mixed,
72
+ default: null
73
+ }
74
+ }, { _id: false });
75
+ const adjustmentSubSchema = new Schema({
76
+ adjustmentId: {
77
+ type: String,
78
+ required: true
79
+ },
80
+ source: {
81
+ type: String,
82
+ enum: [
83
+ "promotion",
84
+ "manual",
85
+ "system"
86
+ ],
87
+ required: true
88
+ },
89
+ ruleRef: {
90
+ type: String,
91
+ default: null
92
+ },
93
+ spec: {
94
+ type: Schema.Types.Mixed,
95
+ required: true
96
+ },
97
+ targetLineId: {
98
+ type: String,
99
+ default: null
100
+ },
101
+ appliedAmount: {
102
+ type: Schema.Types.Mixed,
103
+ required: true
104
+ },
105
+ explanation: {
106
+ type: String,
107
+ default: null
108
+ },
109
+ priority: {
110
+ type: Number,
111
+ default: 0
112
+ },
113
+ appliedAt: {
114
+ type: Date,
115
+ default: () => /* @__PURE__ */ new Date()
116
+ }
117
+ }, { _id: false });
118
+ function createDraftModel(connection, opts = {}) {
119
+ const schema = new Schema({
120
+ publicId: {
121
+ type: String,
122
+ required: true,
123
+ unique: true
124
+ },
125
+ actorRef: {
126
+ type: String,
127
+ required: true
128
+ },
129
+ actorKind: {
130
+ type: String,
131
+ enum: ["user", "session"],
132
+ required: true
133
+ },
134
+ status: {
135
+ type: String,
136
+ enum: [
137
+ "active",
138
+ "abandoned",
139
+ "converted",
140
+ "expired"
141
+ ],
142
+ default: "active"
143
+ },
144
+ lines: {
145
+ type: [lineItemSubSchema],
146
+ default: []
147
+ },
148
+ adjustments: {
149
+ type: [adjustmentSubSchema],
150
+ default: []
151
+ },
152
+ currency: {
153
+ type: String,
154
+ required: true,
155
+ length: 3
156
+ },
157
+ pricing: {
158
+ type: Schema.Types.Mixed,
159
+ default: null
160
+ },
161
+ version: {
162
+ type: Number,
163
+ default: 0,
164
+ min: 0
165
+ },
166
+ expiresAt: {
167
+ type: Date,
168
+ default: null
169
+ },
170
+ lastIdempotencyKey: {
171
+ type: String,
172
+ default: null
173
+ },
174
+ metadata: {
175
+ type: Schema.Types.Mixed,
176
+ default: null
177
+ },
178
+ privateMetadata: {
179
+ type: Schema.Types.Mixed,
180
+ default: null
181
+ }
182
+ }, {
183
+ timestamps: true,
184
+ minimize: false
185
+ });
186
+ schema.index({ actorRef: 1 }, {
187
+ unique: true,
188
+ partialFilterExpression: { status: "active" }
189
+ });
190
+ schema.index({ expiresAt: 1 }, {
191
+ expireAfterSeconds: 0,
192
+ partialFilterExpression: { expiresAt: { $exists: true } }
193
+ });
194
+ const collection = (opts.collectionPrefix ?? "") + "cart_drafts";
195
+ return connection.model("CartDraft", schema, collection);
196
+ }
197
+ //#endregion
198
+ //#region src/models/checkout.model.ts
199
+ function createCheckoutModel(connection, opts = {}) {
200
+ const schema = new Schema({
201
+ publicId: {
202
+ type: String,
203
+ required: true,
204
+ unique: true
205
+ },
206
+ draftId: {
207
+ type: Schema.Types.ObjectId,
208
+ required: true
209
+ },
210
+ actorRef: {
211
+ type: String,
212
+ required: true
213
+ },
214
+ actorKind: {
215
+ type: String,
216
+ enum: ["user", "session"],
217
+ required: true
218
+ },
219
+ state: {
220
+ type: String,
221
+ enum: [
222
+ "open",
223
+ "finalized",
224
+ "canceled"
225
+ ],
226
+ default: "open"
227
+ },
228
+ flowState: {
229
+ type: Schema.Types.Mixed,
230
+ required: true
231
+ },
232
+ lines: {
233
+ type: [{ type: Schema.Types.Mixed }],
234
+ default: []
235
+ },
236
+ adjustments: {
237
+ type: [{ type: Schema.Types.Mixed }],
238
+ default: []
239
+ },
240
+ currency: {
241
+ type: String,
242
+ required: true,
243
+ length: 3
244
+ },
245
+ pricing: {
246
+ type: Schema.Types.Mixed,
247
+ required: true
248
+ },
249
+ externalRef: {
250
+ type: String,
251
+ default: null
252
+ },
253
+ canceledReason: {
254
+ type: String,
255
+ default: null
256
+ },
257
+ version: {
258
+ type: Number,
259
+ default: 0,
260
+ min: 0
261
+ },
262
+ metadata: {
263
+ type: Schema.Types.Mixed,
264
+ default: null
265
+ },
266
+ privateMetadata: {
267
+ type: Schema.Types.Mixed,
268
+ default: null
269
+ }
270
+ }, {
271
+ timestamps: true,
272
+ minimize: false
273
+ });
274
+ schema.index({ draftId: 1 }, {
275
+ unique: true,
276
+ partialFilterExpression: { state: "open" }
277
+ });
278
+ schema.index({
279
+ draftId: 1,
280
+ state: 1
281
+ });
282
+ const collection = (opts.collectionPrefix ?? "") + "cart_checkouts";
283
+ return connection.model("CartCheckout", schema, collection);
284
+ }
285
+ //#endregion
286
+ //#region src/models/reservation.model.ts
287
+ function createReservationModel(connection, opts = {}) {
288
+ const schema = new Schema({
289
+ publicId: {
290
+ type: String,
291
+ required: true,
292
+ unique: true
293
+ },
294
+ checkoutId: {
295
+ type: Schema.Types.ObjectId,
296
+ required: true
297
+ },
298
+ lineId: {
299
+ type: String,
300
+ required: true
301
+ },
302
+ bridgeRef: {
303
+ id: {
304
+ type: String,
305
+ required: true
306
+ },
307
+ payload: {
308
+ type: Schema.Types.Mixed,
309
+ default: null
310
+ }
311
+ },
312
+ skuRef: {
313
+ type: String,
314
+ required: true
315
+ },
316
+ quantity: {
317
+ type: Number,
318
+ required: true,
319
+ min: 1
320
+ },
321
+ status: {
322
+ type: String,
323
+ enum: [
324
+ "held",
325
+ "committed",
326
+ "released",
327
+ "expired"
328
+ ],
329
+ default: "held"
330
+ },
331
+ heldAt: {
332
+ type: Date,
333
+ default: () => /* @__PURE__ */ new Date()
334
+ },
335
+ expiresAt: {
336
+ type: Date,
337
+ required: true
338
+ },
339
+ releasedAt: {
340
+ type: Date,
341
+ default: null
342
+ },
343
+ releaseReason: {
344
+ type: String,
345
+ enum: [
346
+ "compensation",
347
+ "expired",
348
+ "canceled",
349
+ "manual",
350
+ null
351
+ ],
352
+ default: null
353
+ },
354
+ version: {
355
+ type: Number,
356
+ default: 0,
357
+ min: 0
358
+ }
359
+ }, {
360
+ timestamps: true,
361
+ minimize: false
362
+ });
363
+ schema.index({
364
+ status: 1,
365
+ expiresAt: 1
366
+ });
367
+ schema.index({ checkoutId: 1 });
368
+ const collection = (opts.collectionPrefix ?? "") + "cart_reservations";
369
+ return connection.model("CartReservation", schema, collection);
370
+ }
371
+ //#endregion
372
+ //#region src/models/idempotency.model.ts
373
+ function createIdempotencyModel(connection, opts = {}) {
374
+ const schema = new Schema({
375
+ cartRef: {
376
+ type: String,
377
+ required: true
378
+ },
379
+ operation: {
380
+ type: String,
381
+ required: true
382
+ },
383
+ actorRef: {
384
+ type: String,
385
+ required: true
386
+ },
387
+ idempotencyKey: {
388
+ type: String,
389
+ required: true
390
+ },
391
+ status: {
392
+ type: String,
393
+ enum: [
394
+ "in_flight",
395
+ "succeeded",
396
+ "failed"
397
+ ],
398
+ default: "in_flight"
399
+ },
400
+ resultKind: {
401
+ type: String,
402
+ enum: [
403
+ "inline",
404
+ "pointer",
405
+ null
406
+ ],
407
+ default: null
408
+ },
409
+ resultInline: {
410
+ type: Schema.Types.Mixed,
411
+ default: null
412
+ },
413
+ resultPointer: {
414
+ type: Schema.Types.Mixed,
415
+ default: null
416
+ },
417
+ error: {
418
+ type: Schema.Types.Mixed,
419
+ default: null
420
+ },
421
+ leaseToken: {
422
+ type: String,
423
+ required: true
424
+ },
425
+ leaseExpiresAt: {
426
+ type: Date,
427
+ required: true
428
+ },
429
+ completedAt: {
430
+ type: Date,
431
+ default: null
432
+ }
433
+ }, {
434
+ timestamps: {
435
+ createdAt: true,
436
+ updatedAt: false
437
+ },
438
+ minimize: false
439
+ });
440
+ schema.index({
441
+ cartRef: 1,
442
+ operation: 1,
443
+ actorRef: 1,
444
+ idempotencyKey: 1
445
+ }, { unique: true });
446
+ schema.index({ createdAt: 1 }, { expireAfterSeconds: 1440 * 60 });
447
+ const collection = (opts.collectionPrefix ?? "") + "cart_idempotency";
448
+ return connection.model("CartIdempotency", schema, collection);
449
+ }
450
+ //#endregion
451
+ //#region src/models/inject-tenant.ts
452
+ /**
453
+ * Mongoose-specific adapter around `resolveTenantConfig()` from
454
+ * `@classytic/primitives/tenant`. The pure resolution lives in primitives
455
+ * (zero runtime deps) — this file only handles the Mongoose schema
456
+ * mutations (add field, prepend tenant to indexes) that primitives can't
457
+ * own without a mongoose dependency.
458
+ */
459
+ function resolveCartTenant(input = {}) {
460
+ if (typeof input === "boolean" || input === void 0) return resolveTenantConfig(input);
461
+ if ("tenantFieldType" in input || "multiTenant" in input) {
462
+ const legacy = input;
463
+ return resolveTenantConfig({
464
+ enabled: legacy.multiTenant !== false,
465
+ fieldType: legacy.tenantFieldType ?? "objectId"
466
+ });
467
+ }
468
+ return resolveTenantConfig(input);
469
+ }
470
+ /**
471
+ * Inject the tenant field into a Mongoose schema, and (when `enabled` +
472
+ * strategy === 'field') prepend it to every existing compound index so
473
+ * queries are index-efficient under multi-tenant scoping.
474
+ */
475
+ function injectTenantField(schema, tenant) {
476
+ const isFieldStrategy = tenant.strategy === "field";
477
+ const isObjectId = tenant.fieldType === "objectId";
478
+ schema.add({ [tenant.tenantField]: {
479
+ type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
480
+ ...tenant.enabled && tenant.required ? { required: true } : {},
481
+ index: true,
482
+ ...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
483
+ } });
484
+ if (!tenant.enabled || !isFieldStrategy) return;
485
+ const existingIndexes = schema._indexes;
486
+ if (existingIndexes && existingIndexes.length > 0) for (const indexEntry of existingIndexes) {
487
+ const fields = indexEntry[0];
488
+ if (fields[tenant.tenantField] !== void 0) continue;
489
+ const newFields = { [tenant.tenantField]: 1 };
490
+ for (const [key, val] of Object.entries(fields)) newFields[key] = val;
491
+ indexEntry[0] = newFields;
492
+ }
493
+ }
494
+ //#endregion
495
+ //#region src/models/index.ts
496
+ const CART_MODEL_NAMES = [
497
+ "CartDraft",
498
+ "CartCheckout",
499
+ "CartReservation",
500
+ "CartIdempotency"
501
+ ];
502
+ var CartModelCollisionError = class extends Error {
503
+ constructor(name) {
504
+ super(`[cart] Mongoose model "${name}" already exists on this connection. For hot-reload / test fixtures, pass \`forceRecreate: true\` to clobber the existing model. For two cart engines, use two Mongoose connections (\`mongoose.createConnection(...)\`) — each has its own model registry.`);
505
+ this.name = "CartModelCollisionError";
506
+ }
507
+ };
508
+ /**
509
+ * Apply `autoIndex` schema option to a set of models.
510
+ *
511
+ * Mongoose 9 defers `Model.init()` until the first query, so setting
512
+ * `schema.autoIndex` after `connection.model()` is safe.
513
+ */
514
+ function applyAutoIndex(models, autoIndex) {
515
+ if (autoIndex === void 0) return;
516
+ for (const [name, model] of Object.entries(models)) {
517
+ const value = typeof autoIndex === "boolean" ? autoIndex : autoIndex[name] ?? void 0;
518
+ if (value !== void 0) model.schema.set("autoIndex", value);
519
+ }
520
+ }
521
+ function createCartModels(connection, options = {}) {
522
+ if (options.forceRecreate) {
523
+ for (const name of CART_MODEL_NAMES) if (connection.models[name]) connection.deleteModel(name);
524
+ } else for (const name of CART_MODEL_NAMES) if (connection.models[name]) throw new CartModelCollisionError(name);
525
+ const tenant = resolveCartTenant(options);
526
+ const modelOpts = options.collectionPrefix !== void 0 ? { collectionPrefix: options.collectionPrefix } : {};
527
+ const models = {
528
+ Draft: createDraftModel(connection, modelOpts),
529
+ Checkout: createCheckoutModel(connection, modelOpts),
530
+ Reservation: createReservationModel(connection, modelOpts),
531
+ Idempotency: createIdempotencyModel(connection, modelOpts)
532
+ };
533
+ for (const model of Object.values(models)) injectTenantField(model.schema, tenant);
534
+ applyAutoIndex(models, options.autoIndex);
535
+ return models;
536
+ }
537
+ //#endregion
538
+ //#region src/engine/cart-event-publisher.ts
539
+ var CartEventPublisher = class {
540
+ events;
541
+ outbox;
542
+ clock;
543
+ constructor(deps) {
544
+ this.events = deps.events;
545
+ this.outbox = deps.outbox;
546
+ this.clock = deps.clock;
547
+ }
548
+ async emit(type, payload, ctx, options = {}) {
549
+ const event = createCartEvent(type, {
550
+ ...payload,
551
+ emittedAt: this.clock.now().toISOString(),
552
+ correlationId: ctx.correlationId,
553
+ organizationId: ctx.organizationId,
554
+ actorRef: ctx.actorRef
555
+ }, {
556
+ timestamp: this.clock.now(),
557
+ resource: options.resource,
558
+ resourceId: options.resourceId,
559
+ userId: ctx.actorKind === "user" ? ctx.actorRef : void 0,
560
+ organizationId: ctx.organizationId,
561
+ correlationId: ctx.correlationId,
562
+ aggregate: options.aggregate
563
+ });
564
+ if (this.outbox) await this.outbox.save(event, { session: ctx.session });
565
+ else if (ctx.session) throw new Error("CartEventPublisher.emit: ctx.session requires a host-provided outbox for durable event writes");
566
+ if (!ctx.session) await this.events.publish(event);
567
+ }
568
+ };
569
+ //#endregion
570
+ //#region src/services/pricing.service.ts
571
+ /**
572
+ * Pricing pipeline — composable, bridge-activated.
573
+ *
574
+ * Steps run in frozen order. Each step only runs if its bridge is present.
575
+ * No bridge = no step = no overhead.
576
+ *
577
+ * 1. kind.price() — per-line base + kind-specific pricing
578
+ * 2. promo-apply — PromotionsBridge.evaluate() if present
579
+ * 3. tax — TaxBridge.calculate() if present
580
+ * 4. shipping — ShippingBridge.quote() if present
581
+ * 5. rounding — final integer-money rounding (always runs)
582
+ *
583
+ * Incremental repricing:
584
+ * Callers may pass `previous` — the pricing snapshot from before the
585
+ * mutation. Lines whose (lineId + payload) are unchanged reuse the prior
586
+ * `unitPrice` and `validUntil` without hitting the catalog; only new or
587
+ * payload-changed lines pay a fresh `kind.price()` call. Promo, tax, and
588
+ * shipping always re-run because they depend on cart composition. This
589
+ * means a 10-line cart + "remove one" = ZERO catalog reads in step 1
590
+ * (all 9 remaining lines reuse their priced entries).
591
+ *
592
+ * Unit prices can drift between caches — the pricing hash interlock at
593
+ * checkout-freeze still catches drift, so reuse here is safe.
594
+ */
595
+ async function runPricing(opts) {
596
+ const kindCtx = {
597
+ ...opts.ctx,
598
+ bridges: {
599
+ catalog: opts.bridges.catalog,
600
+ inventory: opts.bridges.inventory,
601
+ promotions: opts.bridges.promotions,
602
+ tax: opts.bridges.tax,
603
+ shipping: opts.bridges.shipping
604
+ }
605
+ };
606
+ const priorByLineId = /* @__PURE__ */ new Map();
607
+ if (opts.previous?.lines) for (const p of opts.previous.lines) priorByLineId.set(p.lineId, p);
608
+ const pricedLines = await Promise.all(opts.lines.map(async (line) => {
609
+ const prior = priorByLineId.get(line.lineId);
610
+ if (prior && canReuse(line, prior)) return rebuildSubtotals(prior, line, opts.currency);
611
+ const kind = opts.kinds.get(line.kind);
612
+ const asLineLike = {
613
+ lineId: line.lineId,
614
+ kind: line.kind,
615
+ quantity: line.quantity,
616
+ payload: line.payload,
617
+ currency: opts.currency,
618
+ overrideUnitPrice: line.overrideUnitPrice
619
+ };
620
+ return kind.price(asLineLike, kindCtx);
621
+ }));
622
+ const adjustments = [];
623
+ if (opts.bridges.promotions) {
624
+ const cartSnapshot = {
625
+ organizationId: opts.ctx.organizationId,
626
+ actorRef: opts.ctx.actorRef,
627
+ actorKind: opts.ctx.actorKind,
628
+ currency: opts.currency,
629
+ lines: pricedLines,
630
+ subtotal: sumMoney(pricedLines.map((l) => l.subtotals.prePromo), opts.currency),
631
+ appliedPromoCodes: []
632
+ };
633
+ const promoResults = await opts.bridges.promotions.evaluate(cartSnapshot, opts.ctx);
634
+ for (const result of promoResults.sort((a, b) => b.priority - a.priority)) {
635
+ const appliedAmount = computeAdjustmentAmount(result, pricedLines, opts.currency);
636
+ adjustments.push({
637
+ adjustmentId: `adj_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
638
+ source: "promotion",
639
+ ruleRef: result.ruleRef,
640
+ spec: result.adjustment,
641
+ targetLineId: result.targetLineId,
642
+ appliedAmount,
643
+ explanation: result.explanation,
644
+ priority: result.priority,
645
+ appliedAt: opts.clock.now()
646
+ });
647
+ if (result.targetLineId) {
648
+ const target = pricedLines.find((l) => l.lineId === result.targetLineId);
649
+ if (target) {
650
+ target.subtotals.postPromo = {
651
+ amount: target.subtotals.postPromo.amount - appliedAmount.amount,
652
+ currency: opts.currency
653
+ };
654
+ target.discountTotal = {
655
+ amount: target.discountTotal.amount + appliedAmount.amount,
656
+ currency: opts.currency
657
+ };
658
+ }
659
+ }
660
+ }
661
+ }
662
+ if (opts.bridges.tax) {
663
+ const taxResult = await opts.bridges.tax.calculate({
664
+ currency: opts.currency,
665
+ lines: pricedLines,
666
+ taxClassByLine: {}
667
+ }, opts.ctx);
668
+ for (const line of pricedLines) {
669
+ const lineTax = taxResult.lineTaxes[line.lineId];
670
+ if (lineTax) {
671
+ line.taxTotal = lineTax;
672
+ line.subtotals.postPromoPostTax = {
673
+ amount: line.subtotals.postPromo.amount + lineTax.amount,
674
+ currency: opts.currency
675
+ };
676
+ }
677
+ }
678
+ } else for (const line of pricedLines) line.subtotals.postPromoPostTax = { ...line.subtotals.postPromo };
679
+ let shippingTotal = money(0, opts.currency);
680
+ if (opts.bridges.shipping) {
681
+ const subtotalPreTax = sumMoney(pricedLines.map((l) => l.subtotals.postPromo), opts.currency);
682
+ const subtotalPostTax = sumMoney(pricedLines.map((l) => l.subtotals.postPromoPostTax), opts.currency);
683
+ const quoteResult = await opts.bridges.shipping.quote({
684
+ currency: opts.currency,
685
+ lines: pricedLines,
686
+ destination: {
687
+ line1: "",
688
+ city: "",
689
+ country: ""
690
+ },
691
+ subtotals: {
692
+ prePromo: sumMoney(pricedLines.map((l) => l.subtotals.prePromo), opts.currency),
693
+ postPromo: subtotalPreTax,
694
+ postPromoPreTax: subtotalPreTax,
695
+ postPromoPostTax: subtotalPostTax
696
+ }
697
+ }, opts.ctx);
698
+ if (quoteResult.selected) shippingTotal = quoteResult.selected.price;
699
+ }
700
+ const subtotal = sumMoney(pricedLines.map((l) => l.subtotals.prePromo), opts.currency);
701
+ const discount = sumMoney([...pricedLines.map((l) => l.discountTotal), ...adjustments.filter((a) => !a.targetLineId).map((a) => a.appliedAmount)], opts.currency);
702
+ const tax = sumMoney(pricedLines.map((l) => l.taxTotal), opts.currency);
703
+ const orderDiscount = sumMoney(adjustments.filter((a) => !a.targetLineId).map((a) => a.appliedAmount), opts.currency);
704
+ const grandTotal = {
705
+ amount: Math.max(0, subtotal.amount - discount.amount + tax.amount + shippingTotal.amount),
706
+ currency: opts.currency
707
+ };
708
+ const validUntils = pricedLines.map((l) => l.validUntil).filter((d) => d !== null);
709
+ const pricingValidUntil = validUntils.length > 0 ? new Date(Math.min(...validUntils.map((d) => d.getTime()))) : null;
710
+ return {
711
+ snapshot: {
712
+ lines: pricedLines,
713
+ orderDiscount,
714
+ shipping: shippingTotal,
715
+ tax,
716
+ totals: {
717
+ subtotal,
718
+ discount,
719
+ taxTotal: tax,
720
+ shippingTotal,
721
+ grandTotal
722
+ },
723
+ pricingValidUntil,
724
+ pricingHash: buildPricingHash(pricedLines),
725
+ computedAt: opts.clock.now()
726
+ },
727
+ adjustments
728
+ };
729
+ }
730
+ function sumMoney(moneys, fallbackCurrency) {
731
+ if (moneys.length === 0) return money(0, fallbackCurrency);
732
+ return {
733
+ amount: moneys.reduce((sum, m) => sum + m.amount, 0),
734
+ currency: moneys[0].currency
735
+ };
736
+ }
737
+ /**
738
+ * Can the prior priced entry be reused for this line?
739
+ *
740
+ * The draft repository treats `(lineId, kind, payload)` as immutable once a
741
+ * line exists — `updateItemQuantity` only changes `quantity`, `mergeLine`
742
+ * bumps the qty of a matching line rather than rewriting its payload. So
743
+ * matching on `lineId` is enough to know the catalog lookup would return
744
+ * the same unitPrice.
745
+ *
746
+ * The one invalidation is `overrideUnitPrice`: a host that just set or
747
+ * unset an override must go through `kind.price()` again to honor it.
748
+ */
749
+ function canReuse(line, prior) {
750
+ const override = line.overrideUnitPrice;
751
+ if (!override) return true;
752
+ return override.amount === prior.unitPrice.amount && override.currency === prior.unitPrice.currency;
753
+ }
754
+ /**
755
+ * Rebuild per-line subtotals from the prior unit price at the new
756
+ * quantity. Resets promo/tax accumulators because steps 2-4 recompute
757
+ * them from scratch against the current cart composition.
758
+ */
759
+ function rebuildSubtotals(prior, line, currency) {
760
+ const unitPrice = prior.unitPrice;
761
+ const lineTotal = {
762
+ amount: unitPrice.amount * line.quantity,
763
+ currency
764
+ };
765
+ return {
766
+ lineId: line.lineId,
767
+ unitPrice,
768
+ quantity: line.quantity,
769
+ subtotals: {
770
+ prePromo: lineTotal,
771
+ postPromo: lineTotal,
772
+ postPromoPostTax: lineTotal
773
+ },
774
+ discountTotal: {
775
+ amount: 0,
776
+ currency
777
+ },
778
+ taxTotal: {
779
+ amount: 0,
780
+ currency
781
+ },
782
+ validUntil: prior.validUntil,
783
+ kindMeta: prior.kindMeta
784
+ };
785
+ }
786
+ function buildPricingHash(lines) {
787
+ return lines.map((l) => `${l.lineId}:${l.quantity}:${l.subtotals.postPromoPostTax.amount}:${l.subtotals.postPromoPostTax.currency}`).sort().join("|");
788
+ }
789
+ function computeAdjustmentAmount(result, lines, currency) {
790
+ const spec = result.adjustment;
791
+ if (spec.type === "fixed") return spec.value;
792
+ if (spec.type === "percent") {
793
+ if (result.targetLineId) {
794
+ const target = lines.find((l) => l.lineId === result.targetLineId);
795
+ if (target) return {
796
+ amount: Math.round(target.subtotals.prePromo.amount * spec.value / 100),
797
+ currency
798
+ };
799
+ }
800
+ const total = lines.reduce((s, l) => s + l.subtotals.prePromo.amount, 0);
801
+ return {
802
+ amount: Math.round(total * spec.value / 100),
803
+ currency
804
+ };
805
+ }
806
+ return money(0, currency);
807
+ }
808
+ //#endregion
809
+ //#region src/repositories/draft.repository.ts
810
+ /**
811
+ * DraftRepository — extends mongokit's `Repository<DraftDocument>` directly.
812
+ *
813
+ * All domain logic (validated addItem, merge, pricing, clear) lives here.
814
+ * Multi-tenant scoping is enforced by `multiTenantPlugin` at POLICY priority;
815
+ * `publicId` is generated by `customIdPlugin`. Optimistic concurrency runs
816
+ * through mongokit's `update()` so all hooks (audit, observability) fire.
817
+ */
818
+ var DraftRepository = class extends Repository {
819
+ kinds;
820
+ bridges;
821
+ clock;
822
+ id;
823
+ defaultCurrency;
824
+ eventPublisher;
825
+ constructor(model, plugins, deps) {
826
+ super(model, plugins);
827
+ this.kinds = deps.kinds;
828
+ this.bridges = deps.bridges;
829
+ this.clock = deps.clock;
830
+ this.id = deps.id;
831
+ this.defaultCurrency = deps.defaultCurrency;
832
+ this.eventPublisher = deps.eventPublisher;
833
+ }
834
+ async findActiveByActor(actorRef, ctx) {
835
+ return await this.getByQuery({
836
+ actorRef,
837
+ status: "active"
838
+ }, this.readOptions(ctx));
839
+ }
840
+ async findByPublicId(publicId, ctx) {
841
+ return await this.getByQuery({ publicId }, this.readOptions(ctx));
842
+ }
843
+ async getOrCreateDraft(ctx) {
844
+ const existing = await this.findActiveByActor(ctx.actorRef, ctx);
845
+ if (existing) return existing;
846
+ const created = await this.createForActor({
847
+ actorRef: ctx.actorRef,
848
+ actorKind: ctx.actorKind,
849
+ status: "active",
850
+ currency: this.defaultCurrency,
851
+ lines: [],
852
+ adjustments: [],
853
+ pricing: null
854
+ }, ctx);
855
+ await this.eventPublisher.emit(CartEvents.DRAFT_CREATED, { draftId: created.publicId }, ctx, {
856
+ resource: "draft",
857
+ resourceId: created.publicId,
858
+ aggregate: {
859
+ type: "draft",
860
+ id: created.publicId
861
+ }
862
+ });
863
+ return created;
864
+ }
865
+ async addItem(input, ctx) {
866
+ const draft = await this.getOrCreateDraft(ctx);
867
+ const kind = this.kinds.get(input.kind);
868
+ const quantity = assertPositiveInteger(input.quantity, input.kind);
869
+ const parsedPayload = kind.payloadSchema.safeParse(input.payload);
870
+ if (!parsedPayload.success) throw new KindError(input.kind, "invalid payload shape", { details: { issues: parsedPayload.error.issues } });
871
+ const newLine = {
872
+ lineId: `line_${this.id.newId()}`,
873
+ kind: input.kind,
874
+ quantity,
875
+ payload: parsedPayload.data,
876
+ currency: draft.currency,
877
+ overrideUnitPrice: input.overrideUnitPrice
878
+ };
879
+ const kindCtx = this.kindContextFor(ctx);
880
+ await kind.validate(newLine, kindCtx);
881
+ const display = input.display !== void 0 ? input.display : kind.displayOf ? await kind.displayOf(newLine, kindCtx) : null;
882
+ const persistedLine = {
883
+ lineId: newLine.lineId,
884
+ kind: newLine.kind,
885
+ payload: newLine.payload,
886
+ quantity: newLine.quantity,
887
+ overrideUnitPrice: newLine.overrideUnitPrice,
888
+ display: display ?? void 0,
889
+ addedAt: this.clock.now()
890
+ };
891
+ const nextLines = this.mergeLine(draft.lines, persistedLine);
892
+ const { snapshot: pricing } = await this.price(nextLines, draft.currency, ctx, draft.pricing);
893
+ const updated = await this.updateWithVersion(draft._id, draft.version, {
894
+ lines: nextLines,
895
+ pricing
896
+ }, ctx);
897
+ await this.eventPublisher.emit(CartEvents.DRAFT_ITEM_ADDED, {
898
+ draftId: updated.publicId,
899
+ lineId: persistedLine.lineId,
900
+ kind: persistedLine.kind,
901
+ quantity: persistedLine.quantity
902
+ }, ctx, {
903
+ resource: "draft",
904
+ resourceId: updated.publicId,
905
+ aggregate: {
906
+ type: "draft",
907
+ id: updated.publicId
908
+ }
909
+ });
910
+ return updated;
911
+ }
912
+ async updateItemQuantity(input, ctx) {
913
+ if (input.quantity < 1) return this.removeItem({
914
+ draftPublicId: input.draftPublicId,
915
+ lineId: input.lineId
916
+ }, ctx);
917
+ const draft = await this.requireDraft(input.draftPublicId, ctx);
918
+ const currentLines = draft.lines;
919
+ const existingLine = currentLines.find((l) => l.lineId === input.lineId);
920
+ if (!existingLine) throw new NotFoundError("line", input.lineId, ctx.organizationId);
921
+ const quantity = assertPositiveInteger(input.quantity, existingLine.kind);
922
+ if (existingLine.quantity === quantity) return draft;
923
+ const nextLines = currentLines.map((l) => l.lineId === input.lineId ? {
924
+ ...l,
925
+ quantity
926
+ } : l);
927
+ const { snapshot: pricing } = await this.price(nextLines, draft.currency, ctx, draft.pricing);
928
+ const updated = await this.updateWithVersion(draft._id, draft.version, {
929
+ lines: nextLines,
930
+ pricing
931
+ }, ctx);
932
+ await this.eventPublisher.emit(CartEvents.DRAFT_ITEM_UPDATED, {
933
+ draftId: updated.publicId,
934
+ lineId: input.lineId,
935
+ quantity
936
+ }, ctx, {
937
+ resource: "draft",
938
+ resourceId: updated.publicId,
939
+ aggregate: {
940
+ type: "draft",
941
+ id: updated.publicId
942
+ }
943
+ });
944
+ return updated;
945
+ }
946
+ async removeItem(input, ctx) {
947
+ const draft = await this.requireDraft(input.draftPublicId, ctx);
948
+ const currentLines = draft.lines;
949
+ const nextLines = currentLines.filter((l) => l.lineId !== input.lineId);
950
+ if (nextLines.length === currentLines.length) return draft;
951
+ const pricing = nextLines.length === 0 ? null : (await this.price(nextLines, draft.currency, ctx, draft.pricing)).snapshot;
952
+ const updated = await this.updateWithVersion(draft._id, draft.version, {
953
+ lines: nextLines,
954
+ pricing
955
+ }, ctx);
956
+ await this.eventPublisher.emit(CartEvents.DRAFT_ITEM_REMOVED, {
957
+ draftId: updated.publicId,
958
+ lineId: input.lineId
959
+ }, ctx, {
960
+ resource: "draft",
961
+ resourceId: updated.publicId,
962
+ aggregate: {
963
+ type: "draft",
964
+ id: updated.publicId
965
+ }
966
+ });
967
+ return updated;
968
+ }
969
+ async clear(draftPublicId, ctx) {
970
+ const draft = await this.requireDraft(draftPublicId, ctx);
971
+ const updated = await this.updateWithVersion(draft._id, draft.version, {
972
+ lines: [],
973
+ pricing: null
974
+ }, ctx);
975
+ for (const line of draft.lines) await this.eventPublisher.emit(CartEvents.DRAFT_ITEM_REMOVED, {
976
+ draftId: updated.publicId,
977
+ lineId: line.lineId
978
+ }, ctx, {
979
+ resource: "draft",
980
+ resourceId: updated.publicId,
981
+ aggregate: {
982
+ type: "draft",
983
+ id: updated.publicId
984
+ }
985
+ });
986
+ return updated;
987
+ }
988
+ /**
989
+ * Create a new draft for the given actor. Tenant scoping is injected by
990
+ * `multiTenantPlugin` from `ctx.organizationId`; `publicId` is generated
991
+ * by `customIdPlugin`.
992
+ */
993
+ async createForActor(data, ctx) {
994
+ return await this.create({
995
+ ...data,
996
+ version: 0
997
+ }, this.writeOptions(ctx));
998
+ }
999
+ /**
1000
+ * Optimistic-concurrency update: applies `$set: updates` and `$inc: version`
1001
+ * only when the persisted version matches `expectedVersion`. Throws
1002
+ * `ConcurrencyError` on mismatch (mongokit raises 404 when no doc matches
1003
+ * `{ _id, version }` and we re-translate it).
1004
+ */
1005
+ async updateWithVersion(draftId, expectedVersion, updates, ctx) {
1006
+ try {
1007
+ return await this.update(draftId, {
1008
+ $set: updates,
1009
+ $inc: { version: 1 }
1010
+ }, {
1011
+ ...this.writeOptions(ctx),
1012
+ query: { version: expectedVersion },
1013
+ lean: true,
1014
+ throwOnNotFound: true
1015
+ });
1016
+ } catch (err) {
1017
+ if (isNotFound$2(err)) throw new ConcurrencyError("draft", expectedVersion, String(draftId));
1018
+ throw err;
1019
+ }
1020
+ }
1021
+ /**
1022
+ * Atomic transition `active → abandoned`. Returns null if the draft was
1023
+ * already in a non-active state.
1024
+ */
1025
+ async markAbandoned(draftId, ctx) {
1026
+ try {
1027
+ const updated = await this.update(draftId, {
1028
+ $set: { status: "abandoned" },
1029
+ $inc: { version: 1 }
1030
+ }, {
1031
+ ...this.writeOptions(ctx),
1032
+ query: { status: "active" },
1033
+ lean: true
1034
+ });
1035
+ if (!updated) return null;
1036
+ const doc = updated;
1037
+ const pricing = doc.pricing;
1038
+ await this.eventPublisher.emit(CartEvents.DRAFT_ABANDONED, {
1039
+ draftId: doc.publicId,
1040
+ abandonedAt: this.clock.now().toISOString(),
1041
+ lineCount: doc.lines.length,
1042
+ grandTotal: pricing?.totals?.grandTotal ?? {
1043
+ amount: 0,
1044
+ currency: doc.currency
1045
+ }
1046
+ }, ctx, {
1047
+ resource: "draft",
1048
+ resourceId: doc.publicId,
1049
+ aggregate: {
1050
+ type: "draft",
1051
+ id: doc.publicId
1052
+ }
1053
+ });
1054
+ return doc;
1055
+ } catch (err) {
1056
+ if (isNotFound$2(err)) return null;
1057
+ throw err;
1058
+ }
1059
+ }
1060
+ /**
1061
+ * Mark a draft as converted (called from CheckoutRepository.commit).
1062
+ * Best-effort: a missed update is reconciled by the next getOrCreate.
1063
+ */
1064
+ async markConverted(draftId, ctx) {
1065
+ try {
1066
+ await this.update(draftId, {
1067
+ $set: { status: "converted" },
1068
+ $inc: { version: 1 }
1069
+ }, this.writeOptions(ctx));
1070
+ } catch {}
1071
+ }
1072
+ /**
1073
+ * Replace the line collection atomically and refresh the pricing snapshot.
1074
+ * Internal services use this to keep merge-like flows inside repository
1075
+ * concurrency + pricing rules instead of hand-writing persistence logic.
1076
+ */
1077
+ async replaceLines(input, ctx) {
1078
+ const draft = await this.requireDraft(input.draftPublicId, ctx);
1079
+ const nextLines = input.lines.map((line) => ({ ...line }));
1080
+ const pricing = nextLines.length === 0 ? null : (await this.price(nextLines, draft.currency, ctx, draft.pricing)).snapshot;
1081
+ return this.updateWithVersion(draft._id, draft.version, {
1082
+ lines: nextLines,
1083
+ pricing
1084
+ }, ctx);
1085
+ }
1086
+ mergeLines(existing, incoming) {
1087
+ return incoming.reduce((acc, line) => this.mergeLine(acc, { ...line }), [...existing]);
1088
+ }
1089
+ readOptions(ctx) {
1090
+ return {
1091
+ organizationId: ctx.organizationId,
1092
+ skipTenant: ctx.skipTenant,
1093
+ session: ctx.session,
1094
+ lean: true,
1095
+ throwOnNotFound: false
1096
+ };
1097
+ }
1098
+ writeOptions(ctx) {
1099
+ return {
1100
+ organizationId: ctx.organizationId,
1101
+ skipTenant: ctx.skipTenant,
1102
+ session: ctx.session
1103
+ };
1104
+ }
1105
+ async price(lines, currency, ctx, previous) {
1106
+ return runPricing({
1107
+ lines,
1108
+ currency,
1109
+ kinds: this.kinds,
1110
+ bridges: this.bridges,
1111
+ clock: this.clock,
1112
+ ctx,
1113
+ previous
1114
+ });
1115
+ }
1116
+ async requireDraft(publicId, ctx) {
1117
+ const draft = await this.findByPublicId(publicId, ctx);
1118
+ if (!draft) throw new NotFoundError("draft", publicId, ctx.organizationId);
1119
+ return draft;
1120
+ }
1121
+ kindContextFor(ctx) {
1122
+ return {
1123
+ ...ctx,
1124
+ bridges: {
1125
+ catalog: this.bridges.catalog,
1126
+ inventory: this.bridges.inventory,
1127
+ promotions: this.bridges.promotions,
1128
+ tax: this.bridges.tax,
1129
+ shipping: this.bridges.shipping
1130
+ }
1131
+ };
1132
+ }
1133
+ mergeLine(existing, incoming) {
1134
+ const key = this.computeMergeKey(incoming);
1135
+ if (key === null) return [...existing, incoming];
1136
+ const idx = existing.findIndex((l) => this.computeMergeKey(l) === key);
1137
+ if (idx === -1) return [...existing, incoming];
1138
+ const merged = {
1139
+ ...existing[idx],
1140
+ quantity: existing[idx].quantity + incoming.quantity
1141
+ };
1142
+ return existing.map((l, i) => i === idx ? merged : l);
1143
+ }
1144
+ /**
1145
+ * Resolve a line's merge key.
1146
+ *
1147
+ * Preferred path: delegate to `LineKind.mergeKey()` — every built-in kind
1148
+ * knows its own payload shape and returns a stable grouping key
1149
+ * (e.g. `variant:${productRef}:${variantSku}` for the variant kind).
1150
+ *
1151
+ * Fallback: for kinds that don't implement `mergeKey()` (older custom
1152
+ * kinds, or unregistered kinds seen on legacy drafts), check for a
1153
+ * `payload.skuRef` field — the shape the repository historically
1154
+ * assumed. This keeps drafts written before this change mergeable.
1155
+ */
1156
+ computeMergeKey(line) {
1157
+ const kind = this.kinds.tryGet(line.kind);
1158
+ if (kind?.mergeKey) {
1159
+ const lineLike = {
1160
+ lineId: line.lineId,
1161
+ kind: line.kind,
1162
+ quantity: line.quantity,
1163
+ payload: line.payload,
1164
+ currency: this.defaultCurrency,
1165
+ overrideUnitPrice: line.overrideUnitPrice
1166
+ };
1167
+ return kind.mergeKey(lineLike);
1168
+ }
1169
+ const payload = line.payload;
1170
+ if (!payload?.skuRef) return null;
1171
+ return `${line.kind}:${payload.skuRef}`;
1172
+ }
1173
+ };
1174
+ function isNotFound$2(err) {
1175
+ return typeof err === "object" && err !== null && err.status === 404;
1176
+ }
1177
+ function assertPositiveInteger(quantity, kind) {
1178
+ if (!Number.isInteger(quantity) || quantity < 1) throw new KindError(kind, `quantity must be a positive integer, got ${quantity}`);
1179
+ return quantity;
1180
+ }
1181
+ //#endregion
1182
+ //#region src/repositories/checkout.repository.ts
1183
+ /**
1184
+ * CheckoutRepository — extends mongokit's `Repository<CheckoutDocument>`.
1185
+ *
1186
+ * All domain logic (createFromDraft with hash interlock, commit, cancel)
1187
+ * lives here. Tenant scoping comes from `multiTenantPlugin`; `publicId`
1188
+ * comes from `customIdPlugin`. State transitions go through mongokit's
1189
+ * `update()` so all hooks fire.
1190
+ */
1191
+ var CheckoutRepository = class extends Repository {
1192
+ draftRepo;
1193
+ clock;
1194
+ eventPublisher;
1195
+ constructor(model, plugins, deps) {
1196
+ super(model, plugins);
1197
+ this.draftRepo = deps.draftRepo;
1198
+ this.clock = deps.clock;
1199
+ this.eventPublisher = deps.eventPublisher;
1200
+ }
1201
+ async findByPublicId(publicId, ctx) {
1202
+ return await this.getByQuery({ publicId }, this.readOptions(ctx));
1203
+ }
1204
+ async findByDraft(draftId, ctx) {
1205
+ return await this.getByQuery({ draftId }, this.readOptions(ctx));
1206
+ }
1207
+ /**
1208
+ * Find the currently-open checkout for a draft.
1209
+ * Used by `createFromDraft` dedup — terminal checkouts (canceled /
1210
+ * finalized) are history, they must NOT be returned here or the host
1211
+ * would try to commit a canceled snapshot on retry.
1212
+ */
1213
+ async findOpenByDraft(draftId, ctx) {
1214
+ return await this.getByQuery({
1215
+ draftId,
1216
+ state: "open"
1217
+ }, this.readOptions(ctx));
1218
+ }
1219
+ async createFromDraft(input, ctx) {
1220
+ const draft = await this.draftRepo.findByPublicId(input.draftPublicId, ctx);
1221
+ if (!draft) throw new NotFoundError("draft", input.draftPublicId, ctx.organizationId);
1222
+ if (draft.status !== "active") throw new Error(`Cannot create checkout from draft in status '${draft.status}'`);
1223
+ if (draft.lines.length === 0) throw new Error("Cannot create checkout from an empty draft");
1224
+ if (!draft.pricing) throw new Error("Cannot create checkout from a draft with no priced snapshot — call addItem first");
1225
+ const draftPricingHash = draft.pricing.pricingHash;
1226
+ if (input.expectedPricingHash !== null && draftPricingHash !== input.expectedPricingHash) throw new PriceChangedError(input.expectedPricingHash, draftPricingHash ?? "<missing>", { draftPublicId: input.draftPublicId });
1227
+ const existing = await this.findOpenByDraft(draft._id, ctx);
1228
+ if (existing) return existing;
1229
+ const nowIso = this.clock.now().toISOString();
1230
+ const doc = await this.create({
1231
+ draftId: draft._id,
1232
+ actorRef: draft.actorRef,
1233
+ actorKind: draft.actorKind,
1234
+ state: "open",
1235
+ flowState: {
1236
+ lastStep: CheckoutStep.CreateCheckout,
1237
+ startedAt: nowIso,
1238
+ updatedAt: nowIso
1239
+ },
1240
+ lines: draft.lines,
1241
+ adjustments: draft.adjustments,
1242
+ currency: draft.currency,
1243
+ pricing: draft.pricing,
1244
+ externalRef: null,
1245
+ canceledReason: null,
1246
+ version: 0,
1247
+ metadata: null,
1248
+ privateMetadata: null
1249
+ }, this.writeOptions(ctx));
1250
+ const pricing = doc.pricing;
1251
+ await this.eventPublisher.emit(CartEvents.CHECKOUT_CREATED, {
1252
+ checkoutId: doc.publicId,
1253
+ draftId: input.draftPublicId,
1254
+ grandTotal: pricing.totals?.grandTotal ?? {
1255
+ amount: 0,
1256
+ currency: doc.currency
1257
+ }
1258
+ }, ctx, {
1259
+ resource: "checkout",
1260
+ resourceId: doc.publicId,
1261
+ aggregate: {
1262
+ type: "checkout",
1263
+ id: doc.publicId
1264
+ }
1265
+ });
1266
+ return doc;
1267
+ }
1268
+ async commit(input, ctx) {
1269
+ const checkout = await this.requireCheckout(input.checkoutPublicId, ctx);
1270
+ const draft = await this.draftRepo.getById(checkout.draftId, {
1271
+ organizationId: ctx.organizationId,
1272
+ skipTenant: ctx.skipTenant,
1273
+ session: ctx.session,
1274
+ lean: true,
1275
+ throwOnNotFound: false
1276
+ });
1277
+ if (checkout.state !== "open") throw new StateTransitionError(checkout.publicId, checkout.state, "finalized");
1278
+ const nowIso = this.clock.now().toISOString();
1279
+ const updated = await this.updateWithVersion(checkout._id, checkout.version, {
1280
+ state: "finalized",
1281
+ externalRef: input.externalRef ?? null,
1282
+ flowState: {
1283
+ ...checkout.flowState,
1284
+ lastStep: CheckoutStep.Commit,
1285
+ updatedAt: nowIso
1286
+ }
1287
+ }, ctx);
1288
+ await this.draftRepo.markConverted(checkout.draftId, ctx);
1289
+ const pricing = updated.pricing;
1290
+ await this.eventPublisher.emit(CartEvents.CHECKOUT_COMMITTED, {
1291
+ checkoutId: updated.publicId,
1292
+ draftId: draft?.publicId ?? String(updated.draftId),
1293
+ externalRef: updated.externalRef ?? null,
1294
+ grandTotal: pricing.totals?.grandTotal ?? {
1295
+ amount: 0,
1296
+ currency: updated.currency
1297
+ }
1298
+ }, ctx, {
1299
+ resource: "checkout",
1300
+ resourceId: updated.publicId,
1301
+ aggregate: {
1302
+ type: "checkout",
1303
+ id: updated.publicId
1304
+ }
1305
+ });
1306
+ return updated;
1307
+ }
1308
+ async cancel(input, ctx) {
1309
+ const checkout = await this.requireCheckout(input.checkoutPublicId, ctx);
1310
+ if (checkout.state !== "open") throw new StateTransitionError(checkout.publicId, checkout.state, "canceled");
1311
+ const nowIso = this.clock.now().toISOString();
1312
+ const updated = await this.updateWithVersion(checkout._id, checkout.version, {
1313
+ state: "canceled",
1314
+ canceledReason: input.reason,
1315
+ flowState: {
1316
+ ...checkout.flowState,
1317
+ updatedAt: nowIso
1318
+ }
1319
+ }, ctx);
1320
+ await this.eventPublisher.emit(CartEvents.CHECKOUT_CANCELED, {
1321
+ checkoutId: updated.publicId,
1322
+ reason: input.reason
1323
+ }, ctx, {
1324
+ resource: "checkout",
1325
+ resourceId: updated.publicId,
1326
+ aggregate: {
1327
+ type: "checkout",
1328
+ id: updated.publicId
1329
+ }
1330
+ });
1331
+ return updated;
1332
+ }
1333
+ async updateWithVersion(checkoutId, expectedVersion, updates, ctx) {
1334
+ try {
1335
+ return await this.update(checkoutId, {
1336
+ $set: updates,
1337
+ $inc: { version: 1 }
1338
+ }, {
1339
+ ...this.writeOptions(ctx),
1340
+ query: { version: expectedVersion },
1341
+ lean: true
1342
+ });
1343
+ } catch (err) {
1344
+ if (isNotFound$1(err)) throw new ConcurrencyError("checkout", expectedVersion, String(checkoutId));
1345
+ throw err;
1346
+ }
1347
+ }
1348
+ readOptions(ctx) {
1349
+ return {
1350
+ organizationId: ctx.organizationId,
1351
+ skipTenant: ctx.skipTenant,
1352
+ session: ctx.session,
1353
+ lean: true,
1354
+ throwOnNotFound: false
1355
+ };
1356
+ }
1357
+ writeOptions(ctx) {
1358
+ return {
1359
+ organizationId: ctx.organizationId,
1360
+ skipTenant: ctx.skipTenant,
1361
+ session: ctx.session
1362
+ };
1363
+ }
1364
+ async requireCheckout(publicId, ctx) {
1365
+ const checkout = await this.findByPublicId(publicId, ctx);
1366
+ if (!checkout) throw new NotFoundError("checkout", publicId, ctx.organizationId);
1367
+ return checkout;
1368
+ }
1369
+ };
1370
+ function isNotFound$1(err) {
1371
+ return typeof err === "object" && err !== null && err.status === 404;
1372
+ }
1373
+ //#endregion
1374
+ //#region src/repositories/reservation.repository.ts
1375
+ /**
1376
+ * ReservationRepository — extends mongokit's `Repository<ReservationDocument>`.
1377
+ *
1378
+ * Tenant scoping is enforced by `multiTenantPlugin`; `publicId` comes from
1379
+ * `customIdPlugin`. The TTL index on `expiresAt` is a backstop — the
1380
+ * sweeper drives the active release loop via `findExpiredHeld`.
1381
+ */
1382
+ var ReservationRepository = class extends Repository {
1383
+ constructor(model, plugins) {
1384
+ super(model, plugins);
1385
+ }
1386
+ /** All reservations belonging to a checkout. */
1387
+ async findByCheckout(checkoutId, ctx) {
1388
+ return await this.findAll({ checkoutId }, this.readOptions(ctx));
1389
+ }
1390
+ /**
1391
+ * Expired held reservations for the sweeper. Routed through `getAll` so
1392
+ * the multi-tenant plugin scopes the query at POLICY priority.
1393
+ */
1394
+ async findExpiredHeld(asOf, limit, ctx) {
1395
+ return (await this.getAll({
1396
+ filters: {
1397
+ status: "held",
1398
+ expiresAt: { $lt: asOf }
1399
+ },
1400
+ sort: { expiresAt: 1 },
1401
+ page: 1,
1402
+ limit,
1403
+ countStrategy: "none"
1404
+ }, this.readOptions(ctx))).docs;
1405
+ }
1406
+ /** Atomic transition `held → released` via version check. */
1407
+ async markReleased(reservationId, expectedVersion, reason, ctx) {
1408
+ return this.atomicTransition(reservationId, {
1409
+ $set: {
1410
+ status: "released",
1411
+ releasedAt: /* @__PURE__ */ new Date(),
1412
+ releaseReason: reason
1413
+ },
1414
+ $inc: { version: 1 }
1415
+ }, {
1416
+ version: expectedVersion,
1417
+ status: "held"
1418
+ }, ctx);
1419
+ }
1420
+ /** Atomic transition `held → committed` on saga step 10. */
1421
+ async markCommitted(reservationId, expectedVersion, ctx) {
1422
+ return this.atomicTransition(reservationId, {
1423
+ $set: { status: "committed" },
1424
+ $inc: { version: 1 }
1425
+ }, {
1426
+ version: expectedVersion,
1427
+ status: "held"
1428
+ }, ctx);
1429
+ }
1430
+ async atomicTransition(id, data, constraints, ctx) {
1431
+ try {
1432
+ return await this.update(id, data, {
1433
+ ...this.writeOptions(ctx),
1434
+ query: constraints,
1435
+ lean: true
1436
+ });
1437
+ } catch (err) {
1438
+ if (isNotFound(err)) return null;
1439
+ throw err;
1440
+ }
1441
+ }
1442
+ readOptions(ctx) {
1443
+ return {
1444
+ organizationId: ctx.organizationId,
1445
+ skipTenant: ctx.skipTenant,
1446
+ session: ctx.session,
1447
+ lean: true
1448
+ };
1449
+ }
1450
+ writeOptions(ctx) {
1451
+ return {
1452
+ organizationId: ctx.organizationId,
1453
+ skipTenant: ctx.skipTenant,
1454
+ session: ctx.session
1455
+ };
1456
+ }
1457
+ };
1458
+ function isNotFound(err) {
1459
+ return typeof err === "object" && err !== null && err.status === 404;
1460
+ }
1461
+ //#endregion
1462
+ //#region src/repositories/idempotency.repository.ts
1463
+ /**
1464
+ * IdempotencyRepository — the storage backing cart's composite-identity
1465
+ * idempotency contract (plan §2).
1466
+ *
1467
+ * Provides:
1468
+ * - `findByIdentity()` — look up by the full composite key
1469
+ * - `insertInFlight()` — race-safe insert of a new lease
1470
+ * - `claimExpiredLease()` — reclaim a crashed in_flight record whose
1471
+ * lease has expired
1472
+ * - `markSucceeded()` / `markFailed()` — terminal transitions
1473
+ *
1474
+ * Used by `idempotencyPlugin` (later+) to implement the before:create /
1475
+ * before:update short-circuit. Hosts can also call these methods directly
1476
+ * for custom operations outside the plugin's hook path.
1477
+ */
1478
+ var IdempotencyRepository = class extends Repository {
1479
+ constructor(model, plugins = []) {
1480
+ super(model, plugins);
1481
+ }
1482
+ /** Look up a record by the full composite identity. */
1483
+ async findByIdentity(identity, ctx) {
1484
+ const session = ctx.session;
1485
+ return await this.Model.findOne({
1486
+ organizationId: identity.organizationId,
1487
+ cartRef: identity.cartRef,
1488
+ operation: identity.operation,
1489
+ actorRef: identity.actorRef,
1490
+ idempotencyKey: identity.idempotencyKey
1491
+ }, null, { session }).lean();
1492
+ }
1493
+ /**
1494
+ * Race-safe insert: try to insert a new `in_flight` record. Returns the
1495
+ * newly inserted record on success; returns `null` if the composite
1496
+ * unique index fired (meaning another writer got there first — caller
1497
+ * should then call `findByIdentity` to read the settled state).
1498
+ */
1499
+ async insertInFlight(identity, leaseToken, leaseExpiresAt, ctx) {
1500
+ const session = ctx.session;
1501
+ try {
1502
+ return (await this.Model.create([{
1503
+ ...identity,
1504
+ status: "in_flight",
1505
+ leaseToken,
1506
+ leaseExpiresAt
1507
+ }], { session }))[0];
1508
+ } catch (err) {
1509
+ if (isDuplicateKeyError(err)) return null;
1510
+ throw err;
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Claim an expired lease — transition an in_flight record with a dead
1515
+ * lease to a new lease token, so the caller can re-run the operation.
1516
+ *
1517
+ * Atomic via `findOneAndUpdate` with the prior leaseToken in the filter,
1518
+ * so two concurrent reclaimers can't both win.
1519
+ */
1520
+ async claimExpiredLease(identity, priorLeaseToken, newLeaseToken, newLeaseExpiresAt, ctx) {
1521
+ return await this.findOneAndUpdate({
1522
+ organizationId: identity.organizationId,
1523
+ cartRef: identity.cartRef,
1524
+ operation: identity.operation,
1525
+ actorRef: identity.actorRef,
1526
+ idempotencyKey: identity.idempotencyKey,
1527
+ status: "in_flight",
1528
+ leaseToken: priorLeaseToken
1529
+ }, { $set: {
1530
+ leaseToken: newLeaseToken,
1531
+ leaseExpiresAt: newLeaseExpiresAt
1532
+ } }, {
1533
+ returnDocument: "after",
1534
+ session: ctx.session,
1535
+ lean: true
1536
+ }) ?? null;
1537
+ }
1538
+ async markSucceeded(identity, leaseToken, replay, ctx) {
1539
+ return await this.findOneAndUpdate({
1540
+ organizationId: identity.organizationId,
1541
+ cartRef: identity.cartRef,
1542
+ operation: identity.operation,
1543
+ actorRef: identity.actorRef,
1544
+ idempotencyKey: identity.idempotencyKey,
1545
+ leaseToken
1546
+ }, { $set: {
1547
+ status: "succeeded",
1548
+ ...replay,
1549
+ completedAt: /* @__PURE__ */ new Date()
1550
+ } }, {
1551
+ returnDocument: "after",
1552
+ session: ctx.session,
1553
+ lean: true
1554
+ }) ?? null;
1555
+ }
1556
+ async markFailed(identity, leaseToken, error, ctx) {
1557
+ return await this.findOneAndUpdate({
1558
+ organizationId: identity.organizationId,
1559
+ cartRef: identity.cartRef,
1560
+ operation: identity.operation,
1561
+ actorRef: identity.actorRef,
1562
+ idempotencyKey: identity.idempotencyKey,
1563
+ leaseToken
1564
+ }, { $set: {
1565
+ status: "failed",
1566
+ error,
1567
+ completedAt: /* @__PURE__ */ new Date()
1568
+ } }, {
1569
+ returnDocument: "after",
1570
+ session: ctx.session,
1571
+ lean: true
1572
+ }) ?? null;
1573
+ }
1574
+ };
1575
+ function isDuplicateKeyError(err) {
1576
+ if (!err || typeof err !== "object") return false;
1577
+ const code = err.code;
1578
+ return code === 11e3 || code === 11001;
1579
+ }
1580
+ //#endregion
1581
+ //#region src/repositories/index.ts
1582
+ function tenantPlugin(fieldType = "objectId") {
1583
+ return multiTenantPlugin({
1584
+ tenantField: "organizationId",
1585
+ contextKey: "organizationId",
1586
+ required: false,
1587
+ skipWhen: (ctx) => ctx.skipTenant === true,
1588
+ fieldType
1589
+ });
1590
+ }
1591
+ function createCartRepositories(models, config) {
1592
+ const { kinds, bridges, clock, id, defaultCurrency, events, outbox, plugins = {}, tenantFieldType = "objectId", multiTenant = true } = config;
1593
+ const eventPublisher = new CartEventPublisher({
1594
+ events,
1595
+ outbox,
1596
+ clock
1597
+ });
1598
+ const tenantPlugins = multiTenant ? [tenantPlugin(tenantFieldType)] : [];
1599
+ const draft = new DraftRepository(models.Draft, [
1600
+ ...tenantPlugins,
1601
+ customIdPlugin({
1602
+ field: "publicId",
1603
+ generator: prefixedId({
1604
+ prefix: "cart",
1605
+ separator: "_",
1606
+ length: 20
1607
+ })
1608
+ }),
1609
+ ...plugins.draft ?? []
1610
+ ], {
1611
+ kinds,
1612
+ bridges,
1613
+ clock,
1614
+ id,
1615
+ defaultCurrency,
1616
+ eventPublisher
1617
+ });
1618
+ return {
1619
+ draft,
1620
+ checkout: new CheckoutRepository(models.Checkout, [
1621
+ ...tenantPlugins,
1622
+ customIdPlugin({
1623
+ field: "publicId",
1624
+ generator: prefixedId({
1625
+ prefix: "co",
1626
+ separator: "_",
1627
+ length: 20
1628
+ })
1629
+ }),
1630
+ ...plugins.checkout ?? []
1631
+ ], {
1632
+ draftRepo: draft,
1633
+ clock,
1634
+ eventPublisher
1635
+ }),
1636
+ reservation: new ReservationRepository(models.Reservation, [
1637
+ ...tenantPlugins,
1638
+ customIdPlugin({
1639
+ field: "publicId",
1640
+ generator: prefixedId({
1641
+ prefix: "resv",
1642
+ separator: "_",
1643
+ length: 20
1644
+ })
1645
+ }),
1646
+ ...plugins.reservation ?? []
1647
+ ]),
1648
+ idempotency: new IdempotencyRepository(models.Idempotency, plugins.idempotency ?? [])
1649
+ };
1650
+ }
1651
+ //#endregion
1652
+ //#region src/engine/internal-event-bus.ts
1653
+ var InProcessCartEventBus = class {
1654
+ name = "in-process-cart";
1655
+ subs = [];
1656
+ async publish(event) {
1657
+ const matching = this.subs.filter((s) => matchEventPattern(s.pattern, event.type));
1658
+ for (const sub of matching) try {
1659
+ await sub.handler(event);
1660
+ } catch {}
1661
+ }
1662
+ async publishMany(events) {
1663
+ const results = /* @__PURE__ */ new Map();
1664
+ for (const event of events) try {
1665
+ await this.publish(event);
1666
+ results.set(event.meta.id, null);
1667
+ } catch (err) {
1668
+ results.set(event.meta.id, err instanceof Error ? err : new Error(String(err)));
1669
+ }
1670
+ return results;
1671
+ }
1672
+ async subscribe(pattern, handler) {
1673
+ const sub = {
1674
+ pattern,
1675
+ handler
1676
+ };
1677
+ this.subs.push(sub);
1678
+ return () => {
1679
+ this.subs = this.subs.filter((s) => s !== sub);
1680
+ };
1681
+ }
1682
+ async close() {
1683
+ this.subs = [];
1684
+ }
1685
+ };
1686
+ //#endregion
1687
+ //#region src/engine/create-cart.ts
1688
+ /**
1689
+ * createCart() — build a cart engine.
1690
+ *
1691
+ * Repositories are the primary API. All domain logic (addItem, checkout,
1692
+ * commit, cancel) lives directly on the repository classes. Multi-tenant
1693
+ * scoping and `publicId` generation are handled by mongokit plugins wired
1694
+ * inside `createCartRepositories`, so callers just pass the connection
1695
+ * and bridges.
1696
+ */
1697
+ async function createCart(config) {
1698
+ if (!config.connection) throw new Error("createCart: config.connection is required");
1699
+ if (!config.kinds || config.kinds.length === 0) throw new Error("createCart: config.kinds must contain at least one LineKind");
1700
+ if (!config.bridges) throw new Error("createCart: config.bridges is required");
1701
+ if (!config.bridges.catalog) throw new Error("createCart: config.bridges.catalog is required");
1702
+ const kinds = createKindRegistry(config.kinds);
1703
+ const events = config.eventTransport ?? new InProcessCartEventBus();
1704
+ const clock = config.clock ?? systemClock;
1705
+ const id = config.id ?? cryptoIdPort;
1706
+ const defaultCurrency = config.defaultCurrency ?? "USD";
1707
+ const tenantFieldType = config.tenantFieldType ?? "objectId";
1708
+ const isRealConnection = typeof config.connection.model === "function";
1709
+ let models = {};
1710
+ let repositories = {};
1711
+ let mode = "lite";
1712
+ const multiTenant = config.multiTenant ?? true;
1713
+ if (isRealConnection) {
1714
+ models = createCartModels(config.connection, {
1715
+ tenantFieldType,
1716
+ multiTenant,
1717
+ autoIndex: config.autoIndex,
1718
+ ...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
1719
+ ...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
1720
+ });
1721
+ repositories = createCartRepositories(models, {
1722
+ kinds,
1723
+ bridges: config.bridges,
1724
+ clock,
1725
+ id,
1726
+ defaultCurrency,
1727
+ events,
1728
+ outbox: config.outbox,
1729
+ plugins: config.repositoryPlugins,
1730
+ tenantFieldType,
1731
+ multiTenant
1732
+ });
1733
+ mode = "full";
1734
+ }
1735
+ return {
1736
+ config: Object.freeze({ ...config }),
1737
+ kinds,
1738
+ events,
1739
+ clock,
1740
+ id,
1741
+ models,
1742
+ repositories,
1743
+ mode,
1744
+ async syncIndexes() {
1745
+ await Promise.all(Object.values(models).map((m) => m.createIndexes()));
1746
+ },
1747
+ async destroy() {}
1748
+ };
1749
+ }
1750
+ //#endregion
1751
+ export { ReservationRepository as a, runPricing as c, createReservationModel as d, createCheckoutModel as f, IdempotencyRepository as i, createCartModels as l, InProcessCartEventBus as n, CheckoutRepository as o, createDraftModel as p, createCartRepositories as r, DraftRepository as s, createCart as t, createIdempotencyModel as u };