@thorprovider/create-thor-app 4.0.0 → 4.0.1

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.
Files changed (48) hide show
  1. package/README.md +6 -55
  2. package/dist/index.js +154 -626
  3. package/package.json +1 -1
  4. package/templates/default/.agents/AGENTS.md +27 -0
  5. package/templates/default/.env.example +8 -30
  6. package/templates/default/.eslintrc.json +20 -27
  7. package/templates/default/README.md +52 -123
  8. package/templates/default/ai-validator.json +47 -29
  9. package/templates/default/app/api/revalidate/route.ts +27 -36
  10. package/templates/default/app/backend-unavailable/page.tsx +3 -7
  11. package/templates/default/app/error.tsx +1 -2
  12. package/templates/default/app/global-error.tsx +3 -3
  13. package/templates/default/app/globals.css +1 -71
  14. package/templates/default/app/layout.tsx +16 -38
  15. package/templates/default/app/not-found.tsx +1 -1
  16. package/templates/default/app/page.tsx +10 -119
  17. package/templates/default/components/providers/app-providers.tsx +19 -68
  18. package/templates/default/components/providers/cart-provider.tsx +143 -0
  19. package/templates/default/components/providers/commerce-provider.tsx +33 -0
  20. package/templates/default/components/providers/region-provider.tsx +105 -0
  21. package/templates/default/docs/README.md +46 -37
  22. package/templates/default/docs/commerce-api.md +58 -125
  23. package/templates/default/docs/patterns.md +128 -67
  24. package/templates/default/docs/project-structure.md +58 -50
  25. package/templates/default/docs/rules.md +43 -42
  26. package/templates/default/docs/types.md +105 -1024
  27. package/templates/default/lib/commerce.ts +33 -132
  28. package/templates/default/lib/env.ts +24 -94
  29. package/templates/default/lib/utils.ts +18 -0
  30. package/templates/default/next-env.d.ts +1 -1
  31. package/templates/default/next.config.ts +7 -0
  32. package/templates/default/package.json +2 -8
  33. package/templates/default/registry.json +6 -0
  34. package/templates/default/styles/tokens.css +81 -0
  35. package/templates/default/components/providers/navigation-provider.tsx +0 -37
  36. package/templates/default/config/site.config.ts +0 -156
  37. package/templates/default/docs/components.md +0 -282
  38. package/templates/default/docs/dependencies.md +0 -61
  39. package/templates/default/lib/auth-context.tsx +0 -213
  40. package/templates/default/lib/cart-provider.tsx +0 -53
  41. package/templates/default/lib/commerce-provider.tsx +0 -48
  42. package/templates/default/lib/region-detection.ts +0 -73
  43. package/templates/default/lib/region-provider.tsx +0 -53
  44. package/templates/default/lib/regions-config.ts +0 -48
  45. package/templates/default/lib/storefront-config.ts +0 -54
  46. package/templates/default/next.config.mjs +0 -51
  47. package/templates/default/proxy.ts +0 -155
  48. package/templates/default/scripts/generate-regions-config.ts +0 -498
@@ -1,52 +1,61 @@
1
1
  ---
2
- title: "Thor Commerce App — Getting Started"
3
- purpose: "Entry-point documentation for generated Thor Commerce storefronts, explaining capabilities and quick start"
4
- lastReviewed: "2026-04-25"
2
+ title: "Thor Commerce — V0-Native Template"
3
+ purpose: "Entry-point documentation for V0-native Thor Commerce starters"
4
+ lastReviewed: "2026-05-01"
5
5
  ---
6
6
 
7
- # [App Name] — Thor Commerce App
7
+ # Thor Commerce — V0-Native Template
8
8
 
9
- Next.js 16 storefront with headless commerce backend. Pre-configured with `@thorprovider/components` UI library and commerce adapters.
9
+ Next.js 16 storefront scaffold for V0 AI code generation. Two npm deps: `@thorprovider/types` + `@thorprovider/adapters`.
10
10
 
