@classytic/cart 0.2.1 → 1.0.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.
- package/CHANGELOG.md +54 -0
- package/LICENSE +75 -21
- package/dist/{cart-event-catalog-BxDJhtTM.d.mts → cart-event-catalog-Cokx0iOw.d.mts} +1 -2
- package/dist/cart.error-xi5OT4Sz.mjs +52 -0
- package/dist/{clock.port-CNu2wgdA.d.mts → clock.port-DrSBrsit.d.mts} +9 -5
- package/dist/{create-cart-BeW0xAqD.mjs → define-cart-BPq2kb_V.mjs} +344 -224
- package/dist/domain/errors/index.d.mts +2 -2
- package/dist/domain/errors/index.mjs +6 -6
- package/dist/domain/events/index.d.mts +2 -2
- package/dist/domain/events/index.mjs +2 -2
- package/dist/domain/index.d.mts +14 -11
- package/dist/domain/index.mjs +12 -12
- package/dist/domain/ports/index.d.mts +3 -3
- package/dist/domain/ports/index.mjs +1 -1
- package/dist/domain/saga/index.d.mts +1 -1
- package/dist/domain/saga/index.mjs +1 -1
- package/dist/engine/cart-config.schema.d.mts +3 -4
- package/dist/engine/cart-config.schema.mjs +7 -7
- package/dist/engine/index.d.mts +3 -3
- package/dist/engine/index.mjs +3 -3
- package/dist/{errors-7Pd0yATM.mjs → errors-Dj8itvAh.mjs} +1 -4
- package/dist/{id.port-BhbFZJPm.mjs → id.port-DYAnXbfV.mjs} +1 -1
- package/dist/{index-BB0XzkXF.d.mts → index-BTSo-RLv.d.mts} +41 -4
- package/dist/index.d.mts +75 -17
- package/dist/index.mjs +180 -15
- package/dist/{internal-event-bus-DhQKi9KS.d.mts → internal-event-bus-Bu7Xj7j6.d.mts} +203 -170
- package/dist/{kind-registry-DG2iCCH1.d.mts → kind-registry-DFvNDb81.d.mts} +3 -5
- package/dist/{kind-registry-Bvrj3P1Q.mjs → kind-registry-DQYqRQZU.mjs} +1 -1
- package/dist/{kind.error-DIaJpdUb.mjs → kind.error-BoyoVjKx.mjs} +1 -1
- package/dist/kinds/index.d.mts +1 -1
- package/dist/kinds/index.mjs +1 -1
- package/dist/{line-kind-B1mU1iJp.d.mts → line-kind-BW2zLNSr.d.mts} +3 -4
- package/dist/line-total-6VJQMjGV.mjs +24 -0
- package/dist/{outbox-store-CBt9fSYh.d.mts → outbox-store-Br7MHuOz.d.mts} +3 -18
- package/dist/{outbox-store-CWW8ppxS.mjs → outbox-store-DLxCPOUN.mjs} +2 -30
- package/dist/{reservation.entity-DLMxgpLE.d.mts → reservation.entity-BEeYbRUY.d.mts} +4 -5
- package/dist/{state-transition.error-2fRLh3p0.mjs → state-transition.error-BssJiRoW.mjs} +1 -1
- package/dist/{state-transitions-D19wZe-w.d.mts → state-transitions-BQ2Nhxnb.d.mts} +14 -11
- package/dist/{state-transitions-Defw8gAt.mjs → state-transitions-wunwhjap.mjs} +1 -1
- package/dist/{unmanaged-session.error-C9Z1Yh9j.mjs → unmanaged-session.error-DIRT2PR3.mjs} +31 -2
- package/dist/{variant.kind-q-yv-vnQ.d.mts → variant.kind-CClf8MTF.d.mts} +3 -3
- package/dist/{variant.kind-BHiivO9B.mjs → variant.kind-NmWSslu-.mjs} +23 -32
- package/package.json +10 -9
- package/dist/cart.error-BwWy4RlY.mjs +0 -27
- package/dist/index-2Ag-54t8.d.mts +0 -1
- /package/dist/{cart-status.vo-CNJw4aaB.d.mts → cart-status.vo-BoVPaSXX.d.mts} +0 -0
- /package/dist/{domain-event-CIEORKF6.mjs → domain-event-DBFsiHNJ.mjs} +0 -0
- /package/dist/{id.port-DitjeoHg.d.mts → id.port-DzgWy8sy.d.mts} +0 -0
- /package/dist/{idempotency-key.vo-D0lJsvGn.mjs → idempotency-key.vo-BoRvSIxx.mjs} +0 -0
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { t as KindError } from "./kind.error-
|
|
3
|
-
import { n as CartEvents, t as createCartEvent } from "./domain-event-
|
|
4
|
-
import { n as cryptoIdPort, r as systemClock } from "./id.port-
|
|
5
|
-
import { t as createKindRegistry } from "./kind-registry-
|
|
6
|
-
import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-
|
|
1
|
+
import { a as CurrencyMismatchError, i as NotFoundError, n as StaleQuoteError, o as ConcurrencyError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-DIRT2PR3.mjs";
|
|
2
|
+
import { t as KindError } from "./kind.error-BoyoVjKx.mjs";
|
|
3
|
+
import { n as CartEvents, t as createCartEvent } from "./domain-event-DBFsiHNJ.mjs";
|
|
4
|
+
import { n as cryptoIdPort, r as systemClock } from "./id.port-DYAnXbfV.mjs";
|
|
5
|
+
import { t as createKindRegistry } from "./kind-registry-DQYqRQZU.mjs";
|
|
6
|
+
import { i as CheckoutStep, t as CHECKOUT_MACHINE } from "./state-transitions-wunwhjap.mjs";
|
|
7
|
+
import { t as lineTotal } from "./line-total-6VJQMjGV.mjs";
|
|
7
8
|
import { money } from "@classytic/primitives/money";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { CURRENCY_PATTERN } from "@classytic/primitives/currency";
|
|
9
|
+
import { Repository, customIdPlugin, defineModels, isDuplicateKeyError, multiTenantPlugin, prefixedId, withTransaction } from "@classytic/mongokit";
|
|
10
|
+
import { CURRENCY_PATTERN, currencyCode } from "@classytic/primitives/currency";
|
|
11
11
|
import mongoose, { Schema } from "mongoose";
|
|
12
12
|
import { resolveTenantConfig } from "@classytic/repo-core/tenant";
|
|
13
13
|
import { createHash } from "node:crypto";
|
|
14
|
+
import { InProcessEventBus } from "@classytic/primitives/event-infra";
|
|
14
15
|
//#region src/domain/ports/common.ts
|
|
15
16
|
/**
|
|
16
17
|
* Internal: key under which the post-commit event-publish queue is threaded
|
|
@@ -75,7 +76,11 @@ async function flushPending(eventTransport, events, logger) {
|
|
|
75
76
|
}
|
|
76
77
|
//#endregion
|
|
77
78
|
//#region src/models/checkout.model.ts
|
|
78
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Build the Checkout schema — pure, connection-free. Registration + collection
|
|
81
|
+
* naming + tenant injection are performed by `defineCartModels` at bind time.
|
|
82
|
+
*/
|
|
83
|
+
function buildCheckoutSchema() {
|
|
79
84
|
const schema = new Schema({
|
|
80
85
|
publicId: {
|
|
81
86
|
type: String,
|
|
@@ -160,8 +165,7 @@ function createCheckoutModel(connection, opts = {}) {
|
|
|
160
165
|
draftId: 1,
|
|
161
166
|
state: 1
|
|
162
167
|
});
|
|
163
|
-
|
|
164
|
-
return connection.model("CartCheckout", schema, collection);
|
|
168
|
+
return schema;
|
|
165
169
|
}
|
|
166
170
|
//#endregion
|
|
167
171
|
//#region src/models/draft.model.ts
|
|
@@ -270,7 +274,11 @@ const adjustmentSubSchema = new Schema({
|
|
|
270
274
|
default: () => /* @__PURE__ */ new Date()
|
|
271
275
|
}
|
|
272
276
|
}, { _id: false });
|
|
273
|
-
|
|
277
|
+
/**
|
|
278
|
+
* Build the Draft schema — pure, connection-free. Registration + collection
|
|
279
|
+
* naming + tenant injection are performed by `defineCartModels` at bind time.
|
|
280
|
+
*/
|
|
281
|
+
function buildDraftSchema() {
|
|
274
282
|
const schema = new Schema({
|
|
275
283
|
publicId: {
|
|
276
284
|
type: String,
|
|
@@ -348,12 +356,15 @@ function createDraftModel(connection, opts = {}) {
|
|
|
348
356
|
expireAfterSeconds: 0,
|
|
349
357
|
partialFilterExpression: { expiresAt: { $exists: true } }
|
|
350
358
|
});
|
|
351
|
-
|
|
352
|
-
return connection.model("CartDraft", schema, collection);
|
|
359
|
+
return schema;
|
|
353
360
|
}
|
|
354
361
|
//#endregion
|
|
355
362
|
//#region src/models/idempotency.model.ts
|
|
356
|
-
|
|
363
|
+
/**
|
|
364
|
+
* Build the Idempotency schema — pure, connection-free. Registration + collection
|
|
365
|
+
* naming + tenant injection are performed by `defineCartModels` at bind time.
|
|
366
|
+
*/
|
|
367
|
+
function buildIdempotencySchema() {
|
|
357
368
|
const schema = new Schema({
|
|
358
369
|
cartRef: {
|
|
359
370
|
type: String,
|
|
@@ -426,9 +437,8 @@ function createIdempotencyModel(connection, opts = {}) {
|
|
|
426
437
|
actorRef: 1,
|
|
427
438
|
idempotencyKey: 1
|
|
428
439
|
}, { unique: true });
|
|
429
|
-
schema.index({ createdAt: 1 }, { expireAfterSeconds:
|
|
430
|
-
|
|
431
|
-
return connection.model("CartIdempotency", schema, collection);
|
|
440
|
+
schema.index({ createdAt: 1 }, { expireAfterSeconds: 86400 });
|
|
441
|
+
return schema;
|
|
432
442
|
}
|
|
433
443
|
//#endregion
|
|
434
444
|
//#region src/models/inject-tenant.ts
|
|
@@ -461,7 +471,6 @@ function injectTenantField(schema, tenant) {
|
|
|
461
471
|
schema.add({ [tenant.tenantField]: {
|
|
462
472
|
type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
|
|
463
473
|
...tenant.enabled && tenant.required ? { required: true } : {},
|
|
464
|
-
index: true,
|
|
465
474
|
...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
|
|
466
475
|
} });
|
|
467
476
|
if (!tenant.enabled || !isFieldStrategy) return;
|
|
@@ -473,10 +482,15 @@ function injectTenantField(schema, tenant) {
|
|
|
473
482
|
for (const [key, val] of Object.entries(fields)) newFields[key] = val;
|
|
474
483
|
indexEntry[0] = newFields;
|
|
475
484
|
}
|
|
485
|
+
if (!(existingIndexes ?? []).some(([fields]) => Object.keys(fields)[0] === tenant.tenantField)) schema.index({ [tenant.tenantField]: 1 });
|
|
476
486
|
}
|
|
477
487
|
//#endregion
|
|
478
488
|
//#region src/models/reservation.model.ts
|
|
479
|
-
|
|
489
|
+
/**
|
|
490
|
+
* Build the Reservation schema — pure, connection-free. Registration + collection
|
|
491
|
+
* naming + tenant injection are performed by `defineCartModels` at bind time.
|
|
492
|
+
*/
|
|
493
|
+
function buildReservationSchema() {
|
|
480
494
|
const schema = new Schema({
|
|
481
495
|
publicId: {
|
|
482
496
|
type: String,
|
|
@@ -557,96 +571,86 @@ function createReservationModel(connection, opts = {}) {
|
|
|
557
571
|
expiresAt: 1
|
|
558
572
|
});
|
|
559
573
|
schema.index({ checkoutId: 1 });
|
|
560
|
-
|
|
561
|
-
return connection.model("CartReservation", schema, collection);
|
|
574
|
+
return schema;
|
|
562
575
|
}
|
|
563
576
|
//#endregion
|
|
564
577
|
//#region src/models/index.ts
|
|
565
|
-
const CART_MODEL_NAMES = [
|
|
566
|
-
"CartDraft",
|
|
567
|
-
"CartCheckout",
|
|
568
|
-
"CartReservation",
|
|
569
|
-
"CartIdempotency"
|
|
570
|
-
];
|
|
571
|
-
var CartModelCollisionError = class extends Error {
|
|
572
|
-
constructor(name) {
|
|
573
|
-
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.`);
|
|
574
|
-
this.name = "CartModelCollisionError";
|
|
575
|
-
}
|
|
576
|
-
};
|
|
577
578
|
/**
|
|
578
|
-
*
|
|
579
|
+
* Cart model specification — the ONE authoritative place the cart model set is
|
|
580
|
+
* described.
|
|
579
581
|
*
|
|
580
|
-
*
|
|
581
|
-
* `
|
|
582
|
+
* `defineCartModels(config)` returns a connection-free mongokit `ModelBlueprint`;
|
|
583
|
+
* `defineCart` binds it during engine construction. Collision handling, tenant
|
|
584
|
+
* injection, collection naming and auto-index policy live here once
|
|
585
|
+
* (PACKAGE_RULES §20/§21). A name collision surfaces as mongokit's typed
|
|
586
|
+
* `ModelCollisionError` — there is no cart-specific collision error.
|
|
582
587
|
*/
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
588
|
+
/** Registered Mongoose model name for each cart model bag key. */
|
|
589
|
+
const MODEL_NAME = {
|
|
590
|
+
Draft: "CartDraft",
|
|
591
|
+
Checkout: "CartCheckout",
|
|
592
|
+
Reservation: "CartReservation",
|
|
593
|
+
Idempotency: "CartIdempotency"
|
|
594
|
+
};
|
|
595
|
+
/** Physical collection base name (before `collectionPrefix`) for each model. */
|
|
596
|
+
const COLLECTION = {
|
|
597
|
+
Draft: "cart_drafts",
|
|
598
|
+
Checkout: "cart_checkouts",
|
|
599
|
+
Reservation: "cart_reservations",
|
|
600
|
+
Idempotency: "cart_idempotency"
|
|
601
|
+
};
|
|
602
|
+
/** Pure schema builders — no connection, no registration. */
|
|
603
|
+
const SCHEMA_BUILDER = {
|
|
604
|
+
Draft: buildDraftSchema,
|
|
605
|
+
Checkout: buildCheckoutSchema,
|
|
606
|
+
Reservation: buildReservationSchema,
|
|
607
|
+
Idempotency: buildIdempotencySchema
|
|
608
|
+
};
|
|
609
|
+
function resolveAutoIndex(key, autoIndex) {
|
|
610
|
+
if (autoIndex === void 0) return void 0;
|
|
611
|
+
if (typeof autoIndex === "boolean") return autoIndex;
|
|
612
|
+
return autoIndex[key];
|
|
589
613
|
}
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
const
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
614
|
+
/**
|
|
615
|
+
* Describe the cart model set as a connection-free blueprint. Pure — builds no
|
|
616
|
+
* schema and registers nothing until `.bind(connection)`.
|
|
617
|
+
*/
|
|
618
|
+
function defineCartModels(config = {}) {
|
|
619
|
+
const tenant = resolveCartTenant({
|
|
620
|
+
multiTenant: config.multiTenant,
|
|
621
|
+
tenantFieldType: config.tenantFieldType ?? "objectId"
|
|
622
|
+
});
|
|
623
|
+
const prefix = config.collectionPrefix ?? "";
|
|
624
|
+
return defineModels({
|
|
625
|
+
models: [
|
|
626
|
+
"Draft",
|
|
627
|
+
"Checkout",
|
|
628
|
+
"Reservation",
|
|
629
|
+
"Idempotency"
|
|
630
|
+
].map((key) => ({
|
|
631
|
+
name: MODEL_NAME[key],
|
|
632
|
+
collection: `${prefix}${COLLECTION[key]}`,
|
|
633
|
+
schema: () => {
|
|
634
|
+
const schema = SCHEMA_BUILDER[key]();
|
|
635
|
+
injectTenantField(schema, tenant);
|
|
636
|
+
const autoIndex = resolveAutoIndex(key, config.autoIndex);
|
|
637
|
+
if (autoIndex !== void 0) schema.set("autoIndex", autoIndex);
|
|
638
|
+
return schema;
|
|
639
|
+
},
|
|
640
|
+
existing: config.forceRecreate ? {
|
|
641
|
+
mode: "replace",
|
|
642
|
+
environment: "test"
|
|
643
|
+
} : { mode: "throw" }
|
|
644
|
+
})),
|
|
645
|
+
assemble: (models) => Object.freeze({
|
|
646
|
+
Draft: models.get("CartDraft"),
|
|
647
|
+
Checkout: models.get("CartCheckout"),
|
|
648
|
+
Reservation: models.get("CartReservation"),
|
|
649
|
+
Idempotency: models.get("CartIdempotency")
|
|
650
|
+
})
|
|
651
|
+
});
|
|
605
652
|
}
|
|
606
653
|
//#endregion
|
|
607
|
-
//#region src/engine/cart-event-publisher.ts
|
|
608
|
-
var CartEventPublisher = class {
|
|
609
|
-
events;
|
|
610
|
-
outbox;
|
|
611
|
-
clock;
|
|
612
|
-
logger;
|
|
613
|
-
constructor(deps) {
|
|
614
|
-
this.events = deps.events;
|
|
615
|
-
this.outbox = deps.outbox;
|
|
616
|
-
this.clock = deps.clock;
|
|
617
|
-
this.logger = deps.logger ?? console;
|
|
618
|
-
}
|
|
619
|
-
async emit(type, payload, ctx, options = {}) {
|
|
620
|
-
const event = createCartEvent(type, {
|
|
621
|
-
...payload,
|
|
622
|
-
emittedAt: this.clock.now().toISOString(),
|
|
623
|
-
correlationId: ctx.correlationId,
|
|
624
|
-
organizationId: ctx.organizationId,
|
|
625
|
-
actorRef: ctx.actorRef
|
|
626
|
-
}, {
|
|
627
|
-
timestamp: this.clock.now(),
|
|
628
|
-
resource: options.resource,
|
|
629
|
-
resourceId: options.resourceId,
|
|
630
|
-
userId: ctx.actorKind === "user" ? ctx.actorRef : void 0,
|
|
631
|
-
organizationId: ctx.organizationId,
|
|
632
|
-
correlationId: ctx.correlationId,
|
|
633
|
-
aggregate: options.aggregate
|
|
634
|
-
});
|
|
635
|
-
const pending = ctx[PENDING_EVENTS];
|
|
636
|
-
if (this.outbox) await this.outbox.save(event, { session: ctx.session });
|
|
637
|
-
else if (ctx.session && !pending) throw new UnmanagedSessionError();
|
|
638
|
-
if (pending) {
|
|
639
|
-
pending.push(event);
|
|
640
|
-
return;
|
|
641
|
-
}
|
|
642
|
-
if (!ctx.session) try {
|
|
643
|
-
await this.events.publish(event);
|
|
644
|
-
} catch (err) {
|
|
645
|
-
this.logger.error(`[cart] transport publish failed for ${event.type}:`, err);
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
};
|
|
649
|
-
//#endregion
|
|
650
654
|
//#region src/repositories/checkout.repository.ts
|
|
651
655
|
/**
|
|
652
656
|
* Default zombie window for open checkouts — matches the package's
|
|
@@ -1175,12 +1179,25 @@ async function runPricing(opts) {
|
|
|
1175
1179
|
adjustments
|
|
1176
1180
|
};
|
|
1177
1181
|
}
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1182
|
+
/**
|
|
1183
|
+
* Sum a list of minor-unit money into a single total.
|
|
1184
|
+
*
|
|
1185
|
+
* Every input MUST share `currency` — the pricing pipeline assumes a draft's
|
|
1186
|
+
* one currency, and a blind reduce that stamped the result with `moneys[0]`
|
|
1187
|
+
* would silently fold a divergent-currency line (e.g. an EUR override on a USD
|
|
1188
|
+
* draft) into the grand total and freeze the wrong number into checkout. We
|
|
1189
|
+
* assert instead of guess, throwing `CurrencyMismatchError` on any divergence.
|
|
1190
|
+
*
|
|
1191
|
+
* Exported (module-level, NOT via the package barrel) for direct unit testing
|
|
1192
|
+
* of the single-currency invariant.
|
|
1193
|
+
*/
|
|
1194
|
+
function sumMoney(moneys, currency) {
|
|
1195
|
+
let amount = 0;
|
|
1196
|
+
for (const m of moneys) {
|
|
1197
|
+
if (m.currency !== currency) throw new CurrencyMismatchError(currency, m.currency, { helper: "sumMoney" });
|
|
1198
|
+
amount += m.amount;
|
|
1199
|
+
}
|
|
1200
|
+
return money(amount, currency);
|
|
1184
1201
|
}
|
|
1185
1202
|
/**
|
|
1186
1203
|
* Can the prior priced entry be reused for this line?
|
|
@@ -1206,20 +1223,15 @@ function canReuse(line, prior) {
|
|
|
1206
1223
|
*/
|
|
1207
1224
|
function rebuildSubtotals(prior, line, currency) {
|
|
1208
1225
|
const unitPrice = prior.unitPrice;
|
|
1209
|
-
const
|
|
1210
|
-
if (!Number.isSafeInteger(rawTotal)) throw new RangeError(`cart pricing: line total ${unitPrice.amount} × ${line.quantity} exceeds Number.MAX_SAFE_INTEGER`);
|
|
1211
|
-
const lineTotal = {
|
|
1212
|
-
amount: rawTotal,
|
|
1213
|
-
currency
|
|
1214
|
-
};
|
|
1226
|
+
const total = lineTotal(unitPrice, line.quantity);
|
|
1215
1227
|
return {
|
|
1216
1228
|
lineId: line.lineId,
|
|
1217
1229
|
unitPrice,
|
|
1218
1230
|
quantity: line.quantity,
|
|
1219
1231
|
subtotals: {
|
|
1220
|
-
prePromo:
|
|
1221
|
-
postPromo:
|
|
1222
|
-
postPromoPostTax:
|
|
1232
|
+
prePromo: total,
|
|
1233
|
+
postPromo: total,
|
|
1234
|
+
postPromoPostTax: total
|
|
1223
1235
|
},
|
|
1224
1236
|
discountTotal: {
|
|
1225
1237
|
amount: 0,
|
|
@@ -1798,6 +1810,49 @@ var IdempotencyRepository = class extends Repository {
|
|
|
1798
1810
|
}
|
|
1799
1811
|
};
|
|
1800
1812
|
//#endregion
|
|
1813
|
+
//#region src/engine/cart-event-publisher.ts
|
|
1814
|
+
var CartEventPublisher = class {
|
|
1815
|
+
events;
|
|
1816
|
+
outbox;
|
|
1817
|
+
clock;
|
|
1818
|
+
logger;
|
|
1819
|
+
constructor(deps) {
|
|
1820
|
+
this.events = deps.events;
|
|
1821
|
+
this.outbox = deps.outbox;
|
|
1822
|
+
this.clock = deps.clock;
|
|
1823
|
+
this.logger = deps.logger ?? console;
|
|
1824
|
+
}
|
|
1825
|
+
async emit(type, payload, ctx, options = {}) {
|
|
1826
|
+
const event = createCartEvent(type, {
|
|
1827
|
+
...payload,
|
|
1828
|
+
emittedAt: this.clock.now().toISOString(),
|
|
1829
|
+
correlationId: ctx.correlationId,
|
|
1830
|
+
organizationId: ctx.organizationId,
|
|
1831
|
+
actorRef: ctx.actorRef
|
|
1832
|
+
}, {
|
|
1833
|
+
timestamp: this.clock.now(),
|
|
1834
|
+
resource: options.resource,
|
|
1835
|
+
resourceId: options.resourceId,
|
|
1836
|
+
userId: ctx.actorKind === "user" ? ctx.actorRef : void 0,
|
|
1837
|
+
organizationId: ctx.organizationId,
|
|
1838
|
+
correlationId: ctx.correlationId,
|
|
1839
|
+
aggregate: options.aggregate
|
|
1840
|
+
});
|
|
1841
|
+
const pending = ctx[PENDING_EVENTS];
|
|
1842
|
+
if (this.outbox) await this.outbox.save(event, { session: ctx.session });
|
|
1843
|
+
else if (ctx.session && !pending) throw new UnmanagedSessionError();
|
|
1844
|
+
if (pending) {
|
|
1845
|
+
pending.push(event);
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
if (!ctx.session) try {
|
|
1849
|
+
await this.events.publish(event);
|
|
1850
|
+
} catch (err) {
|
|
1851
|
+
this.logger.error(`[cart] transport publish failed for ${event.type}:`, err);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
};
|
|
1855
|
+
//#endregion
|
|
1801
1856
|
//#region src/repositories/reservation.repository.ts
|
|
1802
1857
|
/**
|
|
1803
1858
|
* ReservationRepository — extends mongokit's `Repository<ReservationDocument>`.
|
|
@@ -1807,9 +1862,6 @@ var IdempotencyRepository = class extends Repository {
|
|
|
1807
1862
|
* sweeper drives the active release loop via `findExpiredHeld`.
|
|
1808
1863
|
*/
|
|
1809
1864
|
var ReservationRepository = class extends Repository {
|
|
1810
|
-
constructor(model, plugins) {
|
|
1811
|
-
super(model, plugins);
|
|
1812
|
-
}
|
|
1813
1865
|
/** All reservations belonging to a checkout. */
|
|
1814
1866
|
async findByCheckout(checkoutId, ctx) {
|
|
1815
1867
|
return await this.findAll({ checkoutId }, this.readOptions(ctx));
|
|
@@ -1961,127 +2013,195 @@ function createCartRepositories(models, config) {
|
|
|
1961
2013
|
}
|
|
1962
2014
|
//#endregion
|
|
1963
2015
|
//#region src/engine/internal-event-bus.ts
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
const sub = {
|
|
1985
|
-
pattern,
|
|
1986
|
-
handler
|
|
1987
|
-
};
|
|
1988
|
-
this.subs.push(sub);
|
|
1989
|
-
return () => {
|
|
1990
|
-
this.subs = this.subs.filter((s) => s !== sub);
|
|
1991
|
-
};
|
|
1992
|
-
}
|
|
1993
|
-
async close() {
|
|
1994
|
-
this.subs = [];
|
|
2016
|
+
/**
|
|
2017
|
+
* InProcessCartEventBus — default transport for CartEngine when no external
|
|
2018
|
+
* transport is provided. Thin subclass of primitives' shared
|
|
2019
|
+
* `InProcessEventBus` (`@classytic/primitives/event-infra`, 0.13.0) —
|
|
2020
|
+
* structurally identical to Arc's `MemoryEventTransport`, so the two are
|
|
2021
|
+
* interchangeable.
|
|
2022
|
+
*
|
|
2023
|
+
* Cart dialect preserved: handler errors are swallowed silently
|
|
2024
|
+
* (`logger: null`) — event emission never propagates OR logs errors.
|
|
2025
|
+
*
|
|
2026
|
+
* Not durable — lost on process restart. For durability, use a
|
|
2027
|
+
* host-provided durable outbox plus a relay worker, or plug in Arc's
|
|
2028
|
+
* EventOutbox.
|
|
2029
|
+
*/
|
|
2030
|
+
var InProcessCartEventBus = class extends InProcessEventBus {
|
|
2031
|
+
constructor() {
|
|
2032
|
+
super({
|
|
2033
|
+
name: "in-process-cart",
|
|
2034
|
+
logger: null
|
|
2035
|
+
});
|
|
1995
2036
|
}
|
|
1996
2037
|
};
|
|
1997
2038
|
//#endregion
|
|
1998
|
-
//#region src/engine/
|
|
1999
|
-
/**
|
|
2039
|
+
//#region src/engine/define-cart.ts
|
|
2040
|
+
/**
|
|
2041
|
+
* `defineCart` — the DESCRIBE/BIND blueprint for the cart engine
|
|
2042
|
+
* (STANDARDIZATION-PLAN §6, Phase 5). Splits construction into two phases:
|
|
2043
|
+
*
|
|
2044
|
+
* - **describe** (`defineCart(shape)`): pure. Builds the kind registry and
|
|
2045
|
+
* freezes the model names via mongokit's `defineModels()`. No connection,
|
|
2046
|
+
* no schema built, no I/O — safe at import / module-composition time.
|
|
2047
|
+
* - **bind** (`blueprint.bind(connection, runtime)`): compiles the schemas on
|
|
2048
|
+
* the supplied connection, registers the models, wires repositories +
|
|
2049
|
+
* transport, verifies capabilities, and returns the frozen `CartEngine`.
|
|
2050
|
+
*
|
|
2051
|
+
* The legitimate connectionless / domain-only use case (kinds + events + clock
|
|
2052
|
+
* WITHOUT persistence) is an EXPLICIT separate surface — `createCartDomain(shape)`
|
|
2053
|
+
* — not a "lite" engine returned by `bind`, and not connection duck-typing.
|
|
2054
|
+
*
|
|
2055
|
+
* This is the sole construction API — there is no `createCart` wrapper.
|
|
2056
|
+
*/
|
|
2057
|
+
/** Runtime capabilities cart's atomic paths require at boot. */
|
|
2000
2058
|
const REQUIRED_CAPABILITIES = ["upsert"];
|
|
2001
2059
|
/**
|
|
2002
2060
|
* Boot gate (PACKAGE_RULES "Runtime capabilities") — the idempotency store's
|
|
2003
|
-
* insert-in-flight/lease pattern needs atomic upserts; fail loud at
|
|
2004
|
-
*
|
|
2061
|
+
* insert-in-flight/lease pattern needs atomic upserts; fail loud at bind time,
|
|
2062
|
+
* not with a cryptic driver error on the first checkout.
|
|
2005
2063
|
*/
|
|
2006
2064
|
function assertCartCapabilities(repositories) {
|
|
2007
2065
|
const caps = repositories.draft.capabilities;
|
|
2008
|
-
if (!caps) throw new Error("
|
|
2066
|
+
if (!caps) throw new Error("defineCart.bind: the wired repository backend declares no `capabilities` descriptor (repo-core 0.6 / mongokit 3.16+). Upgrade the kit.");
|
|
2009
2067
|
const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
|
|
2010
|
-
if (missing.length > 0) throw new Error(`
|
|
2068
|
+
if (missing.length > 0) throw new Error(`defineCart.bind: backend missing required capabilities: ${missing.join(", ")}. The idempotency lease pattern needs atomic upserts.`);
|
|
2069
|
+
}
|
|
2070
|
+
function requireKinds(shape) {
|
|
2071
|
+
if (!shape.kinds || shape.kinds.length === 0) throw new Error("defineCart: shape.kinds must contain at least one LineKind");
|
|
2011
2072
|
}
|
|
2012
2073
|
/**
|
|
2013
|
-
*
|
|
2014
|
-
*
|
|
2015
|
-
* Repositories are the primary API. All domain logic (addItem, checkout,
|
|
2016
|
-
* commit, cancel) lives directly on the repository classes. Multi-tenant
|
|
2017
|
-
* scoping and `publicId` generation are handled by mongokit plugins wired
|
|
2018
|
-
* inside `createCartRepositories`, so callers just pass the connection
|
|
2019
|
-
* and bridges.
|
|
2074
|
+
* Describe the cart engine. Pure — registers no model, builds no schema,
|
|
2075
|
+
* performs no I/O.
|
|
2020
2076
|
*/
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
const
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
let models = {};
|
|
2034
|
-
let repositories = {};
|
|
2035
|
-
let mode = "lite";
|
|
2036
|
-
const multiTenant = config.multiTenant ?? true;
|
|
2037
|
-
if (isRealConnection) {
|
|
2038
|
-
models = createCartModels(config.connection, {
|
|
2039
|
-
tenantFieldType,
|
|
2040
|
-
multiTenant,
|
|
2041
|
-
autoIndex: config.autoIndex,
|
|
2042
|
-
...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
|
|
2043
|
-
...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
|
|
2044
|
-
});
|
|
2045
|
-
repositories = createCartRepositories(models, {
|
|
2046
|
-
kinds,
|
|
2047
|
-
bridges: config.bridges,
|
|
2048
|
-
clock,
|
|
2049
|
-
id,
|
|
2050
|
-
defaultCurrency,
|
|
2051
|
-
events,
|
|
2052
|
-
outbox: config.outbox,
|
|
2053
|
-
plugins: config.repositoryPlugins,
|
|
2054
|
-
tenantFieldType,
|
|
2055
|
-
multiTenant,
|
|
2056
|
-
staleOpenCheckoutMs: config.checkout?.staleOpenCheckoutMs
|
|
2057
|
-
});
|
|
2058
|
-
assertCartCapabilities(repositories);
|
|
2059
|
-
mode = "full";
|
|
2060
|
-
}
|
|
2061
|
-
const allowNonTransactional = config.allowNonTransactional ?? false;
|
|
2077
|
+
function defineCart(shape) {
|
|
2078
|
+
requireKinds(shape);
|
|
2079
|
+
const multiTenant = shape.multiTenant ?? true;
|
|
2080
|
+
const tenantFieldType = shape.tenantFieldType ?? "objectId";
|
|
2081
|
+
const defaultCurrency = currencyCode(shape.defaultCurrency ?? "USD");
|
|
2082
|
+
const modelBlueprint = defineCartModels({
|
|
2083
|
+
multiTenant,
|
|
2084
|
+
tenantFieldType,
|
|
2085
|
+
...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
|
|
2086
|
+
...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
|
|
2087
|
+
...shape.forceRecreate !== void 0 ? { forceRecreate: shape.forceRecreate } : {}
|
|
2088
|
+
});
|
|
2062
2089
|
return {
|
|
2063
|
-
|
|
2090
|
+
id: "cart",
|
|
2091
|
+
modelNames: modelBlueprint.modelNames,
|
|
2092
|
+
bind(connection, runtime) {
|
|
2093
|
+
if (!runtime || !runtime.bridges) throw new Error("defineCart.bind: runtime.bridges is required");
|
|
2094
|
+
if (!runtime.bridges.catalog) throw new Error("defineCart.bind: runtime.bridges.catalog is required");
|
|
2095
|
+
/**
|
|
2096
|
+
* VERIFY (boot gate) — an injected outbox MUST enlist `ctx.session`.
|
|
2097
|
+
*
|
|
2098
|
+
* Checked here with the other argument checks, BEFORE the model blueprint binds: a
|
|
2099
|
+
* cheaper error should report before a costlier one, and a bind refused here must
|
|
2100
|
+
* leave the connection's model registry untouched.
|
|
2101
|
+
*
|
|
2102
|
+
* `OutboxWriteOptions.session` is best-effort BY CONTRACT (see
|
|
2103
|
+
* `@classytic/primitives/outbox`), so a hand-rolled store satisfies `OutboxStore`
|
|
2104
|
+
* and then keeps the row when the transaction aborts. `CartEventPublisher.emit`
|
|
2105
|
+
* saves under `ctx.session` unconditionally so it cannot: a surviving
|
|
2106
|
+
* `cart.checkout.committed` is the one event a host is told to hook for order
|
|
2107
|
+
* creation and reservation commit, so a rolled-back checkout would create an order
|
|
2108
|
+
* and burn inventory holds for a basket that is still open. Nothing throws.
|
|
2109
|
+
*
|
|
2110
|
+
* Cart already refuses a bare host session with no outbox and no queue
|
|
2111
|
+
* (`UnmanagedSessionError`, per call). That guard cannot see this one: a store IS
|
|
2112
|
+
* present and `save()` resolves.
|
|
2113
|
+
*/
|
|
2114
|
+
if (runtime.outbox && runtime.outbox.transactionalSave !== true) throw new Error("defineCart.bind: the configured OutboxStore does not declare `transactionalSave: true`, so it does not promise that `save()` enlists `ctx.session` (see @classytic/primitives/outbox — the option is best-effort by contract). Cart writes every event row inside the caller's transaction; a store that ignores the session emits checkout events for baskets that rolled back. Arc's `repositoryAsOutboxStore` declares it; the in-memory `MemoryOutboxStore` must not — pass no outbox instead.");
|
|
2115
|
+
const kinds = createKindRegistry(shape.kinds);
|
|
2116
|
+
const clock = runtime.clock ?? systemClock;
|
|
2117
|
+
const id = runtime.id ?? cryptoIdPort;
|
|
2118
|
+
const logger = runtime.logger ?? console;
|
|
2119
|
+
const staleOpenCheckoutMs = shape.checkout?.staleOpenCheckoutMs;
|
|
2120
|
+
const ownsBus = runtime.eventTransport === void 0;
|
|
2121
|
+
const events = runtime.eventTransport ?? new InProcessCartEventBus();
|
|
2122
|
+
const models = modelBlueprint.bind(connection);
|
|
2123
|
+
const repositories = createCartRepositories(models, {
|
|
2124
|
+
kinds,
|
|
2125
|
+
bridges: runtime.bridges,
|
|
2126
|
+
clock,
|
|
2127
|
+
id,
|
|
2128
|
+
defaultCurrency,
|
|
2129
|
+
events,
|
|
2130
|
+
...runtime.outbox !== void 0 ? { outbox: runtime.outbox } : {},
|
|
2131
|
+
...runtime.repositoryPlugins !== void 0 ? { plugins: runtime.repositoryPlugins } : {},
|
|
2132
|
+
tenantFieldType,
|
|
2133
|
+
multiTenant,
|
|
2134
|
+
...staleOpenCheckoutMs !== void 0 ? { staleOpenCheckoutMs } : {}
|
|
2135
|
+
});
|
|
2136
|
+
assertCartCapabilities(repositories);
|
|
2137
|
+
const allowNonTransactional = runtime.allowNonTransactional ?? false;
|
|
2138
|
+
const resolved = {
|
|
2139
|
+
multiTenant,
|
|
2140
|
+
tenantFieldType,
|
|
2141
|
+
forceRecreate: shape.forceRecreate ?? false,
|
|
2142
|
+
defaultCurrency,
|
|
2143
|
+
allowNonTransactional,
|
|
2144
|
+
...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
|
|
2145
|
+
...staleOpenCheckoutMs !== void 0 ? { staleOpenCheckoutMs } : {}
|
|
2146
|
+
};
|
|
2147
|
+
let closed = false;
|
|
2148
|
+
const close = async () => {
|
|
2149
|
+
if (closed) return;
|
|
2150
|
+
closed = true;
|
|
2151
|
+
if (ownsBus) await events.close?.();
|
|
2152
|
+
};
|
|
2153
|
+
const engine = {
|
|
2154
|
+
config: Object.freeze(resolved),
|
|
2155
|
+
kinds,
|
|
2156
|
+
events,
|
|
2157
|
+
clock,
|
|
2158
|
+
id,
|
|
2159
|
+
models,
|
|
2160
|
+
repositories,
|
|
2161
|
+
withTransaction(ctx, body) {
|
|
2162
|
+
return runUnit({
|
|
2163
|
+
connection,
|
|
2164
|
+
eventTransport: events,
|
|
2165
|
+
logger,
|
|
2166
|
+
allowNonTransactional
|
|
2167
|
+
}, ctx, body);
|
|
2168
|
+
},
|
|
2169
|
+
async syncIndexes() {
|
|
2170
|
+
await Promise.all(Object.values(models).map((m) => m.createIndexes()));
|
|
2171
|
+
},
|
|
2172
|
+
close
|
|
2173
|
+
};
|
|
2174
|
+
return Object.freeze(engine);
|
|
2175
|
+
}
|
|
2176
|
+
};
|
|
2177
|
+
}
|
|
2178
|
+
/**
|
|
2179
|
+
* `createCartDomain(shape, runtime?)` — the EXPLICIT connectionless domain-only
|
|
2180
|
+
* surface (STANDARDIZATION-PLAN §Phase 5). Builds the kind registry, event
|
|
2181
|
+
* transport, clock and id WITHOUT touching a connection, registering a model,
|
|
2182
|
+
* or wiring a repository. Use it to exercise the LineKind contract or emit
|
|
2183
|
+
* events without persistence. It is NOT a degraded engine — it deliberately
|
|
2184
|
+
* exposes no `models`/`repositories`/`withTransaction`.
|
|
2185
|
+
*/
|
|
2186
|
+
function createCartDomain(shape, runtime = {}) {
|
|
2187
|
+
requireKinds(shape);
|
|
2188
|
+
const kinds = createKindRegistry(shape.kinds);
|
|
2189
|
+
const clock = runtime.clock ?? systemClock;
|
|
2190
|
+
const id = runtime.id ?? cryptoIdPort;
|
|
2191
|
+
const ownsBus = runtime.eventTransport === void 0;
|
|
2192
|
+
const events = runtime.eventTransport ?? new InProcessCartEventBus();
|
|
2193
|
+
let closed = false;
|
|
2194
|
+
return Object.freeze({
|
|
2064
2195
|
kinds,
|
|
2065
2196
|
events,
|
|
2066
2197
|
clock,
|
|
2067
2198
|
id,
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
connection: config.connection,
|
|
2075
|
-
eventTransport: events,
|
|
2076
|
-
logger: console,
|
|
2077
|
-
allowNonTransactional
|
|
2078
|
-
}, ctx, body);
|
|
2079
|
-
},
|
|
2080
|
-
async syncIndexes() {
|
|
2081
|
-
await Promise.all(Object.values(models).map((m) => m.createIndexes()));
|
|
2082
|
-
},
|
|
2083
|
-
async destroy() {}
|
|
2084
|
-
};
|
|
2199
|
+
async close() {
|
|
2200
|
+
if (closed) return;
|
|
2201
|
+
closed = true;
|
|
2202
|
+
if (ownsBus) await events.close?.();
|
|
2203
|
+
}
|
|
2204
|
+
});
|
|
2085
2205
|
}
|
|
2086
2206
|
//#endregion
|
|
2087
|
-
export {
|
|
2207
|
+
export { PENDING_EVENTS as _, ReservationRepository as a, runPricing as c, defineCartModels as d, buildReservationSchema as f, flushPending as g, buildCheckoutSchema as h, createCartRepositories as i, CheckoutRepository as l, buildDraftSchema as m, defineCart as n, IdempotencyRepository as o, buildIdempotencySchema as p, InProcessCartEventBus as r, DraftRepository as s, createCartDomain as t, DEFAULT_STALE_OPEN_CHECKOUT_MS as u };
|