@brainerce/mcp-server 3.6.0 → 3.8.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
@@ -916,6 +916,175 @@ function ProductPage({ product, storeInfo }: { product: Product; storeInfo: Stor
916
916
  }
917
917
  \`\`\`
918
918
 
919
+ ### Variant Attribute Selector with Swatches (color + size **mix**)
920
+
921
+ The simple text-button picker above works, but loses the merchant-configured
922
+ **swatch metadata**. A single product often mixes one attribute that should
923
+ render as **color swatches** (e.g. \`Color\`) and another that should render
924
+ as **text buttons** (e.g. \`Size\`). The product response includes everything
925
+ you need:
926
+
927
+ - \`product.productAttributeOptions[]\` \u2014 the swatch definitions: \`attribute.name\`,
928
+ \`attribute.displayType\` (the \`AttributeDisplayType\` enum: \`DEFAULT\` | \`COLOR_SWATCH\` | \`IMAGE_SWATCH\` | \`MIXED_SWATCH\`),
929
+ \`attributeOption.name\`, \`swatchColor\` (hex), \`swatchColor2\` (hex \u2014 used for dual-color swatches
930
+ like Black & White), \`swatchImageUrl\` (for fabric / pattern thumbnails).
931
+ \`MIXED_SWATCH\` means each option in the group can independently pick image OR color
932
+ (the merchant decides per option). Treat any unrecognized value as \`DEFAULT\`.
933
+ - \`variant.attributes\` \u2014 the selected value per attribute on each variant.
934
+
935
+ Use \`getProductSwatches(product)\` to get a render-ready, grouped structure:
936
+
937
+ \`\`\`typescript
938
+ import { getProductSwatches } from 'brainerce';
939
+
940
+ const groups = getProductSwatches(product);
941
+ // [
942
+ // { attributeName: 'color', displayType: 'COLOR_SWATCH', options: [
943
+ // { name: 'Full Color', swatchColor: '#1D9435', swatchColor2: null, swatchImageUrl: null },
944
+ // { name: 'Black & White', swatchColor: '#000000', swatchColor2: '#FFFFFF', swatchImageUrl: null },
945
+ // ]},
946
+ // { attributeName: 'size', displayType: 'DEFAULT', options: [
947
+ // { name: '16" \xD7 20"' }, { name: '24" \xD7 32"' }, { name: '36" \xD7 48"' },
948
+ // ]},
949
+ // ]
950
+ \`\`\`
951
+
952
+ Render one branch per \`displayType\`. The same loop handles all-swatch, all-text,
953
+ and the mix case:
954
+
955
+ \`\`\`typescript
956
+ function VariantPicker({
957
+ product,
958
+ selections,
959
+ onSelect,
960
+ }: {
961
+ product: Product;
962
+ selections: Record<string, string>; // { color: 'Full Color', size: '24" \xD7 32"' }
963
+ onSelect: (attrName: string, value: string) => void;
964
+ }) {
965
+ const groups = getProductSwatches(product);
966
+ if (groups.length === 0) return null;
967
+
968
+ return (
969
+ <div className="space-y-4">
970
+ {groups.map((group) => (
971
+ <div key={group.attributeName}>
972
+ <label className="block mb-2 text-sm font-medium">
973
+ {group.attributeName}: <span className="text-gray-500">{selections[group.attributeName] ?? ''}</span>
974
+ </label>
975
+ <div className="flex flex-wrap gap-2">
976
+ {group.options.map((opt) => {
977
+ const isSelected = selections[group.attributeName] === opt.name;
978
+
979
+ // COLOR_SWATCH \u2014 round button; dual-color uses a 50/50 gradient.
980
+ if (group.displayType === 'COLOR_SWATCH' && opt.swatchColor) {
981
+ const bg = opt.swatchColor2
982
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
983
+ : opt.swatchColor;
984
+ return (
985
+ <button
986
+ key={opt.name}
987
+ type="button"
988
+ title={opt.name}
989
+ aria-pressed={isSelected}
990
+ onClick={() => onSelect(group.attributeName, opt.name)}
991
+ className={\`h-9 w-9 rounded-full border-2 \${isSelected ? 'border-black ring-2 ring-black/30' : 'border-gray-300 hover:border-black'}\`}
992
+ style={{ background: bg }}
993
+ />
994
+ );
995
+ }
996
+
997
+ // IMAGE_SWATCH \u2014 square thumbnail (fabric/pattern preview).
998
+ if (group.displayType === 'IMAGE_SWATCH' && opt.swatchImageUrl) {
999
+ return (
1000
+ <button
1001
+ key={opt.name}
1002
+ type="button"
1003
+ aria-pressed={isSelected}
1004
+ onClick={() => onSelect(group.attributeName, opt.name)}
1005
+ className={\`h-10 w-10 overflow-hidden rounded border-2 \${isSelected ? 'border-black' : 'border-gray-300'}\`}
1006
+ >
1007
+ <img src={opt.swatchImageUrl} alt={opt.name} className="h-full w-full object-cover" />
1008
+ </button>
1009
+ );
1010
+ }
1011
+
1012
+ // MIXED_SWATCH \u2014 each option is independently image OR color (image wins if present).
1013
+ if (group.displayType === 'MIXED_SWATCH') {
1014
+ if (opt.swatchImageUrl) {
1015
+ return (
1016
+ <button
1017
+ key={opt.name}
1018
+ type="button"
1019
+ aria-pressed={isSelected}
1020
+ onClick={() => onSelect(group.attributeName, opt.name)}
1021
+ className={\`h-10 w-10 overflow-hidden rounded border-2 \${isSelected ? 'border-black' : 'border-gray-300'}\`}
1022
+ >
1023
+ <img src={opt.swatchImageUrl} alt={opt.name} className="h-full w-full object-cover" />
1024
+ </button>
1025
+ );
1026
+ }
1027
+ if (opt.swatchColor) {
1028
+ const bg = opt.swatchColor2
1029
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
1030
+ : opt.swatchColor;
1031
+ return (
1032
+ <button
1033
+ key={opt.name}
1034
+ type="button"
1035
+ title={opt.name}
1036
+ aria-pressed={isSelected}
1037
+ onClick={() => onSelect(group.attributeName, opt.name)}
1038
+ className={\`h-9 w-9 rounded-full border-2 \${isSelected ? 'border-black ring-2 ring-black/30' : 'border-gray-300 hover:border-black'}\`}
1039
+ style={{ background: bg }}
1040
+ />
1041
+ );
1042
+ }
1043
+ // option has neither image nor color \u2192 fall through to text button below.
1044
+ }
1045
+
1046
+ // DEFAULT (or any swatch type missing its data) \u2014 plain text button.
1047
+ return (
1048
+ <button
1049
+ key={opt.name}
1050
+ type="button"
1051
+ aria-pressed={isSelected}
1052
+ onClick={() => onSelect(group.attributeName, opt.name)}
1053
+ className={\`rounded border px-3 py-1.5 text-sm \${isSelected ? 'bg-black text-white border-black' : 'border-gray-300 hover:border-black'}\`}
1054
+ >
1055
+ {opt.name}
1056
+ </button>
1057
+ );
1058
+ })}
1059
+ </div>
1060
+ </div>
1061
+ ))}
1062
+ </div>
1063
+ );
1064
+ }
1065
+ \`\`\`
1066
+
1067
+ Wire it up in the product page: keep \`selections\` in state, find the matching
1068
+ variant after each pick, and update price / image / stock from it.
1069
+
1070
+ \`\`\`typescript
1071
+ const [selections, setSelections] = useState<Record<string, string>>({});
1072
+
1073
+ const matchedVariant = useMemo(() => (
1074
+ product.variants?.find((v) =>
1075
+ Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
1076
+ ) ?? null
1077
+ ), [product.variants, selections]);
1078
+
1079
+ // Greying-out unavailable combinations: for each candidate value, run
1080
+ // the same find() and check \`inventory.canPurchase\`. Disable the button
1081
+ // if no purchasable variant exists under that selection.
1082
+ \`\`\`
1083
+
1084
+ **i18n:** \`getProductSwatches\` returns translated \`attributeName\` and
1085
+ \`option.name\` automatically when \`client.setLocale()\` is active. No
1086
+ client-side overlay needed. Swatch colors are language-agnostic.
1087
+
919
1088
  ### Description Rendering (handles HTML vs text)
920
1089
 
921
1090
  \`\`\`typescript
@@ -1550,17 +1719,28 @@ Allergens (informational chips), scheduled availability windows, nested combos (
1550
1719
  function getProductReviewsSection() {
1551
1720
  return `## Product Reviews (\u2605 ratings + JSON-LD for SEO)
1552
1721
 
1553
- Reviews publish immediately on submit. Merchants hide individual reviews via the admin surface \u2014 no PENDING queue.
1722
+ **Purchaser-only.** Only authenticated customers who purchased the product can submit. Each customer writes one review per product and can edit/delete it. Reviews publish immediately \u2014 no PENDING queue.
1554
1723
 
1555
1724
  \`\`\`typescript
1556
- // PDP \u2014 list visible reviews
1557
- const { data, meta } = await client.listProductReviews(productId, { page: 1, limit: 20 });
1558
- data.forEach(r => render(r.authorName, r.rating, r.body, r.verifiedPurchase));
1725
+ // PDP \u2014 list visible reviews (public)
1726
+ const { data } = await getClient().listProductReviews(productId, { page: 1, limit: 20 });
1727
+
1728
+ // Decide which UI to render for the current customer
1729
+ getClient().setCustomerToken(authToken); // after login
1730
+ const { eligible, reason, myReview } = await getClient().getMyProductReview(productId);
1731
+
1732
+ if (!eligible) {
1733
+ // reason: 'no_eligible_order' | 'reviews_disabled' | 'product_not_found'
1734
+ // \u2192 "only customers who purchased this product can leave a review"
1735
+ } else if (myReview) {
1736
+ // \u2192 edit form prefilled with myReview.rating + myReview.body
1737
+ } else {
1738
+ // \u2192 submit form (rating + body only \u2014 name/email come from customer profile)
1739
+ }
1559
1740
 
1560
- // PDP \u2014 submit form
1561
- await client.submitProductReview(productId, {
1562
- authorName, authorEmail, rating: 5, body,
1563
- });
1741
+ await getClient().submitProductReview(productId, { rating: 5, body: 'Loved it!' });
1742
+ await getClient().updateMyProductReview(productId, { rating: 4, body: 'Updated.' });
1743
+ await getClient().deleteMyProductReview(productId); // can submit a new one after
1564
1744
  \`\`\`
1565
1745
 
1566
1746
  Each \`Product\` carries denormalized rollups: \`product.avgRating\`, \`product.reviewCount\`. Use these on PLP cards.
@@ -1589,9 +1769,10 @@ const productJsonLd = {
1589
1769
 
1590
1770
  ### Rules
1591
1771
  - Rating must be an integer 1-5 (DB constraint).
1592
- - Duplicate from same email \u2192 409 Conflict.
1593
- - Submit endpoint is throttled to 3 / 60s / IP \u2014 surface a friendly "please wait" on 429.
1594
- - \`verifiedPurchase\` is derived server-side from DELIVERED orders \u2014 DO NOT try to set it.
1772
+ - Customer must be logged in AND have purchased the product (\`SHIPPED+\` for physical, \`PAID+\` for downloadable).
1773
+ - One review per (productId, customerId). Duplicate submit \u2192 409 \u2014 use updateMyProductReview instead.
1774
+ - Submit throttled 3 / 60s / IP; edit/delete 5 / 60s / IP.
1775
+ - \`verifiedPurchase\` is always true for customer-submitted reviews.
1595
1776
  - Stores with \`reviewsEnabled = false\` return 403 on storefront endpoints.`;
1596
1777
  }