11
- ## How This Works
11
+ ## How It Works
12
12
 
13
- This app was generated by `create:app` and connects to v0.app for feature development:
13
+ V0 generates feature code (pages, components) on top of this frozen infrastructure. The template provides:
14
14
 
15
- | Step | Action |
16
- |------|--------|
17
- | 1. Created | `create:app` generates this repo with `@thorprovider/*` dependencies pre-installed |
18
- | 2. Git push | Repo pushed to GitHub |
19
- | 3. v0.app import | **You (V0) are working here.** This is the app context. |
20
- | 4. Implement | `@thorprovider/components` if component exists; `components/` if it doesn't |
15
+ - Commerce singleton (`lib/commerce.ts`) — all backend access goes through here
16
+ - Type safety via `@thorprovider/types` — Product, Cart, Order, Customer, Money
17
+ - Local providers (`components/providers/`, `lib/`) — V0 can read source code
18
+ - CSS token theming via `globals.css` — dark mode works automatically
21
19
 
22
- ## Capabilities
20
+ ## Docs Index
23
21
 
24
- - ✅ Regional commerce (IP-based region + currency detection)
25
- - ✅ Shopping cart (persistent, backend-synced)
26
- - ✅ Authentication (JWT)
27
- - ✅ Responsive (mobile-first, Tailwind 4)
28
- - ✅ Dark mode + CSS token theming + backend-driven accent color override
29
- - ✅ Webhook ISR revalidation (opt-in via `FRONTEND_WEBHOOK_SECRET`)
22
+ | File | Purpose |
23
+ |------|---------|
24
+ | `types.md` | Domain type shapes (Product, Cart, Order, Money, etc.) |
25
+ | `commerce-api.md` | All `commerce.*` method signatures |
26
+ | `patterns.md` | Code templates for pages, components, cart, auth, styling |
27
+ | `rules.md` | Non-negotiable constraints (read before generating) |
28
+ | `project-structure.md` | Folder map + where to put new files |
30
29
 
31
- ## Quick Start
30
+ ## Quick Import Reference
32
31
 
