@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
@@ -1,79 +1,9 @@
1
1
  @import 'tailwindcss';
2
2
  @import 'tw-animate-css';
3
+ @import '../styles/tokens.css';
3
4
 
4
5
  @custom-variant dark (&:is(.dark *));
5
6
 
6
- :root {
7
- --background: oklch(0.98 0.002 90);
8
- --foreground: oklch(0.15 0 0);
9
- --card: oklch(1 0 0);
10
- --card-foreground: oklch(0.15 0 0);
11
- --popover: oklch(1 0 0);
12
- --popover-foreground: oklch(0.15 0 0);
13
- --primary: oklch(0.15 0 0);
14
- --primary-foreground: oklch(0.98 0.002 90);
15
- --secondary: oklch(0.96 0.003 90);
16
- --secondary-foreground: oklch(0.15 0 0);
17
- --muted: oklch(0.94 0.003 90);
18
- --muted-foreground: oklch(0.45 0 0);
19
- --accent: oklch(0.65 0.15 25);
20
- --accent-foreground: oklch(1 0 0);
21
- --destructive: oklch(0.55 0.2 25);
22
- --destructive-foreground: oklch(1 0 0);
23
- --border: oklch(0.88 0.003 90);
24
- --input: oklch(0.92 0.003 90);
25
- --ring: oklch(0.15 0 0);
26
- --chart-1: oklch(0.646 0.222 41.116);
27
- --chart-2: oklch(0.6 0.118 184.704);
28
- --chart-3: oklch(0.398 0.07 227.392);
29
- --chart-4: oklch(0.828 0.189 84.429);
30
- --chart-5: oklch(0.769 0.188 70.08);
31
- --radius: 0.375rem;
32
- --sidebar: oklch(0.985 0 0);
33
- --sidebar-foreground: oklch(0.145 0 0);
34
- --sidebar-primary: oklch(0.205 0 0);
35
- --sidebar-primary-foreground: oklch(0.985 0 0);
36
- --sidebar-accent: oklch(0.97 0 0);
37
- --sidebar-accent-foreground: oklch(0.205 0 0);
38
- --sidebar-border: oklch(0.922 0 0);
39
- --sidebar-ring: oklch(0.708 0 0);
40
- }
41
-
42
- .dark {
43
- --background: oklch(0.145 0 0);
44
- --foreground: oklch(0.985 0 0);
45
- --card: oklch(0.145 0 0);
46
- --card-foreground: oklch(0.985 0 0);
47
- --popover: oklch(0.145 0 0);
48
- --popover-foreground: oklch(0.985 0 0);
49
- --primary: oklch(0.985 0 0);
50
- --primary-foreground: oklch(0.205 0 0);
51
- --secondary: oklch(0.269 0 0);
52
- --secondary-foreground: oklch(0.985 0 0);
53
- --muted: oklch(0.269 0 0);
54
- --muted-foreground: oklch(0.708 0 0);
55
- --accent: oklch(0.269 0 0);
56
- --accent-foreground: oklch(0.985 0 0);
57
- --destructive: oklch(0.396 0.141 25.723);
58
- --destructive-foreground: oklch(0.637 0.237 25.331);
59
- --border: oklch(0.269 0 0);
60
- --input: oklch(0.269 0 0);
61
- --ring: oklch(0.439 0 0);
62
- --chart-1: oklch(0.488 0.243 264.376);
63
- --chart-2: oklch(0.696 0.17 162.48);
64
- --chart-3: oklch(0.769 0.188 70.08);
65
- --chart-4: oklch(0.627 0.265 303.9);
66
- --chart-5: oklch(0.645 0.246 16.439);
67
- --sidebar: oklch(0.205 0 0);
68
- --sidebar-foreground: oklch(0.985 0 0);
69
- --sidebar-primary: oklch(0.488 0.243 264.376);
70
- --sidebar-primary-foreground: oklch(0.985 0 0);
71
- --sidebar-accent: oklch(0.269 0 0);
72
- --sidebar-accent-foreground: oklch(0.985 0 0);
73
- --sidebar-border: oklch(0.269 0 0);
74
- --sidebar-ring: oklch(0.439 0 0);
75
- }
76
-
77
7
  @theme inline {
78
8
  --font-sans: 'Inter', 'Inter Fallback', system-ui, sans-serif;
79
9
  --font-mono: 'Geist Mono', 'Geist Mono Fallback';
@@ -1,50 +1,28 @@
1
- import React from 'react';
2
- import type { Metadata } from 'next';
3
- import { Inter } from 'next/font/google';
4
- import { ThemeProvider } from '@thorprovider/providers';
5
- import { AppProviders } from '@/components/providers/app-providers';
6
- import { getRegionFromIpHeaders } from '@/lib/region-detection';
7
- import { getStorefrontConfig, resolveAccentColor } from '@/lib/storefront-config';
8
- import { siteConfig } from '@/config/site.config';
9
- import '@thorprovider/components/styles.css';
10
- import './globals.css';
1
+ import React from 'react'
2
+ import type { Metadata } from 'next'
3
+ import { Inter } from 'next/font/google'
4
+ import { AppProviders } from '@/components/providers/app-providers'
5
+ import './globals.css'
11
6
 
12
- const inter = Inter({ subsets: ['latin'], variable: '--font-inter' });
7
+ const inter = Inter({ subsets: ['latin'], variable: '--font-inter' })
13
8
 
14
9
  export const metadata: Metadata = {
15
- title: siteConfig.title,
16
- description: siteConfig.description,
17
- };
10
+ title: 'My Store | Powered by Thor Commerce',
11
+ description: 'An e-commerce store built with Thor Commerce.',
12
+ }
18
13
 