1597
1778
  function getInventorySection() {
@@ -2013,9 +2194,12 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
2013
2194
  const client = getServerClient();
2014
2195
  client.setLocale(locale);
2015
2196
  const product = await client.getProductBySlug(slug);
2197
+ // NEVER feed raw HTML into <meta name="description"> \u2014 product.description
2198
+ // is often rich-text HTML. Strip tags first, then truncate on a word
2199
+ // boundary. See buildMetaDescription() in lib/seo.ts.
2016
2200
  return {
2017
2201
  title: product.seoTitle || product.name,
2018
- description: product.seoDescription || product.description?.slice(0, 160),
2202
+ description: product.seoDescription || buildMetaDescription(product.description) || product.name,
2019
2203
  };
2020
2204
  }
2021
2205
  \`\`\`
@@ -2131,11 +2315,25 @@ Because the backend already overlays everything, UI code is just:
2131
2315
 
2132
2316
  ### RTL handling
2133
2317
 
2134
- For RTL locales (\`he\`, \`ar\`), set \`<html dir="rtl">\` in the root layout and
2135
- let flexbox reverse automatically. Do NOT add \`flex-row-reverse\` on top of
2136
- \`dir="rtl"\` \u2014 that's a double-swap. DO swap directional icons (chevrons,
2137
- arrows) manually. Use logical CSS properties (\`ms-*\`/\`me-*\`) instead of
2138
- \`ml-*\`/\`mr-*\`.
2318
+ Resolve direction with \`client.getStoreDirection(locale)\` \u2014 it returns
2319
+ \`'ltr' | 'rtl'\` for any BCP-47 tag (Arabic, Hebrew, Persian, Urdu, Yiddish
2320
+ today; future RTL locales added by the platform are picked up automatically).
2321
+ Do NOT maintain your own RTL locale set.
2322
+
2323
+ \`\`\`tsx
2324
+ // app/[locale]/layout.tsx
2325
+ const dir = client.getStoreDirection(locale);
2326
+ return <html lang={locale} dir={dir}>...</html>;
2327
+ \`\`\`
2328
+
2329
+ For static rendering, \`storeInfo.i18n.defaultDirection\` carries the store's
2330
+ default direction, and each entry in \`storeInfo.i18n.supportedLocaleObjects\`
2331
+ includes its own \`direction\`.
2332
+
2333
+ Let flexbox reverse automatically once \`<html dir="rtl">\` is set. Do NOT add
2334
+ \`flex-row-reverse\` on top \u2014 that's a double-swap. DO swap directional icons
2335
+ (chevrons, arrows) manually. Use logical CSS properties (\`ms-*\`/\`me-*\`)
2336
+ instead of \`ml-*\`/\`mr-*\`.
2139
2337
 
2140
2338
  ### Language switcher
2141
2339
 
@@ -2512,6 +2710,141 @@ and a \`newsletter\` form embedded in the footer), render each form from its
2512
2710
  own \`contactForms.get(key, locale)\` call. The \`formKey\` you pass to
2513
2711
  \`createInquiry\` must match.`;
2514
2712
  }
