@brainerce/mcp-server 3.2.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/index.mjs CHANGED
@@ -259,9 +259,14 @@ function CheckoutPage() {
259
259
  }
260
260
 
261
261
  // Step 4: Create payment intent \u2014 returns provider type!
262
+ // Pass saveCard: true when the customer ticked "save my card for next time" \u2014
263
+ // only honored for logged-in customers (not guests). The vaulted card then
264
+ // appears in client.listSavedPaymentMethods(storeId, customerId) and can be
265
+ // charged off-session via subscription / one-click checkout flows.
262
266
  const paymentIntent = await client.createPaymentIntent(checkoutId, {
263
267
  successUrl: \`\${window.location.origin}/order-confirmation?checkout_id=\${checkoutId}\`,
264
268
  cancelUrl: \`\${window.location.origin}/checkout?error=payment_cancelled\`,
269
+ // saveCard: customerOptedIn, // optional opt-in
265
270
  });
266
271
 
267
272
  setPaymentData({ clientSecret: paymentIntent.clientSecret, provider: paymentIntent.provider, checkoutId });
@@ -382,8 +387,10 @@ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; che
382
387
  }
383
388
  if (data?.type === 'brainerce:redirect' && typeof data.url === 'string') {
384
389
  // Top-level navigation (e.g. Bit). ALWAYS validate against an allowlist
385
- // before navigating \u2014 never trust the URL blindly.
386
- if (isTrustedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
390
+ // before navigating \u2014 never trust the URL blindly. The SDK ships with
391
+ // a maintained list of payment-provider hosts; prefer it over a local
392
+ // copy so 'npm update brainerce' picks up new providers automatically.
393
+ if (isAllowedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
387
394
  }
388
395
  if (data?.type === 'brainerce:payment-complete') {
389
396
  // Payment done \u2014 redirect to confirmation page which verifies server-side
@@ -423,15 +430,10 @@ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; che
423
430
  );
424
431
  }
425
432
 
426
- // Allowlist of origins you trust for top-level payment redirects.
427
- function isTrustedPaymentUrl(url: string): boolean {
428
- try {
429
- const u = new URL(url);
430
- if (u.protocol !== 'https:') return false;
431
- // Add your provider hostnames here. Example: Cardcom for Bit express-pay.
432
- return u.hostname === 'cardcom.solutions' || u.hostname.endsWith('.cardcom.solutions');
433
- } catch { return false; }
434
- }
433
+ // Allowlist check is provided by the SDK \u2014 covers Stripe, PayPal, Cardcom,
434
+ // Meshulam, Grow, CreditGuard, plus Brainerce-hosted embed shells. To extend
435
+ // for a self-hosted PSP, pass { extraHosts: ['my-psp.example.com'] }.
436
+ import { isAllowedPaymentUrl } from 'brainerce';
435
437
  \`\`\`
436
438
 
437
439
  ### PayPal Payment Form
@@ -719,6 +721,80 @@ Provider-specific install notes:
719
721
  - **Grow:** No SDK needed \u2014 JS SDK loaded via \`clientSdk.scriptUrl\`. Supports credit cards, Bit, Apple Pay, Google Pay.
720
722
  - **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.`;
721
723
  }
724
+ function getSavedPaymentMethodsSection() {
725
+ return `## Saved Payment Methods (vaulted cards)
726
+
727
+ When a logged-in customer ticks "save my card for next time", the platform vaults the
728
+ card with the underlying provider and stores a reference. Vaulted cards can later be
729
+ charged off-session \u2014 typically via subscription / one-click checkout features built
730
+ on top of this foundation.
731
+
732
+ ### Opt-in at checkout
733
+
734
+ Pass \`saveCard: true\` to \`createPaymentIntent\` when the customer chose to save.
735
+ **Only honored for logged-in customers** \u2014 anonymous (guest) checkouts silently
736
+ skip vaulting because there's no Customer record to attach the resulting saved
737
+ method to.
738
+
739
+ \`\`\`typescript
740
+ const intent = await client.createPaymentIntent(checkoutId, {
741
+ successUrl,
742
+ cancelUrl,
743
+ saveCard: true, // optional \u2014 only when customer ticked the box AND is logged in
744
+ });
745
+ \`\`\`
746
+
747
+ After a successful charge, the saved card appears in the customer's profile.
748
+
749
+ ### Listing saved cards (storefront / customer account page)
750
+
751
+ Show the customer their saved cards on a "Manage Payment Methods" page in their
752
+ account. The platform returns display-only metadata \u2014 last4, brand, expiry,
753
+ default flag, status. The underlying provider token is encrypted at rest and
754
+ NEVER returned through the SDK.
755
+
756
+ \`\`\`typescript
757
+ const methods = await client.listSavedPaymentMethods(storeId, customerId);
758
+
759
+ methods.forEach((m) => {
760
+ console.log(\`\${m.brand} ending in \${m.last4} (expires \${m.expMonth}/\${m.expYear})\`);
761
+ if (m.isDefault) console.log(' \u21B3 default');
762
+ if (m.status === 'expired') console.log(' \u21B3 expired \u2014 please add a new card');
763
+ });
764
+ \`\`\`
765
+
766
+ ### Removing a saved card
767
+
768
+ \`\`\`typescript
769
+ await client.removeSavedPaymentMethod(storeId, customerId, methodId);
770
+ \`\`\`
771
+
772
+ Hard-deletes the row from the platform DB. The provider may still hold the
773
+ underlying token internally \u2014 we don't issue a delete-at-provider call because
774
+ not every provider supports it. From the platform's perspective the token is
775
+ gone; subsequent charges fail.
776
+
777
+ ### Provider support matrix
778
+
779
+ | Provider | Save card on first charge | Charge saved card off-session |
780
+ |---|---|---|
781
+ | Cardcom | \u2705 (Operation: ChargeAndCreateToken) | \u2705 |
782
+ | PayPal | \u2705 (Vault API: store_in_vault) | \u2705 |
783
+ | Stripe | (separate workstream \u2014 Brainerce doesn't ship a Stripe payment app yet) | \u2014 |
784
+ | Grow | \u274C \u2014 returns 501 \`token_storage_unavailable\` | \u274C |
785
+
786
+ When a provider doesn't support tokenization, the platform surfaces a 409 with
787
+ \`code: 'token_storage_unavailable'\`. Storefronts should hide the "save card"
788
+ checkbox when the active provider doesn't support it.
789
+
790
+ ### Charging off-session
791
+
792
+ Charging a saved card from the storefront is **not** part of this foundation \u2014
793
+ that's the job of the Subscription / one-click checkout features built on top.
794
+ For now, charges run through the standard \`createPaymentIntent\` flow. The
795
+ saved-method foundation makes those features possible without further platform
796
+ changes.`;
797
+ }
722
798
  function getProductsSection(_currency) {
723
799
  return `## Products & Variants
724
800
 
@@ -739,6 +815,18 @@ const filtered = await client.getProducts({
739
815
  categories: ['cat_123'], minPrice: 10, maxPrice: 100,
740
816
  sortBy: 'price', sortOrder: 'asc',
741
817
  });
818
+
819
+ // Filter by custom fields (metafields). Only fields the merchant marked
820
+ // \`filterable: true\` are honored; supported types are SELECT, MULTI_SELECT,
821
+ // BOOLEAN. AND across keys, OR within a key.
822
+ const byCustom = await client.getProducts({
823
+ metafields: { color: ['red', 'blue'], in_stock: ['true'] },
824
+ });
825
+
826
+ // Discover which custom fields are filterable for the current store:
827
+ const { definitions } = await client.getPublicMetafieldDefinitions();
828
+ const facets = definitions.filter(d => d.filterable);
829
+ // Render a checkbox group per SELECT/MULTI_SELECT, a switch per BOOLEAN.
742
830
  \`\`\`
743
831
 
744
832
  ### i18n \u2014 translated fields come back on every request
@@ -1108,22 +1196,24 @@ const { upgrades } = await client.getCartUpgrades(cartId);
1108
1196
  // Show inline banner per cart item if upgrade exists
1109
1197
  \`\`\`
1110
1198
 
1111
- **Bundle offers** (discounted complementary products configured by the store owner):
1199
+ **Bundle offers** (N-product bundles configured by the store owner \u2014 productIds[0] triggers the offer, productIds[1..] are offered together at a discount):
1112
1200
  \`\`\`typescript
1113
1201
  import type { CartBundlesResponse } from 'brainerce';
1114
1202
  const { bundles } = await client.getCartBundles(cartId);
1115
- // bundles[].bundleProduct \u2014 the product to offer
1116
- // bundles[].originalPrice / bundles[].discountedPrice \u2014 prices
1203
+ // bundles[].triggerProductId \u2014 already in cart, activates the offer
1204
+ // bundles[].productIds \u2014 full bundle composition (length >= 2)
1205
+ // bundles[].offeredProducts[] \u2014 products customer hasn't added yet
1206
+ // each with originalPrice + discountedPrice
1207
+ // bundles[].totalOriginalPrice / totalDiscountedPrice \u2014 sums across offeredProducts
1117
1208
  // bundles[].discountType ('PERCENTAGE' | 'FIXED_AMOUNT') + discountValue
1118
- // bundles[].requiresVariantSelection \u2014 true if customer must pick a variant
1119
- // bundles[].lockedVariant \u2014 set if admin pre-selected a specific variant
1120
- // bundles[].bundleProduct.variants \u2014 available variants (only when requiresVariantSelection)
1121
1209
 
1122
- // Add a bundle to cart (applies the discount automatically):
1210
+ // Accept a bundle (adds every offered product not yet in cart at the discount):
1123
1211
  await client.addBundleToCart(cartId, bundleOfferId);
1124
- // For products with variants \u2014 pass the selected variantId:
1125
- await client.addBundleToCart(cartId, bundleOfferId, selectedVariantId);
1126
- // Remove a bundle from cart:
1212
+ // If some offered products have variants, pass per-product variant selections:
1213
+ await client.addBundleToCart(cartId, bundleOfferId, {
1214
+ [variantProductId]: selectedVariantId,
1215
+ });
1216
+ // Remove an accepted bundle (removes every cart item linked to that bundle):
1127
1217
  await client.removeBundleFromCart(cartId, bundleOfferId);
1128
1218
  // Detect already-added bundles: check cart.items for metadata?.isBundleItem === true
1129
1219
  \`\`\`
@@ -1179,11 +1269,12 @@ Always check the flag before rendering: \`if (storeInfo?.upsell?.featureName !==
1179
1269
  | CartRecommendationSection | products/ | Cross-sell grid at bottom of cart page |
1180
1270
  | FreeShippingBar | cart/ | Progress bar toward free shipping threshold |
1181
1271
  | CartUpgradeBanner | cart/ | Inline "Upgrade to X for +$Y" per cart item |
1182
- | CartBundleOfferCard | cart/ | Discounted bundle offer card in cart (with inline variant selector for variable products) |
1272
+ | CartBundleOfferCard | cart/ | N-product bundle offer card in cart \u2014 lists every offered product with its discounted price and an "Add bundle" button |
1183
1273
  | OrderBumpCard | checkout/ | Checkbox add-on card in checkout sidebar (with inline variant selector for variable products) |
1184
1274
 
1185
1275
  ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`, \`variants?\` (when variant selection needed).
1186
- OrderBump/CartBundleOffer: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).`;
1276
+ OrderBump: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).
1277
+ 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\`.`;
1187
1278
  }