33
- ```bash
34
- cp .env.example .env.local && yarn install && yarn dev
35
- # → http://localhost:3000
36
- ```
32
+ ```ts
33
+ // Types (everywhere)
34
+ import type { Product, Cart, Money } from '@thorprovider/types';
35
+
36
+ // Commerce data (server components + API routes)
37
+ import { commerce } from '@/lib/commerce';
38
+
39
+ // Cart (client components)
40
+ import { useCart } from '@/components/providers/cart-provider';
37
41
 
38
- ```bash
39
- NEXT_PUBLIC_COMMERCE_API_URL=https://your-backend.com
40
- NODE_AUTH_TOKEN=github-pat-with-read:packages-scope
42
+ // Auth (client components)
43
+ import { useAuth } from '@/lib/auth-context';
44
+
45
+ // Utilities
46
+ import { cn, formatPrice } from '@/lib/utils';
47
+
48
+ // Navigation + images (directly from Next.js)
49
+ import Link from 'next/link';
50
+ import Image from 'next/image';
51
+
52
+ // UI (shadcn/ui — installed per-project)
53
+ import { Button } from '@/components/ui/button';
41
54
  ```
42
55
 
43
- ## Docs Index
56
+ ## NOT Used
44
57
 
45
- | File | When to read |
46
- |------|-------------|
47
- | `project-structure.md` | Where to create files, folder conventions |
48
- | `dependencies.md` | What to import from `@thorprovider/*`, component inventory (55 components) |
49
- | `types.md` | Domain type shapes: Product, Cart, Order, Customer, Address, Money |
50
- | `commerce-api.md` | All `commerce.*` method signatures + circuit breaker usage |
51
- | `patterns.md` | Server/client, styling, backend fetch patterns (with code) |
52
- | `rules.md` | Non-negotiable rules + pre-commit checklist |
58
+ | Package | Why |
59
+ |---------|-----|
60
+ | `@thorprovider/components` | V0 creates UI from shadcn/ui — unique UI per client |
61
+ | `@thorprovider/providers` | Providers are local code — V0 reads source directly |
@@ -1,67 +1,53 @@
1
- # Commerce API
2
-
3
- **lastReviewed**: 2026-04-29
1
+ ---
2
+ title: "Commerce API"
3
+ purpose: "All commerce.* method signatures for the V0-native template"
4
+ lastReviewed: "2026-05-01"
5
+ ---
4
6
 
5
- All backend access goes through `commerce` (from `@/lib/commerce`) + `backendCircuitBreaker` (from `@thorprovider/adapters`).
7
+ # Commerce API
6
8
 
7
- ## Setup (already wired in the app)
9
+ All backend access goes through the `commerce` singleton from `@/lib/commerce`. Retry logic is built into the adapter — never wrap calls manually.
8
10
 
9
11
  ```ts
10
12
  import { commerce } from '@/lib/commerce';
11
- import { backendCircuitBreaker } from '@thorprovider/adapters';
12
- ```
13
-
14
- **Read operations** — always wrap with circuit breaker:
15
- ```ts
16
- const result = await backendCircuitBreaker.execute(() => commerce.method(...), fallback);
17
- ```
18
-
19
- **Mutations** — call directly (adapter retries internally):
20
- ```ts
21
- const result = await commerce.method(...);
22
- ```
23
-
24
- **Admin methods** require `COMMERCE_ADMIN_API_KEY` set in `.env`:
25
- ```bash
26
- COMMERCE_ADMIN_API_KEY=your_admin_api_key
27
13
  ```
28
- Without this key, admin config is not initialized and admin methods will not be available.
29
14
 
30
15
  ---
31
16
 
32
- ## Storefront Methods
33
-
34
- ### Products
17
+ ## Products
35
18
 
36
19
  ```ts
37
- // Get single product by handle (slug)
38
- commerce.getProduct(handle: string, options?: { regionId?: string }): Promise<Product | undefined>
20
+ // Get single product by handle (URL slug)
21
+ commerce.getProduct(handle: string): Promise<Product | undefined>
39
22
 
40
23
  // List products (search, sort, paginate)
41
24
  commerce.getProducts(options?: {
42
25
  query?: string;
43
- sortKey?: string; // e.g. 'title', 'price', 'created_at'
26
+ sortKey?: string; // 'title', 'price', 'created_at'
44
27
  reverse?: boolean;
45
28
  first?: number; // limit (default 20)
46
29
  skip?: number; // offset
47
- regionId?: string;
48
30
  }): Promise<Product[]>
49
31
 
50
32
  // Recommendations for a product
51
33
  commerce.getProductRecommendations(productId: string): Promise<Product[]>
52
34
  ```
53
35
 
54
- ### Collections
36
+ ---
37
+
38
+ ## Collections
55
39
 
56
40
  ```ts
57
41
  commerce.getCollection(handle: string): Promise<Collection | undefined>
58
42
  commerce.getCollections(options?: { limit?: number; query?: string }): Promise<Collection[]>
59
43
  commerce.getCollectionProducts(handle: string, options?: {
60
- sortKey?: string; reverse?: boolean; first?: number; after?: string;
44
+ sortKey?: string; reverse?: boolean; first?: number;
61
45
  }): Promise<Product[]>
62
46
  ```
63
47
 
64
- ### Categories
48
+ ---
49
+
50
+ ## Categories
65
51
 
66
52
  ```ts
67
53
  commerce.getCategory(idOrHandle: string): Promise<ProductCategory | undefined>
@@ -74,16 +60,18 @@ commerce.getCategoryProducts(handle: string, options?: {
74
60
  }): Promise<Product[]>
75
61
  ```
76
62
 
77
- ### Cart
63
+ ---
64
+
65
+ ## Cart
78
66
 
79
67
  ```ts
80
68
  // Create a new cart
81
- commerce.createCart(options?: { regionId?: string }): Promise<Cart>
69
+ commerce.createCart(): Promise<Cart>
82
70
 
83
71
  // Get existing cart
84
72
  commerce.getCart(cartId: string): Promise<Cart | undefined>
85
73
 
86
- // Add items (mutation — no circuit breaker)
74
+ // Add items
87
75
  commerce.addToCart(cartId: string, lines: Array<{
88
76
  merchandiseId: string; // variant ID
89
77
  quantity: number;
@@ -100,42 +88,29 @@ commerce.updateCart(cartId: string, lines: Array<{
100
88
  }>): Promise<Cart>
101
89
  ```
102
90
 
103
- ### Checkout
91
+ ---
92
+
93
+ ## Checkout
104
94
 
105
95
  ```ts
106
- // Complete checkout → creates order
107
96
  commerce.completeCheckout(cartId: string): Promise<Order>
108
-
109
- // Shipping
110
97
  commerce.getShippingMethods(cartId: string): Promise<ShippingMethod[]>
111
98
  commerce.addShippingMethod(cartId: string, methodId: string): Promise<Cart>
112
-
113
- // Payment
114
99
  commerce.getPaymentMethods(options: {
115
100
  regionId?: string; cartId?: string; currencyCode?: string;
116
101
  }): Promise<PaymentMethod[]>
117
102
  commerce.initiatePaymentSession(cartId: string, providerId: string): Promise<void>
118
-
119
- // Discounts
120
103
  commerce.applyDiscountCode(cartId: string, code: string): Promise<Cart>
121
104
  commerce.removeDiscountCode(cartId: string, code: string): Promise<Cart>
122
-
123
- // Address
124
- commerce.updateBillingAddress?(cartId: string, address: Address): Promise<Cart>
125
-
126
- // Region data
127
- commerce.getRegions?(): Promise<Array<{
128
- id: string; name: string; currency_code: string;
129
- countries?: Array<{ id: string; iso_2: string; name: string }>;
130
- }>>
131
- commerce.getRegionCountries(regionId: string): Promise<Country[]>
132
105
  ```
133
106
 
134
- ### Auth (via `commerce.auth`)
107
+ ---
108
+
109
+ ## Auth (via `commerce.auth`)
135
110
 
136
111
  ```ts
137
112
  commerce.auth.login({ email, password }): Promise<AuthResponse>
138
- commerce.auth.register({ email, password, first_name, last_name, phone? }): Promise<AuthResponse>
113
+ commerce.auth.register({ email, password, first_name, last_name }): Promise<AuthResponse>
139
114
  commerce.auth.logout(): Promise<void>
140
115
  commerce.auth.getCurrentCustomer(): Promise<Customer | null>
141
116
  commerce.auth.updateCustomer(data: {
@@ -157,95 +132,53 @@ commerce.auth.deleteAddress(addressId: string): Promise<void>
157
132
 
158
133
  ---
159
134
 
160
- ## Admin Methods
135
+ ## Usage Patterns
161
136
 
162
- Admin methods are used in `app/api/admin/` route handlers.
137
+ ### Server Component (data fetch)
163
138
 
164
- ### Orders
139
+ ```tsx
140
+ import { commerce } from '@/lib/commerce';
165
141
 
166
- ```ts
167
- commerce.getAdminOrders(options?: {
168
- search?: string;
169
- status?: string | string[];
170
- limit?: number; // default 20
171
- offset?: number;
172
- order?: string; // sort field
173
- direction?: 'asc' | 'desc';
174
- }): Promise<{ orders: Order[]; count: number }>
175
-
176
- commerce.getAdminOrder?(orderId: string): Promise<Order | undefined>
177
- commerce.cancelOrder(orderId: string): Promise<Order>
178
- commerce.createFulfillment(orderId: string, items?: Array<{ id: string; quantity: number }>): Promise<void>
179
- commerce.createRefund(orderId: string, amount?: number, reason?: string): Promise<void>
142
+ export default async function ProductsPage() {
143
+ const products = await commerce.getProducts({ first: 20 });
144
+ return <ProductGrid products={products} />;
145
+ }
180
146
  ```
181
147
 
182
- ### Products (admin)
148
+ ### API Route
183
149
 
184
150
  ```ts
185
- commerce.getAdminProducts?(options?: {
186
- query?: string; limit?: number; offset?: number;
187
- }): Promise<{ products: AdminProduct[]; count: number }>
151
+ import { commerce } from '@/lib/commerce';
152
+ import { NextResponse } from 'next/server';
188
153
 
189
- commerce.getAdminProduct?(productId: string): Promise<AdminProduct | undefined>
154
+ export async function GET() {
155
+ const products = await commerce.getProducts();
156
+ return NextResponse.json(products);
157
+ }
190
158
  ```
191
159
 
192
- ### Customers (admin)
193
-
194
- ```ts
195
- commerce.getAdminCustomers?(options?: {
196
- search?: string; limit?: number; offset?: number;
197
- }): Promise<{ customers: Customer[]; count: number }>
198
-
199
- commerce.getAdminCustomer?(customerId: string): Promise<Customer | undefined>
200
- commerce.getAdminCustomerAddresses?(customerId: string): Promise<Address[]>
201
- commerce.getCustomerOrders?(customerId: string, limit?: number): Promise<Order[]>
202
- ```
160
+ ### Error Handling
203
161
 
204
- ### Inventory
162
+ The adapter layer handles retries automatically. For UI-level error handling:
205
163
 
206
- ```ts
207
- commerce.getStockLocations(params?: { salesChannelId?: string }): Promise<StockLocation[]>
208
- commerce.checkInventoryLevels(variantId: string, salesChannelId?: string): Promise<InventoryLevel[]>
209
- commerce.validateCartStock(cartId: string): Promise<StockValidation>
210
- commerce.getFulfillmentOptions(cartId: string, salesChannelId: string): Promise<FulfillmentOption[]>
164
+ ```tsx
165
+ try {
166
+ const product = await commerce.getProduct(handle);
167
+ if (!product) notFound();
168
+ } catch (error) {
169
+ // Adapter exhausted retries — backend is truly unreachable
170
+ redirect('/backend-unavailable');
171
+ }
211
172
  ```
212
173
 
213
174
  ---
214
175
 
215
- ## Optional Methods (check before calling)
176
+ ## Optional Methods
216
177
 
217
- Methods marked with `?` may not exist. Always guard:
178
+ Methods that may not exist on all adapters. Always guard:
218
179
 
219
180
  ```ts
220
- // ✅ Check before calling optional methods
221
181
  if (commerce.getAdminOrder) {
222
- const order = await backendCircuitBreaker.execute(
223
- () => commerce.getAdminOrder!(orderId),
224
- null
225
- );
182
+ const order = await commerce.getAdminOrder(orderId);
226
183
  }
227
-
228
- // ❌ Don't call blindly — will throw if not implemented
229
- const order = await commerce.getAdminOrder(orderId); // might be undefined function
230
- ```
231
-
232
- ---
233
-
234
- ## Circuit Breaker Reference
235
-
236
- ```ts
237
- import { backendCircuitBreaker } from '@thorprovider/adapters';
238
-
239
- // Wrap all READ operations:
240
- const products = await backendCircuitBreaker.execute(
241
- () => commerce.getProducts({ first: 20 }),
242
- [] // fallback shown when backend is down
243
- );
244
-
245
- // DO NOT wrap mutations (cart add, checkout, refund, etc.)
246
- // Adapters handle retry internally for mutations
247
184
  ```
248
-
249
- - **Threshold**: 5 consecutive failures → circuit opens
250
- - **Reset**: Auto-resets after 60 seconds
251
- - **Fallback**: Second argument — returned when circuit is OPEN
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  title: "Patterns (Code Templates)"
3
- purpose: "Canonical code templates for common patterns like server pages, client components, and commerce data fetching"
4
- lastReviewed: "2026-04-29"
3
+ purpose: "Canonical code templates for V0-native Thor Commerce starters"
4
+ lastReviewed: "2026-05-01"
5
5
  ---
6
6
 
7
7
  # Patterns (Code Templates)
@@ -10,122 +10,183 @@ lastReviewed: "2026-04-29"
10
10
 
11
11
  ```tsx
12
12
  // app/products/page.tsx
13
- import { backendCircuitBreaker } from '@thorprovider/adapters';
14
13
  import { commerce } from '@/lib/commerce';
14
+ import type { Product } from '@thorprovider/types';
15
+ import { ProductGrid } from '@/components/product-grid';
15
16
 
16
17
  export default async function ProductsPage() {
17
- const products = await backendCircuitBreaker.execute(
18
- () => commerce.getProducts({ first: 20 }),
19
- [] // shown if backend unreachable
20
- );
18
+ const products: Product[] = await commerce.getProducts({ first: 20 });
21
19
  return <ProductGrid products={products} />;
22
20
  }
23
21
  ```
24
22
 
25
- ❌ Never fetch in client with `useEffect` → causes visible loading flash + worse LCP.
23
+ - Server Components fetch data directly — no useEffect, no loading spinners for initial data.
24
+ - Retry logic is built into the adapter — no manual wrapping needed.
26
25
 
27
26
  ---
28
27
 
29
- ## 2. Client Component
28
+ ## 2. Client Component (Product Card)
30
29
 
31
30
  ```tsx
32
31
  // components/product-card.tsx
33
32
  'use client';
34
- import { useNavigation } from '@thorprovider/providers';
35
- import { Button, Card } from '@thorprovider/components';
33
+ import Link from 'next/link';
34
+ import Image from 'next/image';
36
35
  import type { Product } from '@thorprovider/types';
36
+ import { formatPrice } from '@/lib/utils';
37
37
 
38
38
  export function ProductCard({ product }: { product: Product }) {
39
- const { Link, Image } = useNavigation();
40
39
  return (
41
- <Card>
42
- <Link href={`/products/${product.handle}`}>
43
- <Image src={product.featuredImage?.url ?? ''} alt={product.featuredImage?.altText ?? product.title} width={300} height={300} />
44
- <p>{product.title}</p>
45
- </Link>
46
- <Button>Add to cart</Button>
47
- </Card>
40
+ <Link href={`/products/${product.handle}`} className="group">
41
+ <div className="overflow-hidden rounded-lg">
42
+ <Image
43
+ src={product.featuredImage?.url ?? ''}
44
+ alt={product.featuredImage?.altText ?? product.title}
45
+ width={300}
46
+ height={300}
47
+ className="transition-transform group-hover:scale-105"
48
+ />
49
+ </div>
50
+ <h3 className="mt-2 text-sm font-medium text-foreground">{product.title}</h3>
51
+ <p className="text-sm text-muted-foreground">
52
+ {formatPrice(product.priceRange.minVariantPrice)}
53
+ </p>
54
+ </Link>
48
55
  );
49
56
  }
50
57
  ```
51
58
 
52
- ❌ Never `import Link from 'next/link'` inside `components/` — use `useNavigation()`.
59
+ - Use `next/link` and `next/image` directly.
60
+ - Use `product.handle` in URLs (not `product.id`).
61
+ - Use `product.featuredImage?.url` (not `.thumbnail`).
62
+ - Always `formatPrice(money)` — never render `money.amount` directly.
53
63
 
54
64
  ---
55
65
 
56
- ## 3. Styling
66
+ ## 3. Cart Operations
57
67
 
58
68
  ```tsx
59
- // ✅ CSS tokens (dark mode + theming work automatically)
60
- <div style={{ color: 'var(--foreground)', background: 'var(--background)' }} />
61
- <button className="bg-[var(--primary-9)] hover:bg-[var(--primary-8)]" />
69
+ // components/add-to-cart-button.tsx
70
+ 'use client';
71
+ import { useCart } from '@/components/providers/cart-provider';
72
+ import { Button } from '@/components/ui/button';
62
73
 
63
- // ❌ Hardcoded colors (breaks dark mode)
64
- <div style={{ color: '#1a1a1a', background: '#ffffff' }} />
65
- <button className="bg-blue-500 hover:bg-blue-600" />
74
+ export function AddToCartButton({ variantId }: { variantId: string }) {
75
+ const { addItem, isLoading } = useCart();
76
+
77
+ return (
78
+ <Button
79
+ onClick={() => addItem(variantId, 1)}
80
+ disabled={isLoading}
81
+ >
82
+ {isLoading ? 'Adding...' : 'Add to Cart'}
83
+ </Button>
84
+ );
85
+ }
66
86
  ```
67
87
 
68
- **Available tokens:** `--background`, `--foreground`, `--border`, `--primary-9/8`, `--success`, `--warning`, `--error`
88
+ - Import `useCart` from `@/components/providers/cart-provider`.
89
+ - Cart methods: `addItem(variantId, quantity)`, `removeItem(lineItemId)`, `updateQuantity(lineItemId, qty)`, `clearCart()`.
69
90
 
70
91
  ---
71
92
 
72
- ## 4. API Route (GET)
93
+ ## 4. Region/Currency
73
94
 
74
- ```ts
75
- // app/api/products/route.ts
76
- import { backendCircuitBreaker } from '@thorprovider/adapters';
77
- import { commerce } from '@/lib/commerce';
95
+ ```tsx
96
+ // components/currency-selector.tsx
97
+ 'use client';
98
+ import { useRegion } from '@/components/providers/region-provider';
99
+
100
+ export function CurrencySelector() {
101
+ const { region, regions, setRegion, currencyCode } = useRegion();
78
102
 
79
- export async function GET() {
80
- try {
81
- const products = await backendCircuitBreaker.execute(
82
- () => commerce.getProducts(),
83
- []
84
- );
85
- return Response.json(products);
86
- } catch {
87
- return Response.json({ error: 'Service unavailable' }, { status: 503 });
88
- }
103
+ return (
104
+ <select
105
+ value={region?.id ?? ''}
106
+ onChange={(e) => setRegion(e.target.value)}
107
+ >
108
+ {regions.map((r) => (
109
+ <option key={r.id} value={r.id}>{r.name} ({r.currency})</option>
110
+ ))}
111
+ </select>
112
+ );
89
113
  }
90
114
  ```
91
115
 
116
+ - Import `useRegion` from `@/components/providers/region-provider`.
117
+
118
+ ---
119
+
120
+ ## 5. Styling (CSS Tokens)
121
+
122
+ ```tsx
123
+ // CSS tokens (dark mode + theming work automatically)
124
+ <div className="bg-background text-foreground border-border" />
125
+ <button className="bg-primary text-primary-foreground hover:bg-primary/90" />
126
+ <p className="text-muted-foreground" />
127
+
128
+ // Hardcoded colors (breaks dark mode)
129
+ <div style={{ color: '#1a1a1a', background: '#ffffff' }} />
130
+ ```
131
+
132
+ **Available tokens:** `--background`, `--foreground`, `--border`, `--primary`, `--secondary`, `--muted`, `--accent`, `--destructive` (+ `-foreground` variants)
133
+
92
134
  ---
93
135
 
94
- ## 5. Storefront Config (Theme Accent)
136
+ ## 6. Price Display
95
137
 
96
- `lib/storefront-config.ts` is called automatically in `app/layout.tsx` to apply a backend-driven accent color override. You can also read it in any server component:
138
+ ```tsx
139
+ import { formatPrice } from '@/lib/utils';
140
+ import type { Money } from '@thorprovider/types';
97
141
 
98
- ```ts
99
- // app/some-page/page.tsx
100
- import { getStorefrontConfig } from '@/lib/storefront-config';
142
+ // Correct
143
+ <span>{formatPrice(variant.price)}</span>
144
+ <span>{formatPrice(product.priceRange.minVariantPrice)}</span>
101
145
 
102
- export default async function SomePage() {
103
- const config = await getStorefrontConfig(); // null if backend unreachable or not configured
104
- const accentColor = config?.themeAccentColor; // e.g. "indigo", "blue", or custom oklch value
105
- // ...
106
- }
146
+ // Wrong — Money.amount is a string, not displayable directly
147
+ <span>${variant.price.amount}</span>
148
+ <span>{variant.prices[0].amount}</span> // prices[] doesn't exist!
107
149
  ```
108
150
 
109
- - Returns `null` gracefully when the backend is unreachable or the provider does not implement `getStorefrontConfig`.
110
- - Result is cached per React server request (deduped across components in the same render).
151
+ **Key facts about Money:**
152
+ - `Money.amount` is a **decimal string** (`"29.99"`) — NOT cents, NOT a number
153
+ - `ProductVariant.price` is a **single Money object** — NOT an array
154
+ - Always use `formatPrice()` for locale-aware currency formatting
111
155
 
112
156
  ---
113
157
 
114
- ## 6. Webhook ISR Revalidation
158
+ ## 7. Authentication
159
+
160
+ ```tsx
161
+ 'use client';
162
+ import { commerce } from '@/lib/commerce';
115
163
 
116
- The app ships with a webhook endpoint at `app/api/revalidate/route.ts`. Enable it by setting `FRONTEND_WEBHOOK_SECRET` in `.env`:
164
+ // Auth is built into the adapter — call commerce.auth.* directly
165
+ async function handleLogin(email: string, password: string) {
166
+ const { customer } = await commerce.auth.login({ email, password });
167
+ // Redirect on success
168
+ }
117
169
 
118
- ```bash
119
- FRONTEND_WEBHOOK_SECRET=your-shared-secret
170
+ // Check auth state
171
+ const isAuth = await commerce.auth.isAuthenticated();
172
+ const customer = await commerce.auth.getCurrentCustomer();
120
173
  ```
121
174
 
122
- The backend plugin sends `POST /api/revalidate` with `x-webhook-secret` header. Supported events:
175
+ - Auth is part of `@thorprovider/adapters` — no separate provider needed.
176
+ - See `docs/commerce-api.md` for full auth API reference.
123
177
 
124
- | Event | Effect |
125
- |-------|--------|
126
- | `site_config.updated` | Revalidates `site-config` cache tag |
127
- | `storefront_config.updated` | Revalidates `storefront-config` cache tag |
128
- | `sales_channel.updated` | Revalidates both tags |
129
- | _(any other)_ | Revalidates both tags as a safety net |
178
+ ---
130
179
 
131
- ❌ Never expose `FRONTEND_WEBHOOK_SECRET` in client-side code — it is a server-only env var.
180
+ ## Import Path Summary
181
+
182
+ | What | Import From |
183
+ |------|-------------|
184
+ | Types | `@thorprovider/types` |
185
+ | Commerce data | `@/lib/commerce` |
186
+ | Cart hook | `@/components/providers/cart-provider` |
187
+ | Region hook | `@/components/providers/region-provider` |
188
+ | Commerce hook | `@/components/providers/commerce-provider` |
189
+ | Utilities | `@/lib/utils` (cn, formatPrice) |
190
+ | UI components | `@/components/ui/*` (shadcn/ui) |
191
+ | Navigation | `next/link` |
192
+ | Images | `next/image` |