@brainerce/mcp-server 3.5.1 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/stdio.js CHANGED
@@ -922,6 +922,175 @@ function ProductPage({ product, storeInfo }: { product: Product; storeInfo: Stor
922
922
  }
923
923
  \`\`\`
924
924
 
925
+ ### Variant Attribute Selector with Swatches (color + size **mix**)
926
+
927
+ The simple text-button picker above works, but loses the merchant-configured
928
+ **swatch metadata**. A single product often mixes one attribute that should
929
+ render as **color swatches** (e.g. \`Color\`) and another that should render
930
+ as **text buttons** (e.g. \`Size\`). The product response includes everything
931
+ you need:
932
+
933
+ - \`product.productAttributeOptions[]\` \u2014 the swatch definitions: \`attribute.name\`,
934
+ \`attribute.displayType\` (the \`AttributeDisplayType\` enum: \`DEFAULT\` | \`COLOR_SWATCH\` | \`IMAGE_SWATCH\` | \`MIXED_SWATCH\`),
935
+ \`attributeOption.name\`, \`swatchColor\` (hex), \`swatchColor2\` (hex \u2014 used for dual-color swatches
936
+ like Black & White), \`swatchImageUrl\` (for fabric / pattern thumbnails).
937
+ \`MIXED_SWATCH\` means each option in the group can independently pick image OR color
938
+ (the merchant decides per option). Treat any unrecognized value as \`DEFAULT\`.
939
+ - \`variant.attributes\` \u2014 the selected value per attribute on each variant.
940
+
941
+ Use \`getProductSwatches(product)\` to get a render-ready, grouped structure:
942
+
943
+ \`\`\`typescript
944
+ import { getProductSwatches } from 'brainerce';
945
+
946
+ const groups = getProductSwatches(product);
947
+ // [
948
+ // { attributeName: 'color', displayType: 'COLOR_SWATCH', options: [
949
+ // { name: 'Full Color', swatchColor: '#1D9435', swatchColor2: null, swatchImageUrl: null },
950
+ // { name: 'Black & White', swatchColor: '#000000', swatchColor2: '#FFFFFF', swatchImageUrl: null },
951
+ // ]},
952
+ // { attributeName: 'size', displayType: 'DEFAULT', options: [
953
+ // { name: '16" \xD7 20"' }, { name: '24" \xD7 32"' }, { name: '36" \xD7 48"' },
954
+ // ]},
955
+ // ]
956
+ \`\`\`
957
+
958
+ Render one branch per \`displayType\`. The same loop handles all-swatch, all-text,
959
+ and the mix case:
960
+
961
+ \`\`\`typescript
962
+ function VariantPicker({
963
+ product,
964
+ selections,
965
+ onSelect,
966
+ }: {
967
+ product: Product;
968
+ selections: Record<string, string>; // { color: 'Full Color', size: '24" \xD7 32"' }
969
+ onSelect: (attrName: string, value: string) => void;
970
+ }) {
971
+ const groups = getProductSwatches(product);
972
+ if (groups.length === 0) return null;
973
+
974
+ return (
975
+ <div className="space-y-4">
976
+ {groups.map((group) => (
977
+ <div key={group.attributeName}>
978
+ <label className="block mb-2 text-sm font-medium">
979
+ {group.attributeName}: <span className="text-gray-500">{selections[group.attributeName] ?? ''}</span>
980
+ </label>
981
+ <div className="flex flex-wrap gap-2">
982
+ {group.options.map((opt) => {
983
+ const isSelected = selections[group.attributeName] === opt.name;
984
+
985
+ // COLOR_SWATCH \u2014 round button; dual-color uses a 50/50 gradient.
986
+ if (group.displayType === 'COLOR_SWATCH' && opt.swatchColor) {
987
+ const bg = opt.swatchColor2
988
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
989
+ : opt.swatchColor;
990
+ return (
991
+ <button
992
+ key={opt.name}
993
+ type="button"
994
+ title={opt.name}
995
+ aria-pressed={isSelected}
996
+ onClick={() => onSelect(group.attributeName, opt.name)}
997
+ className={\`h-9 w-9 rounded-full border-2 \${isSelected ? 'border-black ring-2 ring-black/30' : 'border-gray-300 hover:border-black'}\`}
998
+ style={{ background: bg }}
999
+ />
1000
+ );
1001
+ }
1002
+
1003
+ // IMAGE_SWATCH \u2014 square thumbnail (fabric/pattern preview).
1004
+ if (group.displayType === 'IMAGE_SWATCH' && opt.swatchImageUrl) {
1005
+ return (
1006
+ <button
1007
+ key={opt.name}
1008
+ type="button"
1009
+ aria-pressed={isSelected}
1010
+ onClick={() => onSelect(group.attributeName, opt.name)}
1011
+ className={\`h-10 w-10 overflow-hidden rounded border-2 \${isSelected ? 'border-black' : 'border-gray-300'}\`}
1012
+ >
1013
+ <img src={opt.swatchImageUrl} alt={opt.name} className="h-full w-full object-cover" />
1014
+ </button>
1015
+ );
1016
+ }
1017
+
1018
+ // MIXED_SWATCH \u2014 each option is independently image OR color (image wins if present).
1019
+ if (group.displayType === 'MIXED_SWATCH') {
1020
+ if (opt.swatchImageUrl) {
1021
+ return (
1022
+ <button
1023
+ key={opt.name}
1024
+ type="button"
1025
+ aria-pressed={isSelected}
1026
+ onClick={() => onSelect(group.attributeName, opt.name)}
1027
+ className={\`h-10 w-10 overflow-hidden rounded border-2 \${isSelected ? 'border-black' : 'border-gray-300'}\`}
1028
+ >
1029
+ <img src={opt.swatchImageUrl} alt={opt.name} className="h-full w-full object-cover" />
1030
+ </button>
1031
+ );
1032
+ }
1033
+ if (opt.swatchColor) {
1034
+ const bg = opt.swatchColor2
1035
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
1036
+ : opt.swatchColor;
1037
+ return (
1038
+ <button
1039
+ key={opt.name}
1040
+ type="button"
1041
+ title={opt.name}
1042
+ aria-pressed={isSelected}
1043
+ onClick={() => onSelect(group.attributeName, opt.name)}
1044
+ className={\`h-9 w-9 rounded-full border-2 \${isSelected ? 'border-black ring-2 ring-black/30' : 'border-gray-300 hover:border-black'}\`}
1045
+ style={{ background: bg }}
1046
+ />
1047
+ );
1048
+ }
1049
+ // option has neither image nor color \u2192 fall through to text button below.
1050
+ }
1051
+
1052
+ // DEFAULT (or any swatch type missing its data) \u2014 plain text button.
1053
+ return (
1054
+ <button
1055
+ key={opt.name}
1056
+ type="button"
1057
+ aria-pressed={isSelected}
1058
+ onClick={() => onSelect(group.attributeName, opt.name)}
1059
+ className={\`rounded border px-3 py-1.5 text-sm \${isSelected ? 'bg-black text-white border-black' : 'border-gray-300 hover:border-black'}\`}
1060
+ >
1061
+ {opt.name}
1062
+ </button>
1063
+ );
1064
+ })}
1065
+ </div>
1066
+ </div>
1067
+ ))}
1068
+ </div>
1069
+ );
1070
+ }
1071
+ \`\`\`
1072
+
1073
+ Wire it up in the product page: keep \`selections\` in state, find the matching
1074
+ variant after each pick, and update price / image / stock from it.
1075
+
1076
+ \`\`\`typescript
1077
+ const [selections, setSelections] = useState<Record<string, string>>({});
1078
+
1079
+ const matchedVariant = useMemo(() => (
1080
+ product.variants?.find((v) =>
1081
+ Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
1082
+ ) ?? null
1083
+ ), [product.variants, selections]);
1084
+
1085
+ // Greying-out unavailable combinations: for each candidate value, run
1086
+ // the same find() and check \`inventory.canPurchase\`. Disable the button
1087
+ // if no purchasable variant exists under that selection.
1088
+ \`\`\`
1089
+
1090
+ **i18n:** \`getProductSwatches\` returns translated \`attributeName\` and
1091
+ \`option.name\` automatically when \`client.setLocale()\` is active. No
1092
+ client-side overlay needed. Swatch colors are language-agnostic.
1093
+
925
1094
  ### Description Rendering (handles HTML vs text)
926
1095
 
927
1096
  \`\`\`typescript
@@ -1553,6 +1722,65 @@ The merchant can hide a group entirely for one variant by setting \`maxOverride:
1553
1722
 
1554
1723
  Allergens (informational chips), scheduled availability windows, nested combos (depth \u2264 3 via \`nestedByModifierId\`), and downsell modifiers (negative \`priceDelta\`) are all built on the same data model. See INTEGRATION-OPTIONAL.md "Restaurant / build-your-own products" for those flows.`;
1555
1724
  }
