@vectoriox/iox-ui 5.94.0 → 5.96.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 (33) hide show
  1. package/actions-core/index.d.ts +7 -2
  2. package/commerce-core/index.d.ts +312 -2
  3. package/composite-core/index.d.ts +306 -2
  4. package/design-core/index.d.ts +1049 -105
  5. package/fesm2022/vectoriox-iox-ui-actions-core.mjs +15 -4
  6. package/fesm2022/vectoriox-iox-ui-actions-core.mjs.map +1 -1
  7. package/fesm2022/vectoriox-iox-ui-commerce-core.mjs +527 -6
  8. package/fesm2022/vectoriox-iox-ui-commerce-core.mjs.map +1 -1
  9. package/fesm2022/vectoriox-iox-ui-composite-core.mjs +1193 -177
  10. package/fesm2022/vectoriox-iox-ui-composite-core.mjs.map +1 -1
  11. package/fesm2022/vectoriox-iox-ui-design-core.mjs +1147 -43
  12. package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
  13. package/fesm2022/vectoriox-iox-ui-generation-core.mjs +2 -2
  14. package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
  15. package/fesm2022/vectoriox-iox-ui.mjs +8 -1
  16. package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
  17. package/generation-core/index.d.ts +2 -2
  18. package/index.d.ts +2 -0
  19. package/package.json +1 -1
  20. package/src/actions-core/action.model.ts +1 -1
  21. package/src/actions-core/element-actions.ts +17 -3
  22. package/src/commerce-core/cart-transport.ts +211 -0
  23. package/src/commerce-core/public-api.ts +4 -0
  24. package/src/commerce-core/quantity.ts +56 -0
  25. package/src/commerce-core/shop-display.ts +117 -0
  26. package/src/commerce-core/variants.ts +296 -0
  27. package/src/composite-core/exclusive-runtime.ts +20 -7
  28. package/src/composite-core/public-api.ts +2 -0
  29. package/src/composite-core/shop-runtime.ts +626 -0
  30. package/src/composite-core/shop.ts +458 -0
  31. package/src/design-core/flavor-spec.generated.ts +1147 -43
  32. package/src/generation-core/site-spec.generated.ts +2 -2
  33. package/styles/iox-design.css +95 -0
@@ -1239,15 +1239,15 @@ function deepFreeze(value) {
1239
1239
  return value;
1240
1240
  }
1241
1241
  const copyMoney = (value) => money(value.amount, value.currency);
1242
- const text = (value) => (filled(value) ? value.trim() : null);
1242
+ const text$1 = (value) => (filled(value) ? value.trim() : null);
1243
1243
  function copyAddress(address) {
1244
1244
  if (!address || !filled(address.line1) || !filled(address.city) || !filled(address.country))
1245
1245
  return null;
1246
1246
  return {
1247
1247
  line1: address.line1.trim(),
1248
- line2: text(address.line2),
1248
+ line2: text$1(address.line2),
1249
1249
  city: address.city.trim(),
1250
- postalCode: text(address.postalCode),
1250
+ postalCode: text$1(address.postalCode),
1251
1251
  country: address.country.trim(),
1252
1252
  };
1253
1253
  }
@@ -1294,18 +1294,539 @@ function orderSnapshot(pricedCart, payment, buyer) {
1294
1294
  kind: payment.kind,
1295
1295
  channel: paymentChannelOf(payment.kind),
1296
1296
  details: { ...(payment.details ?? {}) },
1297
- note: text(payment.note),
1297
+ note: text$1(payment.note),
1298
1298
  },
1299
1299
  buyer: {
1300
1300
  email: buyer.email.trim(),
1301
1301
  name: buyer.name.trim(),
1302
- phone: text(buyer.phone),
1302
+ phone: text$1(buyer.phone),
1303
1303
  address: delivery?.needsAddress ? copyAddress(buyer.address) : null,
1304
1304
  },
1305
1305
  };
1306
1306
  return { ok: true, snapshot: deepFreeze(snapshot) };
1307
1307
  }
1308
1308
 
