@brainerce/mcp-server 3.1.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/http.js CHANGED
@@ -67,7 +67,7 @@ function getTypeQuickReference() {
67
67
  | OAuth | \`provider.name\` | \`provider\` | it IS the string: \`'GOOGLE' | 'FACEBOOK' | 'GITHUB'\` |
68
68
  | OAuth | \`oauth.url\` | \`oauth.authorizationUrl\` | |
69
69
  | Description | \`getDescriptionContent()\` | \`{ html } | { text } | null\` | check \`'html' in content\` before use |
70
- | \`smartGetCart()\` | always use \`.id\` | check \`'id' in cart\` | returns \`Cart | LocalCart\` |
70
+ | \`smartGetCart()\` | N/A | \`cart.id\` | returns \`CartWithIncludes\` (extends \`Cart\`); pass \`{ include: [...] }\` for extras |
71
71
  | \`startGuestCheckout()\` | always use \`.checkoutId\` | check \`result.tracked\` | discriminated union |
72
72
 
73
73
  **Rules:**
@@ -75,8 +75,8 @@ function getTypeQuickReference() {
75
75
  - CartItem/CheckoutLineItem = **NESTED** (\`item.product.name\`, \`item.unitPrice\`)
76
76
  - OrderItem = **FLAT** (\`item.name\`, \`item.price\`, \`item.totalPrice\`, \`item.image\`)
77
77
  - Cart has NO \`.total\` \u2014 use \`getCartTotals(cart)\`
78
- - \`getCartTotals()\` only works with server \`Cart\`, NOT \`LocalCart\`
79
- - \`smartGetCart()\` returns \`Cart | LocalCart\` \u2014 check \`'id' in cart\` before using Cart fields
78
+ - \`getCartTotals()\` works with server \`Cart\` (all carts are server-side now)
79
+ - \`smartGetCart()\` returns \`CartWithIncludes\` \u2014 always a server cart; pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` for extras
80
80
  - \`startGuestCheckout()\` returns discriminated union \u2014 check \`result.tracked\` before \`.checkoutId\`
81
81
  - \`SetShippingAddressDto.email\` is **required** \u2014 always include email
82
82
 
@@ -204,7 +204,7 @@ async function startCheckout() {
204
204
  6. Select shipping method \u2192 \`selectShippingMethod()\`
205
205
  6b. (Optional) Set checkout custom fields \u2192 \`setCheckoutCustomFields()\` \u2014 surcharges auto-calculated
206
206
  7. Create payment intent \u2192 \`createPaymentIntent()\` \u2192 returns \`{ clientSecret, provider }\`
207
- 8. Branch on \`provider\`: \`'stripe'\` \u2192 Stripe Elements, \`'grow'\` \u2192 iframe, \`'paypal'\` \u2192 PayPal Buttons
207
+ 8. Branch on the **\`clientSdk.renderType\`** returned by \`createPaymentIntent()\` \u2014 NEVER hard-code by provider name. Values: \`'sdk-widget'\` (Stripe, PayPal, Grow), \`'iframe'\` (Cardcom hosted or Brainerce-hosted embed \u2014 detect via URL path), \`'redirect'\`, \`'sandbox'\`, \`'embedded-fields'\` (reserved).
208
208
  9. **Order is created AUTOMATICALLY after payment succeeds (via webhook) \u2014 for ALL providers!**
209
209
 
210
210
  ### Checkout Page Component
@@ -307,8 +307,8 @@ function CheckoutPage() {
307
307
  </div>
308
308
  );
309
309
  }
310
- if (paymentData.provider === 'grow') {
311
- return <GrowPaymentForm paymentUrl={paymentData.clientSecret} checkoutId={paymentData.checkoutId} />;
310
+ if (paymentData.clientSdk?.renderType === 'iframe') {
311
+ return <PaymentIframe clientSecret={paymentData.clientSecret} checkoutId={paymentData.checkoutId} />;
312
312
  }
313
313
  if (paymentData.provider === 'paypal' && paypalClientId) {
314
314
  return <PayPalPaymentForm clientId={paypalClientId} orderId={paymentData.clientSecret} checkoutId={paymentData.checkoutId} />;
@@ -364,26 +364,82 @@ function StripePaymentForm({ checkoutId }: { checkoutId: string }) {
364
364
  }
365
365
  \`\`\`
366
366
 
367
- ### Grow Payment Form (Israeli stores \u2014 iframe based, no SDK needed)
367
+ ### Iframe-Based Providers (Cardcom, legacy Grow, etc.)
368
+
369
+ When \`clientSdk.renderType === 'iframe'\`, the payment intent returns a \`clientSecret\` which is a URL to load in an iframe. There are TWO flavors of iframe rendering you must handle:
370
+
371
+ **Flavor A \u2014 Brainerce-hosted embed (URL path contains \`/embed/\`):** The iframe loads a Brainerce-branded compact form (e.g. Cardcom OpenFields). Render it **INLINE** inside your checkout flow (next to the order summary) \u2014 NO modal, NO dark overlay. The embed page posts messages to resize itself and to request top-level navigation (e.g. for Bit express-pay buttons).
372
+
373
+ **Flavor B \u2014 Provider-hosted page (any other URL):** The iframe loads a full provider-branded page with its own header/chrome. Render inside a **modal overlay** so it doesn't fight your checkout layout.
374
+
375
+ Detect flavor by URL path \u2014 works across localhost/staging/prod without a domain list:
368
376
 
369
377
  \`\`\`typescript
370
- function GrowPaymentForm({ paymentUrl, checkoutId }: { paymentUrl: string; checkoutId: string }) {
371
- const [iframeLoaded, setIframeLoaded] = useState(false);
378
+ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; checkoutId: string }) {
379
+ const [height, setHeight] = useState(540); // default before resize message arrives
380
+ const isBrainerceEmbed = (() => {
381
+ try { return new URL(clientSecret).pathname.includes('/embed/'); }
382
+ catch { return false; }
383
+ })();
384
+
385
+ useEffect(() => {
386
+ function handleMessage(e: MessageEvent) {
387
+ const data = e.data as { type?: string; height?: number; url?: string };
388
+ if (data?.type === 'brainerce:resize' && typeof data.height === 'number') {
389
+ setHeight(data.height);
390
+ }
391
+ if (data?.type === 'brainerce:redirect' && typeof data.url === 'string') {
392
+ // Top-level navigation (e.g. Bit). ALWAYS validate against an allowlist
393
+ // before navigating \u2014 never trust the URL blindly.
394
+ if (isTrustedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
395
+ }
396
+ if (data?.type === 'brainerce:payment-complete') {
397
+ // Payment done \u2014 redirect to confirmation page which verifies server-side
398
+ window.location.href = \`/order-confirmation?checkout_id=\${checkoutId}\`;
399
+ }
400
+ }
401
+ window.addEventListener('message', handleMessage);
402
+ return () => window.removeEventListener('message', handleMessage);
403
+ }, [checkoutId]);
404
+
405
+ if (isBrainerceEmbed) {
406
+ // Inline: part of the checkout flow, no overlay
407
+ return (
408
+ <div className="w-full">
409
+ <iframe
410
+ src={clientSecret}
411
+ style={{ width: '100%', height, border: 0, transition: 'height 0.2s ease-out' }}
412
+ title="Payment"
413
+ allow="payment"
414
+ />
415
+ </div>
416
+ );
417
+ }
418
+
419
+ // Provider-hosted page: modal overlay
372
420
  return (
373
- <div className="w-full">
374
- {!iframeLoaded && <div className="flex items-center justify-center py-12"><span>Loading payment form...</span></div>}
375
- <iframe
376
- src={paymentUrl}
377
- onLoad={() => setIframeLoaded(true)}
378
- style={{ width: '100%', minHeight: '600px', border: 'none', display: iframeLoaded ? 'block' : 'none' }}
379
- allow="payment"
380
- />
381
- <p className="text-center text-sm text-gray-500 mt-4">
382
- Having trouble? <a href={paymentUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 underline">Open payment in new tab</a>
383
- </p>
421
+ <div className="fixed inset-0 z-50 flex items-start justify-center bg-black/50 py-6 overflow-y-auto">
422
+ <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl mx-4">
423
+ <iframe
424
+ src={clientSecret}
425
+ style={{ width: '100%', height: '90vh', minHeight: 700, border: 0 }}
426
+ title="Payment"
427
+ allow="payment"
428
+ />
429
+ </div>
384
430
  </div>
385
431
  );
386
432
  }
433
+
434
+ // Allowlist of origins you trust for top-level payment redirects.
435
+ function isTrustedPaymentUrl(url: string): boolean {
436
+ try {
437
+ const u = new URL(url);
438
+ if (u.protocol !== 'https:') return false;
439
+ // Add your provider hostnames here. Example: Cardcom for Bit express-pay.
440
+ return u.hostname === 'cardcom.solutions' || u.hostname.endsWith('.cardcom.solutions');
441
+ } catch { return false; }
442
+ }
387
443
  \`\`\`
388
444
 
389
445
  ### PayPal Payment Form
@@ -653,12 +709,23 @@ const growProvider = providers.find(p => p.provider === 'grow');
653
709
  const paypalProvider = providers.find(p => p.provider === 'paypal');
654
710
  \`\`\`
655
711
 
656
- Each provider has: \`id\`, \`provider\` ('stripe'|'grow'|'paypal'|'sandbox'), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
712
+ Each provider has: \`id\`, \`provider\` (flexible string \u2014 \`'stripe'\`, \`'grow'\`, \`'paypal'\`, \`'cardcom'\`, \`'sandbox'\`, and future providers), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
713
+
714
+ The payment intent returned from \`createPaymentIntent()\` includes a \`clientSdk\` object whose \`renderType\` tells you exactly how to render \u2014 **branch on THAT, not on the provider name**:
657
715
 
716
+ - \`renderType: 'sdk-widget'\` \u2014 load \`clientSdk.scriptUrl\`, mount into \`<div id={clientSdk.containerId}>\`. Used by Stripe, PayPal, Grow. The SDK paints its own form in your DOM.
717
+ - \`renderType: 'iframe'\` \u2014 render \`<iframe src={clientSecret}>\`. Two flavors detected by URL path:
718
+ - Path contains \`/embed/\` \u2192 Brainerce-hosted embed. Render **INLINE** (no modal). Listen for \`brainerce:resize\` / \`brainerce:redirect\` postMessages. Used by Cardcom (embedded mode).
719
+ - Any other URL \u2192 provider-hosted page. Render inside a **modal**. Used by Cardcom (hosted mode), legacy Grow iframe.
720
+ - \`renderType: 'redirect'\` \u2014 \`window.location.href = URL\`. Customer completes payment off-site and returns via SuccessRedirectUrl.
721
+ - \`renderType: 'sandbox'\` \u2014 show a "Complete Test Order" button; call \`completeGuestCheckout(checkoutId)\`. Orders are \`isTestOrder: true\`. Appears when \`sandboxPaymentsEnabled\` is true.
722
+ - \`renderType: 'embedded-fields'\` \u2014 reserved for future Stripe-Elements-style pattern (PCI micro-iframes for card/CVV mounted directly into the merchant form). **No provider ships this today** \u2014 handle via a "not supported yet" fallback.
723
+
724
+ Provider-specific install notes:
658
725
  - **Stripe:** \`npm install @stripe/stripe-js @stripe/react-stripe-js\` \u2014 \`loadStripe(publicKey, { stripeAccount })\`
659
- - **Grow:** No SDK \u2014 uses iframe with payment URL. Supports credit cards, Bit, Apple Pay, Google Pay.
660
726
  - **PayPal:** \`npm install @paypal/react-paypal-js\` \u2014 \`PayPalScriptProvider\` + \`PayPalButtons\`
661
- - **Sandbox:** No SDK needed \u2014 when \`sandboxPaymentsEnabled\` is true, \`getPaymentProviders()\` includes a sandbox provider with \`renderType: 'sandbox'\`. Show a "Complete Test Order" button. Call \`completeGuestCheckout(checkoutId)\` to finalize. Orders are marked \`isTestOrder: true\`.`;
727
+ - **Grow:** No SDK needed \u2014 JS SDK loaded via \`clientSdk.scriptUrl\`. Supports credit cards, Bit, Apple Pay, Google Pay.
728
+ - **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.`;
662
729
  }
