@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.
- package/CHANGELOG.md +54 -0
- package/LICENSE +21 -0
- package/README.md +109 -0
- package/dist/bundle.kind-BdgnyKZt.d.mts +114 -0
- package/dist/bundle.kind-DFydSxV_.mjs +362 -0
- package/dist/cart-event-catalog-BIbi2Q_n.d.mts +109 -0
- package/dist/cart-event-catalog-BOP9aDhL.mjs +301 -0
- package/dist/cart-status.vo-2iisZGhb.d.mts +46 -0
- package/dist/create-cart-q3CXxPP7.mjs +1751 -0
- package/dist/domain/errors/index.d.mts +2 -0
- package/dist/domain/errors/index.mjs +4 -0
- package/dist/domain/events/index.d.mts +3 -0
- package/dist/domain/events/index.mjs +3 -0
- package/dist/domain/index.d.mts +12 -0
- package/dist/domain/index.mjs +15 -0
- package/dist/domain/ports/index.d.mts +3 -0
- package/dist/domain/ports/index.mjs +2 -0
- package/dist/domain/saga/index.d.mts +2 -0
- package/dist/domain/saga/index.mjs +3 -0
- package/dist/domain-event-DHNkz15G.mjs +57 -0
- package/dist/engine/cart-config.schema.d.mts +41 -0
- package/dist/engine/cart-config.schema.mjs +40 -0
- package/dist/engine/index.d.mts +3 -0
- package/dist/engine/index.mjs +3 -0
- package/dist/errors-CHR9RlbY.mjs +97 -0
- package/dist/id.port-C3rlDAKP.mjs +29 -0
- package/dist/id.port-DPXLrqb2.d.mts +64 -0
- package/dist/idempotency-key.vo-D0lJsvGn.mjs +9 -0
- package/dist/idempotency-record.entity-DIFXjN1V.d.mts +221 -0
- package/dist/index-DEHBdV_z.d.mts +1 -0
- package/dist/index-Doi5uzux.d.mts +231 -0
- package/dist/index.d.mts +103 -0
- package/dist/index.mjs +92 -0
- package/dist/internal-event-bus-IkUfQJxn.d.mts +661 -0
- package/dist/kind-registry-Ba4PO4WC.mjs +35 -0
- package/dist/kind.error-CCjTB6kW.mjs +69 -0
- package/dist/kinds/index.d.mts +2 -0
- package/dist/kinds/index.mjs +2 -0
- package/dist/line-item.entity-B3M_i-pw.d.mts +157 -0
- package/dist/line-kind-Bndo6IS8.d.mts +231 -0
- package/dist/not-found.error-B6WYnAjX.mjs +95 -0
- package/dist/outbox-store-CTWz9pvG.d.mts +155 -0
- package/dist/saga-step-fn-Cyob38iU.d.mts +135 -0
- package/dist/saga-steps-B27LI7xp.mjs +27 -0
- package/dist/shipping.bridge-DD4A_O0O.d.mts +538 -0
- package/dist/state-transitions-CpJpZZTK.mjs +21 -0
- package/package.json +114 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
4
|
+
adhering to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
5
|
+
|
|
6
|
+
## [0.1.0]
|
|
7
|
+
|
|
8
|
+
Initial release. Framework-agnostic universal cart engine — mutable drafts,
|
|
9
|
+
locked checkout snapshots, composable pricing, and the **LineKind** strategy
|
|
10
|
+
that handles every business variation. Zero framework dependencies.
|
|
11
|
+
|
|
12
|
+
### Exports
|
|
13
|
+
|
|
14
|
+
- **`.`** (root) — `createCart(config)` engine factory, re-exports of the
|
|
15
|
+
most-used services and types.
|
|
16
|
+
- **`./domain`** — pure domain types: `Draft`, `Checkout`, `Line`, `Money`,
|
|
17
|
+
validity/staleness, idempotency key shapes.
|
|
18
|
+
- **`./kinds`** — built-in `sku` LineKind + the generic `LineKind<T>` contract.
|
|
19
|
+
- **`./ports`** — 5 bridge ports: `CatalogBridge` (required), `InventoryBridge`,
|
|
20
|
+
`PromotionsBridge`, `TaxBridge`, `ShippingBridge`.
|
|
21
|
+
- **`./errors`** — typed error classes (`DraftNotFoundError`,
|
|
22
|
+
`PriceChangedError`, `InventoryReservationError`, etc.).
|
|
23
|
+
- **`./events`** — `cartEventDefinitions`, `OutboxRepository`, payload map;
|
|
24
|
+
arc-compatible structural types (no arc import).
|
|
25
|
+
- **`./saga`** — checkout state machine (`open → finalized | canceled`),
|
|
26
|
+
transition helpers.
|
|
27
|
+
- **`./engine`** — engine internals for hosts that want to reach past the
|
|
28
|
+
factory.
|
|
29
|
+
- **`./schemas`** — Zod schemas for `createCart()` config; exported for hosts
|
|
30
|
+
that validate config from env or a database.
|
|
31
|
+
|
|
32
|
+
### Peer dependencies
|
|
33
|
+
|
|
34
|
+
- `@classytic/mongokit >= 3.11` — repositories extend `Repository<T>` directly.
|
|
35
|
+
- `@classytic/primitives >= 0.1` — `Money`, `OperationContext`, events.
|
|
36
|
+
- `@classytic/repo-core >= 0.2` — shared repository abstractions.
|
|
37
|
+
- `mongoose >= 9.4` · `zod >= 4`.
|
|
38
|
+
|
|
39
|
+
### Design
|
|
40
|
+
|
|
41
|
+
- **No modes / no tiers.** Features light up based on which bridges the host
|
|
42
|
+
passes to `createCart()`. Catalog bridge is required; inventory, promo, tax,
|
|
43
|
+
shipping are opt-in.
|
|
44
|
+
- **Denormalized display snapshot** on every line (`display.name`,
|
|
45
|
+
`imageUrl`, `variantLabel`, `compareAtPrice`, `capturedAt`) captured at
|
|
46
|
+
add-time by `kind.displayOf()`. UI reads the cart with zero `.populate()`
|
|
47
|
+
calls. Drift is cosmetic; price drift is caught via `pricingHash` at checkout.
|
|
48
|
+
- **Checkout state machine: 3 states, 2 transitions.** `open → finalized`
|
|
49
|
+
(host called `commit`) or `open → canceled`. No payment state inside cart.
|
|
50
|
+
- **Idempotent + typed.** Every mutation accepts an idempotency key.
|
|
51
|
+
Operations are pure async functions with serializable inputs — agent-ready.
|
|
52
|
+
- **Arc-compatible events.** `cartEventDefinitions` are structurally
|
|
53
|
+
compatible with arc's `EventDefinitionOutput`; `OutboxRepository` implements
|
|
54
|
+
arc's `OutboxStore` without importing arc.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Classytic
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# @classytic/cart
|
|
2
|
+
|
|
3
|
+
**Framework-agnostic universal cart engine for commerce.**
|
|
4
|
+
|
|
5
|
+
One cart primitive. Every business. Zero framework dependencies.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createCart, skuKind } from '@classytic/cart';
|
|
9
|
+
|
|
10
|
+
const cart = await createCart({
|
|
11
|
+
connection: mongoose.connection,
|
|
12
|
+
kinds: [skuKind],
|
|
13
|
+
bridges: { catalog: myCatalogBridge },
|
|
14
|
+
// Optional for durable event persistence. Recommended in production.
|
|
15
|
+
outbox: myAppOutboxStore,
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
// Add items — display snapshot captured automatically (zero populate)
|
|
19
|
+
await cart.repositories.draft.addItem(
|
|
20
|
+
{ kind: 'sku', payload: { skuRef: 'sku_shirt' }, quantity: 2 },
|
|
21
|
+
ctx,
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
// Freeze the draft into a checkout snapshot
|
|
25
|
+
const checkout = await cart.repositories.checkout.createFromDraft(
|
|
26
|
+
{ draftPublicId: draft.publicId, expectedPricingHash: hash },
|
|
27
|
+
ctx,
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
// Host does payment + order creation (cart doesn't own these)
|
|
31
|
+
const paymentResult = await stripe.paymentIntents.create({ ... });
|
|
32
|
+
const order = await Order.create({ checkoutRef: checkout.publicId });
|
|
33
|
+
|
|
34
|
+
// Commit (or cancel)
|
|
35
|
+
await cart.repositories.checkout.commit(
|
|
36
|
+
{ checkoutPublicId: checkout.publicId, externalRef: String(order._id) },
|
|
37
|
+
ctx,
|
|
38
|
+
);
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## How features activate
|
|
42
|
+
|
|
43
|
+
No modes. No tiers. Pass the bridges you need:
|
|
44
|
+
|
|
45
|
+
| Bridge | What lights up |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `catalog` (required) | Draft CRUD, checkout, pricing |
|
|
48
|
+
| `+ inventory` | Reservation holds during checkout |
|
|
49
|
+
| `+ promotions` | Promo-apply step in pricing pipeline |
|
|
50
|
+
| `+ tax` | Tax step in pricing pipeline |
|
|
51
|
+
| `+ shipping` | Shipping step in pricing pipeline |
|
|
52
|
+
|
|
53
|
+
## What it fits
|
|
54
|
+
|
|
55
|
+
| Scenario | Uses cart? |
|
|
56
|
+
|---|---|
|
|
57
|
+
| Retail e-commerce | Yes — multi-item basket with SKU lines |
|
|
58
|
+
| Food delivery | Yes — basket + variants + delivery window |
|
|
59
|
+
| Cinema / event ticketing (web) | Yes — multi-seat with held-quote |
|
|
60
|
+
| Hotel / short-term stay | Yes — date-range pricing + room holds |
|
|
61
|
+
| Salon / studio (mixed basket) | Yes — appointment + retail + tip |
|
|
62
|
+
| POS scan-and-pay | No — sub-100ms budget, use `@classytic/flow` |
|
|
63
|
+
| Plain subscription signup | No — use `@classytic/revenue` |
|
|
64
|
+
| Pure single-resource booking | No — direct-commit, no basket |
|
|
65
|
+
|
|
66
|
+
## Architecture
|
|
67
|
+
|
|
68
|
+
- **LineKind** — one strategy per line category (`sku`, `seat`, `stay`,
|
|
69
|
+
`tip`, custom). Each kind owns validate, price, revalidate, displayOf.
|
|
70
|
+
- **Display snapshots** — denormalized on every line at add-time. UI
|
|
71
|
+
reads `line.display.name` directly. Zero `.populate()` calls.
|
|
72
|
+
- **Optimistic concurrency** — `version` field + `ConcurrencyError` on
|
|
73
|
+
stale writes.
|
|
74
|
+
- **Checkout state** — `open → finalized | canceled`. Cart snapshots;
|
|
75
|
+
host commits.
|
|
76
|
+
- **Arc-compatible** — event definitions match Arc structurally, and hosts
|
|
77
|
+
can inject their app-level outbox store for durable event persistence.
|
|
78
|
+
|
|
79
|
+
## Event durability
|
|
80
|
+
|
|
81
|
+
Cart no longer provisions its own durable Mongo outbox by default.
|
|
82
|
+
|
|
83
|
+
- If you pass `eventTransport` only, cart is publish-only.
|
|
84
|
+
- If you pass `eventTransport` + `outbox`, cart gets durable event persistence.
|
|
85
|
+
- If a write runs with `ctx.session` and no `outbox` is configured, cart throws
|
|
86
|
+
instead of pretending the event was written durably.
|
|
87
|
+
|
|
88
|
+
For the exact host contract and examples, see
|
|
89
|
+
[`docs/host-integration.md`](./docs/host-integration.md).
|
|
90
|
+
|
|
91
|
+
## Zero framework dependencies
|
|
92
|
+
|
|
93
|
+
`peerDependencies`: `mongoose`, `@classytic/mongokit`.
|
|
94
|
+
`dependencies`: `zod`.
|
|
95
|
+
|
|
96
|
+
Works from Arc, Express, Nest, Next.js API routes, raw Node, or any
|
|
97
|
+
backend framework.
|
|
98
|
+
|
|
99
|
+
## Tests
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
npm test # 84 tests, 12 files, ~1.5s
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
See [`tests/scenarios/`](./tests/scenarios/) for per-industry examples
|
|
106
|
+
and [`tests/integration/`](./tests/integration/) for real-Mongo proofs.
|
|
107
|
+
|
|
108
|
+
See [`CLAUDE.md`](./CLAUDE.md) for the agent guide and
|
|
109
|
+
[`MIGRATION.md`](./MIGRATION.md) for be-prod migration steps.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { r as LineKind } from "./line-kind-Bndo6IS8.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/kinds/sku.kind.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* `sku` — the plain retail LineKind.
|
|
7
|
+
*
|
|
8
|
+
* Payload is a single SKU reference. The catalog bridge resolves it to
|
|
9
|
+
* a `ProductSummary`, pricing multiplies unit price by quantity, and
|
|
10
|
+
* there is no time-based expiry (webhook-driven invalidation handles
|
|
11
|
+
* price changes). This is the lowest-ceremony kind cart ships and the
|
|
12
|
+
* starting template for custom kinds.
|
|
13
|
+
*
|
|
14
|
+
* Use this when:
|
|
15
|
+
* - The product is a simple catalog entry with a stable price
|
|
16
|
+
* - There is no per-line slot, time window, or bid
|
|
17
|
+
* - You want the minimum possible surface for retail lines
|
|
18
|
+
*/
|
|
19
|
+
interface SkuPayload {
|
|
20
|
+
skuRef: string;
|
|
21
|
+
}
|
|
22
|
+
declare const skuPayloadSchema: z.ZodObject<{
|
|
23
|
+
skuRef: z.ZodString;
|
|
24
|
+
}, z.core.$strip>;
|
|
25
|
+
declare const skuKind: LineKind<SkuPayload>;
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/kinds/variant.kind.d.ts
|
|
28
|
+
/**
|
|
29
|
+
* `variant` — a catalog SKU with structured variant selection.
|
|
30
|
+
*
|
|
31
|
+
* Extends the `sku` kind with an explicit `variantSku` field (e.g.,
|
|
32
|
+
* "shirt-m-blue") that maps to a specific product variant. The catalog
|
|
33
|
+
* bridge resolves the variant SKU to a `ProductSummary` which carries
|
|
34
|
+
* variant-specific pricing, images, and the pre-formatted
|
|
35
|
+
* `variantLabel` ("Size: M, Color: Blue").
|
|
36
|
+
*
|
|
37
|
+
* Use this when the product has selectable options (size, color, material)
|
|
38
|
+
* and each combination has its own price and stock. Use plain `sku` when
|
|
39
|
+
* the product is a single item with no options.
|
|
40
|
+
*/
|
|
41
|
+
interface VariantPayload {
|
|
42
|
+
/** The parent product's stable identifier. */
|
|
43
|
+
productRef: string;
|
|
44
|
+
/** The specific variant's SKU — the one the catalog resolves for pricing. */
|
|
45
|
+
variantSku: string;
|
|
46
|
+
}
|
|
47
|
+
declare const variantPayloadSchema: z.ZodObject<{
|
|
48
|
+
productRef: z.ZodString;
|
|
49
|
+
variantSku: z.ZodString;
|
|
50
|
+
}, z.core.$strip>;
|
|
51
|
+
declare const variantKind: LineKind<VariantPayload>;
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/kinds/timeslot.kind.d.ts
|
|
54
|
+
/**
|
|
55
|
+
* `timeslot` — an appointment or booking slot in a mixed basket.
|
|
56
|
+
*
|
|
57
|
+
* For use when a service appointment (haircut, consultation, court
|
|
58
|
+
* booking) shares a checkout with other items (retail products, tips,
|
|
59
|
+
* add-ons). The catalog bridge resolves the service ref to a
|
|
60
|
+
* `ProductSummary` with pricing. The inventory bridge holds the slot
|
|
61
|
+
* during checkout if the host passes one.
|
|
62
|
+
*
|
|
63
|
+
* Pure single-resource bookings (no basket, direct-commit) should use a
|
|
64
|
+
* dedicated booking package instead of cart.
|
|
65
|
+
*/
|
|
66
|
+
interface TimeslotPayload {
|
|
67
|
+
/** Opaque service / resource reference the catalog bridge resolves. */
|
|
68
|
+
serviceRef: string;
|
|
69
|
+
/** ISO datetime — when the slot starts. */
|
|
70
|
+
startsAt: string;
|
|
71
|
+
/** ISO datetime — when the slot ends. */
|
|
72
|
+
endsAt: string;
|
|
73
|
+
/** Optional: who provides the service (stylist, court, room). */
|
|
74
|
+
providerRef?: string;
|
|
75
|
+
}
|
|
76
|
+
declare const timeslotPayloadSchema: z.ZodObject<{
|
|
77
|
+
serviceRef: z.ZodString;
|
|
78
|
+
startsAt: z.ZodISODateTime;
|
|
79
|
+
endsAt: z.ZodISODateTime;
|
|
80
|
+
providerRef: z.ZodOptional<z.ZodString>;
|
|
81
|
+
}, z.core.$strip>;
|
|
82
|
+
declare const timeslotKind: LineKind<TimeslotPayload>;
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/kinds/bundle.kind.d.ts
|
|
85
|
+
/**
|
|
86
|
+
* `bundle` — a group of products sold together at a combined price.
|
|
87
|
+
*
|
|
88
|
+
* The bundle resolves as a single catalog entry whose `unitPrice` is the
|
|
89
|
+
* bundle price (not the sum of component prices). Components are stored
|
|
90
|
+
* in `payload.components` for display and fulfillment, but pricing uses
|
|
91
|
+
* only the bundle's catalog entry.
|
|
92
|
+
*
|
|
93
|
+
* Validity is `reprice` — bundle prices can drift when component prices
|
|
94
|
+
* change, and silent repricing is acceptable (unlike contested resources
|
|
95
|
+
* like seats).
|
|
96
|
+
*/
|
|
97
|
+
interface BundleComponent {
|
|
98
|
+
skuRef: string;
|
|
99
|
+
quantity: number;
|
|
100
|
+
}
|
|
101
|
+
interface BundlePayload {
|
|
102
|
+
bundleRef: string;
|
|
103
|
+
components: BundleComponent[];
|
|
104
|
+
}
|
|
105
|
+
declare const bundlePayloadSchema: z.ZodObject<{
|
|
106
|
+
bundleRef: z.ZodString;
|
|
107
|
+
components: z.ZodArray<z.ZodObject<{
|
|
108
|
+
skuRef: z.ZodString;
|
|
109
|
+
quantity: z.ZodNumber;
|
|
110
|
+
}, z.core.$strip>>;
|
|
111
|
+
}, z.core.$strip>;
|
|
112
|
+
declare const bundleKind: LineKind<BundlePayload>;
|
|
113
|
+
//#endregion
|
|
114
|
+
export { TimeslotPayload as a, VariantPayload as c, SkuPayload as d, skuKind as f, bundlePayloadSchema as i, variantKind as l, BundlePayload as n, timeslotKind as o, skuPayloadSchema as p, bundleKind as r, timeslotPayloadSchema as s, BundleComponent as t, variantPayloadSchema as u };
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
import { t as KindError } from "./kind.error-CCjTB6kW.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
//#region src/kinds/sku.kind.ts
|
|
4
|
+
const skuPayloadSchema = z.object({ skuRef: z.string().min(1) });
|
|
5
|
+
const skuKind = {
|
|
6
|
+
name: "sku",
|
|
7
|
+
payloadSchema: skuPayloadSchema,
|
|
8
|
+
validity: { onStale: "extend" },
|
|
9
|
+
async validate(line, ctx) {
|
|
10
|
+
const parsed = skuPayloadSchema.safeParse(line.payload);
|
|
11
|
+
if (!parsed.success) throw new KindError(this.name, "invalid payload shape", { details: { issues: parsed.error.issues } });
|
|
12
|
+
if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
|
|
13
|
+
const product = await ctx.bridges.catalog.resolve(parsed.data.skuRef, ctx);
|
|
14
|
+
if (!product) throw new KindError(this.name, `unknown skuRef: ${parsed.data.skuRef}`);
|
|
15
|
+
if (!product.purchasable) throw new KindError(this.name, `product ${parsed.data.skuRef} is not purchasable`);
|
|
16
|
+
},
|
|
17
|
+
async price(line, ctx) {
|
|
18
|
+
const typed = line;
|
|
19
|
+
const product = await ctx.bridges.catalog.resolve(typed.payload.skuRef, ctx);
|
|
20
|
+
if (!product) throw new KindError(this.name, `price() called on unknown skuRef: ${typed.payload.skuRef}`);
|
|
21
|
+
const unitPrice = typed.overrideUnitPrice ?? product.unitPrice;
|
|
22
|
+
const lineTotal = {
|
|
23
|
+
amount: unitPrice.amount * typed.quantity,
|
|
24
|
+
currency: unitPrice.currency
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
lineId: typed.lineId,
|
|
28
|
+
unitPrice,
|
|
29
|
+
quantity: typed.quantity,
|
|
30
|
+
subtotals: {
|
|
31
|
+
prePromo: lineTotal,
|
|
32
|
+
postPromo: lineTotal,
|
|
33
|
+
postPromoPostTax: lineTotal
|
|
34
|
+
},
|
|
35
|
+
discountTotal: {
|
|
36
|
+
amount: 0,
|
|
37
|
+
currency: unitPrice.currency
|
|
38
|
+
},
|
|
39
|
+
taxTotal: {
|
|
40
|
+
amount: 0,
|
|
41
|
+
currency: unitPrice.currency
|
|
42
|
+
},
|
|
43
|
+
validUntil: null
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
async revalidate(_line, priced) {
|
|
47
|
+
return {
|
|
48
|
+
status: "unchanged",
|
|
49
|
+
priced
|
|
50
|
+
};
|
|
51
|
+
},
|
|
52
|
+
mergeKey(line) {
|
|
53
|
+
const typed = line;
|
|
54
|
+
if (!typed.payload?.skuRef) return null;
|
|
55
|
+
return `sku:${typed.payload.skuRef}`;
|
|
56
|
+
},
|
|
57
|
+
/**
|
|
58
|
+
* Populate the display snapshot at add-time. Called by the draft
|
|
59
|
+
* service; the resulting snapshot is stored on `LineItem.display` so
|
|
60
|
+
* the UI renders the cart directly without a second catalog call.
|
|
61
|
+
*/
|
|
62
|
+
async displayOf(line, ctx) {
|
|
63
|
+
const typed = line;
|
|
64
|
+
const product = await ctx.bridges.catalog.resolve(typed.payload.skuRef, ctx);
|
|
65
|
+
if (!product) return null;
|
|
66
|
+
return {
|
|
67
|
+
name: product.name,
|
|
68
|
+
imageUrl: product.primaryImage,
|
|
69
|
+
slug: product.slug,
|
|
70
|
+
variantLabel: product.variantLabel,
|
|
71
|
+
compareAtPrice: product.compareAtPrice,
|
|
72
|
+
capturedAt: ctx.bridges ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date()
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
//#endregion
|
|
77
|
+
//#region src/kinds/variant.kind.ts
|
|
78
|
+
const variantPayloadSchema = z.object({
|
|
79
|
+
productRef: z.string().min(1),
|
|
80
|
+
variantSku: z.string().min(1)
|
|
81
|
+
});
|
|
82
|
+
const variantKind = {
|
|
83
|
+
name: "variant",
|
|
84
|
+
payloadSchema: variantPayloadSchema,
|
|
85
|
+
validity: { onStale: "extend" },
|
|
86
|
+
async validate(line, ctx) {
|
|
87
|
+
const parsed = variantPayloadSchema.safeParse(line.payload);
|
|
88
|
+
if (!parsed.success) throw new KindError(this.name, "invalid variant payload", { details: { issues: parsed.error.issues } });
|
|
89
|
+
if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
|
|
90
|
+
const product = await ctx.bridges.catalog.resolve(parsed.data.variantSku, ctx);
|
|
91
|
+
if (!product) throw new KindError(this.name, `unknown variant SKU: ${parsed.data.variantSku}`);
|
|
92
|
+
if (!product.purchasable) throw new KindError(this.name, `variant ${parsed.data.variantSku} is not purchasable`);
|
|
93
|
+
},
|
|
94
|
+
async price(line, ctx) {
|
|
95
|
+
const typed = line;
|
|
96
|
+
const product = await ctx.bridges.catalog.resolve(typed.payload.variantSku, ctx);
|
|
97
|
+
if (!product) throw new KindError(this.name, `price() on unknown variant: ${typed.payload.variantSku}`);
|
|
98
|
+
const unitPrice = typed.overrideUnitPrice ?? product.unitPrice;
|
|
99
|
+
const lineTotal = {
|
|
100
|
+
amount: unitPrice.amount * typed.quantity,
|
|
101
|
+
currency: unitPrice.currency
|
|
102
|
+
};
|
|
103
|
+
return {
|
|
104
|
+
lineId: typed.lineId,
|
|
105
|
+
unitPrice,
|
|
106
|
+
quantity: typed.quantity,
|
|
107
|
+
subtotals: {
|
|
108
|
+
prePromo: lineTotal,
|
|
109
|
+
postPromo: lineTotal,
|
|
110
|
+
postPromoPostTax: lineTotal
|
|
111
|
+
},
|
|
112
|
+
discountTotal: {
|
|
113
|
+
amount: 0,
|
|
114
|
+
currency: unitPrice.currency
|
|
115
|
+
},
|
|
116
|
+
taxTotal: {
|
|
117
|
+
amount: 0,
|
|
118
|
+
currency: unitPrice.currency
|
|
119
|
+
},
|
|
120
|
+
validUntil: null
|
|
121
|
+
};
|
|
122
|
+
},
|
|
123
|
+
async revalidate(_line, priced) {
|
|
124
|
+
return {
|
|
125
|
+
status: "unchanged",
|
|
126
|
+
priced
|
|
127
|
+
};
|
|
128
|
+
},
|
|
129
|
+
mergeKey(line) {
|
|
130
|
+
const { productRef, variantSku } = line.payload ?? {};
|
|
131
|
+
if (!productRef || !variantSku) return null;
|
|
132
|
+
return `variant:${productRef}:${variantSku}`;
|
|
133
|
+
},
|
|
134
|
+
async displayOf(line, ctx) {
|
|
135
|
+
const typed = line;
|
|
136
|
+
const product = await ctx.bridges.catalog.resolve(typed.payload.variantSku, ctx);
|
|
137
|
+
if (!product) return null;
|
|
138
|
+
return {
|
|
139
|
+
name: product.name,
|
|
140
|
+
imageUrl: product.primaryImage,
|
|
141
|
+
slug: product.slug,
|
|
142
|
+
variantLabel: product.variantLabel,
|
|
143
|
+
compareAtPrice: product.compareAtPrice,
|
|
144
|
+
capturedAt: /* @__PURE__ */ new Date()
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
//#endregion
|
|
149
|
+
//#region src/kinds/timeslot.kind.ts
|
|
150
|
+
const timeslotPayloadSchema = z.object({
|
|
151
|
+
serviceRef: z.string().min(1),
|
|
152
|
+
startsAt: z.iso.datetime(),
|
|
153
|
+
endsAt: z.iso.datetime(),
|
|
154
|
+
providerRef: z.string().optional()
|
|
155
|
+
});
|
|
156
|
+
const TIMESLOT_VALIDITY_MS = 300 * 1e3;
|
|
157
|
+
const timeslotKind = {
|
|
158
|
+
name: "timeslot",
|
|
159
|
+
payloadSchema: timeslotPayloadSchema,
|
|
160
|
+
validity: {
|
|
161
|
+
maxAgeMs: TIMESLOT_VALIDITY_MS,
|
|
162
|
+
onStale: "error"
|
|
163
|
+
},
|
|
164
|
+
async validate(line, ctx) {
|
|
165
|
+
const parsed = timeslotPayloadSchema.safeParse(line.payload);
|
|
166
|
+
if (!parsed.success) throw new KindError(this.name, "invalid timeslot payload", { details: { issues: parsed.error.issues } });
|
|
167
|
+
if (line.quantity !== 1) throw new KindError(this.name, `timeslot lines must have quantity === 1; got ${line.quantity}`);
|
|
168
|
+
const start = new Date(parsed.data.startsAt).getTime();
|
|
169
|
+
if (new Date(parsed.data.endsAt).getTime() <= start) throw new KindError(this.name, "endsAt must be after startsAt");
|
|
170
|
+
if (!await ctx.bridges.catalog.resolve(parsed.data.serviceRef, ctx)) throw new KindError(this.name, `unknown service: ${parsed.data.serviceRef}`);
|
|
171
|
+
},
|
|
172
|
+
async price(line, ctx) {
|
|
173
|
+
const typed = line;
|
|
174
|
+
const service = await ctx.bridges.catalog.resolve(typed.payload.serviceRef, ctx);
|
|
175
|
+
if (!service) throw new KindError(this.name, `price() on unknown service: ${typed.payload.serviceRef}`);
|
|
176
|
+
const unitPrice = typed.overrideUnitPrice ?? service.unitPrice;
|
|
177
|
+
const total = {
|
|
178
|
+
amount: unitPrice.amount,
|
|
179
|
+
currency: unitPrice.currency
|
|
180
|
+
};
|
|
181
|
+
return {
|
|
182
|
+
lineId: typed.lineId,
|
|
183
|
+
unitPrice,
|
|
184
|
+
quantity: 1,
|
|
185
|
+
subtotals: {
|
|
186
|
+
prePromo: total,
|
|
187
|
+
postPromo: total,
|
|
188
|
+
postPromoPostTax: total
|
|
189
|
+
},
|
|
190
|
+
discountTotal: {
|
|
191
|
+
amount: 0,
|
|
192
|
+
currency: unitPrice.currency
|
|
193
|
+
},
|
|
194
|
+
taxTotal: {
|
|
195
|
+
amount: 0,
|
|
196
|
+
currency: unitPrice.currency
|
|
197
|
+
},
|
|
198
|
+
validUntil: new Date(Date.now() + TIMESLOT_VALIDITY_MS),
|
|
199
|
+
kindMeta: {
|
|
200
|
+
startsAt: typed.payload.startsAt,
|
|
201
|
+
endsAt: typed.payload.endsAt,
|
|
202
|
+
provider: typed.payload.providerRef
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
},
|
|
206
|
+
async revalidate(line, priced, _ctx) {
|
|
207
|
+
if (priced.validUntil && priced.validUntil.getTime() <= Date.now()) return {
|
|
208
|
+
status: "invalid",
|
|
209
|
+
reason: "timeslot hold expired — the slot may no longer be available"
|
|
210
|
+
};
|
|
211
|
+
return {
|
|
212
|
+
status: "unchanged",
|
|
213
|
+
priced
|
|
214
|
+
};
|
|
215
|
+
},
|
|
216
|
+
async reserve(line, ctx) {
|
|
217
|
+
if (!ctx.bridges.inventory) return null;
|
|
218
|
+
const typed = line;
|
|
219
|
+
return (await ctx.bridges.inventory.reserve([{
|
|
220
|
+
lineId: typed.lineId,
|
|
221
|
+
skuRef: `slot:${typed.payload.serviceRef}:${typed.payload.startsAt}`,
|
|
222
|
+
quantity: 1,
|
|
223
|
+
ttlSeconds: TIMESLOT_VALIDITY_MS / 1e3,
|
|
224
|
+
slot: {
|
|
225
|
+
startsAt: new Date(typed.payload.startsAt),
|
|
226
|
+
endsAt: new Date(typed.payload.endsAt)
|
|
227
|
+
}
|
|
228
|
+
}], ctx))[0] ?? null;
|
|
229
|
+
},
|
|
230
|
+
async release(ref, ctx) {
|
|
231
|
+
if (ctx.bridges.inventory) await ctx.bridges.inventory.release([ref], ctx);
|
|
232
|
+
},
|
|
233
|
+
async displayOf(line, ctx) {
|
|
234
|
+
const typed = line;
|
|
235
|
+
const service = await ctx.bridges.catalog.resolve(typed.payload.serviceRef, ctx);
|
|
236
|
+
if (!service) return null;
|
|
237
|
+
const startDate = new Date(typed.payload.startsAt);
|
|
238
|
+
return {
|
|
239
|
+
name: service.name,
|
|
240
|
+
imageUrl: service.primaryImage,
|
|
241
|
+
slug: service.slug,
|
|
242
|
+
variantLabel: `${startDate.toLocaleDateString()} ${startDate.toLocaleTimeString([], {
|
|
243
|
+
hour: "2-digit",
|
|
244
|
+
minute: "2-digit"
|
|
245
|
+
})}`,
|
|
246
|
+
capturedAt: /* @__PURE__ */ new Date()
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
//#endregion
|
|
251
|
+
//#region src/kinds/bundle.kind.ts
|
|
252
|
+
const bundlePayloadSchema = z.object({
|
|
253
|
+
bundleRef: z.string().min(1),
|
|
254
|
+
components: z.array(z.object({
|
|
255
|
+
skuRef: z.string().min(1),
|
|
256
|
+
quantity: z.number().int().min(1)
|
|
257
|
+
})).min(1)
|
|
258
|
+
});
|
|
259
|
+
const bundleKind = {
|
|
260
|
+
name: "bundle",
|
|
261
|
+
payloadSchema: bundlePayloadSchema,
|
|
262
|
+
validity: {
|
|
263
|
+
maxAgeMs: 900 * 1e3,
|
|
264
|
+
onStale: "reprice"
|
|
265
|
+
},
|
|
266
|
+
async validate(line, ctx) {
|
|
267
|
+
const parsed = bundlePayloadSchema.safeParse(line.payload);
|
|
268
|
+
if (!parsed.success) throw new KindError(this.name, "invalid bundle payload", { details: { issues: parsed.error.issues } });
|
|
269
|
+
if (line.quantity < 1) throw new KindError(this.name, `quantity must be >= 1, got ${line.quantity}`);
|
|
270
|
+
const bundle = await ctx.bridges.catalog.resolve(parsed.data.bundleRef, ctx);
|
|
271
|
+
if (!bundle) throw new KindError(this.name, `unknown bundle: ${parsed.data.bundleRef}`);
|
|
272
|
+
if (!bundle.purchasable) throw new KindError(this.name, `bundle ${parsed.data.bundleRef} is not purchasable`);
|
|
273
|
+
},
|
|
274
|
+
async price(line, ctx) {
|
|
275
|
+
const typed = line;
|
|
276
|
+
const bundle = await ctx.bridges.catalog.resolve(typed.payload.bundleRef, ctx);
|
|
277
|
+
if (!bundle) throw new KindError(this.name, `price() on unknown bundle: ${typed.payload.bundleRef}`);
|
|
278
|
+
const unitPrice = typed.overrideUnitPrice ?? bundle.unitPrice;
|
|
279
|
+
const total = {
|
|
280
|
+
amount: unitPrice.amount * typed.quantity,
|
|
281
|
+
currency: unitPrice.currency
|
|
282
|
+
};
|
|
283
|
+
return {
|
|
284
|
+
lineId: typed.lineId,
|
|
285
|
+
unitPrice,
|
|
286
|
+
quantity: typed.quantity,
|
|
287
|
+
subtotals: {
|
|
288
|
+
prePromo: total,
|
|
289
|
+
postPromo: total,
|
|
290
|
+
postPromoPostTax: total
|
|
291
|
+
},
|
|
292
|
+
discountTotal: {
|
|
293
|
+
amount: 0,
|
|
294
|
+
currency: unitPrice.currency
|
|
295
|
+
},
|
|
296
|
+
taxTotal: {
|
|
297
|
+
amount: 0,
|
|
298
|
+
currency: unitPrice.currency
|
|
299
|
+
},
|
|
300
|
+
validUntil: new Date(Date.now() + 900 * 1e3),
|
|
301
|
+
kindMeta: {
|
|
302
|
+
bundleRef: typed.payload.bundleRef,
|
|
303
|
+
componentCount: typed.payload.components.length
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
},
|
|
307
|
+
async revalidate(line, priced, ctx) {
|
|
308
|
+
const typed = line;
|
|
309
|
+
const bundle = await ctx.bridges.catalog.resolve(typed.payload.bundleRef, ctx);
|
|
310
|
+
if (!bundle) return {
|
|
311
|
+
status: "invalid",
|
|
312
|
+
reason: "bundle no longer exists"
|
|
313
|
+
};
|
|
314
|
+
const currentPrice = bundle.unitPrice.amount;
|
|
315
|
+
const snapshotPrice = priced.unitPrice.amount;
|
|
316
|
+
if (currentPrice !== snapshotPrice) {
|
|
317
|
+
const delta = {
|
|
318
|
+
amount: (currentPrice - snapshotPrice) * typed.quantity,
|
|
319
|
+
currency: priced.unitPrice.currency
|
|
320
|
+
};
|
|
321
|
+
const newTotal = {
|
|
322
|
+
amount: currentPrice * typed.quantity,
|
|
323
|
+
currency: priced.unitPrice.currency
|
|
324
|
+
};
|
|
325
|
+
return {
|
|
326
|
+
status: "reprice",
|
|
327
|
+
priced: {
|
|
328
|
+
...priced,
|
|
329
|
+
unitPrice: {
|
|
330
|
+
amount: currentPrice,
|
|
331
|
+
currency: priced.unitPrice.currency
|
|
332
|
+
},
|
|
333
|
+
subtotals: {
|
|
334
|
+
prePromo: newTotal,
|
|
335
|
+
postPromo: newTotal,
|
|
336
|
+
postPromoPostTax: newTotal
|
|
337
|
+
},
|
|
338
|
+
validUntil: new Date(Date.now() + 900 * 1e3)
|
|
339
|
+
},
|
|
340
|
+
delta
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
return {
|
|
344
|
+
status: "unchanged",
|
|
345
|
+
priced
|
|
346
|
+
};
|
|
347
|
+
},
|
|
348
|
+
async displayOf(line, ctx) {
|
|
349
|
+
const typed = line;
|
|
350
|
+
const bundle = await ctx.bridges.catalog.resolve(typed.payload.bundleRef, ctx);
|
|
351
|
+
if (!bundle) return null;
|
|
352
|
+
return {
|
|
353
|
+
name: bundle.name,
|
|
354
|
+
imageUrl: bundle.primaryImage,
|
|
355
|
+
slug: bundle.slug,
|
|
356
|
+
variantLabel: `${typed.payload.components.length} items`,
|
|
357
|
+
capturedAt: /* @__PURE__ */ new Date()
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
//#endregion
|
|
362
|
+
export { variantKind as a, skuPayloadSchema as c, timeslotPayloadSchema as i, bundlePayloadSchema as n, variantPayloadSchema as o, timeslotKind as r, skuKind as s, bundleKind as t };
|