1188
1279
  function getProductCustomizationFieldsSection() {
1189
1280
  return `## Product Customization Fields (buyer input on product page)
@@ -1289,6 +1380,157 @@ When the order is created, each line's customization values are snapshotted onto
1289
1380
  - Using a raw external URL (not from \`/customization-upload\`) for \`IMAGE\` / \`GALLERY\` \u2192 HTTP 400
1290
1381
  - Assuming \`enumValues\` is present for all types \u2014 only \`SELECT\` / \`MULTI_SELECT\` require it`;
1291
1382
  }
1383
+ function getModifierGroupsSection() {
1384
+ return `## Modifier Groups (toppings, sauce, build-your-own)
1385
+
1386
+ 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.
1387
+
1388
+ If \`product.modifierGroups\` is empty or missing, render the product page normally and skip everything below.
1389
+
1390
+ ### Wire shape on \`GET /products/:id\`
1391
+
1392
+ \`\`\`typescript
1393
+ import type { Product, ModifierGroup, Modifier, ModifierSelection } from 'brainerce';
1394
+
1395
+ const product = await client.getProductBySlug(slug);
1396
+ const groups: ModifierGroup[] = product.modifierGroups ?? [];
1397
+
1398
+ // Each group looks like:
1399
+ // {
1400
+ // id: 'mg_toppings',
1401
+ // attachmentId: 'pmg_01', // ProductModifierGroup row \u2014 used for attach updates
1402
+ // name: 'Toppings', // customer-facing
1403
+ // internalName?: string, // ADMIN ONLY \u2014 never present in storefront responses
1404
+ // selectionType: 'SINGLE' | 'MULTIPLE',
1405
+ // min: number, // effective (overrides already applied)
1406
+ // max: number | null, // null = unlimited; **0 = group hidden for this variant**
1407
+ // freeQuantity: number, // first N picks at no extra cost
1408
+ // required: boolean,
1409
+ // freeAllocationPolicy: 'EXPENSIVE_FREE' | 'CHEAPEST_FREE' | 'SELECTION_ORDER',
1410
+ // defaultModifierIds: string[], // pre-checked on first render
1411
+ // modifiers: Array<{
1412
+ // id: 'm_olive',
1413
+ // name: 'Olives',
1414
+ // priceDelta: '5.00', // DECIMAL STRING \u2014 never JSON Number
1415
+ // position: 0,
1416
+ // isDefault: false, // pre-check this option even if not in defaultModifierIds
1417
+ // available: true, // false \u2192 "sold out", disabled in UI
1418
+ // referencedProductId?: string, // nested-combo target (depth \u2264 3)
1419
+ // }>,
1420
+ // }
1421
+ \`\`\`
1422
+
1423
+ **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.
1424
+
1425
+ ### Render: SINGLE \u2192 radio, MULTIPLE \u2192 checkbox
1426
+
1427
+ Walk \`groups\` and pick the input type by \`selectionType\`. Sort modifiers by \`position\`.
1428
+
1429
+ \`\`\`typescript
1430
+ for (const group of groups) {
1431
+ if (group.max === 0) continue; // disabled-for-variant convention \u2014 skip entirely
1432
+ const inputType = group.selectionType === 'SINGLE' ? 'radio' : 'checkbox';
1433
+ const sorted = [...group.modifiers].sort((a, b) => a.position - b.position);
1434
+ // Render fieldset \u2192 legend with name + " *" if required \u2192 list of sorted options.
1435
+ // Each option: input(type=inputType, name=group.id, value=modifier.id),
1436
+ // disabled when modifier.available === false, with a "Sold out" badge.
1437
+ }
1438
+ \`\`\`
1439
+
1440
+ When \`group.freeQuantity > 0\`, show a running counter so the customer understands the rule:
1441
+ \`\`\`
1442
+ {Math.min(picks.length, group.freeQuantity)} of {group.freeQuantity} free
1443
+ \`\`\`
1444
+
1445
+ 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.
1446
+
1447
+ ### Initial state
1448
+
1449
+ 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.
1450
+
1451
+ ### Pass selections on add-to-cart
1452
+
1453
+ \`\`\`typescript
1454
+ const selections: ModifierSelection[] = [
1455
+ { modifierGroupId: 'mg_bread', modifierIds: ['m_thick'] },
1456
+ { modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_mushroom', 'm_bacon', 'm_egg'] },
1457
+ ];
1458
+
1459
+ await client.smartAddToCart({
1460
+ productId: product.id,
1461
+ variantId: selectedVariant?.id,
1462
+ quantity: 1,
1463
+ selections,
1464
+ });
1465
+ \`\`\`
1466
+
1467
+ \`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:
1468
+
1469
+ \`\`\`typescript
1470
+ // cart.items[i].modifiers \u2014 same shape as ModifierSelection but with snapshot data
1471
+ [
1472
+ { modifierId: 'm_olive', name: 'Olives', priceDelta: '5.00', freeApplied: true },
1473
+ { modifierId: 'm_mushroom', name: 'Mushrooms', priceDelta: '5.00', freeApplied: true },
1474
+ { modifierId: 'm_bacon', name: 'Bacon', priceDelta: '7.00', freeApplied: true },
1475
+ { modifierId: 'm_egg', name: 'Egg', priceDelta: '6.00', freeApplied: false },
1476
+ ]
1477
+ // + cart.items[i].modifiersTotal \u2014 sum of paid (non-free) deltas as a decimal string
1478
+ \`\`\`
1479
+
1480
+ \`freeApplied: true\` means the modifier consumed a free slot \u2014 render with a "free" badge in the cart UI.
1481
+
1482
+ ### Editing selections after add-to-cart (idempotent)
1483
+
1484
+ \`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).
1485
+
1486
+ \`\`\`typescript
1487
+ await client.updateCartItem(cart.id, itemId, {
1488
+ quantity: 1,
1489
+ selections: [{ modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_mushroom'] }],
1490
+ });
1491
+ \`\`\`
1492
+
1493
+ ### Validation envelope
1494
+
1495
+ When the payload is invalid the server returns HTTP 400 with a structured envelope. The SDK exposes it on \`BrainerceError.details\`:
1496
+
1497
+ \`\`\`typescript
1498
+ try {
1499
+ await client.smartAddToCart({ productId, quantity: 1, selections });
1500
+ } catch (err) {
1501
+ const e = err as { statusCode?: number; details?: { code?: string; errors?: Array<{ code: string; message: string; modifierGroupId?: string; modifierId?: string }> } };
1502
+ if (e.statusCode === 400 && e.details?.code === 'MODIFIER_VALIDATION_FAILED') {
1503
+ for (const issue of e.details.errors ?? []) {
1504
+ // issue.code is one of: REQUIRED_GROUP_MISSING | MIN_SELECTIONS_NOT_MET |
1505
+ // MAX_SELECTIONS_EXCEEDED | SINGLE_GROUP_MULTIPLE_PICKS | UNKNOWN_MODIFIER |
1506
+ // UNKNOWN_GROUP | MODIFIER_DISABLED_FOR_VARIANT | MODIFIER_NOT_AVAILABLE |
1507
+ // NESTED_DEPTH_EXCEEDED | NESTED_REQUIRES_PRODUCT_REF | INVALID_PRICE_DELTA |
1508
+ // MODIFIER_PRICE_FLOOR_VIOLATED
1509
+ console.error(issue.message);
1510
+ }
1511
+ }
1512
+ }
1513
+ \`\`\`
1514
+
1515
+ 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.
1516
+
1517
+ ### Disable-for-variant convention (PRD \xA77.2.2)
1518
+
1519
+ 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.
1520
+
1521
+ ### Common mistakes
1522
+
1523
+ - Treating \`priceDelta\` as a number \u2192 arithmetic precision bugs. Always strings; use \`parseFloat\` only at display time.
1524
+ - Computing the line total client-side \u2192 diverges from the server's free-allocation. Render the server's \`unitPrice\` / \`modifiers[]\` / \`modifiersTotal\` instead.
1525
+ - Rendering a group with \`max: 0\` \u2192 it's the variant-disable signal; treat as absent.
1526
+ - 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.
1527
+ - Building \`selections\` keyed by \`modifier.name\` \u2192 must be \`modifierGroupId\` + \`modifierIds[]\` (the IDs, not names).
1528
+ - Sending \`modifiers\` instead of \`selections\` on add-to-cart \u2192 \`modifiers\` is the response field; the request key is \`selections\`.
1529
+
1530
+ ### Restaurant features (advanced)
1531
+
1532
+ 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.`;
1533
+ }
1292
1534
  function getInventorySection() {
1293
1535
  return `## Inventory, Stock Display & Reservation Countdown
1294
1536
 
@@ -1854,7 +2096,358 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
1854
2096
  // Email: getEmailTemplates(), createEmailTemplate()
1855
2097
  // Conflicts: getSyncConflicts(), resolveSyncConflict()
1856
2098
  // OAuth: getOAuthProviders(), configureOAuthProvider()
1857
- \`\`\``;
2099
+ \`\`\`
2100
+
2101
+ ### Per-Channel Publishing
2102
+
2103
+ Categories, tags, brands, and metafield definitions are gated to specific
2104
+ vibe-coded sites \u2014 same control already exposed for products and coupons.
2105
+ **Explicit opt-in:** an entity is visible to a vibe-coded site only if it
2106
+ has been explicitly published to that connection. Entities with no publish
2107
+ rows are invisible to every site (the merchant must publish them via the
2108
+ dashboard or the admin SDK).
2109
+
2110
+ \`\`\`typescript
2111
+ // Publish to a specific vibe-coded site (admin mode):
2112
+ await admin.publishCategoryToVibeCodedSite('cat_id', 'conn_id');
2113
+ await admin.publishTagToVibeCodedSite('tag_id', 'conn_id');
2114
+ await admin.publishBrandToVibeCodedSite('brand_id', 'conn_id');
2115
+ await admin.publishMetafieldDefinitionToVibeCodedSite('def_id', 'conn_id');
2116
+
2117
+ // Unpublish (entity stays visible to other sites unless they also have publishes):
2118
+ await admin.unpublishCategoryFromVibeCodedSite('cat_id', 'conn_id');
2119
+ // ...same for tag/brand/metafield definition.
2120
+
2121
+ // Read which sites an entity is published to via list/get responses:
2122
+ const cat = await admin.getCategory('cat_id');
2123
+ cat.vibeCodedPublishes; // [{ connection: { id, name, connectionId } }, ...]
2124
+ \`\`\`
2125
+
2126
+ Cross-account isolation is enforced server-side: a publish call only
2127
+ succeeds when entity and connection belong to the same account. Cross-account
2128
+ calls fail with \`404 Not Found\`.
2129
+
2130
+ The vibe-coded read endpoints (used by storefront SDK calls in \`connectionId\`
2131
+ mode) automatically filter by these junction tables, so storefronts never see
2132
+ entities that weren't published to their site.`;
2133
+ }
2134
+ function getContactInquiriesSection() {
2135
+ return `## Contact Inquiries & Forms (optional)
2136
+
2137
+ Accept messages from one or more contact forms on your storefront. The merchant
2138
+ configures everything in the Brainerce dashboard under **Customers \u2192 Contact
2139
+ Forms**; submissions land in **Customers \u2192 Inquiries** and both sides receive
2140
+ email notifications.
2141
+
2142
+ **IMPORTANT for AI code generators:** the merchant OWNS the form shape. Do not
2143
+ hardcode labels, placeholders, help text, the submit button, or the success
2144
+ message. Render from the schema returned by \`contactForms.get()\` so the
2145
+ storefront reflects whatever the merchant configures \u2014 including new fields
2146
+ they add later, translations they add later, and the success message they
2147
+ write. This is the difference between "a contact form" and "THE merchant's
2148
+ contact form."
2149
+
2150
+ ### Two integration paths
2151
+
2152
+ 1. **Simple (legacy)** \u2014 pass \`{ name, email, subject, message }\` and submit.
2153
+ Works out of the box, no dashboard setup needed. Backed by a lazily-seeded
2154
+ default form keyed \`"main"\` with five built-in fields (\`name\`, \`email\`,
2155
+ \`phone\`, \`subject\`, \`message\`). Choose this only for throwaway demos.
2156
+ 2. **Flexible (recommended, default in \`npx create-brainerce-store\`)** \u2014
2157
+ merchants can configure multiple forms per store (e.g. \`main\`,
2158
+ \`newsletter\`, \`whatsapp_prechat\`), add custom fields (TEXT, TEXTAREA,
2159
+ EMAIL, PHONE, NUMBER, SELECT, MULTI_SELECT, CHECKBOX, URL, DATE), translate
2160
+ everything per locale, hide any non-essential built-in. Fetch the schema
2161
+ with \`contactForms.get(formKey, locale)\` and render dynamically.
2162
+
2163
+ ### Simple path (legacy shape)
2164
+
2165
+ \`\`\`typescript
2166
+ import type { CreateInquiryInput, CreateInquiryResponse } from 'brainerce';
2167
+
2168
+ const result = await brainerce.createInquiry({
2169
+ name: 'Jane Doe',
2170
+ email: 'jane@example.com',
2171
+ subject: 'Question about shipping',
2172
+ message: 'Hi, do you ship internationally?',
2173
+ phone: '+1-555-0100', // optional
2174
+ customerId: customer?.id, // optional \u2014 link to logged-in customer
2175
+ metadata: { page: '/contact' }, // optional
2176
+ });
2177
+ // \u2192 { id, status: 'NEW', createdAt }
2178
+ \`\`\`
2179
+
2180
+ ### Flexible path \u2014 end-to-end contract
2181
+
2182
+ **Endpoints:**
2183
+
2184
+ | Method | Path | Returns |
2185
+ | ------ | ----------------------------------------------------------------- | ------------------------------ |
2186
+ | GET | \`/stores/:storeId/contact-forms\` | \`ContactFormSummary[]\` |
2187
+ | GET | \`/stores/:storeId/contact-forms/:formKey?locale=xx\` | \`ContactFormPublic\` |
2188
+ | POST | \`/stores/:storeId/inquiries\` | \`CreateInquiryResponse\` |
2189
+
2190
+ All three are public (no API key). The SDK wraps them so you never call them
2191
+ directly \u2014 use \`brainerce.contactForms.list()\`, \`brainerce.contactForms.get()\`,
2192
+ and \`brainerce.createInquiry()\`.
2193
+
2194
+ \`\`\`typescript
2195
+ import type { ContactFormPublic } from 'brainerce';
2196
+
2197
+ // List active forms (optional \u2014 if you want a form picker or route-per-form setup)
2198
+ const forms = await brainerce.contactForms.list();
2199
+ // \u2192 [{ key: 'main', name: 'Contact us', isDefault: true }, ...]
2200
+
2201
+ // Fetch one form's schema \u2014 server pre-resolves translations for the locale
2202
+ // and strips every field the merchant marked isVisible=false.
2203
+ const form = await brainerce.contactForms.get('main', 'en');
2204
+ // \u2192 {
2205
+ // id, key, name, description?, submitButton, successMessage,
2206
+ // fields: [{ key, type, label, placeholder?, helpText?, isRequired,
2207
+ // enumValues?, validation?, defaultValue?, width? }, ...]
2208
+ // }
2209
+
2210
+ // Submit a keyed payload. Unknown keys are stripped, required fields are
2211
+ // enforced, and every value is validated against \`validation\` server-side.
2212
+ await brainerce.createInquiry({
2213
+ formKey: 'main',
2214
+ fields: {
2215
+ email: 'jane@example.com', // built-in keys
2216
+ message: 'Hi...',
2217
+ // ...any custom keys the merchant added via the dashboard
2218
+ },
2219
+ locale: 'en', // stored on the inquiry \u2014 lets staff filter by language
2220
+ sourceMetadata: { page: '/contact' }, // arbitrary provenance (UTM, referrer, etc.)
2221
+ });
2222
+ \`\`\`
2223
+
2224
+ Both shapes go to the same POST endpoint and may be mixed; \`fields\` wins when
2225
+ both provide the same key. Unknown keys (not defined on the form schema) are
2226
+ stripped server-side.
2227
+
2228
+ ### Dynamic rendering \u2014 reference implementation
2229
+
2230
+ Render every field type the merchant can pick. Keep this as a \`<DynamicField>\`
2231
+ component so the form is fully driven by \`schema.fields\`.
2232
+
2233
+ **Layout.** Each field carries an optional \`width\` hint:
2234
+
2235
+ | \`field.width\` | Meaning | Grid style (6-column grid) |
2236
+ | ------------- | ------- | -------------------------- |
2237
+ | \`'FULL'\` (default) | Full row | \`grid-column: span 6\` |
2238
+ | \`'HALF'\` | Half row | \`grid-column: span 3\` |
2239
+ | \`'THIRD'\` | One-third row | \`grid-column: span 2\` |
2240
+
2241
+ Stack fields to full width on small screens (< ~640 px).
2242
+
2243
+ **Required fields.** Show a red asterisk on required labels, validate
2244
+ **client-side** before calling \`createInquiry()\`, and show inline error
2245
+ messages. Do NOT rely only on the server returning 400.
2246
+
2247
+ \`\`\`tsx
2248
+ import type { ContactFormPublic, ContactFormPublicField } from 'brainerce';
2249
+
2250
+ type FieldValue = string | string[] | boolean;
2251
+
2252
+ function defaultValueFor(f: ContactFormPublicField): FieldValue {
2253
+ if (f.type === 'CHECKBOX') return false;
2254
+ if (f.type === 'MULTI_SELECT') return [];
2255
+ return f.defaultValue ?? '';
2256
+ }
2257
+
2258
+ function isEmpty(v: FieldValue): boolean {
2259
+ if (typeof v === 'string') return v.trim().length === 0;
2260
+ if (Array.isArray(v)) return v.length === 0;
2261
+ return v === false;
2262
+ }
2263
+
2264
+ // Map width \u2192 CSS grid column span (6-column grid)
2265
+ function widthClass(w?: string): string {
2266
+ switch (w) {
2267
+ case 'HALF': return 'grid-col-half'; // grid-column: span 3; on sm+, full on mobile
2268
+ case 'THIRD': return 'grid-col-third'; // grid-column: span 2; on sm+, full on mobile
2269
+ default: return 'grid-col-full'; // grid-column: span 6
2270
+ }
2271
+ }
2272
+
2273
+ function DynamicField({
2274
+ field,
2275
+ value,
2276
+ error,
2277
+ onChange,
2278
+ }: {
2279
+ field: ContactFormPublicField;
2280
+ value: FieldValue;
2281
+ error?: string;
2282
+ onChange: (v: FieldValue) => void;
2283
+ }) {
2284
+ const id = \`contact-\${field.key}\`;
2285
+ const { minLength, maxLength, min, max, pattern } = field.validation ?? {};
2286
+ const strVal = typeof value === 'string' ? value : '';
2287
+
2288
+ // Label \u2014 USE \`field.label\`, NEVER hardcode. Falls back to the key.
2289
+ const label = (
2290
+ <label htmlFor={id} className="mb-1.5 block text-sm font-medium">
2291
+ {field.label}
2292
+ {field.isRequired && <span aria-hidden className="text-red-500"> *</span>}
2293
+ </label>
2294
+ );
2295
+ const help = field.helpText ? <p className="mt-1 text-xs opacity-70">{field.helpText}</p> : null;
2296
+ const errorEl = error ? <p className="mt-1 text-xs text-red-500">{error}</p> : null;
2297
+
2298
+ // Outer div uses widthClass to control grid-column span
2299
+ switch (field.type) {
2300
+ case 'TEXTAREA':
2301
+ 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>);
2302
+ case 'EMAIL':
2303
+ 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>);
2304
+ case 'PHONE':
2305
+ 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>);
2306
+ case 'URL':
2307
+ 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>);
2308
+ case 'NUMBER':
2309
+ 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>);
2310
+ case 'DATE':
2311
+ 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>);
2312
+ case 'SELECT':
2313
+ 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>);
2314
+ case 'MULTI_SELECT': {
2315
+ const arr = Array.isArray(value) ? value : [];
2316
+ 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>);
2317
+ }
2318
+ case 'CHECKBOX':
2319
+ 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>);
2320
+ case 'TEXT':
2321
+ default:
2322
+ 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>);
2323
+ }
2324
+ }
2325
+
2326
+ export function ContactPage() {
2327
+ const [schema, setSchema] = useState<ContactFormPublic | null>(null);
2328
+ const [values, setValues] = useState<Record<string, FieldValue>>({});
2329
+ const [errors, setErrors] = useState<Record<string, string>>({});
2330
+ const [honeypot, setHoneypot] = useState('');
2331
+ const [sent, setSent] = useState(false);
2332
+ const [loading, setLoading] = useState(false);
2333
+
2334
+ // Read the current locale from the <html lang> attribute (or your own i18n context).
2335
+ const locale = typeof document !== 'undefined' ? document.documentElement.lang || undefined : undefined;
2336
+
2337
+ useEffect(() => {
2338
+ brainerce.contactForms.get('main', locale).then((form) => {
2339
+ setSchema(form);
2340
+ const initial: Record<string, FieldValue> = {};
2341
+ for (const f of form.fields) initial[f.key] = defaultValueFor(f);
2342
+ setValues(initial);
2343
+ });
2344
+ }, [locale]);
2345
+
2346
+ if (!schema) return null;
2347
+
2348
+ const onSubmit = async (e: React.FormEvent) => {
2349
+ e.preventDefault();
2350
+ if (loading) return;
2351
+ if (honeypot.trim().length > 0) { setSent(true); return; } // bot \u2192 silent success
2352
+
2353
+ // \u2500\u2500 Client-side required-field validation \u2500\u2500
2354
+ const newErrors: Record<string, string> = {};
2355
+ for (const f of schema.fields) {
2356
+ if (f.isRequired && isEmpty(values[f.key] ?? defaultValueFor(f))) {
2357
+ newErrors[f.key] = \`\${f.label} is required\`; // or pull from your i18n system
2358
+ }
2359
+ }
2360
+ if (Object.keys(newErrors).length > 0) {
2361
+ setErrors(newErrors);
2362
+ return; // block submission
2363
+ }
2364
+ setErrors({});
2365
+
2366
+ setLoading(true);
2367
+ try {
2368
+ const payload: Record<string, unknown> = {};
2369
+ for (const f of schema.fields) {
2370
+ const raw = values[f.key];
2371
+ if (isEmpty(raw)) continue;
2372
+ payload[f.key] = typeof raw === 'string' ? raw.trim() : raw;
2373
+ }
2374
+ await brainerce.createInquiry({ formKey: schema.key, fields: payload, locale });
2375
+ setSent(true);
2376
+ } finally {
2377
+ setLoading(false);
2378
+ }
2379
+ };
2380
+
2381
+ if (sent) {
2382
+ // RENDER THE MERCHANT'S success message \u2014 do not hardcode.
2383
+ return <div>{schema.successMessage}</div>;
2384
+ }
2385
+
2386
+ return (
2387
+ <form onSubmit={onSubmit} noValidate>
2388
+ <h1>{schema.name}</h1>
2389
+ {schema.description && <p>{schema.description}</p>}
2390
+
2391
+ {/* Honeypot \u2014 must be visually hidden from humans, not from bots */}
2392
+ <div aria-hidden style={{ position: 'absolute', left: '-10000px', width: 0, height: 0, overflow: 'hidden' }}>
2393
+ <label htmlFor="contact-honeypot">Leave this field empty</label>
2394
+ <input id="contact-honeypot" type="text" tabIndex={-1} autoComplete="off"
2395
+ value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
2396
+ </div>
2397
+
2398
+ {/* CSS grid \u2014 6 columns on sm+, 1 column on mobile */}
2399
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '1rem' }}>
2400
+ {schema.fields.map((field) => (
2401
+ <DynamicField key={field.key} field={field}
2402
+ value={values[field.key] ?? defaultValueFor(field)}
2403
+ error={errors[field.key]}
2404
+ onChange={(v) => setValues((p) => ({ ...p, [field.key]: v }))} />
2405
+ ))}
2406
+ </div>
2407
+
2408
+ <button type="submit" disabled={loading}>
2409
+ {loading ? '\u2026' : schema.submitButton}
2410
+ </button>
2411
+ </form>
2412
+ );
2413
+ }
2414
+ \`\`\`
2415
+
2416
+ CSS for the grid column helpers (or use the equivalent Tailwind / inline styles):
2417
+
2418
+ \`\`\`css
2419
+ .grid-col-full { grid-column: span 6; }
2420
+ .grid-col-half { grid-column: span 6; }
2421
+ .grid-col-third { grid-column: span 6; }
2422
+
2423
+ @media (min-width: 640px) {
2424
+ .grid-col-half { grid-column: span 3; }
2425
+ .grid-col-third { grid-column: span 2; }
2426
+ }
2427
+ \`\`\`
2428
+
2429
+ ### Rules
2430
+
2431
+ - **Rate limit:** 3 submissions / 60s per IP \u2014 show a friendly "try again later" message on HTTP 429.
2432
+ - **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\`.
2433
+ - **Built-in keys:** \`name\`, \`email\`, \`phone\`, \`subject\`, \`message\` always exist on the default form; the legacy \`createInquiry\` shape keeps working forever.
2434
+ - **Max values:** each field value is capped at 10 000 chars server-side. Validate client-side before submitting using \`field.validation.maxLength\`.
2435
+ - **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.
2436
+ - **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\`.
2437
+ - **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\`.
2438
+ - **Enum values:** SELECT and MULTI_SELECT always return \`enumValues\` (non-empty array). Render from \`enumValues\`, never a hardcoded list.
2439
+ - **Visibility:** the server strips fields with \`isVisible=false\`, so \`schema.fields\` only contains things to render.
2440
+ - **Origin check:** the endpoint validates \`Origin\` against the store's allowed origins. Test from your real storefront URL, not \`file://\` or localhost unless the merchant added it to allowed origins.
2441
+ - **Locale handling:** always pass \`locale\` to \`contactForms.get()\` and to \`createInquiry()\`. The staff inbox filters inquiries by language. Omit to fall back to the store's default language.
2442
+ - **Success message:** render \`schema.successMessage\` as-is. (Variable interpolation like \`{{customerName}}\` is not yet wired; any such placeholders currently render literally. Safe to use plain text.)
2443
+ - **Caching:** the schema GET is safe to cache per \`{storeId, formKey, locale}\`. 60 s feels live without hammering the API.
2444
+
2445
+ ### Multiple forms
2446
+
2447
+ If the merchant set up more than one form (e.g. a \`main\` form on \`/contact\`
2448
+ and a \`newsletter\` form embedded in the footer), render each form from its
2449
+ own \`contactForms.get(key, locale)\` call. The \`formKey\` you pass to
2450
+ \`createInquiry\` must match.`;
1858
2451
  }