663
730
  function getProductsSection(_currency) {
664
731
  return `## Products & Variants
@@ -689,10 +756,12 @@ When \`storeInfo.i18n.enabled\` is true, call \`client.setLocale(locale)\` once
689
756
  \`{ locale }\` params needed. Translated fields include: \`name\`,
690
757
  \`description\`, \`slug\`, \`seoTitle\`, \`seoDescription\`, plus
691
758
  \`categories[].name\`, \`brands[].name\`, \`tags[].name\`, \`variants[].name\`,
692
- \`productAttributeOptions[].attribute.name\`/\`attributeOption.name\`, and
693
- \`metafields[].value\`. No client-side overlay. See the full \`i18n\` section
694
- (\`get-sdk-docs\` topic \`i18n\`) for the \`[locale]\` route pattern, SDK setup,
695
- and the brand/tag badge examples.
759
+ \`variant.attributes\` keys and values (so \`getVariantOptions()\` returns
760
+ translated attribute/option names), \`productAttributeOptions[].attribute.name\`/
761
+ \`attributeOption.name\`, \`metafields[].value\`, cart item product/variant names,
762
+ and recommendation/bundle/bump product names. No client-side overlay. See the
763
+ full \`i18n\` section (\`get-sdk-docs\` topic \`i18n\`) for the \`[locale]\` route
764
+ pattern, SDK setup, and the brand/tag badge examples.
696
765
 
697
766
  ### Price Display (Use SDK Helper!)
698
767
 
@@ -829,6 +898,8 @@ const material = getProductMetafieldValue(product, 'material');
829
898
 
830
899
  Some products allow customers to provide input at purchase time (e.g., text on a cake, upload a logo). Check \`product.customizationFields\` and render input fields accordingly.
831
900
 
901
+ Merchants can also flag a \`MetafieldDefinition\` as \`appliesToAllProducts: true\` \u2014 those fields are folded into every product's \`customizationFields\` array automatically by the backend. Client code does not need to merge or union anything: always render exactly what's in \`product.customizationFields\`.
902
+
832
903
  \`\`\`typescript
833
904
  import { getProductCustomizationFields } from 'brainerce';
834
905
  import type { ProductCustomizationField } from 'brainerce';
@@ -887,7 +958,7 @@ function getCartSection(_currency) {
887
958
  ### Smart Cart Methods (RECOMMENDED)
888
959
 
889
960
  \`\`\`typescript
890
- const cart = await client.smartGetCart(); // Returns Cart | LocalCart
961
+ const cart = await client.smartGetCart(); // Returns CartWithIncludes (extends Cart)
891
962
  await client.smartAddToCart({
892
963
  productId: product.id,
893
964
  variantId: selectedVariant?.id,
@@ -1018,7 +1089,19 @@ const recs = (product as any).recommendations as ProductRecommendationsResponse
1018
1089
 
1019
1090
  ### Cart Page Features
1020
1091
 
1021
- **Cross-sell recommendations** (existing products the customer might also want):
1092
+ **Consolidated include** (fetch recommendations, upgrades, and bundles in one request):
1093
+ \`\`\`typescript
1094
+ import type { CartWithIncludes } from 'brainerce';
1095
+ const cart = await client.getCart(cartId, {
1096
+ include: ['recommendations', 'upgrades', 'bundles'],
1097
+ });
1098
+ // cart.recommendations \u2014 cross-sell recommendations
1099
+ // cart.upgrades \u2014 upgrade suggestions keyed by source product ID
1100
+ // cart.bundles \u2014 bundle offers
1101
+ // Also works with smartGetCart: client.smartGetCart({ include: ['recommendations', 'upgrades', 'bundles'] })
1102
+ \`\`\`
1103
+
1104
+ **Cross-sell recommendations** (or fetch individually for targeted refresh):
1022
1105
  \`\`\`typescript
1023
1106
  import type { CartRecommendationsResponse } from 'brainerce';
1024
1107
  const cartRecs = await client.getCartRecommendations(cartId, 4);
@@ -1110,6 +1193,110 @@ Always check the flag before rendering: \`if (storeInfo?.upsell?.featureName !==
1110
1193
  ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`, \`variants?\` (when variant selection needed).
1111
1194
  OrderBump/CartBundleOffer: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).`;
1112
1195
  }
