@brainerce/mcp-server 3.4.0 → 3.5.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/dist/bin/http.js CHANGED
@@ -267,9 +267,14 @@ function CheckoutPage() {
267
267
  }
268
268
 
269
269
  // Step 4: Create payment intent \u2014 returns provider type!
270
+ // Pass saveCard: true when the customer ticked "save my card for next time" \u2014
271
+ // only honored for logged-in customers (not guests). The vaulted card then
272
+ // appears in client.listSavedPaymentMethods(storeId, customerId) and can be
273
+ // charged off-session via subscription / one-click checkout flows.
270
274
  const paymentIntent = await client.createPaymentIntent(checkoutId, {
271
275
  successUrl: \`\${window.location.origin}/order-confirmation?checkout_id=\${checkoutId}\`,
272
276
  cancelUrl: \`\${window.location.origin}/checkout?error=payment_cancelled\`,
277
+ // saveCard: customerOptedIn, // optional opt-in
273
278
  });
274
279
 
275
280
  setPaymentData({ clientSecret: paymentIntent.clientSecret, provider: paymentIntent.provider, checkoutId });
@@ -390,8 +395,10 @@ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; che
390
395
  }
391
396
  if (data?.type === 'brainerce:redirect' && typeof data.url === 'string') {
392
397
  // Top-level navigation (e.g. Bit). ALWAYS validate against an allowlist
393
- // before navigating \u2014 never trust the URL blindly.
394
- if (isTrustedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
398
+ // before navigating \u2014 never trust the URL blindly. The SDK ships with
399
+ // a maintained list of payment-provider hosts; prefer it over a local
400
+ // copy so 'npm update brainerce' picks up new providers automatically.
401
+ if (isAllowedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
395
402
  }
396
403
  if (data?.type === 'brainerce:payment-complete') {
397
404
  // Payment done \u2014 redirect to confirmation page which verifies server-side
@@ -431,15 +438,10 @@ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; che
431
438
  );
432
439
  }
433
440
 
434
- // Allowlist of origins you trust for top-level payment redirects.
435
- function isTrustedPaymentUrl(url: string): boolean {
436
- try {
437
- const u = new URL(url);
438
- if (u.protocol !== 'https:') return false;
439
- // Add your provider hostnames here. Example: Cardcom for Bit express-pay.
440
- return u.hostname === 'cardcom.solutions' || u.hostname.endsWith('.cardcom.solutions');
441
- } catch { return false; }
442
- }
441
+ // Allowlist check is provided by the SDK \u2014 covers Stripe, PayPal, Cardcom,
442
+ // Meshulam, Grow, CreditGuard, plus Brainerce-hosted embed shells. To extend
443
+ // for a self-hosted PSP, pass { extraHosts: ['my-psp.example.com'] }.
444
+ import { isAllowedPaymentUrl } from 'brainerce';
443
445
  \`\`\`
444
446
 
445
447
  ### PayPal Payment Form
@@ -727,6 +729,80 @@ Provider-specific install notes:
727
729
  - **Grow:** No SDK needed \u2014 JS SDK loaded via \`clientSdk.scriptUrl\`. Supports credit cards, Bit, Apple Pay, Google Pay.
728
730
  - **Cardcom:** No SDK needed \u2014 rendering driven by \`renderType: 'iframe'\` + the inline/modal branch above. Supports credit cards, Bit (when terminal provisions it), installments, 3D Secure.`;
729
731
  }
732
+ function getSavedPaymentMethodsSection() {
733
+ return `## Saved Payment Methods (vaulted cards)
734
+
735
+ When a logged-in customer ticks "save my card for next time", the platform vaults the
736
+ card with the underlying provider and stores a reference. Vaulted cards can later be
737
+ charged off-session \u2014 typically via subscription / one-click checkout features built
738
+ on top of this foundation.
739
+
740
+ ### Opt-in at checkout
741
+
742
+ Pass \`saveCard: true\` to \`createPaymentIntent\` when the customer chose to save.
743
+ **Only honored for logged-in customers** \u2014 anonymous (guest) checkouts silently
744
+ skip vaulting because there's no Customer record to attach the resulting saved
745
+ method to.
746
+
747
+ \`\`\`typescript
748
+ const intent = await client.createPaymentIntent(checkoutId, {
749
+ successUrl,
750
+ cancelUrl,
751
+ saveCard: true, // optional \u2014 only when customer ticked the box AND is logged in
752
+ });
753
+ \`\`\`
754
+
755
+ After a successful charge, the saved card appears in the customer's profile.
756
+
757
+ ### Listing saved cards (storefront / customer account page)
758
+
759
+ Show the customer their saved cards on a "Manage Payment Methods" page in their
760
+ account. The platform returns display-only metadata \u2014 last4, brand, expiry,
761
+ default flag, status. The underlying provider token is encrypted at rest and
762
+ NEVER returned through the SDK.
763
+
764
+ \`\`\`typescript
765
+ const methods = await client.listSavedPaymentMethods(storeId, customerId);
766
+
767
+ methods.forEach((m) => {
768
+ console.log(\`\${m.brand} ending in \${m.last4} (expires \${m.expMonth}/\${m.expYear})\`);
769
+ if (m.isDefault) console.log(' \u21B3 default');
770
+ if (m.status === 'expired') console.log(' \u21B3 expired \u2014 please add a new card');
771
+ });
772
+ \`\`\`
773
+
774
+ ### Removing a saved card
775
+
776
+ \`\`\`typescript
777
+ await client.removeSavedPaymentMethod(storeId, customerId, methodId);
778
+ \`\`\`
779
+
780
+ Hard-deletes the row from the platform DB. The provider may still hold the
781
+ underlying token internally \u2014 we don't issue a delete-at-provider call because
782
+ not every provider supports it. From the platform's perspective the token is
783
+ gone; subsequent charges fail.
784
+
785
+ ### Provider support matrix
786
+
787
+ | Provider | Save card on first charge | Charge saved card off-session |
788
+ |---|---|---|
789
+ | Cardcom | \u2705 (Operation: ChargeAndCreateToken) | \u2705 |
790
+ | PayPal | \u2705 (Vault API: store_in_vault) | \u2705 |
791
+ | Stripe | (separate workstream \u2014 Brainerce doesn't ship a Stripe payment app yet) | \u2014 |
792
+ | Grow | \u274C \u2014 returns 501 \`token_storage_unavailable\` | \u274C |
793
+
794
+ When a provider doesn't support tokenization, the platform surfaces a 409 with
795
+ \`code: 'token_storage_unavailable'\`. Storefronts should hide the "save card"
796
+ checkbox when the active provider doesn't support it.
797
+
798
+ ### Charging off-session
799
+
800
+ Charging a saved card from the storefront is **not** part of this foundation \u2014
801
+ that's the job of the Subscription / one-click checkout features built on top.
802
+ For now, charges run through the standard \`createPaymentIntent\` flow. The
803
+ saved-method foundation makes those features possible without further platform
804
+ changes.`;
805
+ }
730
806
  function getProductsSection(_currency) {
731
807
  return `## Products & Variants
732
808
 
@@ -747,6 +823,18 @@ const filtered = await client.getProducts({
747
823
  categories: ['cat_123'], minPrice: 10, maxPrice: 100,
748
824
  sortBy: 'price', sortOrder: 'asc',
749
825
  });
826
+
827
+ // Filter by custom fields (metafields). Only fields the merchant marked
828
+ // \`filterable: true\` are honored; supported types are SELECT, MULTI_SELECT,
829
+ // BOOLEAN. AND across keys, OR within a key.
830
+ const byCustom = await client.getProducts({
831
+ metafields: { color: ['red', 'blue'], in_stock: ['true'] },
832
+ });
833
+
834
+ // Discover which custom fields are filterable for the current store:
835
+ const { definitions } = await client.getPublicMetafieldDefinitions();
836
+ const facets = definitions.filter(d => d.filterable);
837
+ // Render a checkbox group per SELECT/MULTI_SELECT, a switch per BOOLEAN.
750
838
  \`\`\`
751
839
 
752
840
  ### i18n \u2014 translated fields come back on every request
@@ -1116,22 +1204,24 @@ const { upgrades } = await client.getCartUpgrades(cartId);
1116
1204
  // Show inline banner per cart item if upgrade exists
1117
1205
  \`\`\`
1118
1206
 
1119
- **Bundle offers** (discounted complementary products configured by the store owner):
1207
+ **Bundle offers** (N-product bundles configured by the store owner \u2014 productIds[0] triggers the offer, productIds[1..] are offered together at a discount):
1120
1208
  \`\`\`typescript
1121
1209
  import type { CartBundlesResponse } from 'brainerce';
1122
1210
  const { bundles } = await client.getCartBundles(cartId);
1123
- // bundles[].bundleProduct \u2014 the product to offer
1124
- // bundles[].originalPrice / bundles[].discountedPrice \u2014 prices
1211
+ // bundles[].triggerProductId \u2014 already in cart, activates the offer
1212
+ // bundles[].productIds \u2014 full bundle composition (length >= 2)
1213
+ // bundles[].offeredProducts[] \u2014 products customer hasn't added yet
1214
+ // each with originalPrice + discountedPrice
1215
+ // bundles[].totalOriginalPrice / totalDiscountedPrice \u2014 sums across offeredProducts
1125
1216
  // bundles[].discountType ('PERCENTAGE' | 'FIXED_AMOUNT') + discountValue
1126
- // bundles[].requiresVariantSelection \u2014 true if customer must pick a variant
1127
- // bundles[].lockedVariant \u2014 set if admin pre-selected a specific variant
1128
- // bundles[].bundleProduct.variants \u2014 available variants (only when requiresVariantSelection)
1129
1217
 
1130
- // Add a bundle to cart (applies the discount automatically):
1218
+ // Accept a bundle (adds every offered product not yet in cart at the discount):
1131
1219
  await client.addBundleToCart(cartId, bundleOfferId);
1132
- // For products with variants \u2014 pass the selected variantId:
1133
- await client.addBundleToCart(cartId, bundleOfferId, selectedVariantId);
1134
- // Remove a bundle from cart:
1220
+ // If some offered products have variants, pass per-product variant selections:
1221
+ await client.addBundleToCart(cartId, bundleOfferId, {
1222
+ [variantProductId]: selectedVariantId,
1223
+ });
1224
+ // Remove an accepted bundle (removes every cart item linked to that bundle):
1135
1225
  await client.removeBundleFromCart(cartId, bundleOfferId);
1136
1226
  // Detect already-added bundles: check cart.items for metadata?.isBundleItem === true
1137
1227
  \`\`\`
@@ -1187,11 +1277,12 @@ Always check the flag before rendering: \`if (storeInfo?.upsell?.featureName !==
1187
1277
  | CartRecommendationSection | products/ | Cross-sell grid at bottom of cart page |
1188
1278
  | FreeShippingBar | cart/ | Progress bar toward free shipping threshold |
1189
1279
  | CartUpgradeBanner | cart/ | Inline "Upgrade to X for +$Y" per cart item |
1190
- | CartBundleOfferCard | cart/ | Discounted bundle offer card in cart (with inline variant selector for variable products) |
1280
+ | CartBundleOfferCard | cart/ | N-product bundle offer card in cart \u2014 lists every offered product with its discounted price and an "Add bundle" button |
1191
1281
  | OrderBumpCard | checkout/ | Checkbox add-on card in checkout sidebar (with inline variant selector for variable products) |
1192
1282
 
1193
1283
  ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`, \`variants?\` (when variant selection needed).
1194
- OrderBump/CartBundleOffer: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).`;
1284
+ OrderBump: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).
1285
+ CartBundleOffer: \`productIds\` (length \\>= 2; index 0 = trigger), \`offeredProducts\` (per-product discounted prices), \`totalOriginalPrice\` / \`totalDiscountedPrice\`. Variant selection for offered products is passed per-call via \`variantSelections\` on \`addBundleToCart\`.`;
1195
1286
  }