19
- export default async function RootLayout({
14
+ export default function RootLayout({
20
15
  children,
21
16
  }: Readonly<{
22
- children: React.ReactNode;
17
+ children: React.ReactNode
23
18
  }>) {
24
- const [initialRegionId, storefrontConfig] = await Promise.all([
25
- getRegionFromIpHeaders(),
26
- getStorefrontConfig(),
27
- ]);
28
-
29
- const accentOverride = storefrontConfig?.themeAccentColor
30
- ? resolveAccentColor(storefrontConfig.themeAccentColor)
31
- : undefined;
32
-
33
19
  return (
34
- <html>
20
+ <html lang="en" suppressHydrationWarning>
35
21
  <body className={`${inter.variable} font-sans antialiased`}>
36
- <ThemeProvider {...({ preset: siteConfig.preset, children: (
37
- <AppProviders initialRegionId={initialRegionId}>
38
- {accentOverride ? (
39
- <div style={{ '--accent': accentOverride } as React.CSSProperties}>
40
- {children}
41
- </div>
42
- ) : (
43
- children
44
- )}
45
- </AppProviders>
46
- )} as any)} />
22
+ <AppProviders>
23
+ {children}
24
+ </AppProviders>
47
25
  </body>
48
26
  </html>
49
- );
27
+ )
50
28
  }
@@ -2,7 +2,7 @@
2
2
  * Not Found Page
3
3
  *
4
4
  * Displayed when a requested page does not exist.
5
- * Self-contained — does not import @thorprovider/components components.
5
+ * Self-contained — uses only Tailwind + next/link.
6
6
  * Projects replace this with a branded 404 page.
7
7
  */
8
8
 
@@ -1,124 +1,56 @@
1
- import { Metadata } from 'next';
2
- import { Button, Heading, Text } from '@thorprovider/components';
1
+ // V0 replaces this with the actual storefront homepage
2
+ import { commerce } from '@/lib/commerce'
3
+ import { formatPrice } from '@/lib/utils'
4
+ import type { Product } from '@thorprovider/types'
3
5
 
4
- export const metadata: Metadata = {
5
- title: 'Thor Commerce | Initialized',
6
- description: 'Your highly scalable, hexagonal e-commerce template is ready.',
7
- };
6
+ export default async function HomePage() {
7
+ const products: Product[] = await commerce.getProducts({ first: 8 })
8
+ const isMockMode = commerce.isMock === true
8
9
 
9
- export default function HomePage() {
10
10
  return (
11
- <main className="flex min-h-screen flex-col items-center p-6 md:p-24 bg-background text-foreground relative overflow-hidden selection:bg-primary/30">
12
- {/* Abstract Background Elements */}
13
- <div className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] rounded-full bg-primary/10 blur-[120px] pointer-events-none" />
14
- <div className="absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] rounded-full bg-accent/10 blur-[120px] pointer-events-none" />
15
-
16
- {/* Top Status Bar */}
17
- <div className="z-10 flex flex-col items-center max-w-5xl w-full gap-8">
18
- <div className="flex items-center gap-3 px-5 py-2.5 rounded-full bg-muted/40 border border-border/50 text-sm backdrop-blur-md shadow-sm">
19
- <span className="relative flex h-2.5 w-2.5">
20
- <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"></span>
21
- <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-primary"></span>
22
- </span>
23
- <span className="text-muted-foreground font-medium tracking-wide">
24
- Template Initialized
25
- </span>
26
- <div className="hidden sm:block w-px h-4 bg-border" />
27
- <span className="hidden sm:block text-muted-foreground">
28
- Edit
29
- </span>
30
- <code className="font-mono text-xs font-semibold text-primary bg-muted px-2 py-0.5 rounded-sm border border-border/50">
31
- app/page.tsx
32
- </code>
11
+ <main className="container mx-auto px-4 py-8">
12
+ <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
13
+ <div>
14
+ <h1 className="text-3xl font-bold">Store</h1>
15
+ <p className="text-muted-foreground">{products.length} products available</p>
33
16
  </div>
34
17
 
35
- {/* Hero Section */}
36
- <div className="flex flex-col items-center text-center gap-6 mt-16 md:mt-24 z-10 w-full max-w-3xl">
37
- <Heading
38
- as="h1"
39
- className="text-6xl md:text-8xl font-black tracking-tighter leading-none"
40
- >
41
- Thor<br className="md:hidden" />
42
- <span className="text-transparent bg-clip-text bg-gradient-to-br from-primary to-accent">
43
- Commerce
44
- </span>
45
- </Heading>
46
-
47
- <Text className="text-xl md:text-2xl text-muted-foreground max-w-[600px] leading-relaxed font-light text-balance mt-4">
48
- Your production-ready, hexagonal architecture storefront has been successfully deployed.
49
- </Text>
50
-
51
- <div className="flex flex-col sm:flex-row gap-4 mt-8 w-full sm:w-auto px-4">
52
- <a
53
- href="https://github.com/thorprovider/thor-commerce/blob/main/docs/architecture/overview.md"
54
- target="_blank"
55
- rel="noopener noreferrer"
56
- className="w-full sm:w-auto"
57
- >
58
- <Button size="lg" className="w-full rounded-full px-8 h-12 text-base font-semibold shadow-lg shadow-primary/25 hover:shadow-primary/40 transition-all">
59
- Read the Docs
60
- </Button>
61
- </a>
62
- <a
63
- href="https://github.com/thorprovider/thor-commerce"
64
- target="_blank"
65
- rel="noopener noreferrer"
66
- className="w-full sm:w-auto"
67
- >
68
- <Button size="lg" variant="secondary" className="w-full rounded-full px-8 h-12 text-base font-semibold transition-all">
69
- GitHub Repo
70
- </Button>
71
- </a>
72
- </div>
18
+ <div className="rounded-full border px-4 py-2 text-sm text-muted-foreground">
19
+ {isMockMode
20
+ ? 'Using mock catalog — connect a backend to switch to live commerce data.'
21
+ : 'Connected to live commerce data.'}
73
22
  </div>
74
23
  </div>
75
24
 
76
- {/* Grid Documentation Links */}
77
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl w-full mt-32 z-10">
78
- {[
79
- {
80
- title: 'L1-L5 Architecture',
81
- description: 'Learn the strict unidirectional data flow and layer separation.',
82
- href: 'https://github.com/thorprovider/thor-commerce/blob/main/docs/architecture/layers-l1-to-l5.md',
83
- },
84
- {
85
- title: 'Adapters & Providers',
86
- description: 'Understand how to seamlessly switch between Medusa and Shopify.',
87
- href: 'https://github.com/thorprovider/thor-commerce/blob/main/docs/guides/adapters.md',
88
- },
89
- {
90
- title: 'UI Components',
91
- description: 'Explore the 55+ accessible primitives powering this platform.',
92
- href: 'https://github.com/thorprovider/thor-commerce/blob/main/packages/components/README.md',
93
- },
94
- {
95
- title: 'Workflows & AI',
96
- description: 'Supercharge development using automated V0 context generation.',
97
- href: 'https://github.com/thorprovider/thor-commerce/blob/main/docs/architecture/ai-generation-workflow.md',
98
- },
99
- ].map((feature, i) => (
100
- <a
101
- key={i}
102
- href={feature.href}
103
- target="_blank"
104
- rel="noopener noreferrer"
105
- className="group relative flex flex-col rounded-2xl border border-border/40 bg-card/10 p-6 backdrop-blur-sm transition-all hover:bg-card/40 hover:border-primary/30 overflow-hidden"
106
- >
107
- {/* Hover Gradient */}
108
- <div className="absolute inset-0 bg-gradient-to-br from-primary/10 to-transparent opacity-0 transition-opacity duration-500 group-hover:opacity-100" />
109
-
110
- <Heading as="h3" className="text-xl font-bold mb-3 flex items-center justify-between group-hover:text-primary transition-colors">
111
- {feature.title}
112
- <span className="inline-block transition-transform duration-300 group-hover:translate-x-1 group-hover:-translate-y-1 opacity-50 group-hover:opacity-100">
113
- ↗
114
- </span>
115
- </Heading>
116
- <Text className="text-sm text-muted-foreground leading-relaxed m-0 text-balance flex-grow">
117
- {feature.description}
118
- </Text>
119
- </a>
120
- ))}
25
+ <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
26
+ {products.slice(0, 4).map((product) => {
27
+ const previewPrice = product.variants[0]?.price
28
+
29
+ return (
30
+ <article key={product.id} className="rounded-xl border bg-card p-4 text-card-foreground">
31
+ <div className="aspect-square overflow-hidden rounded-lg bg-muted">
32
+ {product.featuredImage ? (
33
+ <img
34
+ alt={product.featuredImage.altText || product.title}
35
+ className="h-full w-full object-cover"
36
+ src={product.featuredImage.url}
37
+ />
38
+ ) : null}
39
+ </div>
40
+
41
+ <div className="mt-4 space-y-1">
42
+ <h2 className="font-semibold">{product.title}</h2>
43
+ <p className="line-clamp-2 text-sm text-muted-foreground">{product.description}</p>
44
+ {previewPrice ? (
45
+ <p className="text-sm font-medium">{formatPrice(previewPrice)}</p>
46
+ ) : null}
47
+ </div>
48
+ </article>
49
+ )
50
+ })}
121
51
  </div>
52
+
53
+ {/* V0: Generate the actual storefront homepage here */}
122
54
  </main>
123
- );
55
+ )
124
56
  }