1196
+ function getProductCustomizationFieldsSection() {
1197
+ return `## Product Customization Fields (buyer input on product page)
1198
+
1199
+ Some products let the buyer personalize them before adding to cart \u2014 engraving text, a photo upload, a color pick, a multi-select add-on list. The merchant defines these fields in the Brainerce dashboard; the storefront renders them, collects values, uploads any images, and passes everything as \`metadata\` on add-to-cart.
1200
+
1201
+ ### Where the fields come from
1202
+
1203
+ They arrive **embedded on the product response** \u2014 no extra API call:
1204
+
1205
+ \`\`\`typescript
1206
+ import type { Product, ProductCustomizationField, MetafieldType } from 'brainerce';
1207
+
1208
+ const product = await client.getProductBySlug(slug);
1209
+ const fields: ProductCustomizationField[] = product.customizationFields ?? [];
1210
+ // fields is sorted by position. If empty, render the product page normally.
1211
+ \`\`\`
1212
+
1213
+ Each field has:
1214
+ \`\`\`typescript
1215
+ {
1216
+ definitionId: string;
1217
+ key: string; // stable identifier \u2014 use this as the metadata key
1218
+ name: string; // display label (may be localized)
1219
+ description?: string | null;
1220
+ type: MetafieldType; // 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME' |
1221
+ // 'JSON' | 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' |
1222
+ // 'IMAGE' | 'GALLERY' | 'SELECT' | 'MULTI_SELECT'
1223
+ required: boolean;
1224
+ minLength?: number | null; // chars for TEXT/TEXTAREA; array size for MULTI_SELECT
1225
+ maxLength?: number | null;
1226
+ minValue?: number | null; // NUMBER / DIMENSION / WEIGHT
1227
+ maxValue?: number | null;
1228
+ enumValues?: string[]; // required for SELECT / MULTI_SELECT
1229
+ defaultValue?: string | null;
1230
+ position: number;
1231
+ }
1232
+ \`\`\`
1233
+
1234
+ ### Render one control per type
1235
+
1236
+ | type | Render as | Collected value |
1237
+ | --------------- | ---------------------------------------------------------- | ---------------------------- |
1238
+ | \`TEXT\` | \`<input type="text">\` | \`string\` |
1239
+ | \`TEXTAREA\` | \`<textarea>\` | \`string\` |
1240
+ | \`NUMBER\` | \`<input type="number">\` | \`number\` |
1241
+ | \`BOOLEAN\` | checkbox / switch | \`boolean\` |
1242
+ | \`DATE\` | \`<input type="date">\` | \`string\` (YYYY-MM-DD) |
1243
+ | \`DATETIME\` | \`<input type="datetime-local">\` | \`string\` (ISO 8601) |
1244
+ | \`URL\` | \`<input type="url">\` | \`string\` |
1245
+ | \`COLOR\` | \`<input type="color">\` | \`string\` (#RRGGBB) |
1246
+ | \`SELECT\` | \`<select>\` or radio group (use \`enumValues\`) | \`string\` (in enumValues) |
1247
+ | \`MULTI_SELECT\`| checkbox group (use \`enumValues\`) | \`string[]\` (every in enum) |
1248
+ | \`IMAGE\` | file input + upload via \`uploadCustomizationFile\` | \`string\` (URL) |
1249
+ | \`GALLERY\` | multi-file input + one upload per file | \`string[]\` (URLs) |
1250
+ | \`JSON\` | textarea; validate is parseable | \`string\` (JSON) |
1251
+
1252
+ ### Upload buyer-submitted images
1253
+
1254
+ \`IMAGE\` and \`GALLERY\` require uploading before add-to-cart:
1255
+
1256
+ \`\`\`typescript
1257
+ const { url } = await client.uploadCustomizationFile(file);
1258
+ // Server rules: image/* only, max 5 MB, 10 uploads/min per IP.
1259
+ // Files are retained for at least 7 days; after that, if the cart never
1260
+ // became an order, they are automatically deleted.
1261
+ \`\`\`
1262
+
1263
+ ### Add to cart with customization metadata
1264
+
1265
+ \`\`\`typescript
1266
+ // Collect values keyed by field.key \u2014 NOT by field.name or field.definitionId.
1267
+ const metadata: Record<string, unknown> = {
1268
+ engraving_text: 'Happy Birthday!', // TEXT
1269
+ frame_color: 'Gold', // SELECT (must be in enumValues)
1270
+ upload_photo: url, // IMAGE (URL from uploadCustomizationFile)
1271
+ addons: ['Gift wrap'], // MULTI_SELECT (always an array)
1272
+ };
1273
+
1274
+ await client.addToCart(cart.id, {
1275
+ productId: product.id,
1276
+ quantity: 1,
1277
+ metadata,
1278
+ });
1279
+ \`\`\`
1280
+
1281
+ Server validation (rejected with HTTP 400 on failure):
1282
+ - \`required: true\` \u2192 must be present and non-empty
1283
+ - \`TEXT\` / \`TEXTAREA\` \u2192 string; \`minLength\` / \`maxLength\` enforced as character count
1284
+ - \`NUMBER\` \u2192 \`minValue\` / \`maxValue\` enforced
1285
+ - \`SELECT\` \u2192 value must be one of \`enumValues\`
1286
+ - \`MULTI_SELECT\` \u2192 array; each element in \`enumValues\`; duplicates removed; \`minLength\` / \`maxLength\` enforced as array size
1287
+ - \`IMAGE\` / \`GALLERY\` \u2192 URL(s) must be from \`/customization-upload\` on this store
1288
+
1289
+ ### Order snapshot
1290
+
1291
+ When the order is created, each line's customization values are snapshotted onto the order item with \`{ key, name, type, value }\` \u2014 so later edits to the field definition don't orphan old orders. The merchant dashboard shows the values on the order detail page.
1292
+
1293
+ ### Common mistakes
1294
+
1295
+ - Passing values keyed by \`field.name\` instead of \`field.key\` \u2192 silently ignored (unknown key)
1296
+ - Sending a \`MULTI_SELECT\` as a string instead of \`string[]\` \u2192 HTTP 400
1297
+ - Using a raw external URL (not from \`/customization-upload\`) for \`IMAGE\` / \`GALLERY\` \u2192 HTTP 400
1298
+ - Assuming \`enumValues\` is present for all types \u2014 only \`SELECT\` / \`MULTI_SELECT\` require it`;
1299
+ }
1113
1300
  function getInventorySection() {
1114
1301
  return `## Inventory, Stock Display & Reservation Countdown
1115
1302
 
@@ -1366,7 +1553,50 @@ const { data: orders } = await client.getMyOrders({ page: 1, limit: 10 }); // Re
1366
1553
  // \u274C WRONG \u2014 these methods don't exist!
1367
1554
  client.getCustomerProfile();
1368
1555
  client.getCustomerOrders();
1369
- \`\`\``;
1556
+ \`\`\`
1557
+
1558
+ ### Order history should show more than just totals
1559
+
1560
+ A useful order card includes ALL of the following when the data is present. Each section is conditional \u2014 render nothing if the field is empty.
1561
+
1562
+ | Section | Source field | Notes |
1563
+ |---|---|---|
1564
+ | Header (number, status badge, date, total) | \`order.orderNumber\`, \`order.status\`, \`order.createdAt\`, \`order.totalAmount\` | Always present. |
1565
+ | Line items | \`order.items[]\` | Render image, name, qty, price. |
1566
+ | **Per-item customizations** | \`order.items[i].customizations\` | Map of { label, value, type }. Render by \`type\` \u2014 see table below. |
1567
+ | **Status timeline** | \`order.statusHistory\` | \`OrderStatusChange[]\`: \`{ status, at, note? }\`. Render as a vertical list. |
1568
+ | **Shipping address** | \`order.shippingAddress\` | Standard \`OrderAddress\` shape. |
1569
+ | **Tracking** | \`order.trackingNumber\`, \`order.trackingUrl\`, \`order.carrier\`, \`order.shippedAt\`, \`order.deliveredAt\` | Link out to \`trackingUrl\` when set. |
1570
+ | **Payment** | \`order.paymentMethod\`, \`order.financialStatus\` | Badge \`financialStatus\` (paid / pending / refunded / partially_refunded). |
1571
+ | Downloads | \`order.hasDownloads\` \u2192 \`client.getOrderDownloads(id)\` | Separate call; returns \`OrderDownloadLink[]\`. |
1572
+ | Financial summary | \`order.subtotal\`, \`order.appliedDiscounts\`, \`order.couponCode\` + \`couponDiscount\`, \`order.shippingAmount\`, \`order.taxAmount\`, \`order.totalAmount\` | Breakdown rows + final total. |
1573
+
1574
+ #### Rendering \`order.items[i].customizations\` by type
1575
+
1576
+ The map key is the metafield slug; the value is \`{ label, value, type }\`. Dispatch by \`type\`:
1577
+
1578
+ | Type | Value | Render |
1579
+ |---|---|---|
1580
+ | \`TEXT\`, \`TEXTAREA\`, \`URL\`, \`NUMBER\`, \`SELECT\` | string | Plain text (\`URL\` \u2192 anchor). |
1581
+ | \`BOOLEAN\` | \`"yes"\` / \`"no"\` | \u2713 / \u2717 |
1582
+ | \`MULTI_SELECT\` | \`string[]\` | Comma-separated. |
1583
+ | \`IMAGE\` | asset URL (string) | Thumbnail linking to full-size asset. |
1584
+ | \`GALLERY\` | \`string[]\` of URLs | Grid of thumbnails. |
1585
+ | \`COLOR\` | hex string | Swatch + hex text. |
1586
+ | \`DATE\` | ISO-8601 | \`toLocaleDateString()\` |
1587
+ | \`DATETIME\` | ISO-8601 | \`toLocaleString()\` |
1588
+ | Unknown | any | Plain text (defensive default). |
1589
+
1590
+ The storefront scaffolded by \`create-brainerce-store\` already implements this. See \`src/components/account/order-history.tsx\` + the sibling \`order-customizations.tsx\`, \`order-status-timeline.tsx\`, \`order-shipping-block.tsx\`, \`order-payment-block.tsx\` \u2014 mirror that structure.
1591
+
1592
+ ### Do NOT render
1593
+
1594
+ These fields are NOT returned to buyers by \`/customers/me/orders\`. If you see them in older examples, ignore them \u2014 they are for merchant/admin views only.
1595
+
1596
+ - \`order.accountId\`, \`order.storeId\`, \`order.customerId\` (already known on the request)
1597
+ - \`order.notes\` (internal merchant notes)
1598
+ - \`order.customFieldValues\` (order-level checkout fields \u2014 merchant concept; buyers see \`items[i].customizations\`)
1599
+ - \`order.appliedSurcharges\`, \`order.surchargeAmount\`, \`order.appliedRuleIds\`, \`order.downloadMeta\`, \`order.pickupLocationData\``;
1370
1600
  }
1371
1601
  function getOrderConfirmationSection() {
1372
1602
  return `## Order Confirmation Page (/order-confirmation) \u2014 REQUIRED!
@@ -1536,7 +1766,8 @@ overlay needed:
1536
1766
  - \`brands[].name\`
1537
1767
  - \`tags[].name\`
1538
1768
  - \`variants[].name\`
1539
- - \`productAttributeOptions[].attribute.name\`, \`attributeOption.name\`/\`value\`
1769
+ - \`variant.attributes\` keys and values \u2014 \`getVariantOptions(variant)\` returns translated attribute names and option values automatically
1770
+ - \`productAttributeOptions[].attribute.name\`, \`attributeOption.name\`
1540
1771
  - \`metafields[].value\`
1541
1772
 
1542
1773
  **Taxonomy (\`getCategories\`, \`getBrands\`, \`getTags\`):**
@@ -1545,6 +1776,10 @@ overlay needed:
1545
1776
  **Cart:**
1546
1777
  - \`items[].product.name\`, \`items[].variant.name\`
1547
1778
 
1779
+ **Bundles & Order Bumps:**
1780
+ - \`bundleProduct.name\`, \`bundleProduct.slug\`, \`bumpProduct.name\`, \`bumpProduct.slug\`
1781
+ - Variant names inside bundles/bumps
1782
+
1548
1783
  **Checkout:**
1549
1784
  - Line items: \`items[].product.name\`, \`items[].variant.name\`
1550
1785
  - Discount banners, nudges, badges
@@ -1629,6 +1864,265 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
1629
1864
  // OAuth: getOAuthProviders(), configureOAuthProvider()
1630
1865
  \`\`\``;
1631
1866
  }