1196
1287
  function getProductCustomizationFieldsSection() {
1197
1288
  return `## Product Customization Fields (buyer input on product page)
@@ -1297,6 +1388,157 @@ When the order is created, each line's customization values are snapshotted onto
1297
1388
  - Using a raw external URL (not from \`/customization-upload\`) for \`IMAGE\` / \`GALLERY\` \u2192 HTTP 400
1298
1389
  - Assuming \`enumValues\` is present for all types \u2014 only \`SELECT\` / \`MULTI_SELECT\` require it`;
1299
1390
  }
1391
+ function getModifierGroupsSection() {
1392
+ return `## Modifier Groups (toppings, sauce, build-your-own)
1393
+
1394
+ Modifier groups are merchant-defined option blocks attached to a product \u2014 the canonical example is "Toppings" on a pizza, where the customer picks 0\u20138 options with the first 3 free. They differ from \`customizationFields\` (which are arbitrary buyer input \u2014 text, photos, color picks): modifier groups are a **structured selection with priced options**, validated and priced server-side.
1395
+
1396
+ If \`product.modifierGroups\` is empty or missing, render the product page normally and skip everything below.
1397
+
1398
+ ### Wire shape on \`GET /products/:id\`
1399
+
1400
+ \`\`\`typescript
1401
+ import type { Product, ModifierGroup, Modifier, ModifierSelection } from 'brainerce';
1402
+
1403
+ const product = await client.getProductBySlug(slug);
1404
+ const groups: ModifierGroup[] = product.modifierGroups ?? [];
1405
+
1406
+ // Each group looks like:
1407
+ // {
1408
+ // id: 'mg_toppings',
1409
+ // attachmentId: 'pmg_01', // ProductModifierGroup row \u2014 used for attach updates
1410
+ // name: 'Toppings', // customer-facing
1411
+ // internalName?: string, // ADMIN ONLY \u2014 never present in storefront responses
1412
+ // selectionType: 'SINGLE' | 'MULTIPLE',
1413
+ // min: number, // effective (overrides already applied)
1414
+ // max: number | null, // null = unlimited; **0 = group hidden for this variant**
1415
+ // freeQuantity: number, // first N picks at no extra cost
1416
+ // required: boolean,
1417
+ // freeAllocationPolicy: 'EXPENSIVE_FREE' | 'CHEAPEST_FREE' | 'SELECTION_ORDER',
1418
+ // defaultModifierIds: string[], // pre-checked on first render
1419
+ // modifiers: Array<{
1420
+ // id: 'm_olive',
1421
+ // name: 'Olives',
1422
+ // priceDelta: '5.00', // DECIMAL STRING \u2014 never JSON Number
1423
+ // position: 0,
1424
+ // isDefault: false, // pre-check this option even if not in defaultModifierIds
1425
+ // available: true, // false \u2192 "sold out", disabled in UI
1426
+ // referencedProductId?: string, // nested-combo target (depth \u2264 3)
1427
+ // }>,
1428
+ // }
1429
+ \`\`\`
1430
+
1431
+ **Money fields are strings.** \`priceDelta\` is \`"5.00"\` (or \`"-2.00"\` for downsell modifiers \u2014 see below). Use \`parseFloat()\` for display arithmetic; never compute the line total client-side \u2014 the server runs the free-allocation policy and returns the final \`unitPrice\` snapshot on the cart line.
1432
+
1433
+ ### Render: SINGLE \u2192 radio, MULTIPLE \u2192 checkbox
1434
+
1435
+ Walk \`groups\` and pick the input type by \`selectionType\`. Sort modifiers by \`position\`.
1436
+
1437
+ \`\`\`typescript
1438
+ for (const group of groups) {
1439
+ if (group.max === 0) continue; // disabled-for-variant convention \u2014 skip entirely
1440
+ const inputType = group.selectionType === 'SINGLE' ? 'radio' : 'checkbox';
1441
+ const sorted = [...group.modifiers].sort((a, b) => a.position - b.position);
1442
+ // Render fieldset \u2192 legend with name + " *" if required \u2192 list of sorted options.
1443
+ // Each option: input(type=inputType, name=group.id, value=modifier.id),
1444
+ // disabled when modifier.available === false, with a "Sold out" badge.
1445
+ }
1446
+ \`\`\`
1447
+
1448
+ When \`group.freeQuantity > 0\`, show a running counter so the customer understands the rule:
1449
+ \`\`\`
1450
+ {Math.min(picks.length, group.freeQuantity)} of {group.freeQuantity} free
1451
+ \`\`\`
1452
+
1453
+ Note: individual modifiers may have \`excludeFromFree: true\` \u2014 these are "premium" options that always charge their \`priceDelta\` and are never consumed by a free slot. Render them with a label like "premium" so customers know they are not eligible for the free allocation.
1454
+
1455
+ ### Initial state
1456
+
1457
+ Honor \`defaultModifierIds\` first (per-attach defaults set by the merchant for this product/variant), falling back to \`modifier.isDefault\` flags when the group has no per-attach defaults. Filter sold-out modifiers out of the initial picks. For SINGLE groups, cap to one.
1458
+
1459
+ ### Pass selections on add-to-cart
1460
+
1461
+ \`\`\`typescript
1462
+ const selections: ModifierSelection[] = [
1463
+ { modifierGroupId: 'mg_bread', modifierIds: ['m_thick'] },
1464
+ { modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_mushroom', 'm_bacon', 'm_egg'] },
1465
+ ];
1466
+
1467
+ await client.smartAddToCart({
1468
+ productId: product.id,
1469
+ variantId: selectedVariant?.id,
1470
+ quantity: 1,
1471
+ selections,
1472
+ });
1473
+ \`\`\`
1474
+
1475
+ \`modifierIds\` is in **click-order** \u2014 the server uses this for the \`SELECTION_ORDER\` free-allocation policy. The cart response surfaces a per-line snapshot:
1476
+
1477
+ \`\`\`typescript
1478
+ // cart.items[i].modifiers \u2014 same shape as ModifierSelection but with snapshot data
1479
+ [
1480
+ { modifierId: 'm_olive', name: 'Olives', priceDelta: '5.00', freeApplied: true },
1481
+ { modifierId: 'm_mushroom', name: 'Mushrooms', priceDelta: '5.00', freeApplied: true },
1482
+ { modifierId: 'm_bacon', name: 'Bacon', priceDelta: '7.00', freeApplied: true },
1483
+ { modifierId: 'm_egg', name: 'Egg', priceDelta: '6.00', freeApplied: false },
1484
+ ]
1485
+ // + cart.items[i].modifiersTotal \u2014 sum of paid (non-free) deltas as a decimal string
1486
+ \`\`\`
1487
+
1488
+ \`freeApplied: true\` means the modifier consumed a free slot \u2014 render with a "free" badge in the cart UI.
1489
+
1490
+ ### Editing selections after add-to-cart (idempotent)
1491
+
1492
+ \`PATCH /cart/items/:id\` with a fresh \`selections\` array **replaces** the line's modifiers atomically \u2014 the server deletes old \`CartItemModifier\` rows and recreates them inside the same transaction. Omit \`selections\` from the body to leave them unchanged (e.g., quantity-only update).
1493
+
1494
+ \`\`\`typescript
1495
+ await client.updateCartItem(cart.id, itemId, {
1496
+ quantity: 1,
1497
+ selections: [{ modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_mushroom'] }],
1498
+ });
1499
+ \`\`\`
1500
+
1501
+ ### Validation envelope
1502
+
1503
+ When the payload is invalid the server returns HTTP 400 with a structured envelope. The SDK exposes it on \`BrainerceError.details\`:
1504
+
1505
+ \`\`\`typescript
1506
+ try {
1507
+ await client.smartAddToCart({ productId, quantity: 1, selections });
1508
+ } catch (err) {
1509
+ const e = err as { statusCode?: number; details?: { code?: string; errors?: Array<{ code: string; message: string; modifierGroupId?: string; modifierId?: string }> } };
1510
+ if (e.statusCode === 400 && e.details?.code === 'MODIFIER_VALIDATION_FAILED') {
1511
+ for (const issue of e.details.errors ?? []) {
1512
+ // issue.code is one of: REQUIRED_GROUP_MISSING | MIN_SELECTIONS_NOT_MET |
1513
+ // MAX_SELECTIONS_EXCEEDED | SINGLE_GROUP_MULTIPLE_PICKS | UNKNOWN_MODIFIER |
1514
+ // UNKNOWN_GROUP | MODIFIER_DISABLED_FOR_VARIANT | MODIFIER_NOT_AVAILABLE |
1515
+ // NESTED_DEPTH_EXCEEDED | NESTED_REQUIRES_PRODUCT_REF | INVALID_PRICE_DELTA |
1516
+ // MODIFIER_PRICE_FLOOR_VIOLATED
1517
+ console.error(issue.message);
1518
+ }
1519
+ }
1520
+ }
1521
+ \`\`\`
1522
+
1523
+ Special case: \`MODIFIER_PRICE_FLOOR_VIOLATED\` fires when downsell modifiers (negative \`priceDelta\`) would push \`unitPrice\` below \`0\`. The server reports a generic message \u2014 internals never leak \u2014 so show a friendly "Cannot apply more discounts on this item" and let the customer remove a downsell.
1524
+
1525
+ ### Disable-for-variant convention (PRD \xA77.2.2)
1526
+
1527
+ The merchant can hide a group entirely for one variant by setting \`maxOverride: 0\` on a per-variant attachment. The product response then returns the group with \`max: 0\` for that variant. **Skip it entirely** \u2014 do not render, do not include in selections. The validator silently skips groups with \`effectiveMax === 0\` on the cart side.
1528
+
1529
+ ### Common mistakes
1530
+
1531
+ - Treating \`priceDelta\` as a number \u2192 arithmetic precision bugs. Always strings; use \`parseFloat\` only at display time.
1532
+ - Computing the line total client-side \u2192 diverges from the server's free-allocation. Render the server's \`unitPrice\` / \`modifiers[]\` / \`modifiersTotal\` instead.
1533
+ - Rendering a group with \`max: 0\` \u2192 it's the variant-disable signal; treat as absent.
1534
+ - Showing \`internalName\` on a public storefront \u2192 it is **never** present in storefront responses; if your code is reading it, you're using an admin endpoint by accident.
1535
+ - Building \`selections\` keyed by \`modifier.name\` \u2192 must be \`modifierGroupId\` + \`modifierIds[]\` (the IDs, not names).
1536
+ - Sending \`modifiers\` instead of \`selections\` on add-to-cart \u2192 \`modifiers\` is the response field; the request key is \`selections\`.
1537
+
1538
+ ### Restaurant features (advanced)
1539
+
1540
+ Allergens (informational chips), scheduled availability windows, nested combos (depth \u2264 3 via \`nestedByModifierId\`), and downsell modifiers (negative \`priceDelta\`) are all built on the same data model. See INTEGRATION-OPTIONAL.md "Restaurant / build-your-own products" for those flows.`;
1541
+ }
1300
1542
  function getInventorySection() {
1301
1543
  return `## Inventory, Stock Display & Reservation Countdown
1302
1544
 
@@ -1862,7 +2104,40 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
1862
2104
  // Email: getEmailTemplates(), createEmailTemplate()
1863
2105
  // Conflicts: getSyncConflicts(), resolveSyncConflict()
1864
2106
  // OAuth: getOAuthProviders(), configureOAuthProvider()
1865
- \`\`\``;
2107
+ \`\`\`
2108
+
2109
+ ### Per-Channel Publishing
2110
+
2111
+ Categories, tags, brands, and metafield definitions are gated to specific
2112
+ vibe-coded sites \u2014 same control already exposed for products and coupons.
2113
+ **Explicit opt-in:** an entity is visible to a vibe-coded site only if it
2114
+ has been explicitly published to that connection. Entities with no publish
2115
+ rows are invisible to every site (the merchant must publish them via the
2116
+ dashboard or the admin SDK).
2117
+
2118
+ \`\`\`typescript
2119
+ // Publish to a specific vibe-coded site (admin mode):
2120
+ await admin.publishCategoryToVibeCodedSite('cat_id', 'conn_id');
2121
+ await admin.publishTagToVibeCodedSite('tag_id', 'conn_id');
2122
+ await admin.publishBrandToVibeCodedSite('brand_id', 'conn_id');
2123
+ await admin.publishMetafieldDefinitionToVibeCodedSite('def_id', 'conn_id');
2124
+
2125
+ // Unpublish (entity stays visible to other sites unless they also have publishes):
2126
+ await admin.unpublishCategoryFromVibeCodedSite('cat_id', 'conn_id');
2127
+ // ...same for tag/brand/metafield definition.
2128
+
2129
+ // Read which sites an entity is published to via list/get responses:
2130
+ const cat = await admin.getCategory('cat_id');
2131
+ cat.vibeCodedPublishes; // [{ connection: { id, name, connectionId } }, ...]
2132
+ \`\`\`
2133
+
2134
+ Cross-account isolation is enforced server-side: a publish call only
2135
+ succeeds when entity and connection belong to the same account. Cross-account
2136
+ calls fail with \`404 Not Found\`.
2137
+
2138
+ The vibe-coded read endpoints (used by storefront SDK calls in \`connectionId\`
2139
+ mode) automatically filter by these junction tables, so storefronts never see
2140
+ entities that weren't published to their site.`;
1866
2141
  }
