@thorprovider/create-thor-app 4.1.1 → 4.1.3
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.
- package/README.md +43 -0
- package/dist/index.js +34 -8
- package/package.json +1 -1
- package/templates/default/.agents/AGENTS.md +22 -1
- package/templates/default/README.md +1 -0
- package/templates/default/ai-validator.json +47 -2
- package/templates/default/app/page.tsx +56 -3
- package/templates/default/components/providers/cart-provider.tsx +12 -0
- package/templates/default/components/providers/commerce-provider.tsx +2 -1
- package/templates/default/components/providers/region-provider.tsx +10 -0
- package/templates/default/docs/commerce-api.md +0 -9
- package/templates/default/docs/decision-matrix.md +54 -0
- package/templates/default/docs/patterns.md +105 -2
- package/templates/default/docs/project-structure.md +11 -0
- package/templates/default/docs/rules.md +29 -0
- package/templates/default/lib/commerce.ts +26 -10
- package/templates/default/lib/env.ts +55 -11
- package/templates/default/next-env.d.ts +1 -1
package/README.md
CHANGED
|
@@ -426,6 +426,49 @@ The package is structured for maintainability:
|
|
|
426
426
|
| `src/helpers/agents-dir.ts` | .agents/ directory generation (AGENTS.md + context/ + skills/) |
|
|
427
427
|
| `tsup.config.ts` | Build config + template bundling hook |
|
|
428
428
|
|
|
429
|
+
## How V0 is Programmed for ThorBuilder
|
|
430
|
+
|
|
431
|
+
ThorBuilder does not rely on a single prompt. V0 is guided through multiple aligned mechanisms that must stay in sync as the codebase evolves.
|
|
432
|
+
|
|
433
|
+
### Guardrail Layers
|
|
434
|
+
|
|
435
|
+
1. **Template `.agents/AGENTS.md`**
|
|
436
|
+
- Compact mission, architecture, runtime, and conflict-resolution rules
|
|
437
|
+
- Used as project-level instructions and persisted for later chat injection
|
|
438
|
+
|
|
439
|
+
2. **Template docs** (`templates/default/docs/`)
|
|
440
|
+
- `types.md` → domain contracts
|
|
441
|
+
- `commerce-api.md` → all allowed `commerce.*` methods
|
|
442
|
+
- `patterns.md` → canonical implementation patterns
|
|
443
|
+
- `rules.md` → non-negotiable constraints
|
|
444
|
+
- `project-structure.md` → file ownership and boundaries
|
|
445
|
+
- `decision-matrix.md` → fast architecture decisions when prompts create pressure to drift
|
|
446
|
+
|
|
447
|
+
3. **Validator rules** (`templates/default/ai-validator.json`)
|
|
448
|
+
- Regex-based post-generation checks that catch architectural drift
|
|
449
|
+
- Examples: backend SDK imports, raw backend fetches, env gating, alternate backend stacks
|
|
450
|
+
|
|
451
|
+
4. **Dynamic ThorBuilder prompt injection**
|
|
452
|
+
- `thor-commerce-builder/lib/thor-context.ts` injects project config, guardrail policy, and backend guidance at chat time
|
|
453
|
+
- Mode-aware: mock, incomplete real backend config, or live backend configured
|
|
454
|
+
|
|
455
|
+
### Core Programming Rules for V0
|
|
456
|
+
|
|
457
|
+
- Build a **ThorCommerce storefront**, not a generic web app
|
|
458
|
+
- Use **`commerce.*` only** for backend access in starter/app code
|
|
459
|
+
- Never integrate vendors directly via SDKs or raw fetch in L5
|
|
460
|
+
- Respect mock-first / live-immediate runtime behavior
|
|
461
|
+
- Live backend data is authoritative when configured and available
|
|
462
|
+
- Demo fixtures are allowed only for presentation-oriented sections in mock/incomplete mode
|
|
463
|
+
|
|
464
|
+
### Maintenance Rule
|
|
465
|
+
|
|
466
|
+
If you change ThorCommerce architecture, adapters, starter boundaries, or runtime behavior, review **all guardrail layers** together. Do not update AGENTS or validator rules in isolation.
|
|
467
|
+
|
|
468
|
+
See also:
|
|
469
|
+
- `V0_GUARDRAILS_MAINTENANCE.md`
|
|
470
|
+
- `templates/default/docs/decision-matrix.md`
|
|
471
|
+
|
|
429
472
|
### Dual-mode detection
|
|
430
473
|
|
|
431
474
|
`findMonorepoRoot()` walks up the directory tree looking for `packages/core/package.json`:
|
package/dist/index.js
CHANGED
|
@@ -374,8 +374,7 @@ function readSource(sourceDir, relPath) {
|
|
|
374
374
|
if (!existsSync5(abs)) return "";
|
|
375
375
|
return readFileSync4(abs, "utf-8");
|
|
376
376
|
}
|
|
377
|
-
|
|
378
|
-
return `# ${name} \u2014 Thor Commerce Storefront
|
|
377
|
+
var DEFAULT_AGENTS_MD = `# Thor Commerce Storefront
|
|
379
378
|
|
|
380
379
|
## CRITICAL
|
|
381
380
|
ALWAYS import from @thorprovider/types \u2014 NEVER define Product, Cart, Collection, Money.
|
|
@@ -396,13 +395,28 @@ ALWAYS import from @thorprovider/types \u2014 NEVER define Product, Cart, Collec
|
|
|
396
395
|
- useRegion() \u2014 @/components/providers/region-provider
|
|
397
396
|
- useCommerce() \u2014 @/components/providers/commerce-provider
|
|
398
397
|
|
|
398
|
+
## Runtime
|
|
399
|
+
- Default to mock mode when backend env is missing
|
|
400
|
+
- Real provider + URL + API key => live backend immediately
|
|
401
|
+
- Same commerce/useCart/useRegion APIs in both modes
|
|
402
|
+
|
|
399
403
|
## Stack
|
|
400
404
|
Next.js 16, React 19, TS strict, Tailwind 4, shadcn/ui.
|
|
401
405
|
Server Components default. 'use client' only for interactivity.
|
|
402
406
|
|
|
403
407
|
## Docs
|
|
404
|
-
docs/types.md (types), docs/patterns.md (examples)
|
|
408
|
+
docs/types.md (types), docs/patterns.md (examples).
|
|
405
409
|
`;
|
|
410
|
+
function applyProjectNameToAgentsMd(name, content) {
|
|
411
|
+
return content.replace(
|
|
412
|
+
/^#\s+Thor Commerce Storefront\s*$/m,
|
|
413
|
+
`# ${name} \u2014 Thor Commerce Storefront`
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
function buildAgentsMd(name, sourceDir) {
|
|
417
|
+
const sourceAgentsMd = readSource(sourceDir, ".agents/AGENTS.md").trim();
|
|
418
|
+
const baseAgentsMd = sourceAgentsMd || DEFAULT_AGENTS_MD.trim();
|
|
419
|
+
return applyProjectNameToAgentsMd(name, baseAgentsMd);
|
|
406
420
|
}
|
|
407
421
|
function buildArchitectureMd() {
|
|
408
422
|
return `---
|
|
@@ -591,7 +605,7 @@ function generateAgentsDir(name, targetDir, sourceDir) {
|
|
|
591
605
|
const skillsDir = join5(agentsDir, "skills");
|
|
592
606
|
mkdirSync(contextDir, { recursive: true });
|
|
593
607
|
mkdirSync(skillsDir, { recursive: true });
|
|
594
|
-
write(join5(agentsDir, "AGENTS.md"), buildAgentsMd(name));
|
|
608
|
+
write(join5(agentsDir, "AGENTS.md"), buildAgentsMd(name, sourceDir));
|
|
595
609
|
write(join5(contextDir, "architecture.md"), buildArchitectureMd());
|
|
596
610
|
const docFiles = [
|
|
597
611
|
"README.md",
|
|
@@ -821,10 +835,21 @@ function verifyValidatorConfig(targetDir) {
|
|
|
821
835
|
log(" \u26A0\uFE0F ai-validator.json is missing required fields", c.yellow);
|
|
822
836
|
return false;
|
|
823
837
|
}
|
|
838
|
+
if (typeof config.postStreamDelayMs !== "number") {
|
|
839
|
+
log(" \u26A0\uFE0F ai-validator.json must define postStreamDelayMs", c.yellow);
|
|
840
|
+
return false;
|
|
841
|
+
}
|
|
824
842
|
if (!Array.isArray(config.architecturalRules)) {
|
|
825
843
|
log(" \u26A0\uFE0F ai-validator.json architecturalRules must be an array", c.yellow);
|
|
826
844
|
return false;
|
|
827
845
|
}
|
|
846
|
+
const hasInvalidRules = config.architecturalRules.some(
|
|
847
|
+
(rule) => !rule.id || !rule.filePattern || !rule.pattern || !rule.description || rule.severity !== void 0 && rule.severity !== "error" && rule.severity !== "warning"
|
|
848
|
+
);
|
|
849
|
+
if (hasInvalidRules) {
|
|
850
|
+
log(" \u26A0\uFE0F ai-validator.json contains invalid architecturalRules entries", c.yellow);
|
|
851
|
+
return false;
|
|
852
|
+
}
|
|
828
853
|
log(" \u2713 ai-validator.json verified", c.green);
|
|
829
854
|
return true;
|
|
830
855
|
} catch (err) {
|
|
@@ -918,7 +943,7 @@ async function createApp(opts) {
|
|
|
918
943
|
});
|
|
919
944
|
log(" \u2713 package.json updated", c.green);
|
|
920
945
|
const envOverrides = {
|
|
921
|
-
|
|
946
|
+
NEXT_PUBLIC_COMMERCE_PROVIDER: commerceProvider ?? (commerceApiUrl && commerceApiKey ? "medusa" : "mock"),
|
|
922
947
|
...commerceApiUrl && { NEXT_PUBLIC_COMMERCE_API_URL: commerceApiUrl },
|
|
923
948
|
...commerceApiKey && { NEXT_PUBLIC_COMMERCE_API_KEY: commerceApiKey }
|
|
924
949
|
};
|
|
@@ -1016,8 +1041,9 @@ async function createApp(opts) {
|
|
|
1016
1041
|
${step++}. Backend already configured (via CLI flags) \u2713`, c.green);
|
|
1017
1042
|
} else {
|
|
1018
1043
|
log(`
|
|
1019
|
-
${step++}.
|
|
1020
|
-
log(
|
|
1044
|
+
${step++}. Optional: connect a real backend later`, c.cyan);
|
|
1045
|
+
log(" The scaffold starts in mock mode so you can design immediately.", c.yellow);
|
|
1046
|
+
log(` When ready, edit ${relPath}/.env and set NEXT_PUBLIC_COMMERCE_PROVIDER, NEXT_PUBLIC_COMMERCE_API_URL, and NEXT_PUBLIC_COMMERCE_API_KEY`, c.yellow);
|
|
1021
1047
|
}
|
|
1022
1048
|
if (!remoteCreated && !skipRemote) {
|
|
1023
1049
|
const vis = process.env.GITHUB_REPO_VISIBILITY === "public" ? "--public" : "--private";
|
|
@@ -1092,7 +1118,7 @@ if (nodeMajor < NODE_MIN_MAJOR || nodeMajor === NODE_MIN_MAJOR && nodeMinor < NO
|
|
|
1092
1118
|
);
|
|
1093
1119
|
process.exit(1);
|
|
1094
1120
|
}
|
|
1095
|
-
program.name("create-thor-app").description("Create a new Thor Commerce application").argument("[name]", "Project name (kebab-case)").option("--name <name>", "Project name (alternative to positional arg)").option("-o, --output <dir>", "Output directory (default: ./<name>)").option("--skip-git", "Skip git init").option("--skip-install", "Skip yarn install").option("--skip-remote", "Skip GitHub remote repo creation").option("--skip-vercel", "Skip Vercel project linking").option("--no-context", "Skip .agents/ directory generation").option("--no-validator", "Skip ai-validator.json injection (V0 Stop Hooks)").option("--commerce-provider <provider>", "Commerce backend provider (e.g., medusa, shopify)").option("--commerce-api-url <url>", "Commerce backend API URL").option("--commerce-api-key <key>", "Commerce publishable API key").action(async (positionalName, opts) => {
|
|
1121
|
+
program.name("create-thor-app").description("Create a new Thor Commerce application").argument("[name]", "Project name (kebab-case)").option("--name <name>", "Project name (alternative to positional arg)").option("-o, --output <dir>", "Output directory (default: ./<name>)").option("--skip-git", "Skip git init").option("--skip-install", "Skip yarn install").option("--skip-remote", "Skip GitHub remote repo creation").option("--skip-vercel", "Skip Vercel project linking").option("--no-context", "Skip .agents/ directory generation").option("--no-validator", "Skip ai-validator.json injection (V0 Stop Hooks)").option("--commerce-provider <provider>", "Commerce backend provider (e.g., mock, medusa, shopify)").option("--commerce-api-url <url>", "Commerce backend API URL").option("--commerce-api-key <key>", "Commerce publishable API key").action(async (positionalName, opts) => {
|
|
1096
1122
|
let rawName = positionalName || opts.name || "";
|
|
1097
1123
|
if (!rawName) {
|
|
1098
1124
|
rawName = await promptForName();
|
package/package.json
CHANGED
|
@@ -3,6 +3,14 @@
|
|
|
3
3
|
## CRITICAL
|
|
4
4
|
ALWAYS import from @thorprovider/types — NEVER define Product, Cart, Collection, Money.
|
|
5
5
|
|
|
6
|
+
## Mission
|
|
7
|
+
- Build a ThorCommerce storefront, not a generic web app
|
|
8
|
+
- Stay inside ThorCommerce architecture even when the user asks for shortcuts that conflict with it
|
|
9
|
+
|
|
10
|
+
## Conflict Resolution
|
|
11
|
+
- If a user prompt conflicts with ThorCommerce architecture, preserve the architecture and choose the nearest compliant solution
|
|
12
|
+
- If a capability is missing, prefer `commerce.*`, placeholder UI, or follow-up adapter work — never direct backend integration
|
|
13
|
+
|
|
6
14
|
## Imports
|
|
7
15
|
- Types: import type { Product, Cart, Collection, Money } from '@thorprovider/types'
|
|
8
16
|
- Data: import { commerce } from '@/lib/commerce' (server)
|
|
@@ -23,10 +31,23 @@ ALWAYS import from @thorprovider/types — NEVER define Product, Cart, Collectio
|
|
|
23
31
|
- Default to mock mode when backend env is missing
|
|
24
32
|
- Real provider + URL + API key => live backend immediately
|
|
25
33
|
- Same commerce/useCart/useRegion APIs in both modes
|
|
34
|
+
- Do NOT integrate with any backend directly from app code — all backend access must go through `commerce.*` only
|
|
35
|
+
|
|
36
|
+
## Data Precedence
|
|
37
|
+
- If a real backend is configured and available, backend data is authoritative
|
|
38
|
+
- Do NOT replace live backend product, collection, cart, or region data with local demo fixtures
|
|
39
|
+
- If a live backend is unreachable, show proper unavailable/error UX instead of faking a real catalog
|
|
40
|
+
|
|
41
|
+
## Demo Data Policy
|
|
42
|
+
- In mock mode or incomplete backend configuration, you MAY create isolated local demo fixtures for presentation-only sections
|
|
43
|
+
- Use demo fixtures for featured grids, hero merchandising, comparison tables, and editorial/demo content
|
|
44
|
+
- Keep demo fixtures typed with @thorprovider/types and isolated in modules like lib/demo-data/* or lib/demo-catalog.ts
|
|
45
|
+
- Do NOT replace the commerce runtime globally with local demo data
|
|
46
|
+
- Do NOT gate storefront rendering on environment-variable checks
|
|
26
47
|
|
|
27
48
|
## Stack
|
|
28
49
|
Next.js 16, React 19, TS strict, Tailwind 4, shadcn/ui.
|
|
29
50
|
Server Components default. 'use client' only for interactivity.
|
|
30
51
|
|
|
31
52
|
## Docs
|
|
32
|
-
docs/types.md (types), docs/patterns.md (examples).
|
|
53
|
+
docs/types.md (types), docs/patterns.md (examples), docs/rules.md (constraints), docs/commerce-api.md (methods).
|
|
@@ -46,6 +46,7 @@ NEXT_PUBLIC_COMMERCE_API_KEY=pk_live_xxx
|
|
|
46
46
|
- `mock` or missing live-backend env vars → storefront uses fixture-backed mock commerce data
|
|
47
47
|
- real provider + API URL + API key → storefront uses the live backend immediately
|
|
48
48
|
- switching config later should not require rewriting app code that calls `commerce.*`, `useCart()`, or `useRegion()`
|
|
49
|
+
- if a configured live backend becomes unreachable, surface unavailable/error UX instead of masking the failure with fake catalog data
|
|
49
50
|
|
|
50
51
|
## Development with V0
|
|
51
52
|
|
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
{
|
|
9
9
|
"id": "no-backend-sdk-imports",
|
|
10
10
|
"filePattern": "**/*.{ts,tsx}",
|
|
11
|
-
"pattern": "from\\s+['\"]@medusajs/js-sdk['\"]|from\\s+['\"]@shopify/api['\"]",
|
|
12
|
-
"description": "Never import backend SDKs directly —
|
|
11
|
+
"pattern": "from\\s+['\"]@medusajs/js-sdk['\"]|from\\s+['\"]@shopify/api['\"]|from\\s+['\"]@shopify/storefront-api-client['\"]|from\\s+['\"]@bigcommerce/|from\\s+['\"]@woocommerce/|from\\s+['\"]@spree/|from\\s+['\"]@magento/",
|
|
12
|
+
"description": "Never import backend SDKs directly — all backend integration must go through commerce.* from @/lib/commerce"
|
|
13
13
|
},
|
|
14
14
|
{
|
|
15
15
|
"id": "no-raw-commerce-fetch",
|
|
@@ -108,12 +108,57 @@
|
|
|
108
108
|
"pattern": "createProvider\\(",
|
|
109
109
|
"description": "Never call createProvider() in app/ — import commerce from @/lib/commerce (singleton)"
|
|
110
110
|
},
|
|
111
|
+
{
|
|
112
|
+
"id": "no-env-gating-in-pages",
|
|
113
|
+
"filePattern": "app/**/*.{ts,tsx}",
|
|
114
|
+
"pattern": "isEnvConfigured\\(|process\\.env\\.NEXT_PUBLIC_COMMERCE_API_(URL|KEY)|process\\.env\\.NEXT_PUBLIC_COMMERCE_PROVIDER",
|
|
115
|
+
"description": "Do not gate storefront rendering on commerce env vars in app code — use the backend-optional runtime and commerce.*"
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
"id": "no-provider-branching-in-app",
|
|
119
|
+
"filePattern": "app/**/*.{ts,tsx}",
|
|
120
|
+
"pattern": "NEXT_PUBLIC_COMMERCE_PROVIDER|process\\.env\\.NEXT_PUBLIC_COMMERCE_PROVIDER|shouldUseMockProvider\\(|isEnvConfigured\\(",
|
|
121
|
+
"description": "Do not create app-level provider/env branches for mock vs live — keep one storefront architecture using commerce.* and infrastructure-resolved runtime mode"
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
"id": "mock-first-provider-default",
|
|
125
|
+
"filePattern": "lib/env.ts",
|
|
126
|
+
"pattern": "\\.default\\('medusa'\\)",
|
|
127
|
+
"description": "The runtime must default to mock mode when backend config is absent — lib/env.ts must not default the provider to medusa",
|
|
128
|
+
"severity": "error"
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
"id": "no-undefined-commerce-when-env-missing",
|
|
132
|
+
"filePattern": "lib/commerce.ts",
|
|
133
|
+
"pattern": "if \\(!isEnvConfigured\\(\\)\\) return undefined",
|
|
134
|
+
"description": "The commerce singleton must resolve to mock mode instead of returning undefined when backend env vars are missing",
|
|
135
|
+
"severity": "error"
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"id": "no-direct-backend-fetch",
|
|
139
|
+
"filePattern": "app/**/*.{ts,tsx}",
|
|
140
|
+
"pattern": "fetch\\(.*(/store/|/admin/|/api/graphql|/graphql|products|collections)",
|
|
141
|
+
"description": "Never integrate with backend endpoints directly from app code — use commerce.* methods only",
|
|
142
|
+
"required": false
|
|
143
|
+
},
|
|
111
144
|
{
|
|
112
145
|
"id": "no-thorprovider-components-import",
|
|
113
146
|
"filePattern": "**/*.{ts,tsx}",
|
|
114
147
|
"pattern": "from\\s+['\"]@thorprovider/components['\"]|from\\s+['\"]@thorprovider/providers['\"]",
|
|
115
148
|
"description": "Do not import from @thorprovider/components or @thorprovider/providers — use local providers from @/components/providers/ and shadcn/ui for UI"
|
|
116
149
|
},
|
|
150
|
+
{
|
|
151
|
+
"id": "no-alternate-backend-stacks-in-app",
|
|
152
|
+
"filePattern": "app/**/*.{ts,tsx}",
|
|
153
|
+
"pattern": "from\\s+['\"]@supabase/|from\\s+['\"]firebase|from\\s+['\"]@prisma/client['\"]|from\\s+['\"]graphql-request['\"]|from\\s+['\"]@apollo/client['\"]",
|
|
154
|
+
"description": "Do not introduce alternate backend/data clients into starter app code — preserve ThorCommerce architecture"
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
"id": "no-alternate-backend-stacks-in-components",
|
|
158
|
+
"filePattern": "components/**/*.{ts,tsx}",
|
|
159
|
+
"pattern": "from\\s+['\"]@supabase/|from\\s+['\"]firebase|from\\s+['\"]@prisma/client['\"]|from\\s+['\"]graphql-request['\"]|from\\s+['\"]@apollo/client['\"]",
|
|
160
|
+
"description": "Do not introduce alternate backend/data clients into starter UI code — use commerce.* and local providers"
|
|
161
|
+
},
|
|
117
162
|
{
|
|
118
163
|
"id": "use-format-price",
|
|
119
164
|
"filePattern": "**/*.tsx",
|
|
@@ -1,14 +1,67 @@
|
|
|
1
1
|
// V0 replaces this with the actual storefront homepage
|
|
2
2
|
import { commerce } from '@/lib/commerce'
|
|
3
|
+
import { formatPrice } from '@/lib/utils'
|
|
4
|
+
import { redirect } from 'next/navigation'
|
|
3
5
|
import type { Product } from '@thorprovider/types'
|
|
4
6
|
|
|
5
7
|
export default async function HomePage() {
|
|
6
|
-
|
|
8
|
+
let products: Product[]
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
products = await commerce.getProducts({ first: 8 })
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (commerce.isMock !== true) {
|
|
14
|
+
redirect('/backend-unavailable?returnTo=/')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
throw error
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const isMockMode = commerce.isMock === true
|
|
7
21
|
|
|
8
22
|
return (
|
|
9
23
|
<main className="container mx-auto px-4 py-8">
|
|
10
|
-
<
|
|
11
|
-
|
|
24
|
+
<div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
|
|
25
|
+
<div>
|
|
26
|
+
<h1 className="text-3xl font-bold">Store</h1>
|
|
27
|
+
<p className="text-muted-foreground">{products.length} products available</p>
|
|
28
|
+
</div>
|
|
29
|
+
|
|
30
|
+
<div className="rounded-full border px-4 py-2 text-sm text-muted-foreground">
|
|
31
|
+
{isMockMode
|
|
32
|
+
? 'Using mock catalog — connect a backend to switch to live commerce data.'
|
|
33
|
+
: 'Connected to live commerce data.'}
|
|
34
|
+
</div>
|
|
35
|
+
</div>
|
|
36
|
+
|
|
37
|
+
<div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
|
38
|
+
{products.slice(0, 4).map((product) => {
|
|
39
|
+
const previewPrice = product.variants[0]?.price
|
|
40
|
+
|
|
41
|
+
return (
|
|
42
|
+
<article key={product.id} className="rounded-xl border bg-card p-4 text-card-foreground">
|
|
43
|
+
<div className="aspect-square overflow-hidden rounded-lg bg-muted">
|
|
44
|
+
{product.featuredImage ? (
|
|
45
|
+
<img
|
|
46
|
+
alt={product.featuredImage.altText || product.title}
|
|
47
|
+
className="h-full w-full object-cover"
|
|
48
|
+
src={product.featuredImage.url}
|
|
49
|
+
/>
|
|
50
|
+
) : null}
|
|
51
|
+
</div>
|
|
52
|
+
|
|
53
|
+
<div className="mt-4 space-y-1">
|
|
54
|
+
<h2 className="font-semibold">{product.title}</h2>
|
|
55
|
+
<p className="line-clamp-2 text-sm text-muted-foreground">{product.description}</p>
|
|
56
|
+
{previewPrice ? (
|
|
57
|
+
<p className="text-sm font-medium">{formatPrice(previewPrice)}</p>
|
|
58
|
+
) : null}
|
|
59
|
+
</div>
|
|
60
|
+
</article>
|
|
61
|
+
)
|
|
62
|
+
})}
|
|
63
|
+
</div>
|
|
64
|
+
|
|
12
65
|
{/* V0: Generate the actual storefront homepage here */}
|
|
13
66
|
</main>
|
|
14
67
|
)
|
|
@@ -37,6 +37,7 @@ export interface CartContextValue {
|
|
|
37
37
|
const CartContext = createContext<CartContextValue | null>(null)
|
|
38
38
|
|
|
39
39
|
const CART_ID_KEY = 'thor-cart-id'
|
|
40
|
+
const CART_PROVIDER_KEY = 'thor-cart-provider'
|
|
40
41
|
|
|
41
42
|
export function CartProvider({ children }: { children: ReactNode }) {
|
|
42
43
|
const [cart, setCart] = useState<Cart | null>(null)
|
|
@@ -52,6 +53,15 @@ export function CartProvider({ children }: { children: ReactNode }) {
|
|
|
52
53
|
;(async () => {
|
|
53
54
|
try {
|
|
54
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
|
+
|
|
55
65
|
const cartId = localStorage.getItem(CART_ID_KEY)
|
|
56
66
|
if (cartId) {
|
|
57
67
|
const loaded = await commerce.getCart(cartId)
|
|
@@ -74,6 +84,7 @@ export function CartProvider({ children }: { children: ReactNode }) {
|
|
|
74
84
|
const newCart = await commerce.createCart()
|
|
75
85
|
setCart(newCart)
|
|
76
86
|
if (newCart.id) localStorage.setItem(CART_ID_KEY, newCart.id)
|
|
87
|
+
localStorage.setItem(CART_PROVIDER_KEY, commerce.isMock ? 'mock' : 'live')
|
|
77
88
|
return newCart
|
|
78
89
|
}, [cart])
|
|
79
90
|
|
|
@@ -127,6 +138,7 @@ export function CartProvider({ children }: { children: ReactNode }) {
|
|
|
127
138
|
const clearCart = useCallback(() => {
|
|
128
139
|
setCart(null)
|
|
129
140
|
localStorage.removeItem(CART_ID_KEY)
|
|
141
|
+
localStorage.removeItem(CART_PROVIDER_KEY)
|
|
130
142
|
}, [])
|
|
131
143
|
|
|
132
144
|
return (
|
|
@@ -14,13 +14,14 @@ import type { ReactNode } from 'react'
|
|
|
14
14
|
export interface CommerceContextValue {
|
|
15
15
|
/** The commerce adapter instance (same as `@/lib/commerce` export) */
|
|
16
16
|
commerce: typeof commerce
|
|
17
|
+
isMock: boolean
|
|
17
18
|
}
|
|
18
19
|
|
|
19
20
|
const CommerceContext = createContext<CommerceContextValue | null>(null)
|
|
20
21
|
|
|
21
22
|
export function CommerceProvider({ children }: { children: ReactNode }) {
|
|
22
23
|
return (
|
|
23
|
-
<CommerceContext.Provider value={{ commerce }}>
|
|
24
|
+
<CommerceContext.Provider value={{ commerce, isMock: commerce.isMock === true }}>
|
|
24
25
|
{children}
|
|
25
26
|
</CommerceContext.Provider>
|
|
26
27
|
)
|
|
@@ -30,6 +30,7 @@ export interface RegionContextValue {
|
|
|
30
30
|
const RegionContext = createContext<RegionContextValue | null>(null)
|
|
31
31
|
|
|
32
32
|
const REGION_KEY = 'thor-region-id'
|
|
33
|
+
const REGION_PROVIDER_KEY = 'thor-region-provider'
|
|
33
34
|
|
|
34
35
|
/**
|
|
35
36
|
* Normalize adapter response to Region type.
|
|
@@ -64,6 +65,15 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
|
|
64
65
|
setIsLoading(true)
|
|
65
66
|
if (!commerce.getRegions) return
|
|
66
67
|
|
|
68
|
+
const currentProvider = commerce.isMock ? 'mock' : 'live'
|
|
69
|
+
const storedProvider = localStorage.getItem(REGION_PROVIDER_KEY)
|
|
70
|
+
|
|
71
|
+
if (storedProvider && storedProvider !== currentProvider) {
|
|
72
|
+
localStorage.removeItem(REGION_KEY)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
localStorage.setItem(REGION_PROVIDER_KEY, currentProvider)
|
|
76
|
+
|
|
67
77
|
const raw = await commerce.getRegions()
|
|
68
78
|
if (cancelled || !raw) return
|
|
69
79
|
|
|
@@ -12,13 +12,6 @@ All backend access goes through the `commerce` singleton from `@/lib/commerce`.
|
|
|
12
12
|
import { commerce } from '@/lib/commerce';
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
## Runtime Modes
|
|
16
|
-
|
|
17
|
-
- `mock` provider, or missing real-backend env vars → `commerce` uses a fixture-backed mock provider for layout/preview work.
|
|
18
|
-
- Real provider + `NEXT_PUBLIC_COMMERCE_API_URL` + `NEXT_PUBLIC_COMMERCE_API_KEY` → `commerce` uses the live backend immediately.
|
|
19
|
-
- The `commerce.*` API stays the same in both modes. Write app code against the shared interface instead of branching on provider.
|
|
20
|
-
- If backend config is added later, products, categories, region, cart, checkout, and auth flows switch to the live provider without changing call sites.
|
|
21
|
-
|
|
22
15
|
---
|
|
23
16
|
|
|
24
17
|
## Products
|
|
@@ -178,8 +171,6 @@ try {
|
|
|
178
171
|
}
|
|
179
172
|
```
|
|
180
173
|
|
|
181
|
-
In `mock` mode there is no backend network dependency, so preview/design work should continue without live-backend health checks.
|
|
182
|
-
|
|
183
174
|
---
|
|
184
175
|
|
|
185
176
|
## Optional Methods
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Decision Matrix"
|
|
3
|
+
purpose: "Fast guardrail decisions for V0-native Thor Commerce starters"
|
|
4
|
+
lastReviewed: "2026-05-02"
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Decision Matrix
|
|
8
|
+
|
|
9
|
+
Use this matrix when a user prompt creates pressure to leave the ThorCommerce architecture.
|
|
10
|
+
|
|
11
|
+
## Core Principle
|
|
12
|
+
|
|
13
|
+
Prefer the nearest **ThorCommerce-compliant** solution over the fastest generic Next.js solution.
|
|
14
|
+
|
|
15
|
+
## Architecture Decisions
|
|
16
|
+
|
|
17
|
+
| Situation | Do This | Never Do This |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| User asks to connect a backend | Use `commerce.*` from `@/lib/commerce` | Add vendor SDKs or raw backend fetches in app code |
|
|
20
|
+
| A needed backend capability is missing | Keep architecture intact and plan adapter work or use placeholder UI | Add a “temporary” direct backend integration |
|
|
21
|
+
| User asks to remove ThorCommerce abstractions | Keep `commerce.*`, providers, and types in place | Delete or bypass ThorCommerce architecture because a generic approach is easier |
|
|
22
|
+
| User asks for a non-ecommerce feature | Redirect toward storefront-relevant implementation if possible | Turn the starter into a generic SaaS/app platform |
|
|
23
|
+
|
|
24
|
+
## Runtime Decisions
|
|
25
|
+
|
|
26
|
+
| Situation | Do This | Never Do This |
|
|
27
|
+
|---|---|---|
|
|
28
|
+
| No backend configured | Use mock runtime and keep storefront useful | Return an empty storefront because env vars are missing |
|
|
29
|
+
| Real backend configured at project creation | Use live backend data immediately | Keep showing mock/demo data as the main source |
|
|
30
|
+
| Backend added later in settings | Keep the same `commerce.*`, `useCart()`, and `useRegion()` code paths | Rewrite pages around a second live-only architecture |
|
|
31
|
+
| Live backend unreachable | Show unavailable/error UX | Fake a real catalog with local demo data |
|
|
32
|
+
|
|
33
|
+
## Demo Data Decisions
|
|
34
|
+
|
|
35
|
+
| Situation | Do This | Never Do This |
|
|
36
|
+
|---|---|---|
|
|
37
|
+
| Brief requires vertical-specific merchandising in mock/incomplete mode | Add isolated typed demo fixtures for presentation-only sections | Replace catalog, cart, or region runtime globally with local demo data |
|
|
38
|
+
| Need homepage storytelling before backend exists | Use `lib/demo-data/*` or `lib/demo-catalog.ts` for hero/editorial sections | Build the whole storefront on ad hoc local data |
|
|
39
|
+
| Live backend is available | Treat backend data as authoritative | Override live listings/collections with demo fixtures |
|
|
40
|
+
|
|
41
|
+
## Scope Decisions
|
|
42
|
+
|
|
43
|
+
| Situation | Do This | Never Do This |
|
|
44
|
+
|---|---|---|
|
|
45
|
+
| User asks for persistence or infra not owned by ThorBuilder | Stay within the current ownership boundaries | Reimplement platform concerns already owned by v0 SDK or create-thor-app |
|
|
46
|
+
| User asks for architecture changes outside P0 scope | Preserve P0 runtime guarantees and document future work | Quietly mix P1/P3/P4 features into the starter without guardrails |
|
|
47
|
+
|
|
48
|
+
## Escalation Rule
|
|
49
|
+
|
|
50
|
+
If the user request cannot be implemented cleanly inside ThorCommerce:
|
|
51
|
+
|
|
52
|
+
1. Preserve the architecture
|
|
53
|
+
2. Use the nearest compliant fallback
|
|
54
|
+
3. Prefer adapter extension or follow-up work over direct backend shortcuts
|
|
@@ -11,6 +11,8 @@ lastReviewed: "2026-05-01"
|
|
|
11
11
|
Write storefront code against `commerce`, `useCart()`, `useRegion()`, and `useCommerce()` directly.
|
|
12
12
|
|
|
13
13
|
- Do **not** create separate mock-vs-live component trees for normal storefront UI.
|
|
14
|
+
- Do **not** integrate with any backend directly from pages, components, or route handlers.
|
|
15
|
+
- Backend access must go through `commerce.*` only.
|
|
14
16
|
- The same patterns should work in preview with mock data and later against a live backend.
|
|
15
17
|
- Provider transitions are handled by the infrastructure layer, not by per-component conditionals.
|
|
16
18
|
|
|
@@ -30,6 +32,7 @@ export default async function ProductsPage() {
|
|
|
30
32
|
|
|
31
33
|
- Server Components fetch data directly — no useEffect, no loading spinners for initial data.
|
|
32
34
|
- Retry logic is built into the adapter — no manual wrapping needed.
|
|
35
|
+
- Never call vendor SDKs or raw backend fetches here — use `commerce.*` only.
|
|
33
36
|
|
|
34
37
|
---
|
|
35
38
|
|
|
@@ -95,7 +98,6 @@ export function AddToCartButton({ variantId }: { variantId: string }) {
|
|
|
95
98
|
|
|
96
99
|
- Import `useCart` from `@/components/providers/cart-provider`.
|
|
97
100
|
- Cart methods: `addItem(variantId, quantity)`, `removeItem(lineItemId)`, `updateQuantity(lineItemId, qty)`, `clearCart()`.
|
|
98
|
-
- When the storefront switches from mock to live backend, `CartProvider` resets incompatible persisted cart state automatically.
|
|
99
101
|
|
|
100
102
|
---
|
|
101
103
|
|
|
@@ -123,7 +125,6 @@ export function CurrencySelector() {
|
|
|
123
125
|
```
|
|
124
126
|
|
|
125
127
|
- Import `useRegion` from `@/components/providers/region-provider`.
|
|
126
|
-
- When the provider changes between mock and live, `RegionProvider` clears stale persisted region state automatically.
|
|
127
128
|
|
|
128
129
|
---
|
|
129
130
|
|
|
@@ -187,6 +188,108 @@ const customer = await commerce.auth.getCurrentCustomer();
|
|
|
187
188
|
|
|
188
189
|
---
|
|
189
190
|
|
|
191
|
+
## 8. Backend Integration Boundary
|
|
192
|
+
|
|
193
|
+
```tsx
|
|
194
|
+
// Correct — backend access always goes through commerce.*
|
|
195
|
+
import { commerce } from '@/lib/commerce';
|
|
196
|
+
|
|
197
|
+
const products = await commerce.getProducts({ first: 12 });
|
|
198
|
+
const collection = await commerce.getCollection('featured');
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
```tsx
|
|
202
|
+
// Wrong — never integrate with a backend directly from the app
|
|
203
|
+
import Medusa from '@medusajs/js-sdk';
|
|
204
|
+
|
|
205
|
+
const medusa = new Medusa({
|
|
206
|
+
baseUrl: process.env.NEXT_PUBLIC_COMMERCE_API_URL!,
|
|
207
|
+
publishableKey: process.env.NEXT_PUBLIC_COMMERCE_API_KEY!,
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
const products = await medusa.store.product.list();
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
```tsx
|
|
214
|
+
// Wrong — never bypass adapters with raw fetch
|
|
215
|
+
const response = await fetch(`${process.env.NEXT_PUBLIC_COMMERCE_API_URL}/products`);
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
- V0 must not add direct Medusa, Shopify, BigCommerce, or other backend integrations.
|
|
219
|
+
- V0 must only use the local commerce singleton: `import { commerce } from '@/lib/commerce'`.
|
|
220
|
+
- If a capability is needed, check `docs/commerce-api.md` first and call the matching `commerce.*` method.
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## 9. Demo Fixtures for Mock/Incomplete Mode
|
|
225
|
+
|
|
226
|
+
Use this only for presentation-oriented sections when the brief requires vertical-specific merchandising that is not yet represented by the generic mock catalog.
|
|
227
|
+
|
|
228
|
+
```tsx
|
|
229
|
+
// lib/demo-catalog.ts
|
|
230
|
+
import type { Product } from '@thorprovider/types';
|
|
231
|
+
|
|
232
|
+
export const demoFeaturedProducts: Product[] = [
|
|
233
|
+
// Typed demo fixtures for hero/editorial sections only
|
|
234
|
+
];
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
```tsx
|
|
238
|
+
// app/page.tsx
|
|
239
|
+
import { commerce } from '@/lib/commerce';
|
|
240
|
+
import type { Product } from '@thorprovider/types';
|
|
241
|
+
import { demoFeaturedProducts } from '@/lib/demo-catalog';
|
|
242
|
+
import { HeroSpotlight } from '@/components/hero-spotlight';
|
|
243
|
+
import { ProductGrid } from '@/components/product-grid';
|
|
244
|
+
|
|
245
|
+
export default async function HomePage() {
|
|
246
|
+
const products: Product[] = await commerce.getProducts({ first: 8 });
|
|
247
|
+
const heroProducts = commerce.isMock === true
|
|
248
|
+
? demoFeaturedProducts
|
|
249
|
+
: products.slice(0, 4);
|
|
250
|
+
|
|
251
|
+
return (
|
|
252
|
+
<main>
|
|
253
|
+
<HeroSpotlight products={heroProducts} />
|
|
254
|
+
<ProductGrid products={products} />
|
|
255
|
+
</main>
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
- Live backend data remains authoritative when configured and available.
|
|
261
|
+
- Use demo fixtures only in mock mode or incomplete backend configuration.
|
|
262
|
+
- Keep demo fixtures isolated in `lib/demo-data/*` or `lib/demo-catalog.ts`.
|
|
263
|
+
- Do not replace normal product listings, collections, cart, or region flows with demo fixtures.
|
|
264
|
+
|
|
265
|
+
- Minor runtime-aware UX such as mock/live badges is allowed when it reads the already-resolved adapter state (`commerce.isMock`).
|
|
266
|
+
- Do not use environment variables or helper functions like `isEnvConfigured()`/`shouldUseMockProvider()` inside app code to branch storefront rendering.
|
|
267
|
+
|
|
268
|
+
---
|
|
269
|
+
|
|
270
|
+
## 10. What NOT to Do in Backend-Optional Mode
|
|
271
|
+
|
|
272
|
+
```tsx
|
|
273
|
+
// Wrong — do not gate storefront rendering on env checks
|
|
274
|
+
if (!process.env.NEXT_PUBLIC_COMMERCE_API_URL) {
|
|
275
|
+
return <div>No products yet</div>;
|
|
276
|
+
}
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
```tsx
|
|
280
|
+
// Wrong — do not branch into a separate backend integration path
|
|
281
|
+
if (process.env.NEXT_PUBLIC_COMMERCE_PROVIDER === 'medusa') {
|
|
282
|
+
// direct vendor SDK integration
|
|
283
|
+
}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
```tsx
|
|
287
|
+
// Correct — same commerce.* interface in mock and live modes
|
|
288
|
+
const products = await commerce.getProducts({ first: 8 });
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
---
|
|
292
|
+
|
|
190
293
|
## Import Path Summary
|
|
191
294
|
|
|
192
295
|
| What | Import From |
|
|
@@ -40,6 +40,8 @@ lib/
|
|
|
40
40
|
commerce.ts ← Commerce singleton — FROZEN
|
|
41
41
|
env.ts ← Zod environment schema — FROZEN
|
|
42
42
|
utils.ts ← cn() + formatPrice()
|
|
43
|
+
demo-data/ ← Optional typed demo fixtures for presentation-only sections in mock/incomplete mode
|
|
44
|
+
demo-catalog.ts ← Optional single-file demo fallback for brief-specific merchandising
|
|
43
45
|
|
|
44
46
|
docs/
|
|
45
47
|
types.md ← Full @thorprovider/types reference
|
|
@@ -57,6 +59,7 @@ docs/
|
|
|
57
59
|
| Reusable UI primitive | `npx shadcn@latest add [component]` → `components/ui/` |
|
|
58
60
|
| API route | `app/api/[route]/route.ts` |
|
|
59
61
|
| Environment variables | `.env.local` |
|
|
62
|
+
| Typed demo fixtures for mock/incomplete presentation fallback | `lib/demo-data/*` or `lib/demo-catalog.ts` |
|
|
60
63
|
|
|
61
64
|
## Component Decision
|
|
62
65
|
|
|
@@ -80,8 +83,16 @@ Need a UI element?
|
|
|
80
83
|
|------|-------|--------------|
|
|
81
84
|
| `lib/commerce.ts` | Infrastructure | Never |
|
|
82
85
|
| `lib/env.ts` | Infrastructure | Never |
|
|
86
|
+
| `lib/demo-data/*` | Feature support | Yes — only for isolated presentation-only fixtures |
|
|
87
|
+
| `lib/demo-catalog.ts` | Feature support | Yes — only for isolated presentation-only fixtures |
|
|
83
88
|
| `components/providers/*` | Infrastructure | Never |
|
|
84
89
|
| `styles/tokens.css` | Brand config | Only via create-thor-app flags |
|
|
85
90
|
| `app/globals.css` | Design tokens | Only to add custom tokens |
|
|
86
91
|
| `app/**/*.tsx` | Feature code | Yes — V0 creates pages |
|
|
87
92
|
| `components/**/*.tsx` | Feature code | Yes — V0 creates components |
|
|
93
|
+
|
|
94
|
+
## Backend Access Boundary
|
|
95
|
+
|
|
96
|
+
- Never integrate with any backend directly from `app/`, `components/`, or route handlers.
|
|
97
|
+
- All commerce/backend access must go through `import { commerce } from '@/lib/commerce'`.
|
|
98
|
+
- Do not add vendor SDK clients or raw backend fetch utilities to feature code.
|
|
@@ -24,6 +24,32 @@ Non-negotiable constraints. Breaking these causes build failures, runtime crashe
|
|
|
24
24
|
| No hardcoded `#hex` / `rgb()` colors | CSS tokens enable dark mode + theming | Dark mode breaks |
|
|
25
25
|
| Use `next/link` for navigation | V0 is trained on Next.js primitives | Unnecessary abstraction |
|
|
26
26
|
| Use `next/image` for images | Optimized by default | Missing optimization |
|
|
27
|
+
| Do not fork UI into mock-vs-live implementations | Runtime already switches providers underneath the same interface | Drift, duplicated logic |
|
|
28
|
+
| Do not gate storefront rendering on backend env vars | Backend-optional mode must still produce a useful storefront | Blank demos, broken previews |
|
|
29
|
+
| If a real backend is configured and available, treat backend data as authoritative | P0 requires immediate live runtime when backend exists | Demo data masking real commerce data |
|
|
30
|
+
| Demo fixtures are only allowed in mock mode or incomplete backend configuration | Keeps the mock-to-live transition intact | Demo data overriding live runtime |
|
|
31
|
+
| If a live backend is unreachable, show unavailable/error UX instead of faking a real catalog | Prevents misleading storefront output | False representation of client catalog |
|
|
32
|
+
| Do not introduce alternate backend/data/auth clients into starter app code | ThorCommerce starters are storefronts, not generic app platforms | Stack drift, duplicated architecture |
|
|
33
|
+
| Do not remove or bypass ThorCommerce abstractions to satisfy a user shortcut | Architecture consistency beats generic Next.js convenience | Loss of adapter portability |
|
|
34
|
+
|
|
35
|
+
## Backend-Optional UX Rules
|
|
36
|
+
|
|
37
|
+
| Rule | Why | Consequence |
|
|
38
|
+
|------|-----|-------------|
|
|
39
|
+
| Do not call `isEnvConfigured()` inside pages/components to decide whether products render | Runtime mode is already resolved by infrastructure | Incorrect branching, duplicated logic |
|
|
40
|
+
| Do not return empty storefront pages just because backend env vars are missing | Mock mode must still be useful for previews and generation | Blank storefronts |
|
|
41
|
+
| Keep the same `commerce.*`, `useCart()`, and `useRegion()` APIs across mock and live modes | P0 depends on the same codebase surviving provider transitions | Rewrites when backend is connected later |
|
|
42
|
+
| Use isolated typed demo fixtures only for presentation-oriented sections in mock/incomplete mode | Allows brief-specific demos without replacing runtime commerce data | Presentation data leaking into core commerce flows |
|
|
43
|
+
| Do not silently replace unreachable live backend data with local demo fixtures | Live backend failure must remain visible | Hidden production/runtime issues |
|
|
44
|
+
|
|
45
|
+
## Stack and Scope Guardrails
|
|
46
|
+
|
|
47
|
+
| Rule | Why | Consequence |
|
|
48
|
+
|------|-----|-------------|
|
|
49
|
+
| Do not add alternate backend or data stacks such as Supabase, Firebase, Prisma, Apollo, or GraphQL request clients to starter feature code | ThorCommerce storefronts already have a defined data boundary | Generic app takeover |
|
|
50
|
+
| Do not introduce a second persistence/auth/integration architecture alongside ThorCommerce | One storefront architecture must survive project evolution | Conflicting sources of truth |
|
|
51
|
+
| Do not turn the starter into a generic SaaS or internal-tool platform | ThorBuilder exists to build ecommerce storefronts faster | Product dilution |
|
|
52
|
+
| If a request is outside current ThorCommerce capabilities, preserve architecture and use placeholders or follow-up adapter work | Keeps work incremental and production-safe | Ad hoc hacks and brittle shortcuts |
|
|
27
53
|
|
|
28
54
|
## Provider Chain (Frozen Order)
|
|
29
55
|
|
|
@@ -57,9 +83,12 @@ Never modify these — they are infrastructure:
|
|
|
57
83
|
- [ ] No `@thorprovider/components` or `@thorprovider/providers` imports?
|
|
58
84
|
- [ ] No backend SDK imports (`@medusajs/*`, `@shopify/*`)?
|
|
59
85
|
- [ ] No raw `fetch(COMMERCE_API_URL...)` calls?
|
|
86
|
+
- [ ] No env-based gating that disables storefront rendering?
|
|
87
|
+
- [ ] No alternate backend/data/auth clients (Supabase/Firebase/Prisma/Apollo/etc.) added to starter code?
|
|
60
88
|
- [ ] All prices rendered via `formatPrice()`?
|
|
61
89
|
- [ ] Using `product.handle` in URLs?
|
|
62
90
|
- [ ] No hardcoded hex/rgb colors?
|
|
63
91
|
- [ ] Types from `@thorprovider/types` (not redefined locally)?
|
|
64
92
|
- [ ] `tsc --noEmit` passes?
|
|
65
93
|
- [ ] Server components fetch; client components receive data via props?
|
|
94
|
+
- [ ] Live backend data remains authoritative when configured?
|
|
@@ -12,30 +12,47 @@
|
|
|
12
12
|
import { createProvider } from '@thorprovider/adapters'
|
|
13
13
|
import type { ProviderTypeString } from '@thorprovider/types'
|
|
14
14
|
import { isSupportedProviderType } from '@thorprovider/types'
|
|
15
|
-
import {
|
|
15
|
+
import { getConfiguredProvider, isRealBackendProvider, shouldUseMockProvider } from './env'
|
|
16
16
|
|
|
17
17
|
let _commerce: ReturnType<typeof createProvider> | undefined
|
|
18
18
|
|
|
19
19
|
function createCommerceInstance(): ReturnType<typeof createProvider> {
|
|
20
20
|
if (_commerce) return _commerce
|
|
21
21
|
|
|
22
|
-
const rawProviderType =
|
|
23
|
-
|
|
22
|
+
const rawProviderType = getConfiguredProvider()
|
|
23
|
+
|
|
24
|
+
if (rawProviderType === 'custom') {
|
|
25
|
+
throw new Error(
|
|
26
|
+
'[commerce] The "custom" provider is not supported by the V0-native template runtime. Configure a supported real backend or use mock mode.'
|
|
27
|
+
)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const resolvedProviderType: ProviderTypeString = shouldUseMockProvider()
|
|
31
|
+
? 'mock'
|
|
32
|
+
: rawProviderType
|
|
33
|
+
|
|
34
|
+
if (!isSupportedProviderType(resolvedProviderType)) {
|
|
24
35
|
throw new Error(
|
|
25
|
-
`[commerce] Unsupported provider: "${
|
|
36
|
+
`[commerce] Unsupported provider: "${resolvedProviderType}". Set NEXT_PUBLIC_COMMERCE_PROVIDER to a supported value.`
|
|
26
37
|
)
|
|
27
38
|
}
|
|
28
39
|
|
|
29
|
-
const providerType: ProviderTypeString = rawProviderType
|
|
30
40
|
const baseUrl = (process.env.NEXT_PUBLIC_COMMERCE_API_URL ?? '').replace(/\/+$/, '')
|
|
31
41
|
const apiKey = process.env.NEXT_PUBLIC_COMMERCE_API_KEY ?? ''
|
|
42
|
+
const currencyCode = process.env.NEXT_PUBLIC_DEFAULT_CURRENCY || 'USD'
|
|
43
|
+
const isRealProvider = isRealBackendProvider(resolvedProviderType)
|
|
32
44
|
|
|
33
45
|
_commerce = createProvider({
|
|
34
|
-
provider:
|
|
46
|
+
provider: resolvedProviderType,
|
|
35
47
|
config: {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
48
|
+
...(isRealProvider
|
|
49
|
+
? {
|
|
50
|
+
baseUrl,
|
|
51
|
+
publishableKey: apiKey,
|
|
52
|
+
}
|
|
53
|
+
: {}),
|
|
54
|
+
currencyCode,
|
|
55
|
+
siteUrl: process.env.NEXT_PUBLIC_SITE_URL,
|
|
39
56
|
debug: process.env.NODE_ENV === 'development',
|
|
40
57
|
retry: {
|
|
41
58
|
maxRetries: 3,
|
|
@@ -60,7 +77,6 @@ function createCommerceInstance(): ReturnType<typeof createProvider> {
|
|
|
60
77
|
*/
|
|
61
78
|
export const commerce = new Proxy({} as ReturnType<typeof createProvider>, {
|
|
62
79
|
get(_target, prop: string | symbol) {
|
|
63
|
-
if (!isEnvConfigured()) return undefined
|
|
64
80
|
return createCommerceInstance()[prop as keyof ReturnType<typeof createProvider>]
|
|
65
81
|
},
|
|
66
82
|
})
|
|
@@ -7,11 +7,27 @@
|
|
|
7
7
|
|
|
8
8
|
import { z } from 'zod'
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
const realProviderSchema = z.enum(['medusa', 'shopify', 'bigcommerce'])
|
|
11
|
+
|
|
12
|
+
const BaseEnvSchema = z.object({
|
|
11
13
|
NEXT_PUBLIC_COMMERCE_PROVIDER: z
|
|
12
|
-
.enum(['medusa', 'shopify', 'bigcommerce', 'custom'])
|
|
13
|
-
.default('
|
|
14
|
+
.enum(['mock', 'medusa', 'shopify', 'bigcommerce', 'custom'])
|
|
15
|
+
.default('mock'),
|
|
16
|
+
|
|
17
|
+
NEXT_PUBLIC_DEFAULT_CURRENCY: z
|
|
18
|
+
.string()
|
|
19
|
+
.default('USD'),
|
|
14
20
|
|
|
21
|
+
NEXT_PUBLIC_SALES_CHANNEL_ID: z
|
|
22
|
+
.string()
|
|
23
|
+
.optional(),
|
|
24
|
+
|
|
25
|
+
FRONTEND_WEBHOOK_SECRET: z
|
|
26
|
+
.string()
|
|
27
|
+
.optional(),
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
const RealBackendEnvSchema = BaseEnvSchema.extend({
|
|
15
31
|
NEXT_PUBLIC_COMMERCE_API_URL: z
|
|
16
32
|
.string()
|
|
17
33
|
.url(),
|
|
@@ -19,22 +35,44 @@ export const EnvSchema = z.object({
|
|
|
19
35
|
NEXT_PUBLIC_COMMERCE_API_KEY: z
|
|
20
36
|
.string()
|
|
21
37
|
.min(1),
|
|
38
|
+
})
|
|
22
39
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
.default('USD'),
|
|
26
|
-
|
|
27
|
-
NEXT_PUBLIC_SALES_CHANNEL_ID: z
|
|
40
|
+
const MockEnvSchema = BaseEnvSchema.extend({
|
|
41
|
+
NEXT_PUBLIC_COMMERCE_API_URL: z
|
|
28
42
|
.string()
|
|
29
43
|
.optional(),
|
|
30
44
|
|
|
31
|
-
|
|
45
|
+
NEXT_PUBLIC_COMMERCE_API_KEY: z
|
|
32
46
|
.string()
|
|
33
47
|
.optional(),
|
|
34
48
|
})
|
|
35
49
|
|
|
50
|
+
export const EnvSchema = MockEnvSchema
|
|
51
|
+
|
|
36
52
|
export type Env = z.infer<typeof EnvSchema>
|
|
37
53
|
|
|
54
|
+
export function getConfiguredProvider(): Env['NEXT_PUBLIC_COMMERCE_PROVIDER'] {
|
|
55
|
+
return BaseEnvSchema.shape.NEXT_PUBLIC_COMMERCE_PROVIDER.parse(
|
|
56
|
+
process.env.NEXT_PUBLIC_COMMERCE_PROVIDER
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function isRealBackendProvider(
|
|
61
|
+
provider: string | undefined
|
|
62
|
+
): provider is z.infer<typeof realProviderSchema> {
|
|
63
|
+
return realProviderSchema.safeParse(provider).success
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function shouldUseMockProvider(): boolean {
|
|
67
|
+
const provider = getConfiguredProvider()
|
|
68
|
+
|
|
69
|
+
if (provider === 'mock') {
|
|
70
|
+
return true
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return !isRealBackendProvider(provider) || !isEnvConfigured()
|
|
74
|
+
}
|
|
75
|
+
|
|
38
76
|
/**
|
|
39
77
|
* Check whether required commerce env vars are present.
|
|
40
78
|
* Used to bail out gracefully during build/SSG.
|
|
@@ -55,14 +93,20 @@ export function isEnvConfigured(): boolean {
|
|
|
55
93
|
*/
|
|
56
94
|
export function getEnv(): Env {
|
|
57
95
|
try {
|
|
58
|
-
|
|
96
|
+
const rawEnv = {
|
|
59
97
|
NEXT_PUBLIC_COMMERCE_PROVIDER: process.env.NEXT_PUBLIC_COMMERCE_PROVIDER,
|
|
60
98
|
NEXT_PUBLIC_COMMERCE_API_URL: process.env.NEXT_PUBLIC_COMMERCE_API_URL,
|
|
61
99
|
NEXT_PUBLIC_COMMERCE_API_KEY: process.env.NEXT_PUBLIC_COMMERCE_API_KEY,
|
|
62
100
|
NEXT_PUBLIC_DEFAULT_CURRENCY: process.env.NEXT_PUBLIC_DEFAULT_CURRENCY,
|
|
63
101
|
NEXT_PUBLIC_SALES_CHANNEL_ID: process.env.NEXT_PUBLIC_SALES_CHANNEL_ID,
|
|
64
102
|
FRONTEND_WEBHOOK_SECRET: process.env.FRONTEND_WEBHOOK_SECRET,
|
|
65
|
-
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (shouldUseMockProvider()) {
|
|
106
|
+
return MockEnvSchema.parse(rawEnv)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return RealBackendEnvSchema.parse(rawEnv)
|
|
66
110
|
} catch (error) {
|
|
67
111
|
if (error instanceof z.ZodError) {
|
|
68
112
|
const issues = error.issues
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference types="next" />
|
|
2
2
|
/// <reference types="next/image-types/global" />
|
|
3
|
-
import "./.next/
|
|
3
|
+
import "./.next/types/routes.d.ts";
|
|
4
4
|
|
|
5
5
|
// NOTE: This file should not be edited
|
|
6
6
|
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|