@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/index.mjs CHANGED
@@ -59,7 +59,7 @@ function getTypeQuickReference() {
59
59
  | OAuth | \`provider.name\` | \`provider\` | it IS the string: \`'GOOGLE' | 'FACEBOOK' | 'GITHUB'\` |
60
60
  | OAuth | \`oauth.url\` | \`oauth.authorizationUrl\` | |
61
61
  | Description | \`getDescriptionContent()\` | \`{ html } | { text } | null\` | check \`'html' in content\` before use |
62
- | \`smartGetCart()\` | always use \`.id\` | check \`'id' in cart\` | returns \`Cart | LocalCart\` |
62
+ | \`smartGetCart()\` | N/A | \`cart.id\` | returns \`CartWithIncludes\` (extends \`Cart\`); pass \`{ include: [...] }\` for extras |
63
63
  | \`startGuestCheckout()\` | always use \`.checkoutId\` | check \`result.tracked\` | discriminated union |
64
64
 
65
65
  **Rules:**
@@ -67,8 +67,8 @@ function getTypeQuickReference() {
67
67
  - CartItem/CheckoutLineItem = **NESTED** (\`item.product.name\`, \`item.unitPrice\`)
68
68
  - OrderItem = **FLAT** (\`item.name\`, \`item.price\`, \`item.totalPrice\`, \`item.image\`)
69
69
  - Cart has NO \`.total\` \u2014 use \`getCartTotals(cart)\`
70
- - \`getCartTotals()\` only works with server \`Cart\`, NOT \`LocalCart\`
71
- - \`smartGetCart()\` returns \`Cart | LocalCart\` \u2014 check \`'id' in cart\` before using Cart fields
70
+ - \`getCartTotals()\` works with server \`Cart\` (all carts are server-side now)
71
+ - \`smartGetCart()\` returns \`CartWithIncludes\` \u2014 always a server cart; pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` for extras
72
72
  - \`startGuestCheckout()\` returns discriminated union \u2014 check \`result.tracked\` before \`.checkoutId\`
73
73
  - \`SetShippingAddressDto.email\` is **required** \u2014 always include email
74
74
 
@@ -196,7 +196,7 @@ async function startCheckout() {
196
196
  6. Select shipping method \u2192 \`selectShippingMethod()\`
197
197
  6b. (Optional) Set checkout custom fields \u2192 \`setCheckoutCustomFields()\` \u2014 surcharges auto-calculated
198
198
  7. Create payment intent \u2192 \`createPaymentIntent()\` \u2192 returns \`{ clientSecret, provider }\`
199
- 8. Branch on \`provider\`: \`'stripe'\` \u2192 Stripe Elements, \`'grow'\` \u2192 iframe, \`'paypal'\` \u2192 PayPal Buttons
199
+ 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).
200
200
  9. **Order is created AUTOMATICALLY after payment succeeds (via webhook) \u2014 for ALL providers!**
201
201
 
202
202
  ### Checkout Page Component
@@ -299,8 +299,8 @@ function CheckoutPage() {
299
299
  </div>
300
300
  );
301
301
  }
302
- if (paymentData.provider === 'grow') {
303
- return <GrowPaymentForm paymentUrl={paymentData.clientSecret} checkoutId={paymentData.checkoutId} />;
302
+ if (paymentData.clientSdk?.renderType === 'iframe') {
303
+ return <PaymentIframe clientSecret={paymentData.clientSecret} checkoutId={paymentData.checkoutId} />;
304
304
  }
305
305
  if (paymentData.provider === 'paypal' && paypalClientId) {
306
306
  return <PayPalPaymentForm clientId={paypalClientId} orderId={paymentData.clientSecret} checkoutId={paymentData.checkoutId} />;
@@ -356,26 +356,82 @@ function StripePaymentForm({ checkoutId }: { checkoutId: string }) {
356
356
  }
357
357
  \`\`\`
358
358
 
359
- ### Grow Payment Form (Israeli stores \u2014 iframe based, no SDK needed)
359
+ ### Iframe-Based Providers (Cardcom, legacy Grow, etc.)
360
+
361
+ 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:
362
+
363
+ **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).
364
+
365
+ **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.
366
+
367
+ Detect flavor by URL path \u2014 works across localhost/staging/prod without a domain list:
360
368
 
361
369
  \`\`\`typescript
362
- function GrowPaymentForm({ paymentUrl, checkoutId }: { paymentUrl: string; checkoutId: string }) {
363
- const [iframeLoaded, setIframeLoaded] = useState(false);
370
+ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; checkoutId: string }) {
371
+ const [height, setHeight] = useState(540); // default before resize message arrives
372
+ const isBrainerceEmbed = (() => {
373
+ try { return new URL(clientSecret).pathname.includes('/embed/'); }
374
+ catch { return false; }
375
+ })();
376
+
377
+ useEffect(() => {
378
+ function handleMessage(e: MessageEvent) {
379
+ const data = e.data as { type?: string; height?: number; url?: string };
380
+ if (data?.type === 'brainerce:resize' && typeof data.height === 'number') {
381
+ setHeight(data.height);
382
+ }
383
+ if (data?.type === 'brainerce:redirect' && typeof data.url === 'string') {
384
+ // Top-level navigation (e.g. Bit). ALWAYS validate against an allowlist
385
+ // before navigating \u2014 never trust the URL blindly.
386
+ if (isTrustedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
387
+ }
388
+ if (data?.type === 'brainerce:payment-complete') {
389
+ // Payment done \u2014 redirect to confirmation page which verifies server-side
390
+ window.location.href = \`/order-confirmation?checkout_id=\${checkoutId}\`;
391
+ }
392
+ }
393
+ window.addEventListener('message', handleMessage);
394
+ return () => window.removeEventListener('message', handleMessage);
395
+ }, [checkoutId]);
396
+
397
+ if (isBrainerceEmbed) {
398
+ // Inline: part of the checkout flow, no overlay
399
+ return (
400
+ <div className="w-full">
401
+ <iframe
402
+ src={clientSecret}
403
+ style={{ width: '100%', height, border: 0, transition: 'height 0.2s ease-out' }}
404
+ title="Payment"
405
+ allow="payment"
406
+ />
407
+ </div>
408
+ );
409
+ }
410
+
411
+ // Provider-hosted page: modal overlay
364
412
  return (
365
- <div className="w-full">
366
- {!iframeLoaded && <div className="flex items-center justify-center py-12"><span>Loading payment form...</span></div>}
367
- <iframe
368
- src={paymentUrl}
369
- onLoad={() => setIframeLoaded(true)}
370
- style={{ width: '100%', minHeight: '600px', border: 'none', display: iframeLoaded ? 'block' : 'none' }}
371
- allow="payment"
372
- />
373
- <p className="text-center text-sm text-gray-500 mt-4">
374
- Having trouble? <a href={paymentUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 underline">Open payment in new tab</a>
375
- </p>
413
+ <div className="fixed inset-0 z-50 flex items-start justify-center bg-black/50 py-6 overflow-y-auto">
414
+ <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl mx-4">
415
+ <iframe
416
+ src={clientSecret}
417
+ style={{ width: '100%', height: '90vh', minHeight: 700, border: 0 }}
418
+ title="Payment"
419
+ allow="payment"
420
+ />
421
+ </div>
376
422
  </div>
377
423
  );
378
424
  }
425
+
426
+ // Allowlist of origins you trust for top-level payment redirects.
427
+ function isTrustedPaymentUrl(url: string): boolean {
428
+ try {
429
+ const u = new URL(url);
430
+ if (u.protocol !== 'https:') return false;
431
+ // Add your provider hostnames here. Example: Cardcom for Bit express-pay.
432
+ return u.hostname === 'cardcom.solutions' || u.hostname.endsWith('.cardcom.solutions');
433
+ } catch { return false; }
434
+ }
379
435
  \`\`\`
380
436
 
381
437
  ### PayPal Payment Form
@@ -645,12 +701,23 @@ const growProvider = providers.find(p => p.provider === 'grow');
645
701
  const paypalProvider = providers.find(p => p.provider === 'paypal');
646
702
  \`\`\`
647
703
 
648
- Each provider has: \`id\`, \`provider\` ('stripe'|'grow'|'paypal'|'sandbox'), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
704
+ Each provider has: \`id\`, \`provider\` (flexible string \u2014 \`'stripe'\`, \`'grow'\`, \`'paypal'\`, \`'cardcom'\`, \`'sandbox'\`, and future providers), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
705
+
706
+ 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**:
649
707
 
708
+ - \`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.
709
+ - \`renderType: 'iframe'\` \u2014 render \`<iframe src={clientSecret}>\`. Two flavors detected by URL path:
710
+ - Path contains \`/embed/\` \u2192 Brainerce-hosted embed. Render **INLINE** (no modal). Listen for \`brainerce:resize\` / \`brainerce:redirect\` postMessages. Used by Cardcom (embedded mode).
711
+ - Any other URL \u2192 provider-hosted page. Render inside a **modal**. Used by Cardcom (hosted mode), legacy Grow iframe.
712
+ - \`renderType: 'redirect'\` \u2014 \`window.location.href = URL\`. Customer completes payment off-site and returns via SuccessRedirectUrl.
713
+ - \`renderType: 'sandbox'\` \u2014 show a "Complete Test Order" button; call \`completeGuestCheckout(checkoutId)\`. Orders are \`isTestOrder: true\`. Appears when \`sandboxPaymentsEnabled\` is true.
714
+ - \`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.
715
+
716
+ Provider-specific install notes:
650
717
  - **Stripe:** \`npm install @stripe/stripe-js @stripe/react-stripe-js\` \u2014 \`loadStripe(publicKey, { stripeAccount })\`
651
- - **Grow:** No SDK \u2014 uses iframe with payment URL. Supports credit cards, Bit, Apple Pay, Google Pay.
652
718
  - **PayPal:** \`npm install @paypal/react-paypal-js\` \u2014 \`PayPalScriptProvider\` + \`PayPalButtons\`
653
- - **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\`.`;
719
+ - **Grow:** No SDK needed \u2014 JS SDK loaded via \`clientSdk.scriptUrl\`. Supports credit cards, Bit, Apple Pay, Google Pay.
720
+ - **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.`;
654
721
  }