1309
+ /**
1310
+ * A product's OPTIONS and its VARIANTS as the storefront serves them (iox-cms `storefront-projection.ts`), read into
1311
+ * what a product page needs (commerce plan §3i, trap T26): which values each option offers, which of them can still be
1312
+ * bought given what is already chosen, and the variant a full choice names.
1313
+ *
1314
+ * A stored variant has no option map, only a flat NAME — the option values in option order joined by `-` (the admin's
1315
+ * `product.component.ts` `generateCombinations`: "Red-M"). A name is matched against every combination of the options'
1316
+ * values, never split on `-`, so a value that holds a `-` ("Off-white") still reads.
1317
+ */
1318
+ const VARIANT_NAME_SEPARATOR = '-';
1319
+ /** The one variant row a product with no options keeps (iox-cms `DEFAULT_VARIANT_NAME`). */
1320
+ const DEFAULT_VARIANT_NAME = 'Default';
1321
+ const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
1322
+ const text = (value) => (typeof value === 'string' ? value.trim() : typeof value === 'number' && Number.isFinite(value) ? String(value) : '');
1323
+ /** True for something the storefront could have served as a product: a title and a price or variants. */
1324
+ function isStorefrontProduct(value) {
1325
+ return isRecord(value) && typeof value['title'] === 'string' && (isRecord(value['pricing']) || Array.isArray(value['variants']));
1326
+ }
1327
+ /** The product's currency, or null when it names none we know (a price is then never shown — never guessed). */
1328
+ function productCurrency(product) {
1329
+ const code = text(product?.currency).toUpperCase();
1330
+ return isCurrencyCode(code) ? code : null;
1331
+ }
1332
+ /** The options a product offers, cleaned: named, each value once, no empty value. None when it has no variants. */
1333
+ function productOptions(product) {
1334
+ if (!product?.productVariants || !Array.isArray(product.options))
1335
+ return [];
1336
+ const out = [];
1337
+ for (const raw of product.options) {
1338
+ const name = text(raw?.name);
1339
+ if (!name || out.some(o => o.name === name))
1340
+ continue;
1341
+ const values = [];
1342
+ for (const v of Array.isArray(raw?.values) ? raw.values : []) {
1343
+ const value = text(v);
1344
+ if (value && !values.includes(value))
1345
+ values.push(value);
1346
+ }
1347
+ if (values.length)
1348
+ out.push({ name, values });
1349
+ }
1350
+ return out;
1351
+ }
1352
+ /** Every full choice of `options`, in the admin's order, with the variant name it writes. */
1353
+ function combinations(options) {
1354
+ let acc = [{ parts: [], choice: {} }];
1355
+ for (const option of options) {
1356
+ const next = [];
1357
+ for (const partial of acc) {
1358
+ for (const value of option.values)
1359
+ next.push({ parts: [...partial.parts, value], choice: { ...partial.choice, [option.name]: value } });
1360
+ }
1361
+ acc = next;
1362
+ }
1363
+ return acc.map(c => ({ name: c.parts.join(VARIANT_NAME_SEPARATOR), choice: c.choice }));
1364
+ }
1365
+ /** The choice a stored variant's flat name stands for, or null when no combination of the options writes it. */
1366
+ function variantChoiceOf(variant, options) {
1367
+ const name = text(variant?.name);
1368
+ if (!name || !options.length)
1369
+ return null;
1370
+ return combinations(options).find(c => c.name === name)?.choice ?? null;
1371
+ }
1372
+ /** A stored major-unit price as Money, or null (no price, a currency we do not know, a value that is no price). */
1373
+ function storefrontMoney(value, currency) {
1374
+ if (!currency)
1375
+ return null;
1376
+ if (isMoney(value))
1377
+ return value.currency === currency ? value : null;
1378
+ if (typeof value !== 'number' && typeof value !== 'string')
1379
+ return null;
1380
+ if (typeof value === 'string' && value.trim() === '')
1381
+ return null;
1382
+ try {
1383
+ return money(majorToMinor(value, currency), currency);
1384
+ }
1385
+ catch {
1386
+ const minor = migrateMajorPrice(value, currency);
1387
+ return minor === null ? null : money(minor, currency);
1388
+ }
1389
+ }
1390
+ const AVAILABILITIES = Object.values(Availability);
1391
+ function availabilityOf(value, enabled) {
1392
+ if (!enabled)
1393
+ return Availability.Out;
1394
+ return AVAILABILITIES.includes(text(value)) ? text(value) : Availability.InStock;
1395
+ }
1396
+ function aboveOnly(compareAt, price) {
1397
+ return compareAt && price && compareAt.amount > price.amount ? compareAt : null;
1398
+ }
1399
+ /**
1400
+ * Every variant of a product, read. A product with no options is ONE view: its Default row's id (or null when it has
1401
+ * no row) and the product's own price. A variant whose name matches no combination of the options is left out — the
1402
+ * page cannot offer what it cannot name.
1403
+ */
1404
+ function productVariants(product) {
1405
+ if (!product)
1406
+ return [];
1407
+ const currency = productCurrency(product);
1408
+ const options = productOptions(product);
1409
+ const rows = Array.isArray(product.variants) ? product.variants.filter(isRecord) : [];
1410
+ const view = (row, choice, priceRaw, compareRaw, image, availability) => {
1411
+ const enabled = row?.enable !== false;
1412
+ const price = storefrontMoney(priceRaw, currency);
1413
+ const state = availabilityOf(availability, enabled);
1414
+ return {
1415
+ variantId: text(row?._id) || null,
1416
+ name: text(row?.name) || null,
1417
+ choice,
1418
+ price,
1419
+ compareAt: aboveOnly(storefrontMoney(compareRaw, currency), price),
1420
+ image: text(image) || null,
1421
+ availability: state,
1422
+ enabled,
1423
+ sellable: enabled && !!price && state !== Availability.Out,
1424
+ };
1425
+ };
1426
+ if (!options.length) {
1427
+ const row = rows.find(r => r.name === DEFAULT_VARIANT_NAME) ?? (rows.length === 1 ? rows[0] : null);
1428
+ const pricing = product.pricing ?? {};
1429
+ return [view(row, {}, row?.price ?? pricing.price, row?.compareat ?? pricing.compareat, row?.image || product.mainImage, row?.availability ?? product.availability)];
1430
+ }
1431
+ const out = [];
1432
+ for (const row of rows) {
1433
+ const choice = variantChoiceOf(row, options);
1434
+ if (choice)
1435
+ out.push(view(row, choice, row.price, row.compareat, row.image || product.mainImage, row.availability));
1436
+ }
1437
+ return out;
1438
+ }
1439
+ const matches = (variant, choice, names) => names.every(name => choice[name] === undefined || variant.choice[name] === choice[name]);
1440
+ /** The variant a FULL choice names, or null (a choice that misses an option, or names no stored variant). */
1441
+ function findVariant(options, variants, choice) {
1442
+ if (!options.length)
1443
+ return variants[0] ?? null;
1444
+ if (options.some(o => !choice[o.name]))
1445
+ return null;
1446
+ return variants.find(v => options.every(o => v.choice[o.name] === choice[o.name])) ?? null;
1447
+ }
1448
+ /**
1449
+ * What each option offers now. Availability CASCADES in option order (the way a buyer reads the page, top to bottom):
1450
+ * a value of the first option is available when ANY sellable variant has it; a value of a later option, when a
1451
+ * sellable variant has it together with the values chosen for the options before it. So a buyer can always change an
1452
+ * earlier option and the later ones follow (`chooseValue`) — never stuck behind a combination that is sold out.
1453
+ */
1454
+ function optionValueStates(options, variants, choice) {
1455
+ const sellable = variants.filter(v => v.sellable);
1456
+ return options.map((option, index) => {
1457
+ const before = options.slice(0, index).map(o => o.name);
1458
+ return {
1459
+ name: option.name,
1460
+ values: option.values.map(value => ({
1461
+ value,
1462
+ available: sellable.some(v => v.choice[option.name] === value && matches(v, choice, before)),
1463
+ selected: choice[option.name] === value,
1464
+ })),
1465
+ };
1466
+ });
1467
+ }
1468
+ /** The choice a page opens with: the first sellable variant's, else the first value of every option. */
1469
+ function defaultChoice(options, variants) {
1470
+ const first = variants.find(v => v.sellable && options.every(o => v.choice[o.name]));
1471
+ if (first)
1472
+ return { ...first.choice };
1473
+ return Object.fromEntries(options.map(o => [o.name, o.values[0]]));
1474
+ }
1475
+ /**
1476
+ * The buyer picks `value` for option `name`. The options AFTER it keep their value while it is still available after
1477
+ * the change, else move to their first available value (else keep it — the page then says the combination is sold out).
1478
+ * An unknown option or value changes nothing.
1479
+ */
1480
+ function chooseValue(options, variants, choice, name, value) {
1481
+ const at = options.findIndex(o => o.name === name);
1482
+ if (at < 0 || !options[at].values.includes(value))
1483
+ return choice;
1484
+ const next = { ...choice, [name]: value };
1485
+ for (let i = at + 1; i < options.length; i++) {
1486
+ const state = optionValueStates(options, variants, next)[i];
1487
+ const keeps = state.values.find(v => v.value === next[options[i].name])?.available;
1488
+ if (keeps)
1489
+ continue;
1490
+ const first = state.values.find(v => v.available);
1491
+ if (first)
1492
+ next[options[i].name] = first.value;
1493
+ }
1494
+ return next;
1495
+ }
1496
+ /** The catalog entries a storefront product sells (one per variant, or one for a product with no options) — what
1497
+ * `priceCart` reads where only the storefront is known (the builder canvas's simulated cart). iox-cms builds its own
1498
+ * from the stored row, with the stock COUNT. */
1499
+ function storefrontCatalog(product) {
1500
+ const productId = text(product?._id);
1501
+ if (!product || !productId)
1502
+ return [];
1503
+ const hasOptions = productOptions(product).length > 0;
1504
+ return productVariants(product).map(v => ({
1505
+ productId,
1506
+ variantId: hasOptions ? v.variantId : null,
1507
+ title: text(product.title),
1508
+ variantName: hasOptions ? Object.values(v.choice).join(' · ') : null,
1509
+ unitPrice: v.price,
1510
+ compareAt: v.compareAt,
1511
+ availability: v.availability,
1512
+ enabled: v.enabled,
1513
+ published: true,
1514
+ requiresShipping: true,
1515
+ image: v.image,
1516
+ }));
1517
+ }
1518
+ /** The words a chosen variant is shown with in a cart line ("Sand · 32 cm"). */
1519
+ function variantWords(choice, options) {
1520
+ return options.map(o => choice[o.name]).filter(Boolean).join(' · ');
1521
+ }
1522
+ // ── the product in scope ─────────────────────────────────────────────────────────────────────
1523
+ /** The data keys a product page's own item sits under (the route's item first — relative data sources). */
1524
+ const ROUTE_KEYS = ['$current', '$route'];
1525
+ /**
1526
+ * The product an element is about, the SAME rule on the builder canvas and the live site: the repeated row it sits in
1527
+ * when that row is a product (a card in a product list), else the page's route item, else the first product the page's
1528
+ * data holds (a product page bound to one product). Null when the page has none.
1529
+ */
1530
+ function productInScope(rowItem, data) {
1531
+ if (isStorefrontProduct(rowItem))
1532
+ return rowItem;
1533
+ const all = data ?? {};
1534
+ for (const key of ROUTE_KEYS)
1535
+ if (isStorefrontProduct(all[key]))
1536
+ return all[key];
1537
+ for (const value of Object.values(all))
1538
+ if (isStorefrontProduct(value))
1539
+ return value;
1540
+ return null;
1541
+ }
1542
+
1543
+ /**
1544
+ * The quantity a buyer may ask for — the stepper on a product page and on every cart line (commerce plan §3i). Whole
1545
+ * numbers only, the forms-core number rule: anything that is not a whole number reads as the least. The most is the
1546
+ * one-line cap (`MAX_LINE_QUANTITY`), lowered to the count when the count is known (iox-cms) — the storefront knows only
1547
+ * a word, so it caps at the line cap and the server clamps (`priceCart` QuantityClamped).
1548
+ */
1549
+ const MIN_LINE_QUANTITY = 1;
1550
+ var QuantityStep;
1551
+ (function (QuantityStep) {
1552
+ QuantityStep[QuantityStep["Down"] = -1] = "Down";
1553
+ QuantityStep[QuantityStep["Up"] = 1] = "Up";
1554
+ })(QuantityStep || (QuantityStep = {}));
1555
+ /** What a stepper allows for a unit with this count / word. `out` (or a count of 0) allows nothing. */
1556
+ function quantityBounds(unit) {
1557
+ if (typeof unit?.stock === 'number') {
1558
+ const left = Number.isSafeInteger(unit.stock) && unit.stock > 0 ? unit.stock : 0;
1559
+ return { min: MIN_LINE_QUANTITY, max: Math.min(MAX_LINE_QUANTITY, left) };
1560
+ }
1561
+ if (unit?.availability === Availability.Out)
1562
+ return { min: MIN_LINE_QUANTITY, max: 0 };
1563
+ return { min: MIN_LINE_QUANTITY, max: MAX_LINE_QUANTITY };
1564
+ }
1565
+ /** True when the bounds allow buying at all. */
1566
+ function canBuy(bounds) {
1567
+ return bounds.max >= bounds.min;
1568
+ }
1569
+ /** A quantity held within the bounds; not a whole number → the least. */
1570
+ function clampQuantity(value, bounds) {
1571
+ const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
1572
+ if (!Number.isSafeInteger(n))
1573
+ return bounds.min;
1574
+ if (!canBuy(bounds))
1575
+ return bounds.min;
1576
+ return Math.min(bounds.max, Math.max(bounds.min, n));
1577
+ }
1578
+ /** True when a step in `direction` stays within the bounds. */
1579
+ function canStep(value, direction, bounds) {
1580
+ if (!canBuy(bounds))
1581
+ return false;
1582
+ const next = clampQuantity(value, bounds) + direction;
1583
+ return next >= bounds.min && next <= bounds.max;
1584
+ }
1585
+ /** One step, held within the bounds. */
1586
+ function stepQuantity(value, direction, bounds) {
1587
+ return clampQuantity(clampQuantity(value, bounds) + direction, bounds);
1588
+ }
1589
+
1590
+ var CartTransportErrorCode;
1591
+ (function (CartTransportErrorCode) {
1592
+ /** No cart on this host (the engine before E1d, a site with no shop). */
1593
+ CartTransportErrorCode["Unavailable"] = "unavailable";
1594
+ /** The server said no (a product no longer sold, a rate limit). */
1595
+ CartTransportErrorCode["Refused"] = "refused";
1596
+ /** The call never reached the server. */
1597
+ CartTransportErrorCode["Network"] = "network";
1598
+ })(CartTransportErrorCode || (CartTransportErrorCode = {}));
1599
+ const CART_TRANSPORT_ERROR_LABELS = Object.freeze({
1600
+ [CartTransportErrorCode.Unavailable]: { en: 'The shop is not open yet.', he: 'החנות עוד לא פתוחה.' },
1601
+ [CartTransportErrorCode.Refused]: { en: 'That could not be added to your bag.', he: 'לא ניתן היה להוסיף לסל.' },
1602
+ [CartTransportErrorCode.Network]: { en: 'We could not reach the shop. Try again.', he: 'לא הצלחנו להגיע לחנות. נסו שוב.' },
1603
+ });
1604
+ class CartTransportError extends Error {
1605
+ constructor(code, message) {
1606
+ super(message ?? code);
1607
+ this.code = code;
1608
+ this.name = 'CartTransportError';
1609
+ }
1610
+ }
1611
+ /** A line's id when the host has none of its own: the product and the variant, URL-safe. */
1612
+ function cartLineId(productId, variantId) {
1613
+ return `${encodeURIComponent(productId)}~${encodeURIComponent(variantId ?? '')}`;
1614
+ }
1615
+ /** The public cart routes (§3d) — ROOT-relative, like the forms submit path (a relative path under the org's
1616
+ * `<base href>` reaches the engine, never iox-cms). `lineId` addresses one line. */
1617
+ function cartEndpointPath(orgId, lineId) {
1618
+ const base = `/api/site/${encodeURIComponent(orgId)}/cart`;
1619
+ return lineId ? `${base}/lines/${encodeURIComponent(lineId)}` : base;
1620
+ }
1621
+ /** The fixed checkout route (C-D3), relative to the site's `<base href="/<orgLabel>/">`. */
1622
+ const CHECKOUT_PATH = 'checkout';
1623
+ /** The checkout's href: `/<orgLabel>/checkout` under a label, else `/checkout`. */
1624
+ function checkoutHref(orgLabel) {
1625
+ const label = String(orgLabel ?? '').replace(/^\/+|\/+$/g, '');
1626
+ return label ? `/${encodeURIComponent(label)}/${CHECKOUT_PATH}` : `/${CHECKOUT_PATH}`;
1627
+ }
1628
+ /** A cart with nothing in it. */
1629
+ function emptyCartView(currency = null) {
1630
+ return { currency, lines: [], count: 0, empty: true, subtotal: null, total: null, vat: null, vatPercent: 0, issues: [], freeShippingRemaining: null };
1631
+ }
1632
+ /** The view of a priced cart. `lineIdOf` names each line the way the host's routes do (default `cartLineId`);
1633
+ * `maxOf` says how many a line may hold (default the line cap). */
1634
+ function cartViewOf(priced, options = {}) {
1635
+ const lineIdOf = options.lineIdOf ?? (line => cartLineId(line.productId, line.variantId));
1636
+ const maxOf = options.maxOf ?? (() => MAX_LINE_QUANTITY);
1637
+ const lines = priced.lines.map(line => ({ ...line, lineId: lineIdOf(line), maxQuantity: Math.max(line.quantity, maxOf(line)) }));
1638
+ const count = lines.reduce((sum, line) => sum + line.quantity, 0);
1639
+ return {
1640
+ currency: priced.currency,
1641
+ lines,
1642
+ count,
1643
+ empty: lines.length === 0,
1644
+ subtotal: priced.subtotal,
1645
+ total: priced.total,
1646
+ vat: priced.vat,
1647
+ vatPercent: priced.vatPercent,
1648
+ issues: priced.issues,
1649
+ freeShippingRemaining: options.freeShippingRemaining ?? null,
1650
+ };
1651
+ }
1652
+ /** iox-cms's answer as the view the parts paint — the server's line ids, its prices untouched. */
1653
+ function siteCartView(site, freeShippingRemaining = null) {
1654
+ const ids = new Map(site.lines.map(line => [line, line.id]));
1655
+ return cartViewOf(site, { lineIdOf: line => ids.get(line) ?? cartLineId(line.productId, line.variantId), freeShippingRemaining });
1656
+ }
1657
+ /** How a refused cart call is said: no cart service (501, 503) or a shop off the plan (403) is Unavailable, a
1658
+ * status the server chose is Refused, anything that never got an answer is Network. */
1659
+ function cartTransportErrorFor(status) {
1660
+ if (!status)
1661
+ return new CartTransportError(CartTransportErrorCode.Network);
1662
+ if (status === 501 || status === 503 || status === 403)
1663
+ return new CartTransportError(CartTransportErrorCode.Unavailable, String(status));
1664
+ return new CartTransportError(CartTransportErrorCode.Refused, String(status));
1665
+ }
1666
+ /** The words a cart's issues are said with, once each. */
1667
+ function cartIssueWords(view, lang) {
1668
+ const codes = [...new Set(view.issues.map(i => i.code))];
1669
+ return codes.map(code => labelIn(CART_ISSUE_LABELS[code], lang));
1670
+ }
1671
+ /** The host with no cart yet (the engine until E1d binds its own): every read is an empty cart, every change refused. */
1672
+ const NO_CART_TRANSPORT = Object.freeze({
1673
+ read: () => Promise.resolve(emptyCartView()),
1674
+ add: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
1675
+ setQuantity: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
1676
+ remove: () => Promise.reject(new CartTransportError(CartTransportErrorCode.Unavailable)),
1677
+ });
1678
+ function simulatedCartTransport(catalog, studio, initial = { lines: [] }) {
1679
+ const entries = new Map();
1680
+ const known = (list) => list.forEach(e => entries.set(catalogKey(e.productId, e.variantId), e));
1681
+ known(catalog);
1682
+ let cart = { lines: [] };
1683
+ const maxOf = (line) => quantityBounds(entries.get(catalogKey(line.productId, line.variantId))).max;
1684
+ const price = (next) => {
1685
+ const priced = priceCart(next, [...entries.values()], studio);
1686
+ cart = cartOf(priced);
1687
+ return cartViewOf(priced, { maxOf });
1688
+ };
1689
+ price(initial);
1690
+ const lineOf = (lineId) => cart.lines.find(l => cartLineId(l.productId, l.variantId) === lineId);
1691
+ return {
1692
+ addEntries: list => known(list),
1693
+ peek: () => price(cart),
1694
+ read: () => Promise.resolve(price(cart)),
1695
+ add: request => {
1696
+ if (!entries.has(catalogKey(request.productId, request.variantId)))
1697
+ return Promise.reject(new CartTransportError(CartTransportErrorCode.Refused));
1698
+ const same = cart.lines.find(l => l.productId === request.productId && (l.variantId ?? null) === (request.variantId ?? null));
1699
+ const lines = same
1700
+ ? cart.lines.map(l => (l === same ? { ...l, quantity: l.quantity + request.quantity } : l))
1701
+ : [...cart.lines, { productId: request.productId, variantId: request.variantId ?? null, quantity: request.quantity }];
1702
+ return Promise.resolve(price({ lines }));
1703
+ },
1704
+ setQuantity: (lineId, quantity) => {
1705
+ const line = lineOf(lineId);
1706
+ if (!line)
1707
+ return Promise.reject(new CartTransportError(CartTransportErrorCode.Refused));
1708
+ return Promise.resolve(price({ lines: cart.lines.map(l => (l === line ? { ...l, quantity } : l)) }));
1709
+ },
1710
+ remove: lineId => Promise.resolve(price({ lines: cart.lines.filter(l => l !== lineOf(lineId)) })),
1711
+ };
1712
+ }
1713
+
1714
+ /**
1715
+ * How a price READS on a page — the `money` binding pipe (shop-aware plan A-D2, amended by C-D7) on the builder canvas,
1716
+ * the engine's SSR and its hydration: ONE function, so the three never disagree on a digit.
1717
+ *
1718
+ * - a `Money` (minor units + its currency — `$variant.price`, a cart's totals) is formatted as it is;
1719
+ * - a bare number or numeric string (`pricing.price` as the storefront serves it: MAJOR units) needs a currency — the
1720
+ * pipe's own argument, else the studio's (`PipeContext.currency`); with none it is left as it was, never guessed;
1721
+ * - nothing (null, undefined, '') reads as nothing.
1722
+ * The locale is the page's language (`en` when unsaid, so the canvas and the server agree).
1723
+ */
1724
+ const DEFAULT_MONEY_LOCALE = 'en';
1725
+ function formatMoneyValue(value, currency, locale) {
1726
+ if (value === null || value === undefined || value === '')
1727
+ return '';
1728
+ const lang = locale || DEFAULT_MONEY_LOCALE;
1729
+ if (isMoney(value)) {
1730
+ try {
1731
+ return formatMoney(value, lang);
1732
+ }
1733
+ catch {
1734
+ return value;
1735
+ }
1736
+ }
1737
+ const code = String(currency ?? '').trim().toUpperCase();
1738
+ if (!isCurrencyCode(code))
1739
+ return value;
1740
+ const amount = storefrontMoney(value, code);
1741
+ if (!amount)
1742
+ return value;
1743
+ try {
1744
+ return formatMoney(amount, lang);
1745
+ }
1746
+ catch {
1747
+ return value;
1748
+ }
1749
+ }
1750
+ /**
1751
+ * The two slots the shop parts write at runtime (the element-context channel — a slot is a `resolvedData` key written
1752
+ * at runtime, element-context-state plan): the variant the buyer has chosen (`$variant.price | money`) and the cart
1753
+ * (`$cart.count` on the cart button's badge). Written by the shop runtime through its host, read by ordinary bindings.
1754
+ */
1755
+ var ShopSlot;
1756
+ (function (ShopSlot) {
1757
+ ShopSlot["Variant"] = "$variant";
1758
+ ShopSlot["Cart"] = "$cart";
1759
+ })(ShopSlot || (ShopSlot = {}));
1760
+ const SHOP_SLOTS = Object.freeze(Object.values(ShopSlot));
1761
+ // ── the shop parts' words (a string-rendered site has no translation service — the labels.ts rule) ──────────────
1762
+ var ShopWord;
1763
+ (function (ShopWord) {
1764
+ ShopWord["Added"] = "added";
1765
+ ShopWord["SoldOut"] = "soldOut";
1766
+ ShopWord["ValueSoldOut"] = "valueSoldOut";
1767
+ ShopWord["Decrease"] = "decrease";
1768
+ ShopWord["Increase"] = "increase";
1769
+ ShopWord["Remove"] = "remove";
1770
+ ShopWord["Cart"] = "cart";
1771
+ ShopWord["CartCount"] = "cartCount";
1772
+ ShopWord["Quantity"] = "quantity";
1773
+ ShopWord["FreeShippingGap"] = "freeShippingGap";
1774
+ ShopWord["ChooseOption"] = "chooseOption";
1775
+ })(ShopWord || (ShopWord = {}));
1776
+ /** `{name}` / `{n}` / `{amount}` are filled by `shopWord`. */
1777
+ const SHOP_WORDS = Object.freeze({
1778
+ [ShopWord.Added]: { en: 'Added ✓', he: 'נוסף ✓' },
1779
+ [ShopWord.SoldOut]: { en: 'Sold out', he: 'אזל' },
1780
+ [ShopWord.ValueSoldOut]: { en: '{name} is sold out', he: '{name} אזל מהמלאי' },
1781
+ [ShopWord.Decrease]: { en: 'Decrease quantity', he: 'הפחתת כמות' },
1782
+ [ShopWord.Increase]: { en: 'Increase quantity', he: 'הגדלת כמות' },
1783
+ [ShopWord.Remove]: { en: 'Remove {name}', he: 'הסרת {name}' },
1784
+ [ShopWord.Cart]: { en: 'Bag', he: 'סל' },
1785
+ [ShopWord.CartCount]: { en: 'Bag, {n} items', he: 'סל, {n} פריטים' },
1786
+ [ShopWord.Quantity]: { en: 'Quantity', he: 'כמות' },
1787
+ [ShopWord.FreeShippingGap]: { en: 'Add {amount} more for free delivery', he: 'עוד {amount} למשלוח חינם' },
1788
+ [ShopWord.ChooseOption]: { en: 'Choose {name}', he: 'בחירת {name}' },
1789
+ });
1790
+ function shopWord(word, lang, fill = {}) {
1791
+ const primary = String(lang ?? '').toLowerCase().split(/[-_]/)[0];
1792
+ const label = SHOP_WORDS[word];
1793
+ const raw = primary === 'he' || primary === 'iw' ? label.he : label.en;
1794
+ return raw.replace(/\{(\w+)\}/g, (all, key) => (key in fill ? String(fill[key]) : all));
1795
+ }
1796
+ // ── the sample a canvas shows when no product is bound (commerce board 10, "Studio Kadar") ────────────────────────
1797
+ /** Board 10's tall speckled vase: Glaze (Sand · Ash · Charcoal — Charcoal sold out) × Size (24 · 32 · 40 cm — 40 sold
1798
+ * out), ₪240 against ₪280. Major units, as the storefront serves them. */
1799
+ const SAMPLE_PRODUCT = Object.freeze({
1800
+ _id: 'sample-vase',
1801
+ title: 'Tall speckled vase',
1802
+ slug: 'tall-speckled-vase',
1803
+ mainImage: null,
1804
+ productVariants: true,
1805
+ currency: CurrencyCode.ILS,
1806
+ availability: 'in_stock',
1807
+ pricing: { price: 240, compareat: 280 },
1808
+ options: [
1809
+ { name: 'Glaze', values: ['Sand', 'Ash', 'Charcoal'] },
1810
+ { name: 'Size', values: ['24 cm', '32 cm', '40 cm'] },
1811
+ ],
1812
+ // Rows in the order a page opens on: Sand · 32 cm first (the first sellable row is the default choice).
1813
+ variants: ['Sand', 'Ash', 'Charcoal'].flatMap(glaze => ['32 cm', '24 cm', '40 cm'].map(size => ({
1814
+ _id: `sample-${glaze}-${size}`.toLowerCase().replace(/\s+/g, ''),
1815
+ name: `${glaze}-${size}`,
1816
+ enable: true,
1817
+ image: null,
1818
+ price: size === '24 cm' ? 190 : 240,
1819
+ compareat: size === '32 cm' ? 280 : null,
1820
+ availability: glaze === 'Charcoal' || size === '40 cm' ? 'out' : 'in_stock',
1821
+ }))),
1822
+ });
1823
+ /** The colours board 10 draws its sample glazes with (a sample value has no colour of its own). */
1824
+ const SAMPLE_SWATCHES = Object.freeze({ Sand: '#D8C6A8', Ash: '#F3F1EC', Charcoal: '#3A3B3D' });
1825
+ /** The sample studio's money (VAT 18 %, ₪). */
1826
+ const SAMPLE_STUDIO = Object.freeze({ currency: CurrencyCode.ILS, vatPercent: 18, shippingMethods: [] });
1827
+ /** The cart the canvas starts with: one sample line, so the drawer has a line to design. */
1828
+ const SAMPLE_CART_LINE = Object.freeze({ productId: 'sample-vase', variantId: 'sample-sand-32cm', quantity: 1 });
1829
+
1309
1830
  /**
1310
1831
  * @vectoriox/iox-ui/commerce-core — the shared, FRAMEWORK-FREE core of selling (commerce plan C-D7…C-D11, C-D19).
1311
1832
  *
@@ -1321,5 +1842,5 @@ function orderSnapshot(pricedCart, payment, buyer) {
1321
1842
  * Generated bundle index. Do not edit.
1322
1843
  */