2713
+ function getContentSection() {
2714
+ return `## Content \u2014 typed merchant content store
2715
+
2716
+ Brainerce ships a typed content store so merchants can edit site chrome, FAQ,
2717
+ static pages, and inline rich-text blocks in the dashboard \u2014 without
2718
+ re-prompting the AI that built their storefront. Every row has a \`type\` +
2719
+ \`key\` + typed \`data\` payload + free-form \`customFields\`.
2720
+
2721
+ **Six content types.** Each one has a fixed \`data\` shape; the SDK's TypeScript
2722
+ generics keep them in lockstep:
2723
+
2724
+ | Type | Use for | \`data\` shape (abbreviated) |
2725
+ | -------------- | -------------------------------------- | --------------------------- |
2726
+ | \`FAQ\` | Q/A accordions | \`{ items: { question, answer }[] }\` |
2727
+ | \`FOOTER\` | Site footer (chrome) | \`{ columns, copyright?, social? }\` |
2728
+ | \`HEADER\` | Top nav + logo + CTA (chrome) | \`{ logo?, navItems, cta? }\` |
2729
+ | \`ANNOUNCEMENT\`| Banners; time-bound by \`startsAt/endsAt\` | \`{ message, severity, dismissible, ... }\` |
2730
+ | \`RICH_TEXT\` | Free-form HTML blocks embedded inline | \`{ html }\` |
2731
+ | \`PAGE\` | Static pages with slug + SEO | \`{ slug, title, html, seo? }\` |
2732
+
2733
+ Run \`get-type-definitions\` with \`domain: 'content'\` for the full interfaces.
2734
+
2735
+ ### Default key
2736
+
2737
+ Every type has \`'main'\` as its universal default key. \`client.content.faq.get()\`
2738
+ with no arguments resolves to \`key='main'\`. Topical keys (\`'shipping'\`,
2739
+ \`'holiday-2026'\`, \`'about'\`) are merchant-named.
2740
+
2741
+ ### Reading content (any SDK mode)
2742
+
2743
+ Public reads work in vibe-coded mode, storefront mode, and admin mode. They
2744
+ return \`null\` on 404 \u2014 render hard-coded fallbacks so the page never crashes
2745
+ when the merchant hasn't seeded yet.
2746
+
2747
+ \`\`\`ts
2748
+ // Single entry, default key 'main', resolved to a locale
2749
+ const faq = await client.content.faq.get('main', locale);
2750
+ if (faq) {
2751
+ faq.data.items.forEach(({ question, answer }) => {
2752
+ // Render question + sanitize(answer)
2753
+ });
2754
+ }
2755
+
2756
+ // All entries of a type
2757
+ const allFaqs = await client.content.faq.list(locale);
2758
+
2759
+ // Page by URL slug \u2014 for app/[slug]/page.tsx
2760
+ const page = await client.content.page.getBySlug(slug, locale);
2761
+ if (!page) notFound();
2762
+ \`\`\`
2763
+
2764
+ ### Security \u2014 sanitize HTML before rendering
2765
+
2766
+ \`FAQ.items[i].answer\`, \`RICH_TEXT.html\`, and \`PAGE.html\` carry
2767
+ MERCHANT-AUTHORED HTML. The server does NOT pre-sanitize \u2014 some merchants
2768
+ embed iframes (e.g. YouTube) which strict sanitizers would strip. ALWAYS
2769
+ sanitize on the storefront before injecting:
2770
+
2771
+ \`\`\`ts
2772
+ // Recommended: isomorphic-dompurify
2773
+ import DOMPurify from 'isomorphic-dompurify';
2774
+ const safe = DOMPurify.sanitize(rawHtml);
2775
+ <div dangerouslySetInnerHTML={{ __html: safe }} />;
2776
+ \`\`\`
2777
+
2778
+ Skipping this is XSS.
2779
+
2780
+ ### Custom fields
2781
+
2782
+ Every Content row carries a free-form \`customFields: Record<string, string>\`.
2783
+ Merchants add arbitrary key-value extras (\`helpEmail\`, \`phoneNumber\`,
2784
+ \`foundedYear\`) that you can opt into reading:
2785
+
2786
+ \`\`\`ts
2787
+ const faq = await client.content.faq.get('shipping');
2788
+ <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
2789
+ \`\`\`
2790
+
2791
+ The shape is whatever the merchant entered. Read keys you expect; ignore the rest.
2792
+
2793
+ ### Locale resolution
2794
+
2795
+ All public reads accept a \`locale\` argument. The server resolves
2796
+ \`translations[locale]\` server-side and returns the resolved \`data\` payload \u2014
2797
+ the storefront does NOT need to do its own overlay. Empty / missing translations
2798
+ fall through to the default-locale value.
2799
+
2800
+ ### Cache
2801
+
2802
+ Public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`.
2803
+ Merchant edits propagate within ~5 minutes. Don't layer extra client-side
2804
+ caching beyond Next.js's default fetch cache.
2805
+
2806
+ ### Admin writes (apiKey mode)
2807
+
2808
+ \`\`\`ts
2809
+ const adminClient = new BrainerceClient({ apiKey: process.env.BRAINERCE_API_KEY });
2810
+
2811
+ // Create \u2014 always starts in DRAFT
2812
+ const faq = await adminClient.content.faq.create({
2813
+ key: 'shipping',
2814
+ name: 'Shipping FAQ',
2815
+ data: { items: [{ question: 'How long?', answer: 'Most orders ship in 2 days.' }] },
2816
+ });
2817
+
2818
+ // Update (data replaces wholesale; last-write-wins on the data field)
2819
+ await adminClient.content.update(faq.id, {
2820
+ data: { items: [{ question: 'How long?', answer: 'Updated answer.' }] },
2821
+ });
2822
+
2823
+ // Publish / unpublish
2824
+ await adminClient.content.publish(faq.id);
2825
+ await adminClient.content.unpublish(faq.id);
2826
+
2827
+ // Hard delete
2828
+ await adminClient.content.remove(faq.id);
2829
+ \`\`\`
2830
+
2831
+ Write operations throw if called from vibe-coded or storefront mode.
2832
+
2833
+ ### Reserved key convention
2834
+
2835
+ \`'main'\` is reserved as the universal default. Don't use it for topical
2836
+ entries \u2014 pick a descriptive slug (\`'shipping'\`, \`'returns'\`, \`'about'\`,
2837
+ \`'holiday-2026'\`). The validation rule is \`^[a-z][a-z0-9-]*$\`, max 64 chars.
2838
+
2839
+ ### See also
2840
+
2841
+ - \`get-business-flows\` with \`flow: 'content-bootstrap'\` for the full
2842
+ layout / FAQ / page recipe.
2843
+ - \`get-required-features\` lists each Content surface (\`site-header\`,
2844
+ \`site-footer\`, \`announcement-bar\`, \`faq-page\`, \`static-pages\`).
2845
+ - \`get-type-definitions\` with \`domain: 'content'\` for the TypeScript
2846
+ interfaces.`;
2847
+ }
2515
2848
  function getSectionByTopic(topic, connectionId, currency) {
2516
2849
  const cid = connectionId || "vc_YOUR_CONNECTION_ID";
2517
2850
  const cur = currency || "USD";
@@ -2558,6 +2891,8 @@ function getSectionByTopic(topic, connectionId, currency) {
2558
2891
  return getAdminApiSection();
2559
2892
  case "inquiries":
2560
2893
  return getContactInquiriesSection();
2894
+ case "content":
2895
+ return getContentSection();
2561
2896
  case "all":
2562
2897
  return [
2563
2898
  "# Brainerce SDK \u2014 full topic dump",
@@ -2646,10 +2981,14 @@ function getSectionByTopic(topic, connectionId, currency) {
2646
2981
  "",
2647
2982
  "---",
2648
2983
  "",
2649
- getContactInquiriesSection()
2984
+ getContactInquiriesSection(),
2985
+ "",
2986
+ "---",
2987
+ "",
2988
+ getContentSection()
2650
2989
  ].join("\n");
2651
2990
  default:
2652
- return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, all`;
2991
+ return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, content, all`;
2653
2992
  }
2654
2993
  }
2655
2994
 
@@ -2677,6 +3016,7 @@ var GET_SDK_DOCS_SCHEMA = {
2677
3016
  "i18n",
2678
3017
  "admin",
2679
3018
  "inquiries",
3019
+ "content",
2680
3020
  "all"
2681
3021
  ]).describe("The SDK documentation topic to retrieve"),
2682
3022
  salesChannelId: z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
