@brainerce/mcp-server 3.1.0 → 3.2.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
@@ -1655,6 +1890,8 @@ function getSectionByTopic(topic, connectionId, currency) {
1655
1890
  return getDiscountsSection();
1656
1891
  case "recommendations":
1657
1892
  return getRecommendationsSection();
1893
+ case "product-customization-fields":
1894
+ return getProductCustomizationFieldsSection();
1658
1895
  case "tax":
1659
1896
  return getTaxDisplaySection(cur);
1660
1897
  case "i18n":
@@ -1729,6 +1966,10 @@ function getSectionByTopic(topic, connectionId, currency) {
1729
1966
  "",
1730
1967
  "---",
1731
1968
  "",
1969
+ getProductCustomizationFieldsSection(),
1970
+ "",
1971
+ "---",
1972
+ "",
1732
1973
  getTaxDisplaySection(cur),
1733
1974
  "",
1734
1975
  "---",
@@ -1740,7 +1981,7 @@ function getSectionByTopic(topic, connectionId, currency) {
1740
1981
  getAdminApiSection()
1741
1982
  ].join("\n");
1742
1983
  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`;
1984
+ 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`;
1744
1985
  }
1745
1986
  }
1746
1987
 
@@ -1760,6 +2001,7 @@ var GET_SDK_DOCS_SCHEMA = {
1760
2001
  "inventory",
1761
2002
  "discounts",
1762
2003
  "recommendations",
2004
+ "product-customization-fields",
1763
2005
  "tax",
1764
2006
  "critical-rules",
1765
2007
  "type-reference",
@@ -1804,6 +2046,7 @@ interface Product {
1804
2046
  brands?: Array<{ id: string; name: string }>;
1805
2047
  tags?: string[];
1806
2048
  metafields?: ProductMetafield[];
2049
+ 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
2050
  productAttributeOptions?: Array<{
1808
2051
  id: string;
1809
2052
  attributeId: string;
@@ -1862,6 +2105,32 @@ interface ProductMetafield {
1862
2105
  variantId?: string | null;
1863
2106
  }
1864
2107
 
2108
+ // Metafield type enum \u2014 used by ProductCustomizationField.type
2109
+ type MetafieldType =
2110
+ | 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME'
2111
+ | 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' | 'JSON'
2112
+ | 'IMAGE' | 'GALLERY'
2113
+ | 'SELECT' | 'MULTI_SELECT';
2114
+
2115
+ // Customer-facing input assigned per product. Render on the PDP in the order of \`position\`.
2116
+ // Submit values keyed by \`key\` inside AddToCartDto.metadata.
2117
+ // Upload files via \`uploadCustomizationFile()\` first, then place the returned \`url\` in metadata.
2118
+ interface ProductCustomizationField {
2119
+ definitionId: string;
2120
+ name: string; // Label to show buyers
2121
+ key: string; // Use as metadata key in AddToCartDto.metadata
2122
+ description?: string | null; // Help text
2123
+ type: MetafieldType;
2124
+ required: boolean;
2125
+ minLength?: number | null; // TEXT/TEXTAREA char bounds; MULTI_SELECT array bounds
2126
+ maxLength?: number | null;
2127
+ minValue?: number | null; // NUMBER bounds
2128
+ maxValue?: number | null;
2129
+ enumValues?: string[]; // REQUIRED for SELECT / MULTI_SELECT
2130
+ defaultValue?: string | null;
2131
+ position: number; // Render order
2132
+ }
2133
+
1865
2134
  interface ProductQueryParams {
1866
2135
  page?: number;
1867
2136
  limit?: number;
@@ -1945,6 +2214,7 @@ interface CartItem {
1945
2214
  sku?: string | null;
1946
2215
  image?: ProductImage | string | null;
1947
2216
  } | null;
2217
+ metadata?: Record<string, unknown> | null; // Buyer-submitted customization values, keyed by ProductCustomizationField.key
1948
2218
  createdAt: string;
1949
2219
  updatedAt: string;
1950
2220
  }
@@ -2009,6 +2279,9 @@ interface Checkout {
2009
2279
  taxAmount: string;
2010
2280
  taxBreakdown?: TaxBreakdown | null;
2011
2281
  total: string;
2282
+ surchargeAmount: string;
2283
+ appliedSurcharges?: Array<{ key: string; name: string; value: unknown; amount: string }> | null;
2284
+ customFieldValues?: Record<string, unknown> | null;
2012
2285
  couponCode?: string | null;
2013
2286
  lineItems: CheckoutLineItem[]; // Use THIS for order summary, NOT cart.items!
2014
2287
  itemCount: number;
@@ -2027,6 +2300,7 @@ interface CheckoutLineItem {
2027
2300
  discountAmount: string;
2028
2301
  product: { id: string; name: string; sku: string; images?: ProductImage[]; };
2029
2302
  variant?: { id: string; name?: string | null; sku?: string | null; image?: ProductImage | string | null; } | null;
2303
+ metadata?: Record<string, unknown> | null; // Copied from CartItem.metadata \u2014 buyer customization values
2030
2304
  }
2031
2305
 
2032
2306
  interface CheckoutAddress {
@@ -2108,6 +2382,27 @@ interface Order {
2108
2382
  billingAddress?: OrderAddress;
2109
2383
  hasDownloads?: boolean;
2110
2384
  createdAt: string;
2385
+
2386
+ // Payment + fulfillment
2387
+ paymentMethod?: string | null;
2388
+ financialStatus?: string | null; // "pending" | "paid" | "refunded" | "partially_refunded" | "voided"
2389
+ fulfillmentStatus?: string | null; // "unfulfilled" | "partial" | "fulfilled"
2390
+
2391
+ // Tracking
2392
+ trackingNumber?: string | null;
2393
+ trackingUrl?: string | null;
2394
+ carrier?: string | null;
2395
+ shippedAt?: string | null; // ISO-8601
2396
+ deliveredAt?: string | null; // ISO-8601
2397
+
2398
+ // Timeline of status transitions, chronological
2399
+ statusHistory?: OrderStatusChange[] | null;
2400
+ }
2401
+
2402
+ interface OrderStatusChange {
2403
+ status: OrderStatus;
2404
+ at: string; // ISO-8601
2405
+ note?: string | null;
2111
2406
  }
2112
2407
 
2113
2408
  // \u26A0\uFE0F OrderItem is FLAT \u2014 unlike CartItem which is NESTED
@@ -2121,6 +2416,9 @@ interface OrderItem {
2121
2416
  unitPrice?: string; // alias
2122
2417
  totalPrice?: string;
2123
2418
  image?: string; // FLAT: item.image (NOT nested)
2419
+ // Snapshot of buyer-submitted customization values captured at checkout.
2420
+ // Keyed by metafield slug. \`value\` is string[] for MULTI_SELECT / GALLERY, string otherwise.
2421
+ customizations?: Record<string, { label: string; value: string | string[]; type: string }>;
2124
2422
  }
2125
2423
 
2126
2424
  interface OrderCustomer {
@@ -2342,6 +2640,32 @@ interface ProductRecommendationsResponse {
2342
2640
  }
2343
2641
  interface CartRecommendationsResponse {
2344
2642
  recommendations: ProductRecommendation[];
2643
+ }
2644
+
2645
+ // Cart include types (for consolidated getCart requests)
2646
+ type CartIncludeOption = 'recommendations' | 'upgrades' | 'bundles';
2647
+ interface CartIncludeOptions {
2648
+ include?: CartIncludeOption[];
2649
+ }
2650
+ interface CartWithIncludes extends Cart {
2651
+ recommendations?: { recommendations: ProductRecommendation[] };
2652
+ upgrades?: { upgrades: Record<string, CartUpgradeSuggestion> };
2653
+ bundles?: { bundles: CartBundleOffer[] };
2654
+ }
2655
+ interface CartUpgradeSuggestion {
2656
+ targetProduct: ProductRecommendation;
2657
+ priceDelta: string;
2658
+ deltaPercent: number;
2659
+ }
2660
+ interface CartBundleOffer {
2661
+ id: string;
2662
+ bundleProduct: ProductRecommendation;
2663
+ originalPrice: string;
2664
+ discountedPrice: string;
2665
+ discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
2666
+ discountValue: number;
2667
+ requiresVariantSelection: boolean;
2668
+ lockedVariant?: { id: string; name?: string };
2345
2669
  }`;
2346
2670
  var TYPES_BY_DOMAIN = {
2347
2671
  products: PRODUCTS_TYPES,
@@ -2405,7 +2729,8 @@ var GET_CODE_EXAMPLE_SCHEMA = {
2405
2729
  "coupon-apply-and-remove",
2406
2730
  "reservation-countdown",
2407
2731
  "search-autocomplete-debounce",
2408
- "i18n-set-locale"
2732
+ "i18n-set-locale",
2733
+ "order-history-full"
2409
2734
  ]).describe("The SDK operation to get a snippet for.")
2410
2735
  };
2411
2736
  var SNIPPETS = {
@@ -2500,23 +2825,51 @@ const checkout = await client.getCheckout(checkoutId);
2500
2825
  "checkout-payment-providers": `// Fetch configured payment providers for this checkout.
2501
2826
  import { client } from './brainerce';
2502
2827
 
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)
2828
+ const { providers, hasPayments, defaultProvider } = await client.getPaymentProviders();
2829
+ // each provider: { id, provider, name, publicKey, supportedMethods, testMode, isDefault, clientSdk? }
2830
+ //
2831
+ // After createPaymentIntent, the response carries a clientSdk.renderType that
2832
+ // tells your UI how to render the payment step. The 5 possible values:
2833
+ //
2834
+ // 'sdk-widget' \u2014 Load the provider's JS SDK (scriptUrl), then mount
2835
+ // into a <div id={containerId}>. Used by Stripe,
2836
+ // PayPal, Grow. The SDK paints its own form inside
2837
+ // your DOM. You control layout/placement.
2838
+ //
2839
+ // 'iframe' \u2014 Render <iframe src={clientSecret}>. Two flavors:
2840
+ // a) URL path contains "/embed/" \u2192 Brainerce-hosted
2841
+ // embed page. Render INLINE in your checkout
2842
+ // flow. Listen for postMessage:
2843
+ // - 'brainerce:resize' \u2192 update iframe height
2844
+ // - 'brainerce:redirect' \u2192 validated top-level
2845
+ // navigation (e.g. Bit express-pay)
2846
+ // b) Any other URL \u2192 provider-hosted page. Render
2847
+ // inside a modal overlay (it carries its own
2848
+ // branding/chrome).
2849
+ //
2850
+ // 'redirect' \u2014 Full-page navigate: window.location.href = URL.
2851
+ // Customer leaves your site, pays on provider page,
2852
+ // returns via SuccessRedirectUrl.
2853
+ //
2854
+ // 'sandbox' \u2014 Test mode. Render a "Complete Test Order" button;
2855
+ // call completeGuestCheckout(checkoutId). Orders are
2856
+ // flagged isTestOrder: true. No real charge.
2857
+ //
2858
+ // 'embedded-fields' \u2014 (Reserved \u2014 not yet shipped in any provider.) PCI
2859
+ // micro-iframes for sensitive fields (card number,
2860
+ // CVV) mounted directly into the merchant form. Full
2861
+ // control of surrounding layout, like Stripe
2862
+ // Elements. Requires the provider to ship a client
2863
+ // SDK that exposes mount points.
2864
+ //
2865
+ // Always branch on clientSdk.renderType \u2014 NEVER hard-code by provider name.
2866
+ // New providers can be added without storefront changes.
2510
2867
 
2511
- // Pick the first configured provider by default (or let the user pick if
2512
- // multiple are configured).
2513
- const active = providers[0];
2514
-
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
2868
  if (providers.length === 0) {
2518
2869
  throw new Error('No payment provider configured for this store');
2519
- }`,
2870
+ }
2871
+
2872
+ const active = providers[0];`,
2520
2873
  "checkout-stripe-confirm": `// Stripe confirm flow. Requires @stripe/stripe-js and @stripe/react-stripe-js
2521
2874
  // (or the vanilla Stripe.js browser SDK).
2522
2875
  import { loadStripe } from '@stripe/stripe-js';
@@ -2730,12 +3083,82 @@ const locale = 'he'; // e.g., from the /[locale] route segment
2730
3083
  client.setLocale(locale);
2731
3084
 
2732
3085
  // ALL content comes back translated: products, categories, brands,
2733
- // tags, variants, metafields, cart items, checkout line items,
2734
- // recommendations, search suggestions, discount banners, nudges,
3086
+ // tags, variants (name + attributes keys/values), metafields,
3087
+ // cart items, checkout line items, recommendations, bundles,
3088
+ // order bumps, search suggestions, discount banners, nudges,
2735
3089
  // badges, order history.
2736
3090
 
2737
3091
  // For RTL locales (he, ar), set the document direction.
2738
- // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`
3092
+ // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`,
3093
+ "order-history-full": `// Full "My Orders" account page. Render every piece of data the server
3094
+ // already returns \u2014 not just order number / total / status.
3095
+ //
3096
+ // Data you get from client.getMyOrders() (already on the wire today):
3097
+ // - items[].customizations \u2014 buyer's custom-field entries
3098
+ // - statusHistory \u2014 status timeline
3099
+ // - shippingAddress \u2014 name + address lines + country
3100
+ // - trackingNumber / trackingUrl / carrier / shippedAt / deliveredAt
3101
+ // - paymentMethod / financialStatus / fulfillmentStatus
3102
+ // - appliedDiscounts \u2014 shaped buyer-facing view
3103
+ // - hasDownloads \u2014 call /orders/:id/downloads to fetch
3104
+ //
3105
+ // Do NOT render: accountId, storeId, customerId, notes, customFieldValues
3106
+ // (merchant-internal, order-level), appliedRuleIds, appliedSurcharges,
3107
+ // surchargeAmount, downloadMeta (raw), pickupLocationData. The backend
3108
+ // does not return these to buyers \u2014 if you see them in a type, they're
3109
+ // an oversight; still skip them.
3110
+ import { client } from './brainerce';
3111
+ import type { Order, OrderItem, OrderStatusChange } from 'brainerce';
3112
+
3113
+ const { data: orders } = await client.getMyOrders({ page: 1, limit: 10 });
3114
+
3115
+ for (const order of orders) {
3116
+ // Line items + per-item customizations
3117
+ for (const item of order.items) {
3118
+ // item.image, item.productName, item.quantity, item.price
3119
+ if (item.customizations) {
3120
+ for (const [fieldId, entry] of Object.entries(item.customizations)) {
3121
+ // entry = { label, value, type }
3122
+ // Type-aware render (see account-page section in get-sdk-docs):
3123
+ // TEXT / TEXTAREA / URL / NUMBER / SELECT \u2014 plain text
3124
+ // BOOLEAN \u2014 \u2713 / \u2717
3125
+ // MULTI_SELECT \u2014 comma-separated
3126
+ // IMAGE \u2014 <img src={value}>
3127
+ // GALLERY \u2014 wrap grid of <img>
3128
+ // COLOR \u2014 swatch + hex
3129
+ // DATE / DATETIME \u2014 localized format
3130
+ }
3131
+ }
3132
+ }
3133
+
3134
+ // Status timeline \u2014 skip silently when null/empty
3135
+ if (order.statusHistory?.length) {
3136
+ for (const entry of order.statusHistory as OrderStatusChange[]) {
3137
+ // entry = { status, at, note? }
3138
+ // Render a dot + localized status label + new Date(entry.at).toLocaleString()
3139
+ }
3140
+ }
3141
+
3142
+ // Shipping + tracking
3143
+ if (order.shippingAddress) {
3144
+ // Render firstName lastName \xB7 line1 \xB7 line2 \xB7 city, region \xB7 postalCode \xB7 country
3145
+ }
3146
+ if (order.trackingNumber) {
3147
+ // Render carrier \xB7 trackingNumber, shippedAt/deliveredAt dates,
3148
+ // and an anchor to order.trackingUrl when present.
3149
+ }
3150
+
3151
+ // Payment
3152
+ if (order.paymentMethod || order.financialStatus) {
3153
+ // paymentMethod: 'card' | 'paypal' | 'bank_transfer' | 'cash_on_delivery' | ...
3154
+ // financialStatus: 'pending' | 'paid' | 'refunded' | 'partially_refunded' | 'voided'
3155
+ // Map financialStatus \u2192 a colored badge.
3156
+ }
3157
+ }
3158
+
3159
+ // All sections above are conditional. Absent data = section not rendered \u2014
3160
+ // never show empty placeholders. The create-brainerce-store template's
3161
+ // src/components/account/order-history.tsx is the reference implementation.`
2739
3162
  };
2740
3163
  async function handleGetCodeExample(args) {
2741
3164
  const snippet = SNIPPETS[args.operation];
@@ -3201,7 +3624,7 @@ var RULES = {
3201
3624
  - All prices are STRINGS in the SDK. \`parseFloat\` them before math or comparisons.
3202
3625
  - CartItem and CheckoutLineItem are NESTED (\`item.product.name\`, \`item.unitPrice\`). OrderItem is FLAT (\`item.name\`, \`item.price\`). They are not interchangeable.
3203
3626
  - 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.
3627
+ - \`smartGetCart()\` returns \`CartWithIncludes\` (extends \`Cart\`). Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
3205
3628
  - \`startGuestCheckout()\` is also a discriminated union. Check \`result.tracked\` before reading \`result.checkoutId\`.`
3206
3629
  }
3207
3630
  };
@@ -3239,6 +3662,7 @@ var GET_BUSINESS_FLOWS_SCHEMA = {
3239
3662
  "order-confirmation",
3240
3663
  "cart-persistence",
3241
3664
  "inventory-reservation",
3665
+ "product-customization",
3242
3666
  "all"
3243
3667
  ]).describe('Which flow to retrieve. Use "all" to get every flow.')
3244
3668
  };
@@ -3358,7 +3782,7 @@ Build the OAuth button region AND the callback handler even when no providers ar
3358
3782
  - **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
3783
  - **Writes:** use \`client.addToCart\`, \`client.updateCartItem\`, \`client.removeCartItem\`, \`client.applyCoupon\`, \`client.removeCoupon\`. After each mutation the SDK returns the updated cart.
3360
3784
  - **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.
3785
+ - **\`smartGetCart()\`** returns \`CartWithIncludes\` (extends \`Cart\`). All carts are server-side. Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
3362
3786
  - **NEVER mutate cart state outside SDK helpers.** Any hand-rolled cart update risks desync with the reservation timer and the checkout flow.`
3363
3787
  },
3364
3788
  "inventory-reservation": {
@@ -3372,6 +3796,54 @@ Build the OAuth button region AND the callback handler even when no providers ar
3372
3796
  - **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
3797
 
3374
3798
  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.`
3799
+ },
3800
+ "product-customization": {
3801
+ title: "Product customization (buyer input)",
3802
+ 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.
3803
+
3804
+ 1. **Read the fields** from the product payload. Sort by \`position\`. If the array is empty, nothing to render.
3805
+ 2. **Render one control per field** based on \`type\`:
3806
+ - \`TEXT\` / \`URL\` / \`COLOR\` / \`DIMENSION\` / \`WEIGHT\` \u2192 \`<input type="text">\` (honour \`minLength\`/\`maxLength\`)
3807
+ - \`TEXTAREA\` \u2192 \`<textarea>\`
3808
+ - \`NUMBER\` \u2192 \`<input type="number">\` (honour \`minValue\`/\`maxValue\`)
3809
+ - \`BOOLEAN\` \u2192 checkbox (value \`true\`/\`false\`)
3810
+ - \`DATE\` \u2192 \`<input type="date">\` (ISO \`YYYY-MM-DD\`)
3811
+ - \`DATETIME\` \u2192 \`<input type="datetime-local">\` (ISO timestamp)
3812
+ - \`SELECT\` \u2192 \`<select>\` populated from \`enumValues\` (value = one string)
3813
+ - \`MULTI_SELECT\` \u2192 checkbox group from \`enumValues\` (value = \`string[]\`)
3814
+ - \`IMAGE\` \u2192 file input + preview (value = one URL string)
3815
+ - \`GALLERY\` \u2192 multi-file input (value = \`string[]\` of URLs)
3816
+ - \`JSON\` \u2192 advanced; render an admin-style editor or skip unless you control the data
3817
+ 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.
3818
+ 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.
3819
+ 5. **Add to cart with metadata keyed by \`field.key\`:**
3820
+ \`\`\`ts
3821
+ await client.addToCart({
3822
+ productId,
3823
+ quantity: 1,
3824
+ metadata: {
3825
+ engraving_text: 'For Mom',
3826
+ frame_color: 'Gold',
3827
+ upload_photo: photoUrl, // from uploadCustomizationFile()
3828
+ addons: ['Gift wrap'], // MULTI_SELECT
3829
+ },
3830
+ });
3831
+ \`\`\`
3832
+ 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).
3833
+ 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.
3834
+
3835
+ **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.
3836
+
3837
+ Server-side guardrails that WILL reject bad requests (so validate client-side to avoid round-trips):
3838
+ - Unknown keys \u2192 rejected. Only use keys that appear in \`product.customizationFields\`.
3839
+ - Missing \`required\` fields \u2192 rejected.
3840
+ - \`SELECT\` value not in \`enumValues\` \u2192 rejected.
3841
+ - \`MULTI_SELECT\` value not \`string[]\` OR containing values outside \`enumValues\` \u2192 rejected.
3842
+ - \`IMAGE\` / \`GALLERY\` values must be URLs returned from \`/customization-upload\` on this store \u2014 pasting an external URL is rejected.
3843
+ - Upload > 5MB or non-image MIME \u2192 rejected by upload endpoint.
3844
+ - More than 10 uploads per IP per minute \u2192 429.
3845
+
3846
+ 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
3847
  }
3376
3848
  };
3377
3849
  var FLOW_ORDER = [
@@ -3382,7 +3854,8 @@ var FLOW_ORDER = [
3382
3854
  "oauth",
3383
3855
  "order-confirmation",
3384
3856
  "cart-persistence",
3385
- "inventory-reservation"
3857
+ "inventory-reservation",
3858
+ "product-customization"
3386
3859
  ];
3387
3860
  async function handleGetBusinessFlows(args) {
3388
3861
  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 +3920,14 @@ var FEATURES = [
3447
3920
  sdk: "client.getProductBySlug(slug). Helpers: getProductPriceInfo, getVariantPrice, getStockStatus, getVariantOptions, getProductSwatches, getDescriptionContent, getProductMetafieldValue.",
3448
3921
  mandatory: "mandatory"
3449
3922
  },
3923
+ {
3924
+ id: "product-customization-fields",
3925
+ title: "Render buyer-input customization fields on the product page",
3926
+ 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.",
3927
+ sdk: "product.customizationFields, client.uploadCustomizationFile(file), client.addToCart({ productId, quantity, metadata })",
3928
+ flowRef: "product-customization",
3929
+ mandatory: "mandatory"
3930
+ },
3450
3931
  {
3451
3932
  id: "cart",
3452
3933
  title: "Manage a cart with quantity, removal, and totals",