@@ -1,77 +1,28 @@
1
- 'use client';
1
+ 'use client'
2
2
 
3
3
  /**
4
- * @thorprovider/core - Application Providers Composition
5
- *
6
- * V0: COPY THIS FILE VERBATIM when creating starters or apps.
7
- * Only customize: add new providers as children of ClientNavigationProvider.
8
- * NEVER remove, reorder, or replace providers with direct @thorprovider/providers imports.
9
- * See: .v0/docs/v0_provider_chain.md
4
+ * Application Providers — Composites all context providers.
10
5
  *
11
6
  * Provider Hierarchy (ordered by dependencies — FROZEN, do not reorder):
12
- * 1. ClientCommerceProvider - Commerce backend access (no dependencies)
13
- * 2. ClientRegionProvider - Regional settings (depends on commerce)
14
- * 3. AuthProvider - Authentication (no dependencies)
15
- * 4. ClientCartProvider - Shopping cart (depends on commerce, region, auth)
16
- * 5. ClientNavigationProvider - URL resolvers (no dependencies)
17
- *
18
- * Rule for V0: Add new providers as children of ClientNavigationProvider.
19
- * Never reorder or remove from this chain.
20
- */
21
-
22
- import React from 'react';
23
- import { ClientCommerceProvider } from '@/lib/commerce-provider';
24
- import { ClientRegionProvider } from '@/lib/region-provider';
25
- import { AuthProvider } from '@/lib/auth-context';
26
- import { ClientCartProvider } from '@/lib/cart-provider';
27
- import { ClientNavigationProvider } from './navigation-provider';
28
- import type { ReactNode } from 'react';
29
-
30
- /**
31
- * AppProviders Props
7
+ * 1. CommerceProvider — Commerce backend access (no dependencies)
8
+ * 2. RegionProvider — Region/currency context (depends on commerce)
9
+ * 3. CartProvider — Shopping cart (depends on commerce)
32
10
  */