1323
1844
 
1324
- export { Availability, CART_ISSUE_LABELS, CHECKOUT_GATE_RULES, CHECKOUT_STEPS, CHECKOUT_STEP_LABELS, CURRENCY_CODES, CURRENCY_EXPONENTS, CartIssueCode, CheckoutGateArea, CheckoutGateCode, CheckoutStep, CommerceLanguage, CurrencyCode, DeliveryFit, FINAL_ORDER_STATES, LegalPage, MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY, MAX_VAT_PERCENT, MoneyError, MoneyErrorCode, ORDER_STATE_LABELS, ORDER_STOCK_HOLD, ORDER_TRANSITIONS, OrderActor, OrderEvent, OrderRefusal, OrderSnapshotRefusal, OrderState, PAYMENT_FIELD_LABELS, PAYMENT_METHODS, PaymentChannel, PaymentField, PaymentMethodKind, PaymentProvider, SHIPPING_KINDS, STOCK_EFFECTS, STOCK_RESERVATION_MINUTES, ShippingField, ShippingMethodKind, StockEffect, StockHold, VAT_PERCENT_MAX_DECIMALS, addMoney, availableShippingMethods, cartOf, catalogKey, checkoutGate, commerceLanguage, currencyExponent, formatMoney, furthestStep, includedVat, isCurrencyCode, isMoney, isPaymentMethodKind, isShippingMethodKind, isVatPercent, labelIn, majorToMinor, mergeCarts, migrateMajorPrice, minorToMajor, money, nextOrderState, openingOrderState, orderSnapshot, paymentChannelOf, paymentInstructions, paymentMethodProblems, paymentMethodReady, percentOf, priceCart, quoteShipping, reservationExpiresAt, sellableQuantity, shippingMethodProblems, shippingMethodReady, shippingNeedsAddress, stockEffect, subtractMoney, timesMoney, usablePaymentMethods };
1845
+ export { Availability, CART_ISSUE_LABELS, CART_TRANSPORT_ERROR_LABELS, CHECKOUT_GATE_RULES, CHECKOUT_PATH, CHECKOUT_STEPS, CHECKOUT_STEP_LABELS, CURRENCY_CODES, CURRENCY_EXPONENTS, CartIssueCode, CartTransportError, CartTransportErrorCode, CheckoutGateArea, CheckoutGateCode, CheckoutStep, CommerceLanguage, CurrencyCode, DEFAULT_MONEY_LOCALE, DEFAULT_VARIANT_NAME, DeliveryFit, FINAL_ORDER_STATES, LegalPage, MAX_CART_AMOUNT, MAX_CART_LINES, MAX_LINE_QUANTITY, MAX_VAT_PERCENT, MIN_LINE_QUANTITY, MoneyError, MoneyErrorCode, NO_CART_TRANSPORT, ORDER_STATE_LABELS, ORDER_STOCK_HOLD, ORDER_TRANSITIONS, OrderActor, OrderEvent, OrderRefusal, OrderSnapshotRefusal, OrderState, PAYMENT_FIELD_LABELS, PAYMENT_METHODS, PaymentChannel, PaymentField, PaymentMethodKind, PaymentProvider, QuantityStep, SAMPLE_CART_LINE, SAMPLE_PRODUCT, SAMPLE_STUDIO, SAMPLE_SWATCHES, SHIPPING_KINDS, SHOP_SLOTS, SHOP_WORDS, STOCK_EFFECTS, STOCK_RESERVATION_MINUTES, ShippingField, ShippingMethodKind, ShopSlot, ShopWord, StockEffect, StockHold, VARIANT_NAME_SEPARATOR, VAT_PERCENT_MAX_DECIMALS, addMoney, availableShippingMethods, canBuy, canStep, cartEndpointPath, cartIssueWords, cartLineId, cartOf, cartTransportErrorFor, cartViewOf, catalogKey, checkoutGate, checkoutHref, chooseValue, clampQuantity, commerceLanguage, currencyExponent, defaultChoice, emptyCartView, findVariant, formatMoney, formatMoneyValue, furthestStep, includedVat, isCurrencyCode, isMoney, isPaymentMethodKind, isShippingMethodKind, isStorefrontProduct, isVatPercent, labelIn, majorToMinor, mergeCarts, migrateMajorPrice, minorToMajor, money, nextOrderState, openingOrderState, optionValueStates, orderSnapshot, paymentChannelOf, paymentInstructions, paymentMethodProblems, paymentMethodReady, percentOf, priceCart, productCurrency, productInScope, productOptions, productVariants, quantityBounds, quoteShipping, reservationExpiresAt, sellableQuantity, shippingMethodProblems, shippingMethodReady, shippingNeedsAddress, shopWord, simulatedCartTransport, siteCartView, stepQuantity, stockEffect, storefrontCatalog, storefrontMoney, subtractMoney, timesMoney, usablePaymentMethods, variantChoiceOf, variantWords };
1325
1846
  //# sourceMappingURL=vectoriox-iox-ui-commerce-core.mjs.map