@thorprovider/create-thor-app 4.0.0 → 4.1.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.
Files changed (47) hide show
  1. package/README.md +31 -68
  2. package/dist/index.js +158 -629
  3. package/package.json +1 -1
  4. package/templates/default/.agents/AGENTS.md +27 -0
  5. package/templates/default/.env.example +12 -33
  6. package/templates/default/.eslintrc.json +20 -27
  7. package/templates/default/README.md +60 -119
  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 +45 -113
  17. package/templates/default/components/providers/app-providers.tsx +19 -68
  18. package/templates/default/components/providers/cart-provider.tsx +155 -0
  19. package/templates/default/components/providers/commerce-provider.tsx +34 -0
  20. package/templates/default/components/providers/region-provider.tsx +115 -0
  21. package/templates/default/docs/README.md +52 -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 +44 -42
  26. package/templates/default/docs/types.md +105 -1024
  27. package/templates/default/lib/commerce.ts +52 -135
  28. package/templates/default/lib/env.ts +68 -94
  29. package/templates/default/lib/utils.ts +18 -0
  30. package/templates/default/next.config.ts +7 -0
  31. package/templates/default/package.json +2 -8
  32. package/templates/default/registry.json +6 -0
  33. package/templates/default/styles/tokens.css +81 -0
  34. package/templates/default/components/providers/navigation-provider.tsx +0 -37
  35. package/templates/default/config/site.config.ts +0 -156
  36. package/templates/default/docs/components.md +0 -282
  37. package/templates/default/docs/dependencies.md +0 -61
  38. package/templates/default/lib/auth-context.tsx +0 -213
  39. package/templates/default/lib/cart-provider.tsx +0 -53
  40. package/templates/default/lib/commerce-provider.tsx +0 -48
  41. package/templates/default/lib/region-detection.ts +0 -73
  42. package/templates/default/lib/region-provider.tsx +0 -53
  43. package/templates/default/lib/regions-config.ts +0 -48
  44. package/templates/default/lib/storefront-config.ts +0 -54
  45. package/templates/default/next.config.mjs +0 -51
  46. package/templates/default/proxy.ts +0 -155
  47. package/templates/default/scripts/generate-regions-config.ts +0 -498
@@ -0,0 +1,115 @@
1
+ 'use client'
2
+
3
+ /**
4
+ * Region Provider — Manages region/currency context.
5
+ *
6
+ * V0: Use `useRegion()` from `@/components/providers/region-provider` to access
7
+ * the current region and currency settings.
8
+ *
9
+ * API:
10
+ * region — Current Region object (or null before hydration)
11
+ * regions — All available regions
12
+ * currencyCode — Active currency code (e.g. "USD")
13
+ * setRegion(id) — Switch active region
14
+ * isLoading — True while fetching regions
15
+ */
16
+
17
+ import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
18
+ import { commerce } from '@/lib/commerce'
19
+ import type { ReactNode } from 'react'
20
+ import type { Region } from '@thorprovider/types'
21
+
22
+ export interface RegionContextValue {
23
+ region: Region | null
24
+ regions: Region[]
25
+ currencyCode: string
26
+ setRegion: (regionId: string) => void
27
+ isLoading: boolean
28
+ }
29
+
30
+ const RegionContext = createContext<RegionContextValue | null>(null)
31
+
32
+ const REGION_KEY = 'thor-region-id'
33
+ const REGION_PROVIDER_KEY = 'thor-region-provider'
34
+
35
+ /**
36
+ * Normalize adapter response to Region type.
37
+ * Handles both universal (Region) and raw adapter shapes (currency_code, countries[]).
38
+ */
39
+ function normalizeRegion(raw: Record<string, unknown>): Region {
40
+ return {
41
+ id: String(raw.id ?? ''),
42
+ name: String(raw.name ?? ''),
43
+ // Handle both shapes: universal `currency` or adapter `currency_code`
44
+ currency: String(raw.currency ?? raw.currency_code ?? 'USD'),
45
+ // Handle both shapes: universal `countryCodes` or adapter `countries[].iso_2`
46
+ countryCodes: Array.isArray(raw.countryCodes)
47
+ ? raw.countryCodes as string[]
48
+ : Array.isArray(raw.countries)
49
+ ? (raw.countries as Array<{ iso_2?: string }>).map((c) => c.iso_2 ?? '').filter(Boolean)
50
+ : [],
51
+ }
52
+ }
53
+
54
+ export function RegionProvider({ children }: { children: ReactNode }) {
55
+ const [regions, setRegions] = useState<Region[]>([])
56
+ const [region, setCurrentRegion] = useState<Region | null>(null)
57
+ const [isLoading, setIsLoading] = useState(true)
58
+
59
+ const currencyCode = region?.currency ?? process.env.NEXT_PUBLIC_DEFAULT_CURRENCY ?? 'USD'
60
+
61
+ useEffect(() => {
62
+ let cancelled = false
63
+ ;(async () => {
64
+ try {
65
+ setIsLoading(true)
66
+ if (!commerce.getRegions) return
67
+
68
+ const currentProvider = commerce.isMock ? 'mock' : 'live'
69
+ const storedProvider = localStorage.getItem(REGION_PROVIDER_KEY)
70
+
71
+ if (storedProvider && storedProvider !== currentProvider) {
72
+ localStorage.removeItem(REGION_KEY)
73
+ }
74
+
75
+ localStorage.setItem(REGION_PROVIDER_KEY, currentProvider)
76
+
77
+ const raw = await commerce.getRegions()
78
+ if (cancelled || !raw) return
79
+
80
+ const normalized = (raw as Array<Record<string, unknown>>).map(normalizeRegion)
81
+ setRegions(normalized)
82
+
83
+ // Restore saved region or use first available
84
+ const savedId = localStorage.getItem(REGION_KEY)
85
+ const match = normalized.find((r) => r.id === savedId) ?? normalized[0] ?? null
86
+ setCurrentRegion(match)
87
+ } catch {
88
+ // Regions may not be configured — graceful fallback
89
+ } finally {
90
+ if (!cancelled) setIsLoading(false)
91
+ }
92
+ })()
93
+ return () => { cancelled = true }
94
+ }, [])
95
+
96
+ const setRegion = useCallback((regionId: string) => {
97
+ const found = regions.find((r) => r.id === regionId)
98
+ if (found) {
99
+ setCurrentRegion(found)
100
+ localStorage.setItem(REGION_KEY, regionId)
101
+ }
102
+ }, [regions])
103
+
104
+ return (
105
+ <RegionContext.Provider value={{ region, regions, currencyCode, setRegion, isLoading }}>
106
+ {children}
107
+ </RegionContext.Provider>
108
+ )
109
+ }
110
+
111
+ export function useRegion(): RegionContextValue {
112
+ const ctx = useContext(RegionContext)
113
+ if (!ctx) throw new Error('useRegion must be used within <RegionProvider>')
114
+ return ctx
115
+ }
@@ -1,52 +1,67 @@
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
+ ## Runtime modes
12
12
 