1867
2142
  function getContactInquiriesSection() {
1868
2143
  return `## Contact Inquiries & Forms (optional)
@@ -1937,7 +2212,7 @@ const form = await brainerce.contactForms.get('main', 'en');
1937
2212
  // \u2192 {
1938
2213
  // id, key, name, description?, submitButton, successMessage,
1939
2214
  // fields: [{ key, type, label, placeholder?, helpText?, isRequired,
1940
- // enumValues?, validation?, defaultValue? }, ...]
2215
+ // enumValues?, validation?, defaultValue?, width? }, ...]
1941
2216
  // }
1942
2217
 
1943
2218
  // Submit a keyed payload. Unknown keys are stripped, required fields are
@@ -1963,6 +2238,20 @@ stripped server-side.
1963
2238
  Render every field type the merchant can pick. Keep this as a \`<DynamicField>\`
1964
2239
  component so the form is fully driven by \`schema.fields\`.
1965
2240
 
2241
+ **Layout.** Each field carries an optional \`width\` hint:
2242
+
2243
+ | \`field.width\` | Meaning | Grid style (6-column grid) |
2244
+ | ------------- | ------- | -------------------------- |
2245
+ | \`'FULL'\` (default) | Full row | \`grid-column: span 6\` |
2246
+ | \`'HALF'\` | Half row | \`grid-column: span 3\` |
2247
+ | \`'THIRD'\` | One-third row | \`grid-column: span 2\` |
2248
+
2249
+ Stack fields to full width on small screens (< ~640 px).
2250
+
2251
+ **Required fields.** Show a red asterisk on required labels, validate
2252
+ **client-side** before calling \`createInquiry()\`, and show inline error
2253
+ messages. Do NOT rely only on the server returning 400.
2254
+
1966
2255
  \`\`\`tsx
1967
2256
  import type { ContactFormPublic, ContactFormPublicField } from 'brainerce';
1968
2257
 
@@ -1980,13 +2269,24 @@ function isEmpty(v: FieldValue): boolean {
1980
2269
  return v === false;
1981
2270
  }
1982
2271
 
2272
+ // Map width \u2192 CSS grid column span (6-column grid)
2273
+ function widthClass(w?: string): string {
2274
+ switch (w) {
2275
+ case 'HALF': return 'grid-col-half'; // grid-column: span 3; on sm+, full on mobile
2276
+ case 'THIRD': return 'grid-col-third'; // grid-column: span 2; on sm+, full on mobile
2277
+ default: return 'grid-col-full'; // grid-column: span 6
2278
+ }
2279
+ }
2280
+
1983
2281
  function DynamicField({
1984
2282
  field,
1985
2283
  value,
2284
+ error,
1986
2285
  onChange,
1987
2286
  }: {
1988
2287
  field: ContactFormPublicField;
1989
2288
  value: FieldValue;
2289
+ error?: string;
1990
2290
  onChange: (v: FieldValue) => void;
1991
2291
  }) {
1992
2292
  const id = \`contact-\${field.key}\`;
@@ -2001,37 +2301,40 @@ function DynamicField({
2001
2301
  </label>
2002
2302
  );
2003
2303
  const help = field.helpText ? <p className="mt-1 text-xs opacity-70">{field.helpText}</p> : null;
2304
+ const errorEl = error ? <p className="mt-1 text-xs text-red-500">{error}</p> : null;
2004
2305
 
2306
+ // Outer div uses widthClass to control grid-column span
2005
2307
  switch (field.type) {
2006
2308
  case 'TEXTAREA':
2007
- return (<div>{label}<textarea id={id} required={field.isRequired} maxLength={maxLength} minLength={minLength} rows={6} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2309
+ return (<div className={widthClass(field.width)}>{label}<textarea id={id} required={field.isRequired} maxLength={maxLength} minLength={minLength} rows={6} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2008
2310
  case 'EMAIL':
2009
- return (<div>{label}<input id={id} type="email" required={field.isRequired} autoComplete="email" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2311
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="email" required={field.isRequired} autoComplete="email" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2010
2312
  case 'PHONE':
2011
- return (<div>{label}<input id={id} type="tel" required={field.isRequired} autoComplete="tel" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2313
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="tel" required={field.isRequired} autoComplete="tel" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2012
2314
  case 'URL':
2013
- return (<div>{label}<input id={id} type="url" required={field.isRequired} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2315
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="url" required={field.isRequired} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2014
2316
  case 'NUMBER':
2015
- return (<div>{label}<input id={id} type="number" required={field.isRequired} min={min} max={max} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2317
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="number" required={field.isRequired} min={min} max={max} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2016
2318
  case 'DATE':
2017
- return (<div>{label}<input id={id} type="date" required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2319
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="date" required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2018
2320
  case 'SELECT':
2019
- return (<div>{label}<select id={id} required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)}><option value="">\u2014</option>{field.enumValues?.map((o) => (<option key={o.value} value={o.value}>{o.label}</option>))}</select>{help}</div>);
2321
+ return (<div className={widthClass(field.width)}>{label}<select id={id} required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)}><option value="">\u2014</option>{field.enumValues?.map((o) => (<option key={o.value} value={o.value}>{o.label}</option>))}</select>{help}{errorEl}</div>);
2020
2322
  case 'MULTI_SELECT': {
2021
2323
  const arr = Array.isArray(value) ? value : [];
2022
- return (<div>{label}<div>{field.enumValues?.map((o) => { const checked = arr.includes(o.value); return (<label key={o.value}><input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked ? [...arr, o.value] : arr.filter((v) => v !== o.value))} /><span>{o.label}</span></label>); })}</div>{help}</div>);
2324
+ return (<div className={widthClass(field.width)}>{label}<div>{field.enumValues?.map((o) => { const checked = arr.includes(o.value); return (<label key={o.value}><input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked ? [...arr, o.value] : arr.filter((v) => v !== o.value))} /><span>{o.label}</span></label>); })}</div>{help}{errorEl}</div>);
2023
2325
  }
2024
2326
  case 'CHECKBOX':
2025
- return (<div><label htmlFor={id}><input id={id} type="checkbox" required={field.isRequired} checked={value === true} onChange={(e) => onChange(e.target.checked)} /><span>{field.label}</span></label>{help}</div>);
2327
+ return (<div className={widthClass(field.width)}><label htmlFor={id}><input id={id} type="checkbox" required={field.isRequired} checked={value === true} onChange={(e) => onChange(e.target.checked)} /><span>{field.label}</span></label>{help}{errorEl}</div>);
2026
2328
  case 'TEXT':
2027
2329
  default:
2028
- return (<div>{label}<input id={id} type="text" required={field.isRequired} maxLength={maxLength} minLength={minLength} pattern={pattern} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2330
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="text" required={field.isRequired} maxLength={maxLength} minLength={minLength} pattern={pattern} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2029
2331
  }
2030
2332
  }
2031
2333
 
2032
2334
  export function ContactPage() {
2033
2335
  const [schema, setSchema] = useState<ContactFormPublic | null>(null);
2034
2336
  const [values, setValues] = useState<Record<string, FieldValue>>({});
2337
+ const [errors, setErrors] = useState<Record<string, string>>({});
2035
2338
  const [honeypot, setHoneypot] = useState('');
2036
2339
  const [sent, setSent] = useState(false);
2037
2340
  const [loading, setLoading] = useState(false);
@@ -2055,6 +2358,19 @@ export function ContactPage() {
2055
2358
  if (loading) return;
2056
2359
  if (honeypot.trim().length > 0) { setSent(true); return; } // bot \u2192 silent success
2057
2360
 
2361
+ // \u2500\u2500 Client-side required-field validation \u2500\u2500
2362
+ const newErrors: Record<string, string> = {};
2363
+ for (const f of schema.fields) {
2364
+ if (f.isRequired && isEmpty(values[f.key] ?? defaultValueFor(f))) {
2365
+ newErrors[f.key] = \`\${f.label} is required\`; // or pull from your i18n system
2366
+ }
2367
+ }
2368
+ if (Object.keys(newErrors).length > 0) {
2369
+ setErrors(newErrors);
2370
+ return; // block submission
2371
+ }
2372
+ setErrors({});
2373
+
2058
2374
  setLoading(true);
2059
2375
  try {
2060
2376
  const payload: Record<string, unknown> = {};
@@ -2087,11 +2403,15 @@ export function ContactPage() {
2087
2403
  value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
2088
2404
  </div>
2089
2405
 
2090
- {schema.fields.map((field) => (
2091
- <DynamicField key={field.key} field={field}
2092
- value={values[field.key] ?? defaultValueFor(field)}
2093
- onChange={(v) => setValues((p) => ({ ...p, [field.key]: v }))} />
2094
- ))}
2406
+ {/* CSS grid \u2014 6 columns on sm+, 1 column on mobile */}
2407
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '1rem' }}>
2408
+ {schema.fields.map((field) => (
2409
+ <DynamicField key={field.key} field={field}
2410
+ value={values[field.key] ?? defaultValueFor(field)}
2411
+ error={errors[field.key]}
2412
+ onChange={(v) => setValues((p) => ({ ...p, [field.key]: v }))} />
2413
+ ))}
2414
+ </div>
2095
2415
 
2096
2416
  <button type="submit" disabled={loading}>
2097
2417
  {loading ? '\u2026' : schema.submitButton}
@@ -2101,13 +2421,27 @@ export function ContactPage() {
2101
2421
  }
2102
2422
  \`\`\`
2103
2423
 
2424
+ CSS for the grid column helpers (or use the equivalent Tailwind / inline styles):
2425
+
2426
+ \`\`\`css
2427
+ .grid-col-full { grid-column: span 6; }
2428
+ .grid-col-half { grid-column: span 6; }
2429
+ .grid-col-third { grid-column: span 6; }
2430
+
2431
+ @media (min-width: 640px) {
2432
+ .grid-col-half { grid-column: span 3; }
2433
+ .grid-col-third { grid-column: span 2; }
2434
+ }
2435
+ \`\`\`
2436
+
2104
2437
  ### Rules
2105
2438
 
2106
2439
  - **Rate limit:** 3 submissions / 60s per IP \u2014 show a friendly "try again later" message on HTTP 429.
2107
2440
  - **Honeypot:** always render a hidden field named \`honeypot\` and **never send** it. Bots fill every input; the server rejects submissions carrying a non-empty \`honeypot\`.
2108
2441
  - **Built-in keys:** \`name\`, \`email\`, \`phone\`, \`subject\`, \`message\` always exist on the default form; the legacy \`createInquiry\` shape keeps working forever.
2109
2442
  - **Max values:** each field value is capped at 10 000 chars server-side. Validate client-side before submitting using \`field.validation.maxLength\`.
2110
- - **Required fields:** respect \`field.isRequired\`. The server validates too, but show \`required\` on the input for browser-level UX.
2443
+ - **Required fields:** respect \`field.isRequired\`. Show a red asterisk (\`*\`) next to the label. **Validate client-side before submission** \u2014 iterate over \`schema.fields\`, check \`isEmpty(values[f.key])\` for each required field, and block the submit with inline error messages. The server validates too, but the user should never see a raw 400 error.
2444
+ - **Width (layout):** respect \`field.width\`. Use a CSS grid with 6 columns: \`FULL\` = span 6 (default), \`HALF\` = span 3, \`THIRD\` = span 2. Stack to full width on small screens. If \`width\` is missing, treat as \`FULL\`.
2111
2445
  - **Validation:** when \`field.validation.pattern\` is present, pass it as the input's \`pattern\` attribute; the server also enforces it. Likewise \`minLength\`/\`maxLength\`/\`min\`/\`max\`.
2112
2446
  - **Enum values:** SELECT and MULTI_SELECT always return \`enumValues\` (non-empty array). Render from \`enumValues\`, never a hardcoded list.
2113
2447
  - **Visibility:** the server strips fields with \`isVisible=false\`, so \`schema.fields\` only contains things to render.
@@ -2139,6 +2473,8 @@ function getSectionByTopic(topic, connectionId, currency) {
2139
2473
  return getCheckoutCustomFieldsSection();
2140
2474
  case "payment":
2141
2475
  return getPaymentProvidersSection();
2476
+ case "saved-payment-methods":
2477
+ return getSavedPaymentMethodsSection();
2142
2478
  case "auth":
2143
2479
  return getCustomerAuthSection();
2144
2480
  case "order-confirmation":
@@ -2151,6 +2487,8 @@ function getSectionByTopic(topic, connectionId, currency) {
2151
2487
  return getRecommendationsSection();
2152
2488
  case "product-customization-fields":
2153
2489
  return getProductCustomizationFieldsSection();
2490
+ case "modifier-groups":
2491
+ return getModifierGroupsSection();
2154
2492
  case "tax":
2155
2493
  return getTaxDisplaySection(cur);
2156
2494
  case "i18n":
@@ -2231,6 +2569,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2231
2569
  "",
2232
2570
  "---",
2233
2571
  "",
2572
+ getModifierGroupsSection(),
2573
+ "",
2574
+ "---",
2575
+ "",
2234
2576
  getTaxDisplaySection(cur),
2235
2577
  "",
2236
2578
  "---",
@@ -2275,11 +2617,19 @@ var GET_SDK_DOCS_SCHEMA = {
2275
2617
  "inquiries",
2276
2618
  "all"
2277
2619
  ]).describe("The SDK documentation topic to retrieve"),
2278
- connectionId: import_zod.z.string().optional().describe("Vibe-coded connection ID (starts with vc_). Used to personalize setup code."),
2620
+ salesChannelId: import_zod.z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
2621
+ /** @deprecated alias of salesChannelId */
2622
+ connectionId: import_zod.z.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat"),
2279
2623
  currency: import_zod.z.string().optional().describe("Store currency code (e.g., USD, ILS, EUR). Used in price formatting examples.")
2280
2624
  };
2281
2625
  async function handleGetSdkDocs(args) {
2282
- const content = getSectionByTopic(args.topic, args.connectionId, args.currency);
2626
+ const id = args.salesChannelId ?? args.connectionId;
2627
+ if (!args.salesChannelId && args.connectionId) {
2628
+ console.warn(
2629
+ "get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
2630
+ );
2631
+ }
2632
+ const content = getSectionByTopic(args.topic, id, args.currency);
2283
2633
  return {
2284
2634
  content: [{ type: "text", text: content }]
2285
2635
  };
@@ -2318,7 +2668,7 @@ interface Product {
2318
2668
  attributeId: string;
2319
2669
  attributeOptionId: string;
2320
2670
  platform: string;
2321
- attribute: { id: string; name: string; displayType?: 'DEFAULT' | 'COLOR_SWATCH' | 'IMAGE_SWATCH' } | null;
2671
+ attribute: { id: string; name: string; displayType?: 'DEFAULT' | 'COLOR_SWATCH' | 'IMAGE_SWATCH' | 'MIXED_SWATCH' } | null;
2322
2672
  attributeOption: { id: string; name: string; value?: string | null; swatchColor?: string | null; swatchColor2?: string | null; swatchImageUrl?: string | null } | null;
2323
2673
  }>;
2324
2674
  createdAt: string;
@@ -2327,6 +2677,8 @@ interface Product {
2327
2677
 
2328
2678
  // Use getProductSwatches(product) to get grouped swatch data for storefront rendering.
2329
2679
  // Returns Array<{ attributeName, displayType, options: Array<{ name, swatchColor?, swatchColor2?, swatchImageUrl? }> }>
2680
+ // displayType rendering: COLOR_SWATCH \u2192 color circle (swatchColor/swatchColor2); IMAGE_SWATCH \u2192 image thumbnail (swatchImageUrl);
2681
+ // MIXED_SWATCH \u2192 per-option: render swatchImageUrl if set, else swatchColor if set, else text only.
2330
2682
 
2331
2683
  interface ProductImage {
2332
2684
  url: string;
@@ -2407,6 +2759,10 @@ interface ProductQueryParams {
2407
2759
  tags?: string | string[];
2408
2760
  minPrice?: number;
2409
2761
  maxPrice?: number;
2762
+ // Filter by custom-field (metafield) values. Keys = definition.key,
2763
+ // values = accepted values. Only definitions with filterable=true and
2764
+ // type SELECT/MULTI_SELECT/BOOLEAN are honored. AND across keys, OR within.
2765
+ metafields?: Record<string, string | string[]>;
2410
2766
  sortBy?: 'name' | 'price' | 'createdAt';
2411
2767
  sortOrder?: 'asc' | 'desc';
2412
2768
  }
@@ -2824,6 +3180,36 @@ interface PaymentStatus {
2824
3180
  error?: string;
2825
3181
  }
2826
3182
 
3183
+ // ---- Saved Payment Methods (vaulted cards) ----
3184
+ // Display-only summary of a customer's vaulted payment method. The
3185
+ // underlying provider token is encrypted at rest in the platform DB
3186
+ // and NEVER returned through the SDK.
3187
+ //
3188
+ // To opt into vaulting at checkout, pass saveCard: true to
3189
+ // createPaymentIntent (only honored for logged-in customers).
3190
+ //
3191
+ // To list / remove saved methods, see:
3192
+ // client.listSavedPaymentMethods(storeId, customerId)
3193
+ // client.removeSavedPaymentMethod(storeId, customerId, methodId)
3194
+
3195
+ interface SavedPaymentMethodSummary {
3196
+ id: string;
3197
+ customerId: string;
3198
+ appInstallationId: string;
3199
+ paymentMethod: string; // 'credit_card' | 'paypal' | 'bank_account'
3200
+ brand: string | null;
3201
+ last4: string | null;
3202
+ expMonth: number | null;
3203
+ expYear: number | null;
3204
+ isDefault: boolean;
3205
+ status: string; // 'active' | 'expired' | 'invalid'
3206
+ failureReason: string | null;
3207
+ lastUsedAt: string | null;
3208
+ expiresAt: string | null;
3209
+ createdAt: string;
3210
+ updatedAt: string;
3211
+ }
3212
+
2827
3213
  interface WaitForOrderResult {
2828
3214
  success: boolean;
2829
3215
  status: PaymentStatus; // Access: result.status.orderNumber
@@ -2923,15 +3309,32 @@ interface CartUpgradeSuggestion {
2923
3309
  priceDelta: string;
2924
3310
  deltaPercent: number;
2925
3311
  }
2926
- interface CartBundleOffer {
3312
+ interface CartBundleOfferOfferedProduct {
2927
3313
  id: string;
2928
- bundleProduct: ProductRecommendation;
3314
+ name: string;
3315
+ slug: string | null;
3316
+ basePrice: string;
3317
+ salePrice: string | null;
3318
+ images: Array<{ url: string }>;
3319
+ type: string;
2929
3320
  originalPrice: string;
2930
3321
  discountedPrice: string;
3322
+ }
3323
+ interface CartBundleOffer {
3324
+ id: string;
3325
+ name: string;
3326
+ description: string | null;
3327
+ // productIds[0] = trigger product (must be in cart for the bundle to surface);
3328
+ // productIds[1..] = offered together at the bundle discount.
3329
+ triggerProductId: string;
3330
+ productIds: string[];
3331
+ // offeredProducts = productIds[1..] minus those already in cart, each with
3332
+ // its own original/discounted price applied.
3333
+ offeredProducts: CartBundleOfferOfferedProduct[];
2931
3334
  discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
2932
- discountValue: number;
2933
- requiresVariantSelection: boolean;
2934
- lockedVariant?: { id: string; name?: string };
3335
+ discountValue: string;
3336
+ totalOriginalPrice: string;
3337
+ totalDiscountedPrice: string;
2935
3338
  }`;
2936
3339
  var INQUIRIES_TYPES = `// ---- Contact Inquiries & Forms ----
2937
3340
 
@@ -2986,6 +3389,7 @@ interface ContactFormPublicField {
2986
3389
  enumValues?: { value: string; label: string }[]; // present (non-empty) for SELECT / MULTI_SELECT
2987
3390
  validation?: ContactFormFieldValidation;
2988
3391
  defaultValue?: string;
3392
+ width?: 'FULL' | 'HALF' | 'THIRD'; // layout hint \u2014 FULL = full row, HALF = half row, THIRD = one-third row
2989
3393
  }
2990
3394
 
2991
3395
  interface ContactFormPublic {
@@ -3017,6 +3421,19 @@ interface ContactFormSummary {
3017
3421
  // MULTI_SELECT \u2192 multiple <input type="checkbox">, value is string[]
3018
3422
  // CHECKBOX \u2192 single <input type="checkbox">, value is boolean
3019
3423
  // ------------------------------------------------------------------
3424
+ //
3425
+ // Layout: render fields inside a CSS grid container.
3426
+ // width='FULL' (default) \u2192 span entire row
3427
+ // width='HALF' \u2192 span half the row (two HALF fields sit side-by-side)
3428
+ // width='THIRD' \u2192 span one-third of the row (three THIRD fields sit side-by-side)
3429
+ // Use a 6-column grid for clean divisibility:
3430
+ // FULL \u2192 col-span-6 | HALF \u2192 col-span-3 | THIRD \u2192 col-span-2
3431
+ // Stack to full width on small screens (< sm breakpoint).
3432
+ //
3433
+ // Required fields: show a red asterisk (*) next to the label, validate
3434
+ // client-side before submission, and display inline error messages for
3435
+ // any empty required field. Do NOT rely only on the server returning 400.
3436
+ // ------------------------------------------------------------------
3020
3437
 
3021
3438
  // SDK methods
3022
3439
  // await brainerce.createInquiry(input) \u2192 POST /stores/{storeId}/inquiries
@@ -3029,6 +3446,130 @@ interface ContactFormSummary {
3029
3446
  // - Always pass \`locale\` \u2014 inbox filters inquiries by language, and schema labels come back translated
3030
3447
  // - Render \`schema.name\` / \`description\` / \`submitButton\` / \`successMessage\` directly \u2014 do NOT hardcode copy
3031
3448
  // - Unknown field keys are stripped server-side \u2014 safe to send extras during dev`;
3449
+ var MODIFIER_GROUPS_TYPES = `// ---- Modifier Groups (Restaurant / Build-Your-Own) ----
3450
+ // Modifier groups are merchant-defined option blocks attached to a product
3451
+ // (toppings, sauce, bread type, \u2026). They differ from product.customizationFields:
3452
+ // modifier groups are STRUCTURED priced choices validated server-side, while
3453
+ // customizationFields are arbitrary buyer input (text/photo/color).
3454
+ //
3455
+ // Money fields are decimal STRINGS on the wire \u2014 "5.00", "-2.00" (downsell).
3456
+ // Never JSON Number. Use parseFloat() only at display time. Do not compute
3457
+ // the line total client-side; the server runs free-allocation and returns
3458
+ // cart.items[i].unitPrice + .modifiers[] + .modifiersTotal.
3459
+
3460
+ export type ModifierSelectionType = 'SINGLE' | 'MULTIPLE';
3461
+
3462
+ export type FreeAllocationPolicy = 'EXPENSIVE_FREE' | 'CHEAPEST_FREE' | 'SELECTION_ORDER';
3463
+
3464
+ export interface Modifier {
3465
+ id: string;
3466
+ name: string;
3467
+ description?: string;
3468
+ /** Decimal string. Negative values = downsell modifiers ("-2.00"). */
3469
+ priceDelta: string;
3470
+ sku?: string;
3471
+ image?: { url: string; thumbnailUrl?: string; alt?: string };
3472
+ position: number;
3473
+ /** Pre-checked on first render. */
3474
+ isDefault: boolean;
3475
+ /** false = sold out \u2014 disable in UI with a "Sold out" badge. */
3476
+ available: boolean;
3477
+ /** When true, never applied as a free selection \u2014 always charges priceDelta even when freeQuantity > 0 on the group. */
3478
+ excludeFromFree?: boolean;
3479
+ /** Nested combo: opens a sub-flow; depth \u2264 3 enforced server-side. */
3480
+ referencedProductId?: string;
3481
+ translations?: Record<string, { name?: string; description?: string }>;
3482
+ }
3483
+
3484
+ export interface ModifierGroup {
3485
+ id: string;
3486
+ /**
3487
+ * Set when fetched in a product context (the ProductModifierGroup row id).
3488
+ * Use this to update or detach the attachment without reattaching the group.
3489
+ */
3490
+ attachmentId?: string;
3491
+ /** Customer-facing canonical name. */
3492
+ name: string;
3493
+ /**
3494
+ * Admin-only disambiguator \u2014 NEVER present in storefront responses.
3495
+ * If your client code reads this, you're hitting an admin endpoint by mistake.
3496
+ */
3497
+ internalName?: string;
3498
+ description?: string;
3499
+ selectionType: ModifierSelectionType;
3500
+ /** Effective minimum after any per-attach / per-variant overrides. */
3501
+ min: number;
3502
+ /** Effective maximum; null = unlimited. **0 = group hidden for this variant** (PRD \xA77.2.2). */
3503
+ max?: number | null;
3504
+ freeQuantity: number;
3505
+ required: boolean;
3506
+ freeAllocationPolicy: FreeAllocationPolicy;
3507
+ modifiers: Modifier[];
3508
+ /** Effective default selections (after attachment-level overrides). */
3509
+ defaultModifierIds: string[];
3510
+ translations?: Record<string, { name?: string; description?: string }>;
3511
+ }
3512
+
3513
+ /** Customer-side selection payload \u2014 modifierIds in click-order. */
3514
+ export interface ModifierSelection {
3515
+ modifierGroupId: string;
3516
+ modifierIds: string[];
3517
+ }
3518
+
3519
+ /** Per-line modifier breakdown surfaced on cart.items[i] / order.items[i]. */
3520
+ export interface CartItemModifierLine {
3521
+ modifierId: string;
3522
+ /** Snapshot of the modifier's name at the time the line was added. */
3523
+ name: string;
3524
+ /** Decimal string snapshot of the priceDelta at the time the line was added. */
3525
+ priceDelta: string;
3526
+ /** True if this modifier consumed one of the group's free slots. */
3527
+ freeApplied: boolean;
3528
+ }
3529
+
3530
+ /**
3531
+ * Stable error codes returned in the structured 400 envelope when a cart
3532
+ * payload fails server-side validation. The SDK exposes the envelope on
3533
+ * BrainerceError.details \u2014 switch on details.code === 'MODIFIER_VALIDATION_FAILED'
3534
+ * first, then iterate details.errors[].
3535
+ */
3536
+ export type ModifierValidationCode =
3537
+ | 'REQUIRED_GROUP_MISSING'
3538
+ | 'MIN_SELECTIONS_NOT_MET'
3539
+ | 'MAX_SELECTIONS_EXCEEDED'
3540
+ | 'SINGLE_GROUP_MULTIPLE_PICKS'
3541
+ | 'UNKNOWN_MODIFIER'
3542
+ | 'UNKNOWN_GROUP'
3543
+ | 'MODIFIER_DISABLED_FOR_VARIANT'
3544
+ | 'MODIFIER_NOT_AVAILABLE'
3545
+ | 'NESTED_DEPTH_EXCEEDED'
3546
+ | 'NESTED_REQUIRES_PRODUCT_REF'
3547
+ | 'INVALID_PRICE_DELTA'
3548
+ | 'MODIFIER_PRICE_FLOOR_VIOLATED';
3549
+
3550
+ export interface ModifierValidationError {
3551
+ code: ModifierValidationCode;
3552
+ message: string;
3553
+ modifierGroupId?: string;
3554
+ modifierId?: string;
3555
+ }
3556
+
3557
+ // Cart DTOs gain optional selections + nestedByModifierId \u2014 see CART_TYPES above.
3558
+ // Add to cart with selections:
3559
+ //
3560
+ // await client.smartAddToCart({
3561
+ // productId,
3562
+ // variantId,
3563
+ // quantity: 1,
3564
+ // selections: [
3565
+ // { modifierGroupId: 'mg_bread', modifierIds: ['m_thick'] },
3566
+ // { modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_bacon'] },
3567
+ // ],
3568
+ // });
3569
+ //
3570
+ // The cart line then carries:
3571
+ // cart.items[i].modifiers \u2014 CartItemModifierLine[]
3572
+ // cart.items[i].modifiersTotal \u2014 decimal string of the paid (non-free) deltas`;
3032
3573
  var TYPES_BY_DOMAIN = {
3033
3574
  products: PRODUCTS_TYPES,
3034
3575
  cart: CART_TYPES,
@@ -3037,7 +3578,8 @@ var TYPES_BY_DOMAIN = {
3037
3578
  customers: CUSTOMERS_TYPES,
3038
3579
  payments: PAYMENTS_TYPES,
3039
3580
  helpers: HELPERS_TYPES,
3040
- inquiries: INQUIRIES_TYPES
3581
+ inquiries: INQUIRIES_TYPES,
3582
+ "modifier-groups": MODIFIER_GROUPS_TYPES
3041
3583
  };
3042
3584
  function getTypesByDomain(domain) {
3043
3585
  if (domain === "all") {
@@ -3103,7 +3645,12 @@ var GET_CODE_EXAMPLE_SCHEMA = {
3103
3645
  "reservation-countdown",
3104
3646
  "search-autocomplete-debounce",
3105
3647
  "i18n-set-locale",
3106
- "order-history-full"
3648
+ "order-history-full",
3649
+ "modifier-groups-render",
3650
+ "cart-add-with-selections",
3651
+ "modifier-validation-error-handling",
3652
+ "checkout-price-drift",
3653
+ "cart-item-modifier-display"
3107
3654
  ]).describe("The SDK operation to get a snippet for.")
3108
3655
  };
3109
3656
  var SNIPPETS = {
@@ -3111,7 +3658,10 @@ var SNIPPETS = {
3111
3658
  import { BrainerceClient } from 'brainerce';
3112
3659
 
3113
3660
  export const client = new BrainerceClient({
3114
- connectionId: process.env.BRAINERCE_CONNECTION_ID!, // vc_*
3661
+ // Read either env var name (the new one is preferred; the old one is a soft
3662
+ // alias kept for backwards compatibility \u2014 both are accepted by the SDK).
3663
+ salesChannelId:
3664
+ process.env.BRAINERCE_SALES_CHANNEL_ID! ?? process.env.BRAINERCE_CONNECTION_ID!, // vc_*
3115
3665
  });
3116
3666
 
3117
3667
  // If the store has i18n enabled, set the locale at app start based on
@@ -3531,7 +4081,418 @@ for (const order of orders) {
3531
4081
 
3532
4082
  // All sections above are conditional. Absent data = section not rendered \u2014
3533
4083
  // never show empty placeholders. The create-brainerce-store template's
3534
- // src/components/account/order-history.tsx is the reference implementation.`
4084
+ // src/components/account/order-history.tsx is the reference implementation.`,
4085
+ "modifier-groups-render": `// Render modifier groups on the product detail page (toppings / sauce /
4086
+ // build-your-own). The data lives on product.modifierGroups \u2014 only present
4087
+ // for restaurant / customizable products.
4088
+ import { useState } from 'react';
4089
+ import type { ModifierGroup, Product } from 'brainerce';
4090
+
4091
+ function ModifierGroups({ product }: { product: Product }) {
4092
+ const groups: ModifierGroup[] = product.modifierGroups ?? [];
4093
+ if (groups.length === 0) return null; // not a customizable product
4094
+
4095
+ // Local state: selected modifier IDs per group, in click-order.
4096
+ const [selections, setSelections] = useState<Record<string, string[]>>(() =>
4097
+ buildInitialSelections(groups)
4098
+ );
4099
+
4100
+ return (
4101
+ <>
4102
+ {groups.map((group) => {
4103
+ // PRD \xA77.2.2: max === 0 means "hidden for this variant" \u2014 skip entirely.
4104
+ if (group.max === 0) return null;
4105
+
4106
+ const isSingle = group.selectionType === 'SINGLE';
4107
+ const inputType = isSingle ? 'radio' : 'checkbox';
4108
+ const sorted = [...group.modifiers].sort((a, b) => a.position - b.position);
4109
+ const picks = selections[group.id] ?? [];
4110
+ const usedFree = Math.min(picks.length, group.freeQuantity);
4111
+
4112
+ const toggle = (modifierId: string, checked: boolean) => {
4113
+ setSelections((prev) => {
4114
+ const cur = prev[group.id] ?? [];
4115
+ if (isSingle) return { ...prev, [group.id]: checked ? [modifierId] : [] };
4116
+ if (checked) {
4117
+ if (group.max != null && cur.length >= group.max) return prev; // at cap
4118
+ return { ...prev, [group.id]: [...cur, modifierId] };
4119
+ }
4120
+ return { ...prev, [group.id]: cur.filter((id) => id !== modifierId) };
4121
+ });
4122
+ };
4123
+
4124
+ return (
4125
+ <fieldset key={group.id}>
4126
+ <legend>
4127
+ {group.name}{group.required && ' *'}
4128
+ </legend>
4129
+ {group.freeQuantity > 0 && (
4130
+ <p>{usedFree} of {group.freeQuantity} free</p>
4131
+ )}
4132
+ {sorted.map((m) => (
4133
+ <label key={m.id}>
4134
+ <input
4135
+ type={inputType}
4136
+ name={\`mg-\${group.id}\`}
4137
+ value={m.id}
4138
+ checked={picks.includes(m.id)}
4139
+ disabled={!m.available}
4140
+ onChange={(e) => toggle(m.id, e.target.checked)}
4141
+ />
4142
+ {m.name}
4143
+ {parseFloat(m.priceDelta) !== 0 && (
4144
+ <span> {parseFloat(m.priceDelta) > 0 ? '+' : ''}{m.priceDelta}</span>
4145
+ )}
4146
+ {!m.available && <span> (Sold out)</span>}
4147
+ </label>
4148
+ ))}
4149
+ </fieldset>
4150
+ );
4151
+ })}
4152
+ </>
4153
+ );
4154
+ }
4155
+
4156
+ // Initial state: prefer per-attach defaultModifierIds; fall back to
4157
+ // modifier.isDefault flags. Filter sold-out modifiers.
4158
+ function buildInitialSelections(groups: ModifierGroup[]): Record<string, string[]> {
4159
+ const out: Record<string, string[]> = {};
4160
+ for (const group of groups) {
4161
+ if (group.max === 0) continue;
4162
+ const fromAttach = group.defaultModifierIds ?? [];
4163
+ const fromIsDefault = group.modifiers
4164
+ .filter((m) => m.isDefault && m.available)
4165
+ .map((m) => m.id);
4166
+ const merged =
4167
+ fromAttach.length > 0
4168
+ ? fromAttach.filter((id) => group.modifiers.some((m) => m.id === id && m.available))
4169
+ : fromIsDefault;
4170
+ const capped = group.selectionType === 'SINGLE' ? merged.slice(0, 1) : merged;
4171
+ if (capped.length > 0) out[group.id] = capped;
4172
+ }
4173
+ return out;
4174
+ }
4175
+
4176
+ // PRICE-DELTA RULES:
4177
+ // - "5.00" \u2192 +$5 added to unit price
4178
+ // - "-2.00" \u2192 downsell: subtracts $2; never consumes a free slot
4179
+ // - "0.00" \u2192 free option; render no price label
4180
+ // Server enforces unitPrice >= 0; rejects negative deltas combined with
4181
+ // referencedProductId. Do NOT compute the line total client-side \u2014 the
4182
+ // server runs free-allocation and returns cart.items[i].unitPrice.
4183
+
4184
+ `,
4185
+ "cart-add-with-selections": `// Pass modifier-group selections on add-to-cart. The server validates
4186
+ // against the effective rules and computes the final unitPrice (base +
4187
+ // paid modifiers, after the free-allocation policy runs).
4188
+ import { client } from './brainerce';
4189
+ import type { ModifierSelection } from 'brainerce';
4190
+
4191
+ async function addPizzaToCart(
4192
+ productId: string,
4193
+ variantId: string,
4194
+ selectionsByGroup: Record<string, string[]>
4195
+ ) {
4196
+ // Adapter: shape used in component state \u2192 wire format the SDK accepts.
4197
+ const selections: ModifierSelection[] = Object.entries(selectionsByGroup)
4198
+ .filter(([, modifierIds]) => modifierIds.length > 0)
4199
+ .map(([modifierGroupId, modifierIds]) => ({ modifierGroupId, modifierIds }));
4200
+
4201
+ // modifierIds is in CLICK-ORDER \u2014 used by the SELECTION_ORDER free-allocation
4202
+ // policy. Don't sort it; preserve the order the customer clicked.
4203
+
4204
+ const cart = await client.smartAddToCart({
4205
+ productId,
4206
+ variantId,
4207
+ quantity: 1,
4208
+ selections,
4209
+ });
4210
+
4211
+ // Read the snapshot back off the new cart line.
4212
+ const line = cart.items[cart.items.length - 1];
4213
+ // line.modifiers \u2192 CartItemModifierLine[] with { modifierId, name, priceDelta, freeApplied }
4214
+ // line.modifiersTotal \u2192 decimal string of paid (non-free) deltas
4215
+ // line.unitPrice \u2192 final unit price including all paid modifiers
4216
+ console.log('Free applied:', line.modifiers?.filter((m) => m.freeApplied).map((m) => m.name));
4217
+ }
4218
+
4219
+ // EDITING SELECTIONS LATER (PRD \xA77.2.3 \u2014 idempotent replacement):
4220
+ // PATCH the cart item with a fresh selections array. The server deletes ALL
4221
+ // existing CartItemModifier rows and recreates them in the same transaction.
4222
+ // To leave selections untouched (e.g., quantity-only update), omit them.
4223
+ async function changeToppings(cartId: string, itemId: string, newToppingIds: string[]) {
4224
+ await client.updateCartItem(cartId, itemId, {
4225
+ quantity: 1,
4226
+ selections: [{ modifierGroupId: 'mg_toppings', modifierIds: newToppingIds }],
4227
+ });
4228
+ }
4229
+
4230
+ // NESTED COMBOS (depth \u2264 3): when a picked modifier carries
4231
+ // referencedProductId, fetch that product's own modifierGroups, collect the
4232
+ // nested selections, and pass them keyed by the PARENT modifier id.
4233
+ async function addCombo(productId: string, mainBurger: string) {
4234
+ await client.smartAddToCart({
4235
+ productId,
4236
+ quantity: 1,
4237
+ selections: [
4238
+ { modifierGroupId: 'mg_main', modifierIds: [mainBurger] }, // the burger
4239
+ { modifierGroupId: 'mg_drink', modifierIds: ['m_cola'] },
4240
+ ],
4241
+ nestedByModifierId: {
4242
+ [mainBurger]: [
4243
+ { modifierGroupId: 'mg_doneness', modifierIds: ['m_medium'] },
4244
+ { modifierGroupId: 'mg_cheese', modifierIds: ['m_cheddar'] },
4245
+ ],
4246
+ },
4247
+ });
4248
+ }`,
4249
+ "modifier-validation-error-handling": `// Surface MODIFIER_VALIDATION_FAILED to the user. The SDK throws
4250
+ // BrainerceError on HTTP 400; the structured envelope is on .details.
4251
+ import { client } from './brainerce';
4252
+ import type { ModifierSelection } from 'brainerce';
4253
+
4254
+ interface ModifierValidationError {
4255
+ code:
4256
+ | 'REQUIRED_GROUP_MISSING'
4257
+ | 'MIN_SELECTIONS_NOT_MET'
4258
+ | 'MAX_SELECTIONS_EXCEEDED'
4259
+ | 'SINGLE_GROUP_MULTIPLE_PICKS'
4260
+ | 'UNKNOWN_MODIFIER'
4261
+ | 'UNKNOWN_GROUP'
4262
+ | 'MODIFIER_DISABLED_FOR_VARIANT'
4263
+ | 'MODIFIER_NOT_AVAILABLE'
4264
+ | 'NESTED_DEPTH_EXCEEDED'
4265
+ | 'NESTED_REQUIRES_PRODUCT_REF'
4266
+ | 'INVALID_PRICE_DELTA'
4267
+ | 'MODIFIER_PRICE_FLOOR_VIOLATED';
4268
+ message: string;
4269
+ modifierGroupId?: string;
4270
+ modifierId?: string;
4271
+ }
4272
+
4273
+ async function tryAddToCart(productId: string, selections: ModifierSelection[]) {
4274
+ try {
4275
+ await client.smartAddToCart({ productId, quantity: 1, selections });
4276
+ return { ok: true as const };
4277
+ } catch (err) {
4278
+ const e = err as {
4279
+ statusCode?: number;
4280
+ details?: { code?: string; errors?: ModifierValidationError[] };
4281
+ };
4282
+
4283
+ if (e.statusCode === 400 && e.details?.code === 'MODIFIER_VALIDATION_FAILED') {
4284
+ // Surface each issue inline. groupId / modifierId let you highlight the
4285
+ // specific control the customer needs to fix.
4286
+ const issues = e.details.errors ?? [];
4287
+ const messages = issues.map((i) => formatIssue(i));
4288
+ return { ok: false as const, issues, messages };
4289
+ }
4290
+
4291
+ // Some other error (network, 500, etc.) \u2014 re-throw to a generic handler.
4292
+ throw err;
4293
+ }
4294
+ }
4295
+
4296
+ function formatIssue(issue: ModifierValidationError): string {
4297
+ switch (issue.code) {
4298
+ case 'REQUIRED_GROUP_MISSING':
4299
+ return 'Please pick at least one option from this group.';
4300
+ case 'MIN_SELECTIONS_NOT_MET':
4301
+ case 'MAX_SELECTIONS_EXCEEDED':
4302
+ case 'SINGLE_GROUP_MULTIPLE_PICKS':
4303
+ return issue.message; // server's message already says "Pick at least N" / "Pick at most N"
4304
+ case 'UNKNOWN_MODIFIER':
4305
+ case 'UNKNOWN_GROUP':
4306
+ case 'MODIFIER_DISABLED_FOR_VARIANT':
4307
+ case 'MODIFIER_NOT_AVAILABLE':
4308
+ // The catalog moved under us \u2014 refetch the product and ask the customer
4309
+ // to re-pick. These codes mean the option simply isn't valid anymore.
4310
+ return 'This option is no longer available \u2014 please refresh.';
4311
+ case 'NESTED_DEPTH_EXCEEDED':
4312
+ case 'NESTED_REQUIRES_PRODUCT_REF':
4313
+ return issue.message; // bug in your renderer \u2014 never go past 3 levels
4314
+ case 'INVALID_PRICE_DELTA':
4315
+ return issue.message; // shouldn't happen for SDK callers \u2014 server-validated on save
4316
+ case 'MODIFIER_PRICE_FLOOR_VIOLATED':
4317
+ // The server reports a generic message \u2014 internals never leak. Show a
4318
+ // friendly error and let the customer remove a downsell.
4319
+ return 'Cannot apply more discounts on this item.';
4320
+ }
4321
+ }
4322
+
4323
+ // CLIENT-SIDE PRE-FLIGHT (UX):
4324
+ // You can mirror these checks before calling addToCart to give faster
4325
+ // feedback, but the SERVER is authoritative. Always treat the 400 envelope
4326
+ // as the source of truth.
4327
+ function preflightSelections(
4328
+ groups: { id: string; name: string; min: number; max?: number | null; required: boolean; selectionType: 'SINGLE' | 'MULTIPLE'; }[],
4329
+ selections: Record<string, string[]>
4330
+ ): string | null {
4331
+ for (const g of groups) {
4332
+ if (g.max === 0) continue; // disabled-for-variant
4333
+ const picks = selections[g.id] ?? [];
4334
+ if (g.required && picks.length === 0) return \`\${g.name} is required\`;
4335
+ if (picks.length < g.min) return \`Pick at least \${g.min} from \${g.name}\`;
4336
+ if (g.max != null && picks.length > g.max) return \`Pick at most \${g.max} from \${g.name}\`;
4337
+ if (g.selectionType === 'SINGLE' && picks.length > 1) return \`Only one option allowed in \${g.name}\`;
4338
+ }
4339
+ return null;
4340
+ }`,
4341
+ "checkout-price-drift": `// PRICE_DRIFT \u2014 a product's price changed between add-to-cart and checkout.
4342
+ // The server returns HTTP 400 with code "PRICE_DRIFT" when it detects that
4343
+ // the stored unitPrice no longer matches the live price.
4344
+ //
4345
+ // Strategy: catch the error \u2192 show "prices updated" dialog \u2192
4346
+ // call refreshCartSnapshots() to re-snapshot all live prices \u2192
4347
+ // retry createCheckout once.
4348
+
4349
+ import { client } from './brainerce-client';
4350
+
4351
+ interface CheckoutOptions {
4352
+ cartId: string;
4353
+ shippingAddress: object;
4354
+ shippingMethodId: string;
4355
+ paymentProviderId: string;
4356
+ }
4357
+
4358
+ async function createCheckoutSafe(opts: CheckoutOptions) {
4359
+ try {
4360
+ return await client.createCheckout({
4361
+ cartId: opts.cartId,
4362
+ shippingAddress: opts.shippingAddress,
4363
+ shippingMethodId: opts.shippingMethodId,
4364
+ paymentProviderId: opts.paymentProviderId,
4365
+ });
4366
+ } catch (err: unknown) {
4367
+ if (!isApiError(err, 'PRICE_DRIFT')) throw err;
4368
+
4369
+ // Prices changed \u2014 refresh snapshots then retry once.
4370
+ // refreshCartSnapshots updates every cart item's unitPrice to the current
4371
+ // live price (base price + any modifier deltas) so the next checkout call
4372
+ // will pass the drift guard.
4373
+ await client.refreshCartSnapshots(opts.cartId);
4374
+
4375
+ // After refreshing, re-fetch the cart so your UI shows the updated prices
4376
+ // before you retry, giving the customer a chance to review.
4377
+ const updatedCart = await client.getCart(opts.cartId);
4378
+
4379
+ // Signal to the UI layer that prices changed so it can show a dialog.
4380
+ throw Object.assign(new Error('PRICES_UPDATED'), {
4381
+ code: 'PRICES_UPDATED',
4382
+ updatedCart,
4383
+ });
4384
+ }
4385
+ }
4386
+
4387
+ function isApiError(err: unknown, code: string): boolean {
4388
+ return (
4389
+ typeof err === 'object' &&
4390
+ err !== null &&
4391
+ 'code' in err &&
4392
+ (err as { code: string }).code === code
4393
+ );
4394
+ }
4395
+
4396
+ // --- UI integration example (framework-neutral) ---
4397
+ //
4398
+ // async function handlePlaceOrder() {
4399
+ // try {
4400
+ // const checkout = await createCheckoutSafe({ cartId, ... });
4401
+ // router.push(\`/order-confirmation?checkoutId=\${checkout.id}\`);
4402
+ // } catch (err: unknown) {
4403
+ // if (isApiError(err, 'PRICES_UPDATED')) {
4404
+ // const { updatedCart } = err as { updatedCart: Cart };
4405
+ // showPricesUpdatedDialog(updatedCart); // show diff, let user confirm
4406
+ // return;
4407
+ // }
4408
+ // showGenericError(err);
4409
+ // }
4410
+ // }
4411
+ //
4412
+ // The dialog should:
4413
+ // 1. Show which items changed price (compare old vs new unitPrice)
4414
+ // 2. Offer "Continue with new prices" (calls createCheckoutSafe again)
4415
+ // and "Go back to cart" (returns to cart page)
4416
+ // 3. NOT silently retry \u2014 the customer must acknowledge the price change.`,
4417
+ "cart-item-modifier-display": `// Rendering cart items that have modifier selections.
4418
+ // Each cart item has a \`modifiers\` array \u2014 each entry records the modifier
4419
+ // name, the price delta at time of add-to-cart, and whether it was free
4420
+ // (inside the group's freeQuantity allowance).
4421
+ //
4422
+ // Typical display:
4423
+ // Margherita \u20AA45.00
4424
+ // Extra cheese +\u20AA5.00
4425
+ // Mushrooms free
4426
+ // No onions \u2014
4427
+ // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
4428
+ // Base \u20AA45.00 + Modifiers \u20AA5.00 = \u20AA50.00
4429
+
4430
+ import { formatPrice } from 'brainerce';
4431
+
4432
+ interface CartItemModifier {
4433
+ modifierId: string;
4434
+ name: string;
4435
+ priceDeltaAtTime: number; // in store currency units, e.g. 5.00
4436
+ freeApplied: boolean; // true when inside the group's freeQuantity
4437
+ }
4438
+
4439
+ interface CartItem {
4440
+ id: string;
4441
+ name: string;
4442
+ unitPrice: number; // base + all chargeable modifier deltas, as stored
4443
+ quantity: number;
4444
+ modifiers?: CartItemModifier[];
4445
+ currency: string; // e.g. 'ILS', 'USD'
4446
+ }
4447
+
4448
+ function renderCartItem(item: CartItem): string {
4449
+ const currency = item.currency;
4450
+ const lines: string[] = [];
4451
+
4452
+ lines.push(\`\${item.name} \${formatPrice(item.unitPrice, { currency })}\`);
4453
+
4454
+ const chargeableModifiers = (item.modifiers ?? []).filter(
4455
+ (m) => !m.freeApplied && m.priceDeltaAtTime !== 0
4456
+ );
4457
+ const freeModifiers = (item.modifiers ?? []).filter((m) => m.freeApplied);
4458
+ const zeroModifiers = (item.modifiers ?? []).filter(
4459
+ (m) => !m.freeApplied && m.priceDeltaAtTime === 0
4460
+ );
4461
+
4462
+ for (const m of chargeableModifiers) {
4463
+ const sign = m.priceDeltaAtTime > 0 ? '+' : '';
4464
+ lines.push(\` \${m.name} \${sign}\${formatPrice(m.priceDeltaAtTime, { currency })}\`);
4465
+ }
4466
+ for (const m of freeModifiers) {
4467
+ lines.push(\` \${m.name} free\`);
4468
+ }
4469
+ for (const m of zeroModifiers) {
4470
+ lines.push(\` \${m.name} \u2014\`);
4471
+ }
4472
+
4473
+ // Price breakdown: only show when there are chargeable modifiers
4474
+ const modifiersTotal = chargeableModifiers.reduce(
4475
+ (sum, m) => sum + m.priceDeltaAtTime,
4476
+ 0
4477
+ );
4478
+ if (modifiersTotal !== 0) {
4479
+ // unitPrice already includes modifiers \u2014 derive base for display only
4480
+ const basePrice = item.unitPrice - modifiersTotal;
4481
+ const base = formatPrice(basePrice, { currency }) as string;
4482
+ const mods = formatPrice(modifiersTotal, { currency }) as string;
4483
+ const total = formatPrice(item.unitPrice, { currency }) as string;
4484
+ lines.push(\`Base \${base} + Modifiers \${mods} = \${total}\`);
4485
+ }
4486
+
4487
+ return lines.join('\\n');
4488
+ }
4489
+
4490
+ // IMPORTANT: unitPrice already includes all chargeable modifier deltas.
4491
+ // Do NOT add modifier prices on top of unitPrice when computing line totals \u2014
4492
+ // multiply unitPrice \xD7 quantity directly.
4493
+ function lineTotal(item: CartItem): number {
4494
+ return item.unitPrice * item.quantity;
4495
+ }`
3535
4496
  };
3536
4497
  async function handleGetCodeExample(args) {
3537
4498
  const snippet = SNIPPETS[args.operation];
@@ -3647,13 +4608,27 @@ function getCandidateApiUrls() {
3647
4608
 
3648
4609
  // src/tools/get-store-info.ts
3649
4610
  var GET_STORE_INFO_NAME = "get-store-info";
3650
- var GET_STORE_INFO_DESCRIPTION = "Fetch live store information from the Brainerce API using a connection ID. Returns the channel display name (what the user sees in their dashboard), parent store name, currency, and language. Use this to personalize the store being built \u2014 prefer the channel name for user-facing text since a single Brainerce store can have multiple sales channels.";
4611
+ var GET_STORE_INFO_DESCRIPTION = "Fetch live store information from the Brainerce API using a sales channel ID. Returns the channel display name (what the user sees in their dashboard), parent store name, currency, and language. Use this to personalize the store being built \u2014 prefer the channel name for user-facing text since a single Brainerce store can have multiple sales channels.";
3651
4612
  var GET_STORE_INFO_SCHEMA = {
3652
- connectionId: import_zod4.z.string().describe("Vibe-coded connection ID (starts with vc_)")
4613
+ salesChannelId: import_zod4.z.string().optional().describe("Sales channel ID (starts with vc_)"),
4614
+ /** @deprecated alias of salesChannelId */
4615
+ connectionId: import_zod4.z.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
3653
4616
  };
3654
4617
  async function handleGetStoreInfo(args) {
4618
+ const id = args.salesChannelId ?? args.connectionId;
4619
+ if (!id) {
4620
+ return {
4621
+ content: [{ type: "text", text: "Error: salesChannelId is required" }],
4622
+ isError: true
4623
+ };
4624
+ }
4625
+ if (!args.salesChannelId && args.connectionId) {
4626
+ console.warn(
4627
+ "get-store-info: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
4628
+ );
4629
+ }
3655
4630
  try {
3656
- const resolved = await resolveStoreInfo(args.connectionId, getCandidateApiUrls());
4631
+ const resolved = await resolveStoreInfo(id, getCandidateApiUrls());
3657
4632
  return {
3658
4633
  content: [
3659
4634
  {
@@ -3666,7 +4641,8 @@ async function handleGetStoreInfo(args) {
3666
4641
  storeName: resolved.info.storeName,
3667
4642
  currency: resolved.info.currency,
3668
4643
  language: resolved.info.language,
3669
- connectionId: args.connectionId,
4644
+ salesChannelId: id,
4645
+ connectionId: id,
3670
4646
  apiBaseUrl: resolved.apiBaseUrl
3671
4647
  },
3672
4648
  null,
@@ -3751,9 +4727,11 @@ async function resolveStoreCapabilities(connectionId, candidateUrls) {
3751
4727
 
3752
4728
  // src/tools/get-store-capabilities.ts
3753
4729
  var GET_STORE_CAPABILITIES_NAME = "get-store-capabilities";
3754
- var GET_STORE_CAPABILITIES_DESCRIPTION = "Get live store capabilities and configured features for a vibe-coded connection. Returns what payment providers, OAuth, shipping, discounts, and other features are set up. Use this to discover what your store supports and what pages/components to build.";
4730
+ var GET_STORE_CAPABILITIES_DESCRIPTION = "Get live store capabilities and configured features for a sales channel. Returns what payment providers, OAuth, shipping, discounts, and other features are set up. Use this to discover what your store supports and what pages/components to build.";
3755
4731
  var GET_STORE_CAPABILITIES_SCHEMA = {
3756
- connectionId: import_zod5.z.string().describe("Vibe-coded connection ID (starts with vc_)")
4732
+ salesChannelId: import_zod5.z.string().optional().describe("Sales channel ID (starts with vc_)"),
4733
+ /** @deprecated alias of salesChannelId */
4734
+ connectionId: import_zod5.z.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
3757
4735
  };
3758
4736
  function formatCapabilities(caps) {
3759
4737
  const lines = [];
@@ -3866,15 +4844,27 @@ function formatCapabilities(caps) {
3866
4844
  }
3867
4845
  if (suggestions.length === 0) {
3868
4846
  suggestions.push(
3869
- "Start by building the required features. Use get-required-features with this connectionId for the checklist."
4847
+ "Start by building the required features. Use get-required-features with this salesChannelId for the checklist."
3870
4848
  );
3871
4849
  }
3872
4850
  suggestions.forEach((s) => lines.push(`- ${s}`));
3873
4851
  return lines.join("\n");
3874
4852
  }
3875
4853
  async function handleGetStoreCapabilities(args) {
4854
+ const id = args.salesChannelId ?? args.connectionId;
4855
+ if (!id) {
4856
+ return {
4857
+ content: [{ type: "text", text: "Error: salesChannelId is required" }],
4858
+ isError: true
4859
+ };
4860
+ }
4861
+ if (!args.salesChannelId && args.connectionId) {
4862
+ console.warn(
4863
+ "get-store-capabilities: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
4864
+ );
4865
+ }
3876
4866
  try {
3877
- const resolved = await resolveStoreCapabilities(args.connectionId, getCandidateApiUrls());
4867
+ const resolved = await resolveStoreCapabilities(id, getCandidateApiUrls());
3878
4868
  return {
3879
4869
  content: [{ type: "text", text: formatCapabilities(resolved.capabilities) }]
3880
4870
  };
@@ -3979,7 +4969,7 @@ var RULES = {
3979
4969
  tokens: {
3980
4970
  title: "Auth tokens & BFF pattern",
3981
4971
  body: `- NEVER store customer auth tokens in \`localStorage\` directly from client code. Use a Backend-For-Frontend proxy: the server receives the token, sets an HttpOnly cookie, and the client reads session state from an endpoint like \`/api/auth/me\`.
3982
- - NEVER put the admin API key (\`brainerce_*\`) in client code. It is a server-only secret. Client code uses \`connectionId\` or storefront endpoints.
4972
+ - NEVER put the admin API key (\`brainerce_*\`) in client code. It is a server-only secret. Client code uses \`salesChannelId\` (or the deprecated \`connectionId\` alias) or storefront endpoints.
3983
4973
  - OAuth callbacks arrive with the token in URL params. Extract it SERVER-side and exchange it for a session cookie before redirecting to the app. Do not let the token land in browser history.
3984
4974
  - On logout, clear the BFF session server-side. A client-only logout that forgets to tell the server leaves an active session on the server until it expires.`
3985
4975
  },
@@ -4272,18 +5262,20 @@ ${flow.body}`
4272
5262
  // src/tools/get-required-features.ts
4273
5263
  var import_zod9 = require("zod");
4274
5264
  var GET_REQUIRED_FEATURES_NAME = "get-required-features";
4275
- var GET_REQUIRED_FEATURES_DESCRIPTION = "Get the functional coverage checklist for a Brainerce store. Returns user-capability-level features (what users must be able to do) rather than pages or file paths. Every feature marked mandatory must exist in the finished build, even when the underlying capability is currently disabled \u2014 those features auto-hide and store owners enable them later. Pass a connectionId to tune the checklist to the live store; without it, returns the generic complete-store checklist.";
5265
+ var GET_REQUIRED_FEATURES_DESCRIPTION = "Get the functional coverage checklist for a Brainerce store. Returns user-capability-level features (what users must be able to do) rather than pages or file paths. Every feature marked mandatory must exist in the finished build, even when the underlying capability is currently disabled \u2014 those features auto-hide and store owners enable them later. Pass a salesChannelId to tune the checklist to the live store; without it, returns the generic complete-store checklist.";
4276
5266
  var GET_REQUIRED_FEATURES_SCHEMA = {
4277
- connectionId: import_zod9.z.string().optional().describe(
4278
- "Vibe-coded connection ID (starts with vc_). Optional \u2014 without it, returns the generic checklist."
4279
- )
5267
+ salesChannelId: import_zod9.z.string().optional().describe(
5268
+ "Sales channel ID (starts with vc_). Optional \u2014 without it, returns the generic checklist."
5269
+ ),
5270
+ /** @deprecated alias of salesChannelId */
5271
+ connectionId: import_zod9.z.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
4280
5272
  };
4281
5273
  var FEATURES = [
4282
5274
  {
4283
5275
  id: "browse-products",
4284
5276
  title: "Browse, filter, and search products",
4285
- description: "Users can list products with pagination, apply category / price / attribute filters, sort by name / price / newest, and run a search with autocomplete. Must handle empty states and loading states.",
4286
- sdk: "client.getProducts({ page, limit, filters, sort }), client.searchProducts(query)",
5277
+ description: "Users can list products with pagination, apply category / price / attribute / custom-field filters, sort by name / price / newest, and run a search with autocomplete. Custom-field filters surface metafield definitions whose filterable=true (SELECT, MULTI_SELECT, BOOLEAN). Must handle empty states and loading states.",
5278
+ sdk: "client.getProducts({ page, limit, filters, sort, metafields }), client.getPublicMetafieldDefinitions(), client.searchProducts(query)",
4287
5279
  mandatory: "mandatory"
4288
5280
  },
4289
5281
  {
@@ -4498,10 +5490,16 @@ function renderCapabilitiesSummary(caps) {
4498
5490
  return lines.join("\n");
4499
5491
  }
4500
5492
  async function handleGetRequiredFeatures(args) {
5493
+ const id = args.salesChannelId ?? args.connectionId;
5494
+ if (!args.salesChannelId && args.connectionId) {
5495
+ console.warn(
5496
+ "get-required-features: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
5497
+ );
5498
+ }
4501
5499
  let caps = null;
4502
- if (args.connectionId) {
5500
+ if (id) {
4503
5501
  try {
4504
- const resolved = await resolveStoreCapabilities(args.connectionId, getCandidateApiUrls());
5502
+ const resolved = await resolveStoreCapabilities(id, getCandidateApiUrls());
4505
5503
  caps = resolved.capabilities;
4506
5504
  } catch {
4507
5505
  caps = null;
@@ -4513,11 +5511,11 @@ async function handleGetRequiredFeatures(args) {
4513
5511
  );
4514
5512
  if (caps) {
4515
5513
  sections.push(renderCapabilitiesSummary(caps));
4516
- } else if (args.connectionId) {
5514
+ } else if (id) {
4517
5515
  sections.push(
4518
5516
  `## Live store capabilities
4519
5517
 
4520
- Could not fetch live capabilities for \`${args.connectionId}\`. Proceeding with the generic checklist. Call \`get-store-capabilities\` separately if you want a targeted checklist.`
5518
+ Could not fetch live capabilities for \`${id}\`. Proceeding with the generic checklist. Call \`get-store-capabilities\` separately if you want a targeted checklist.`
4521
5519
  );
4522
5520
  }
4523
5521
  sections.push("## Features");