655
722
  function getProductsSection(_currency) {
656
723
  return `## Products & Variants
@@ -681,10 +748,12 @@ When \`storeInfo.i18n.enabled\` is true, call \`client.setLocale(locale)\` once
681
748
  \`{ locale }\` params needed. Translated fields include: \`name\`,
682
749
  \`description\`, \`slug\`, \`seoTitle\`, \`seoDescription\`, plus
683
750
  \`categories[].name\`, \`brands[].name\`, \`tags[].name\`, \`variants[].name\`,
684
- \`productAttributeOptions[].attribute.name\`/\`attributeOption.name\`, and
685
- \`metafields[].value\`. No client-side overlay. See the full \`i18n\` section
686
- (\`get-sdk-docs\` topic \`i18n\`) for the \`[locale]\` route pattern, SDK setup,
687
- and the brand/tag badge examples.
751
+ \`variant.attributes\` keys and values (so \`getVariantOptions()\` returns
752
+ translated attribute/option names), \`productAttributeOptions[].attribute.name\`/
753
+ \`attributeOption.name\`, \`metafields[].value\`, cart item product/variant names,
754
+ and recommendation/bundle/bump product names. No client-side overlay. See the
755
+ full \`i18n\` section (\`get-sdk-docs\` topic \`i18n\`) for the \`[locale]\` route
756
+ pattern, SDK setup, and the brand/tag badge examples.
688
757
 
689
758
  ### Price Display (Use SDK Helper!)
690
759
 
@@ -821,6 +890,8 @@ const material = getProductMetafieldValue(product, 'material');
821
890
 
822
891
  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.
823
892
 
893
+ 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\`.
894
+
824
895
  \`\`\`typescript
825
896
  import { getProductCustomizationFields } from 'brainerce';
826
897
  import type { ProductCustomizationField } from 'brainerce';
@@ -879,7 +950,7 @@ function getCartSection(_currency) {
879
950
  ### Smart Cart Methods (RECOMMENDED)
880
951
 
881
952
  \`\`\`typescript
882
- const cart = await client.smartGetCart(); // Returns Cart | LocalCart
953
+ const cart = await client.smartGetCart(); // Returns CartWithIncludes (extends Cart)
883
954
  await client.smartAddToCart({
884
955
  productId: product.id,
885
956
  variantId: selectedVariant?.id,
@@ -1010,7 +1081,19 @@ const recs = (product as any).recommendations as ProductRecommendationsResponse
1010
1081
 
1011
1082
  ### Cart Page Features
1012
1083
 
1013
- **Cross-sell recommendations** (existing products the customer might also want):
1084
+ **Consolidated include** (fetch recommendations, upgrades, and bundles in one request):
1085
+ \`\`\`typescript
1086
+ import type { CartWithIncludes } from 'brainerce';
1087
+ const cart = await client.getCart(cartId, {
1088
+ include: ['recommendations', 'upgrades', 'bundles'],
1089
+ });
1090
+ // cart.recommendations \u2014 cross-sell recommendations
1091
+ // cart.upgrades \u2014 upgrade suggestions keyed by source product ID
1092
+ // cart.bundles \u2014 bundle offers
1093
+ // Also works with smartGetCart: client.smartGetCart({ include: ['recommendations', 'upgrades', 'bundles'] })
1094
+ \`\`\`
1095
+
1096
+ **Cross-sell recommendations** (or fetch individually for targeted refresh):
1014
1097
  \`\`\`typescript
1015
1098
  import type { CartRecommendationsResponse } from 'brainerce';
1016
1099
  const cartRecs = await client.getCartRecommendations(cartId, 4);
@@ -1102,6 +1185,110 @@ Always check the flag before rendering: \`if (storeInfo?.upsell?.featureName !==
1102
1185
  ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`, \`variants?\` (when variant selection needed).
1103
1186
  OrderBump/CartBundleOffer: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).`;
1104
1187
  }