1725
+ function getProductReviewsSection() {
1726
+ return `## Product Reviews (\u2605 ratings + JSON-LD for SEO)
1727
+
1728
+ **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.
1729
+
1730
+ \`\`\`typescript
1731
+ // PDP \u2014 list visible reviews (public)
1732
+ const { data } = await getClient().listProductReviews(productId, { page: 1, limit: 20 });
1733
+
1734
+ // Decide which UI to render for the current customer
1735
+ getClient().setCustomerToken(authToken); // after login
1736
+ const { eligible, reason, myReview } = await getClient().getMyProductReview(productId);
1737
+
1738
+ if (!eligible) {
1739
+ // reason: 'no_eligible_order' | 'reviews_disabled' | 'product_not_found'
1740
+ // \u2192 "only customers who purchased this product can leave a review"
1741
+ } else if (myReview) {
1742
+ // \u2192 edit form prefilled with myReview.rating + myReview.body
1743
+ } else {
1744
+ // \u2192 submit form (rating + body only \u2014 name/email come from customer profile)
1745
+ }
1746
+
1747
+ await getClient().submitProductReview(productId, { rating: 5, body: 'Loved it!' });
1748
+ await getClient().updateMyProductReview(productId, { rating: 4, body: 'Updated.' });
1749
+ await getClient().deleteMyProductReview(productId); // can submit a new one after
1750
+ \`\`\`
1751
+
1752
+ Each \`Product\` carries denormalized rollups: \`product.avgRating\`, \`product.reviewCount\`. Use these on PLP cards.
1753
+
1754
+ ### JSON-LD (mandatory for SEO stars in Google)
1755
+
1756
+ Emit \`aggregateRating\` ONLY when \`product.reviewCount > 0\`:
1757
+
1758
+ \`\`\`typescript
1759
+ const productJsonLd = {
1760
+ '@context': 'https://schema.org',
1761
+ '@type': 'Product',
1762
+ name: product.name,
1763
+ // \u2026existing fields
1764
+ ...(product.reviewCount > 0 && {
1765
+ aggregateRating: {
1766
+ '@type': 'AggregateRating',
1767
+ ratingValue: product.avgRating,
1768
+ reviewCount: product.reviewCount,
1769
+ bestRating: 5,
1770
+ worstRating: 1,
1771
+ },
1772
+ }),
1773
+ };
1774
+ \`\`\`
1775
+
1776
+ ### Rules
1777
+ - Rating must be an integer 1-5 (DB constraint).
1778
+ - Customer must be logged in AND have purchased the product (\`SHIPPED+\` for physical, \`PAID+\` for downloadable).
1779
+ - One review per (productId, customerId). Duplicate submit \u2192 409 \u2014 use updateMyProductReview instead.
1780
+ - Submit throttled 3 / 60s / IP; edit/delete 5 / 60s / IP.
1781
+ - \`verifiedPurchase\` is always true for customer-submitted reviews.
1782
+ - Stores with \`reviewsEnabled = false\` return 403 on storefront endpoints.`;
1783
+ }
1556
1784
  function getInventorySection() {
1557
1785
  return `## Inventory, Stock Display & Reservation Countdown
1558
1786
 
@@ -2499,6 +2727,8 @@ function getSectionByTopic(topic, connectionId, currency) {
2499
2727
  return getDiscountsSection();
2500
2728
  case "recommendations":
2501
2729
  return getRecommendationsSection();
2730
+ case "reviews":
2731
+ return getProductReviewsSection();
2502
2732
  case "product-customization-fields":
2503
2733
  return getProductCustomizationFieldsSection();
2504
2734
  case "modifier-groups":
@@ -2571,6 +2801,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2571
2801
  "",
2572
2802
  "---",
2573
2803
  "",
2804
+ getProductReviewsSection(),
2805
+ "",
2806
+ "---",
2807
+ "",
2574
2808
  getDiscountsSection(),
2575
2809
  "",
2576
2810
  "---",
@@ -2622,6 +2856,7 @@ var GET_SDK_DOCS_SCHEMA = {
2622
2856
  "inventory",
2623
2857
  "discounts",
2624
2858
  "recommendations",
2859
+ "reviews",
2625
2860
  "product-customization-fields",
2626
2861
  "tax",
2627
2862
  "critical-rules",
@@ -2639,9 +2874,7 @@ var GET_SDK_DOCS_SCHEMA = {
2639
2874
  async function handleGetSdkDocs(args) {
2640
2875
  const id = args.salesChannelId ?? args.connectionId;
2641
2876
  if (!args.salesChannelId && args.connectionId) {
2642
- console.warn(
2643
- "get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
2644
- );
2877
+ console.warn("get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead");
2645
2878
  }
2646
2879
  const content = getSectionByTopic(args.topic, id, args.currency);
2647
2880
  return {
@@ -3353,6 +3586,42 @@ interface CartBundleOffer {
3353
3586
  totalOriginalPrice: string;
3354
3587
  totalDiscountedPrice: string;
3355
3588
  }`;
3589
+ var REVIEWS_TYPES = `// ---- Product Reviews ----
3590
+
3591
+ interface ProductReview {
3592
+ id: string;
3593
+ productId: string;
3594
+ authorName: string; // max 100 chars
3595
+ rating: number; // integer 1-5
3596
+ body: string | null; // plain text, max 5000 chars
3597
+ verifiedPurchase: boolean; // derived server-side from DELIVERED orders
3598
+ hiddenAt?: string | null; // ISO datetime; admin responses only \u2014 null = visible
3599
+ createdAt: string; // ISO datetime
3600
+ }
3601
+
3602
+ interface ProductReviewAdmin extends ProductReview {
3603
+ customerId: string | null;
3604
+ authorEmail: string | null;
3605
+ orderId: string | null;
3606
+ updatedAt: string;
3607
+ }
3608
+
3609
+ interface WriteProductReviewInput {
3610
+ rating: number; // 1-5
3611
+ body?: string; // optional, max 5000 chars
3612
+ }
3613
+
3614
+ interface MyProductReview {
3615
+ eligible: boolean;
3616
+ // Machine-readable reason when not eligible. null when eligible=true.
3617
+ reason: 'no_eligible_order' | 'reviews_disabled' | 'product_not_found' | null;
3618
+ myReview: ProductReview | null;
3619
+ }
3620
+
3621
+ // Each Product carries denormalized review stats:
3622
+ // product.avgRating: number // 0 when reviewCount is 0
3623
+ // product.reviewCount: number // count of visible (hiddenAt IS NULL) reviews
3624
+ `;
3356
3625
  var INQUIRIES_TYPES = `// ---- Contact Inquiries & Forms ----
3357
3626
 
3358
3627
  // Two shapes \u2014 legacy and flexible. The two may be mixed; \`fields\` wins on key collision.
@@ -3596,6 +3865,7 @@ var TYPES_BY_DOMAIN = {
3596
3865
  payments: PAYMENTS_TYPES,
3597
3866
  helpers: HELPERS_TYPES,
3598
3867
  inquiries: INQUIRIES_TYPES,
3868
+ reviews: REVIEWS_TYPES,
3599
3869
  "modifier-groups": MODIFIER_GROUPS_TYPES
3600
3870
  };
3601
3871
  function getTypesByDomain(domain) {
@@ -3626,6 +3896,7 @@ var GET_TYPE_DEFINITIONS_SCHEMA = {
3626
3896
  "payments",
3627
3897
  "helpers",
3628
3898
  "inquiries",
3899
+ "reviews",
3629
3900
  "all"
3630
3901
  ]).describe(
3631
3902
  'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse.'
@@ -3647,6 +3918,7 @@ var GET_CODE_EXAMPLE_SCHEMA = {
3647
3918
  "sdk-init",
3648
3919
  "cart-read-and-mutate",
3649
3920
  "variant-selection",
3921
+ "variant-selector-swatches",
3650
3922
  "checkout-address-and-shipping",
3651
3923
  "checkout-payment-providers",
3652
3924
  "checkout-stripe-confirm",
@@ -3716,28 +3988,148 @@ for (const item of cart.items) {
3716
3988
  const unitPrice = parseFloat(item.unitPrice); // prices are strings!
3717
3989
  }`,
3718
3990
  "variant-selection": `// Variant selection with live stock + price updates.
3991
+ // Variants expose attributes as a flat object: { color: 'Red', size: 'M' }.
3992
+ // NOT 'options' \u2014 that field does not exist on ProductVariant.
3719
3993
  import { getVariantPrice, getStockStatus, getVariantOptions } from 'brainerce';
3720
3994
  import type { Product, ProductVariant } from 'brainerce';
3721
3995
 
3722
3996
  function selectVariant(product: Product, selections: Record<string, string>) {
3723
- // selections = { Size: 'M', Color: 'Red' }
3724
- const variant = product.variants.find((v) =>
3725
- v.options.every((o) => selections[o.name] === o.value)
3997
+ // selections = { size: 'M', color: 'Red' } (keys match variant.attributes keys)
3998
+ const variant = product.variants?.find((v) =>
3999
+ Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
3726
4000
  );
3727
4001
  if (!variant) return null;
3728
4002
 
3729
- const price = getVariantPrice(product, variant); // handles compare-at, currency
3730
- const stock = getStockStatus(variant); // 'IN_STOCK' | 'LOW_STOCK' | 'OUT_OF_STOCK'
3731
- const canPurchase = stock !== 'OUT_OF_STOCK';
4003
+ const price = getVariantPrice(variant, product.basePrice); // string, fallback-aware
4004
+ const stock = getStockStatus(variant.inventory); // 'in-stock' | 'low-stock' | 'out-of-stock' | 'unavailable'
4005
+ const canPurchase = variant.inventory?.canPurchase !== false;
3732
4006
 
3733
4007
  // Switch the main product image to the variant's image if it has one
3734
- const image = variant.image ?? product.images[0];
4008
+ const image = variant.image ?? product.images?.[0];
3735
4009
 
3736
4010
  return { variant, price, stock, canPurchase, image };
3737
4011
  }
3738
4012
 
3739
- // Build the option picker from getVariantOptions(product) \u2014 returns
3740
- // [{ name: 'Size', values: ['S','M','L'] }, ...]`,
4013
+ // Build the option picker by iterating product.variants and grouping
4014
+ // variant.attributes into { color: ['Red', 'Blue'], size: ['S','M','L'] }.
4015
+ // For each variant you can also call getVariantOptions(variant) which returns
4016
+ // the same key/value pairs as an array with translated names when setLocale() is active.
4017
+ // For swatch metadata (color hex, dual-color, image), use the
4018
+ // 'variant-selector-swatches' operation instead.`,
4019
+ "variant-selector-swatches": `// Variant picker that mixes color swatches and text buttons in one product.
4020
+ // Uses product.productAttributeOptions[] \u2014 the merchant-configured swatch
4021
+ // metadata. displayType is the AttributeDisplayType Prisma enum, one of:
4022
+ // 'DEFAULT' \u2014 plain text button
4023
+ // 'COLOR_SWATCH' \u2014 swatchColor (+ optional swatchColor2 dual-color gradient)
4024
+ // 'IMAGE_SWATCH' \u2014 swatchImageUrl thumbnail
4025
+ // 'MIXED_SWATCH' \u2014 per-option hybrid: image if swatchImageUrl is set,
4026
+ // otherwise fall back to swatchColor
4027
+ // getProductSwatches() groups options by attribute name so you can render each
4028
+ // attribute with its own displayType \u2014 a single product can have Color as
4029
+ // swatches AND Size as text buttons.
4030
+ import { getProductSwatches } from 'brainerce';
4031
+ import type { Product } from 'brainerce';
4032
+
4033
+ function VariantPicker({
4034
+ product,
4035
+ selections,
4036
+ onSelect,
4037
+ }: {
4038
+ product: Product;
4039
+ selections: Record<string, string>;
4040
+ onSelect: (attrName: string, value: string) => void;
4041
+ }) {
4042
+ const groups = getProductSwatches(product);
4043
+ // groups: [{ attributeName, displayType, options: [{ name, swatchColor, swatchColor2, swatchImageUrl }] }]
4044
+
4045
+ return (
4046
+ <>
4047
+ {groups.map((group) => (
4048
+ <div key={group.attributeName}>
4049
+ <label>{group.attributeName}: {selections[group.attributeName] ?? ''}</label>
4050
+ <div style={{ display: 'flex', gap: 8 }}>
4051
+ {group.options.map((opt) => {
4052
+ const selected = selections[group.attributeName] === opt.name;
4053
+ const onClick = () => onSelect(group.attributeName, opt.name);
4054
+
4055
+ // COLOR_SWATCH: round button. swatchColor2 = dual-color gradient.
4056
+ if (group.displayType === 'COLOR_SWATCH' && opt.swatchColor) {
4057
+ const bg = opt.swatchColor2
4058
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
4059
+ : opt.swatchColor;
4060
+ return (
4061
+ <button
4062
+ key={opt.name}
4063
+ type="button"
4064
+ title={opt.name}
4065
+ aria-pressed={selected}
4066
+ onClick={onClick}
4067
+ style={{
4068
+ width: 36,
4069
+ height: 36,
4070
+ borderRadius: '50%',
4071
+ background: bg,
4072
+ outline: selected ? '2px solid black' : 'none',
4073
+ }}
4074
+ />
4075
+ );
4076
+ }
4077
+
4078
+ // IMAGE_SWATCH: square thumbnail.
4079
+ if (group.displayType === 'IMAGE_SWATCH' && opt.swatchImageUrl) {
4080
+ return (
4081
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4082
+ <img src={opt.swatchImageUrl} alt={opt.name} width={40} height={40} />
4083
+ </button>
4084
+ );
4085
+ }
4086
+
4087
+ // MIXED_SWATCH: per-option hybrid (image wins if present).
4088
+ if (group.displayType === 'MIXED_SWATCH') {
4089
+ if (opt.swatchImageUrl) {
4090
+ return (
4091
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4092
+ <img src={opt.swatchImageUrl} alt={opt.name} width={40} height={40} />
4093
+ </button>
4094
+ );
4095
+ }
4096
+ if (opt.swatchColor) {
4097
+ const bg = opt.swatchColor2
4098
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
4099
+ : opt.swatchColor;
4100
+ return (
4101
+ <button
4102
+ key={opt.name}
4103
+ type="button"
4104
+ title={opt.name}
4105
+ aria-pressed={selected}
4106
+ onClick={onClick}
4107
+ style={{ width: 36, height: 36, borderRadius: '50%', background: bg }}
4108
+ />
4109
+ );
4110
+ }
4111
+ }
4112
+
4113
+ // DEFAULT (or any swatch type missing its data): text button.
4114
+ return (
4115
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4116
+ {opt.name}
4117
+ </button>
4118
+ );
4119
+ })}
4120
+ </div>
4121
+ </div>
4122
+ ))}
4123
+ </>
4124
+ );
4125
+ }
4126
+
4127
+ // After the user picks a value, find the matching ProductVariant:
4128
+ // product.variants?.find((v) =>
4129
+ // Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
4130
+ // )
4131
+ // Then read variant.price, variant.image, variant.inventory.canPurchase
4132
+ // to update the rest of the PDP.`,
3741
4133
  "checkout-address-and-shipping": `// Step 1-3 of the checkout flow. Never reorder or skip.
3742
4134
  import { client } from './brainerce';
3743
4135
 
@@ -4529,6 +4921,138 @@ function renderCartItem(item: CartItem): string {
4529
4921
  // multiply unitPrice \xD7 quantity directly.
4530
4922
  function lineTotal(item: CartItem): number {
4531
4923
  return item.unitPrice * item.quantity;
4924
+ }`,
4925
+ "product-reviews": `// Purchaser-only reviews. Customer must be logged in AND have purchased
4926
+ // the product. The component switches between sign-in CTA / not-eligible /
4927
+ // submit form / edit form based on getMyProductReview().
4928
+ import { getClient, getServerClient } from '@/lib/brainerce';
4929
+ import { checkAuthStatus } from '@/lib/auth';
4930
+ import type { Product, ProductReview, MyProductReview } from 'brainerce';
4931
+
4932
+ // Server component \u2014 fetches existing reviews + emits JSON-LD aggregateRating.
4933
+ export async function ProductReviewsSection({ product }: { product: Product }) {
4934
+ const { data } = await getServerClient().listProductReviews(product.id, { page: 1, limit: 20 });
4935
+
4936
+ return (
4937
+ <section>
4938
+ <h2>Reviews ({product.reviewCount ?? 0})</h2>
4939
+ {data.length === 0 && <p>No reviews yet.</p>}
4940
+ {data.map((r) => (
4941
+ <article key={r.id}>
4942
+ <strong>{r.authorName}</strong>
4943
+ {r.verifiedPurchase && <span> \xB7 Verified purchase</span>}
4944
+ <div>{'\u2605'.repeat(r.rating)}{'\u2606'.repeat(5 - r.rating)}</div>
4945
+ {r.body && <p>{r.body}</p>}
4946
+ </article>
4947
+ ))}
4948
+ <ReviewForm productId={product.id} />
4949
+ </section>
4950
+ );
4951
+ }
4952
+
4953
+ // JSON-LD \u2014 emit aggregateRating only when there is data
4954
+ function productJsonLd(product: Product, url: string) {
4955
+ return {
4956
+ '@context': 'https://schema.org',
4957
+ '@type': 'Product',
4958
+ name: product.name,
4959
+ image: product.images?.[0]?.url,
4960
+ url,
4961
+ sku: product.sku ?? product.id,
4962
+ ...(product.reviewCount && product.reviewCount > 0 && {
4963
+ aggregateRating: {
4964
+ '@type': 'AggregateRating',
4965
+ ratingValue: product.avgRating,
4966
+ reviewCount: product.reviewCount,
4967
+ bestRating: 5,
4968
+ worstRating: 1,
4969
+ },
4970
+ }),
4971
+ };
4972
+ }
4973
+
4974
+ // Client-side form
4975
+ 'use client';
4976
+ import { useEffect, useState } from 'react';
4977
+
4978
+ type Stage =
4979
+ | { kind: 'loading' }
4980
+ | { kind: 'signed_out' }
4981
+ | { kind: 'not_eligible'; reason: MyProductReview['reason'] }
4982
+ | { kind: 'submit' }
4983
+ | { kind: 'edit'; review: ProductReview };
4984
+
4985
+ function ReviewForm({ productId }: { productId: string }) {
4986
+ const [stage, setStage] = useState<Stage>({ kind: 'loading' });
4987
+ const [rating, setRating] = useState(5);
4988
+ const [body, setBody] = useState('');
4989
+ const [error, setError] = useState<string | null>(null);
4990
+
4991
+ useEffect(() => {
4992
+ (async () => {
4993
+ const auth = await checkAuthStatus();
4994
+ if (!auth.isLoggedIn) return setStage({ kind: 'signed_out' });
4995
+ const me = await getClient().getMyProductReview(productId);
4996
+ if (!me.eligible) return setStage({ kind: 'not_eligible', reason: me.reason });
4997
+ if (me.myReview) {
4998
+ setRating(me.myReview.rating);
4999
+ setBody(me.myReview.body ?? '');
5000
+ return setStage({ kind: 'edit', review: me.myReview });
5001
+ }
5002
+ setStage({ kind: 'submit' });
5003
+ })();
5004
+ }, [productId]);
5005
+
5006
+ if (stage.kind === 'loading') return <p>Loading\u2026</p>;
5007
+ if (stage.kind === 'signed_out')
5008
+ return <p><a href="/account/login">Sign in</a> to leave a review.</p>;
5009
+ if (stage.kind === 'not_eligible')
5010
+ return <p>Only customers who purchased this product can leave a review.</p>;
5011
+
5012
+ async function submit(e: React.FormEvent) {
5013
+ e.preventDefault();
5014
+ setError(null);
5015
+ const client = getClient();
5016
+ const input = { rating, body: body || undefined };
5017
+ try {
5018
+ if (stage.kind === 'edit') {
5019
+ await client.updateMyProductReview(productId, input);
5020
+ } else {
5021
+ await client.submitProductReview(productId, input);
5022
+ }
5023
+ window.location.reload();
5024
+ } catch (err: any) {
5025
+ if (err?.status === 403) setError('Only customers who purchased this product can leave a review.');
5026
+ else if (err?.status === 409) setError('You already reviewed this product.');
5027
+ else if (err?.status === 429) setError('Too many submissions. Please wait a moment.');
5028
+ else setError('Could not save your review. Please try again.');
5029
+ }
5030
+ }
5031
+
5032
+ async function remove() {
5033
+ if (!confirm('Delete your review?')) return;
5034
+ await getClient().deleteMyProductReview(productId);
5035
+ window.location.reload();
5036
+ }
5037
+
5038
+ return (
5039
+ <form onSubmit={submit}>
5040
+ <h3>{stage.kind === 'edit' ? 'Edit your review' : 'Write a review'}</h3>
5041
+ <div>
5042
+ {[1,2,3,4,5].map(n => (
5043
+ <button type="button" key={n} onClick={() => setRating(n)}>
5044
+ {n <= rating ? '\u2605' : '\u2606'}
5045
+ </button>
5046
+ ))}
5047
+ </div>
5048
+ <textarea value={body} onChange={(e) => setBody(e.target.value)} maxLength={5000} />
5049
+ <button type="submit">{stage.kind === 'edit' ? 'Save changes' : 'Submit review'}</button>
5050
+ {stage.kind === 'edit' && (
5051
+ <button type="button" onClick={remove}>Delete review</button>
5052
+ )}
5053
+ {error && <p role="alert">{error}</p>}
5054
+ </form>
5055
+ );
4532
5056
  }`
4533
5057
  };
4534
5058
  async function handleGetCodeExample(args) {
@@ -5331,6 +5855,13 @@ var FEATURES = [
5331
5855
  sdk: "client.getProductBySlug(slug). Helpers: getProductPriceInfo, getVariantPrice, getStockStatus, getVariantOptions, getProductSwatches, getDescriptionContent, getProductMetafieldValue.",
5332
5856
  mandatory: "mandatory"
5333
5857
  },
5858
+ {
5859
+ id: "product-reviews",
5860
+ title: "Display + collect product reviews (purchaser-only) with stars + JSON-LD",
5861
+ 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.',
5862
+ 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.",
5863
+ mandatory: "mandatory"
5864
+ },
5334
5865
  {
5335
5866
  id: "product-customization-fields",
5336
5867
  title: "Render buyer-input customization fields on the product page",