33
- export interface AppProvidersProps {
34
- /**
35
- * Child components to wrap with all providers
36
- */
37
- children: ReactNode;
38
11
 
39
- /**
40
- * Region ID detected server-side from the client's IP geolocation headers.
41
- * When provided, RegionProvider uses this as the initial region, bypassing
42
- * the locale-based fallback. localStorage takes priority if the user
43
- * has previously selected a region explicitly.
44
- */
45
- initialRegionId?: string;
46
- }
12
+ import React from 'react'
13
+ import { CommerceProvider } from './commerce-provider'
14
+ import { RegionProvider } from './region-provider'
15
+ import { CartProvider } from './cart-provider'
16
+ import type { ReactNode } from 'react'
47
17
 
48
- /**
49
- * Application Providers Composition
50
- *
51
- * Wraps children with all required Context Providers in the correct order.
52
- * This component is a Client Component because it contains provider functions
53
- * that cannot be serialized for Server Components.
54
- */
55
- export function AppProviders({ children, initialRegionId }: AppProvidersProps) {
18
+ export function AppProviders({ children }: { children: ReactNode }) {
56
19
  return (
57
- // FROZEN: Provider order is critical. Do NOT reorder or remove providers.
58
- // Each provider depends on the previous ones in this exact sequence:
59
- // 1. ClientCommerceProvider (no deps)
60
- // 2. ClientRegionProvider (uses commerce context)
61
- // 3. AuthProvider (no deps)
62
- // 4. ClientCartProvider (uses commerce, region, auth contexts)
63
- // 5. ClientNavigationProvider (no deps)
64
- // Reordering will break context dependencies and cause runtime errors.
65
- <ClientCommerceProvider>
66
- <ClientRegionProvider initialRegionId={initialRegionId}>
67
- <AuthProvider>
68
- <ClientCartProvider>
69
- <ClientNavigationProvider>
70
- {children}
71
- </ClientNavigationProvider>
72
- </ClientCartProvider>
73
- </AuthProvider>
74
- </ClientRegionProvider>
75
- </ClientCommerceProvider>
76
- );
20
+ <CommerceProvider>
21
+ <RegionProvider>
22
+ <CartProvider>
23
+ {children}
24
+ </CartProvider>
25
+ </RegionProvider>
26
+ </CommerceProvider>
27
+ )
77
28
  }