1188
+ function getProductCustomizationFieldsSection() {
1189
+ return `## Product Customization Fields (buyer input on product page)
1190
+
1191
+ 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.
1192
+
1193
+ ### Where the fields come from
1194
+
1195
+ They arrive **embedded on the product response** \u2014 no extra API call:
1196
+
1197
+ \`\`\`typescript
1198
+ import type { Product, ProductCustomizationField, MetafieldType } from 'brainerce';
1199
+
1200
+ const product = await client.getProductBySlug(slug);
1201
+ const fields: ProductCustomizationField[] = product.customizationFields ?? [];
1202
+ // fields is sorted by position. If empty, render the product page normally.
1203
+ \`\`\`
1204
+
1205
+ Each field has:
1206
+ \`\`\`typescript
1207
+ {
1208
+ definitionId: string;
1209
+ key: string; // stable identifier \u2014 use this as the metadata key
1210
+ name: string; // display label (may be localized)
1211
+ description?: string | null;
1212
+ type: MetafieldType; // 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME' |
1213
+ // 'JSON' | 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' |
1214
+ // 'IMAGE' | 'GALLERY' | 'SELECT' | 'MULTI_SELECT'
1215
+ required: boolean;
1216
+ minLength?: number | null; // chars for TEXT/TEXTAREA; array size for MULTI_SELECT
1217
+ maxLength?: number | null;
1218
+ minValue?: number | null; // NUMBER / DIMENSION / WEIGHT
1219
+ maxValue?: number | null;
1220
+ enumValues?: string[]; // required for SELECT / MULTI_SELECT
1221
+ defaultValue?: string | null;
1222
+ position: number;
1223
+ }
1224
+ \`\`\`
1225
+
1226
+ ### Render one control per type
1227
+
1228
+ | type | Render as | Collected value |
1229
+ | --------------- | ---------------------------------------------------------- | ---------------------------- |
1230
+ | \`TEXT\` | \`<input type="text">\` | \`string\` |
1231
+ | \`TEXTAREA\` | \`<textarea>\` | \`string\` |
1232
+ | \`NUMBER\` | \`<input type="number">\` | \`number\` |
1233
+ | \`BOOLEAN\` | checkbox / switch | \`boolean\` |
1234
+ | \`DATE\` | \`<input type="date">\` | \`string\` (YYYY-MM-DD) |
1235
+ | \`DATETIME\` | \`<input type="datetime-local">\` | \`string\` (ISO 8601) |
1236
+ | \`URL\` | \`<input type="url">\` | \`string\` |
1237
+ | \`COLOR\` | \`<input type="color">\` | \`string\` (#RRGGBB) |
1238
+ | \`SELECT\` | \`<select>\` or radio group (use \`enumValues\`) | \`string\` (in enumValues) |
1239
+ | \`MULTI_SELECT\`| checkbox group (use \`enumValues\`) | \`string[]\` (every in enum) |
1240
+ | \`IMAGE\` | file input + upload via \`uploadCustomizationFile\` | \`string\` (URL) |
1241
+ | \`GALLERY\` | multi-file input + one upload per file | \`string[]\` (URLs) |
1242
+ | \`JSON\` | textarea; validate is parseable | \`string\` (JSON) |
1243
+
1244
+ ### Upload buyer-submitted images
1245
+
1246
+ \`IMAGE\` and \`GALLERY\` require uploading before add-to-cart:
1247
+
1248
+ \`\`\`typescript
1249
+ const { url } = await client.uploadCustomizationFile(file);
1250
+ // Server rules: image/* only, max 5 MB, 10 uploads/min per IP.
1251
+ // Files are retained for at least 7 days; after that, if the cart never
1252
+ // became an order, they are automatically deleted.
1253
+ \`\`\`
1254
+
1255
+ ### Add to cart with customization metadata
1256
+
1257
+ \`\`\`typescript
1258
+ // Collect values keyed by field.key \u2014 NOT by field.name or field.definitionId.
1259
+ const metadata: Record<string, unknown> = {
1260
+ engraving_text: 'Happy Birthday!', // TEXT
1261
+ frame_color: 'Gold', // SELECT (must be in enumValues)
1262
+ upload_photo: url, // IMAGE (URL from uploadCustomizationFile)
1263
+ addons: ['Gift wrap'], // MULTI_SELECT (always an array)
1264
+ };
1265
+
1266
+ await client.addToCart(cart.id, {
1267
+ productId: product.id,
1268
+ quantity: 1,
1269
+ metadata,
1270
+ });
1271
+ \`\`\`
1272
+
1273
+ Server validation (rejected with HTTP 400 on failure):
1274
+ - \`required: true\` \u2192 must be present and non-empty
1275
+ - \`TEXT\` / \`TEXTAREA\` \u2192 string; \`minLength\` / \`maxLength\` enforced as character count
1276
+ - \`NUMBER\` \u2192 \`minValue\` / \`maxValue\` enforced
1277
+ - \`SELECT\` \u2192 value must be one of \`enumValues\`
1278
+ - \`MULTI_SELECT\` \u2192 array; each element in \`enumValues\`; duplicates removed; \`minLength\` / \`maxLength\` enforced as array size
1279
+ - \`IMAGE\` / \`GALLERY\` \u2192 URL(s) must be from \`/customization-upload\` on this store
1280
+
1281
+ ### Order snapshot
1282
+
1283
+ 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.
1284
+
1285
+ ### Common mistakes
1286
+
1287
+ - Passing values keyed by \`field.name\` instead of \`field.key\` \u2192 silently ignored (unknown key)
1288
+ - Sending a \`MULTI_SELECT\` as a string instead of \`string[]\` \u2192 HTTP 400
1289
+ - Using a raw external URL (not from \`/customization-upload\`) for \`IMAGE\` / \`GALLERY\` \u2192 HTTP 400
1290
+ - Assuming \`enumValues\` is present for all types \u2014 only \`SELECT\` / \`MULTI_SELECT\` require it`;
1291
+ }
1105
1292
  function getInventorySection() {
1106
1293
  return `## Inventory, Stock Display & Reservation Countdown
1107
1294
 
@@ -1358,7 +1545,50 @@ const { data: orders } = await client.getMyOrders({ page: 1, limit: 10 }); // Re
1358
1545
  // \u274C WRONG \u2014 these methods don't exist!
1359
1546
  client.getCustomerProfile();
1360
1547
  client.getCustomerOrders();
1361
- \`\`\``;
1548
+ \`\`\`
1549
+
1550
+ ### Order history should show more than just totals
1551
+
1552
+ 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.
1553
+
1554
+ | Section | Source field | Notes |
1555
+ |---|---|---|
1556
+ | Header (number, status badge, date, total) | \`order.orderNumber\`, \`order.status\`, \`order.createdAt\`, \`order.totalAmount\` | Always present. |
1557
+ | Line items | \`order.items[]\` | Render image, name, qty, price. |
1558
+ | **Per-item customizations** | \`order.items[i].customizations\` | Map of { label, value, type }. Render by \`type\` \u2014 see table below. |
1559
+ | **Status timeline** | \`order.statusHistory\` | \`OrderStatusChange[]\`: \`{ status, at, note? }\`. Render as a vertical list. |
1560
+ | **Shipping address** | \`order.shippingAddress\` | Standard \`OrderAddress\` shape. |
1561
+ | **Tracking** | \`order.trackingNumber\`, \`order.trackingUrl\`, \`order.carrier\`, \`order.shippedAt\`, \`order.deliveredAt\` | Link out to \`trackingUrl\` when set. |
1562
+ | **Payment** | \`order.paymentMethod\`, \`order.financialStatus\` | Badge \`financialStatus\` (paid / pending / refunded / partially_refunded). |
1563
+ | Downloads | \`order.hasDownloads\` \u2192 \`client.getOrderDownloads(id)\` | Separate call; returns \`OrderDownloadLink[]\`. |
1564
+ | Financial summary | \`order.subtotal\`, \`order.appliedDiscounts\`, \`order.couponCode\` + \`couponDiscount\`, \`order.shippingAmount\`, \`order.taxAmount\`, \`order.totalAmount\` | Breakdown rows + final total. |
1565
+
1566
+ #### Rendering \`order.items[i].customizations\` by type
1567
+
1568
+ The map key is the metafield slug; the value is \`{ label, value, type }\`. Dispatch by \`type\`:
1569
+
1570
+ | Type | Value | Render |
1571
+ |---|---|---|
1572
+ | \`TEXT\`, \`TEXTAREA\`, \`URL\`, \`NUMBER\`, \`SELECT\` | string | Plain text (\`URL\` \u2192 anchor). |
1573
+ | \`BOOLEAN\` | \`"yes"\` / \`"no"\` | \u2713 / \u2717 |
1574
+ | \`MULTI_SELECT\` | \`string[]\` | Comma-separated. |
1575
+ | \`IMAGE\` | asset URL (string) | Thumbnail linking to full-size asset. |
1576
+ | \`GALLERY\` | \`string[]\` of URLs | Grid of thumbnails. |
1577
+ | \`COLOR\` | hex string | Swatch + hex text. |
1578
+ | \`DATE\` | ISO-8601 | \`toLocaleDateString()\` |
1579
+ | \`DATETIME\` | ISO-8601 | \`toLocaleString()\` |
1580
+ | Unknown | any | Plain text (defensive default). |
1581
+
1582
+ 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.
1583
+
1584
+ ### Do NOT render
1585
+
1586
+ 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.
1587
+
1588
+ - \`order.accountId\`, \`order.storeId\`, \`order.customerId\` (already known on the request)
1589
+ - \`order.notes\` (internal merchant notes)
1590
+ - \`order.customFieldValues\` (order-level checkout fields \u2014 merchant concept; buyers see \`items[i].customizations\`)
1591
+ - \`order.appliedSurcharges\`, \`order.surchargeAmount\`, \`order.appliedRuleIds\`, \`order.downloadMeta\`, \`order.pickupLocationData\``;
1362
1592
  }
