brainerce 1.0.2 → 1.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.
@@ -1,700 +1,782 @@
1
- # Brainerce Store Builder
2
-
3
- Build a **{store_type}** store called "{store_name}" | Style: **{style}** | Currency: **{currency}**
4
-
5
- ---
6
-
7
- ## ⛔ STOP! Read These 3 Rules First (Breaking = Store Won't Work)
8
-
9
- ### Rule 1: Guest vs Logged-In = Different Checkout Methods!
10
-
11
- ```typescript
12
- // ❌ THIS WILL FAIL - "Cart not found" error!
13
- const cart = await client.smartGetCart(); // Guest cart has id: "__local__"
14
- await client.createCheckout({ cartId: cart.id }); // 💥 "__local__" doesn't exist on server!
15
-
16
- // ✅ CORRECT - Check user type first!
17
- if (client.isCustomerLoggedIn()) {
18
- // Logged-in user → server cart exists
19
- const checkout = await client.createCheckout({ cartId: cart.id });
20
- const checkoutId = checkout.id;
21
- } else {
22
- // Guest user → use startGuestCheckout()
23
- const result = await client.startGuestCheckout();
24
- const checkoutId = result.checkoutId;
25
- }
26
- ```
27
-
28
- | User Type | Cart Location | Checkout Method | Get Checkout ID |
29
- | ------------- | ------------- | ---------------------------- | ------------------- |
30
- | **Guest** | localStorage | `startGuestCheckout()` | `result.checkoutId` |
31
- | **Logged-in** | Server | `createCheckout({ cartId })` | `checkout.id` |
32
-
33
- ### Rule 2: Complete Checkout & Clear Cart After Payment!
34
-
35
- ```typescript
36
- // On /checkout/success page - MUST DO THIS!
37
- export default function CheckoutSuccessPage() {
38
- const checkoutId = new URLSearchParams(window.location.search).get('checkout_id');
39
-
40
- useEffect(() => {
41
- if (checkoutId) {
42
- // ⚠️ CRITICAL: This sends the order to the server AND clears the cart!
43
- // handlePaymentSuccess() only clears the local cart - it does NOT create the order!
44
- client.completeGuestCheckout(checkoutId);
45
- }
46
- }, []);
47
-
48
- return <div>Thank you for your order!</div>;
49
- }
50
- ```
51
-
52
- > **WARNING:** Do NOT use `handlePaymentSuccess()` to complete an order. It only clears
53
- > the local cart (localStorage) and does NOT communicate with the server.
54
- > Always use `completeGuestCheckout()` after payment succeeds.
55
-
56
- ### Rule 3: Never Hardcode Products!
57
-
58
- ```typescript
59
- // ❌ FORBIDDEN - Store will show fake data!
60
- const products = [{ id: '1', name: 'T-Shirt', price: 29.99 }];
61
-
62
- // ✅ CORRECT - Fetch from API
63
- const { data: products } = await client.getProducts();
64
- ```
65
-
66
- ---
67
-
68
- ## Quick Setup
69
-
70
- ```bash
71
- npm install brainerce
72
- ```
73
-
74
- ```typescript
75
- // lib/brainerce.ts
76
- import { BrainerceClient } from 'brainerce';
77
-
78
- export const client = new BrainerceClient({
79
- connectionId: '{connection_id}',
80
- baseUrl: '{api_url}',
81
- });
82
-
83
- // Restore customer session on page load
84
- export function initBrainerce() {
85
- if (typeof window === 'undefined') return;
86
- const token = localStorage.getItem('customerToken');
87
- if (token) client.setCustomerToken(token);
88
- }
89
-
90
- // Save/clear customer token
91
- export function setCustomerToken(token: string | null) {
92
- if (token) {
93
- localStorage.setItem('customerToken', token);
94
- client.setCustomerToken(token);
95
- } else {
96
- localStorage.removeItem('customerToken');
97
- client.clearCustomerToken();
98
- }
99
- }
100
- ```
101
-
102
- ---
103
-
104
- ## Cart (Works for Both Guest & Logged-in)
105
-
106
- ```typescript
107
- // Get or create cart - handles both guest (localStorage) and logged-in (server) automatically
108
- const cart = await client.smartGetCart();
109
-
110
- // Add to cart - ALWAYS pass name, price, image for guest cart display!
111
- await client.smartAddToCart({
112
- productId: product.id,
113
- variantId: selectedVariant?.id,
114
- quantity: 1,
115
- // IMPORTANT: Pass product info for guest cart display
116
- name: selectedVariant?.name ? `${product.name} - ${selectedVariant.name}` : product.name,
117
- price: getVariantPrice(selectedVariant, product.basePrice),
118
- image: selectedVariant?.image
119
- ? typeof selectedVariant.image === 'string'
120
- ? selectedVariant.image
121
- : selectedVariant.image.url
122
- : product.images?.[0]?.url,
123
- });
124
-
125
- // Update quantity (by productId, not itemId!)
126
- await client.smartUpdateCartItem('prod_xxx', 2); // productId, quantity
127
- await client.smartUpdateCartItem('prod_xxx', 3, 'var_xxx'); // with variant
128
-
129
- // Remove item (by productId, not itemId!)
130
- await client.smartRemoveFromCart('prod_xxx');
131
- await client.smartRemoveFromCart('prod_xxx', 'var_xxx'); // with variant
132
-
133
- // Get cart totals (cart doesn't have .total field!)
134
- import { getCartTotals } from 'brainerce';
135
- const totals = getCartTotals(cart);
136
- // { subtotal: 59.98, discount: 10, shipping: 0, total: 49.98 }
137
-
138
- // All smart* methods return a server Cart (even for guests via session carts)
139
- // Cart has: id, itemCount, subtotal, discountAmount, items, couponCode
140
- ```
141
-
142
- ### 🏷️ Coupon Code (Add to Cart Page!)
143
-
144
- ```typescript
145
- // Apply coupon to cart
146
- const cart = await client.smartGetCart();
147
- const updatedCart = await client.applyCoupon(cart.id, 'SAVE20');
148
- console.log(updatedCart.discountAmount); // "10.00" (string)
149
- console.log(updatedCart.couponCode); // "SAVE20"
150
-
151
- // Remove coupon
152
- const updatedCart = await client.removeCoupon(cartId);
153
-
154
- // Calculate totals including discount
155
- import { getCartTotals } from 'brainerce';
156
- const totals = getCartTotals(cart); // { subtotal, discount, shipping, total }
157
- ```
158
-
159
- **Cart page coupon UI:**
160
-
161
- ```typescript
162
- // State
163
- const [couponCode, setCouponCode] = useState('');
164
- const [couponError, setCouponError] = useState('');
165
- const [isApplying, setIsApplying] = useState(false);
166
-
167
- // Apply handler
168
- async function handleApplyCoupon() {
169
- if (!couponCode.trim() || !('id' in cart)) return;
170
- setIsApplying(true);
171
- setCouponError('');
172
- try {
173
- const updatedCart = await client.applyCoupon(cart.id, couponCode.trim());
174
- setCart(updatedCart);
175
- setCouponCode('');
176
- } catch (err: any) {
177
- setCouponError(err.message || 'Invalid coupon code');
178
- } finally {
179
- setIsApplying(false);
180
- }
181
- }
182
-
183
- // Remove handler
184
- async function handleRemoveCoupon() {
185
- if (!('id' in cart)) return;
186
- const updatedCart = await client.removeCoupon(cart.id);
187
- setCart(updatedCart);
188
- }
189
-
190
- // UI - place in cart order summary
191
- {('id' in cart) && (
192
- <div>
193
- {cart.couponCode ? (
194
- <div className="flex items-center justify-between bg-green-50 p-2 rounded">
195
- <span className="text-green-700 text-sm">🏷️ {cart.couponCode}</span>
196
- <button onClick={handleRemoveCoupon} className="text-red-500 text-sm">✕</button>
197
- </div>
198
- ) : (
199
- <div className="flex gap-2">
200
- <input value={couponCode} onChange={(e) => setCouponCode(e.target.value)}
201
- placeholder="Coupon code" className="flex-1 border rounded px-3 py-2 text-sm" />
202
- <button onClick={handleApplyCoupon} disabled={isApplying}
203
- className="px-4 py-2 bg-gray-800 text-white rounded text-sm">
204
- {isApplying ? '...' : 'Apply'}
205
- </button>
206
- </div>
207
- )}
208
- {couponError && <p className="text-red-500 text-xs mt-1">{couponError}</p>}
209
- </div>
210
- )}
211
-
212
- // Order summary - show discount line
213
- {('id' in cart) && parseFloat(cart.discountAmount) > 0 && (
214
- <div className="text-green-600">Discount: -{formatPrice(cart.discountAmount)}</div>
215
- )}
216
- ```
217
-
218
- **Checkout order summary - coupon carries over from cart:**
219
-
220
- ```typescript
221
- // Checkout already includes coupon from cart
222
- <div>Subtotal: {formatPrice(checkout.subtotal)}</div>
223
- {parseFloat(checkout.discountAmount) > 0 && (
224
- <div className="text-green-600">
225
- Discount ({checkout.couponCode}): -{formatPrice(checkout.discountAmount)}
226
- </div>
227
- )}
228
- <div>Shipping: {formatPrice(selectedRate?.price || '0')}</div>
229
- <div className="font-bold">Total: {formatPrice(checkout.total)}</div>
230
- ```
231
-
232
- ---
233
-
234
- ## 🛒 Partial Checkout (AliExpress Style) - REQUIRED!
235
-
236
- Cart page MUST have checkboxes so users can select which items to buy:
237
-
238
- ```typescript
239
- // Cart page - track selected items
240
- const [selectedIndices, setSelectedIndices] = useState<number[]>(
241
- cart.items.map((_, i) => i) // All selected by default
242
- );
243
-
244
- const toggleItem = (index: number) => {
245
- setSelectedIndices(prev =>
246
- prev.includes(index)
247
- ? prev.filter(i => i !== index)
248
- : [...prev, index]
249
- );
250
- };
251
-
252
- const toggleAll = () => {
253
- if (selectedIndices.length === cart.items.length) {
254
- setSelectedIndices([]); // Deselect all
255
- } else {
256
- setSelectedIndices(cart.items.map((_, i) => i)); // Select all
257
- }
258
- };
259
-
260
- // In your cart UI:
261
- <div>
262
- <label>
263
- <input
264
- type="checkbox"
265
- checked={selectedIndices.length === cart.items.length}
266
- onChange={toggleAll}
267
- />
268
- Select All
269
- </label>
270
- </div>
271
-
272
- {cart.items.map((item, index) => (
273
- <div key={index}>
274
- <input
275
- type="checkbox"
276
- checked={selectedIndices.includes(index)}
277
- onChange={() => toggleItem(index)}
278
- />
279
- {/* ... item details ... */}
280
- </div>
281
- ))}
282
-
283
- // On checkout button - pass selected items!
284
- const handleCheckout = async () => {
285
- if (selectedIndices.length === 0) {
286
- alert('Please select items to checkout');
287
- return;
288
- }
289
-
290
- const result = await client.startGuestCheckout({ selectedIndices });
291
- // Only selected items go to checkout, others stay in cart!
292
- };
293
- ```
294
-
295
- **Why this matters:**
296
-
297
- - Users can buy some items now, leave others for later
298
- - After payment, `completeGuestCheckout()` sends the order and only removes purchased items
299
- - Remaining items stay in cart for future purchase
300
-
301
- **⚠️ Order Summary on Checkout Page - Use checkout.lineItems!**
302
-
303
- ```typescript
304
- // ❌ WRONG - Shows ALL cart items (even unselected ones!)
305
- <div className="order-summary">
306
- {cart.items.map(item => (
307
- <div>{item.product.name} - ${item.price}</div>
308
- ))}
309
- </div>
310
-
311
- // ✅ CORRECT - Shows only items being purchased in this checkout
312
- <div className="order-summary">
313
- {checkout.lineItems.map(item => (
314
- <div>{item.product.name} - ${item.price}</div>
315
- ))}
316
- </div>
317
- ```
318
-
319
- The `checkout` object's `lineItems` array contains ONLY the items selected for this checkout!
320
-
321
- ---
322
-
323
- ## Complete Checkout Flow
324
-
325
- ### Step 1: Start Checkout (Different for Guest vs Logged-in!)
326
-
327
- ```typescript
328
- async function startCheckout() {
329
- const cart = await client.smartGetCart();
330
-
331
- if (cart.items.length === 0) {
332
- alert('Cart is empty');
333
- return;
334
- }
335
-
336
- let checkoutId: string;
337
-
338
- if (client.isCustomerLoggedIn()) {
339
- // Logged-in: create checkout from server cart
340
- const checkout = await client.createCheckout({ cartId: cart.id });
341
- checkoutId = checkout.id;
342
- } else {
343
- // Guest: use startGuestCheckout (syncs local cart to server)
344
- const result = await client.startGuestCheckout();
345
- if (!result.tracked || !result.checkoutId) {
346
- throw new Error('Failed to create checkout');
347
- }
348
- checkoutId = result.checkoutId;
349
- }
350
-
351
- // Save for payment page
352
- localStorage.setItem('checkoutId', checkoutId);
353
-
354
- // Navigate to checkout
355
- window.location.href = '/checkout';
356
- }
357
- ```
358
-
359
- ### Step 2: Shipping Address
360
-
361
- ```typescript
362
- const checkoutId = localStorage.getItem('checkoutId')!;
363
-
364
- // Set shipping address (email is required!)
365
- const { checkout, rates } = await client.setShippingAddress(checkoutId, {
366
- email: 'customer@example.com',
367
- firstName: 'John',
368
- lastName: 'Doe',
369
- line1: '123 Main St',
370
- city: 'New York',
371
- region: 'NY', // ⚠️ Use 'region', NOT 'state'!
372
- postalCode: '10001',
373
- country: 'US',
374
- });
375
-
376
- // Show available shipping rates
377
- rates.forEach((rate) => {
378
- console.log(`${rate.name}: $${rate.price}`);
379
- });
380
- ```
381
-
382
- ### Step 3: Select Shipping Method
383
-
384
- ```typescript
385
- await client.selectShippingMethod(checkoutId, selectedRateId);
386
- ```
387
-
388
- ### Step 4: Payment (Multi-Provider)
389
-
390
- ```typescript
391
- // 1. Check if payment is configured
392
- const { hasPayments, providers } = await client.getPaymentProviders();
393
- if (!hasPayments) {
394
- return <div>Payment not configured for this store</div>;
395
- }
396
-
397
- // 2. Create payment intent — returns provider type!
398
- const intent = await client.createPaymentIntent(checkoutId, {
399
- successUrl: `${window.location.origin}/checkout/success?checkout_id=${checkoutId}`,
400
- cancelUrl: `${window.location.origin}/checkout?error=cancelled`,
401
- });
402
-
403
- // 3. Branch by provider
404
- if (intent.provider === 'grow') {
405
- // Grow: clientSecret is a payment URL show in iframe
406
- // <iframe src={intent.clientSecret} style={{ width: '100%', minHeight: '600px', border: 'none' }} allow="payment" />
407
- // Supports credit cards, Bit, Apple Pay, Google Pay, bank transfers
408
- // Add fallback: <a href={intent.clientSecret} target="_blank">Open payment in new tab</a>
409
- // Order created automatically via webhook!
410
- } else {
411
- // Stripe: install @stripe/stripe-js @stripe/react-stripe-js
412
- import { loadStripe } from '@stripe/stripe-js';
413
- const stripeProvider = providers.find(p => p.provider === 'stripe');
414
- const stripe = await loadStripe(stripeProvider.publicKey, {
415
- stripeAccount: stripeProvider.stripeAccountId,
416
- });
417
-
418
- // Confirm payment (in your payment form)
419
- const { error } = await stripe.confirmPayment({
420
- elements,
421
- confirmParams: {
422
- return_url: `${window.location.origin}/checkout/success?checkout_id=${checkoutId}`,
423
- },
424
- });
425
-
426
- if (error) {
427
- setError(error.message);
428
- }
429
- // If no error, Stripe redirects to success page
430
- }
431
- ```
432
-
433
- ### Step 5: Success Page (Complete Order & Clear Cart!)
434
-
435
- ```typescript
436
- // /checkout/success/page.tsx
437
- 'use client';
438
- import { useEffect, useState } from 'react';
439
- import { client } from '@/lib/brainerce';
440
-
441
- export default function CheckoutSuccessPage() {
442
- const [orderNumber, setOrderNumber] = useState<string>();
443
- const [loading, setLoading] = useState(true);
444
-
445
- useEffect(() => {
446
- // Break out of iframe if redirected here from Grow payment page
447
- if (window.top !== window.self) {
448
- window.top!.location.href = window.location.href;
449
- return;
450
- }
451
-
452
- const checkoutId = new URLSearchParams(window.location.search).get('checkout_id');
453
-
454
- if (checkoutId) {
455
- // ⚠️ CRITICAL: Complete the order on the server AND clear the cart!
456
- // Do NOT use handlePaymentSuccess() - it only clears localStorage!
457
- client.completeGuestCheckout(checkoutId).then(result => {
458
- setOrderNumber(result.orderNumber);
459
- setLoading(false);
460
- }).catch(() => {
461
- // Order may already be completed (e.g., page refresh) - check status
462
- client.getPaymentStatus(checkoutId).then(status => {
463
- if (status.orderNumber) {
464
- setOrderNumber(status.orderNumber);
465
- }
466
- setLoading(false);
467
- });
468
- });
469
- }
470
- }, []);
471
-
472
- return (
473
- <div className="text-center py-12">
474
- <h1 className="text-2xl font-bold text-green-600">Thank you for your order!</h1>
475
- {loading && <p className="mt-2">Processing your order...</p>}
476
- {orderNumber && <p className="mt-2">Order #{orderNumber}</p>}
477
- <p className="mt-4">A confirmation email will be sent shortly.</p>
478
- </div>
479
- );
480
- }
481
- ```
482
-
483
- ---
484
-
485
- ## Partial Checkout (AliExpress Style)
486
-
487
- Allow customers to buy only some items from their cart:
488
-
489
- ```typescript
490
- // Start checkout with only selected items (by index)
491
- const result = await client.startGuestCheckout({
492
- selectedIndices: [0, 2], // Buy items at index 0 and 2 only
493
- });
494
-
495
- // After payment, completeGuestCheckout() sends the order AND removes only those items!
496
- // Other items stay in cart.
497
- ```
498
-
499
- ---
500
-
501
- ## Products API
502
-
503
- ```typescript
504
- // List products with pagination
505
- const { data: products, meta } = await client.getProducts({
506
- page: 1,
507
- limit: 20,
508
- search: 'blue shirt', // Searches name, description, SKU, categories, tags
509
- });
510
- // meta = { page: 1, limit: 20, total: 150, totalPages: 8 }
511
-
512
- // Get single product by slug (for product detail page)
513
- const product = await client.getProductBySlug('blue-cotton-shirt');
514
-
515
- // Search suggestions (for autocomplete)
516
- const suggestions = await client.getSearchSuggestions('blue', 5);
517
- // { products: [...], categories: [...] }
518
- ```
519
-
520
- ---
521
-
522
- ## Product Custom Fields (Metafields)
523
-
524
- Products may have custom fields defined by the store owner (e.g., "Material", "Care Instructions", "Warranty").
525
-
526
- ```typescript
527
- import { getProductMetafield, getProductMetafieldValue } from 'brainerce';
528
-
529
- // Access metafields on a product
530
- const product = await client.getProductBySlug('blue-shirt');
531
-
532
- // Get all custom fields
533
- product.metafields?.forEach((field) => {
534
- console.log(`${field.definitionName}: ${field.value}`);
535
- });
536
-
537
- // Get specific field by key
538
- const material = getProductMetafieldValue(product, 'material');
539
- const careInstructions = getProductMetafield(product, 'care_instructions');
540
-
541
- // Get available metafield definitions (schema)
542
- const { definitions } = await client.getPublicMetafieldDefinitions();
543
- // Use definitions to build dynamic UI (filters, forms, etc.)
544
- ```
545
-
546
- > **Tip:** `metafields` may be empty if the store hasn't defined custom fields. Always use optional chaining.
547
-
548
- ---
549
-
550
- ## Customer Authentication
551
-
552
- ```typescript
553
- // Register
554
- const auth = await client.registerCustomer({
555
- email: 'john@example.com',
556
- password: 'securepass123',
557
- firstName: 'John',
558
- lastName: 'Doe',
559
- });
560
-
561
- if (auth.requiresVerification) {
562
- // Store token for verification step
563
- localStorage.setItem('verificationToken', auth.token);
564
- localStorage.setItem('verificationEmail', 'john@example.com');
565
- window.location.href = '/verify-email';
566
- } else {
567
- client.setCustomerToken(auth.token);
568
- localStorage.setItem('customerToken', auth.token);
569
- }
570
-
571
- // Login
572
- const auth = await client.loginCustomer('john@example.com', 'password');
573
-
574
- if (auth.requiresVerification) {
575
- localStorage.setItem('verificationToken', auth.token);
576
- localStorage.setItem('verificationEmail', 'john@example.com');
577
- window.location.href = '/verify-email';
578
- } else {
579
- client.setCustomerToken(auth.token);
580
- localStorage.setItem('customerToken', auth.token);
581
- }
582
-
583
- // Verify email (on /verify-email page)
584
- const result = await client.verifyEmail(code, token);
585
- if (result.verified) {
586
- client.setCustomerToken(token);
587
- localStorage.setItem('customerToken', token);
588
- localStorage.removeItem('verificationToken');
589
- localStorage.removeItem('verificationEmail');
590
- window.location.href = '/account';
591
- }
592
-
593
- // Resend verification code
594
- await client.resendVerificationEmail(token);
595
-
596
- // Logout
597
- client.setCustomerToken(null);
598
- localStorage.removeItem('customerToken');
599
-
600
- // Get profile (requires token)
601
- const profile = await client.getMyProfile();
602
-
603
- // Get order history
604
- const { data: orders, meta } = await client.getMyOrders({ page: 1, limit: 10 });
605
- ```
606
-
607
- ---
608
-
609
- ## OAuth / Social Login
610
-
611
- ```typescript
612
- // Get available providers for this store
613
- const { providers } = await client.getAvailableOAuthProviders();
614
- // providers = ['GOOGLE', 'FACEBOOK', 'GITHUB']
615
-
616
- // Redirect to OAuth provider
617
- const { authorizationUrl } = await client.getOAuthAuthorizeUrl('GOOGLE', {
618
- redirectUrl: `${window.location.origin}/auth/callback`,
619
- });
620
- window.location.href = authorizationUrl;
621
-
622
- // Handle callback (on /auth/callback page — backend redirects here with params)
623
- const params = new URLSearchParams(window.location.search);
624
- if (params.get('oauth_success') === 'true') {
625
- const token = params.get('token');
626
- client.setCustomerToken(token!);
627
- // Also available: customer_id, customer_email, is_new
628
- } else if (params.get('oauth_error')) {
629
- // Show error to user
630
- }
631
- ```
632
-
633
- ---
634
-
635
- ## Required Pages Checklist
636
-
637
- - [ ] **Home** (`/`) - Featured products grid
638
- - [ ] **Products** (`/products`) - Product list with infinite scroll
639
- - [ ] **Product Detail** (`/products/[slug]`) - Use `getProductBySlug(slug)`
640
- - [ ] **Cart** (`/cart`) - Show items, quantities, totals, **coupon code input**, discount display
641
- - [ ] **Checkout** (`/checkout`) - Address → Shipping → Payment. **Show discount in order summary!**
642
- - [ ] **Success** (`/checkout/success`) - **Must call `completeGuestCheckout()`!**
643
- - [ ] **Login** (`/login`) - Email/password + social buttons, handle `requiresVerification`
644
- - [ ] **Register** (`/register`) - Registration form, handle `requiresVerification`
645
- - [ ] **Verify Email** (`/verify-email`) - 6-digit code input + resend button. **ALWAYS create this page** even if verification is currently disabled — the store owner can enable it at any time
646
- - [ ] **OAuth Callback** (`/auth/callback`) - Handle OAuth redirect with token from URL params
647
- - [ ] **Account** (`/account`) - Profile + order history
648
- - [ ] **Header** - Logo, nav, cart icon with count, search
649
-
650
- ### ALWAYS Build These (Even If Currently Disabled)
651
-
652
- Some features may not be configured yet, but the store owner can enable them at any time. **Always create the UI** — SDK methods return empty/null when not configured:
653
-
654
- - **Email Verification** `/verify-email` page. `requiresVerification` is checked in login/register flows.
655
- - **OAuth Buttons** → Social login buttons on Login & Register + `/auth/callback` page. `getAvailableOAuthProviders()` returns `[]` when none configured — buttons just don't render.
656
- - **Discount Banners** → `getDiscountBanners()` returns `[]` when no rules — component renders nothing.
657
- - **Product Discount Badges** → `getProductDiscountBadge(id)` returns `null` — renders nothing.
658
- - **Cart Nudges** → `cart.nudges` is `[]` — renders nothing.
659
- - **Coupon Input** → Always show in cart. Works even with no coupons configured.
660
-
661
- ---
662
-
663
- ## Common Type Gotchas
664
-
665
- ```typescript
666
- // WRONG // CORRECT
667
- address.state address.region
668
- cart.total getCartTotals(cart).total
669
- cart.discount cart.discountAmount
670
- item.name (in cart) item.product.name
671
- response.url (OAuth) response.authorizationUrl
672
- providers.forEach (OAuth) response.providers.forEach
673
- status === 'completed' status === 'succeeded'
674
- product.metafields.name product.metafields[0].definitionName
675
- product.metafields.key product.metafields[0].definitionKey
676
- orderItem.unitPrice orderItem.price (OrderItem is FLAT, not nested!)
677
- cartItem.price cartItem.unitPrice (Cart/Checkout items use unitPrice)
678
- waitResult.orderNumber waitResult.status.orderNumber (nested in PaymentStatus)
679
- variant.attributes.map(...) Object.entries(variant.attributes || {}) (it's an object!)
680
- categorySuggestion.slug // ❌ doesn't exist! Only: id, name, productCount
681
- order.status === 'COMPLETED' order.status === 'delivered' (OrderStatus is lowercase!)
682
- getCartTotals(cart) // Works all carts are server carts now
683
- result.checkoutId (guest checkout) // ⚠️ Check result.tracked first! It's a union type
684
- ```
685
-
686
- **Key distinctions:**
687
-
688
- - **OrderItem** (from orders): Flat structure — `item.price`, `item.name`, `item.image`
689
- - **CartItem / CheckoutLineItem**: Nested structure — `item.unitPrice`, `item.product.name`, `item.product.images`
690
- - **`getCartTotals()`** works on all carts — guests now use server-side session carts with full `subtotal`/`discountAmount` fields.
691
- - **`GuestCheckoutStartResponse`** is a union type — always check `result.tracked` before accessing `result.checkoutId`
692
- - **`WaitForOrderResult`** has `result.status.orderNumber`, NOT `result.orderNumber`. But `completeGuestCheckout()` returns `GuestOrderResponse` which DOES have `result.orderNumber` directly.
693
- - **Cart state**: Use `useState<Cart | null>(null)` and load with `smartGetCart()` in `useEffect` — all carts are server-side now, no hydration mismatch issues.
694
-
695
- ---
696
-
697
- ## Full SDK Documentation
698
-
699
- For complete API reference and working code examples:
700
- **https://brainerce.com/docs/sdk**
1
+ # Brainerce Store Builder
2
+
3
+ Build a **{store_type}** store called "{store_name}" | Style: **{style}** | Currency: **{currency}**
4
+
5
+ ---
6
+
7
+ ## ⛔ STOP! Read These 3 Rules First (Breaking = Store Won't Work)
8
+
9
+ ### Rule 1: Guest vs Logged-In = Different Checkout Methods!
10
+
11
+ ```typescript
12
+ // ❌ THIS WILL FAIL - "Cart not found" error!
13
+ const cart = await client.smartGetCart(); // Guest cart has id: "__local__"
14
+ await client.createCheckout({ cartId: cart.id }); // 💥 "__local__" doesn't exist on server!
15
+
16
+ // ✅ CORRECT - Check user type first!
17
+ if (client.isCustomerLoggedIn()) {
18
+ // Logged-in user → server cart exists
19
+ const checkout = await client.createCheckout({ cartId: cart.id });
20
+ const checkoutId = checkout.id;
21
+ } else {
22
+ // Guest user → use startGuestCheckout()
23
+ const result = await client.startGuestCheckout();
24
+ const checkoutId = result.checkoutId;
25
+ }
26
+ ```
27
+
28
+ | User Type | Cart Location | Checkout Method | Get Checkout ID |
29
+ | ------------- | ------------- | ---------------------------- | ------------------- |
30
+ | **Guest** | localStorage | `startGuestCheckout()` | `result.checkoutId` |
31
+ | **Logged-in** | Server | `createCheckout({ cartId })` | `checkout.id` |
32
+
33
+ ### Rule 2: Complete Checkout & Clear Cart After Payment!
34
+
35
+ ```typescript
36
+ // On /checkout/success page - MUST DO THIS!
37
+ export default function CheckoutSuccessPage() {
38
+ const checkoutId = new URLSearchParams(window.location.search).get('checkout_id');
39
+
40
+ useEffect(() => {
41
+ if (checkoutId) {
42
+ // ⚠️ CRITICAL: This sends the order to the server AND clears the cart!
43
+ // handlePaymentSuccess() only clears the local cart - it does NOT create the order!
44
+ client.completeGuestCheckout(checkoutId);
45
+ }
46
+ }, []);
47
+
48
+ return <div>Thank you for your order!</div>;
49
+ }
50
+ ```
51
+
52
+ > **WARNING:** Do NOT use `handlePaymentSuccess()` to complete an order. It only clears
53
+ > the local cart (localStorage) and does NOT communicate with the server.
54
+ > Always use `completeGuestCheckout()` after payment succeeds.
55
+
56
+ ### Rule 3: Never Hardcode Products!
57
+
58
+ ```typescript
59
+ // ❌ FORBIDDEN - Store will show fake data!
60
+ const products = [{ id: '1', name: 'T-Shirt', price: 29.99 }];
61
+
62
+ // ✅ CORRECT - Fetch from API
63
+ const { data: products } = await client.getProducts();
64
+ ```
65
+
66
+ ---
67
+
68
+ ## Quick Setup
69
+
70
+ ```bash
71
+ npm install brainerce
72
+ ```
73
+
74
+ ```typescript
75
+ // lib/brainerce.ts
76
+ import { BrainerceClient } from 'brainerce';
77
+
78
+ export const client = new BrainerceClient({
79
+ connectionId: '{connection_id}',
80
+ baseUrl: '{api_url}',
81
+ });
82
+
83
+ // Restore customer session on page load
84
+ export function initBrainerce() {
85
+ if (typeof window === 'undefined') return;
86
+ const token = localStorage.getItem('customerToken');
87
+ if (token) client.setCustomerToken(token);
88
+ }
89
+
90
+ // Save/clear customer token
91
+ export function setCustomerToken(token: string | null) {
92
+ if (token) {
93
+ localStorage.setItem('customerToken', token);
94
+ client.setCustomerToken(token);
95
+ } else {
96
+ localStorage.removeItem('customerToken');
97
+ client.clearCustomerToken();
98
+ }
99
+ }
100
+ ```
101
+
102
+ ---
103
+
104
+ ## Cart (Works for Both Guest & Logged-in)
105
+
106
+ ```typescript
107
+ // Get or create cart - handles both guest (localStorage) and logged-in (server) automatically
108
+ const cart = await client.smartGetCart();
109
+
110
+ // Add to cart - ALWAYS pass name, price, image for guest cart display!
111
+ await client.smartAddToCart({
112
+ productId: product.id,
113
+ variantId: selectedVariant?.id,
114
+ quantity: 1,
115
+ // IMPORTANT: Pass product info for guest cart display
116
+ name: selectedVariant?.name ? `${product.name} - ${selectedVariant.name}` : product.name,
117
+ price: getVariantPrice(selectedVariant, product.basePrice),
118
+ image: selectedVariant?.image
119
+ ? typeof selectedVariant.image === 'string'
120
+ ? selectedVariant.image
121
+ : selectedVariant.image.url
122
+ : product.images?.[0]?.url,
123
+ });
124
+
125
+ // Update quantity (by productId, not itemId!)
126
+ await client.smartUpdateCartItem('prod_xxx', 2); // productId, quantity
127
+ await client.smartUpdateCartItem('prod_xxx', 3, 'var_xxx'); // with variant
128
+
129
+ // Remove item (by productId, not itemId!)
130
+ await client.smartRemoveFromCart('prod_xxx');
131
+ await client.smartRemoveFromCart('prod_xxx', 'var_xxx'); // with variant
132
+
133
+ // Get cart totals (cart doesn't have .total field!)
134
+ import { getCartTotals } from 'brainerce';
135
+ const totals = getCartTotals(cart);
136
+ // { subtotal: 59.98, discount: 10, shipping: 0, total: 49.98 }
137
+
138
+ // All smart* methods return a server Cart (even for guests via session carts)
139
+ // Cart has: id, itemCount, subtotal, discountAmount, items, couponCode
140
+ ```
141
+
142
+ ### 🏷️ Coupon Code (Add to Cart Page!)
143
+
144
+ ```typescript
145
+ // Apply coupon to cart
146
+ const cart = await client.smartGetCart();
147
+ const updatedCart = await client.applyCoupon(cart.id, 'SAVE20');
148
+ console.log(updatedCart.discountAmount); // "10.00" (string)
149
+ console.log(updatedCart.couponCode); // "SAVE20"
150
+
151
+ // Remove coupon
152
+ const updatedCart = await client.removeCoupon(cartId);
153
+
154
+ // Calculate totals including discount
155
+ import { getCartTotals } from 'brainerce';
156
+ const totals = getCartTotals(cart); // { subtotal, discount, shipping, total }
157
+ ```
158
+
159
+ **Cart page coupon UI:**
160
+
161
+ ```typescript
162
+ // State
163
+ const [couponCode, setCouponCode] = useState('');
164
+ const [couponError, setCouponError] = useState('');
165
+ const [isApplying, setIsApplying] = useState(false);
166
+
167
+ // Apply handler
168
+ async function handleApplyCoupon() {
169
+ if (!couponCode.trim() || !('id' in cart)) return;
170
+ setIsApplying(true);
171
+ setCouponError('');
172
+ try {
173
+ const updatedCart = await client.applyCoupon(cart.id, couponCode.trim());
174
+ setCart(updatedCart);
175
+ setCouponCode('');
176
+ } catch (err: any) {
177
+ setCouponError(err.message || 'Invalid coupon code');
178
+ } finally {
179
+ setIsApplying(false);
180
+ }
181
+ }
182
+
183
+ // Remove handler
184
+ async function handleRemoveCoupon() {
185
+ if (!('id' in cart)) return;
186
+ const updatedCart = await client.removeCoupon(cart.id);
187
+ setCart(updatedCart);
188
+ }
189
+
190
+ // UI - place in cart order summary
191
+ {('id' in cart) && (
192
+ <div>
193
+ {cart.couponCode ? (
194
+ <div className="flex items-center justify-between bg-green-50 p-2 rounded">
195
+ <span className="text-green-700 text-sm">🏷️ {cart.couponCode}</span>
196
+ <button onClick={handleRemoveCoupon} className="text-red-500 text-sm">✕</button>
197
+ </div>
198
+ ) : (
199
+ <div className="flex gap-2">
200
+ <input value={couponCode} onChange={(e) => setCouponCode(e.target.value)}
201
+ placeholder="Coupon code" className="flex-1 border rounded px-3 py-2 text-sm" />
202
+ <button onClick={handleApplyCoupon} disabled={isApplying}
203
+ className="px-4 py-2 bg-gray-800 text-white rounded text-sm">
204
+ {isApplying ? '...' : 'Apply'}
205
+ </button>
206
+ </div>
207
+ )}
208
+ {couponError && <p className="text-red-500 text-xs mt-1">{couponError}</p>}
209
+ </div>
210
+ )}
211
+
212
+ // Order summary - show discount line
213
+ {('id' in cart) && parseFloat(cart.discountAmount) > 0 && (
214
+ <div className="text-green-600">Discount: -{formatPrice(cart.discountAmount)}</div>
215
+ )}
216
+ ```
217
+
218
+ **Checkout order summary - coupon carries over from cart:**
219
+
220
+ ```typescript
221
+ // Checkout already includes coupon from cart
222
+ <div>Subtotal: {formatPrice(checkout.subtotal)}</div>
223
+ {parseFloat(checkout.discountAmount) > 0 && (
224
+ <div className="text-green-600">
225
+ Discount ({checkout.couponCode}): -{formatPrice(checkout.discountAmount)}
226
+ </div>
227
+ )}
228
+ <div>Shipping: {formatPrice(selectedRate?.price || '0')}</div>
229
+ <div className="font-bold">Total: {formatPrice(checkout.total)}</div>
230
+ ```
231
+
232
+ ---
233
+
234
+ ## 🛒 Partial Checkout (AliExpress Style) - REQUIRED!
235
+
236
+ Cart page MUST have checkboxes so users can select which items to buy:
237
+
238
+ ```typescript
239
+ // Cart page - track selected items
240
+ const [selectedIndices, setSelectedIndices] = useState<number[]>(
241
+ cart.items.map((_, i) => i) // All selected by default
242
+ );
243
+
244
+ const toggleItem = (index: number) => {
245
+ setSelectedIndices(prev =>
246
+ prev.includes(index)
247
+ ? prev.filter(i => i !== index)
248
+ : [...prev, index]
249
+ );
250
+ };
251
+
252
+ const toggleAll = () => {
253
+ if (selectedIndices.length === cart.items.length) {
254
+ setSelectedIndices([]); // Deselect all
255
+ } else {
256
+ setSelectedIndices(cart.items.map((_, i) => i)); // Select all
257
+ }
258
+ };
259
+
260
+ // In your cart UI:
261
+ <div>
262
+ <label>
263
+ <input
264
+ type="checkbox"
265
+ checked={selectedIndices.length === cart.items.length}
266
+ onChange={toggleAll}
267
+ />
268
+ Select All
269
+ </label>
270
+ </div>
271
+
272
+ {cart.items.map((item, index) => (
273
+ <div key={index}>
274
+ <input
275
+ type="checkbox"
276
+ checked={selectedIndices.includes(index)}
277
+ onChange={() => toggleItem(index)}
278
+ />
279
+ {/* ... item details ... */}
280
+ </div>
281
+ ))}
282
+
283
+ // On checkout button - pass selected items!
284
+ const handleCheckout = async () => {
285
+ if (selectedIndices.length === 0) {
286
+ alert('Please select items to checkout');
287
+ return;
288
+ }
289
+
290
+ const result = await client.startGuestCheckout({ selectedIndices });
291
+ // Only selected items go to checkout, others stay in cart!
292
+ };
293
+ ```
294
+
295
+ **Why this matters:**
296
+
297
+ - Users can buy some items now, leave others for later
298
+ - After payment, `completeGuestCheckout()` sends the order and only removes purchased items
299
+ - Remaining items stay in cart for future purchase
300
+
301
+ **⚠️ Order Summary on Checkout Page - Use checkout.lineItems!**
302
+
303
+ ```typescript
304
+ // ❌ WRONG - Shows ALL cart items (even unselected ones!)
305
+ <div className="order-summary">
306
+ {cart.items.map(item => (
307
+ <div>{item.product.name} - ${item.price}</div>
308
+ ))}
309
+ </div>
310
+
311
+ // ✅ CORRECT - Shows only items being purchased in this checkout
312
+ <div className="order-summary">
313
+ {checkout.lineItems.map(item => (
314
+ <div>{item.product.name} - ${item.price}</div>
315
+ ))}
316
+ </div>
317
+ ```
318
+
319
+ The `checkout` object's `lineItems` array contains ONLY the items selected for this checkout!
320
+
321
+ ---
322
+
323
+ ## Shipping Destinations (Country/Region Dropdowns)
324
+
325
+ Before showing a checkout form, fetch where the store ships to and render `<select>` dropdowns instead of free-text inputs:
326
+
327
+ ```typescript
328
+ import type { ShippingDestinations } from 'brainerce';
329
+
330
+ // Fetch on page load (no checkout needed)
331
+ const destinations: ShippingDestinations = await client.getShippingDestinations();
332
+ // {
333
+ // worldwide: boolean, // true if store ships everywhere
334
+ // countries: [{ code: 'US', name: 'United States' }, ...],
335
+ // regions: { 'US': [{ code: 'CA', name: 'California' }, ...] }
336
+ // }
337
+
338
+ // Country <select>
339
+ <select value={country} onChange={(e) => setCountry(e.target.value)}>
340
+ <option value="">Select country</option>
341
+ {destinations.countries.map((c) => (
342
+ <option key={c.code} value={c.code}>{c.name}</option>
343
+ ))}
344
+ </select>
345
+
346
+ // Region <select> only show when regions exist for selected country
347
+ {destinations.regions[country]?.length > 0 ? (
348
+ <select value={region} onChange={(e) => setRegion(e.target.value)}>
349
+ <option value="">Select region</option>
350
+ {destinations.regions[country].map((r) => (
351
+ <option key={r.code} value={r.code}>{r.name}</option>
352
+ ))}
353
+ </select>
354
+ ) : (
355
+ <input type="text" value={region} onChange={(e) => setRegion(e.target.value)} />
356
+ )}
357
+ ```
358
+
359
+ > **Note:** `regions` is an object keyed by country code. If a country has no region restrictions, it won't appear in `regions` — use a free-text input as fallback.
360
+
361
+ ---
362
+
363
+ ## Complete Checkout Flow
364
+
365
+ ### Step 1: Start Checkout (Different for Guest vs Logged-in!)
366
+
367
+ ```typescript
368
+ async function startCheckout() {
369
+ const cart = await client.smartGetCart();
370
+
371
+ if (cart.items.length === 0) {
372
+ alert('Cart is empty');
373
+ return;
374
+ }
375
+
376
+ let checkoutId: string;
377
+
378
+ if (client.isCustomerLoggedIn()) {
379
+ // Logged-in: create checkout from server cart
380
+ const checkout = await client.createCheckout({ cartId: cart.id });
381
+ checkoutId = checkout.id;
382
+ } else {
383
+ // Guest: use startGuestCheckout (syncs local cart to server)
384
+ const result = await client.startGuestCheckout();
385
+ if (!result.tracked || !result.checkoutId) {
386
+ throw new Error('Failed to create checkout');
387
+ }
388
+ checkoutId = result.checkoutId;
389
+ }
390
+
391
+ // Save for payment page
392
+ localStorage.setItem('checkoutId', checkoutId);
393
+
394
+ // Navigate to checkout
395
+ window.location.href = '/checkout';
396
+ }
397
+ ```
398
+
399
+ ### Step 2: Shipping Address
400
+
401
+ ```typescript
402
+ const checkoutId = localStorage.getItem('checkoutId')!;
403
+
404
+ // Set shipping address (email is required!)
405
+ const { checkout, rates } = await client.setShippingAddress(checkoutId, {
406
+ email: 'customer@example.com',
407
+ firstName: 'John',
408
+ lastName: 'Doe',
409
+ line1: '123 Main St',
410
+ city: 'New York',
411
+ region: 'NY', // ⚠️ Use 'region', NOT 'state'!
412
+ postalCode: '10001',
413
+ country: 'US',
414
+ });
415
+
416
+ // Show available shipping rates
417
+ rates.forEach((rate) => {
418
+ console.log(`${rate.name}: $${rate.price}`);
419
+ });
420
+ ```
421
+
422
+ ### Step 3: Select Shipping Method
423
+
424
+ ```typescript
425
+ await client.selectShippingMethod(checkoutId, selectedRateId);
426
+ ```
427
+
428
+ ### Step 4: Payment (Multi-Provider)
429
+
430
+ ```typescript
431
+ // 1. Check if payment is configured
432
+ const { hasPayments, providers } = await client.getPaymentProviders();
433
+ if (!hasPayments) {
434
+ return <div>Payment not configured for this store</div>;
435
+ }
436
+
437
+ // 2. Create payment intent — returns provider type!
438
+ const intent = await client.createPaymentIntent(checkoutId, {
439
+ successUrl: `${window.location.origin}/checkout/success?checkout_id=${checkoutId}`,
440
+ cancelUrl: `${window.location.origin}/checkout?error=cancelled`,
441
+ });
442
+
443
+ // 3. Branch by provider
444
+ if (intent.provider === 'grow') {
445
+ // Grow: clientSecret is a payment URL — show in iframe
446
+ // <iframe src={intent.clientSecret} style={{ width: '100%', minHeight: '600px', border: 'none' }} allow="payment" />
447
+ // Supports credit cards, Bit, Apple Pay, Google Pay, bank transfers
448
+ // Add fallback: <a href={intent.clientSecret} target="_blank">Open payment in new tab</a>
449
+ // Order created automatically via webhook!
450
+ } else {
451
+ // Stripe: install @stripe/stripe-js @stripe/react-stripe-js
452
+ import { loadStripe } from '@stripe/stripe-js';
453
+ const stripeProvider = providers.find(p => p.provider === 'stripe');
454
+ const stripe = await loadStripe(stripeProvider.publicKey, {
455
+ stripeAccount: stripeProvider.stripeAccountId,
456
+ });
457
+
458
+ // Confirm payment (in your payment form)
459
+ const { error } = await stripe.confirmPayment({
460
+ elements,
461
+ confirmParams: {
462
+ return_url: `${window.location.origin}/checkout/success?checkout_id=${checkoutId}`,
463
+ },
464
+ });
465
+
466
+ if (error) {
467
+ setError(error.message);
468
+ }
469
+ // If no error, Stripe redirects to success page
470
+ }
471
+ ```
472
+
473
+ ### Step 5: Success Page (Complete Order & Clear Cart!)
474
+
475
+ ```typescript
476
+ // /checkout/success/page.tsx
477
+ 'use client';
478
+ import { useEffect, useState } from 'react';
479
+ import { client } from '@/lib/brainerce';
480
+
481
+ export default function CheckoutSuccessPage() {
482
+ const [orderNumber, setOrderNumber] = useState<string>();
483
+ const [loading, setLoading] = useState(true);
484
+
485
+ useEffect(() => {
486
+ // Break out of iframe if redirected here from Grow payment page
487
+ if (window.top !== window.self) {
488
+ window.top!.location.href = window.location.href;
489
+ return;
490
+ }
491
+
492
+ const checkoutId = new URLSearchParams(window.location.search).get('checkout_id');
493
+
494
+ if (checkoutId) {
495
+ // ⚠️ CRITICAL: Complete the order on the server AND clear the cart!
496
+ // Do NOT use handlePaymentSuccess() - it only clears localStorage!
497
+ client.completeGuestCheckout(checkoutId).then(result => {
498
+ setOrderNumber(result.orderNumber);
499
+ setLoading(false);
500
+ }).catch(() => {
501
+ // Order may already be completed (e.g., page refresh) - check status
502
+ client.getPaymentStatus(checkoutId).then(status => {
503
+ if (status.orderNumber) {
504
+ setOrderNumber(status.orderNumber);
505
+ }
506
+ setLoading(false);
507
+ });
508
+ });
509
+ }
510
+ }, []);
511
+
512
+ return (
513
+ <div className="text-center py-12">
514
+ <h1 className="text-2xl font-bold text-green-600">Thank you for your order!</h1>
515
+ {loading && <p className="mt-2">Processing your order...</p>}
516
+ {orderNumber && <p className="mt-2">Order #{orderNumber}</p>}
517
+ <p className="mt-4">A confirmation email will be sent shortly.</p>
518
+ </div>
519
+ );
520
+ }
521
+ ```
522
+
523
+ ---
524
+
525
+ ## Partial Checkout (AliExpress Style)
526
+
527
+ Allow customers to buy only some items from their cart:
528
+
529
+ ```typescript
530
+ // Start checkout with only selected items (by index)
531
+ const result = await client.startGuestCheckout({
532
+ selectedIndices: [0, 2], // Buy items at index 0 and 2 only
533
+ });
534
+
535
+ // After payment, completeGuestCheckout() sends the order AND removes only those items!
536
+ // Other items stay in cart.
537
+ ```
538
+
539
+ ---
540
+
541
+ ## Products API
542
+
543
+ ```typescript
544
+ // List products with pagination
545
+ const { data: products, meta } = await client.getProducts({
546
+ page: 1,
547
+ limit: 20,
548
+ search: 'blue shirt', // Searches name, description, SKU, categories, tags
549
+ });
550
+ // meta = { page: 1, limit: 20, total: 150, totalPages: 8 }
551
+
552
+ // Get single product by slug (for product detail page)
553
+ const product = await client.getProductBySlug('blue-cotton-shirt');
554
+
555
+ // Search suggestions (for autocomplete)
556
+ const suggestions = await client.getSearchSuggestions('blue', 5);
557
+ // { products: [...], categories: [...] }
558
+ ```
559
+
560
+ ---
561
+
562
+ ## Product Custom Fields (Metafields)
563
+
564
+ Products may have custom fields defined by the store owner (e.g., "Material", "Care Instructions", "Warranty").
565
+
566
+ **Important:** Each metafield has a `type` field. When rendering, you **must** check `field.type` and render accordingly:
567
+
568
+ | Type | Rendering |
569
+ | ---------------------------------- | ------------------------------------------------------- |
570
+ | `IMAGE` | `<img>` thumbnail (value is URL) |
571
+ | `GALLERY` | Row of `<img>` thumbnails (value is JSON array of URLs) |
572
+ | `URL` | `<a>` clickable link |
573
+ | `COLOR` | Color swatch + hex value |
574
+ | `BOOLEAN` | "Yes" / "No" |
575
+ | `DATE` | `new Date(value).toLocaleDateString()` |
576
+ | `DATETIME` | `new Date(value).toLocaleString()` |
577
+ | `TEXT`, `TEXTAREA`, `NUMBER`, etc. | Plain text |
578
+
579
+ ```typescript
580
+ import { getProductMetafield, getProductMetafieldValue } from 'brainerce';
581
+ import type { ProductMetafield } from 'brainerce';
582
+
583
+ // Access metafields on a product
584
+ const product = await client.getProductBySlug('blue-shirt');
585
+
586
+ // ⚠️ MUST render based on type! Don't just show field.value as text for all types.
587
+ function MetafieldValue({ field }: { field: ProductMetafield }) {
588
+ switch (field.type) {
589
+ case 'IMAGE':
590
+ return field.value ? <img src={field.value} alt={field.definitionName} className="h-16 w-16 rounded object-cover" /> : <>-</>;
591
+ case 'GALLERY': {
592
+ let urls: string[] = [];
593
+ try { urls = JSON.parse(field.value); } catch { urls = field.value ? [field.value] : []; }
594
+ return <div className="flex gap-2">{urls.map((url, i) => <img key={i} src={url} className="h-16 w-16 rounded object-cover" />)}</div>;
595
+ }
596
+ case 'URL':
597
+ return field.value ? <a href={field.value} target="_blank" rel="noopener noreferrer">{field.value}</a> : <>-</>;
598
+ case 'COLOR':
599
+ return <span><span className="inline-block h-4 w-4 rounded-full border" style={{ backgroundColor: field.value }} /> {field.value}</span>;
600
+ case 'BOOLEAN':
601
+ return <>{field.value === 'true' ? 'Yes' : 'No'}</>;
602
+ case 'DATE':
603
+ return <>{field.value ? new Date(field.value).toLocaleDateString() : '-'}</>;
604
+ case 'DATETIME':
605
+ return <>{field.value ? new Date(field.value).toLocaleString() : '-'}</>;
606
+ default:
607
+ return <>{field.value || '-'}</>;
608
+ }
609
+ }
610
+
611
+ // Display in spec table
612
+ {product.metafields?.map(mf => (
613
+ <tr key={mf.id}>
614
+ <td>{mf.definitionName}</td>
615
+ <td><MetafieldValue field={mf} /></td>
616
+ </tr>
617
+ ))}
618
+
619
+ // Get specific field by key
620
+ const material = getProductMetafieldValue(product, 'material');
621
+ const careInstructions = getProductMetafield(product, 'care_instructions');
622
+
623
+ // Get available metafield definitions (schema)
624
+ const { definitions } = await client.getPublicMetafieldDefinitions();
625
+ // Use definitions to build dynamic UI (filters, forms, etc.)
626
+ ```
627
+
628
+ > **Tip:** `metafields` may be empty if the store hasn't defined custom fields. Always use optional chaining.
629
+
630
+ ---
631
+
632
+ ## Customer Authentication
633
+
634
+ ```typescript
635
+ // Register
636
+ const auth = await client.registerCustomer({
637
+ email: 'john@example.com',
638
+ password: 'securepass123',
639
+ firstName: 'John',
640
+ lastName: 'Doe',
641
+ });
642
+
643
+ if (auth.requiresVerification) {
644
+ // Store token for verification step
645
+ localStorage.setItem('verificationToken', auth.token);
646
+ localStorage.setItem('verificationEmail', 'john@example.com');
647
+ window.location.href = '/verify-email';
648
+ } else {
649
+ client.setCustomerToken(auth.token);
650
+ localStorage.setItem('customerToken', auth.token);
651
+ }
652
+
653
+ // Login
654
+ const auth = await client.loginCustomer('john@example.com', 'password');
655
+
656
+ if (auth.requiresVerification) {
657
+ localStorage.setItem('verificationToken', auth.token);
658
+ localStorage.setItem('verificationEmail', 'john@example.com');
659
+ window.location.href = '/verify-email';
660
+ } else {
661
+ client.setCustomerToken(auth.token);
662
+ localStorage.setItem('customerToken', auth.token);
663
+ }
664
+
665
+ // Verify email (on /verify-email page)
666
+ const result = await client.verifyEmail(code, token);
667
+ if (result.verified) {
668
+ client.setCustomerToken(token);
669
+ localStorage.setItem('customerToken', token);
670
+ localStorage.removeItem('verificationToken');
671
+ localStorage.removeItem('verificationEmail');
672
+ window.location.href = '/account';
673
+ }
674
+
675
+ // Resend verification code
676
+ await client.resendVerificationEmail(token);
677
+
678
+ // Logout
679
+ client.setCustomerToken(null);
680
+ localStorage.removeItem('customerToken');
681
+
682
+ // Get profile (requires token)
683
+ const profile = await client.getMyProfile();
684
+
685
+ // Get order history
686
+ const { data: orders, meta } = await client.getMyOrders({ page: 1, limit: 10 });
687
+ ```
688
+
689
+ ---
690
+
691
+ ## OAuth / Social Login
692
+
693
+ ```typescript
694
+ // Get available providers for this store
695
+ const { providers } = await client.getAvailableOAuthProviders();
696
+ // providers = ['GOOGLE', 'FACEBOOK', 'GITHUB']
697
+
698
+ // Redirect to OAuth provider
699
+ const { authorizationUrl } = await client.getOAuthAuthorizeUrl('GOOGLE', {
700
+ redirectUrl: `${window.location.origin}/auth/callback`,
701
+ });
702
+ window.location.href = authorizationUrl;
703
+
704
+ // Handle callback (on /auth/callback page — backend redirects here with params)
705
+ const params = new URLSearchParams(window.location.search);
706
+ if (params.get('oauth_success') === 'true') {
707
+ const token = params.get('token');
708
+ client.setCustomerToken(token!);
709
+ // Also available: customer_id, customer_email, is_new
710
+ } else if (params.get('oauth_error')) {
711
+ // Show error to user
712
+ }
713
+ ```
714
+
715
+ ---
716
+
717
+ ## Required Pages Checklist
718
+
719
+ - [ ] **Home** (`/`) - Featured products grid
720
+ - [ ] **Products** (`/products`) - Product list with infinite scroll
721
+ - [ ] **Product Detail** (`/products/[slug]`) - Use `getProductBySlug(slug)`
722
+ - [ ] **Cart** (`/cart`) - Show items, quantities, totals, **coupon code input**, discount display
723
+ - [ ] **Checkout** (`/checkout`) - Address → Shipping → Payment. **Show discount in order summary!**
724
+ - [ ] **Success** (`/checkout/success`) - **Must call `completeGuestCheckout()`!**
725
+ - [ ] **Login** (`/login`) - Email/password + social buttons, handle `requiresVerification`
726
+ - [ ] **Register** (`/register`) - Registration form, handle `requiresVerification`
727
+ - [ ] **Verify Email** (`/verify-email`) - 6-digit code input + resend button. **ALWAYS create this page** even if verification is currently disabled — the store owner can enable it at any time
728
+ - [ ] **OAuth Callback** (`/auth/callback`) - Handle OAuth redirect with token from URL params
729
+ - [ ] **Account** (`/account`) - Profile + order history
730
+ - [ ] **Header** - Logo, nav, cart icon with count, search
731
+
732
+ ### ALWAYS Build These (Even If Currently Disabled)
733
+
734
+ Some features may not be configured yet, but the store owner can enable them at any time. **Always create the UI** — SDK methods return empty/null when not configured:
735
+
736
+ - **Email Verification** → `/verify-email` page. `requiresVerification` is checked in login/register flows.
737
+ - **OAuth Buttons** → Social login buttons on Login & Register + `/auth/callback` page. `getAvailableOAuthProviders()` returns `[]` when none configured — buttons just don't render.
738
+ - **Discount Banners** → `getDiscountBanners()` returns `[]` when no rules — component renders nothing.
739
+ - **Product Discount Badges** → `getProductDiscountBadge(id)` returns `null` — renders nothing.
740
+ - **Cart Nudges** → `cart.nudges` is `[]` — renders nothing.
741
+ - **Coupon Input** → Always show in cart. Works even with no coupons configured.
742
+
743
+ ---
744
+
745
+ ## Common Type Gotchas
746
+
747
+ ```typescript
748
+ // ❌ WRONG // ✅ CORRECT
749
+ address.state address.region
750
+ cart.total getCartTotals(cart).total
751
+ cart.discount cart.discountAmount
752
+ item.name (in cart) item.product.name
753
+ response.url (OAuth) response.authorizationUrl
754
+ providers.forEach (OAuth) response.providers.forEach
755
+ status === 'completed' status === 'succeeded'
756
+ product.metafields.name product.metafields[0].definitionName
757
+ product.metafields.key product.metafields[0].definitionKey
758
+ orderItem.unitPrice orderItem.price (OrderItem is FLAT, not nested!)
759
+ cartItem.price cartItem.unitPrice (Cart/Checkout items use unitPrice)
760
+ waitResult.orderNumber waitResult.status.orderNumber (nested in PaymentStatus)
761
+ variant.attributes.map(...) Object.entries(variant.attributes || {}) (it's an object!)
762
+ categorySuggestion.slug // ❌ doesn't exist! Only: id, name, productCount
763
+ order.status === 'COMPLETED' order.status === 'delivered' (OrderStatus is lowercase!)
764
+ getCartTotals(cart) // ✅ Works — all carts are server carts now
765
+ result.checkoutId (guest checkout) // ⚠️ Check result.tracked first! It's a union type
766
+ ```
767
+
768
+ **Key distinctions:**
769
+
770
+ - **OrderItem** (from orders): Flat structure — `item.price`, `item.name`, `item.image`
771
+ - **CartItem / CheckoutLineItem**: Nested structure — `item.unitPrice`, `item.product.name`, `item.product.images`
772
+ - **`getCartTotals()`** works on all carts — guests now use server-side session carts with full `subtotal`/`discountAmount` fields.
773
+ - **`GuestCheckoutStartResponse`** is a union type — always check `result.tracked` before accessing `result.checkoutId`
774
+ - **`WaitForOrderResult`** has `result.status.orderNumber`, NOT `result.orderNumber`. But `completeGuestCheckout()` returns `GuestOrderResponse` which DOES have `result.orderNumber` directly.
775
+ - **Cart state**: Use `useState<Cart | null>(null)` and load with `smartGetCart()` in `useEffect` — all carts are server-side now, no hydration mismatch issues.
776
+
777
+ ---
778
+
779
+ ## Full SDK Documentation
780
+
781
+ For complete API reference and working code examples:
782
+ **https://brainerce.com/docs/sdk**