13
- This app was generated by `create:app` and connects to v0.app for feature development:
13
+ - **Mock-first**: the template defaults to `mock` so previews work even before a backend exists.
14
+ - **Live immediately**: if real backend env vars are present, the same template runtime uses the live provider immediately.
15
+ - **Same app code**: pages/components should keep using `commerce`, `useCart()`, `useRegion()`, and `useCommerce()` without provider-specific branching.
14
16
 
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 |
17
+ ## How It Works
21
18
 
22
- ## Capabilities
19
+ V0 generates feature code (pages, components) on top of this frozen infrastructure. The template provides:
23
20
 
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`)
21
+ - Commerce singleton (`lib/commerce.ts`) — all backend access goes through here
22
+ - Type safety via `@thorprovider/types` — Product, Cart, Order, Customer, Money
23
+ - Local providers (`components/providers/`, `lib/`) — V0 can read source code
24
+ - CSS token theming via `globals.css` — dark mode works automatically
30
25
 
31
- ## Quick Start
26
+ ## Docs Index
32
27
 
33
- ```bash
34
- cp .env.example .env.local && yarn install && yarn dev
35
- # → http://localhost:3000
36
- ```
28
+ | File | Purpose |
29
+ |------|---------|
30
+ | `types.md` | Domain type shapes (Product, Cart, Order, Money, etc.) |
31
+ | `commerce-api.md` | All `commerce.*` method signatures |
32
+ | `patterns.md` | Code templates for pages, components, cart, auth, styling |
33
+ | `rules.md` | Non-negotiable constraints (read before generating) |
34
+ | `project-structure.md` | Folder map + where to put new files |
35
+
36
+ ## Quick Import Reference
37
+
38
+ ```ts
39
+ // Types (everywhere)
40
+ import type { Product, Cart, Money } from '@thorprovider/types';
41
+
42
+ // Commerce data (server components + API routes)
43
+ import { commerce } from '@/lib/commerce';
37
44
 
38
- ```bash
39
- NEXT_PUBLIC_COMMERCE_API_URL=https://your-backend.com
40
- NODE_AUTH_TOKEN=github-pat-with-read:packages-scope
45
+ // Cart (client components)
46
+ import { useCart } from '@/components/providers/cart-provider';
47
+
48
+ // Auth (client components)
49
+ import { useAuth } from '@/lib/auth-context';
50
+
51
+ // Utilities
52
+ import { cn, formatPrice } from '@/lib/utils';
53
+
54
+ // Navigation + images (directly from Next.js)
55
+ import Link from 'next/link';
56
+ import Image from 'next/image';
57
+
58
+ // UI (shadcn/ui — installed per-project)
59
+ import { Button } from '@/components/ui/button';
41
60
  ```
42
61
 
43
- ## Docs Index
62
+ ## NOT Used
44
63
 
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 |
64
+ | Package | Why |
65
+ |---------|-----|
66
+ | `@thorprovider/components` | V0 creates UI from shadcn/ui — unique UI per client |
67
+ | `@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