1363
1593
  function getOrderConfirmationSection() {
1364
1594
  return `## Order Confirmation Page (/order-confirmation) \u2014 REQUIRED!
@@ -1528,7 +1758,8 @@ overlay needed:
1528
1758
  - \`brands[].name\`
1529
1759
  - \`tags[].name\`
1530
1760
  - \`variants[].name\`
1531
- - \`productAttributeOptions[].attribute.name\`, \`attributeOption.name\`/\`value\`
1761
+ - \`variant.attributes\` keys and values \u2014 \`getVariantOptions(variant)\` returns translated attribute names and option values automatically
1762
+ - \`productAttributeOptions[].attribute.name\`, \`attributeOption.name\`
1532
1763
  - \`metafields[].value\`
1533
1764
 
1534
1765
  **Taxonomy (\`getCategories\`, \`getBrands\`, \`getTags\`):**
@@ -1537,6 +1768,10 @@ overlay needed:
1537
1768
  **Cart:**
1538
1769
  - \`items[].product.name\`, \`items[].variant.name\`
1539
1770
 
1771
+ **Bundles & Order Bumps:**
1772
+ - \`bundleProduct.name\`, \`bundleProduct.slug\`, \`bumpProduct.name\`, \`bumpProduct.slug\`
1773
+ - Variant names inside bundles/bumps
1774
+
1540
1775
  **Checkout:**
1541
1776
  - Line items: \`items[].product.name\`, \`items[].variant.name\`
1542
1777
  - Discount banners, nudges, badges
@@ -1647,6 +1882,8 @@ function getSectionByTopic(topic, connectionId, currency) {
1647
1882
  return getDiscountsSection();
1648
1883
  case "recommendations":
1649
1884
  return getRecommendationsSection();
1885
+ case "product-customization-fields":
1886
+ return getProductCustomizationFieldsSection();
1650
1887
  case "tax":
1651
1888
  return getTaxDisplaySection(cur);
1652
1889
  case "i18n":
@@ -1721,6 +1958,10 @@ function getSectionByTopic(topic, connectionId, currency) {
1721
1958
  "",
1722
1959
  "---",
1723
1960
  "",
1961
+ getProductCustomizationFieldsSection(),
1962
+ "",
1963
+ "---",
1964
+ "",
1724
1965
  getTaxDisplaySection(cur),
1725
1966
  "",
1726
1967
  "---",
@@ -1732,7 +1973,7 @@ function getSectionByTopic(topic, connectionId, currency) {
1732
1973
  getAdminApiSection()
1733
1974
  ].join("\n");
1734
1975
  default:
1735
- 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`;
1976
+ return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, all`;
1736
1977
  }
1737
1978
  }
1738
1979
 
@@ -1752,6 +1993,7 @@ var GET_SDK_DOCS_SCHEMA = {
1752
1993
  "inventory",
1753
1994
  "discounts",
1754
1995
  "recommendations",
1996
+ "product-customization-fields",
1755
1997
  "tax",
1756
1998
  "critical-rules",
1757
1999
  "type-reference",
@@ -1796,6 +2038,7 @@ interface Product {
1796
2038
  brands?: Array<{ id: string; name: string }>;
1797
2039
  tags?: string[];
1798
2040
  metafields?: ProductMetafield[];
2041
+ 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.
1799
2042
  productAttributeOptions?: Array<{
1800
2043
  id: string;
1801
2044
  attributeId: string;
@@ -1854,6 +2097,32 @@ interface ProductMetafield {
1854
2097
  variantId?: string | null;
1855
2098
  }
1856
2099
 
2100
+ // Metafield type enum \u2014 used by ProductCustomizationField.type
2101
+ type MetafieldType =
2102
+ | 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME'
2103
+ | 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' | 'JSON'
2104
+ | 'IMAGE' | 'GALLERY'
2105
+ | 'SELECT' | 'MULTI_SELECT';
2106
+
2107
+ // Customer-facing input assigned per product. Render on the PDP in the order of \`position\`.
2108
+ // Submit values keyed by \`key\` inside AddToCartDto.metadata.
2109
+ // Upload files via \`uploadCustomizationFile()\` first, then place the returned \`url\` in metadata.
2110
+ interface ProductCustomizationField {
2111
+ definitionId: string;
2112
+ name: string; // Label to show buyers
2113
+ key: string; // Use as metadata key in AddToCartDto.metadata
2114
+ description?: string | null; // Help text
2115
+ type: MetafieldType;
2116
+ required: boolean;
2117
+ minLength?: number | null; // TEXT/TEXTAREA char bounds; MULTI_SELECT array bounds
2118
+ maxLength?: number | null;
2119
+ minValue?: number | null; // NUMBER bounds
2120
+ maxValue?: number | null;
2121
+ enumValues?: string[]; // REQUIRED for SELECT / MULTI_SELECT
2122
+ defaultValue?: string | null;
2123
+ position: number; // Render order
2124
+ }
2125
+
1857
2126
  interface ProductQueryParams {
1858
2127
  page?: number;
1859
2128
  limit?: number;
@@ -1937,6 +2206,7 @@ interface CartItem {
1937
2206
  sku?: string | null;
1938
2207
  image?: ProductImage | string | null;
1939
2208
  } | null;
2209
+ metadata?: Record<string, unknown> | null; // Buyer-submitted customization values, keyed by ProductCustomizationField.key
1940
2210
  createdAt: string;
1941
2211
  updatedAt: string;
1942
2212
  }
@@ -2001,6 +2271,9 @@ interface Checkout {
2001
2271
  taxAmount: string;
2002
2272
  taxBreakdown?: TaxBreakdown | null;
2003
2273
  total: string;
2274
+ surchargeAmount: string;
2275
+ appliedSurcharges?: Array<{ key: string; name: string; value: unknown; amount: string }> | null;
2276
+ customFieldValues?: Record<string, unknown> | null;
2004
2277
  couponCode?: string | null;
2005
2278
  lineItems: CheckoutLineItem[]; // Use THIS for order summary, NOT cart.items!
2006
2279
  itemCount: number;
@@ -2019,6 +2292,7 @@ interface CheckoutLineItem {
2019
2292
  discountAmount: string;
2020
2293
  product: { id: string; name: string; sku: string; images?: ProductImage[]; };
2021
2294
  variant?: { id: string; name?: string | null; sku?: string | null; image?: ProductImage | string | null; } | null;
2295
+ metadata?: Record<string, unknown> | null; // Copied from CartItem.metadata \u2014 buyer customization values
2022
2296
  }
2023
2297
 
2024
2298
  interface CheckoutAddress {
@@ -2100,6 +2374,27 @@ interface Order {
2100
2374
  billingAddress?: OrderAddress;
2101
2375
  hasDownloads?: boolean;
2102
2376
  createdAt: string;
2377
+
2378
+ // Payment + fulfillment
2379
+ paymentMethod?: string | null;
2380
+ financialStatus?: string | null; // "pending" | "paid" | "refunded" | "partially_refunded" | "voided"
2381
+ fulfillmentStatus?: string | null; // "unfulfilled" | "partial" | "fulfilled"
2382
+
2383
+ // Tracking
2384
+ trackingNumber?: string | null;
2385
+ trackingUrl?: string | null;
2386
+ carrier?: string | null;
2387
+ shippedAt?: string | null; // ISO-8601
2388
+ deliveredAt?: string | null; // ISO-8601
2389
+
2390
+ // Timeline of status transitions, chronological
2391
+ statusHistory?: OrderStatusChange[] | null;
2392
+ }
2393
+
2394
+ interface OrderStatusChange {
2395
+ status: OrderStatus;
2396
+ at: string; // ISO-8601
2397
+ note?: string | null;
2103
2398
  }
2104
2399
 
2105
2400
  // \u26A0\uFE0F OrderItem is FLAT \u2014 unlike CartItem which is NESTED
@@ -2113,6 +2408,9 @@ interface OrderItem {
2113
2408
  unitPrice?: string; // alias
2114
2409
  totalPrice?: string;
2115
2410
  image?: string; // FLAT: item.image (NOT nested)
2411
+ // Snapshot of buyer-submitted customization values captured at checkout.
2412
+ // Keyed by metafield slug. \`value\` is string[] for MULTI_SELECT / GALLERY, string otherwise.
2413
+ customizations?: Record<string, { label: string; value: string | string[]; type: string }>;
2116
2414
  }
2117
2415
 
2118
2416
  interface OrderCustomer {
@@ -2334,6 +2632,32 @@ interface ProductRecommendationsResponse {
2334
2632
  }
2335
2633
  interface CartRecommendationsResponse {
2336
2634
  recommendations: ProductRecommendation[];
2635
+ }
2636
+
2637
+ // Cart include types (for consolidated getCart requests)
2638
+ type CartIncludeOption = 'recommendations' | 'upgrades' | 'bundles';
2639
+ interface CartIncludeOptions {
2640
+ include?: CartIncludeOption[];
2641
+ }
2642
+ interface CartWithIncludes extends Cart {
2643
+ recommendations?: { recommendations: ProductRecommendation[] };
2644
+ upgrades?: { upgrades: Record<string, CartUpgradeSuggestion> };
2645
+ bundles?: { bundles: CartBundleOffer[] };
2646
+ }
2647
+ interface CartUpgradeSuggestion {
2648
+ targetProduct: ProductRecommendation;
2649
+ priceDelta: string;
2650
+ deltaPercent: number;
2651
+ }
2652
+ interface CartBundleOffer {
2653
+ id: string;
2654
+ bundleProduct: ProductRecommendation;
2655
+ originalPrice: string;
2656
+ discountedPrice: string;
2657
+ discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
2658
+ discountValue: number;
2659
+ requiresVariantSelection: boolean;
2660
+ lockedVariant?: { id: string; name?: string };
2337
2661
  }`;
2338
2662
  var TYPES_BY_DOMAIN = {
2339
2663
  products: PRODUCTS_TYPES,
@@ -2397,7 +2721,8 @@ var GET_CODE_EXAMPLE_SCHEMA = {
2397
2721
  "coupon-apply-and-remove",
2398
2722
  "reservation-countdown",
2399
2723
  "search-autocomplete-debounce",
2400
- "i18n-set-locale"
2724
+ "i18n-set-locale",
2725
+ "order-history-full"
2401
2726
  ]).describe("The SDK operation to get a snippet for.")
2402
2727
  };
