@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
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@thorprovider/create-thor-app",
3
+ "version": "2.1.0",
4
+ "description": "CLI to scaffold a new Thor Commerce application from @thorprovider/core template",
5
+ "type": "module",
6
+ "bin": "./dist/index.js",
7
+ "main": "dist/index.js",
8
+ "files": [
9
+ "dist",
10
+ "templates"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18.17.0"
14
+ },
15
+ "scripts": {
16
+ "build": "tsup",
17
+ "dev": "tsup --watch",
18
+ "type-check": "tsc --noEmit"
19
+ },
20
+ "dependencies": {
21
+ "commander": "^13.1.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^22.0.0",
25
+ "tsup": "^8.0.0",
26
+ "typescript": "^5.0.0"
27
+ },
28
+ "publishConfig": {
29
+ "access": "restricted",
30
+ "registry": "https://registry.npmjs.org/"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/thorprovider/thor-commerce",
35
+ "directory": "packages/create-thor-app"
36
+ },
37
+ "keywords": [
38
+ "thor-commerce",
39
+ "nextjs",
40
+ "ecommerce",
41
+ "scaffolding",
42
+ "cli",
43
+ "create-app"
44
+ ],
45
+ "license": "MIT"
46
+ }
@@ -0,0 +1,56 @@
1
+ # ============================================================================
2
+ # Thor Commerce Core Template — Environment Configuration
3
+ # ============================================================================
4
+ # Copy this file to .env and fill in your values.
5
+ # ============================================================================
6
+
7
+ # ---------------------------------------------------------------------------
8
+ # Commerce Backend (required)
9
+ # ---------------------------------------------------------------------------
10
+ # Which commerce platform to use: medusa | shopify | bigcommerce | custom
11
+ NEXT_PUBLIC_COMMERCE_PROVIDER=medusa
12
+ # Your commerce backend API URL (e.g., Medusa, Shopify, custom provider)
13
+ NEXT_PUBLIC_COMMERCE_API_URL=http://localhost:9000
14
+ NEXT_PUBLIC_COMMERCE_API_KEY=your-publishable-api-key
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Default Currency
18
+ # ---------------------------------------------------------------------------
19
+ NEXT_PUBLIC_DEFAULT_CURRENCY=USD
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Health Check
23
+ # ---------------------------------------------------------------------------
24
+ # Path used by proxy.ts to verify backend availability.
25
+ # Example for Medusa: /store/regions
26
+ # Consult your backend provider's API docs for the appropriate endpoint.
27
+ HEALTH_CHECK_PATH=/store/regions
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Region Script Retry Policy
31
+ # ---------------------------------------------------------------------------
32
+ REGIONS_SCRIPT_MAX_RETRIES=3
33
+ REGIONS_SCRIPT_RETRY_DELAY=1000
34
+ REGIONS_SCRIPT_RETRY_MAX_DELAY=10000
35
+ REGIONS_SCRIPT_RETRY_BACKOFF=2
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Admin API (optional)
39
+ # ---------------------------------------------------------------------------
40
+ # COMMERCE_ADMIN_EMAIL=admin@example.com
41
+ # COMMERCE_ADMIN_PASSWORD=your-admin-password
42
+ # COMMERCE_ADMIN_API_URL=http://localhost:9000
43
+ # COMMERCE_ADMIN_TOKEN_TTL_MS=3600000
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Sales Channel (optional — multi-tenant stores)
47
+ # ---------------------------------------------------------------------------
48
+ # NEXT_PUBLIC_SALES_CHANNEL_ID=sc_01...
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Webhook Revalidation (optional — Thor Commerce plugin)
52
+ # ---------------------------------------------------------------------------
53
+ # Shared secret used by the backend to authenticate webhook calls.
54
+ # Must match the FRONTEND_WEBHOOK_SECRET configured in the Medusa backend.
55
+ # FRONTEND_WEBHOOK_SECRET=your-shared-webhook-secret
56
+
@@ -0,0 +1,43 @@
1
+ {
2
+ "extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
3
+ "rules": {
4
+ // FROZEN: Prevent L3 components from importing directly from 'next/'
5
+ // Instead, they must use abstractions from @thorprovider/providers (useNavigation, useImage, etc.)
6
+ "no-restricted-imports": [
7
+ "error",
8
+ {
9
+ "patterns": [
10
+ {
11
+ "group": ["next/link", "next/image", "next/router"],
12
+ "message": "L3 components must use useNavigation() from @thorprovider/providers instead of importing next/link directly. This maintains abstraction layers and allows V0 to generate provider-agnostic code.",
13
+ "importNames": ["default"]
14
+ },
15
+ {
16
+ "group": ["next/*"],
17
+ "importNames": ["default"],
18
+ "message": "L3 components should avoid importing from 'next/' directly. Use abstractions from @thorprovider/providers instead.",
19
+ "allowTransitive": true
20
+ }
21
+ ]
22
+ }
23
+ ],
24
+
25
+ // FROZEN: Prevent hardcoded colors (require CSS variables instead)
26
+ "@typescript-eslint/no-unused-expressions": "off",
27
+ "no-restricted-syntax": [
28
+ "error",
29
+ {
30
+ "selector": "ObjectExpression > Property[key.name='color'][value.type='Literal'][value.value=/^#[0-9a-fA-F]+$/]",
31
+ "message": "Hardcoded hex colors are not allowed. Use CSS custom properties via style={{ color: 'var(--color-name)' }} instead."
32
+ }
33
+ ]
34
+ },
35
+ "overrides": [
36
+ {
37
+ "files": ["app/global-error.tsx"],
38
+ "rules": {
39
+ "no-restricted-imports": "off"
40
+ }
41
+ }
42
+ ]
43
+ }
@@ -0,0 +1,151 @@
1
+ # [App Name]
2
+
3
+ Next.js 16 storefront with headless commerce. Commerce, auth, i18n, and theming are pre-configured via `@thorprovider/*` packages — just connect your backend and build features.
4
+
5
+ ---
6
+
7
+ ## 🚀 Development Workflow
8
+
9
+ ### Step 1: Create the App (Local)
10
+
11
+ ```bash
12
+ # Minimal
13
+ yarn create:app --name my-store
14
+
15
+ # With backend pre-configured
16
+ yarn create:app --name my-store \
17
+ --commerce-provider medusa \
18
+ --commerce-api-url https://your-backend.com \
19
+ --commerce-api-key pk_live_xxx \
20
+ --preset electro \
21
+ --site-url https://my-store.com \
22
+ --generate-regions
23
+
24
+ cd projects/my-store
25
+ ```
26
+
27
+ This command:
28
+ - Clones `@thorprovider/core` into `projects/my-store/`
29
+ - Installs dependencies
30
+ - Generates `.env` from `.env.example` (backend flags inject values directly)
31
+ - Patches `config/site.config.ts` with `--preset` and `--site-url` if provided
32
+ - Optionally runs region generation (`--generate-regions`) to pre-populate `lib/regions-config.ts`
33
+ - Initializes git with an initial commit
34
+ - Generates `.v0-context.md` (contains frozen architecture files)
35
+
36
+ **Configure your backend** (if you didn't use CLI flags):
37
+ ```bash
38
+ nano .env
39
+ # Set: NEXT_PUBLIC_COMMERCE_API_URL=https://your-backend.com
40
+ # NEXT_PUBLIC_COMMERCE_API_KEY=pk_live_xxx
41
+ ```
42
+
43
+ **Test locally:**
44
+ ```bash
45
+ yarn dev
46
+ # → http://localhost:3000
47
+ ```
48
+
49
+ ### Step 2: Connect to GitHub
50
+
51
+ 1. Create a new repo on GitHub (without README, .gitignore, or license)
52
+ 2. In your local app directory, add the remote and push:
53
+
54
+ ```bash
55
+ git remote add origin https://github.com/your-org/your-repo.git
56
+ git branch -M main
57
+ git push -u origin main
58
+ ```
59
+
60
+ This repository is auto-generated by `create:app` from `@thorprovider/core`—it contains frozen architecture files that **must not be modified manually**. See "Frozen Files" below.
61
+
62
+ ### Step 3: Use V0 for Feature Development
63
+
64
+ 1. **Copy `.v0-context.md`** (in this repo root) into your first message on [v0.app](https://v0.app)
65
+ 2. **Connect your GitHub repo** to V0 (V0 will pull from the remote)
66
+ 3. **Paste the entire `.v0-context.md`** — it tells V0 which files are frozen and which patterns to follow
67
+ 4. **Describe your feature** in subsequent messages (e.g., "Add product filters to the product list page")
68
+ 5. **V0 generates code** respecting the frozen architecture and `@thorprovider/*` package constraints
69
+ 6. **Review the PR**, merge to main, and deploy to Vercel
70
+
71
+ Example first message on v0.app:
72
+ ```
73
+ [Paste full .v0-context.md here]
74
+
75
+ Now, create a product filter sidebar for the /products page that filters by category and price range.
76
+ ```
77
+
78
+ ### Step 4: Deploy
79
+
80
+ After merging changes to main, deployment happens automatically (if you've connected Vercel).
81
+
82
+ ---
83
+
84
+ ## 🔒 Frozen Files (Do NOT Modify)
85
+
86
+ These files define the app's architecture and are **frozen by design**. V0 respects these; you must too:
87
+
88
+ | File | Purpose |
89
+ |------|---------|
90
+ | `lib/commerce.ts` | Commerce provider initialization (singleton) |
91
+ | `lib/commerce-provider.tsx` | CommerceProvider context wrapper |
92
+ | `lib/region-provider.tsx` | RegionProvider context wrapper |
93
+ | `lib/auth-context.tsx` | Authentication context |
94
+ | `lib/cart-provider.tsx` | CartProvider context wrapper |
95
+ | `components/providers/app-providers.tsx` | Provider hierarchy (order is critical) |
96
+ | `components/providers/navigation-provider.tsx` | NavigationProvider wrapper |
97
+ | `app/[locale]/layout.tsx` | Root layout (passes `initialRegionId` to AppProviders) |
98
+ | `src/i18n/routing.ts` | i18n routing config |
99
+ | `config/site.config.ts` | Site configuration (values can change, shape is frozen) |
100
+
101
+ **Why frozen?** Changing these breaks the L1–L5 architecture. If you need to modify one, you're likely breaking a constraint. Read `docs/rules.md` first.
102
+
103
+ ---
104
+
105
+ ## What's Pre-Configured
106
+
107
+ - i18n via next-intl (add locales in `src/i18n/routing.ts` + `messages/`)
108
+ - Regional commerce (IP-based region + currency detection)
109
+ - **V0 Note:** Region config (`lib/regions-config.ts`) uses relative imports for v0 preview compatibility. Never change imports to bare paths.
110
+ - Shopping cart (persistent, backend-synced)
111
+ - Authentication (JWT)
112
+ - Dark mode + CSS token theming
113
+ - Circuit breaker (auto-fallback when backend is unavailable)
114
+ - `@thorprovider/components` UI library (55 accessible components)
115
+
116
+ ## 📚 Documentation
117
+
118
+ ### For Humans (You)
119
+
120
+ Read in this order:
121
+ 1. **[docs/README.md](docs/README.md)** — Overview + capabilities
122
+ 2. **[docs/project-structure.md](docs/project-structure.md)** — Where files live
123
+ 3. **[docs/patterns.md](docs/patterns.md)** — How to write pages, fetch data, style components
124
+
125
+ ### For V0 / AI Agents
126
+
127
+ **Copy `.v0-context.md` to V0's first message.** It includes:
128
+ - Frozen architecture files (do not modify)
129
+ - Type shapes for all domain objects
130
+ - Method signatures for all `commerce.*` calls
131
+ - Pre-commit checklist
132
+
133
+ **Then read `docs/` in order:**
134
+ 1. [docs/project-structure.md](docs/project-structure.md)
135
+ 2. [docs/dependencies.md](docs/dependencies.md) — 55 available components
136
+ 3. [docs/types.md](docs/types.md) — Product, Cart, Order, Customer, Address shapes
137
+ 4. [docs/commerce-api.md](docs/commerce-api.md) — getProducts(), createCart(), etc.
138
+ 5. [docs/patterns.md](docs/patterns.md) — Server/client, fetch patterns
139
+ 6. [docs/rules.md](docs/rules.md) — Non-negotiable constraints
140
+
141
+ ## Deployment
142
+
143
+ **Vercel:** Connect repo → set env vars (`NEXT_PUBLIC_COMMERCE_API_URL`, `NODE_AUTH_TOKEN`) → deploy.
144
+
145
+ **Self-hosted:** `yarn build && yarn start` with env vars set in host.
146
+
147
+ ## Troubleshooting
148
+
149
+ **`Module not found: @thorprovider/*`** → Verify `NODE_AUTH_TOKEN` has `read:packages` scope, then `yarn install`.
150
+
151
+ **Backend unavailable / circuit breaker** → Check `NEXT_PUBLIC_COMMERCE_API_URL` and network connectivity. Auto-resets after 60s.
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Webhook Revalidation Route
3
+ *
4
+ * Receives webhook events from the Thor Commerce backend plugin
5
+ * and triggers ISR revalidation for the affected pages/tags.
6
+ *
7
+ * Events handled:
8
+ * - `site_config.updated` — revalidates site-config tag
9
+ * - `storefront_config.updated` — revalidates storefront-config tag
10
+ * - `sales_channel.updated` — revalidates all
11
+ *
12
+ * Security: Validates `x-webhook-secret` header against FRONTEND_WEBHOOK_SECRET.
13
+ */
14
+
15
+ import { revalidatePath, revalidateTag } from 'next/cache';
16
+ import { NextRequest, NextResponse } from 'next/server';
17
+
18
+ export async function POST(req: NextRequest) {
19
+ const expectedSecret = process.env.FRONTEND_WEBHOOK_SECRET;
20
+
21
+ // Reject if secret is not configured — endpoint is effectively disabled
22
+ if (!expectedSecret) {
23
+ return NextResponse.json({ message: 'Webhook not configured' }, { status: 503 });
24
+ }
25
+
26
+ const secret = req.headers.get('x-webhook-secret');
27
+
28
+ if (!secret || secret !== expectedSecret) {
29
+ return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
30
+ }
31
+
32
+ let body: { event?: string; sales_channel_id?: string; timestamp?: string };
33
+ try {
34
+ body = await req.json();
35
+ } catch {
36
+ return NextResponse.json({ message: 'Invalid JSON body' }, { status: 400 });
37
+ }
38
+
39
+ const event = body.event ?? 'unknown';
40
+
41
+ // Revalidate cache tags based on event type
42
+ switch (event) {
43
+ case 'site_config.updated':
44
+ revalidateTag('site-config', 'max');
45
+ break;
46
+ case 'storefront_config.updated':
47
+ revalidateTag('storefront-config', 'max');
48
+ break;
49
+ case 'sales_channel.updated':
50
+ revalidateTag('site-config', 'max');
51
+ revalidateTag('storefront-config', 'max');
52
+ break;
53
+ default:
54
+ // Unknown event — revalidate everything as a safety net
55
+ revalidateTag('site-config', 'max');
56
+ revalidateTag('storefront-config', 'max');
57
+ break;
58
+ }
59
+
60
+ // Also revalidate the root path for any static pages
61
+ revalidatePath('/');
62
+
63
+ return NextResponse.json({ revalidated: true, event });
64
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Backend Unavailable Page
3
+ *
4
+ * Shown when the proxy.ts health check detects the commerce backend is unreachable.
5
+ * Self-contained — zero dependency on providers or @thorprovider/components because the
6
+ * provider chain itself may be what failed.
7
+ *
8
+ * Privacy:
9
+ * - Development: shows backend URL being checked + troubleshooting steps.
10
+ * - Production: generic message only — no internal URLs or env var names exposed.
11
+ */
12
+
13
+ import Link from 'next/link'
14
+
15
+ export default async function BackendUnavailablePage({
16
+ searchParams,
17
+ }: {
18
+ searchParams: Promise<{ returnTo?: string }>
19
+ }) {
20
+ const { returnTo } = await searchParams
21
+ const isDev = process.env.NODE_ENV === 'development'
22
+
23
+ return (
24
+ <div className="flex flex-col items-center justify-center min-h-[70vh] px-6 py-16 text-center font-sans">
25
+ {/* Icon */}
26
+ <div className="w-14 h-14 rounded-full bg-amber-100 flex items-center justify-center mb-5">
27
+ <svg
28
+ xmlns="http://www.w3.org/2000/svg"
29
+ width="28"
30
+ height="28"
31
+ viewBox="0 0 24 24"
32
+ fill="none"
33
+ stroke="currentColor"
34
+ strokeWidth="2"
35
+ strokeLinecap="round"
36
+ strokeLinejoin="round"
37
+ className="text-amber-600"
38
+ >
39
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
40
+ <line x1="12" x2="12" y1="9" y2="13" />
41
+ <line x1="12" x2="12.01" y1="17" y2="17" />
42
+ </svg>
43
+ </div>
44
+
45
+ <h1 className="text-xl font-semibold text-foreground mb-2">
46
+ Service Temporarily Unavailable
47
+ </h1>
48
+
49
+ <p className="text-muted-foreground max-w-[440px] leading-relaxed mb-6">
50
+ We&apos;re unable to reach our servers right now. This is usually
51
+ temporary — please try again in a moment.
52
+ </p>
53
+
54
+ {/* Dev-only troubleshooting — never rendered in production builds */}
55
+ {isDev && (
56
+ <div className="bg-muted border border-border rounded-md p-4 mb-6 max-w-[480px] text-left text-sm">
57
+ <p className="font-medium text-foreground mb-2">
58
+ Development Troubleshooting
59
+ </p>
60
+ <ul className="list-disc pl-5 space-y-1.5 text-muted-foreground text-xs">
61
+ <li>
62
+ Verify <code className="bg-background px-1 rounded text-[11px]">NEXT_PUBLIC_COMMERCE_API_URL</code> in{' '}
63
+ <code className="bg-background px-1 rounded text-[11px]">.env.local</code>
64
+ </li>
65
+ <li>Confirm the backend server is running and reachable</li>
66
+ <li>
67
+ Check <code className="bg-background px-1 rounded text-[11px]">HEALTH_CHECK_PATH</code> matches
68
+ a valid endpoint on your backend
69
+ </li>
70
+ <li>The circuit breaker auto-resets after 60 seconds</li>
71
+ </ul>
72
+ </div>
73
+ )}
74
+
75
+ <div className="flex gap-3">
76
+ <Link
77
+ href={returnTo || '/'}
78
+ className="px-5 py-2 bg-primary text-primary-foreground rounded-md no-underline text-sm font-medium hover:bg-primary/90 transition-colors"
79
+ >
80
+ Try Again
81
+ </Link>
82
+ </div>
83
+ </div>
84
+ )
85
+ }
@@ -0,0 +1,58 @@
1
+ 'use client'
2
+
3
+ /**
4
+ * Locale-Level Error Boundary
5
+ *
6
+ * Catches errors thrown inside app/[locale]/layout.tsx provider chain
7
+ * (RegionProvider, AuthProvider, CartProvider failures).
8
+ *
9
+ * Self-contained — does not import from @/components/ so it can render
10
+ * even when the component tree that caused the error cannot.
11
+ */
12
+
13
+ import { useEffect } from 'react'
14
+
15
+ export default function LocaleError({
16
+ error,
17
+ reset,
18
+ }: {
19
+ error: Error & { digest?: string }
20
+ reset: () => void
21
+ }) {
22
+ useEffect(() => {
23
+ console.error('[LocaleError]', error)
24
+ }, [error])
25
+
26
+ let title = 'Unable to load page'
27
+ let message = 'We encountered an error while loading this page. Please try again.'
28
+
29
+ if (error.message?.includes('Region')) {
30
+ title = 'Region loading failed'
31
+ message = 'Unable to load regional settings. Please check your connection and try again.'
32
+ } else if (error.message?.includes('Auth') || error.message?.includes('auth')) {
33
+ title = 'Authentication error'
34
+ message = 'Unable to initialize authentication. Please try again.'
35
+ }
36
+
37
+ return (
38
+ <div className="flex flex-col items-center justify-center min-h-[60vh] p-8 text-center font-sans">
39
+ <h2 className="text-xl font-semibold text-foreground mb-2">
40
+ {title}
41
+ </h2>
42
+ <p className="text-muted-foreground max-w-[420px] leading-relaxed mb-6">
43
+ {message}
44
+ </p>
45
+ {error.digest && (
46
+ <p className="text-xs text-muted-foreground/60 font-mono mb-5">
47
+ Ref: {error.digest}
48
+ </p>
49
+ )}
50
+ <button
51
+ onClick={reset}
52
+ className="px-5 py-2 bg-primary text-primary-foreground rounded-md cursor-pointer text-sm font-medium hover:bg-primary/90 transition-colors border-0"
53
+ >
54
+ Try Again
55
+ </button>
56
+ </div>
57
+ )
58
+ }