@@ -0,0 +1,155 @@
1
+ 'use client'
2
+
3
+ /**
4
+ * Cart Provider — Local provider that manages shopping cart state.
5
+ *
6
+ * V0: Use `useCart()` from `@/components/providers/cart-provider` to access cart operations.
7
+ * This is a client component that provides cart context to the entire app.
8
+ *
9
+ * API:
10
+ * cart — Current Cart object (or null if no cart)
11
+ * items — Cart line items array
12
+ * totalQuantity — Total items in cart
13
+ * isLoading — True during cart operations
14
+ * addItem(variantId, quantity?) — Add item to cart
15
+ * removeItem(lineItemId) — Remove item from cart
16
+ * updateQuantity(lineItemId, quantity) — Update item quantity
17
+ * clearCart() — Clear cart and remove from localStorage
18
+ */
19
+
20
+ import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
21
+ import { commerce } from '@/lib/commerce'
22
+ import type { ReactNode } from 'react'
23
+ import type { Cart, CartItem, CartLineInput, CartLineUpdate } from '@thorprovider/types'
24
+
25
+ export interface CartContextValue {
26
+ cart: Cart | null
27
+ items: CartItem[]
28
+ totalQuantity: number
29
+ isLoading: boolean
30
+ error: Error | null
31
+ addItem: (variantId: string, quantity?: number) => Promise<void>
32
+ removeItem: (lineItemId: string) => Promise<void>
33
+ updateQuantity: (lineItemId: string, quantity: number) => Promise<void>
34
+ clearCart: () => void
35
+ }
36
+
37
+ const CartContext = createContext<CartContextValue | null>(null)
38
+
39
+ const CART_ID_KEY = 'thor-cart-id'
40
+ const CART_PROVIDER_KEY = 'thor-cart-provider'
41
+
42
+ export function CartProvider({ children }: { children: ReactNode }) {
43
+ const [cart, setCart] = useState<Cart | null>(null)
44
+ const [isLoading, setIsLoading] = useState(true)
45
+ const [error, setError] = useState<Error | null>(null)
46
+
47
+ const items: CartItem[] = cart?.lines ?? []
48
+ const totalQuantity = cart?.totalQuantity ?? 0
49
+
50
+ // Hydrate cart from localStorage on mount
51
+ useEffect(() => {
52
+ let cancelled = false
53
+ ;(async () => {
54
+ try {
55
+ setIsLoading(true)
56
+ const currentProvider = commerce.isMock ? 'mock' : 'live'
57
+ const storedProvider = localStorage.getItem(CART_PROVIDER_KEY)
58
+
59
+ if (storedProvider && storedProvider !== currentProvider) {
60
+ localStorage.removeItem(CART_ID_KEY)
61
+ }
62
+
63
+ localStorage.setItem(CART_PROVIDER_KEY, currentProvider)
64
+
65
+ const cartId = localStorage.getItem(CART_ID_KEY)
66
+ if (cartId) {
67
+ const loaded = await commerce.getCart(cartId)
68
+ if (!cancelled && loaded) setCart(loaded)
69
+ }
70
+ } catch (err) {
71
+ if (!cancelled) {
72
+ setError(err instanceof Error ? err : new Error(String(err)))
73
+ localStorage.removeItem(CART_ID_KEY)
74
+ }
75
+ } finally {
76
+ if (!cancelled) setIsLoading(false)
77
+ }
78
+ })()
79
+ return () => { cancelled = true }
80
+ }, [])
81
+
82
+ const ensureCart = useCallback(async (): Promise<Cart> => {
83
+ if (cart) return cart
84
+ const newCart = await commerce.createCart()
85
+ setCart(newCart)
86
+ if (newCart.id) localStorage.setItem(CART_ID_KEY, newCart.id)
87
+ localStorage.setItem(CART_PROVIDER_KEY, commerce.isMock ? 'mock' : 'live')
88
+ return newCart
89
+ }, [cart])
90
+
91
+ const addItem = useCallback(async (variantId: string, quantity = 1) => {
92
+ setIsLoading(true)
93
+ try {
94
+ const c = await ensureCart()
95
+ if (!c.id) return
96
+ const line: CartLineInput = { merchandiseId: variantId, quantity }
97
+ const updated = await commerce.addToCart(c.id, [line])
98
+ setCart(updated)
99
+ } catch (err) {
100
+ setError(err instanceof Error ? err : new Error(String(err)))
101
+ throw err
102
+ } finally {
103
+ setIsLoading(false)
104
+ }
105
+ }, [ensureCart])
106
+
107
+ const removeItem = useCallback(async (lineItemId: string) => {
108
+ if (!cart?.id) return
109
+ setIsLoading(true)
110
+ try {
111
+ const updated = await commerce.removeFromCart(cart.id, [lineItemId])
112
+ setCart(updated)
113
+ } catch (err) {
114
+ setError(err instanceof Error ? err : new Error(String(err)))
115
+ throw err
116
+ } finally {
117
+ setIsLoading(false)
118
+ }
119
+ }, [cart])
120
+
121
+ const updateQuantity = useCallback(async (lineItemId: string, quantity: number) => {
122
+ if (!cart?.id) return
123
+ setIsLoading(true)
124
+ try {
125
+ const existing = cart.lines.find((l) => l.id === lineItemId)
126
+ const merchandiseId = existing?.merchandise?.id ?? lineItemId
127
+ const line: CartLineUpdate = { id: lineItemId, merchandiseId, quantity }
128
+ const updated = await commerce.updateCart(cart.id, [line])
129
+ setCart(updated)
130
+ } catch (err) {
131
+ setError(err instanceof Error ? err : new Error(String(err)))
132
+ throw err
133
+ } finally {
134
+ setIsLoading(false)
135
+ }
136
+ }, [cart])
137
+
138
+ const clearCart = useCallback(() => {
139
+ setCart(null)
140
+ localStorage.removeItem(CART_ID_KEY)
141
+ localStorage.removeItem(CART_PROVIDER_KEY)
142
+ }, [])
143
+
144
+ return (
145
+ <CartContext.Provider value={{ cart, items, totalQuantity, isLoading, error, addItem, removeItem, updateQuantity, clearCart }}>
146
+ {children}
147
+ </CartContext.Provider>
148
+ )
149
+ }
150
+
151
+ export function useCart(): CartContextValue {
152
+ const ctx = useContext(CartContext)
153
+ if (!ctx) throw new Error('useCart must be used within <CartProvider>')
154
+ return ctx
155
+ }
@@ -0,0 +1,34 @@
1
+ 'use client'
2
+
3
+ /**
4
+ * Commerce Provider — Injects the commerce adapter into the React tree.
5
+ *
6
+ * V0: Use `useCommerce()` for client-side access to commerce methods.
7
+ * Server components should import `commerce` directly from `@/lib/commerce`.
8
+ */
9
+
10
+ import React, { createContext, useContext } from 'react'
11
+ import { commerce } from '@/lib/commerce'
12
+ import type { ReactNode } from 'react'
13
+
14
+ export interface CommerceContextValue {
15
+ /** The commerce adapter instance (same as `@/lib/commerce` export) */
16
+ commerce: typeof commerce
17
+ isMock: boolean
18
+ }
19
+
20
+ const CommerceContext = createContext<CommerceContextValue | null>(null)
21
+
22
+ export function CommerceProvider({ children }: { children: ReactNode }) {
23
+ return (
24
+ <CommerceContext.Provider value={{ commerce, isMock: commerce.isMock === true }}>
25
+ {children}
26
+ </CommerceContext.Provider>
27
+ )
28
+ }
29
+
30
+ export function useCommerce(): CommerceContextValue {
31
+ const ctx = useContext(CommerceContext)
32
+ if (!ctx) throw new Error('useCommerce must be used within <CommerceProvider>')
33
+ return ctx
34
+ }