2403
2728
  var SNIPPETS = {
@@ -2492,23 +2817,51 @@ const checkout = await client.getCheckout(checkoutId);
2492
2817
  "checkout-payment-providers": `// Fetch configured payment providers for this checkout.
2493
2818
  import { client } from './brainerce';
2494
2819
 
2495
- const providers = await client.getPaymentProviders(checkoutId);
2496
- // providers = [{ provider, name, renderType, config }, ...]
2497
- // renderType tells you how to render:
2498
- // 'stripe-elements' \u2014 render Stripe Elements form and call stripe.confirmCardPayment
2499
- // 'redirect' \u2014 render a button that navigates to provider.authorizationUrl
2500
- // 'paypal' \u2014 render PayPal SDK button
2501
- // 'sandbox' \u2014 render a "complete test order" button (no real charge)
2820
+ const { providers, hasPayments, defaultProvider } = await client.getPaymentProviders();
2821
+ // each provider: { id, provider, name, publicKey, supportedMethods, testMode, isDefault, clientSdk? }
2822
+ //
2823
+ // After createPaymentIntent, the response carries a clientSdk.renderType that
2824
+ // tells your UI how to render the payment step. The 5 possible values:
2825
+ //
2826
+ // 'sdk-widget' \u2014 Load the provider's JS SDK (scriptUrl), then mount
2827
+ // into a <div id={containerId}>. Used by Stripe,
2828
+ // PayPal, Grow. The SDK paints its own form inside
2829
+ // your DOM. You control layout/placement.
2830
+ //
2831
+ // 'iframe' \u2014 Render <iframe src={clientSecret}>. Two flavors:
2832
+ // a) URL path contains "/embed/" \u2192 Brainerce-hosted
2833
+ // embed page. Render INLINE in your checkout
2834
+ // flow. Listen for postMessage:
2835
+ // - 'brainerce:resize' \u2192 update iframe height
2836
+ // - 'brainerce:redirect' \u2192 validated top-level
2837
+ // navigation (e.g. Bit express-pay)
2838
+ // b) Any other URL \u2192 provider-hosted page. Render
2839
+ // inside a modal overlay (it carries its own
2840
+ // branding/chrome).
2841
+ //
2842
+ // 'redirect' \u2014 Full-page navigate: window.location.href = URL.
2843
+ // Customer leaves your site, pays on provider page,
2844
+ // returns via SuccessRedirectUrl.
2845
+ //
2846
+ // 'sandbox' \u2014 Test mode. Render a "Complete Test Order" button;
2847
+ // call completeGuestCheckout(checkoutId). Orders are
2848
+ // flagged isTestOrder: true. No real charge.
2849
+ //
2850
+ // 'embedded-fields' \u2014 (Reserved \u2014 not yet shipped in any provider.) PCI
2851
+ // micro-iframes for sensitive fields (card number,
2852
+ // CVV) mounted directly into the merchant form. Full
2853
+ // control of surrounding layout, like Stripe
2854
+ // Elements. Requires the provider to ship a client
2855
+ // SDK that exposes mount points.
2856
+ //
2857
+ // Always branch on clientSdk.renderType \u2014 NEVER hard-code by provider name.
2858
+ // New providers can be added without storefront changes.
2502
2859
 
2503
- // Pick the first configured provider by default (or let the user pick if
2504
- // multiple are configured).
2505
- const active = providers[0];
2506
-
2507
- // If providers is empty, NO payment provider is configured and customers
2508
- // cannot pay. Display a clear error \u2014 do not try to fake a checkout.
2509
2860
  if (providers.length === 0) {
2510
2861
  throw new Error('No payment provider configured for this store');
2511
- }`,
2862
+ }
2863
+
2864
+ const active = providers[0];`,
2512
2865
  "checkout-stripe-confirm": `// Stripe confirm flow. Requires @stripe/stripe-js and @stripe/react-stripe-js