1859
2452
  function getSectionByTopic(topic, connectionId, currency) {
1860
2453
  const cid = connectionId || "vc_YOUR_CONNECTION_ID";
@@ -1872,6 +2465,8 @@ function getSectionByTopic(topic, connectionId, currency) {
1872
2465
  return getCheckoutCustomFieldsSection();
1873
2466
  case "payment":
1874
2467
  return getPaymentProvidersSection();
2468
+ case "saved-payment-methods":
2469
+ return getSavedPaymentMethodsSection();
1875
2470
  case "auth":
1876
2471
  return getCustomerAuthSection();
1877
2472
  case "order-confirmation":
@@ -1884,6 +2479,8 @@ function getSectionByTopic(topic, connectionId, currency) {
1884
2479
  return getRecommendationsSection();
1885
2480
  case "product-customization-fields":
1886
2481
  return getProductCustomizationFieldsSection();
2482
+ case "modifier-groups":
2483
+ return getModifierGroupsSection();
1887
2484
  case "tax":
1888
2485
  return getTaxDisplaySection(cur);
1889
2486
  case "i18n":
@@ -1894,6 +2491,8 @@ function getSectionByTopic(topic, connectionId, currency) {
1894
2491
  return getTypeQuickReference();
1895
2492
  case "admin":
1896
2493
  return getAdminApiSection();
2494
+ case "inquiries":
2495
+ return getContactInquiriesSection();
1897
2496
  case "all":
1898
2497
  return [
1899
2498
  "# Brainerce SDK \u2014 full topic dump",
@@ -1962,6 +2561,10 @@ function getSectionByTopic(topic, connectionId, currency) {
1962
2561
  "",
1963
2562
  "---",
1964
2563
  "",
2564
+ getModifierGroupsSection(),
2565
+ "",
2566
+ "---",
2567
+ "",
1965
2568
  getTaxDisplaySection(cur),
1966
2569
  "",
1967
2570
  "---",
@@ -1970,10 +2573,14 @@ function getSectionByTopic(topic, connectionId, currency) {
1970
2573
  "",
1971
2574
  "---",
1972
2575
  "",
1973
- getAdminApiSection()
2576
+ getAdminApiSection(),
2577
+ "",
2578
+ "---",
2579
+ "",
2580
+ getContactInquiriesSection()
1974
2581
  ].join("\n");
1975
2582
  default:
1976
- return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, all`;
2583
+ return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, all`;
1977
2584
  }
1978
2585
  }
1979
2586
 
@@ -1999,13 +2606,22 @@ var GET_SDK_DOCS_SCHEMA = {
1999
2606
  "type-reference",
2000
2607
  "i18n",
2001
2608
  "admin",
2609
+ "inquiries",
2002
2610
  "all"
2003
2611
  ]).describe("The SDK documentation topic to retrieve"),
2004
- connectionId: z.string().optional().describe("Vibe-coded connection ID (starts with vc_). Used to personalize setup code."),
2612
+ salesChannelId: z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
2613
+ /** @deprecated alias of salesChannelId */
2614
+ connectionId: z.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat"),
2005
2615
  currency: z.string().optional().describe("Store currency code (e.g., USD, ILS, EUR). Used in price formatting examples.")
2006
2616
  };
2007
2617
  async function handleGetSdkDocs(args) {
2008
- const content = getSectionByTopic(args.topic, args.connectionId, args.currency);
2618
+ const id = args.salesChannelId ?? args.connectionId;
2619
+ if (!args.salesChannelId && args.connectionId) {
2620
+ console.warn(
2621
+ "get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
2622
+ );
2623
+ }
2624
+ const content = getSectionByTopic(args.topic, id, args.currency);
2009
2625
  return {
2010
2626
  content: [{ type: "text", text: content }]
2011
2627
  };
@@ -2044,7 +2660,7 @@ interface Product {
2044
2660
  attributeId: string;
2045
2661
  attributeOptionId: string;
2046
2662
  platform: string;
2047
- attribute: { id: string; name: string; displayType?: 'DEFAULT' | 'COLOR_SWATCH' | 'IMAGE_SWATCH' } | null;
2663
+ attribute: { id: string; name: string; displayType?: 'DEFAULT' | 'COLOR_SWATCH' | 'IMAGE_SWATCH' | 'MIXED_SWATCH' } | null;
2048
2664
  attributeOption: { id: string; name: string; value?: string | null; swatchColor?: string | null; swatchColor2?: string | null; swatchImageUrl?: string | null } | null;
2049
2665
  }>;
2050
2666
  createdAt: string;
@@ -2053,6 +2669,8 @@ interface Product {
2053
2669
 
2054
2670
  // Use getProductSwatches(product) to get grouped swatch data for storefront rendering.
2055
2671
  // Returns Array<{ attributeName, displayType, options: Array<{ name, swatchColor?, swatchColor2?, swatchImageUrl? }> }>
2672
+ // displayType rendering: COLOR_SWATCH \u2192 color circle (swatchColor/swatchColor2); IMAGE_SWATCH \u2192 image thumbnail (swatchImageUrl);
2673
+ // MIXED_SWATCH \u2192 per-option: render swatchImageUrl if set, else swatchColor if set, else text only.
2056
2674
 
2057
2675
  interface ProductImage {
2058
2676
  url: string;
@@ -2133,6 +2751,10 @@ interface ProductQueryParams {
2133
2751
  tags?: string | string[];
2134
2752
  minPrice?: number;
2135
2753
  maxPrice?: number;
2754
+ // Filter by custom-field (metafield) values. Keys = definition.key,
2755
+ // values = accepted values. Only definitions with filterable=true and
2756
+ // type SELECT/MULTI_SELECT/BOOLEAN are honored. AND across keys, OR within.
2757
+ metafields?: Record<string, string | string[]>;
2136
2758
  sortBy?: 'name' | 'price' | 'createdAt';
2137
2759
  sortOrder?: 'asc' | 'desc';
2138
2760
  }
@@ -2550,6 +3172,36 @@ interface PaymentStatus {
2550
3172
  error?: string;
2551
3173
  }
2552
3174
 
3175
+ // ---- Saved Payment Methods (vaulted cards) ----
3176
+ // Display-only summary of a customer's vaulted payment method. The
3177
+ // underlying provider token is encrypted at rest in the platform DB
3178
+ // and NEVER returned through the SDK.
3179
+ //
3180
+ // To opt into vaulting at checkout, pass saveCard: true to
3181
+ // createPaymentIntent (only honored for logged-in customers).
3182
+ //
3183
+ // To list / remove saved methods, see:
3184
+ // client.listSavedPaymentMethods(storeId, customerId)
3185
+ // client.removeSavedPaymentMethod(storeId, customerId, methodId)
3186
+
3187
+ interface SavedPaymentMethodSummary {
3188
+ id: string;
3189
+ customerId: string;
3190
+ appInstallationId: string;
3191
+ paymentMethod: string; // 'credit_card' | 'paypal' | 'bank_account'
3192
+ brand: string | null;
3193
+ last4: string | null;
3194
+ expMonth: number | null;
3195
+ expYear: number | null;
3196
+ isDefault: boolean;
3197
+ status: string; // 'active' | 'expired' | 'invalid'
3198
+ failureReason: string | null;
3199
+ lastUsedAt: string | null;
3200
+ expiresAt: string | null;
3201
+ createdAt: string;
3202
+ updatedAt: string;
3203
+ }
3204
+
2553
3205
  interface WaitForOrderResult {
2554
3206
  success: boolean;
2555
3207
  status: PaymentStatus; // Access: result.status.orderNumber
@@ -2649,16 +3301,267 @@ interface CartUpgradeSuggestion {
2649
3301
  priceDelta: string;
2650
3302
  deltaPercent: number;
2651
3303
  }
2652
- interface CartBundleOffer {
3304
+ interface CartBundleOfferOfferedProduct {
2653
3305
  id: string;
2654
- bundleProduct: ProductRecommendation;
3306
+ name: string;
3307
+ slug: string | null;
3308
+ basePrice: string;
3309
+ salePrice: string | null;
3310
+ images: Array<{ url: string }>;
3311
+ type: string;
2655
3312
  originalPrice: string;
2656
3313
  discountedPrice: string;
3314
+ }
3315
+ interface CartBundleOffer {
3316
+ id: string;
3317
+ name: string;
3318
+ description: string | null;
3319
+ // productIds[0] = trigger product (must be in cart for the bundle to surface);
3320
+ // productIds[1..] = offered together at the bundle discount.
3321
+ triggerProductId: string;
3322
+ productIds: string[];
3323
+ // offeredProducts = productIds[1..] minus those already in cart, each with
3324
+ // its own original/discounted price applied.
3325
+ offeredProducts: CartBundleOfferOfferedProduct[];
2657
3326
  discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
2658
- discountValue: number;
2659
- requiresVariantSelection: boolean;
2660
- lockedVariant?: { id: string; name?: string };
3327
+ discountValue: string;
3328
+ totalOriginalPrice: string;
3329
+ totalDiscountedPrice: string;
2661
3330
  }`;
3331
+ var INQUIRIES_TYPES = `// ---- Contact Inquiries & Forms ----
3332
+
3333
+ // Two shapes \u2014 legacy and flexible. The two may be mixed; \`fields\` wins on key collision.
3334
+ interface CreateInquiryInput {
3335
+ // Legacy shape (still supported forever, backed by default "main" form)
3336
+ name?: string; // max 120 chars (if provided)
3337
+ email?: string; // must be valid email if provided
3338
+ subject?: string; // max 200 chars
3339
+ message?: string; // max 10000 chars
3340
+ phone?: string;
3341
+
3342
+ // Flexible shape
3343
+ formKey?: string; // defaults to "main"; merchant-defined keys e.g. "newsletter"
3344
+ fields?: Record<string, unknown>; // bag of values keyed by field key (built-in or custom)
3345
+ locale?: string; // e.g. "en", "he" \u2014 stored on the inquiry
3346
+ sourceMetadata?: Record<string, unknown>; // arbitrary context (e.g. { page: '/contact', campaign: 'fall-2026' })
3347
+
3348
+ // Shared
3349
+ customerId?: string; // link to logged-in customer
3350
+ metadata?: Record<string, unknown>; // deprecated alias of sourceMetadata
3351
+ }
3352
+
3353
+ interface CreateInquiryResponse {
3354
+ id: string;
3355
+ status: 'NEW';
3356
+ createdAt: string; // ISO datetime
3357
+ }
3358
+
3359
+ // ---- Form schema (for dynamic rendering) ----
3360
+
3361
+ type ContactFormFieldType =
3362
+ | 'TEXT' | 'TEXTAREA' | 'EMAIL' | 'PHONE' | 'NUMBER'
3363
+ | 'SELECT' | 'MULTI_SELECT' | 'CHECKBOX' | 'URL' | 'DATE';
3364
+
3365
+ interface ContactFormFieldValidation {
3366
+ minLength?: number;
3367
+ maxLength?: number;
3368
+ min?: number;
3369
+ max?: number;
3370
+ pattern?: string; // regex string
3371
+ patternMessage?: string;
3372
+ }
3373
+
3374
+ interface ContactFormPublicField {
3375
+ key: string; // stable identifier, e.g. "email", "company"
3376
+ type: ContactFormFieldType;
3377
+ label: string; // already localized for the requested locale
3378
+ placeholder?: string; // already localized
3379
+ helpText?: string; // already localized
3380
+ isRequired: boolean;
3381
+ enumValues?: { value: string; label: string }[]; // present (non-empty) for SELECT / MULTI_SELECT
3382
+ validation?: ContactFormFieldValidation;
3383
+ defaultValue?: string;
3384
+ width?: 'FULL' | 'HALF' | 'THIRD'; // layout hint \u2014 FULL = full row, HALF = half row, THIRD = one-third row
3385
+ }
3386
+
3387
+ interface ContactFormPublic {
3388
+ id: string;
3389
+ key: string; // e.g. "main", "newsletter"
3390
+ name: string; // already localized \u2014 use as form heading
3391
+ description?: string; // already localized \u2014 use as subtitle
3392
+ submitButton: string; // already localized \u2014 use as submit label
3393
+ successMessage: string; // already localized \u2014 render after submit succeeds
3394
+ fields: ContactFormPublicField[]; // in display order; hidden fields already filtered out
3395
+ }
3396
+
3397
+ interface ContactFormSummary {
3398
+ key: string;
3399
+ name: string;
3400
+ isDefault: boolean;
3401
+ }
3402
+
3403
+ // Field-type \u2192 HTML mapping for dynamic rendering
3404
+ // ------------------------------------------------------------------
3405
+ // TEXT \u2192 <input type="text" ... pattern?={validation.pattern}>
3406
+ // TEXTAREA \u2192 <textarea rows={6} ...>
3407
+ // EMAIL \u2192 <input type="email" autoComplete="email" ...>
3408
+ // PHONE \u2192 <input type="tel" autoComplete="tel" ...>
3409
+ // NUMBER \u2192 <input type="number" min={validation.min} max={validation.max}>
3410
+ // URL \u2192 <input type="url" ...>
3411
+ // DATE \u2192 <input type="date" ...> (value is ISO yyyy-MM-dd)
3412
+ // SELECT \u2192 <select>{enumValues.map(...)}</select> \u2014 always rendered from enumValues
3413
+ // MULTI_SELECT \u2192 multiple <input type="checkbox">, value is string[]
3414
+ // CHECKBOX \u2192 single <input type="checkbox">, value is boolean
3415
+ // ------------------------------------------------------------------
3416
+ //
3417
+ // Layout: render fields inside a CSS grid container.
3418
+ // width='FULL' (default) \u2192 span entire row
3419
+ // width='HALF' \u2192 span half the row (two HALF fields sit side-by-side)
3420
+ // width='THIRD' \u2192 span one-third of the row (three THIRD fields sit side-by-side)
3421
+ // Use a 6-column grid for clean divisibility:
3422
+ // FULL \u2192 col-span-6 | HALF \u2192 col-span-3 | THIRD \u2192 col-span-2
3423
+ // Stack to full width on small screens (< sm breakpoint).
3424
+ //
3425
+ // Required fields: show a red asterisk (*) next to the label, validate
3426
+ // client-side before submission, and display inline error messages for
3427
+ // any empty required field. Do NOT rely only on the server returning 400.
3428
+ // ------------------------------------------------------------------
3429
+
3430
+ // SDK methods
3431
+ // await brainerce.createInquiry(input) \u2192 POST /stores/{storeId}/inquiries
3432
+ // await brainerce.contactForms.list() \u2192 GET /stores/{storeId}/contact-forms
3433
+ // await brainerce.contactForms.get(key?, locale?) \u2192 GET /stores/{storeId}/contact-forms/{key}?locale={locale}
3434
+ //
3435
+ // Rules
3436
+ // - Rate limit: 3 submissions / 60s per IP \u2014 handle 429 responses gracefully
3437
+ // - Honeypot: always render an invisible field named \`honeypot\` and never send it
3438
+ // - Always pass \`locale\` \u2014 inbox filters inquiries by language, and schema labels come back translated
3439
+ // - Render \`schema.name\` / \`description\` / \`submitButton\` / \`successMessage\` directly \u2014 do NOT hardcode copy
3440
+ // - Unknown field keys are stripped server-side \u2014 safe to send extras during dev`;
3441
+ var MODIFIER_GROUPS_TYPES = `// ---- Modifier Groups (Restaurant / Build-Your-Own) ----
3442
+ // Modifier groups are merchant-defined option blocks attached to a product
3443
+ // (toppings, sauce, bread type, \u2026). They differ from product.customizationFields:
3444
+ // modifier groups are STRUCTURED priced choices validated server-side, while
3445
+ // customizationFields are arbitrary buyer input (text/photo/color).
3446
+ //
3447
+ // Money fields are decimal STRINGS on the wire \u2014 "5.00", "-2.00" (downsell).
3448
+ // Never JSON Number. Use parseFloat() only at display time. Do not compute
3449
+ // the line total client-side; the server runs free-allocation and returns
3450
+ // cart.items[i].unitPrice + .modifiers[] + .modifiersTotal.
3451
+
3452
+ export type ModifierSelectionType = 'SINGLE' | 'MULTIPLE';
3453
+
3454
+ export type FreeAllocationPolicy = 'EXPENSIVE_FREE' | 'CHEAPEST_FREE' | 'SELECTION_ORDER';
3455
+
3456
+ export interface Modifier {
3457
+ id: string;
3458
+ name: string;
3459
+ description?: string;
3460
+ /** Decimal string. Negative values = downsell modifiers ("-2.00"). */
3461
+ priceDelta: string;
3462
+ sku?: string;
3463
+ image?: { url: string; thumbnailUrl?: string; alt?: string };
3464
+ position: number;
3465
+ /** Pre-checked on first render. */
3466
+ isDefault: boolean;
3467
+ /** false = sold out \u2014 disable in UI with a "Sold out" badge. */
3468
+ available: boolean;
3469
+ /** When true, never applied as a free selection \u2014 always charges priceDelta even when freeQuantity > 0 on the group. */
3470
+ excludeFromFree?: boolean;
3471
+ /** Nested combo: opens a sub-flow; depth \u2264 3 enforced server-side. */
3472
+ referencedProductId?: string;
3473
+ translations?: Record<string, { name?: string; description?: string }>;
3474
+ }
3475
+
3476
+ export interface ModifierGroup {
3477
+ id: string;
3478
+ /**
3479
+ * Set when fetched in a product context (the ProductModifierGroup row id).
3480
+ * Use this to update or detach the attachment without reattaching the group.
3481
+ */
3482
+ attachmentId?: string;
3483
+ /** Customer-facing canonical name. */
3484
+ name: string;
3485
+ /**
3486
+ * Admin-only disambiguator \u2014 NEVER present in storefront responses.
3487
+ * If your client code reads this, you're hitting an admin endpoint by mistake.
3488
+ */
3489
+ internalName?: string;
3490
+ description?: string;
3491
+ selectionType: ModifierSelectionType;
3492
+ /** Effective minimum after any per-attach / per-variant overrides. */
3493
+ min: number;
3494
+ /** Effective maximum; null = unlimited. **0 = group hidden for this variant** (PRD \xA77.2.2). */
3495
+ max?: number | null;
3496
+ freeQuantity: number;
3497
+ required: boolean;
3498
+ freeAllocationPolicy: FreeAllocationPolicy;
3499
+ modifiers: Modifier[];
3500
+ /** Effective default selections (after attachment-level overrides). */
3501
+ defaultModifierIds: string[];
3502
+ translations?: Record<string, { name?: string; description?: string }>;
3503
+ }
3504
+
3505
+ /** Customer-side selection payload \u2014 modifierIds in click-order. */
3506
+ export interface ModifierSelection {
3507
+ modifierGroupId: string;
3508
+ modifierIds: string[];
3509
+ }
3510
+
3511
+ /** Per-line modifier breakdown surfaced on cart.items[i] / order.items[i]. */
3512
+ export interface CartItemModifierLine {
3513
+ modifierId: string;
3514
+ /** Snapshot of the modifier's name at the time the line was added. */
3515
+ name: string;
3516
+ /** Decimal string snapshot of the priceDelta at the time the line was added. */
3517
+ priceDelta: string;
3518
+ /** True if this modifier consumed one of the group's free slots. */
3519
+ freeApplied: boolean;
3520
+ }
3521
+
3522
+ /**
3523
+ * Stable error codes returned in the structured 400 envelope when a cart
3524
+ * payload fails server-side validation. The SDK exposes the envelope on
3525
+ * BrainerceError.details \u2014 switch on details.code === 'MODIFIER_VALIDATION_FAILED'
3526
+ * first, then iterate details.errors[].
3527
+ */
3528
+ export type ModifierValidationCode =
3529
+ | 'REQUIRED_GROUP_MISSING'
3530
+ | 'MIN_SELECTIONS_NOT_MET'
3531
+ | 'MAX_SELECTIONS_EXCEEDED'
3532
+ | 'SINGLE_GROUP_MULTIPLE_PICKS'
3533
+ | 'UNKNOWN_MODIFIER'
3534
+ | 'UNKNOWN_GROUP'
3535
+ | 'MODIFIER_DISABLED_FOR_VARIANT'
3536
+ | 'MODIFIER_NOT_AVAILABLE'
3537
+ | 'NESTED_DEPTH_EXCEEDED'
3538
+ | 'NESTED_REQUIRES_PRODUCT_REF'
3539
+ | 'INVALID_PRICE_DELTA'
3540
+ | 'MODIFIER_PRICE_FLOOR_VIOLATED';
3541
+
3542
+ export interface ModifierValidationError {
3543
+ code: ModifierValidationCode;
3544
+ message: string;
3545
+ modifierGroupId?: string;
3546
+ modifierId?: string;
3547
+ }
3548
+
3549
+ // Cart DTOs gain optional selections + nestedByModifierId \u2014 see CART_TYPES above.
3550
+ // Add to cart with selections:
3551
+ //
3552
+ // await client.smartAddToCart({
3553
+ // productId,
3554
+ // variantId,
3555
+ // quantity: 1,
3556
+ // selections: [
3557
+ // { modifierGroupId: 'mg_bread', modifierIds: ['m_thick'] },
3558
+ // { modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_bacon'] },
3559
+ // ],
3560
+ // });
3561
+ //
3562
+ // The cart line then carries:
3563
+ // cart.items[i].modifiers \u2014 CartItemModifierLine[]
3564
+ // cart.items[i].modifiersTotal \u2014 decimal string of the paid (non-free) deltas`;
2662
3565
  var TYPES_BY_DOMAIN = {
2663
3566
  products: PRODUCTS_TYPES,
2664
3567
  cart: CART_TYPES,
@@ -2666,7 +3569,9 @@ var TYPES_BY_DOMAIN = {
2666
3569
  orders: ORDERS_TYPES,
2667
3570
  customers: CUSTOMERS_TYPES,
2668
3571
  payments: PAYMENTS_TYPES,
2669
- helpers: HELPERS_TYPES
3572
+ helpers: HELPERS_TYPES,
3573
+ inquiries: INQUIRIES_TYPES,
3574
+ "modifier-groups": MODIFIER_GROUPS_TYPES
2670
3575
  };
2671
3576
  function getTypesByDomain(domain) {
2672
3577
  if (domain === "all") {
@@ -2687,7 +3592,17 @@ var AVAILABLE_DOMAINS = Object.keys(TYPES_BY_DOMAIN);
2687
3592
  var GET_TYPE_DEFINITIONS_NAME = "get-type-definitions";
2688
3593
  var GET_TYPE_DEFINITIONS_DESCRIPTION = "Get TypeScript type definitions from the Brainerce SDK, segmented by domain. Use this when you need to understand the exact shape of objects like Product, Cart, Checkout, Order, etc.";
2689
3594
  var GET_TYPE_DEFINITIONS_SCHEMA = {
2690
- domain: z2.enum(["products", "cart", "checkout", "orders", "customers", "payments", "helpers", "all"]).describe(
3595
+ domain: z2.enum([
3596
+ "products",
3597
+ "cart",
3598
+ "checkout",
3599
+ "orders",
3600
+ "customers",
3601
+ "payments",
3602
+ "helpers",
3603
+ "inquiries",
3604
+ "all"
3605
+ ]).describe(
2691
3606
  'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse.'
2692
3607
  )
2693
3608
  };
@@ -2722,7 +3637,12 @@ var GET_CODE_EXAMPLE_SCHEMA = {
2722
3637
  "reservation-countdown",
2723
3638
  "search-autocomplete-debounce",
2724
3639
  "i18n-set-locale",
2725
- "order-history-full"
3640
+ "order-history-full",
3641
+ "modifier-groups-render",
3642
+ "cart-add-with-selections",
3643
+ "modifier-validation-error-handling",
3644
+ "checkout-price-drift",
3645
+ "cart-item-modifier-display"
2726
3646
  ]).describe("The SDK operation to get a snippet for.")
2727
3647
  };
2728
3648
  var SNIPPETS = {
@@ -2730,7 +3650,10 @@ var SNIPPETS = {
2730
3650
  import { BrainerceClient } from 'brainerce';
2731
3651
 
2732
3652
  export const client = new BrainerceClient({
2733
- connectionId: process.env.BRAINERCE_CONNECTION_ID!, // vc_*
3653
+ // Read either env var name (the new one is preferred; the old one is a soft
3654
+ // alias kept for backwards compatibility \u2014 both are accepted by the SDK).
3655
+ salesChannelId:
3656
+ process.env.BRAINERCE_SALES_CHANNEL_ID! ?? process.env.BRAINERCE_CONNECTION_ID!, // vc_*
2734
3657
  });
2735
3658
 
2736
3659
  // If the store has i18n enabled, set the locale at app start based on
@@ -3150,7 +4073,418 @@ for (const order of orders) {
3150
4073
 
3151
4074
  // All sections above are conditional. Absent data = section not rendered \u2014
3152
4075
  // never show empty placeholders. The create-brainerce-store template's
3153
- // src/components/account/order-history.tsx is the reference implementation.`
4076
+ // src/components/account/order-history.tsx is the reference implementation.`,
4077
+ "modifier-groups-render": `// Render modifier groups on the product detail page (toppings / sauce /
4078
+ // build-your-own). The data lives on product.modifierGroups \u2014 only present
4079
+ // for restaurant / customizable products.
4080
+ import { useState } from 'react';
4081
+ import type { ModifierGroup, Product } from 'brainerce';
4082
+
4083
+ function ModifierGroups({ product }: { product: Product }) {
4084
+ const groups: ModifierGroup[] = product.modifierGroups ?? [];
4085
+ if (groups.length === 0) return null; // not a customizable product
4086
+
4087
+ // Local state: selected modifier IDs per group, in click-order.
4088
+ const [selections, setSelections] = useState<Record<string, string[]>>(() =>
4089
+ buildInitialSelections(groups)
4090
+ );
4091
+
4092
+ return (
4093
+ <>
4094
+ {groups.map((group) => {
4095
+ // PRD \xA77.2.2: max === 0 means "hidden for this variant" \u2014 skip entirely.
4096
+ if (group.max === 0) return null;
4097
+
4098
+ const isSingle = group.selectionType === 'SINGLE';
4099
+ const inputType = isSingle ? 'radio' : 'checkbox';
4100
+ const sorted = [...group.modifiers].sort((a, b) => a.position - b.position);
4101
+ const picks = selections[group.id] ?? [];
4102
+ const usedFree = Math.min(picks.length, group.freeQuantity);
4103
+
4104
+ const toggle = (modifierId: string, checked: boolean) => {
4105
+ setSelections((prev) => {
4106
+ const cur = prev[group.id] ?? [];
4107
+ if (isSingle) return { ...prev, [group.id]: checked ? [modifierId] : [] };
4108
+ if (checked) {
4109
+ if (group.max != null && cur.length >= group.max) return prev; // at cap
4110
+ return { ...prev, [group.id]: [...cur, modifierId] };
4111
+ }
4112
+ return { ...prev, [group.id]: cur.filter((id) => id !== modifierId) };
4113
+ });
4114
+ };
4115
+
4116
+ return (
4117
+ <fieldset key={group.id}>
4118
+ <legend>
4119
+ {group.name}{group.required && ' *'}
4120
+ </legend>
4121
+ {group.freeQuantity > 0 && (
4122
+ <p>{usedFree} of {group.freeQuantity} free</p>
4123
+ )}
4124
+ {sorted.map((m) => (
4125
+ <label key={m.id}>
4126
+ <input
4127
+ type={inputType}
4128
+ name={\`mg-\${group.id}\`}
4129
+ value={m.id}
4130
+ checked={picks.includes(m.id)}
4131
+ disabled={!m.available}
4132
+ onChange={(e) => toggle(m.id, e.target.checked)}
4133
+ />
4134
+ {m.name}
4135
+ {parseFloat(m.priceDelta) !== 0 && (
4136
+ <span> {parseFloat(m.priceDelta) > 0 ? '+' : ''}{m.priceDelta}</span>
4137
+ )}
4138
+ {!m.available && <span> (Sold out)</span>}
4139
+ </label>
4140
+ ))}
4141
+ </fieldset>
4142
+ );
4143
+ })}
4144
+ </>
4145
+ );
4146
+ }
4147
+
4148
+ // Initial state: prefer per-attach defaultModifierIds; fall back to
4149
+ // modifier.isDefault flags. Filter sold-out modifiers.
4150
+ function buildInitialSelections(groups: ModifierGroup[]): Record<string, string[]> {
4151
+ const out: Record<string, string[]> = {};
4152
+ for (const group of groups) {
4153
+ if (group.max === 0) continue;
4154
+ const fromAttach = group.defaultModifierIds ?? [];
4155
+ const fromIsDefault = group.modifiers
4156
+ .filter((m) => m.isDefault && m.available)
4157
+ .map((m) => m.id);
4158
+ const merged =
4159
+ fromAttach.length > 0
4160
+ ? fromAttach.filter((id) => group.modifiers.some((m) => m.id === id && m.available))
4161
+ : fromIsDefault;
4162
+ const capped = group.selectionType === 'SINGLE' ? merged.slice(0, 1) : merged;
4163
+ if (capped.length > 0) out[group.id] = capped;
4164
+ }
4165
+ return out;
4166
+ }
4167
+
4168
+ // PRICE-DELTA RULES:
4169
+ // - "5.00" \u2192 +$5 added to unit price
4170
+ // - "-2.00" \u2192 downsell: subtracts $2; never consumes a free slot
4171
+ // - "0.00" \u2192 free option; render no price label
4172
+ // Server enforces unitPrice >= 0; rejects negative deltas combined with
4173
+ // referencedProductId. Do NOT compute the line total client-side \u2014 the
4174
+ // server runs free-allocation and returns cart.items[i].unitPrice.
4175
+
4176
+ `,
4177
+ "cart-add-with-selections": `// Pass modifier-group selections on add-to-cart. The server validates
4178
+ // against the effective rules and computes the final unitPrice (base +
4179
+ // paid modifiers, after the free-allocation policy runs).
4180
+ import { client } from './brainerce';
4181
+ import type { ModifierSelection } from 'brainerce';
4182
+
4183
+ async function addPizzaToCart(
4184
+ productId: string,
4185
+ variantId: string,
4186
+ selectionsByGroup: Record<string, string[]>
4187
+ ) {
4188
+ // Adapter: shape used in component state \u2192 wire format the SDK accepts.
4189
+ const selections: ModifierSelection[] = Object.entries(selectionsByGroup)
4190
+ .filter(([, modifierIds]) => modifierIds.length > 0)
4191
+ .map(([modifierGroupId, modifierIds]) => ({ modifierGroupId, modifierIds }));
4192
+
4193
+ // modifierIds is in CLICK-ORDER \u2014 used by the SELECTION_ORDER free-allocation
4194
+ // policy. Don't sort it; preserve the order the customer clicked.
4195
+
4196
+ const cart = await client.smartAddToCart({
4197
+ productId,
4198
+ variantId,
4199
+ quantity: 1,
4200
+ selections,
4201
+ });
4202
+
4203
+ // Read the snapshot back off the new cart line.
4204
+ const line = cart.items[cart.items.length - 1];
4205
+ // line.modifiers \u2192 CartItemModifierLine[] with { modifierId, name, priceDelta, freeApplied }
4206
+ // line.modifiersTotal \u2192 decimal string of paid (non-free) deltas
4207
+ // line.unitPrice \u2192 final unit price including all paid modifiers
4208
+ console.log('Free applied:', line.modifiers?.filter((m) => m.freeApplied).map((m) => m.name));
4209
+ }
4210
+
4211
+ // EDITING SELECTIONS LATER (PRD \xA77.2.3 \u2014 idempotent replacement):
4212
+ // PATCH the cart item with a fresh selections array. The server deletes ALL
4213
+ // existing CartItemModifier rows and recreates them in the same transaction.
4214
+ // To leave selections untouched (e.g., quantity-only update), omit them.
4215
+ async function changeToppings(cartId: string, itemId: string, newToppingIds: string[]) {
4216
+ await client.updateCartItem(cartId, itemId, {
4217
+ quantity: 1,
4218
+ selections: [{ modifierGroupId: 'mg_toppings', modifierIds: newToppingIds }],
4219
+ });
4220
+ }
4221
+
4222
+ // NESTED COMBOS (depth \u2264 3): when a picked modifier carries
4223
+ // referencedProductId, fetch that product's own modifierGroups, collect the
4224
+ // nested selections, and pass them keyed by the PARENT modifier id.
4225
+ async function addCombo(productId: string, mainBurger: string) {
4226
+ await client.smartAddToCart({
4227
+ productId,
4228
+ quantity: 1,
4229
+ selections: [
4230
+ { modifierGroupId: 'mg_main', modifierIds: [mainBurger] }, // the burger
4231
+ { modifierGroupId: 'mg_drink', modifierIds: ['m_cola'] },
4232
+ ],
4233
+ nestedByModifierId: {
4234
+ [mainBurger]: [
4235
+ { modifierGroupId: 'mg_doneness', modifierIds: ['m_medium'] },
4236
+ { modifierGroupId: 'mg_cheese', modifierIds: ['m_cheddar'] },
4237
+ ],
4238
+ },
4239
+ });
4240
+ }`,
4241
+ "modifier-validation-error-handling": `// Surface MODIFIER_VALIDATION_FAILED to the user. The SDK throws
4242
+ // BrainerceError on HTTP 400; the structured envelope is on .details.
4243
+ import { client } from './brainerce';
4244
+ import type { ModifierSelection } from 'brainerce';
4245
+
4246
+ interface ModifierValidationError {
4247
+ code:
4248
+ | 'REQUIRED_GROUP_MISSING'
4249
+ | 'MIN_SELECTIONS_NOT_MET'
4250
+ | 'MAX_SELECTIONS_EXCEEDED'
4251
+ | 'SINGLE_GROUP_MULTIPLE_PICKS'
4252
+ | 'UNKNOWN_MODIFIER'
4253
+ | 'UNKNOWN_GROUP'
4254
+ | 'MODIFIER_DISABLED_FOR_VARIANT'
4255
+ | 'MODIFIER_NOT_AVAILABLE'
4256
+ | 'NESTED_DEPTH_EXCEEDED'
4257
+ | 'NESTED_REQUIRES_PRODUCT_REF'
4258
+ | 'INVALID_PRICE_DELTA'
4259
+ | 'MODIFIER_PRICE_FLOOR_VIOLATED';
4260
+ message: string;
4261
+ modifierGroupId?: string;
4262
+ modifierId?: string;
4263
+ }
4264
+
4265
+ async function tryAddToCart(productId: string, selections: ModifierSelection[]) {
4266
+ try {
4267
+ await client.smartAddToCart({ productId, quantity: 1, selections });
4268
+ return { ok: true as const };
4269
+ } catch (err) {
4270
+ const e = err as {
4271
+ statusCode?: number;
4272
+ details?: { code?: string; errors?: ModifierValidationError[] };
4273
+ };
4274
+
4275
+ if (e.statusCode === 400 && e.details?.code === 'MODIFIER_VALIDATION_FAILED') {
4276
+ // Surface each issue inline. groupId / modifierId let you highlight the
4277
+ // specific control the customer needs to fix.
4278
+ const issues = e.details.errors ?? [];
4279
+ const messages = issues.map((i) => formatIssue(i));
4280
+ return { ok: false as const, issues, messages };
4281
+ }
4282
+
4283
+ // Some other error (network, 500, etc.) \u2014 re-throw to a generic handler.
4284
+ throw err;
4285
+ }
4286
+ }
4287
+
4288
+ function formatIssue(issue: ModifierValidationError): string {
4289
+ switch (issue.code) {
4290
+ case 'REQUIRED_GROUP_MISSING':
4291
+ return 'Please pick at least one option from this group.';
4292
+ case 'MIN_SELECTIONS_NOT_MET':
4293
+ case 'MAX_SELECTIONS_EXCEEDED':
4294
+ case 'SINGLE_GROUP_MULTIPLE_PICKS':
4295
+ return issue.message; // server's message already says "Pick at least N" / "Pick at most N"
4296
+ case 'UNKNOWN_MODIFIER':
4297
+ case 'UNKNOWN_GROUP':
4298
+ case 'MODIFIER_DISABLED_FOR_VARIANT':
4299
+ case 'MODIFIER_NOT_AVAILABLE':
4300
+ // The catalog moved under us \u2014 refetch the product and ask the customer
4301
+ // to re-pick. These codes mean the option simply isn't valid anymore.
4302
+ return 'This option is no longer available \u2014 please refresh.';
4303
+ case 'NESTED_DEPTH_EXCEEDED':
4304
+ case 'NESTED_REQUIRES_PRODUCT_REF':
4305
+ return issue.message; // bug in your renderer \u2014 never go past 3 levels
4306
+ case 'INVALID_PRICE_DELTA':
4307
+ return issue.message; // shouldn't happen for SDK callers \u2014 server-validated on save
4308
+ case 'MODIFIER_PRICE_FLOOR_VIOLATED':
4309
+ // The server reports a generic message \u2014 internals never leak. Show a
4310
+ // friendly error and let the customer remove a downsell.
4311
+ return 'Cannot apply more discounts on this item.';
4312
+ }
4313
+ }
4314
+
4315
+ // CLIENT-SIDE PRE-FLIGHT (UX):
4316
+ // You can mirror these checks before calling addToCart to give faster
4317
+ // feedback, but the SERVER is authoritative. Always treat the 400 envelope
4318
+ // as the source of truth.
4319
+ function preflightSelections(
4320
+ groups: { id: string; name: string; min: number; max?: number | null; required: boolean; selectionType: 'SINGLE' | 'MULTIPLE'; }[],
4321
+ selections: Record<string, string[]>
4322
+ ): string | null {
4323
+ for (const g of groups) {
4324
+ if (g.max === 0) continue; // disabled-for-variant
4325
+ const picks = selections[g.id] ?? [];
4326
+ if (g.required && picks.length === 0) return \`\${g.name} is required\`;
4327
+ if (picks.length < g.min) return \`Pick at least \${g.min} from \${g.name}\`;
4328
+ if (g.max != null && picks.length > g.max) return \`Pick at most \${g.max} from \${g.name}\`;
4329
+ if (g.selectionType === 'SINGLE' && picks.length > 1) return \`Only one option allowed in \${g.name}\`;
4330
+ }
4331
+ return null;
4332
+ }`,
4333
+ "checkout-price-drift": `// PRICE_DRIFT \u2014 a product's price changed between add-to-cart and checkout.
4334
+ // The server returns HTTP 400 with code "PRICE_DRIFT" when it detects that
4335
+ // the stored unitPrice no longer matches the live price.
4336
+ //
4337
+ // Strategy: catch the error \u2192 show "prices updated" dialog \u2192
4338
+ // call refreshCartSnapshots() to re-snapshot all live prices \u2192
4339
+ // retry createCheckout once.
4340
+
4341
+ import { client } from './brainerce-client';
4342
+
4343
+ interface CheckoutOptions {
4344
+ cartId: string;
4345
+ shippingAddress: object;
4346
+ shippingMethodId: string;
4347
+ paymentProviderId: string;
4348
+ }
4349
+
4350
+ async function createCheckoutSafe(opts: CheckoutOptions) {
4351
+ try {
4352
+ return await client.createCheckout({
4353
+ cartId: opts.cartId,
4354
+ shippingAddress: opts.shippingAddress,
4355
+ shippingMethodId: opts.shippingMethodId,
4356
+ paymentProviderId: opts.paymentProviderId,
4357
+ });
4358
+ } catch (err: unknown) {
4359
+ if (!isApiError(err, 'PRICE_DRIFT')) throw err;
4360
+
4361
+ // Prices changed \u2014 refresh snapshots then retry once.
4362
+ // refreshCartSnapshots updates every cart item's unitPrice to the current
4363
+ // live price (base price + any modifier deltas) so the next checkout call
4364
+ // will pass the drift guard.
4365
+ await client.refreshCartSnapshots(opts.cartId);
4366
+
4367
+ // After refreshing, re-fetch the cart so your UI shows the updated prices
4368
+ // before you retry, giving the customer a chance to review.
4369
+ const updatedCart = await client.getCart(opts.cartId);
4370
+
4371
+ // Signal to the UI layer that prices changed so it can show a dialog.
4372
+ throw Object.assign(new Error('PRICES_UPDATED'), {
4373
+ code: 'PRICES_UPDATED',
4374
+ updatedCart,
4375
+ });
4376
+ }
4377
+ }
4378
+
4379
+ function isApiError(err: unknown, code: string): boolean {
4380
+ return (
4381
+ typeof err === 'object' &&
4382
+ err !== null &&
4383
+ 'code' in err &&
4384
+ (err as { code: string }).code === code
4385
+ );
4386
+ }
4387
+
4388
+ // --- UI integration example (framework-neutral) ---
4389
+ //
4390
+ // async function handlePlaceOrder() {
4391
+ // try {
4392
+ // const checkout = await createCheckoutSafe({ cartId, ... });
4393
+ // router.push(\`/order-confirmation?checkoutId=\${checkout.id}\`);
4394
+ // } catch (err: unknown) {
4395
+ // if (isApiError(err, 'PRICES_UPDATED')) {
4396
+ // const { updatedCart } = err as { updatedCart: Cart };
4397
+ // showPricesUpdatedDialog(updatedCart); // show diff, let user confirm
4398
+ // return;
4399
+ // }
4400
+ // showGenericError(err);
4401
+ // }
4402
+ // }
4403
+ //
4404
+ // The dialog should:
4405
+ // 1. Show which items changed price (compare old vs new unitPrice)
4406
+ // 2. Offer "Continue with new prices" (calls createCheckoutSafe again)
4407
+ // and "Go back to cart" (returns to cart page)
4408
+ // 3. NOT silently retry \u2014 the customer must acknowledge the price change.`,
4409
+ "cart-item-modifier-display": `// Rendering cart items that have modifier selections.
4410
+ // Each cart item has a \`modifiers\` array \u2014 each entry records the modifier
4411
+ // name, the price delta at time of add-to-cart, and whether it was free
4412
+ // (inside the group's freeQuantity allowance).
4413
+ //
4414
+ // Typical display:
4415
+ // Margherita \u20AA45.00
4416
+ // Extra cheese +\u20AA5.00
4417
+ // Mushrooms free
4418
+ // No onions \u2014
4419
+ // \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
4420
+ // Base \u20AA45.00 + Modifiers \u20AA5.00 = \u20AA50.00
4421
+
4422
+ import { formatPrice } from 'brainerce';
4423
+
4424
+ interface CartItemModifier {
4425
+ modifierId: string;
4426
+ name: string;
4427
+ priceDeltaAtTime: number; // in store currency units, e.g. 5.00
4428
+ freeApplied: boolean; // true when inside the group's freeQuantity
4429
+ }
4430
+
4431
+ interface CartItem {
4432
+ id: string;
4433
+ name: string;
4434
+ unitPrice: number; // base + all chargeable modifier deltas, as stored
4435
+ quantity: number;
4436
+ modifiers?: CartItemModifier[];
4437
+ currency: string; // e.g. 'ILS', 'USD'
4438
+ }
4439
+
4440
+ function renderCartItem(item: CartItem): string {
4441
+ const currency = item.currency;
4442
+ const lines: string[] = [];
4443
+
4444
+ lines.push(\`\${item.name} \${formatPrice(item.unitPrice, { currency })}\`);
4445
+
4446
+ const chargeableModifiers = (item.modifiers ?? []).filter(
4447
+ (m) => !m.freeApplied && m.priceDeltaAtTime !== 0
4448
+ );
4449
+ const freeModifiers = (item.modifiers ?? []).filter((m) => m.freeApplied);
4450
+ const zeroModifiers = (item.modifiers ?? []).filter(
4451
+ (m) => !m.freeApplied && m.priceDeltaAtTime === 0
4452
+ );
4453
+
4454
+ for (const m of chargeableModifiers) {
4455
+ const sign = m.priceDeltaAtTime > 0 ? '+' : '';
4456
+ lines.push(\` \${m.name} \${sign}\${formatPrice(m.priceDeltaAtTime, { currency })}\`);
4457
+ }
4458
+ for (const m of freeModifiers) {
4459
+ lines.push(\` \${m.name} free\`);
4460
+ }
4461
+ for (const m of zeroModifiers) {
4462
+ lines.push(\` \${m.name} \u2014\`);
4463
+ }
4464
+
4465
+ // Price breakdown: only show when there are chargeable modifiers
4466
+ const modifiersTotal = chargeableModifiers.reduce(
4467
+ (sum, m) => sum + m.priceDeltaAtTime,
4468
+ 0
4469
+ );
4470
+ if (modifiersTotal !== 0) {
4471
+ // unitPrice already includes modifiers \u2014 derive base for display only
4472
+ const basePrice = item.unitPrice - modifiersTotal;
4473
+ const base = formatPrice(basePrice, { currency }) as string;
4474
+ const mods = formatPrice(modifiersTotal, { currency }) as string;
4475
+ const total = formatPrice(item.unitPrice, { currency }) as string;
4476
+ lines.push(\`Base \${base} + Modifiers \${mods} = \${total}\`);
4477
+ }
4478
+
4479
+ return lines.join('\\n');
4480
+ }
4481
+
4482
+ // IMPORTANT: unitPrice already includes all chargeable modifier deltas.
4483
+ // Do NOT add modifier prices on top of unitPrice when computing line totals \u2014
4484
+ // multiply unitPrice \xD7 quantity directly.
4485
+ function lineTotal(item: CartItem): number {
4486
+ return item.unitPrice * item.quantity;
4487
+ }`
3154
4488
  };
3155
4489
  async function handleGetCodeExample(args) {
3156
4490
  const snippet = SNIPPETS[args.operation];
@@ -3266,13 +4600,27 @@ function getCandidateApiUrls() {
3266
4600
 
3267
4601
  // src/tools/get-store-info.ts
3268
4602
  var GET_STORE_INFO_NAME = "get-store-info";
3269
- 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.";
4603
+ 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.";
3270
4604
  var GET_STORE_INFO_SCHEMA = {
3271
- connectionId: z4.string().describe("Vibe-coded connection ID (starts with vc_)")
4605
+ salesChannelId: z4.string().optional().describe("Sales channel ID (starts with vc_)"),
4606
+ /** @deprecated alias of salesChannelId */
4607
+ connectionId: z4.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
3272
4608
  };
3273
4609
  async function handleGetStoreInfo(args) {
4610
+ const id = args.salesChannelId ?? args.connectionId;
4611
+ if (!id) {
4612
+ return {
4613
+ content: [{ type: "text", text: "Error: salesChannelId is required" }],
4614
+ isError: true
4615
+ };
4616
+ }
4617
+ if (!args.salesChannelId && args.connectionId) {
4618
+ console.warn(
4619
+ "get-store-info: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
4620
+ );
4621
+ }
3274
4622
  try {
3275
- const resolved = await resolveStoreInfo(args.connectionId, getCandidateApiUrls());
4623
+ const resolved = await resolveStoreInfo(id, getCandidateApiUrls());
3276
4624
  return {
3277
4625
  content: [
3278
4626
  {
@@ -3285,7 +4633,8 @@ async function handleGetStoreInfo(args) {
3285
4633
  storeName: resolved.info.storeName,
3286
4634
  currency: resolved.info.currency,
3287
4635
  language: resolved.info.language,
3288
- connectionId: args.connectionId,
4636
+ salesChannelId: id,
4637
+ connectionId: id,
3289
4638
  apiBaseUrl: resolved.apiBaseUrl
3290
4639
  },
3291
4640
  null,
@@ -3370,9 +4719,11 @@ async function resolveStoreCapabilities(connectionId, candidateUrls) {
3370
4719
 
3371
4720
  // src/tools/get-store-capabilities.ts
3372
4721
  var GET_STORE_CAPABILITIES_NAME = "get-store-capabilities";
3373
- 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.";
4722
+ 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.";
3374
4723
  var GET_STORE_CAPABILITIES_SCHEMA = {
3375
- connectionId: z5.string().describe("Vibe-coded connection ID (starts with vc_)")
4724
+ salesChannelId: z5.string().optional().describe("Sales channel ID (starts with vc_)"),
4725
+ /** @deprecated alias of salesChannelId */
4726
+ connectionId: z5.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
3376
4727
  };
3377
4728
  function formatCapabilities(caps) {
3378
4729
  const lines = [];
@@ -3485,15 +4836,27 @@ function formatCapabilities(caps) {
3485
4836
  }
3486
4837
  if (suggestions.length === 0) {
3487
4838
  suggestions.push(
3488
- "Start by building the required features. Use get-required-features with this connectionId for the checklist."
4839
+ "Start by building the required features. Use get-required-features with this salesChannelId for the checklist."
3489
4840
  );
3490
4841
  }
3491
4842
  suggestions.forEach((s) => lines.push(`- ${s}`));
3492
4843
  return lines.join("\n");
3493
4844
  }
3494
4845
  async function handleGetStoreCapabilities(args) {
4846
+ const id = args.salesChannelId ?? args.connectionId;
4847
+ if (!id) {
4848
+ return {
4849
+ content: [{ type: "text", text: "Error: salesChannelId is required" }],
4850
+ isError: true
4851
+ };
4852
+ }
4853
+ if (!args.salesChannelId && args.connectionId) {
4854
+ console.warn(
4855
+ "get-store-capabilities: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
4856
+ );
4857
+ }
3495
4858
  try {
3496
- const resolved = await resolveStoreCapabilities(args.connectionId, getCandidateApiUrls());
4859
+ const resolved = await resolveStoreCapabilities(id, getCandidateApiUrls());
3497
4860
  return {
3498
4861
  content: [{ type: "text", text: formatCapabilities(resolved.capabilities) }]
3499
4862
  };
@@ -3598,7 +4961,7 @@ var RULES = {
3598
4961
  tokens: {
3599
4962
  title: "Auth tokens & BFF pattern",
3600
4963
  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\`.
3601
- - NEVER put the admin API key (\`brainerce_*\`) in client code. It is a server-only secret. Client code uses \`connectionId\` or storefront endpoints.
4964
+ - 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.
3602
4965
  - 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.
3603
4966
  - 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.`
3604
4967
  },
@@ -3891,18 +5254,20 @@ ${flow.body}`
3891
5254
  // src/tools/get-required-features.ts
3892
5255
  import { z as z9 } from "zod";
3893
5256
  var GET_REQUIRED_FEATURES_NAME = "get-required-features";
3894
- 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.";
5257
+ 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.";
3895
5258
  var GET_REQUIRED_FEATURES_SCHEMA = {
3896
- connectionId: z9.string().optional().describe(
3897
- "Vibe-coded connection ID (starts with vc_). Optional \u2014 without it, returns the generic checklist."
3898
- )
5259
+ salesChannelId: z9.string().optional().describe(
5260
+ "Sales channel ID (starts with vc_). Optional \u2014 without it, returns the generic checklist."
5261
+ ),
5262
+ /** @deprecated alias of salesChannelId */
5263
+ connectionId: z9.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
3899
5264
  };
3900
5265
  var FEATURES = [
3901
5266
  {
3902
5267
  id: "browse-products",
3903
5268
  title: "Browse, filter, and search products",
3904
- 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.",
3905
- sdk: "client.getProducts({ page, limit, filters, sort }), client.searchProducts(query)",
5269
+ 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.",
5270
+ sdk: "client.getProducts({ page, limit, filters, sort, metafields }), client.getPublicMetafieldDefinitions(), client.searchProducts(query)",
3906
5271
  mandatory: "mandatory"
3907
5272
  },
3908
5273
  {
@@ -4117,10 +5482,16 @@ function renderCapabilitiesSummary(caps) {
4117
5482
  return lines.join("\n");
4118
5483
  }
4119
5484
  async function handleGetRequiredFeatures(args) {
5485
+ const id = args.salesChannelId ?? args.connectionId;
5486
+ if (!args.salesChannelId && args.connectionId) {
5487
+ console.warn(
5488
+ "get-required-features: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
5489
+ );
5490
+ }
4120
5491
  let caps = null;
4121
- if (args.connectionId) {
5492
+ if (id) {
4122
5493
  try {
4123
- const resolved = await resolveStoreCapabilities(args.connectionId, getCandidateApiUrls());
5494
+ const resolved = await resolveStoreCapabilities(id, getCandidateApiUrls());
4124
5495
  caps = resolved.capabilities;
4125
5496
  } catch {
4126
5497
  caps = null;
@@ -4132,11 +5503,11 @@ async function handleGetRequiredFeatures(args) {
4132
5503
  );
4133
5504
  if (caps) {
4134
5505
  sections.push(renderCapabilitiesSummary(caps));
4135
- } else if (args.connectionId) {
5506
+ } else if (id) {
4136
5507
  sections.push(
4137
5508
  `## Live store capabilities
4138
5509
 
4139
- Could not fetch live capabilities for \`${args.connectionId}\`. Proceeding with the generic checklist. Call \`get-store-capabilities\` separately if you want a targeted checklist.`
5510
+ Could not fetch live capabilities for \`${id}\`. Proceeding with the generic checklist. Call \`get-store-capabilities\` separately if you want a targeted checklist.`
4140
5511
  );
4141
5512
  }
4142
5513
  sections.push("## Features");