@thorprovider/create-thor-app 2.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 (42) hide show
  1. package/README.md +470 -0
  2. package/dist/index.js +1054 -0
  3. package/package.json +46 -0
  4. package/templates/default/.env.example +56 -0
  5. package/templates/default/.eslintrc.json +43 -0
  6. package/templates/default/README.md +151 -0
  7. package/templates/default/app/api/revalidate/route.ts +64 -0
  8. package/templates/default/app/backend-unavailable/page.tsx +85 -0
  9. package/templates/default/app/error.tsx +58 -0
  10. package/templates/default/app/global-error.tsx +208 -0
  11. package/templates/default/app/globals.css +125 -0
  12. package/templates/default/app/layout.tsx +50 -0
  13. package/templates/default/app/not-found.tsx +31 -0
  14. package/templates/default/app/page.tsx +124 -0
  15. package/templates/default/components/providers/app-providers.tsx +77 -0
  16. package/templates/default/components/providers/navigation-provider.tsx +37 -0
  17. package/templates/default/config/site.config.ts +156 -0
  18. package/templates/default/docs/README.md +46 -0
  19. package/templates/default/docs/commerce-api.md +243 -0
  20. package/templates/default/docs/components.md +276 -0
  21. package/templates/default/docs/dependencies.md +53 -0
  22. package/templates/default/docs/patterns.md +100 -0
  23. package/templates/default/docs/project-structure.md +53 -0
  24. package/templates/default/docs/rules.md +51 -0
  25. package/templates/default/docs/types.md +329 -0
  26. package/templates/default/lib/auth-context.tsx +213 -0
  27. package/templates/default/lib/cart-provider.tsx +53 -0
  28. package/templates/default/lib/commerce-provider.tsx +48 -0
  29. package/templates/default/lib/commerce.ts +165 -0
  30. package/templates/default/lib/env.ts +147 -0
  31. package/templates/default/lib/region-detection.ts +80 -0
  32. package/templates/default/lib/region-provider.tsx +53 -0
  33. package/templates/default/lib/regions-config.ts +48 -0
  34. package/templates/default/lib/storefront-config.ts +54 -0
  35. package/templates/default/lib/utils.ts +10 -0
  36. package/templates/default/next-env.d.ts +6 -0
  37. package/templates/default/next.config.mjs +51 -0
  38. package/templates/default/package.json +42 -0
  39. package/templates/default/postcss.config.mjs +8 -0
  40. package/templates/default/proxy.ts +155 -0
  41. package/templates/default/scripts/generate-regions-config.ts +498 -0
  42. package/templates/default/tsconfig.json +43 -0