2513
2866
  // (or the vanilla Stripe.js browser SDK).
2514
2867
  import { loadStripe } from '@stripe/stripe-js';
@@ -2722,12 +3075,82 @@ const locale = 'he'; // e.g., from the /[locale] route segment
2722
3075
  client.setLocale(locale);
2723
3076
 
2724
3077
  // ALL content comes back translated: products, categories, brands,
2725
- // tags, variants, metafields, cart items, checkout line items,
2726
- // recommendations, search suggestions, discount banners, nudges,
3078
+ // tags, variants (name + attributes keys/values), metafields,
3079
+ // cart items, checkout line items, recommendations, bundles,
3080
+ // order bumps, search suggestions, discount banners, nudges,
2727
3081
  // badges, order history.
2728
3082
 
2729
3083
  // For RTL locales (he, ar), set the document direction.
2730
- // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`
3084
+ // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`,
3085
+ "order-history-full": `// Full "My Orders" account page. Render every piece of data the server
3086
+ // already returns \u2014 not just order number / total / status.
3087
+ //
3088
+ // Data you get from client.getMyOrders() (already on the wire today):
3089
+ // - items[].customizations \u2014 buyer's custom-field entries
3090
+ // - statusHistory \u2014 status timeline
3091
+ // - shippingAddress \u2014 name + address lines + country
3092
+ // - trackingNumber / trackingUrl / carrier / shippedAt / deliveredAt
3093
+ // - paymentMethod / financialStatus / fulfillmentStatus
3094
+ // - appliedDiscounts \u2014 shaped buyer-facing view
3095
+ // - hasDownloads \u2014 call /orders/:id/downloads to fetch
3096
+ //
3097
+ // Do NOT render: accountId, storeId, customerId, notes, customFieldValues
3098
+ // (merchant-internal, order-level), appliedRuleIds, appliedSurcharges,
3099
+ // surchargeAmount, downloadMeta (raw), pickupLocationData. The backend
3100
+ // does not return these to buyers \u2014 if you see them in a type, they're
3101
+ // an oversight; still skip them.
3102
+ import { client } from './brainerce';
3103
+ import type { Order, OrderItem, OrderStatusChange } from 'brainerce';
3104
+
3105
+ const { data: orders } = await client.getMyOrders({ page: 1, limit: 10 });
3106
+
3107
+ for (const order of orders) {
3108
+ // Line items + per-item customizations
3109
+ for (const item of order.items) {
3110
+ // item.image, item.productName, item.quantity, item.price
3111
+ if (item.customizations) {
3112
+ for (const [fieldId, entry] of Object.entries(item.customizations)) {
3113
+ // entry = { label, value, type }
3114
+ // Type-aware render (see account-page section in get-sdk-docs):
3115
+ // TEXT / TEXTAREA / URL / NUMBER / SELECT \u2014 plain text
3116
+ // BOOLEAN \u2014 \u2713 / \u2717
3117
+ // MULTI_SELECT \u2014 comma-separated
3118
+ // IMAGE \u2014 <img src={value}>
3119
+ // GALLERY \u2014 wrap grid of <img>
3120
+ // COLOR \u2014 swatch + hex
3121
+ // DATE / DATETIME \u2014 localized format
3122
+ }
3123
+ }
3124
+ }
3125
+
3126
+ // Status timeline \u2014 skip silently when null/empty
3127
+ if (order.statusHistory?.length) {
3128
+ for (const entry of order.statusHistory as OrderStatusChange[]) {
3129
+ // entry = { status, at, note? }
3130
+ // Render a dot + localized status label + new Date(entry.at).toLocaleString()
3131
+ }
3132
+ }
3133
+
3134
+ // Shipping + tracking
3135
+ if (order.shippingAddress) {
3136
+ // Render firstName lastName \xB7 line1 \xB7 line2 \xB7 city, region \xB7 postalCode \xB7 country
3137
+ }
3138
+ if (order.trackingNumber) {
3139
+ // Render carrier \xB7 trackingNumber, shippedAt/deliveredAt dates,
3140
+ // and an anchor to order.trackingUrl when present.
3141
+ }
3142
+
3143
+ // Payment
3144
+ if (order.paymentMethod || order.financialStatus) {
3145
+ // paymentMethod: 'card' | 'paypal' | 'bank_transfer' | 'cash_on_delivery' | ...
3146
+ // financialStatus: 'pending' | 'paid' | 'refunded' | 'partially_refunded' | 'voided'
3147
+ // Map financialStatus \u2192 a colored badge.
3148
+ }
3149
+ }
3150
+
3151
+ // All sections above are conditional. Absent data = section not rendered \u2014
3152
+ // never show empty placeholders. The create-brainerce-store template's
3153
+ // src/components/account/order-history.tsx is the reference implementation.`
2731
3154
  };