1867
+ function getContactInquiriesSection() {
1868
+ return `## Contact Inquiries & Forms (optional)
1869
+
1870
+ Accept messages from one or more contact forms on your storefront. The merchant
1871
+ configures everything in the Brainerce dashboard under **Customers \u2192 Contact
1872
+ Forms**; submissions land in **Customers \u2192 Inquiries** and both sides receive
1873
+ email notifications.
1874
+
1875
+ **IMPORTANT for AI code generators:** the merchant OWNS the form shape. Do not
1876
+ hardcode labels, placeholders, help text, the submit button, or the success
1877
+ message. Render from the schema returned by \`contactForms.get()\` so the
1878
+ storefront reflects whatever the merchant configures \u2014 including new fields
1879
+ they add later, translations they add later, and the success message they
1880
+ write. This is the difference between "a contact form" and "THE merchant's
1881
+ contact form."
1882
+
1883
+ ### Two integration paths
1884
+
1885
+ 1. **Simple (legacy)** \u2014 pass \`{ name, email, subject, message }\` and submit.
1886
+ Works out of the box, no dashboard setup needed. Backed by a lazily-seeded
1887
+ default form keyed \`"main"\` with five built-in fields (\`name\`, \`email\`,
1888
+ \`phone\`, \`subject\`, \`message\`). Choose this only for throwaway demos.
1889
+ 2. **Flexible (recommended, default in \`npx create-brainerce-store\`)** \u2014
1890
+ merchants can configure multiple forms per store (e.g. \`main\`,
1891
+ \`newsletter\`, \`whatsapp_prechat\`), add custom fields (TEXT, TEXTAREA,
1892
+ EMAIL, PHONE, NUMBER, SELECT, MULTI_SELECT, CHECKBOX, URL, DATE), translate
1893
+ everything per locale, hide any non-essential built-in. Fetch the schema
1894
+ with \`contactForms.get(formKey, locale)\` and render dynamically.
1895
+
1896
+ ### Simple path (legacy shape)
1897
+
1898
+ \`\`\`typescript
1899
+ import type { CreateInquiryInput, CreateInquiryResponse } from 'brainerce';
1900
+
1901
+ const result = await brainerce.createInquiry({
1902
+ name: 'Jane Doe',
1903
+ email: 'jane@example.com',
1904
+ subject: 'Question about shipping',
1905
+ message: 'Hi, do you ship internationally?',
1906
+ phone: '+1-555-0100', // optional
1907
+ customerId: customer?.id, // optional \u2014 link to logged-in customer
1908
+ metadata: { page: '/contact' }, // optional
1909
+ });
1910
+ // \u2192 { id, status: 'NEW', createdAt }
1911
+ \`\`\`
1912
+
1913
+ ### Flexible path \u2014 end-to-end contract
1914
+
1915
+ **Endpoints:**
1916
+
1917
+ | Method | Path | Returns |
1918
+ | ------ | ----------------------------------------------------------------- | ------------------------------ |
1919
+ | GET | \`/stores/:storeId/contact-forms\` | \`ContactFormSummary[]\` |
1920
+ | GET | \`/stores/:storeId/contact-forms/:formKey?locale=xx\` | \`ContactFormPublic\` |
1921
+ | POST | \`/stores/:storeId/inquiries\` | \`CreateInquiryResponse\` |
1922
+
1923
+ All three are public (no API key). The SDK wraps them so you never call them
1924
+ directly \u2014 use \`brainerce.contactForms.list()\`, \`brainerce.contactForms.get()\`,
1925
+ and \`brainerce.createInquiry()\`.
1926
+
1927
+ \`\`\`typescript
1928
+ import type { ContactFormPublic } from 'brainerce';
1929
+
1930
+ // List active forms (optional \u2014 if you want a form picker or route-per-form setup)
1931
+ const forms = await brainerce.contactForms.list();
1932
+ // \u2192 [{ key: 'main', name: 'Contact us', isDefault: true }, ...]
1933
+
1934
+ // Fetch one form's schema \u2014 server pre-resolves translations for the locale
1935
+ // and strips every field the merchant marked isVisible=false.
1936
+ const form = await brainerce.contactForms.get('main', 'en');
1937
+ // \u2192 {
1938
+ // id, key, name, description?, submitButton, successMessage,
1939
+ // fields: [{ key, type, label, placeholder?, helpText?, isRequired,
1940
+ // enumValues?, validation?, defaultValue? }, ...]
1941
+ // }
1942
+
1943
+ // Submit a keyed payload. Unknown keys are stripped, required fields are
1944
+ // enforced, and every value is validated against \`validation\` server-side.
1945
+ await brainerce.createInquiry({
1946
+ formKey: 'main',
1947
+ fields: {
1948
+ email: 'jane@example.com', // built-in keys
1949
+ message: 'Hi...',
1950
+ // ...any custom keys the merchant added via the dashboard
1951
+ },
1952
+ locale: 'en', // stored on the inquiry \u2014 lets staff filter by language
1953
+ sourceMetadata: { page: '/contact' }, // arbitrary provenance (UTM, referrer, etc.)
1954
+ });
1955
+ \`\`\`
1956
+
1957
+ Both shapes go to the same POST endpoint and may be mixed; \`fields\` wins when
1958
+ both provide the same key. Unknown keys (not defined on the form schema) are
1959
+ stripped server-side.
1960
+
1961
+ ### Dynamic rendering \u2014 reference implementation
1962
+
1963
+ Render every field type the merchant can pick. Keep this as a \`<DynamicField>\`
1964
+ component so the form is fully driven by \`schema.fields\`.
1965
+
1966
+ \`\`\`tsx
1967
+ import type { ContactFormPublic, ContactFormPublicField } from 'brainerce';
1968
+
1969
+ type FieldValue = string | string[] | boolean;
1970
+
1971
+ function defaultValueFor(f: ContactFormPublicField): FieldValue {
1972
+ if (f.type === 'CHECKBOX') return false;
1973
+ if (f.type === 'MULTI_SELECT') return [];
1974
+ return f.defaultValue ?? '';
1975
+ }
1976
+
1977
+ function isEmpty(v: FieldValue): boolean {
1978
+ if (typeof v === 'string') return v.trim().length === 0;
1979
+ if (Array.isArray(v)) return v.length === 0;
1980
+ return v === false;
1981
+ }
1982
+
1983
+ function DynamicField({
1984
+ field,
1985
+ value,
1986
+ onChange,
1987
+ }: {
1988
+ field: ContactFormPublicField;
1989
+ value: FieldValue;
1990
+ onChange: (v: FieldValue) => void;
1991
+ }) {
1992
+ const id = \`contact-\${field.key}\`;
1993
+ const { minLength, maxLength, min, max, pattern } = field.validation ?? {};
1994
+ const strVal = typeof value === 'string' ? value : '';
1995
+
1996
+ // Label \u2014 USE \`field.label\`, NEVER hardcode. Falls back to the key.
1997
+ const label = (
1998
+ <label htmlFor={id} className="mb-1.5 block text-sm font-medium">
1999
+ {field.label}
2000
+ {field.isRequired && <span aria-hidden className="text-red-500"> *</span>}
2001
+ </label>
2002
+ );
2003
+ const help = field.helpText ? <p className="mt-1 text-xs opacity-70">{field.helpText}</p> : null;
2004
+
2005
+ switch (field.type) {
2006
+ case 'TEXTAREA':
2007
+ return (<div>{label}<textarea id={id} required={field.isRequired} maxLength={maxLength} minLength={minLength} rows={6} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2008
+ case 'EMAIL':
2009
+ return (<div>{label}<input id={id} type="email" required={field.isRequired} autoComplete="email" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2010
+ case 'PHONE':
2011
+ return (<div>{label}<input id={id} type="tel" required={field.isRequired} autoComplete="tel" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2012
+ case 'URL':
2013
+ return (<div>{label}<input id={id} type="url" required={field.isRequired} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2014
+ case 'NUMBER':
2015
+ return (<div>{label}<input id={id} type="number" required={field.isRequired} min={min} max={max} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2016
+ case 'DATE':
2017
+ return (<div>{label}<input id={id} type="date" required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2018
+ case 'SELECT':
2019
+ return (<div>{label}<select id={id} required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)}><option value="">\u2014</option>{field.enumValues?.map((o) => (<option key={o.value} value={o.value}>{o.label}</option>))}</select>{help}</div>);
2020
+ case 'MULTI_SELECT': {
2021
+ const arr = Array.isArray(value) ? value : [];
2022
+ return (<div>{label}<div>{field.enumValues?.map((o) => { const checked = arr.includes(o.value); return (<label key={o.value}><input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked ? [...arr, o.value] : arr.filter((v) => v !== o.value))} /><span>{o.label}</span></label>); })}</div>{help}</div>);
2023
+ }
2024
+ case 'CHECKBOX':
2025
+ return (<div><label htmlFor={id}><input id={id} type="checkbox" required={field.isRequired} checked={value === true} onChange={(e) => onChange(e.target.checked)} /><span>{field.label}</span></label>{help}</div>);
2026
+ case 'TEXT':
2027
+ default:
2028
+ return (<div>{label}<input id={id} type="text" required={field.isRequired} maxLength={maxLength} minLength={minLength} pattern={pattern} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2029
+ }
2030
+ }
2031
+
2032
+ export function ContactPage() {
2033
+ const [schema, setSchema] = useState<ContactFormPublic | null>(null);
2034
+ const [values, setValues] = useState<Record<string, FieldValue>>({});
2035
+ const [honeypot, setHoneypot] = useState('');
2036
+ const [sent, setSent] = useState(false);
2037
+ const [loading, setLoading] = useState(false);
2038
+
2039
+ // Read the current locale from the <html lang> attribute (or your own i18n context).
2040
+ const locale = typeof document !== 'undefined' ? document.documentElement.lang || undefined : undefined;
2041
+
2042
+ useEffect(() => {
2043
+ brainerce.contactForms.get('main', locale).then((form) => {
2044
+ setSchema(form);
2045
+ const initial: Record<string, FieldValue> = {};
2046
+ for (const f of form.fields) initial[f.key] = defaultValueFor(f);
2047
+ setValues(initial);
2048
+ });
2049
+ }, [locale]);
2050
+
2051
+ if (!schema) return null;
2052
+
2053
+ const onSubmit = async (e: React.FormEvent) => {
2054
+ e.preventDefault();
2055
+ if (loading) return;
2056
+ if (honeypot.trim().length > 0) { setSent(true); return; } // bot \u2192 silent success
2057
+
2058
+ setLoading(true);
2059
+ try {
2060
+ const payload: Record<string, unknown> = {};
2061
+ for (const f of schema.fields) {
2062
+ const raw = values[f.key];
2063
+ if (isEmpty(raw)) continue;
2064
+ payload[f.key] = typeof raw === 'string' ? raw.trim() : raw;
2065
+ }
2066
+ await brainerce.createInquiry({ formKey: schema.key, fields: payload, locale });
2067
+ setSent(true);
2068
+ } finally {
2069
+ setLoading(false);
2070
+ }
2071
+ };
2072
+
2073
+ if (sent) {
2074
+ // RENDER THE MERCHANT'S success message \u2014 do not hardcode.
2075
+ return <div>{schema.successMessage}</div>;
2076
+ }
2077
+
2078
+ return (
2079
+ <form onSubmit={onSubmit} noValidate>
2080
+ <h1>{schema.name}</h1>
2081
+ {schema.description && <p>{schema.description}</p>}
2082
+
2083
+ {/* Honeypot \u2014 must be visually hidden from humans, not from bots */}
2084
+ <div aria-hidden style={{ position: 'absolute', left: '-10000px', width: 0, height: 0, overflow: 'hidden' }}>
2085
+ <label htmlFor="contact-honeypot">Leave this field empty</label>
2086
+ <input id="contact-honeypot" type="text" tabIndex={-1} autoComplete="off"
2087
+ value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
2088
+ </div>
2089
+
2090
+ {schema.fields.map((field) => (
2091
+ <DynamicField key={field.key} field={field}
2092
+ value={values[field.key] ?? defaultValueFor(field)}
2093
+ onChange={(v) => setValues((p) => ({ ...p, [field.key]: v }))} />
2094
+ ))}
2095
+
2096
+ <button type="submit" disabled={loading}>
2097
+ {loading ? '\u2026' : schema.submitButton}
2098
+ </button>
2099
+ </form>
2100
+ );
2101
+ }
2102
+ \`\`\`
2103
+
2104
+ ### Rules
2105
+
2106
+ - **Rate limit:** 3 submissions / 60s per IP \u2014 show a friendly "try again later" message on HTTP 429.
2107
+ - **Honeypot:** always render a hidden field named \`honeypot\` and **never send** it. Bots fill every input; the server rejects submissions carrying a non-empty \`honeypot\`.
2108
+ - **Built-in keys:** \`name\`, \`email\`, \`phone\`, \`subject\`, \`message\` always exist on the default form; the legacy \`createInquiry\` shape keeps working forever.
2109
+ - **Max values:** each field value is capped at 10 000 chars server-side. Validate client-side before submitting using \`field.validation.maxLength\`.
2110
+ - **Required fields:** respect \`field.isRequired\`. The server validates too, but show \`required\` on the input for browser-level UX.
2111
+ - **Validation:** when \`field.validation.pattern\` is present, pass it as the input's \`pattern\` attribute; the server also enforces it. Likewise \`minLength\`/\`maxLength\`/\`min\`/\`max\`.
2112
+ - **Enum values:** SELECT and MULTI_SELECT always return \`enumValues\` (non-empty array). Render from \`enumValues\`, never a hardcoded list.
2113
+ - **Visibility:** the server strips fields with \`isVisible=false\`, so \`schema.fields\` only contains things to render.
2114
+ - **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.
2115
+ - **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.
2116
+ - **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.)
2117
+ - **Caching:** the schema GET is safe to cache per \`{storeId, formKey, locale}\`. 60 s feels live without hammering the API.
2118
+
2119
+ ### Multiple forms
2120
+
2121
+ If the merchant set up more than one form (e.g. a \`main\` form on \`/contact\`
2122
+ and a \`newsletter\` form embedded in the footer), render each form from its
2123
+ own \`contactForms.get(key, locale)\` call. The \`formKey\` you pass to
2124
+ \`createInquiry\` must match.`;
2125
+ }
1632
2126
  function getSectionByTopic(topic, connectionId, currency) {
1633
2127
  const cid = connectionId || "vc_YOUR_CONNECTION_ID";
1634
2128
  const cur = currency || "USD";
@@ -1655,6 +2149,8 @@ function getSectionByTopic(topic, connectionId, currency) {
1655
2149
  return getDiscountsSection();
1656
2150
  case "recommendations":
1657
2151
  return getRecommendationsSection();
2152
+ case "product-customization-fields":
2153
+ return getProductCustomizationFieldsSection();
1658
2154
  case "tax":
1659
2155
  return getTaxDisplaySection(cur);
1660
2156
  case "i18n":
@@ -1665,6 +2161,8 @@ function getSectionByTopic(topic, connectionId, currency) {
1665
2161
  return getTypeQuickReference();
1666
2162
  case "admin":
1667
2163
  return getAdminApiSection();
2164
+ case "inquiries":
2165
+ return getContactInquiriesSection();
1668
2166
  case "all":
1669
2167
  return [
1670
2168
  "# Brainerce SDK \u2014 full topic dump",
@@ -1729,6 +2227,10 @@ function getSectionByTopic(topic, connectionId, currency) {
1729
2227
  "",
1730
2228
  "---",
1731
2229
  "",
2230
+ getProductCustomizationFieldsSection(),
2231
+ "",
2232
+ "---",
2233
+ "",
1732
2234
  getTaxDisplaySection(cur),
1733
2235
  "",
1734
2236
  "---",
@@ -1737,10 +2239,14 @@ function getSectionByTopic(topic, connectionId, currency) {
1737
2239
  "",
1738
2240
  "---",
1739
2241
  "",
1740
- getAdminApiSection()
2242
+ getAdminApiSection(),
2243
+ "",
2244
+ "---",
2245
+ "",
2246
+ getContactInquiriesSection()
1741
2247
  ].join("\n");
1742
2248
  default:
1743
- return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, tax, i18n, critical-rules, type-reference, admin, all`;
2249
+ 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`;
1744
2250
  }
1745
2251
  }
1746
2252
 
@@ -1760,11 +2266,13 @@ var GET_SDK_DOCS_SCHEMA = {
1760
2266
  "inventory",
1761
2267
  "discounts",
1762
2268
  "recommendations",
2269
+ "product-customization-fields",
1763
2270
  "tax",
1764
2271
  "critical-rules",
1765
2272
  "type-reference",
1766
2273
  "i18n",
1767
2274
  "admin",
2275
+ "inquiries",
1768
2276
  "all"
1769
2277
  ]).describe("The SDK documentation topic to retrieve"),
1770
2278
  connectionId: import_zod.z.string().optional().describe("Vibe-coded connection ID (starts with vc_). Used to personalize setup code."),
@@ -1804,6 +2312,7 @@ interface Product {
1804
2312
  brands?: Array<{ id: string; name: string }>;
1805
2313
  tags?: string[];
1806
2314
  metafields?: ProductMetafield[];
2315
+ customizationFields?: ProductCustomizationField[]; // Buyer input fields \u2014 render on PDP, send values in cart metadata. Account-wide fields (MetafieldDefinition.appliesToAllProducts=true) are folded in here automatically; no client-side merging.
1807
2316
  productAttributeOptions?: Array<{
1808
2317
  id: string;
1809
2318
  attributeId: string;
@@ -1862,6 +2371,32 @@ interface ProductMetafield {
1862
2371
  variantId?: string | null;
1863
2372
  }
1864
2373
 
2374
+ // Metafield type enum \u2014 used by ProductCustomizationField.type
2375
+ type MetafieldType =
2376
+ | 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME'
2377
+ | 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' | 'JSON'
2378
+ | 'IMAGE' | 'GALLERY'
2379
+ | 'SELECT' | 'MULTI_SELECT';
2380
+
2381
+ // Customer-facing input assigned per product. Render on the PDP in the order of \`position\`.
2382
+ // Submit values keyed by \`key\` inside AddToCartDto.metadata.
2383
+ // Upload files via \`uploadCustomizationFile()\` first, then place the returned \`url\` in metadata.
2384
+ interface ProductCustomizationField {
2385
+ definitionId: string;
2386
+ name: string; // Label to show buyers
2387
+ key: string; // Use as metadata key in AddToCartDto.metadata
2388
+ description?: string | null; // Help text
2389
+ type: MetafieldType;
2390
+ required: boolean;
2391
+ minLength?: number | null; // TEXT/TEXTAREA char bounds; MULTI_SELECT array bounds
2392
+ maxLength?: number | null;
2393
+ minValue?: number | null; // NUMBER bounds
2394
+ maxValue?: number | null;
2395
+ enumValues?: string[]; // REQUIRED for SELECT / MULTI_SELECT
2396
+ defaultValue?: string | null;
2397
+ position: number; // Render order
2398
+ }
2399
+
1865
2400
  interface ProductQueryParams {
1866
2401
  page?: number;
1867
2402
  limit?: number;
@@ -1945,6 +2480,7 @@ interface CartItem {
1945
2480
  sku?: string | null;
1946
2481
  image?: ProductImage | string | null;
1947
2482
  } | null;
2483
+ metadata?: Record<string, unknown> | null; // Buyer-submitted customization values, keyed by ProductCustomizationField.key
1948
2484
  createdAt: string;
1949
2485
  updatedAt: string;
1950
2486
  }
@@ -2009,6 +2545,9 @@ interface Checkout {
2009
2545
  taxAmount: string;
2010
2546
  taxBreakdown?: TaxBreakdown | null;
2011
2547
  total: string;
2548
+ surchargeAmount: string;
2549
+ appliedSurcharges?: Array<{ key: string; name: string; value: unknown; amount: string }> | null;
2550
+ customFieldValues?: Record<string, unknown> | null;
2012
2551
  couponCode?: string | null;
2013
2552
  lineItems: CheckoutLineItem[]; // Use THIS for order summary, NOT cart.items!
2014
2553
  itemCount: number;
@@ -2027,6 +2566,7 @@ interface CheckoutLineItem {
2027
2566
  discountAmount: string;
2028
2567
  product: { id: string; name: string; sku: string; images?: ProductImage[]; };
2029
2568
  variant?: { id: string; name?: string | null; sku?: string | null; image?: ProductImage | string | null; } | null;
2569
+ metadata?: Record<string, unknown> | null; // Copied from CartItem.metadata \u2014 buyer customization values
2030
2570
  }
2031
2571
 
2032
2572
  interface CheckoutAddress {
@@ -2108,6 +2648,27 @@ interface Order {
2108
2648
  billingAddress?: OrderAddress;
2109
2649
  hasDownloads?: boolean;
2110
2650
  createdAt: string;
2651
+
2652
+ // Payment + fulfillment
2653
+ paymentMethod?: string | null;
2654
+ financialStatus?: string | null; // "pending" | "paid" | "refunded" | "partially_refunded" | "voided"
2655
+ fulfillmentStatus?: string | null; // "unfulfilled" | "partial" | "fulfilled"
2656
+
2657
+ // Tracking
2658
+ trackingNumber?: string | null;
2659
+ trackingUrl?: string | null;
2660
+ carrier?: string | null;
2661
+ shippedAt?: string | null; // ISO-8601
2662
+ deliveredAt?: string | null; // ISO-8601
2663
+
2664
+ // Timeline of status transitions, chronological
2665
+ statusHistory?: OrderStatusChange[] | null;
2666
+ }
2667
+
2668
+ interface OrderStatusChange {
2669
+ status: OrderStatus;
2670
+ at: string; // ISO-8601
2671
+ note?: string | null;
2111
2672
  }
2112
2673
 
2113
2674
  // \u26A0\uFE0F OrderItem is FLAT \u2014 unlike CartItem which is NESTED
@@ -2121,6 +2682,9 @@ interface OrderItem {
2121
2682
  unitPrice?: string; // alias
2122
2683
  totalPrice?: string;
2123
2684
  image?: string; // FLAT: item.image (NOT nested)
2685
+ // Snapshot of buyer-submitted customization values captured at checkout.
2686
+ // Keyed by metafield slug. \`value\` is string[] for MULTI_SELECT / GALLERY, string otherwise.
2687
+ customizations?: Record<string, { label: string; value: string | string[]; type: string }>;
2124
2688
  }
2125
2689
 
2126
2690
  interface OrderCustomer {
@@ -2342,7 +2906,129 @@ interface ProductRecommendationsResponse {
2342
2906
  }
2343
2907
  interface CartRecommendationsResponse {
2344
2908
  recommendations: ProductRecommendation[];
2909
+ }
2910
+
2911
+ // Cart include types (for consolidated getCart requests)
2912
+ type CartIncludeOption = 'recommendations' | 'upgrades' | 'bundles';
2913
+ interface CartIncludeOptions {
2914
+ include?: CartIncludeOption[];
2915
+ }
2916
+ interface CartWithIncludes extends Cart {
2917
+ recommendations?: { recommendations: ProductRecommendation[] };
2918
+ upgrades?: { upgrades: Record<string, CartUpgradeSuggestion> };
2919
+ bundles?: { bundles: CartBundleOffer[] };
2920
+ }
2921
+ interface CartUpgradeSuggestion {
2922
+ targetProduct: ProductRecommendation;
2923
+ priceDelta: string;
2924
+ deltaPercent: number;
2925
+ }
2926
+ interface CartBundleOffer {
2927
+ id: string;
2928
+ bundleProduct: ProductRecommendation;
2929
+ originalPrice: string;
2930
+ discountedPrice: string;
2931
+ discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
2932
+ discountValue: number;
2933
+ requiresVariantSelection: boolean;
2934
+ lockedVariant?: { id: string; name?: string };
2345
2935
  }`;
2936
+ var INQUIRIES_TYPES = `// ---- Contact Inquiries & Forms ----
2937
+
2938
+ // Two shapes \u2014 legacy and flexible. The two may be mixed; \`fields\` wins on key collision.
2939
+ interface CreateInquiryInput {
2940
+ // Legacy shape (still supported forever, backed by default "main" form)
2941
+ name?: string; // max 120 chars (if provided)
2942
+ email?: string; // must be valid email if provided
2943
+ subject?: string; // max 200 chars
2944
+ message?: string; // max 10000 chars
2945
+ phone?: string;
2946
+
2947
+ // Flexible shape
2948
+ formKey?: string; // defaults to "main"; merchant-defined keys e.g. "newsletter"
2949
+ fields?: Record<string, unknown>; // bag of values keyed by field key (built-in or custom)
2950
+ locale?: string; // e.g. "en", "he" \u2014 stored on the inquiry
2951
+ sourceMetadata?: Record<string, unknown>; // arbitrary context (e.g. { page: '/contact', campaign: 'fall-2026' })
2952
+
2953
+ // Shared
2954
+ customerId?: string; // link to logged-in customer
2955
+ metadata?: Record<string, unknown>; // deprecated alias of sourceMetadata
2956
+ }
2957
+
2958
+ interface CreateInquiryResponse {
2959
+ id: string;
2960
+ status: 'NEW';
2961
+ createdAt: string; // ISO datetime
2962
+ }
2963
+
2964
+ // ---- Form schema (for dynamic rendering) ----
2965
+
2966
+ type ContactFormFieldType =
2967
+ | 'TEXT' | 'TEXTAREA' | 'EMAIL' | 'PHONE' | 'NUMBER'
2968
+ | 'SELECT' | 'MULTI_SELECT' | 'CHECKBOX' | 'URL' | 'DATE';
2969
+
2970
+ interface ContactFormFieldValidation {
2971
+ minLength?: number;
2972
+ maxLength?: number;
2973
+ min?: number;
2974
+ max?: number;
2975
+ pattern?: string; // regex string
2976
+ patternMessage?: string;
2977
+ }
2978
+
2979
+ interface ContactFormPublicField {
2980
+ key: string; // stable identifier, e.g. "email", "company"
2981
+ type: ContactFormFieldType;
2982
+ label: string; // already localized for the requested locale
2983
+ placeholder?: string; // already localized
2984
+ helpText?: string; // already localized
2985
+ isRequired: boolean;
2986
+ enumValues?: { value: string; label: string }[]; // present (non-empty) for SELECT / MULTI_SELECT
2987
+ validation?: ContactFormFieldValidation;
2988
+ defaultValue?: string;
2989
+ }
2990
+
2991
+ interface ContactFormPublic {
2992
+ id: string;
2993
+ key: string; // e.g. "main", "newsletter"
2994
+ name: string; // already localized \u2014 use as form heading
2995
+ description?: string; // already localized \u2014 use as subtitle
2996
+ submitButton: string; // already localized \u2014 use as submit label
2997
+ successMessage: string; // already localized \u2014 render after submit succeeds
2998
+ fields: ContactFormPublicField[]; // in display order; hidden fields already filtered out
2999
+ }
3000
+
3001
+ interface ContactFormSummary {
3002
+ key: string;
3003
+ name: string;
3004
+ isDefault: boolean;
3005
+ }
3006
+
3007
+ // Field-type \u2192 HTML mapping for dynamic rendering
3008
+ // ------------------------------------------------------------------
3009
+ // TEXT \u2192 <input type="text" ... pattern?={validation.pattern}>
3010
+ // TEXTAREA \u2192 <textarea rows={6} ...>
3011
+ // EMAIL \u2192 <input type="email" autoComplete="email" ...>
3012
+ // PHONE \u2192 <input type="tel" autoComplete="tel" ...>
3013
+ // NUMBER \u2192 <input type="number" min={validation.min} max={validation.max}>
3014
+ // URL \u2192 <input type="url" ...>
3015
+ // DATE \u2192 <input type="date" ...> (value is ISO yyyy-MM-dd)
3016
+ // SELECT \u2192 <select>{enumValues.map(...)}</select> \u2014 always rendered from enumValues
3017
+ // MULTI_SELECT \u2192 multiple <input type="checkbox">, value is string[]
3018
+ // CHECKBOX \u2192 single <input type="checkbox">, value is boolean
3019
+ // ------------------------------------------------------------------
3020
+
3021
+ // SDK methods
3022
+ // await brainerce.createInquiry(input) \u2192 POST /stores/{storeId}/inquiries
3023
+ // await brainerce.contactForms.list() \u2192 GET /stores/{storeId}/contact-forms
3024
+ // await brainerce.contactForms.get(key?, locale?) \u2192 GET /stores/{storeId}/contact-forms/{key}?locale={locale}
3025
+ //
3026
+ // Rules
3027
+ // - Rate limit: 3 submissions / 60s per IP \u2014 handle 429 responses gracefully
3028
+ // - Honeypot: always render an invisible field named \`honeypot\` and never send it
3029
+ // - Always pass \`locale\` \u2014 inbox filters inquiries by language, and schema labels come back translated
3030
+ // - Render \`schema.name\` / \`description\` / \`submitButton\` / \`successMessage\` directly \u2014 do NOT hardcode copy
3031
+ // - Unknown field keys are stripped server-side \u2014 safe to send extras during dev`;
2346
3032
  var TYPES_BY_DOMAIN = {
2347
3033
  products: PRODUCTS_TYPES,
2348
3034
  cart: CART_TYPES,
@@ -2350,7 +3036,8 @@ var TYPES_BY_DOMAIN = {
2350
3036
  orders: ORDERS_TYPES,
2351
3037
  customers: CUSTOMERS_TYPES,
2352
3038
  payments: PAYMENTS_TYPES,
2353
- helpers: HELPERS_TYPES
3039
+ helpers: HELPERS_TYPES,
3040
+ inquiries: INQUIRIES_TYPES
2354
3041
  };
2355
3042
  function getTypesByDomain(domain) {
2356
3043
  if (domain === "all") {
@@ -2371,7 +3058,17 @@ var AVAILABLE_DOMAINS = Object.keys(TYPES_BY_DOMAIN);
2371
3058
  var GET_TYPE_DEFINITIONS_NAME = "get-type-definitions";
2372
3059
  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.";
2373
3060
  var GET_TYPE_DEFINITIONS_SCHEMA = {
2374
- domain: import_zod2.z.enum(["products", "cart", "checkout", "orders", "customers", "payments", "helpers", "all"]).describe(
3061
+ domain: import_zod2.z.enum([
3062
+ "products",
3063
+ "cart",
3064
+ "checkout",
3065
+ "orders",
3066
+ "customers",
3067
+ "payments",
3068
+ "helpers",
3069
+ "inquiries",
3070
+ "all"
3071
+ ]).describe(
2375
3072
  'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse.'
2376
3073
  )
2377
3074
  };
@@ -2405,7 +3102,8 @@ var GET_CODE_EXAMPLE_SCHEMA = {
2405
3102
  "coupon-apply-and-remove",
2406
3103
  "reservation-countdown",
2407
3104
  "search-autocomplete-debounce",
2408
- "i18n-set-locale"
3105
+ "i18n-set-locale",
3106
+ "order-history-full"
2409
3107
  ]).describe("The SDK operation to get a snippet for.")
2410
3108
  };
2411
3109
  var SNIPPETS = {
@@ -2500,23 +3198,51 @@ const checkout = await client.getCheckout(checkoutId);
2500
3198
  "checkout-payment-providers": `// Fetch configured payment providers for this checkout.
2501
3199
  import { client } from './brainerce';
2502
3200
 
2503
- const providers = await client.getPaymentProviders(checkoutId);
2504
- // providers = [{ provider, name, renderType, config }, ...]
2505
- // renderType tells you how to render:
2506
- // 'stripe-elements' \u2014 render Stripe Elements form and call stripe.confirmCardPayment
2507
- // 'redirect' \u2014 render a button that navigates to provider.authorizationUrl
2508
- // 'paypal' \u2014 render PayPal SDK button
2509
- // 'sandbox' \u2014 render a "complete test order" button (no real charge)
2510
-
2511
- // Pick the first configured provider by default (or let the user pick if
2512
- // multiple are configured).
2513
- const active = providers[0];
3201
+ const { providers, hasPayments, defaultProvider } = await client.getPaymentProviders();
3202
+ // each provider: { id, provider, name, publicKey, supportedMethods, testMode, isDefault, clientSdk? }
3203
+ //
3204
+ // After createPaymentIntent, the response carries a clientSdk.renderType that
3205
+ // tells your UI how to render the payment step. The 5 possible values:
3206
+ //
3207
+ // 'sdk-widget' \u2014 Load the provider's JS SDK (scriptUrl), then mount
3208
+ // into a <div id={containerId}>. Used by Stripe,
3209
+ // PayPal, Grow. The SDK paints its own form inside
3210
+ // your DOM. You control layout/placement.
3211
+ //
3212
+ // 'iframe' \u2014 Render <iframe src={clientSecret}>. Two flavors:
3213
+ // a) URL path contains "/embed/" \u2192 Brainerce-hosted
3214
+ // embed page. Render INLINE in your checkout
3215
+ // flow. Listen for postMessage:
3216
+ // - 'brainerce:resize' \u2192 update iframe height
3217
+ // - 'brainerce:redirect' \u2192 validated top-level
3218
+ // navigation (e.g. Bit express-pay)
3219
+ // b) Any other URL \u2192 provider-hosted page. Render
3220
+ // inside a modal overlay (it carries its own
3221
+ // branding/chrome).
3222
+ //
3223
+ // 'redirect' \u2014 Full-page navigate: window.location.href = URL.
3224
+ // Customer leaves your site, pays on provider page,
3225
+ // returns via SuccessRedirectUrl.
3226
+ //
3227
+ // 'sandbox' \u2014 Test mode. Render a "Complete Test Order" button;
3228
+ // call completeGuestCheckout(checkoutId). Orders are
3229
+ // flagged isTestOrder: true. No real charge.
3230
+ //
3231
+ // 'embedded-fields' \u2014 (Reserved \u2014 not yet shipped in any provider.) PCI
3232
+ // micro-iframes for sensitive fields (card number,
3233
+ // CVV) mounted directly into the merchant form. Full
3234
+ // control of surrounding layout, like Stripe
3235
+ // Elements. Requires the provider to ship a client
3236
+ // SDK that exposes mount points.
3237
+ //
3238
+ // Always branch on clientSdk.renderType \u2014 NEVER hard-code by provider name.
3239
+ // New providers can be added without storefront changes.
2514
3240
 
2515
- // If providers is empty, NO payment provider is configured and customers
2516
- // cannot pay. Display a clear error \u2014 do not try to fake a checkout.
2517
3241
  if (providers.length === 0) {
2518
3242
  throw new Error('No payment provider configured for this store');
2519
- }`,
3243
+ }
3244
+
3245
+ const active = providers[0];`,
2520
3246
  "checkout-stripe-confirm": `// Stripe confirm flow. Requires @stripe/stripe-js and @stripe/react-stripe-js
2521
3247
  // (or the vanilla Stripe.js browser SDK).
2522
3248
  import { loadStripe } from '@stripe/stripe-js';
@@ -2730,12 +3456,82 @@ const locale = 'he'; // e.g., from the /[locale] route segment
2730
3456
  client.setLocale(locale);
2731
3457
 
2732
3458
  // ALL content comes back translated: products, categories, brands,
2733
- // tags, variants, metafields, cart items, checkout line items,
2734
- // recommendations, search suggestions, discount banners, nudges,
3459
+ // tags, variants (name + attributes keys/values), metafields,
3460
+ // cart items, checkout line items, recommendations, bundles,
3461
+ // order bumps, search suggestions, discount banners, nudges,
2735
3462
  // badges, order history.
2736
3463
 
2737
3464
  // For RTL locales (he, ar), set the document direction.
2738
- // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`
3465
+ // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`,
3466
+ "order-history-full": `// Full "My Orders" account page. Render every piece of data the server
3467
+ // already returns \u2014 not just order number / total / status.
3468
+ //
3469
+ // Data you get from client.getMyOrders() (already on the wire today):
3470
+ // - items[].customizations \u2014 buyer's custom-field entries
3471
+ // - statusHistory \u2014 status timeline
3472
+ // - shippingAddress \u2014 name + address lines + country
3473
+ // - trackingNumber / trackingUrl / carrier / shippedAt / deliveredAt
3474
+ // - paymentMethod / financialStatus / fulfillmentStatus
3475
+ // - appliedDiscounts \u2014 shaped buyer-facing view
3476
+ // - hasDownloads \u2014 call /orders/:id/downloads to fetch
3477
+ //
3478
+ // Do NOT render: accountId, storeId, customerId, notes, customFieldValues
3479
+ // (merchant-internal, order-level), appliedRuleIds, appliedSurcharges,
3480
+ // surchargeAmount, downloadMeta (raw), pickupLocationData. The backend
3481
+ // does not return these to buyers \u2014 if you see them in a type, they're
3482
+ // an oversight; still skip them.
3483
+ import { client } from './brainerce';
3484
+ import type { Order, OrderItem, OrderStatusChange } from 'brainerce';
3485
+
3486
+ const { data: orders } = await client.getMyOrders({ page: 1, limit: 10 });
3487
+
3488
+ for (const order of orders) {
3489
+ // Line items + per-item customizations
3490
+ for (const item of order.items) {
3491
+ // item.image, item.productName, item.quantity, item.price
3492
+ if (item.customizations) {
3493
+ for (const [fieldId, entry] of Object.entries(item.customizations)) {
3494
+ // entry = { label, value, type }
3495
+ // Type-aware render (see account-page section in get-sdk-docs):
3496
+ // TEXT / TEXTAREA / URL / NUMBER / SELECT \u2014 plain text
3497
+ // BOOLEAN \u2014 \u2713 / \u2717
3498
+ // MULTI_SELECT \u2014 comma-separated
3499
+ // IMAGE \u2014 <img src={value}>
3500
+ // GALLERY \u2014 wrap grid of <img>
3501
+ // COLOR \u2014 swatch + hex
3502
+ // DATE / DATETIME \u2014 localized format
3503
+ }
3504
+ }
3505
+ }
3506
+
3507
+ // Status timeline \u2014 skip silently when null/empty
3508
+ if (order.statusHistory?.length) {
3509
+ for (const entry of order.statusHistory as OrderStatusChange[]) {
3510
+ // entry = { status, at, note? }
3511
+ // Render a dot + localized status label + new Date(entry.at).toLocaleString()
3512
+ }
3513
+ }
3514
+
3515
+ // Shipping + tracking
3516
+ if (order.shippingAddress) {
3517
+ // Render firstName lastName \xB7 line1 \xB7 line2 \xB7 city, region \xB7 postalCode \xB7 country
3518
+ }
3519
+ if (order.trackingNumber) {
3520
+ // Render carrier \xB7 trackingNumber, shippedAt/deliveredAt dates,
3521
+ // and an anchor to order.trackingUrl when present.
3522
+ }
3523
+
3524
+ // Payment
3525
+ if (order.paymentMethod || order.financialStatus) {
3526
+ // paymentMethod: 'card' | 'paypal' | 'bank_transfer' | 'cash_on_delivery' | ...
3527
+ // financialStatus: 'pending' | 'paid' | 'refunded' | 'partially_refunded' | 'voided'
3528
+ // Map financialStatus \u2192 a colored badge.
3529
+ }
3530
+ }
3531
+
3532
+ // All sections above are conditional. Absent data = section not rendered \u2014
3533
+ // never show empty placeholders. The create-brainerce-store template's
3534
+ // src/components/account/order-history.tsx is the reference implementation.`
2739
3535
  };
2740
3536
  async function handleGetCodeExample(args) {
2741
3537
  const snippet = SNIPPETS[args.operation];
@@ -3201,7 +3997,7 @@ var RULES = {
3201
3997
  - All prices are STRINGS in the SDK. \`parseFloat\` them before math or comparisons.
3202
3998
  - CartItem and CheckoutLineItem are NESTED (\`item.product.name\`, \`item.unitPrice\`). OrderItem is FLAT (\`item.name\`, \`item.price\`). They are not interchangeable.
3203
3999
  - Cart has no \`.total\` field \u2014 call \`getCartTotals(cart)\` to get \`{ subtotal, tax, shipping, discount, total }\`.
3204
- - \`smartGetCart()\` returns a discriminated union (\`Cart | LocalCart\`). Check \`'id' in cart\` before using server-only fields.
4000
+ - \`smartGetCart()\` returns \`CartWithIncludes\` (extends \`Cart\`). Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
3205
4001
  - \`startGuestCheckout()\` is also a discriminated union. Check \`result.tracked\` before reading \`result.checkoutId\`.`
3206
4002
  }
3207
4003
  };
@@ -3239,6 +4035,7 @@ var GET_BUSINESS_FLOWS_SCHEMA = {
3239
4035
  "order-confirmation",
3240
4036
  "cart-persistence",
3241
4037
  "inventory-reservation",
4038
+ "product-customization",
3242
4039
  "all"
3243
4040
  ]).describe('Which flow to retrieve. Use "all" to get every flow.')
3244
4041
  };
@@ -3358,7 +4155,7 @@ Build the OAuth button region AND the callback handler even when no providers ar
3358
4155
  - **Reads:** \`client.getCart()\` returns the current cart. Call it on mount in your cart UI and on any page that shows a cart count (header).
3359
4156
  - **Writes:** use \`client.addToCart\`, \`client.updateCartItem\`, \`client.removeCartItem\`, \`client.applyCoupon\`, \`client.removeCoupon\`. After each mutation the SDK returns the updated cart.
3360
4157
  - **Totals:** call \`getCartTotals(cart)\` \u2014 do NOT read \`cart.total\`. The helper understands taxes, shipping, and discounts.
3361
- - **\`smartGetCart()\`** returns \`Cart | LocalCart\` (guest users have no server cart until they add an item). Check \`'id' in cart\` before using server-only fields.
4158
+ - **\`smartGetCart()\`** returns \`CartWithIncludes\` (extends \`Cart\`). All carts are server-side. Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
3362
4159
  - **NEVER mutate cart state outside SDK helpers.** Any hand-rolled cart update risks desync with the reservation timer and the checkout flow.`
3363
4160
  },
3364
4161
  "inventory-reservation": {
@@ -3372,6 +4169,54 @@ Build the OAuth button region AND the callback handler even when no providers ar
3372
4169
  - **On the cart page:** show per-item availability \u2014 items that can no longer be purchased (because their reservation expired or the stock dropped) should display an "out of stock" badge and the "proceed to checkout" action should be disabled until they are removed.
3373
4170
 
3374
4171
  The reservation strategy (\`HARD\` vs \`SOFT\`) is exposed via \`get-store-capabilities\`. A HARD reservation means the stock is physically held; a SOFT reservation just tracks intent. Your UI behaves identically either way \u2014 the SDK hides the difference.`
4172
+ },
4173
+ "product-customization": {
4174
+ title: "Product customization (buyer input)",
4175
+ body: `Products can ship with \`customizationFields: ProductCustomizationField[]\` \u2014 buyer-filled inputs (engraving text, uploaded photo, pick-a-color, etc.). If you ignore them, merchants lose the data they need to fulfill the order.
4176
+
4177
+ 1. **Read the fields** from the product payload. Sort by \`position\`. If the array is empty, nothing to render.
4178
+ 2. **Render one control per field** based on \`type\`:
4179
+ - \`TEXT\` / \`URL\` / \`COLOR\` / \`DIMENSION\` / \`WEIGHT\` \u2192 \`<input type="text">\` (honour \`minLength\`/\`maxLength\`)
4180
+ - \`TEXTAREA\` \u2192 \`<textarea>\`
4181
+ - \`NUMBER\` \u2192 \`<input type="number">\` (honour \`minValue\`/\`maxValue\`)
4182
+ - \`BOOLEAN\` \u2192 checkbox (value \`true\`/\`false\`)
4183
+ - \`DATE\` \u2192 \`<input type="date">\` (ISO \`YYYY-MM-DD\`)
4184
+ - \`DATETIME\` \u2192 \`<input type="datetime-local">\` (ISO timestamp)
4185
+ - \`SELECT\` \u2192 \`<select>\` populated from \`enumValues\` (value = one string)
4186
+ - \`MULTI_SELECT\` \u2192 checkbox group from \`enumValues\` (value = \`string[]\`)
4187
+ - \`IMAGE\` \u2192 file input + preview (value = one URL string)
4188
+ - \`GALLERY\` \u2192 multi-file input (value = \`string[]\` of URLs)
4189
+ - \`JSON\` \u2192 advanced; render an admin-style editor or skip unless you control the data
4190
+ 3. **For IMAGE / GALLERY types: upload FIRST, then attach the URL.** Call \`client.uploadCustomizationFile(file)\` \u2014 it returns \`{ url }\`. Put that \`url\` string into the field value. NEVER put a \`File\` object in cart metadata.
4191
+ 4. **Enforce \`required: true\` client-side** before add-to-cart \u2014 show a red hint, block submit. The server re-validates; you want the user to fix it before the request fails.
4192
+ 5. **Add to cart with metadata keyed by \`field.key\`:**
4193
+ \`\`\`ts
4194
+ await client.addToCart({
4195
+ productId,
4196
+ quantity: 1,
4197
+ metadata: {
4198
+ engraving_text: 'For Mom',
4199
+ frame_color: 'Gold',
4200
+ upload_photo: photoUrl, // from uploadCustomizationFile()
4201
+ addons: ['Gift wrap'], // MULTI_SELECT
4202
+ },
4203
+ });
4204
+ \`\`\`
4205
+ 6. **On cart / checkout UIs, surface the metadata.** \`CartItem.metadata\` and \`CheckoutLineItem.metadata\` carry the values the buyer submitted. Show them in the line-item row so the buyer can verify before paying (especially uploaded image thumbnails).
4206
+ 7. **After the order is placed, values live on \`OrderItem.customizations\`** \u2014 a \`Record<string, { label, value, type }>\` keyed by field key. Definitions may be renamed/deleted after the order; the snapshot preserves what the buyer saw at purchase time.
4207
+
4208
+ **Apply-to-all fields.** A merchant can flag a \`MetafieldDefinition\` with \`appliesToAllProducts: true\` \u2014 the backend then includes it in every product's \`customizationFields\` array automatically, including products created after the flag was set. Your client code reads \`product.customizationFields\` as-is and never merges or unions anything \u2014 just render what's there.
4209
+
4210
+ Server-side guardrails that WILL reject bad requests (so validate client-side to avoid round-trips):
4211
+ - Unknown keys \u2192 rejected. Only use keys that appear in \`product.customizationFields\`.
4212
+ - Missing \`required\` fields \u2192 rejected.
4213
+ - \`SELECT\` value not in \`enumValues\` \u2192 rejected.
4214
+ - \`MULTI_SELECT\` value not \`string[]\` OR containing values outside \`enumValues\` \u2192 rejected.
4215
+ - \`IMAGE\` / \`GALLERY\` values must be URLs returned from \`/customization-upload\` on this store \u2014 pasting an external URL is rejected.
4216
+ - Upload > 5MB or non-image MIME \u2192 rejected by upload endpoint.
4217
+ - More than 10 uploads per IP per minute \u2192 429.
4218
+
4219
+ Never render customization fields without also wiring the upload + metadata flow \u2014 a form that submits nothing is worse than no form at all.`
3375
4220
  }
3376
4221
  };
3377
4222
  var FLOW_ORDER = [
@@ -3382,7 +4227,8 @@ var FLOW_ORDER = [
3382
4227
  "oauth",
3383
4228
  "order-confirmation",
3384
4229
  "cart-persistence",
3385
- "inventory-reservation"
4230
+ "inventory-reservation",
4231
+ "product-customization"
3386
4232
  ];
3387
4233
  async function handleGetBusinessFlows(args) {
3388
4234
  const header = "# Brainerce Business Flows\n\nThese sequences are framework-neutral and non-negotiable. Your framework and file layout are your choice \u2014 the order of SDK calls and the error handling is not.";
@@ -3447,6 +4293,14 @@ var FEATURES = [
3447
4293
  sdk: "client.getProductBySlug(slug). Helpers: getProductPriceInfo, getVariantPrice, getStockStatus, getVariantOptions, getProductSwatches, getDescriptionContent, getProductMetafieldValue.",
3448
4294
  mandatory: "mandatory"
3449
4295
  },
4296
+ {
4297
+ id: "product-customization-fields",
4298
+ title: "Render buyer-input customization fields on the product page",
4299
+ description: "When a product ships with `customizationFields` (engraving text, uploaded photo, picked color, date, select / multi-select), render one control per field sorted by `position`. Enforce required + enumValues + min/max client-side. For IMAGE / GALLERY, upload via client.uploadCustomizationFile() and place the returned URL in the value. Submit all values keyed by `field.key` inside addToCart({ metadata }). Show the metadata on cart / checkout rows so the buyer can verify. Build the UI anyway \u2014 it auto-hides when a product has no customization fields. NOTE: merchants can flag a definition with `appliesToAllProducts: true`; the backend folds those into every product's `customizationFields` array automatically \u2014 the client never merges or unions anything, just reads `product.customizationFields` as-is.",
4300
+ sdk: "product.customizationFields, client.uploadCustomizationFile(file), client.addToCart({ productId, quantity, metadata })",
4301
+ flowRef: "product-customization",
4302
+ mandatory: "mandatory"
4303
+ },
3450
4304
  {
3451
4305
  id: "cart",
3452
4306
  title: "Manage a cart with quantity, removal, and totals",