@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,213 +0,0 @@
1
- 'use client'
2
-
3
- /**
4
- * @thorprovider/core - Authentication Context
5
- *
6
- * Provides authentication state and methods to the application.
7
- * Uses @thorprovider/adapters for framework-agnostic auth implementation.
8
- */
9
-
10
- import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
11
- import { commerce } from './commerce'
12
- import type {
13
- Customer,
14
- LoginCredentials,
15
- RegisterData,
16
- UpdateCustomerData
17
- } from '@thorprovider/types'
18
-
19
- /**
20
- * Authentication context value
21
- */
22
- interface AuthContextValue {
23
- customer: Customer | null
24
- loading: boolean
25
- isInitializing: boolean
26
- login: (credentials: LoginCredentials) => Promise<void>
27
- register: (data: RegisterData) => Promise<void>
28
- logout: () => Promise<void>
29
- requestPasswordReset: (email: string) => Promise<void>
30
- resetPassword: (token: string, password: string, metadata?: Record<string, unknown>) => Promise<void>
31
- updateCustomer: (data: UpdateCustomerData) => Promise<void>
32
- isAuthenticated: boolean
33
- }
34
-
35
- const AuthContext = createContext<AuthContextValue | undefined>(undefined)
36
-
37
- export function useAuth() {
38
- const context = useContext(AuthContext)
39
-
40
- if (!context) {
41
- throw new Error('useAuth must be used within AuthProvider')
42
- }
43
-
44
- return context
45
- }
46
-
47
- interface AuthProviderProps {
48
- children: React.ReactNode
49
- }
50
-
51
- export function AuthProvider({ children }: AuthProviderProps) {
52
- const [customer, setCustomer] = useState<Customer | null>(null)
53
- const [loading, setLoading] = useState(false)
54
- const [isInitializing, setIsInitializing] = useState(true)
55
-
56
- useEffect(() => {
57
- async function checkAuth() {
58
- if (!commerce.auth) {
59
- console.warn('Auth not configured in commerce provider')
60
- setIsInitializing(false)
61
- return
62
- }
63
-
64
- try {
65
- const currentCustomer = await commerce.auth.getCurrentCustomer()
66
- setCustomer(currentCustomer)
67
- } catch (error) {
68
- console.error('Failed to check auth status:', error)
69
- } finally {
70
- setIsInitializing(false)
71
- }
72
- }
73
-
74
- checkAuth()
75
- }, [])
76
-
77
- const login = useCallback(async (credentials: LoginCredentials) => {
78
- if (!commerce.auth) {
79
- throw new Error('Auth not configured')
80
- }
81
-
82
- setLoading(true)
83
-
84
- try {
85
- const response = await commerce.auth.login(credentials)
86
-
87
- if (response.requiresAction) {
88
- if (response.redirectUrl) {
89
- window.location.href = response.redirectUrl
90
- }
91
- return
92
- }
93
-
94
- setCustomer(response.customer ?? null)
95
- } catch (error) {
96
- console.error('Login failed:', error)
97
- throw error
98
- } finally {
99
- setLoading(false)
100
- }
101
- }, [])
102
-
103
- const register = useCallback(async (data: RegisterData) => {
104
- if (!commerce.auth) {
105
- throw new Error('Auth not configured')
106
- }
107
-
108
- setLoading(true)
109
-
110
- try {
111
- const response = await commerce.auth.register(data)
112
- setCustomer(response.customer ?? null)
113
- } catch (error) {
114
- console.error('Registration failed:', error)
115
- throw error
116
- } finally {
117
- setLoading(false)
118
- }
119
- }, [])
120
-
121
- const logout = useCallback(async () => {
122
- if (!commerce.auth) {
123
- throw new Error('Auth not configured')
124
- }
125
-
126
- setLoading(true)
127
-
128
- try {
129
- await commerce.auth.logout()
130
- setCustomer(null)
131
- } catch (error) {
132
- console.error('Logout failed:', error)
133
- throw error
134
- } finally {
135
- setLoading(false)
136
- }
137
- }, [])
138
-
139
- const requestPasswordReset = useCallback(async (email: string) => {
140
- if (!commerce.auth) {
141
- throw new Error('Auth not configured')
142
- }
143
-
144
- setLoading(true)
145
-
146
- try {
147
- await commerce.auth.requestPasswordReset(email)
148
- } catch (error) {
149
- console.error('Password reset request failed:', error)
150
- throw error
151
- } finally {
152
- setLoading(false)
153
- }
154
- }, [])
155
-
156
- const resetPassword = useCallback(async (
157
- token: string,
158
- password: string,
159
- metadata?: Record<string, unknown>
160
- ) => {
161
- if (!commerce.auth) {
162
- throw new Error('Auth not configured')
163
- }
164
-
165
- setLoading(true)
166
-
167
- try {
168
- await commerce.auth.resetPassword(token, password, metadata)
169
- } catch (error) {
170
- console.error('Password reset failed:', error)
171
- throw error
172
- } finally {
173
- setLoading(false)
174
- }
175
- }, [])
176
-
177
- const updateCustomer = useCallback(async (data: UpdateCustomerData) => {
178
- if (!commerce.auth) {
179
- throw new Error('Auth not configured')
180
- }
181
-
182
- setLoading(true)
183
-
184
- try {
185
- const updatedCustomer = await commerce.auth.updateCustomer(data)
186
- setCustomer(updatedCustomer ?? null)
187
- } catch (error) {
188
- console.error('Update customer failed:', error)
189
- throw error
190
- } finally {
191
- setLoading(false)
192
- }
193
- }, [])
194
-
195
- const value: AuthContextValue = {
196
- customer,
197
- loading,
198
- isInitializing,
199
- login,
200
- register,
201
- logout,
202
- requestPasswordReset,
203
- resetPassword,
204
- updateCustomer,
205
- isAuthenticated: customer !== null,
206
- }
207
-
208
- return (
209
- <AuthContext.Provider value={value}>
210
- {children}
211
- </AuthContext.Provider>
212
- )
213
- }
@@ -1,53 +0,0 @@
1
- /**
2
- * @thorprovider/core - Cart Provider (Next.js Wrapper)
3
- *
4
- * Framework-specific wrapper for CartProvider from @thorprovider/providers.
5
- * Injects commerce, region, and auth dependencies via Dependency Injection.
6
- */
7
-
8
- 'use client';
9
-
10
- import React from 'react';
11
- import { CartProvider, useCart as useCartBase } from '@thorprovider/providers';
12
- import { useCommerce } from './commerce-provider';
13
- import { useRegion } from './region-provider';
14
- import { useAuth } from './auth-context';
15
- import type { ReactNode } from 'react';
16
- import type { CommerceProvider as CommerceProviderType } from '@thorprovider/types';
17
- import type { CartContextValue as ElementsCartContextValue } from '@thorprovider/providers';
18
-
19
- export type CartContextValue = ElementsCartContextValue;
20
-
21
- /**
22
- * ClientCartProvider (Next.js Wrapper)
23
- *
24
- * Wrapper for framework-agnostic CartProvider.
25
- * Injects Next.js dependencies:
26
- * - commerce from CommerceProvider context
27
- * - region from RegionProvider context
28
- * - auth from AuthProvider context
29
- * - localStorage/sessionStorage for persistence
30
- */
31
- export function ClientCartProvider({ children }: { children: ReactNode }) {
32
- const { provider: commerce } = useCommerce();
33
- const { region } = useRegion();
34
- const auth = useAuth();
35
-
36
- return (
37
- <CartProvider
38
- commerce={commerce as unknown as CommerceProviderType}
39
- region={region}
40
- auth={auth}
41
- storage={typeof window !== 'undefined' ? localStorage : undefined}
42
- sessionStorage={typeof window !== 'undefined' ? sessionStorage : undefined}
43
- debug={process.env.NODE_ENV === 'development'}
44
- >
45
- {children}
46
- </CartProvider>
47
- );
48
- }
49
-
50
- // Typed wrapper to avoid `never` inference in consuming app code.
51
- export function useCart(): CartContextValue {
52
- return useCartBase() as CartContextValue;
53
- }
@@ -1,48 +0,0 @@
1
- /**
2
- * @thorprovider/core - Commerce Provider (Next.js Wrapper)
3
- *
4
- * Framework-specific wrapper for CommerceProvider from @thorprovider/providers.
5
- * Injects commerce singleton via Dependency Injection pattern.
6
- */
7
-
8
- 'use client';
9
-
10
- import React from 'react';
11
- import {
12
- CommerceProvider,
13
- useCommerce as useCommerceBase,
14
- useCapabilities as useCapabilitiesBase,
15
- } from '@thorprovider/providers';
16
- import { commerce } from './commerce';
17
- import type { ReactNode } from 'react';
18
- import type { BackendCapabilities, CommerceProvider as CommerceProviderType } from '@thorprovider/types';
19
-
20
- export type CommerceContextValue = {
21
- provider: CommerceProviderType;
22
- capabilities: BackendCapabilities;
23
- backendName: string;
24
- backendVersion: string;
25
- };
26
-
27
- /**
28
- * ClientCommerceProvider (Next.js Wrapper)
29
- *
30
- * Wrapper for framework-agnostic CommerceProvider.
31
- * Injects commerce singleton from ./commerce.ts
32
- */
33
- export function ClientCommerceProvider({ children }: { children: ReactNode }) {
34
- return (
35
- <CommerceProvider commerce={commerce as unknown as CommerceProviderType}>
36
- {children}
37
- </CommerceProvider>
38
- );
39
- }
40
-
41
- // Typed wrappers to prevent `never` inference in consuming app code.
42
- export function useCommerce(): CommerceContextValue {
43
- return useCommerceBase() as unknown as CommerceContextValue;
44
- }
45
-
46
- export function useCapabilities(): BackendCapabilities {
47
- return useCapabilitiesBase() as unknown as BackendCapabilities;
48
- }
@@ -1,73 +0,0 @@
1
- /**
2
- * @thorprovider/core - IP-based Region Detection
3
- *
4
- * Detects a region ID from the incoming request's geolocation headers.
5
- * Supports Vercel (`x-vercel-ip-country`) and Cloudflare (`cf-ipcountry`).
6
- *
7
- * Uses auto-generated regions-config (from `yarn generate:regions`) as the
8
- * source of truth for locale→region mapping. The generated file lives at
9
- * lib/regions-config.ts (same directory) so that relative imports work in
10
- * all environments, including v0's preview sandbox.
11
- */
12
-
13
- import { headers } from 'next/headers';
14
- import {
15
- localeToRegionMap,
16
- fallbackRegionId,
17
- supportedLocales,
18
- } from './regions-config';
19
-
20
- /**
21
- * ISO 3166-1 alpha-2 country code → BCP 47 locale mapping.
22
- */
23
- const COUNTRY_TO_LOCALE: Record<string, string> = {
24
- // English
25
- US: 'en', GB: 'en', AU: 'en', CA: 'en', IE: 'en', NZ: 'en', ZA: 'en',
26
- // Spanish
27
- ES: 'es', MX: 'es', AR: 'es', CO: 'es', CL: 'es', PE: 'es', VE: 'es',
28
- UY: 'es', EC: 'es', BO: 'es', PY: 'es', CR: 'es', GT: 'es', HN: 'es',
29
- SV: 'es', NI: 'es', PA: 'es', DO: 'es', CU: 'es',
30
- // French
31
- FR: 'fr', BE: 'fr', CH: 'fr', LU: 'fr', MC: 'fr',
32
- // German
33
- DE: 'de', AT: 'de',
34
- // Portuguese
35
- PT: 'pt', BR: 'pt',
36
- // Italian
37
- IT: 'it',
38
- // Dutch
39
- NL: 'nl',
40
- };
41
-
42
- /**
43
- * Detect a region ID from the request's IP geolocation headers.
44
- *
45
- * Detection cascade:
46
- * 1. Read country code from Vercel or Cloudflare header
47
- * 2. Map country code → locale
48
- * 3. Validate locale is supported (from generated regions-config)
49
- * 4. Map locale → regionId (from generated regions-config)
50
- * 5. Fallback: return fallbackRegionId
51
- */
52
- export async function getRegionFromIpHeaders(): Promise<string | undefined> {
53
- try {
54
- const headersList = await headers();
55
-
56
- const country =
57
- headersList.get('x-vercel-ip-country') ??
58
- headersList.get('cf-ipcountry');
59
-
60
- if (country) {
61
- const locale = COUNTRY_TO_LOCALE[country.toUpperCase()];
62
-
63
- if (locale && (supportedLocales as readonly string[]).includes(locale)) {
64
- const regionId = localeToRegionMap[locale];
65
- if (regionId) return regionId;
66
- }
67
- }
68
- } catch {
69
- // headers() is not available during static generation — silently fall through
70
- }
71
-
72
- return fallbackRegionId || undefined;
73
- }
@@ -1,53 +0,0 @@
1
- /**
2
- * @thorprovider/core - Region Provider (Next.js Wrapper)
3
- *
4
- * Framework-specific wrapper for RegionProvider from @thorprovider/providers.
5
- * Injects commerce instance via Dependency Injection.
6
- */
7
-
8
- 'use client';
9
-
10
- import React from 'react';
11
- import { RegionProvider, useRegion as useRegionBase } from '@thorprovider/providers';
12
- import { useCommerce } from './commerce-provider';
13
- import type { ReactNode } from 'react';
14
- import type { CommerceProvider as CommerceProviderType } from '@thorprovider/types';
15
-
16
- export type RegionContextValue = {
17
- region: any;
18
- regions: any[];
19
- setRegion: (regionId: string) => void;
20
- isLoading: boolean;
21
- error: Error | null;
22
- };
23
-
24
- interface ClientRegionProviderProps {
25
- children: ReactNode;
26
- /**
27
- * Region ID detected server-side from IP geolocation headers.
28
- * Passed through to RegionProvider as `initialRegionId`.
29
- * localStorage takes priority if the user has previously selected a region.
30
- */
31
- initialRegionId?: string;
32
- }
33
-
34
- export function ClientRegionProvider({ children, initialRegionId }: ClientRegionProviderProps) {
35
- const { provider: commerce } = useCommerce(); // Commerce from context
36
-
37
- return (
38
- <RegionProvider
39
- commerce={commerce as unknown as CommerceProviderType}
40
- locale="en"
41
- storage={typeof window !== 'undefined' ? localStorage : undefined}
42
- initialRegionId={initialRegionId}
43
- debug={process.env.NODE_ENV === 'development'}
44
- >
45
- {children}
46
- </RegionProvider>
47
- );
48
- }
49
-
50
- // Typed wrapper to avoid `never` inference in consuming app code.
51
- export function useRegion(): RegionContextValue {
52
- return useRegionBase() as unknown as RegionContextValue;
53
- }
@@ -1,48 +0,0 @@
1
- /**
2
- * Auto-generated Regions Configuration
3
- *
4
- * This file is automatically generated by scripts/generate-regions-config.ts
5
- * DO NOT EDIT MANUALLY - Your changes will be overwritten!
6
- *
7
- * ⚠️ FALLBACK CONFIG: No regions found in database!
8
- * This is a minimal configuration using English only.
9
- * Please ensure your backend has regions configured.
10
- * Generated: 2026-04-25T16:54:05.783Z
11
- *
12
- * To regenerate:
13
- * - Run: yarn generate:regions (from the package directory)
14
- * - Or: Build/dev will regenerate automatically (prebuild/predev hooks)
15
- *
16
- * This configuration maps locales to actual regions from your database,
17
- * ensuring users are only redirected to regions that actually exist.
18
- */
19
-
20
- /**
21
- * List of all supported locales
22
- * Determined by analyzing countries in each region
23
- */
24
- export const supportedLocales = [
25
- "en"
26
- ] as const;
27
-
28
- /**
29
- * Default locale to use when no match is found
30
- */
31
- export const defaultLocale = "en" as const;
32
-
33
- /**
34
- * Mapping from locale to region ID
35
- * This ensures locale-based routing maps to real database regions
36
- */
37
- export const localeToRegionMap: Record<string, string> = {};
38
-
39
- /**
40
- * Fallback region ID when no region is detected
41
- * Used as last resort if locale mapping fails
42
- */
43
- export const fallbackRegionId = undefined;
44
-
45
- /**
46
- * Type helper for supported locales
47
- */
48
- export type SupportedLocale = typeof supportedLocales[number];
@@ -1,54 +0,0 @@
1
- import { cache } from 'react';
2
- import { commerce } from './commerce';
3
- import { backendCircuitBreaker } from '@thorprovider/adapters';
4
- import type { StorefrontConfig } from '@thorprovider/types';
5
-
6
- /**
7
- * Named accent colors → oklch overrides for --accent CSS variable.
8
- * Keys match values returned by the Thor Commerce backend plugin.
9
- */
10
- const ACCENT_COLOR_MAP: Record<string, string> = {
11
- indigo: 'oklch(0.55 0.2 270)',
12
- blue: 'oklch(0.55 0.2 250)',
13
- red: 'oklch(0.55 0.2 25)',
14
- orange: 'oklch(0.65 0.2 50)',
15
- amber: 'oklch(0.7 0.18 80)',
16
- green: 'oklch(0.55 0.18 150)',
17
- teal: 'oklch(0.55 0.15 180)',
18
- purple: 'oklch(0.5 0.2 300)',
19
- pink: 'oklch(0.6 0.2 350)',
20
- slate: 'oklch(0.45 0.02 260)',
21
- };
22
-
23
- /**
24
- * Resolve a theme accent color name to a CSS oklch value.
25
- * Falls back to the raw value if not in the preset map (allows custom oklch/hex).
26
- */
27
- export function resolveAccentColor(color: string): string | undefined {
28
- if (!color) return undefined;
29
- return ACCENT_COLOR_MAP[color.toLowerCase()] ?? color;
30
- }
31
-
32
- /**
33
- * Fetch StorefrontConfig from the backend with circuit breaker protection.
34
- * Cached per React server request (deduped across components in the same render).
35
- *
36
- * Returns null when:
37
- * - The commerce provider does not implement getStorefrontConfig
38
- * - Required environment variables are not set (e.g. during CI build / SSG)
39
- * - The backend is unreachable (circuit breaker fallback)
40
- */
41
- export const getStorefrontConfig = cache(
42
- async (): Promise<StorefrontConfig | null> => {
43
- try {
44
- if (!commerce.getStorefrontConfig) return null;
45
- return backendCircuitBreaker.execute(
46
- () => commerce.getStorefrontConfig!(),
47
- null,
48
- );
49
- } catch {
50
- // Commerce not yet configured (missing env vars during SSG / CI build).
51
- return null;
52
- }
53
- },
54
- );
@@ -1,51 +0,0 @@
1
- import { execSync } from 'child_process';
2
- import { fileURLToPath } from 'url';
3
- import { dirname, relative, resolve } from 'path';
4
- import { existsSync } from 'fs';
5
-
6
- // Region generation is handled by prebuild/predev scripts in package.json.
7
- // next.config.mjs runs as a safety net ONLY during build/dev (not next start)
8
- // to support standalone projects that bypass npm lifecycle scripts.
9
- const isProductionServer = process.argv.includes('start');
10
-
11
- if (!isProductionServer) {
12
- try {
13
- const __filename = fileURLToPath(import.meta.url);
14
- const __dirname = dirname(__filename);
15
-
16
- // 1. Try local script first (standalone / exported project)
17
- const localScript = resolve(__dirname, 'scripts', 'generate-regions-config.ts');
18
- if (existsSync(localScript)) {
19
- execSync('tsx scripts/generate-regions-config.ts --package-dir="."', {
20
- stdio: 'inherit',
21
- cwd: __dirname,
22
- });
23
- } else {
24
- // 2. Try monorepo script (packages/core or projects/<name>)
25
- const monorepoRoot = resolve(__dirname, '..', '..');
26
- const monorepoScript = resolve(monorepoRoot, 'scripts', 'generate-regions-config.ts');
27
- if (existsSync(monorepoScript)) {
28
- const packageDir = relative(monorepoRoot, __dirname);
29
- execSync(`tsx ../../scripts/generate-regions-config.ts --package-dir="${packageDir}"`, {
30
- stdio: 'inherit',
31
- cwd: __dirname,
32
- });
33
- }
34
- }
35
- } catch (error) {
36
- console.warn('⚠ Failed to generate regions configuration:', error.message);
37
- }
38
- }
39
-
40
- /** @type {import('next').NextConfig} */
41
- const nextConfig = {
42
- transpilePackages: ['@thorprovider/components', '@thorprovider/adapters', '@thorprovider/types'],
43
- typescript: {
44
- ignoreBuildErrors: true,
45
- },
46
- images: {
47
- unoptimized: true,
48
- },
49
- };
50
-
51
- export default nextConfig;