2732
3155
  async function handleGetCodeExample(args) {
2733
3156
  const snippet = SNIPPETS[args.operation];
@@ -3193,7 +3616,7 @@ var RULES = {
3193
3616
  - All prices are STRINGS in the SDK. \`parseFloat\` them before math or comparisons.
3194
3617
  - CartItem and CheckoutLineItem are NESTED (\`item.product.name\`, \`item.unitPrice\`). OrderItem is FLAT (\`item.name\`, \`item.price\`). They are not interchangeable.
3195
3618
  - Cart has no \`.total\` field \u2014 call \`getCartTotals(cart)\` to get \`{ subtotal, tax, shipping, discount, total }\`.
3196
- - \`smartGetCart()\` returns a discriminated union (\`Cart | LocalCart\`). Check \`'id' in cart\` before using server-only fields.
3619
+ - \`smartGetCart()\` returns \`CartWithIncludes\` (extends \`Cart\`). Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
3197
3620
  - \`startGuestCheckout()\` is also a discriminated union. Check \`result.tracked\` before reading \`result.checkoutId\`.`
3198
3621
  }
3199
3622
  };
@@ -3231,6 +3654,7 @@ var GET_BUSINESS_FLOWS_SCHEMA = {
3231
3654
  "order-confirmation",
3232
3655
  "cart-persistence",
3233
3656
  "inventory-reservation",
3657
+ "product-customization",
3234
3658
  "all"
3235
3659
  ]).describe('Which flow to retrieve. Use "all" to get every flow.')