@@ -2687,9 +3027,7 @@ var GET_SDK_DOCS_SCHEMA = {
2687
3027
  async function handleGetSdkDocs(args) {
2688
3028
  const id = args.salesChannelId ?? args.connectionId;
2689
3029
  if (!args.salesChannelId && args.connectionId) {
2690
- console.warn(
2691
- "get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
2692
- );
3030
+ console.warn("get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead");
2693
3031
  }
2694
3032
  const content = getSectionByTopic(args.topic, id, args.currency);
2695
3033
  return {
@@ -3421,11 +3759,16 @@ interface ProductReviewAdmin extends ProductReview {
3421
3759
  updatedAt: string;
3422
3760
  }
3423
3761
 
3424
- interface SubmitProductReviewInput {
3425
- authorName: string;
3426
- authorEmail?: string; // recommended \u2014 used for guest dedupe + verified-purchase derivation
3762
+ interface WriteProductReviewInput {
3427
3763
  rating: number; // 1-5
3428
- body?: string; // optional
3764
+ body?: string; // optional, max 5000 chars
3765
+ }
3766
+
3767
+ interface MyProductReview {
3768
+ eligible: boolean;
3769
+ // Machine-readable reason when not eligible. null when eligible=true.
3770
+ reason: 'no_eligible_order' | 'reviews_disabled' | 'product_not_found' | null;
3771
+ myReview: ProductReview | null;
3429
3772
  }
3430
3773
 
3431
3774
  // Each Product carries denormalized review stats:
@@ -3666,6 +4009,156 @@ export interface ModifierValidationError {
3666
4009
  // The cart line then carries:
3667
4010
  // cart.items[i].modifiers \u2014 CartItemModifierLine[]
3668
4011
  // cart.items[i].modifiersTotal \u2014 decimal string of the paid (non-free) deltas`;
4012
+ var CONTENT_TYPES = `// ---- Content (typed merchant content store) ----
4013
+ // Brainerce ships a typed content store so merchants can edit FAQ, footer,
4014
+ // header, announcements, rich text, and static pages in the dashboard
4015
+ // without re-prompting the AI that built the storefront. Every row has a
4016
+ // 'type' + 'key' + typed 'data' payload + free-form 'customFields'.
4017
+ //
4018
+ // SECURITY (read carefully):
4019
+ // RICH_TEXT.html, PAGE.html, and FAQ answers are MERCHANT-AUTHORED HTML.
4020
+ // ALWAYS sanitize with isomorphic-dompurify (or equivalent) before
4021
+ // injecting via dangerouslySetInnerHTML. The server does NOT pre-sanitize
4022
+ // because some merchants embed iframes (e.g. YouTube) which strict
4023
+ // sanitizers would strip; the storefront chooses the policy.
4024
+ //
4025
+ // 404 contract: client.content.<type>.get(key) returns null when no
4026
+ // PUBLISHED row exists. Always render a hard-coded fallback on null so
4027
+ // the page never crashes when the merchant hasn't seeded yet.
4028
+ //
4029
+ // Default key: every type has 'main' as its universal default. Pass no
4030
+ // argument to fetch the main entry; pass a custom key ('shipping',
4031
+ // 'holiday-2026', 'about') for topical entries.
4032
+
4033
+ export type ContentType = 'FAQ' | 'FOOTER' | 'HEADER' | 'ANNOUNCEMENT' | 'RICH_TEXT' | 'PAGE';
4034
+ export type ContentStatus = 'DRAFT' | 'PUBLISHED';
4035
+
4036
+ export interface FaqItem {
4037
+ question: string;
4038
+ /** Sanitized HTML \u2014 sanitize before rendering. */
4039
+ answer: string;
4040
+ }
4041
+ export interface FaqContent { items: FaqItem[] }
4042
+
4043
+ export interface FooterLink { label: string; url: string }
4044
+ export interface FooterColumn { title: string; links: FooterLink[] }
4045
+ export interface FooterSocialLink { platform: string; url: string } // 'instagram' | 'facebook' | 'x' | ...
4046
+ export interface FooterContent {
4047
+ columns: FooterColumn[];
4048
+ copyright?: string;
4049
+ social?: FooterSocialLink[];
4050
+ }
4051
+
4052
+ export interface HeaderLogo { src: string; alt: string }
4053
+ export interface HeaderNavItem { label: string; url: string }
4054
+ export interface HeaderCta { label: string; url: string }
4055
+ export interface HeaderContent {
4056
+ logo?: HeaderLogo;
4057
+ navItems: HeaderNavItem[];
4058
+ cta?: HeaderCta;
4059
+ }
4060
+
4061
+ export type AnnouncementSeverity = 'info' | 'warning' | 'success';
4062
+ export interface AnnouncementContent {
4063
+ message: string;
4064
+ severity: AnnouncementSeverity;
4065
+ dismissible: boolean;
4066
+ /** ISO 8601 \u2014 filter client-side. */
4067
+ startsAt?: string;
4068
+ endsAt?: string;
4069
+ ctaLabel?: string;
4070
+ ctaHref?: string;
4071
+ }
4072
+
4073
+ export interface RichTextContent {
4074
+ /** Raw HTML \u2014 sanitize before rendering. */
4075
+ html: string;
4076
+ }
4077
+
4078
+ export interface PageSeo {
4079
+ title?: string;
4080
+ description?: string;
4081
+ ogImage?: string;
4082
+ }
4083
+ export interface PageContent {
4084
+ /** URL slug, lower-kebab. */
4085
+ slug: string;
4086
+ title: string;
4087
+ /** Raw HTML \u2014 sanitize before rendering. */
4088
+ html: string;
4089
+ seo?: PageSeo;
4090
+ }
4091
+
4092
+ export interface ContentSummary {
4093
+ id: string;
4094
+ type: ContentType;
4095
+ key: string;
4096
+ name: string;
4097
+ status: ContentStatus;
4098
+ position: number;
4099
+ updatedAt: string;
4100
+ }
4101
+
4102
+ export interface Content<T extends ContentType = ContentType> extends ContentSummary {
4103
+ type: T;
4104
+ data: T extends 'FAQ' ? FaqContent
4105
+ : T extends 'FOOTER' ? FooterContent
4106
+ : T extends 'HEADER' ? HeaderContent
4107
+ : T extends 'ANNOUNCEMENT' ? AnnouncementContent
4108
+ : T extends 'RICH_TEXT' ? RichTextContent
4109
+ : T extends 'PAGE' ? PageContent
4110
+ : never;
4111
+ /** Free-form merchant-defined extras. Read keys the merchant told you to expect. */
4112
+ customFields: Record<string, string>;
4113
+ salesChannelIds: string[];
4114
+ }
4115
+
4116
+ // ---- SDK usage examples ----
4117
+ //
4118
+ // FAQ \u2014 render an accordion from the main FAQ (or a topical one):
4119
+ // const faq = await client.content.faq.get('main', locale); // 'shipping', 'returns', ...
4120
+ // if (faq) {
4121
+ // faq.data.items.forEach(({ question, answer }) => {
4122
+ // // Render question + sanitize(answer) \u2014 never inject raw HTML.
4123
+ // });
4124
+ // }
4125
+ //
4126
+ // Footer \u2014 server component in root layout:
4127
+ // const footer = await client.content.footer.get('main', locale);
4128
+ // if (!footer) return <Fallback />;
4129
+ // // Render footer.data.columns, footer.data.social, footer.data.copyright
4130
+ //
4131
+ // Header \u2014 same pattern as footer:
4132
+ // const header = await client.content.header.get('main', locale);
4133
+ //
4134
+ // Announcement \u2014 multiple may be active; filter by date client-side:
4135
+ // const announcements = await client.content.announcement.list(locale);
4136
+ // const now = Date.now();
4137
+ // const active = announcements.filter((a) => {
4138
+ // const startOk = !a.data.startsAt || new Date(a.data.startsAt).getTime() <= now;
4139
+ // const endOk = !a.data.endsAt || new Date(a.data.endsAt).getTime() >= now;
4140
+ // return startOk && endOk;
4141
+ // });
4142
+ //
4143
+ // Rich text \u2014 inline block anywhere on a page:
4144
+ // const block = await client.content.richText.get('about-intro', locale);
4145
+ // <div dangerouslySetInnerHTML={{ __html: sanitize(block.data.html) }} />
4146
+ //
4147
+ // Page \u2014 catch-all route by slug (e.g. /about, /terms, /privacy):
4148
+ // // app/[slug]/page.tsx
4149
+ // const page = await client.content.page.getBySlug(params.slug, locale);
4150
+ // if (!page) notFound();
4151
+ // // page.data.title, page.data.html, page.data.seo
4152
+ // return <article dangerouslySetInnerHTML={{ __html: sanitize(page.data.html) }} />;
4153
+ //
4154
+ // Custom fields \u2014 every Content row carries a free-form Record<string, string>:
4155
+ // const faq = await client.content.faq.get('shipping');
4156
+ // <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
4157
+ //
4158
+ // Cache \u2014 public reads carry Cache-Control: public, max-age=300,
4159
+ // stale-while-revalidate=60. Storefront changes propagate within ~5 min
4160
+ // of the merchant publishing. Do not add extra client-side caching
4161
+ // beyond Next.js's default fetch cache.`;
3669
4162
  var TYPES_BY_DOMAIN = {
3670
4163
  products: PRODUCTS_TYPES,
3671
4164
  cart: CART_TYPES,
@@ -3676,7 +4169,8 @@ var TYPES_BY_DOMAIN = {
3676
4169
  helpers: HELPERS_TYPES,
3677
4170
  inquiries: INQUIRIES_TYPES,
3678
4171
  reviews: REVIEWS_TYPES,
3679
- "modifier-groups": MODIFIER_GROUPS_TYPES
4172
+ "modifier-groups": MODIFIER_GROUPS_TYPES,
4173
+ content: CONTENT_TYPES
3680
4174
  };
3681
4175
  function getTypesByDomain(domain) {
3682
4176
  if (domain === "all") {
@@ -3707,9 +4201,10 @@ var GET_TYPE_DEFINITIONS_SCHEMA = {
3707
4201
  "helpers",
3708
4202
  "inquiries",
3709
4203
  "reviews",
4204
+ "content",
3710
4205
  "all"
3711
4206
  ]).describe(
3712
- 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse.'
4207
+ 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse. Use "content" for FAQ / Footer / Header / Announcement / RichText / Page.'
3713
4208
  )
3714
4209
  };
3715
4210
  async function handleGetTypeDefinitions(args) {
@@ -3728,6 +4223,7 @@ var GET_CODE_EXAMPLE_SCHEMA = {
3728
4223
  "sdk-init",
3729
4224
  "cart-read-and-mutate",
3730
4225
  "variant-selection",
4226
+ "variant-selector-swatches",
3731
4227
  "checkout-address-and-shipping",
3732
4228
  "checkout-payment-providers",
3733
4229
  "checkout-stripe-confirm",
@@ -3797,28 +4293,148 @@ for (const item of cart.items) {
3797
4293
  const unitPrice = parseFloat(item.unitPrice); // prices are strings!
3798
4294
  }`,
3799
4295
  "variant-selection": `// Variant selection with live stock + price updates.
4296
+ // Variants expose attributes as a flat object: { color: 'Red', size: 'M' }.
4297
+ // NOT 'options' \u2014 that field does not exist on ProductVariant.
3800
4298
  import { getVariantPrice, getStockStatus, getVariantOptions } from 'brainerce';
3801
4299
  import type { Product, ProductVariant } from 'brainerce';
3802
4300
 
3803
4301
  function selectVariant(product: Product, selections: Record<string, string>) {
3804
- // selections = { Size: 'M', Color: 'Red' }
3805
- const variant = product.variants.find((v) =>
3806
- v.options.every((o) => selections[o.name] === o.value)
4302
+ // selections = { size: 'M', color: 'Red' } (keys match variant.attributes keys)
4303
+ const variant = product.variants?.find((v) =>
4304
+ Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
3807
4305
  );
3808
4306
  if (!variant) return null;
3809
4307
 
3810
- const price = getVariantPrice(product, variant); // handles compare-at, currency
3811
- const stock = getStockStatus(variant); // 'IN_STOCK' | 'LOW_STOCK' | 'OUT_OF_STOCK'
3812
- const canPurchase = stock !== 'OUT_OF_STOCK';
4308
+ const price = getVariantPrice(variant, product.basePrice); // string, fallback-aware
4309
+ const stock = getStockStatus(variant.inventory); // 'in-stock' | 'low-stock' | 'out-of-stock' | 'unavailable'
4310
+ const canPurchase = variant.inventory?.canPurchase !== false;
3813
4311
 
3814
4312
  // Switch the main product image to the variant's image if it has one
3815
- const image = variant.image ?? product.images[0];
4313
+ const image = variant.image ?? product.images?.[0];
3816
4314
 
3817
4315
  return { variant, price, stock, canPurchase, image };
3818
4316
  }
3819
4317
 
3820
- // Build the option picker from getVariantOptions(product) \u2014 returns
3821
- // [{ name: 'Size', values: ['S','M','L'] }, ...]`,
4318
+ // Build the option picker by iterating product.variants and grouping
4319
+ // variant.attributes into { color: ['Red', 'Blue'], size: ['S','M','L'] }.
4320
+ // For each variant you can also call getVariantOptions(variant) which returns
4321
+ // the same key/value pairs as an array with translated names when setLocale() is active.
4322
+ // For swatch metadata (color hex, dual-color, image), use the
4323
+ // 'variant-selector-swatches' operation instead.`,
4324
+ "variant-selector-swatches": `// Variant picker that mixes color swatches and text buttons in one product.
4325
+ // Uses product.productAttributeOptions[] \u2014 the merchant-configured swatch
4326
+ // metadata. displayType is the AttributeDisplayType Prisma enum, one of:
4327
+ // 'DEFAULT' \u2014 plain text button
4328
+ // 'COLOR_SWATCH' \u2014 swatchColor (+ optional swatchColor2 dual-color gradient)
4329
+ // 'IMAGE_SWATCH' \u2014 swatchImageUrl thumbnail
4330
+ // 'MIXED_SWATCH' \u2014 per-option hybrid: image if swatchImageUrl is set,
4331
+ // otherwise fall back to swatchColor
4332
+ // getProductSwatches() groups options by attribute name so you can render each
4333
+ // attribute with its own displayType \u2014 a single product can have Color as
4334
+ // swatches AND Size as text buttons.
4335
+ import { getProductSwatches } from 'brainerce';
4336
+ import type { Product } from 'brainerce';
4337
+
4338
+ function VariantPicker({
4339
+ product,
4340
+ selections,
4341
+ onSelect,
4342
+ }: {
4343
+ product: Product;
4344
+ selections: Record<string, string>;
4345
+ onSelect: (attrName: string, value: string) => void;
4346
+ }) {
4347
+ const groups = getProductSwatches(product);
4348
+ // groups: [{ attributeName, displayType, options: [{ name, swatchColor, swatchColor2, swatchImageUrl }] }]
4349
+
4350
+ return (
4351
+ <>
4352
+ {groups.map((group) => (
4353
+ <div key={group.attributeName}>
4354
+ <label>{group.attributeName}: {selections[group.attributeName] ?? ''}</label>
4355
+ <div style={{ display: 'flex', gap: 8 }}>
4356
+ {group.options.map((opt) => {
4357
+ const selected = selections[group.attributeName] === opt.name;
4358
+ const onClick = () => onSelect(group.attributeName, opt.name);
4359
+
4360
+ // COLOR_SWATCH: round button. swatchColor2 = dual-color gradient.
4361
+ if (group.displayType === 'COLOR_SWATCH' && opt.swatchColor) {
4362
+ const bg = opt.swatchColor2
4363
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
4364
+ : opt.swatchColor;
4365
+ return (
4366
+ <button
4367
+ key={opt.name}
4368
+ type="button"
4369
+ title={opt.name}
4370
+ aria-pressed={selected}
4371
+ onClick={onClick}
4372
+ style={{
4373
+ width: 36,
4374
+ height: 36,
4375
+ borderRadius: '50%',
4376
+ background: bg,
4377
+ outline: selected ? '2px solid black' : 'none',
4378
+ }}
4379
+ />
4380
+ );
4381
+ }
4382
+
4383
+ // IMAGE_SWATCH: square thumbnail.
4384
+ if (group.displayType === 'IMAGE_SWATCH' && opt.swatchImageUrl) {
4385
+ return (
4386
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4387
+ <img src={opt.swatchImageUrl} alt={opt.name} width={40} height={40} />
4388
+ </button>
4389
+ );
4390
+ }
4391
+
4392
+ // MIXED_SWATCH: per-option hybrid (image wins if present).
4393
+ if (group.displayType === 'MIXED_SWATCH') {
4394
+ if (opt.swatchImageUrl) {
4395
+ return (
4396
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4397
+ <img src={opt.swatchImageUrl} alt={opt.name} width={40} height={40} />
4398
+ </button>
4399
+ );
4400
+ }
4401
+ if (opt.swatchColor) {
4402
+ const bg = opt.swatchColor2
4403
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
4404
+ : opt.swatchColor;
4405
+ return (
4406
+ <button
4407
+ key={opt.name}
4408
+ type="button"
4409
+ title={opt.name}
4410
+ aria-pressed={selected}
4411
+ onClick={onClick}
4412
+ style={{ width: 36, height: 36, borderRadius: '50%', background: bg }}
4413
+ />
4414
+ );
4415
+ }
4416
+ }
4417
+
4418
+ // DEFAULT (or any swatch type missing its data): text button.
4419
+ return (
4420
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4421
+ {opt.name}
4422
+ </button>
4423
+ );
4424
+ })}
4425
+ </div>
4426
+ </div>
4427
+ ))}
4428
+ </>
4429
+ );
4430
+ }
4431
+
4432
+ // After the user picks a value, find the matching ProductVariant:
4433
+ // product.variants?.find((v) =>
4434
+ // Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
4435
+ // )
4436
+ // Then read variant.price, variant.image, variant.inventory.canPurchase
4437
+ // to update the rest of the PDP.`,
3822
4438
  "checkout-address-and-shipping": `// Step 1-3 of the checkout flow. Never reorder or skip.
3823
4439
  import { client } from './brainerce';
3824
4440
 
@@ -4135,8 +4751,10 @@ client.setLocale(locale);
4135
4751
  // order bumps, search suggestions, discount banners, nudges,
4136
4752
  // badges, order history.
4137
4753
 
4138
- // For RTL locales (he, ar), set the document direction.
4139
- // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`,
4754
+ // For RTL direction, do not hardcode the locale list. Ask the SDK:
4755
+ // const dir = client.getStoreDirection(currentLocale); // 'ltr' | 'rtl'
4756
+ // document.documentElement.setAttribute('dir', dir);
4757
+ // (Or in React: <html dir={dir}>...</html>.)`,
4140
4758
  "order-history-full": `// Full "My Orders" account page. Render every piece of data the server
4141
4759
  // already returns \u2014 not just order number / total / status.
4142
4760
  //
@@ -4611,21 +5229,25 @@ function renderCartItem(item: CartItem): string {
4611
5229
  function lineTotal(item: CartItem): number {
4612
5230
  return item.unitPrice * item.quantity;
4613
5231
  }`,
4614
- "product-reviews": `// PDP: list visible reviews + submit form + JSON-LD aggregateRating
4615
- import { client } from '@/lib/brainerce';
4616
- import type { Product, ProductReview, SubmitProductReviewInput } from 'brainerce';
4617
-
5232
+ "product-reviews": `// Purchaser-only reviews. Customer must be logged in AND have purchased
5233
+ // the product. The component switches between sign-in CTA / not-eligible /
5234
+ // submit form / edit form based on getMyProductReview().
5235
+ import { getClient, getServerClient } from '@/lib/brainerce';
5236
+ import { checkAuthStatus } from '@/lib/auth';
5237
+ import type { Product, ProductReview, MyProductReview } from 'brainerce';
5238
+
5239
+ // Server component \u2014 fetches existing reviews + emits JSON-LD aggregateRating.
4618
5240
  export async function ProductReviewsSection({ product }: { product: Product }) {
4619
- const { data } = await client.listProductReviews(product.id, { page: 1, limit: 20 });
5241
+ const { data } = await getServerClient().listProductReviews(product.id, { page: 1, limit: 20 });
4620
5242
 
4621
5243
  return (
4622
5244
  <section>
4623
5245
  <h2>Reviews ({product.reviewCount ?? 0})</h2>
4624
- {data.length === 0 && <p>No reviews yet \u2014 be the first.</p>}
5246
+ {data.length === 0 && <p>No reviews yet.</p>}
4625
5247
  {data.map((r) => (
4626
5248
  <article key={r.id}>
4627
5249
  <strong>{r.authorName}</strong>
4628
- {r.verifiedPurchase && <span> \xB7 Verified</span>}
5250
+ {r.verifiedPurchase && <span> \xB7 Verified purchase</span>}
4629
5251
  <div>{'\u2605'.repeat(r.rating)}{'\u2606'.repeat(5 - r.rating)}</div>
4630
5252
  {r.body && <p>{r.body}</p>}
4631
5253
  </article>
@@ -4658,42 +5280,83 @@ function productJsonLd(product: Product, url: string) {
4658
5280
 
4659
5281
  // Client-side form
4660
5282
  'use client';
4661
- import { useState } from 'react';
5283
+ import { useEffect, useState } from 'react';
5284
+
5285
+ type Stage =
5286
+ | { kind: 'loading' }
5287
+ | { kind: 'signed_out' }
5288
+ | { kind: 'not_eligible'; reason: MyProductReview['reason'] }
5289
+ | { kind: 'submit' }
5290
+ | { kind: 'edit'; review: ProductReview };
4662
5291
 
4663
5292
  function ReviewForm({ productId }: { productId: string }) {
5293
+ const [stage, setStage] = useState<Stage>({ kind: 'loading' });
4664
5294
  const [rating, setRating] = useState(5);
4665
5295
  const [body, setBody] = useState('');
4666
- const [name, setName] = useState('');
4667
- const [email, setEmail] = useState('');
4668
5296
  const [error, setError] = useState<string | null>(null);
4669
5297
 
5298
+ useEffect(() => {
5299
+ (async () => {
5300
+ const auth = await checkAuthStatus();
5301
+ if (!auth.isLoggedIn) return setStage({ kind: 'signed_out' });
5302
+ const me = await getClient().getMyProductReview(productId);
5303
+ if (!me.eligible) return setStage({ kind: 'not_eligible', reason: me.reason });
5304
+ if (me.myReview) {
5305
+ setRating(me.myReview.rating);
5306
+ setBody(me.myReview.body ?? '');
5307
+ return setStage({ kind: 'edit', review: me.myReview });
5308
+ }
5309
+ setStage({ kind: 'submit' });
5310
+ })();
5311
+ }, [productId]);
5312
+
5313
+ if (stage.kind === 'loading') return <p>Loading\u2026</p>;
5314
+ if (stage.kind === 'signed_out')
5315
+ return <p><a href="/account/login">Sign in</a> to leave a review.</p>;
5316
+ if (stage.kind === 'not_eligible')
5317
+ return <p>Only customers who purchased this product can leave a review.</p>;
5318
+
4670
5319
  async function submit(e: React.FormEvent) {
4671
5320
  e.preventDefault();
4672
5321
  setError(null);
5322
+ const client = getClient();
5323
+ const input = { rating, body: body || undefined };
4673
5324
  try {
4674
- await client.submitProductReview(productId, {
4675
- authorName: name,
4676
- authorEmail: email,
4677
- rating,
4678
- body: body || undefined,
4679
- });
5325
+ if (stage.kind === 'edit') {
5326
+ await client.updateMyProductReview(productId, input);
5327
+ } else {
5328
+ await client.submitProductReview(productId, input);
5329
+ }
4680
5330
  window.location.reload();
4681
5331
  } catch (err: any) {
4682
- if (err?.status === 409) setError("You've already reviewed this product.");
5332
+ if (err?.status === 403) setError('Only customers who purchased this product can leave a review.');
5333
+ else if (err?.status === 409) setError('You already reviewed this product.');
4683
5334
  else if (err?.status === 429) setError('Too many submissions. Please wait a moment.');
4684
- else setError('Could not submit review. Please try again.');
5335
+ else setError('Could not save your review. Please try again.');
4685
5336
  }
4686
5337
  }
4687
5338
 
5339
+ async function remove() {
5340
+ if (!confirm('Delete your review?')) return;
5341
+ await getClient().deleteMyProductReview(productId);
5342
+ window.location.reload();
5343
+ }
5344
+
4688
5345
  return (
4689
5346
  <form onSubmit={submit}>
4690
- <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" required maxLength={100} />
4691
- <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
4692
- <select value={rating} onChange={(e) => setRating(Number(e.target.value))}>
4693
- {[5,4,3,2,1].map(n => <option key={n} value={n}>{'\u2605'.repeat(n)}</option>)}
4694
- </select>
4695
- <textarea value={body} onChange={(e) => setBody(e.target.value)} maxLength={5000} placeholder="Tell us what you think (optional)" />
4696
- <button type="submit">Submit review</button>
5347
+ <h3>{stage.kind === 'edit' ? 'Edit your review' : 'Write a review'}</h3>
5348
+ <div>
5349
+ {[1,2,3,4,5].map(n => (
5350
+ <button type="button" key={n} onClick={() => setRating(n)}>
5351
+ {n <= rating ? '\u2605' : '\u2606'}
5352
+ </button>
5353
+ ))}
5354
+ </div>
5355
+ <textarea value={body} onChange={(e) => setBody(e.target.value)} maxLength={5000} />
5356
+ <button type="submit">{stage.kind === 'edit' ? 'Save changes' : 'Submit review'}</button>
5357
+ {stage.kind === 'edit' && (
5358
+ <button type="button" onClick={remove}>Delete review</button>
5359
+ )}
4697
5360
  {error && <p role="alert">{error}</p>}
4698
5361
  </form>
4699
5362
  );
@@ -5183,7 +5846,7 @@ var RULES = {
5183
5846
  body: `- NEVER hardcode currency, locale, or language strings. Read them from \`get-store-info\` / \`get-store-capabilities\` and use the configured values.
5184
5847
  - NEVER format prices with \`toFixed(2)\` or custom logic. Use \`formatPrice()\` from the SDK \u2014 it honors the store's currency and locale.
5185
5848
  - When the store has i18n enabled (\`capabilities.store.i18n.enabled === true\`), you MUST call \`client.setLocale(locale)\` at app init and include a language switcher. All SDK reads will then return localized content automatically.
5186
- - For RTL locales (\`he\`, \`ar\`), set the document direction to RTL. Do not manually reverse flex layouts \u2014 the platform's CSS reversal handles it.`
5849
+ - For RTL direction, do NOT maintain a local list of RTL locales. Call \`client.getStoreDirection(locale)\` \u2014 it returns \`'ltr' | 'rtl'\` for any BCP-47 tag (covers Arabic, Hebrew, Persian, Urdu, Yiddish, and any future RTL locales the platform adds). Set \`<html dir={...}>\` from this value. The platform's CSS reversal handles flex layouts \u2014 do not manually swap them.`
5187
5850
  },
5188
5851
  types: {
5189
5852
  title: "Type safety",
@@ -5231,6 +5894,7 @@ var GET_BUSINESS_FLOWS_SCHEMA = {
5231
5894
  "cart-persistence",
5232
5895
  "inventory-reservation",
5233
5896
  "product-customization",
5897
+ "content-bootstrap",
5234
5898
  "all"
5235
5899
  ]).describe('Which flow to retrieve. Use "all" to get every flow.')
5236
5900
  };
@@ -5421,6 +6085,76 @@ Server-side guardrails that WILL reject bad requests (so validate client-side to
5421
6085
  - More than 10 uploads per IP per minute \u2192 429.
5422
6086
 
5423
6087
  Never render customization fields without also wiring the upload + metadata flow \u2014 a form that submits nothing is worse than no form at all.`
6088
+ },
6089
+ "content-bootstrap": {
6090
+ title: "Content Bootstrap \u2014 site chrome & static content",
6091
+ body: `Every Brainerce storefront should render merchant-defined site chrome (header, footer, announcements, FAQ, static pages) from the Content API. The merchant edits these in the Brainerce dashboard; storefronts pick up changes within ~5 minutes (public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`).
6092
+
6093
+ 1. **Fetch chrome at the root layout** (server component if Next.js). All three return \`null\` on 404 \u2014 render hard-coded fallbacks so the page never crashes when the merchant hasn't seeded yet.
6094
+ \`\`\`ts
6095
+ const [header, footer, announcements] = await Promise.all([
6096
+ client.content.header.get('main', locale),
6097
+ client.content.footer.get('main', locale),
6098
+ client.content.announcement.list(locale),
6099
+ ]);
6100
+ \`\`\`
6101
+
6102
+ 2. **FAQ \u2014 fetch lazily on the FAQ page.** Default key is \`'main'\`; pass a topical key (\`'shipping'\`, \`'returns'\`) for sub-FAQs.
6103
+ \`\`\`ts
6104
+ const faq = await client.content.faq.get('main', locale);
6105
+ if (faq) {
6106
+ faq.data.items.forEach(({ question, answer }) => {
6107
+ // sanitize(answer) \u2014 see step 4
6108
+ });
6109
+ }
6110
+ \`\`\`
6111
+
6112
+ 3. **Static pages \u2014 catch-all route by slug:**
6113
+ \`\`\`tsx
6114
+ // app/[slug]/page.tsx
6115
+ export default async function Page({ params }) {
6116
+ const page = await client.content.page.getBySlug(params.slug, locale);
6117
+ if (!page) notFound();
6118
+ return (
6119
+ <article dangerouslySetInnerHTML={{ __html: sanitize(page.data.html) }} />
6120
+ );
6121
+ }
6122
+ \`\`\`
6123
+
6124
+ 4. **SECURITY \u2014 sanitize HTML before rendering.** \`FAQ.items[i].answer\`, \`PAGE.html\`, and \`RICH_TEXT.html\` are merchant-authored HTML. The server does NOT pre-sanitize because some merchants embed iframes (e.g. YouTube). Always sanitize at the edge of your render:
6125
+ \`\`\`ts
6126
+ import DOMPurify from 'isomorphic-dompurify';
6127
+ const safe = DOMPurify.sanitize(rawHtml);
6128
+ <div dangerouslySetInnerHTML={{ __html: safe }} />;
6129
+ \`\`\`
6130
+ Skipping this is XSS.
6131
+
6132
+ 5. **Announcements \u2014 multiple may be active; filter by date client-side:**
6133
+ \`\`\`ts
6134
+ const now = Date.now();
6135
+ const visible = announcements.filter((a) => {
6136
+ const startOk = !a.data.startsAt || new Date(a.data.startsAt).getTime() <= now;
6137
+ const endOk = !a.data.endsAt || new Date(a.data.endsAt).getTime() >= now;
6138
+ return startOk && endOk;
6139
+ });
6140
+ \`\`\`
6141
+
6142
+ 6. **RTL direction \u2014 call \`client.getStoreDirection(locale)\`:**
6143
+ \`\`\`tsx
6144
+ const dir = client.getStoreDirection(locale);
6145
+ <html lang={locale} dir={dir}>...</html>
6146
+ \`\`\`
6147
+ Do NOT maintain a local RTL locale set \u2014 the SDK helper covers Arabic / Hebrew / Persian / Urdu / Yiddish today and picks up any future RTL locale automatically.
6148
+
6149
+ 7. **Custom fields \u2014 every Content row has free-form \`customFields: Record<string, string>\`.** Read keys the merchant told you to expect:
6150
+ \`\`\`ts
6151
+ const faq = await client.content.faq.get('shipping');
6152
+ <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
6153
+ \`\`\`
6154
+
6155
+ 8. **Cache:** public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`. Don't add extra client-side caching beyond Next.js's default fetch cache \u2014 merchants expect their edits to appear within ~5 minutes.
6156
+
6157
+ **Translations.** All public reads accept a \`locale\` argument; the server resolves \`translations[locale]\` server-side. Empty / missing overlays fall through to the default-locale value. The storefront does NOT need to do its own per-field overlay \u2014 call with the active locale and render what comes back.`
5424
6158
  }
5425
6159
  };
5426
6160
  var FLOW_ORDER = [
@@ -5432,7 +6166,8 @@ var FLOW_ORDER = [
5432
6166
  "order-confirmation",
5433
6167
  "cart-persistence",
5434
6168
  "inventory-reservation",
5435
- "product-customization"
6169
+ "product-customization",
6170
+ "content-bootstrap"
5436
6171
  ];
5437
6172
  async function handleGetBusinessFlows(args) {
5438
6173
  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.";
@@ -5501,9 +6236,9 @@ var FEATURES = [
5501
6236
  },
5502
6237
  {
5503
6238
  id: "product-reviews",
5504
- title: "Display + collect product reviews with stars + JSON-LD",
5505
- description: 'On the PDP show a Reviews section: list of customer reviews with star rating, author name, verified-purchase badge, body, and date. Include a submit form (name + email + 1-5 stars + optional body). On PLP cards show \u2605 avgRating and (reviewCount). Emit Product JSON-LD with aggregateRating ONLY when product.reviewCount > 0 \u2014 this is what unlocks the star rich snippet in Google. Reviews publish immediately; the merchant moderates from the admin surface. Rate-limited to 3 submits / 60s / IP. Show a friendly "you already reviewed this" message on 409.',
5506
- sdk: "client.listProductReviews(productId), client.submitProductReview(productId, { authorName, authorEmail, rating, body }). Product.avgRating + Product.reviewCount are denormalized rollups returned on every product fetch.",
6239
+ title: "Display + collect product reviews (purchaser-only) with stars + JSON-LD",
6240
+ description: 'On the PDP show a Reviews section: list of customer reviews with star rating, author name (from customer profile), verified-purchase badge, body, and date \u2014 public, no login needed. Below the list, a form that adapts to the current customer: signed-in + purchased + no review yet \u2192 submit form (rating 1-5 + optional body, no name/email \u2014 those are derived from the customer profile); signed-in + purchased + already has review \u2192 edit form prefilled with rating/body plus a delete button; signed-in but did NOT purchase \u2192 "only customers who purchased this product can leave a review"; not signed in \u2192 sign-in CTA. Eligibility: physical products require an order in SHIPPED+; downloadable products additionally accept PAID/PROCESSING. On PLP cards show \u2605 avgRating and (reviewCount). Emit Product JSON-LD with aggregateRating ONLY when product.reviewCount > 0 \u2014 this is what unlocks the star rich snippet in Google. Reviews publish immediately; merchants moderate (hide/show) from the admin surface. Rate-limited 3 submits / 60s / IP.',
6241
+ sdk: "client.listProductReviews(productId) for the public list; client.getMyProductReview(productId) for the form-state decision; client.submitProductReview / updateMyProductReview / deleteMyProductReview for the three customer actions. All four customer methods require setCustomerToken(...) after login. Product.avgRating + Product.reviewCount are denormalized rollups returned on every product fetch.",
5507
6242
  mandatory: "mandatory"
5508
6243
  },
5509
6244
  {
@@ -5644,11 +6379,57 @@ var FEATURES = [
5644
6379
  {
5645
6380
  id: "i18n",
5646
6381
  title: "Serve multiple languages with a language switcher",
5647
- description: "When i18n is enabled, the experience routes by locale, sets the SDK locale (client.setLocale), includes a language switcher in the header, and renders RTL locales (he, ar) with the correct document direction.",
5648
- sdk: "client.setLocale(locale). Read supported locales from get-store-capabilities.store.i18n.",
6382
+ description: "When i18n is enabled, the experience routes by locale, sets the SDK locale (client.setLocale), includes a language switcher in the header, and renders the correct document direction by reading client.getStoreDirection(locale) \u2014 do not hardcode an RTL locale set.",
6383
+ sdk: "client.setLocale(locale). client.getStoreDirection(locale) for <html dir>. Read supported locales from get-store-capabilities.store.i18n.",
5649
6384
  mandatory: "conditional",
5650
6385
  capabilityFlag: "i18n",
5651
6386
  whenDisabledNote: "This store is single-language. Do not build the language switcher."
6387
+ },
6388
+ {
6389
+ id: "site-header",
6390
+ title: "Site header from merchant content (logo + nav + CTA)",
6391
+ description: 'Fetch client.content.header.get("main", locale) in the root layout. Returns null when the merchant has not seeded yet \u2014 render a hard-coded fallback so the page never crashes. Renders header.data.logo, header.data.navItems[], header.data.cta if present.',
6392
+ sdk: 'client.content.header.get("main", locale)',
6393
+ flowRef: "content-bootstrap",
6394
+ mandatory: "mandatory"
6395
+ },
6396
+ {
6397
+ id: "site-footer",
6398
+ title: "Site footer from merchant content (columns + social + copyright)",
6399
+ description: 'Fetch client.content.footer.get("main", locale) in the root layout. Returns null when unseeded \u2014 render a hard-coded fallback. Render footer.data.columns[].links, footer.data.social[], footer.data.copyright.',
6400
+ sdk: 'client.content.footer.get("main", locale)',
6401
+ flowRef: "content-bootstrap",
6402
+ mandatory: "mandatory"
6403
+ },
6404
+ {
6405
+ id: "announcement-bar",
6406
+ title: "Announcement bar at the top of every page",
6407
+ description: "Fetch client.content.announcement.list(locale) in the root layout. Filter by data.startsAt / data.endsAt client-side. Render a dismissible bar when data.dismissible=true. Build the UI anyway \u2014 it auto-hides when no announcements exist.",
6408
+ sdk: "client.content.announcement.list(locale)",
6409
+ flowRef: "content-bootstrap",
6410
+ mandatory: "conditional",
6411
+ capabilityFlag: "hasContent",
6412
+ whenDisabledNote: "Store has no published Content rows yet. Build the announcement bar anyway \u2014 it auto-hides on empty."
6413
+ },
6414
+ {
6415
+ id: "faq-page",
6416
+ title: "FAQ page rendered from merchant content",
6417
+ description: 'Build /faq as an accordion fed by client.content.faq.get("main", locale). For topical FAQs, use a key parameter (shipping, returns, ...). Always sanitize answer HTML before injecting via dangerouslySetInnerHTML. Build the page anyway \u2014 it auto-hides or 404s when no FAQ rows exist.',
6418
+ sdk: 'client.content.faq.get("main", locale), client.content.faq.list(locale)',
6419
+ flowRef: "content-bootstrap",
6420
+ mandatory: "conditional",
6421
+ capabilityFlag: "hasContent",
6422
+ whenDisabledNote: "No FAQ content yet. Build /faq anyway \u2014 it auto-hides on empty."
6423
+ },
6424
+ {
6425
+ id: "static-pages",
6426
+ title: "Static pages from merchant content (About, Terms, Privacy, \u2026)",
6427
+ description: "Mount a catch-all app/[slug]/page.tsx route. Inside, call client.content.page.getBySlug(params.slug, locale). On null \u2192 notFound(). On hit, sanitize page.data.html before injecting via dangerouslySetInnerHTML. Generate <Metadata> from page.data.seo. Build the route anyway \u2014 it 404s on unknown slugs.",
6428
+ sdk: "client.content.page.getBySlug(slug, locale), client.content.page.list(locale)",
6429
+ flowRef: "content-bootstrap",
6430
+ mandatory: "conditional",
6431
+ capabilityFlag: "hasContent",
6432
+ whenDisabledNote: "No static pages yet. Build the catch-all route anyway \u2014 it 404s on unknown slugs."
5652
6433
  }
5653
6434
  ];
5654
6435
  function isFeatureActive(feature, caps) {
@@ -5699,6 +6480,7 @@ function renderCapabilitiesSummary(caps) {
5699
6480
  );
5700
6481
  lines.push(`- Downloadable products: ${caps.features.hasDownloadableProducts ? "yes" : "no"}`);
5701
6482
  lines.push(`- Checkout custom fields: ${caps.features.hasCheckoutCustomFields ? "yes" : "no"}`);
6483
+ lines.push(`- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`);
5702
6484
  lines.push(
5703
6485
  `- Email verification: ${caps.connection.requireEmailVerification ? "required" : "not required (still build the verify-email flow)"}`
5704
6486
  );