@@ -0,0 +1,165 @@
1
+ /**
2
+ * @thorprovider/core Commerce Configuration
3
+ *
4
+ * V0: COPY THIS FILE VERBATIM when creating starters or apps.
5
+ * This is the ONLY place where createProvider() should be called.
6
+ * NEVER call createProvider() in app/[locale]/layout.tsx or elsewhere.
7
+ * See: .v0/docs/v0_provider_chain.md
8
+ *
9
+ * This file initializes the commerce provider for Thor Commerce starters.
10
+ * It uses @thorprovider/adapters v2.0 to provide a unified API for e-commerce operations.
11
+ */
12
+
13
+ import { createProvider } from '@thorprovider/adapters';
14
+ import type { StorefrontContext, ProviderTypeString } from '@thorprovider/types';
15
+ import { isSupportedProviderType } from '@thorprovider/types';
16
+ import { getEnv, isEnvConfigured } from './env';
17
+
18
+ // Normalize backend URL so we never append paths to a value that ends with a slash.
19
+ function normalizeBackendUrl(value?: string): string | undefined {
20
+ if (!value) return undefined;
21
+ const trimmed = value.trim();
22
+ if (!trimmed) return undefined;
23
+ return trimmed.replace(/\/+$/, '');
24
+ }
25
+
26
+ // Lazy singleton — only initialized on first access at runtime, never during build.
27
+ // This allows @thorprovider/core to compile as a package template without env variables present.
28
+ let _commerce: ReturnType<typeof createProvider> | undefined;
29
+
30
+ function createCommerceInstance(): ReturnType<typeof createProvider> {
31
+ if (_commerce) return _commerce;
32
+
33
+ // Validate env now (throws with a clear Zod error if vars are missing).
34
+ // Runs only at runtime on first use, not during static build.
35
+ getEnv();
36
+
37
+ const rawProviderType = process.env.NEXT_PUBLIC_COMMERCE_PROVIDER || 'medusa';
38
+ if (!isSupportedProviderType(rawProviderType)) {
39
+ throw new Error(
40
+ `[INIT] Unsupported commerce provider: "${rawProviderType}". ` +
41
+ `Currently only "medusa" is implemented. ` +
42
+ `Please set NEXT_PUBLIC_COMMERCE_PROVIDER="medusa" in your environment variables.`
43
+ );
44
+ }
45
+
46
+ const providerType: ProviderTypeString = rawProviderType;
47
+ const baseUrl = normalizeBackendUrl(process.env.NEXT_PUBLIC_COMMERCE_API_URL)!;
48
+ const apiKey = process.env.NEXT_PUBLIC_COMMERCE_API_KEY!;
49
+
50
+ _commerce = createProvider({
51
+ provider: providerType,
52
+ config: {
53
+ baseUrl: baseUrl,
54
+ publishableKey: apiKey,
55
+ currencyCode: process.env.NEXT_PUBLIC_DEFAULT_CURRENCY || 'USD',
56
+ debug: process.env.NODE_ENV === 'development',
57
+
58
+ // Retry configuration - prevents "fetch failed" errors from temporary network issues
59
+ retry: {
60
+ maxRetries: 3, // Retry up to 3 times (4 attempts total)
61
+ timeoutMs: 10000, // 10 second timeout per request
62
+ initialDelayMs: 300, // Start with 300ms delay between retries
63
+ backoffMultiplier: 2, // Double the delay each retry (300ms, 600ms, 1200ms)
64
+ maxDelayMs: 5000, // Cap delay at 5 seconds
65
+ },
66
+
67
+ // Authentication configuration
68
+ auth: {
69
+ method: 'jwt', // Use JWT tokens (stored in localStorage on client)
70
+ storage: 'localStorage', // Store tokens in browser localStorage
71
+ },
72
+
73
+ // Admin API configuration (passed to @thorprovider/adapters for inventory + admin dashboard operations)
74
+ // Only configured when API key is present in env
75
+ adminConfig: process.env.COMMERCE_ADMIN_API_KEY
76
+ ? {
77
+ apiKey: process.env.COMMERCE_ADMIN_API_KEY,
78
+ }
79
+ : undefined,
80
+ },
81
+ });
82
+
83
+ return _commerce;
84
+ }
85
+
86
+ /**
87
+ * Commerce provider instance
88
+ *
89
+ * Transparent Proxy — defers instantiation (and env validation) until first method call.
90
+ * This allows @thorprovider/core to compile as a package template without environment variables.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * import { commerce } from '@/lib/commerce';
95
+ *
96
+ * // Fetch products
97
+ * const products = await commerce.getProducts();
98
+ *
99
+ * // Create cart
100
+ * const cart = await commerce.createCart();
101
+ * ```
102
+ */
103
+ export const commerce = new Proxy({} as ReturnType<typeof createProvider>, {
104
+ get(_target, prop: string | symbol) {
105
+ // During build/SSG without env vars, return undefined for property checks
106
+ // and no-op async functions for method calls — prevents build failures.
107
+ if (!isEnvConfigured()) {
108
+ return undefined;
109
+ }
110
+ return createCommerceInstance()[prop as keyof ReturnType<typeof createProvider>];
111
+ },
112
+ });
113
+
114
+ /**
115
+ * Initialize storefront context on app startup.
116
+ *
117
+ * Validates that the storefront/sales channel is configured and reachable.
118
+ * For providers where storefront is mandatory (e.g. Medusa), a missing or
119
+ * invalid configuration will throw a `StorefrontConfigError`.
120
+ *
121
+ * MUST be called once before any commerce operation that depends on
122
+ * storefront isolation (product listing, cart creation, etc.).
123
+ *
124
+ * @returns StorefrontContext for the current storefront
125
+ * @throws {StorefrontConfigError} if configuration is invalid and required
126
+ */
127
+ export async function initializeStorefront(): Promise<StorefrontContext> {
128
+ try {
129
+ const context = await commerce.getStorefrontContext();
130
+ return context;
131
+ } catch (error) {
132
+ if (commerce.isStorefrontRequired()) {
133
+ throw error;
134
+ }
135
+
136
+ // Provider allows optional storefront; use safe defaults
137
+ const rawProvider = (process.env.NEXT_PUBLIC_COMMERCE_PROVIDER || 'medusa') as ProviderTypeString;
138
+ return {
139
+ id: 'default',
140
+ name: 'Default Storefront',
141
+ platformType: rawProvider,
142
+ requiresProductScoping: false,
143
+ currencyCode: process.env.NEXT_PUBLIC_DEFAULT_CURRENCY || 'USD',
144
+ };
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Re-export types from @thorprovider/adapters for convenience
150
+ */
151
+ export type {
152
+ Product,
153
+ ProductVariant,
154
+ Cart,
155
+ CartItem,
156
+ Collection,
157
+ BackendCapabilities,
158
+ CommerceProvider,
159
+ StorefrontContext,
160
+ } from '@thorprovider/adapters';
161
+
162
+ /**
163
+ * Re-export React provider and hooks
164
+ */
165
+ export { ClientCommerceProvider, useCommerce, useCapabilities } from './commerce-provider';
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Environment Variable Validation (Zod Schema)
3
+ *
4
+ * FROZEN: This schema validates all required environment variables on application startup.
5
+ * Changes must be approved by the architecture team to maintain consistency across starters.
6
+ *
7
+ * Usage in components/lib/commerce.ts:
8
+ * import { env } from './env';
9
+ * const { baseUrl, apiKey } = env;
10
+ *
11
+ * The validated env object is re-exported at module scope to catch errors during build.
12
+ */
13
+
14
+ import { z } from 'zod';
15
+
16
+ /**
17
+ * Schema for environment variables
18
+ * Required vars: throw error on startup
19
+ * Optional vars: only validated if provided
20
+ */
21
+ export const EnvSchema = z.object({
22
+ // Commerce Provider Configuration (REQUIRED)
23
+ NEXT_PUBLIC_COMMERCE_PROVIDER: z
24
+ .enum(['medusa', 'shopify', 'bigcommerce', 'custom'])
25
+ .default('medusa')
26
+ .describe('Commerce backend provider (defaults to medusa)'),
27
+
28
+ NEXT_PUBLIC_COMMERCE_API_URL: z
29
+ .string()
30
+ .url()
31
+ .describe('Your commerce backend API base URL (Medusa, Shopify, etc.)'),
32
+
33
+ NEXT_PUBLIC_COMMERCE_API_KEY: z
34
+ .string()
35
+ .min(1)
36
+ .describe('Public API key for commerce backend'),
37
+
38
+ // Currency (REQUIRED — defaults to USD)
39
+ NEXT_PUBLIC_DEFAULT_CURRENCY: z
40
+ .string()
41
+ .default('USD')
42
+ .describe('Default currency code (e.g., "USD", "EUR")'),
43
+
44
+ // Health Check (OPTIONAL — used by proxy.ts circuit breaker)
45
+ HEALTH_CHECK_PATH: z
46
+ .string()
47
+ .default('/store/regions')
48
+ .describe('Path used by proxy.ts to verify backend availability'),
49
+
50
+ // Sales Channel (OPTIONAL — multi-tenant stores)
51
+ NEXT_PUBLIC_SALES_CHANNEL_ID: z
52
+ .string()
53
+ .optional()
54
+ .describe('Sales channel ID for multi-tenant stores (required for Medusa)'),
55
+
56
+ // Admin API (OPTIONAL)
57
+ COMMERCE_ADMIN_EMAIL: z
58
+ .string()
59
+ .email()
60
+ .optional()
61
+ .describe('Admin email for backend admin API'),
62
+
63
+ COMMERCE_ADMIN_PASSWORD: z
64
+ .string()
65
+ .min(1)
66
+ .optional()
67
+ .describe('Admin password for backend admin API'),
68
+
69
+ COMMERCE_ADMIN_API_URL: z
70
+ .string()
71
+ .url()
72
+ .optional()
73
+ .describe('Commerce backend admin API URL (defaults to NEXT_PUBLIC_COMMERCE_API_URL)'),
74
+
75
+ COMMERCE_ADMIN_TOKEN_TTL_MS: z
76
+ .string()
77
+ .optional()
78
+ .transform(v => v ? Number.parseInt(v, 10) : undefined)
79
+ .describe('Admin token TTL in milliseconds'),
80
+
81
+ // Webhook Revalidation (OPTIONAL)
82
+ FRONTEND_WEBHOOK_SECRET: z
83
+ .string()
84
+ .optional()
85
+ .describe('Shared secret for backend webhook revalidation (must match backend FRONTEND_WEBHOOK_SECRET)'),
86
+ });
87
+
88
+ export type Env = z.infer<typeof EnvSchema>;
89
+
90
+ /**
91
+ * Check whether required commerce env vars are present.
92
+ * Used to bail out gracefully during build/SSG when no backend is configured.
93
+ */
94
+ export function isEnvConfigured(): boolean {
95
+ return Boolean(
96
+ process.env.NEXT_PUBLIC_COMMERCE_API_URL &&
97
+ process.env.NEXT_PUBLIC_COMMERCE_API_KEY
98
+ );
99
+ }
100
+
101
+ /**
102
+ * Validate and return environment variables.
103
+ * Throws detailed error if validation fails at runtime.
104
+ *
105
+ * IMPORTANT: Each env var is referenced individually via process.env.X so that
106
+ * Next.js can statically replace NEXT_PUBLIC_* values in the client bundle.
107
+ * Passing the whole process.env object to Zod would break client-side validation
108
+ * because Next.js only inlines individual property accesses.
109
+ *
110
+ * @throws {Error} if required env vars are missing or invalid
111
+ */
112
+ export function getEnv(): Env {
113
+ try {
114
+ return EnvSchema.parse({
115
+ NEXT_PUBLIC_COMMERCE_PROVIDER: process.env.NEXT_PUBLIC_COMMERCE_PROVIDER,
116
+ NEXT_PUBLIC_COMMERCE_API_URL: process.env.NEXT_PUBLIC_COMMERCE_API_URL,
117
+ NEXT_PUBLIC_COMMERCE_API_KEY: process.env.NEXT_PUBLIC_COMMERCE_API_KEY,
118
+ NEXT_PUBLIC_DEFAULT_CURRENCY: process.env.NEXT_PUBLIC_DEFAULT_CURRENCY,
119
+ HEALTH_CHECK_PATH: process.env.HEALTH_CHECK_PATH,
120
+ NEXT_PUBLIC_SALES_CHANNEL_ID: process.env.NEXT_PUBLIC_SALES_CHANNEL_ID,
121
+ COMMERCE_ADMIN_EMAIL: process.env.COMMERCE_ADMIN_EMAIL,
122
+ COMMERCE_ADMIN_PASSWORD: process.env.COMMERCE_ADMIN_PASSWORD,
123
+ COMMERCE_ADMIN_API_URL: process.env.COMMERCE_ADMIN_API_URL,
124
+ COMMERCE_ADMIN_TOKEN_TTL_MS: process.env.COMMERCE_ADMIN_TOKEN_TTL_MS,
125
+ FRONTEND_WEBHOOK_SECRET: process.env.FRONTEND_WEBHOOK_SECRET,
126
+ });
127
+ } catch (error) {
128
+ if (error instanceof z.ZodError) {
129
+ const issues = error.issues
130
+ .map(issue => ` - ${issue.path.join('.')}: ${issue.message}`)
131
+ .join('\n');
132
+ throw new Error(
133
+ `Invalid environment variables:\n${issues}\n\n` +
134
+ `See .env.example for correct format.`
135
+ );
136
+ }
137
+ throw error;
138
+ }
139
+ }
140
+
141
+ // Lazy getter — call getEnv() at runtime, not at module scope (avoids build-time failures
142
+ // when @thorprovider/core is compiled as a package template without environment variables).
143
+ export const env: Env = new Proxy({} as Env, {
144
+ get(_target, prop: string | symbol) {
145
+ return getEnv()[prop as keyof Env];
146
+ },
147
+ });
@@ -0,0 +1,80 @@
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.
9
+ *
10
+ * **Important: Import paths matter**
11
+ * The generated file at `lib/regions-config.ts` uses RELATIVE imports (./regions-config)
12
+ * not bare paths like '../src/generated/...'. This is critical for V0 compatibility:
13
+ * - V0's bundler sandbox cannot resolve bare path imports
14
+ * - Only relative imports (../, ./) and node_modules work in V0's ESBuild bundler
15
+ * - Local bundlers (Turbopack, webpack) handle bare paths, but V0 is stricter
16
+ *
17
+ * If you move this file or change imports, always use relative paths!
18
+ */
19
+
20
+ import { headers } from 'next/headers';
21
+ import {
22
+ localeToRegionMap,
23
+ fallbackRegionId,
24
+ supportedLocales,
25
+ } from './regions-config';
26
+
27
+ /**
28
+ * ISO 3166-1 alpha-2 country code → BCP 47 locale mapping.
29
+ */
30
+ const COUNTRY_TO_LOCALE: Record<string, string> = {
31
+ // English
32
+ US: 'en', GB: 'en', AU: 'en', CA: 'en', IE: 'en', NZ: 'en', ZA: 'en',
33
+ // Spanish
34
+ ES: 'es', MX: 'es', AR: 'es', CO: 'es', CL: 'es', PE: 'es', VE: 'es',
35
+ UY: 'es', EC: 'es', BO: 'es', PY: 'es', CR: 'es', GT: 'es', HN: 'es',
36
+ SV: 'es', NI: 'es', PA: 'es', DO: 'es', CU: 'es',
37
+ // French
38
+ FR: 'fr', BE: 'fr', CH: 'fr', LU: 'fr', MC: 'fr',
39
+ // German
40
+ DE: 'de', AT: 'de',
41
+ // Portuguese
42
+ PT: 'pt', BR: 'pt',
43
+ // Italian
44
+ IT: 'it',
45
+ // Dutch
46
+ NL: 'nl',
47
+ };
48
+
49
+ /**
50
+ * Detect a region ID from the request's IP geolocation headers.
51
+ *
52
+ * Detection cascade:
53
+ * 1. Read country code from Vercel or Cloudflare header
54
+ * 2. Map country code → locale
55
+ * 3. Validate locale is supported (from generated regions-config)
56
+ * 4. Map locale → regionId (from generated regions-config)
57
+ * 5. Fallback: return fallbackRegionId
58
+ */
59
+ export async function getRegionFromIpHeaders(): Promise<string | undefined> {
60
+ try {
61
+ const headersList = await headers();
62
+
63
+ const country =
64
+ headersList.get('x-vercel-ip-country') ??
65
+ headersList.get('cf-ipcountry');
66
+
67
+ if (country) {
68
+ const locale = COUNTRY_TO_LOCALE[country.toUpperCase()];
69
+
70
+ if (locale && (supportedLocales as readonly string[]).includes(locale)) {
71
+ const regionId = localeToRegionMap[locale];
72
+ if (regionId) return regionId;
73
+ }
74
+ }
75
+ } catch {
76
+ // headers() is not available during static generation — silently fall through
77
+ }
78
+
79
+ return fallbackRegionId || undefined;
80
+ }
@@ -0,0 +1,53 @@
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
+ }
@@ -0,0 +1,48 @@
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-24T18:34:12.555Z
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];
@@ -0,0 +1,54 @@
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
+ );
@@ -0,0 +1,10 @@
1
+ import { clsx, type ClassValue } from 'clsx'
2
+ import { twMerge } from 'tailwind-merge'
3
+
4
+ /**
5
+ * Merge Tailwind CSS class names safely.
6
+ * Deduplicates conflicting utilities (e.g. `p-4` vs `p-2` → keeps last).
7
+ */
8
+ export function cn(...inputs: ClassValue[]) {
9
+ return twMerge(clsx(inputs))
10
+ }
@@ -0,0 +1,6 @@
1
+ /// <reference types="next" />
2
+ /// <reference types="next/image-types/global" />
3
+ import "./.next/types/routes.d.ts";
4
+
5
+ // NOTE: This file should not be edited
6
+ // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
@@ -0,0 +1,51 @@
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;
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@thorprovider/core",
3
+ "version": "1.0.3",
4
+ "description": "Thor Commerce core infrastructure template. Used as base for V0-generated starters.",
5
+ "scripts": {
6
+ "prebuild": "PACKAGE_DIR=packages/core tsx ../../scripts/generate-regions-config.ts",
7
+ "build": "next build",
8
+ "predev": "PACKAGE_DIR=packages/core tsx ../../scripts/generate-regions-config.ts",
9
+ "dev": "next dev",
10
+ "start": "next start",
11
+ "type-check": "tsc --noEmit",
12
+ "generate:regions": "PACKAGE_DIR=packages/core tsx ../../scripts/generate-regions-config.ts",
13
+ "generate:agent-index": "node ../../scripts/generate-core-agents-index.cjs"
14
+ },
15
+ "dependencies": {
16
+ "@thorprovider/adapters": "^3.0.2",
17
+ "@thorprovider/components": "^1.0.2",
18
+ "@thorprovider/providers": "^1.0.2",
19
+ "@thorprovider/types": "^2.0.2",
20
+ "clsx": "^2.1.1",
21
+ "next": "16.0.10",
22
+ "react": "19.2.0",
23
+ "react-dom": "19.2.0",
24
+ "tailwind-merge": "^3.3.1"
25
+ },
26
+ "devDependencies": {
27
+ "@tailwindcss/postcss": "^4.1.9",
28
+ "@types/node": "^22",
29
+ "@types/react": "^19",
30
+ "@types/react-dom": "^19",
31
+ "postcss": "^8.5",
32
+ "tailwindcss": "^4.1.9",
33
+ "tsx": "^4.19.2",
34
+ "tw-animate-css": "1.3.3",
35
+ "typescript": "^5"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/thorprovider/thor-commerce",
40
+ "directory": "packages/core"
41
+ }
42
+ }
@@ -0,0 +1,8 @@
1
+ /** @type {import('postcss-load-config').Config} */
2
+ const config = {
3
+ plugins: {
4
+ '@tailwindcss/postcss': {},
5
+ },
6
+ }
7
+
8
+ export default config