3236
3660
  };
@@ -3350,7 +3774,7 @@ Build the OAuth button region AND the callback handler even when no providers ar
3350
3774
  - **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).
3351
3775
  - **Writes:** use \`client.addToCart\`, \`client.updateCartItem\`, \`client.removeCartItem\`, \`client.applyCoupon\`, \`client.removeCoupon\`. After each mutation the SDK returns the updated cart.
3352
3776
  - **Totals:** call \`getCartTotals(cart)\` \u2014 do NOT read \`cart.total\`. The helper understands taxes, shipping, and discounts.
3353
- - **\`smartGetCart()\`** returns \`Cart | LocalCart\` (guest users have no server cart until they add an item). Check \`'id' in cart\` before using server-only fields.
3777
+ - **\`smartGetCart()\`** returns \`CartWithIncludes\` (extends \`Cart\`). All carts are server-side. Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
3354
3778
  - **NEVER mutate cart state outside SDK helpers.** Any hand-rolled cart update risks desync with the reservation timer and the checkout flow.`
3355
3779
  },
3356
3780
  "inventory-reservation": {
@@ -3364,6 +3788,54 @@ Build the OAuth button region AND the callback handler even when no providers ar
3364
3788
  - **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.
3365
3789
 
3366
3790
  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.`
3791
+ },
3792
+ "product-customization": {
3793
+ title: "Product customization (buyer input)",
3794
+ 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.
3795
+
3796
+ 1. **Read the fields** from the product payload. Sort by \`position\`. If the array is empty, nothing to render.
3797
+ 2. **Render one control per field** based on \`type\`:
3798
+ - \`TEXT\` / \`URL\` / \`COLOR\` / \`DIMENSION\` / \`WEIGHT\` \u2192 \`<input type="text">\` (honour \`minLength\`/\`maxLength\`)
3799
+ - \`TEXTAREA\` \u2192 \`<textarea>\`
3800
+ - \`NUMBER\` \u2192 \`<input type="number">\` (honour \`minValue\`/\`maxValue\`)
3801
+ - \`BOOLEAN\` \u2192 checkbox (value \`true\`/\`false\`)
3802
+ - \`DATE\` \u2192 \`<input type="date">\` (ISO \`YYYY-MM-DD\`)
3803
+ - \`DATETIME\` \u2192 \`<input type="datetime-local">\` (ISO timestamp)
3804
+ - \`SELECT\` \u2192 \`<select>\` populated from \`enumValues\` (value = one string)
3805
+ - \`MULTI_SELECT\` \u2192 checkbox group from \`enumValues\` (value = \`string[]\`)
3806
+ - \`IMAGE\` \u2192 file input + preview (value = one URL string)
3807
+ - \`GALLERY\` \u2192 multi-file input (value = \`string[]\` of URLs)
3808
+ - \`JSON\` \u2192 advanced; render an admin-style editor or skip unless you control the data
3809
+ 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.
3810
+ 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.
3811
+ 5. **Add to cart with metadata keyed by \`field.key\`:**
3812
+ \`\`\`ts
3813
+ await client.addToCart({
3814
+ productId,
3815
+ quantity: 1,
3816
+ metadata: {
3817
+ engraving_text: 'For Mom',
3818
+ frame_color: 'Gold',
3819
+ upload_photo: photoUrl, // from uploadCustomizationFile()
3820
+ addons: ['Gift wrap'], // MULTI_SELECT
3821
+ },
3822
+ });
3823
+ \`\`\`
3824
+ 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).
3825
+ 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.
3826
+
3827
+ **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.
3828
+
3829
+ Server-side guardrails that WILL reject bad requests (so validate client-side to avoid round-trips):
3830
+ - Unknown keys \u2192 rejected. Only use keys that appear in \`product.customizationFields\`.
3831
+ - Missing \`required\` fields \u2192 rejected.
3832
+ - \`SELECT\` value not in \`enumValues\` \u2192 rejected.
3833
+ - \`MULTI_SELECT\` value not \`string[]\` OR containing values outside \`enumValues\` \u2192 rejected.
3834
+ - \`IMAGE\` / \`GALLERY\` values must be URLs returned from \`/customization-upload\` on this store \u2014 pasting an external URL is rejected.
3835
+ - Upload > 5MB or non-image MIME \u2192 rejected by upload endpoint.
3836
+ - More than 10 uploads per IP per minute \u2192 429.
3837
+
3838
+ Never render customization fields without also wiring the upload + metadata flow \u2014 a form that submits nothing is worse than no form at all.`
3367
3839
  }
3368
3840
  };
3369
3841
  var FLOW_ORDER = [
@@ -3374,7 +3846,8 @@ var FLOW_ORDER = [
3374
3846
  "oauth",
3375
3847
  "order-confirmation",
3376
3848
  "cart-persistence",
3377
- "inventory-reservation"
3849
+ "inventory-reservation",
3850
+ "product-customization"
3378
3851
  ];
3379
3852
  async function handleGetBusinessFlows(args) {
3380
3853
  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.";
@@ -3439,6 +3912,14 @@ var FEATURES = [
3439
3912
  sdk: "client.getProductBySlug(slug). Helpers: getProductPriceInfo, getVariantPrice, getStockStatus, getVariantOptions, getProductSwatches, getDescriptionContent, getProductMetafieldValue.",
3440
3913
  mandatory: "mandatory"
3441
3914
  },
3915
+ {
3916
+ id: "product-customization-fields",
3917
+ title: "Render buyer-input customization fields on the product page",
3918
+ 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.",
3919
+ sdk: "product.customizationFields, client.uploadCustomizationFile(file), client.addToCart({ productId, quantity, metadata })",
3920
+ flowRef: "product-customization",
3921
+ mandatory: "mandatory"
3922
+ },
3442
3923
  {
3443
3924
  id: "cart",
3444
3925
  title: "Manage a cart with quantity, removal, and totals",