@thorprovider/create-thor-app 4.1.9 → 5.0.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 (29) hide show
  1. package/README.md +57 -470
  2. package/dist/index.js +1 -2
  3. package/package.json +1 -1
  4. package/templates/default/.env.example +1 -1
  5. package/templates/default/.eslintrc.json +0 -4
  6. package/templates/default/README.md +2 -2
  7. package/templates/default/ai-validator.json +2 -2
  8. package/templates/default/app/cart/page.tsx +114 -0
  9. package/templates/default/app/checkout/page.tsx +395 -0
  10. package/templates/default/app/checkout/success/page.tsx +43 -0
  11. package/templates/default/app/layout.tsx +31 -7
  12. package/templates/default/app/products/[handle]/add-to-cart-button.tsx +85 -0
  13. package/templates/default/app/products/[handle]/page.tsx +108 -0
  14. package/templates/default/docs/README.md +0 -1
  15. package/templates/default/docs/project-structure.md +16 -6
  16. package/templates/default/docs/rules.md +1 -2
  17. package/templates/default/lib/commerce-client.ts +2 -3
  18. package/templates/default/lib/commerce.ts +1 -2
  19. package/templates/default/lib/env.ts +2 -2
  20. package/templates/default/lib/theme.ts +40 -0
  21. package/templates/default/package.json +7 -3
  22. package/templates/default/playwright.config.ts +86 -0
  23. package/templates/default/tests/e2e/auth.spec.ts +80 -0
  24. package/templates/default/tests/e2e/backend-unavailable.spec.ts +25 -0
  25. package/templates/default/tests/e2e/cart.spec.ts +79 -0
  26. package/templates/default/tests/e2e/checkout.spec.ts +95 -0
  27. package/templates/default/tests/e2e/global-setup.ts +42 -0
  28. package/templates/default/tests/e2e/product.spec.ts +53 -0
  29. package/templates/default/tests/e2e/smoke.spec.ts +48 -0
@@ -0,0 +1,85 @@
1
+ 'use client'
2
+
3
+ import React, { useState } from 'react'
4
+ import { useCart } from '@/components/providers/cart-provider'
5
+ import type { Product, ProductVariant } from '@thorprovider/types'
6
+
7
+ interface AddToCartButtonProps {
8
+ product: Product
9
+ }
10
+
11
+ export function AddToCartButton({ product }: AddToCartButtonProps) {
12
+ const { addItem, isLoading } = useCart()
13
+ const [selectedVariantId, setSelectedVariantId] = useState<string>(
14
+ product.variants[0]?.id ?? '',
15
+ )
16
+ const [quantity, setQuantity] = useState(1)
17
+ const [added, setAdded] = useState(false)
18
+
19
+ const selectedVariant: ProductVariant | undefined = product.variants.find(
20
+ (v) => v.id === selectedVariantId,
21
+ )
22
+
23
+ const unavailable = !selectedVariant?.availableForSale
24
+
25
+ async function handleAddToCart() {
26
+ if (!selectedVariantId || unavailable) return
27
+ await addItem(selectedVariantId, quantity)
28
+ setAdded(true)
29
+ setTimeout(() => setAdded(false), 2000)
30
+ }
31
+
32
+ return (
33
+ <div className="flex flex-col gap-4">
34
+ {product.variants.length > 1 && (
35
+ <div className="flex flex-col gap-1">
36
+ <label className="text-sm font-medium" htmlFor="variant-select">
37
+ Variant
38
+ </label>
39
+ <select
40
+ className="rounded-md border bg-background px-3 py-2 text-sm"
41
+ id="variant-select"
42
+ onChange={(e) => setSelectedVariantId(e.target.value)}
43
+ value={selectedVariantId}
44
+ >
45
+ {product.variants.map((v) => (
46
+ <option disabled={!v.availableForSale} key={v.id} value={v.id}>
47
+ {v.title}
48
+ {!v.availableForSale ? ' — Out of stock' : ''}
49
+ </option>
50
+ ))}
51
+ </select>
52
+ </div>
53
+ )}
54
+
55
+ <div className="flex items-center gap-2">
56
+ <label className="text-sm font-medium" htmlFor="quantity-input">
57
+ Qty
58
+ </label>
59
+ <input
60
+ className="w-16 rounded-md border bg-background px-3 py-2 text-sm"
61
+ id="quantity-input"
62
+ min={1}
63
+ onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value, 10) || 1))}
64
+ type="number"
65
+ value={quantity}
66
+ />
67
+ </div>
68
+
69
+ <button
70
+ className="rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground transition-opacity disabled:opacity-50"
71
+ disabled={isLoading || unavailable}
72
+ onClick={handleAddToCart}
73
+ type="button"
74
+ >
75
+ {isLoading
76
+ ? 'Adding…'
77
+ : added
78
+ ? 'Added to cart!'
79
+ : unavailable
80
+ ? 'Out of stock'
81
+ : 'Add to cart'}
82
+ </button>
83
+ </div>
84
+ )
85
+ }
@@ -0,0 +1,108 @@
1
+ import React from 'react'
2
+ import type { Metadata } from 'next'
3
+ import { notFound, redirect } from 'next/navigation'
4
+ import { commerce } from '@/lib/commerce'
5
+ import { formatPrice } from '@/lib/utils'
6
+ import { AddToCartButton } from './add-to-cart-button'
7
+
8
+ interface PDPPageProps {
9
+ params: Promise<{ handle: string }>
10
+ }
11
+
12
+ export async function generateMetadata({ params }: PDPPageProps): Promise<Metadata> {
13
+ const { handle } = await params
14
+ try {
15
+ const product = await commerce.getProduct(handle)
16
+ if (!product) return {}
17
+ return {
18
+ title: product.seo?.title ?? product.title,
19
+ description: product.seo?.description ?? product.description,
20
+ }
21
+ } catch {
22
+ return {}
23
+ }
24
+ }
25
+
26
+ export default async function ProductPage({ params }: PDPPageProps) {
27
+ const { handle } = await params
28
+
29
+ let product
30
+ try {
31
+ product = await commerce.getProduct(handle)
32
+ } catch {
33
+ redirect(`/backend-unavailable?returnTo=/products/${handle}`)
34
+ }
35
+
36
+ if (!product) {
37
+ notFound()
38
+ }
39
+
40
+ const firstVariantPrice = product.variants[0]?.price
41
+
42
+ return (
43
+ <main className="container mx-auto px-4 py-8">
44
+ <div className="grid gap-8 md:grid-cols-2">
45
+ {/* Images */}
46
+ <div className="flex flex-col gap-3">
47
+ <div className="aspect-square overflow-hidden rounded-xl bg-muted">
48
+ {product.featuredImage ? (
49
+ <img
50
+ alt={product.featuredImage.altText || product.title}
51
+ className="h-full w-full object-cover"
52
+ src={product.featuredImage.url}
53
+ />
54
+ ) : (
55
+ <div className="flex h-full items-center justify-center text-muted-foreground text-sm">
56
+ No image
57
+ </div>
58
+ )}
59
+ </div>
60
+ {product.images.length > 1 && (
61
+ <div className="flex gap-2 overflow-x-auto">
62
+ {product.images.slice(1, 5).map((img) => (
63
+ <div
64
+ className="h-16 w-16 flex-shrink-0 overflow-hidden rounded-md bg-muted"
65
+ key={img.url}
66
+ >
67
+ <img
68
+ alt={img.altText || product.title}
69
+ className="h-full w-full object-cover"
70
+ src={img.url}
71
+ />
72
+ </div>
73
+ ))}
74
+ </div>
75
+ )}
76
+ </div>
77
+
78
+ {/* Details */}
79
+ <div className="flex flex-col gap-6">
80
+ <div>
81
+ {product.vendor && (
82
+ <p className="text-sm font-medium text-muted-foreground uppercase tracking-wide mb-1">
83
+ {product.vendor}
84
+ </p>
85
+ )}
86
+ <h1 className="text-3xl font-bold">{product.title}</h1>
87
+ {firstVariantPrice && (
88
+ <p className="mt-2 text-2xl font-semibold">{formatPrice(firstVariantPrice)}</p>
89
+ )}
90
+ </div>
91
+
92
+ {product.description && (
93
+ <p className="text-muted-foreground leading-relaxed">{product.description}</p>
94
+ )}
95
+
96
+ <AddToCartButton product={product} />
97
+
98
+ <a
99
+ className="text-sm text-muted-foreground underline-offset-4 hover:underline"
100
+ href="/cart"
101
+ >
102
+ View cart
103
+ </a>
104
+ </div>
105
+ </div>
106
+ </main>
107
+ )
108
+ }
@@ -64,4 +64,3 @@ import { Button } from '@/components/ui/button';
64
64
  | Package | Why |
65
65
  |---------|-----|
66
66
  | `@thorprovider/components` | V0 creates UI from shadcn/ui — unique UI per client |
67
- | `@thorprovider/providers` | Providers are local code — V0 reads source directly |
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  title: "Project Structure"
3
3
  purpose: "Folder map and file ownership for V0-native Thor Commerce template"
4
- lastReviewed: "2026-05-01"
4
+ lastReviewed: "2026-05-23"
5
5
  ---
6
6
 
7
7
  # Project Structure
@@ -26,6 +26,16 @@ app/
26
26
  revalidate/route.ts ← Webhook ISR revalidation (opt-in)
27
27
  backend-unavailable/
28
28
  page.tsx ← Shown when backend is unreachable
29
+ products/
30
+ [handle]/
31
+ page.tsx ← Product detail page (Server Component)
32
+ add-to-cart-button.tsx ← Add-to-cart Client Component
33
+ cart/
34
+ page.tsx ← Cart page
35
+ checkout/
36
+ page.tsx ← Checkout (4-step form)
37
+ success/
38
+ page.tsx ← Order confirmation
29
39
 
30
40
  components/
31
41
  providers/
@@ -33,6 +43,7 @@ components/
33
43
  commerce-provider.tsx ← CommerceProvider + useCommerce hook
34
44
  region-provider.tsx ← RegionProvider + useRegion hook
35
45
  cart-provider.tsx ← CartProvider + useCart hook
46
+ theme-provider.tsx ← ThemeProvider (next-themes)
36
47
  ui/ ← shadcn/ui components (npx shadcn@latest add)
37
48
  [feature].tsx ← Page-specific components (V0 generates)
38
49
 
@@ -40,8 +51,8 @@ lib/
40
51
  commerce.ts ← Commerce singleton — FROZEN
41
52
  env.ts ← Zod environment schema — FROZEN
42
53
  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
54
+ theme.ts ← accentColorToOklch() — accent color mapping
55
+ commerce-client.ts ← Client-safe commerce factory
45
56
 
46
57
  docs/
47
58
  types.md ← Full @thorprovider/types reference
@@ -59,7 +70,6 @@ docs/
59
70
  | Reusable UI primitive | `npx shadcn@latest add [component]` → `components/ui/` |
60
71
  | API route | `app/api/[route]/route.ts` |
61
72
  | Environment variables | `.env.local` |
62
- | Typed demo fixtures for mock/incomplete presentation fallback | `lib/demo-data/*` or `lib/demo-catalog.ts` |
63
73
 
64
74
  ## Component Decision
65
75
 
@@ -83,8 +93,8 @@ Need a UI element?
83
93
  |------|-------|--------------|
84
94
  | `lib/commerce.ts` | Infrastructure | Never |
85
95
  | `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 |
96
+ | `lib/theme.ts` | Infrastructure | Never |
97
+ | `lib/commerce-client.ts` | Infrastructure | Never |
88
98
  | `components/providers/*` | Infrastructure | Never |
89
99
  | `styles/tokens.css` | Brand config | Only via create-thor-app flags |
90
100
  | `app/globals.css` | Design tokens | Only to add custom tokens |
@@ -14,7 +14,6 @@ Non-negotiable constraints. Breaking these causes build failures, runtime crashe
14
14
  |------|-----|-------------|
15
15
  | Import types from `@thorprovider/types` | Single source of truth for all domain objects | Type drift, adapter incompatibility |
16
16
  | Never import `@thorprovider/components` | Doesn't exist in this template | Build failure |
17
- | Never import `@thorprovider/providers` | Providers are local code in `components/providers/` | Build failure |
18
17
  | Never import backend SDKs (`@medusajs/*`, `@shopify/*`) | Backend is swappable via adapters | Vendor lock-in |
19
18
  | Never raw `fetch(COMMERCE_API_URL + '...')` | Bypasses adapter layer | No retry, no credential safety |
20
19
  | Always `formatPrice(money)` | `Money.amount` is a string like "29.99" | Broken display |
@@ -80,7 +79,7 @@ Never modify these — they are infrastructure:
80
79
 
81
80
  ## Pre-Commit Checklist
82
81
 
83
- - [ ] No `@thorprovider/components` or `@thorprovider/providers` imports?
82
+ - [ ] No `@thorprovider/components` imports?
84
83
  - [ ] No backend SDK imports (`@medusajs/*`, `@shopify/*`)?
85
84
  - [ ] No raw `fetch(COMMERCE_API_URL...)` calls?
86
85
  - [ ] No env-based gating that disables storefront rendering?
@@ -10,12 +10,11 @@
10
10
  * const instance = createCommerceClient(config) // config injected by layout.tsx
11
11
  */
12
12
 
13
- import { createProvider } from '@thorprovider/adapters'
13
+ import { createProvider, isSupportedProviderType } from '@thorprovider/adapters'
14
14
  import type { ProviderTypeString } from '@thorprovider/types'
15
- import { isSupportedProviderType } from '@thorprovider/types'
16
15
 
17
16
  /** Real-backend provider identifiers (must stay in sync with env.ts realProviderSchema) */
18
- const REAL_BACKEND_PROVIDERS = new Set(['medusa', 'stelorder'])
17
+ const REAL_BACKEND_PROVIDERS = new Set(['medusa', 'shopify', 'bigcommerce'])
19
18
 
20
19
  /**
21
20
  * Serializable commerce config — safe to pass across the RSC boundary.
@@ -11,9 +11,8 @@
11
11
 
12
12
  import 'server-only'
13
13
 
14
- import { createProvider } from '@thorprovider/adapters'
14
+ import { createProvider, isSupportedProviderType } from '@thorprovider/adapters'
15
15
  import type { ProviderTypeString } from '@thorprovider/types'
16
- import { isSupportedProviderType } from '@thorprovider/types'
17
16
  import { getConfiguredProvider, isRealBackendProvider, shouldUseMockProvider } from './env'
18
17
 
19
18
  let _commerce: ReturnType<typeof createProvider> | undefined
@@ -7,11 +7,11 @@
7
7
 
8
8
  import { z } from 'zod'
9
9
 
10
- const realProviderSchema = z.enum(['medusa', 'stelorder'])
10
+ const realProviderSchema = z.enum(['medusa', 'shopify', 'bigcommerce'])
11
11
 
12
12
  const BaseEnvSchema = z.object({
13
13
  NEXT_PUBLIC_COMMERCE_PROVIDER: z
14
- .enum(['mock', 'medusa', 'stelorder', 'custom'])
14
+ .enum(['mock', 'medusa', 'shopify', 'bigcommerce', 'custom'])
15
15
  .default('mock'),
16
16
 
17
17
  NEXT_PUBLIC_DEFAULT_CURRENCY: z
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Theme utilities for Thor Commerce storefront.
3
+ *
4
+ * Maps `StorefrontConfig.themeAccentColor` (a string name like "indigo")
5
+ * to an OKLCH CSS value injected as `--accent-color` on the `<html>` element.
6
+ *
7
+ * Lightness rule (WCAG AA safe pairs):
8
+ * Background L < 0.55 → foreground L ≥ 0.93
9
+ * Background L ≥ 0.55 → foreground L ≤ 0.20
10
+ */
11
+
12
+ /** Maps an accent color name to its OKLCH background value */
13
+ const ACCENT_OKLCH: Record<string, string> = {
14
+ indigo: 'oklch(0.55 0.22 264)',
15
+ blue: 'oklch(0.55 0.22 232)',
16
+ violet: 'oklch(0.55 0.22 290)',
17
+ purple: 'oklch(0.55 0.22 310)',
18
+ pink: 'oklch(0.55 0.22 350)',
19
+ red: 'oklch(0.55 0.22 27)',
20
+ orange: 'oklch(0.55 0.22 55)',
21
+ amber: 'oklch(0.60 0.18 75)',
22
+ yellow: 'oklch(0.65 0.18 95)',
23
+ lime: 'oklch(0.60 0.18 130)',
24
+ green: 'oklch(0.55 0.18 155)',
25
+ teal: 'oklch(0.55 0.18 185)',
26
+ cyan: 'oklch(0.55 0.18 210)',
27
+ slate: 'oklch(0.45 0.04 240)',
28
+ gray: 'oklch(0.45 0.01 240)',
29
+ neutral: 'oklch(0.45 0.00 0)',
30
+ stone: 'oklch(0.45 0.02 60)',
31
+ zinc: 'oklch(0.45 0.01 240)',
32
+ }
33
+
34
+ /**
35
+ * Converts a StorefrontConfig accent color name to an OKLCH CSS value.
36
+ * Falls back to indigo if the name is unknown or empty.
37
+ */
38
+ export function accentColorToOklch(name: string): string {
39
+ return ACCENT_OKLCH[name.toLowerCase()] ?? ACCENT_OKLCH['indigo']
40
+ }
@@ -8,11 +8,14 @@
8
8
  "dev": "next dev",
9
9
  "start": "next start",
10
10
  "type-check": "tsc --noEmit",
11
- "generate:agent-index": "node ../../scripts/generate-core-agents-index.cjs"
11
+ "generate:agent-index": "node ../../scripts/generate-core-agents-index.cjs",
12
+ "test:e2e": "playwright test",
13
+ "test:e2e:ui": "playwright test --ui",
14
+ "test:e2e:report": "playwright show-report"
12
15
  },
13
16
  "dependencies": {
14
- "@thorprovider/adapters": "^5.0.0",
15
- "@thorprovider/types": "^3.3.0",
17
+ "@thorprovider/adapters": "^5.1.0",
18
+ "@thorprovider/types": "^6.0.0",
16
19
  "clsx": "^2.1.1",
17
20
  "next": "16.0.10",
18
21
  "next-themes": "^0.4.6",
@@ -23,6 +26,7 @@
23
26
  "zod": "^3.25.0"
24
27
  },
25
28
  "devDependencies": {
29
+ "@playwright/test": "^1.60.0",
26
30
  "@tailwindcss/postcss": "^4.1.9",
27
31
  "@types/node": "^22",
28
32
  "@types/react": "^19",
@@ -0,0 +1,86 @@
1
+ import { defineConfig } from '@playwright/test'
2
+ import path from 'path'
3
+
4
+ // Load .env.test when running tests
5
+ import { config as dotenv } from 'dotenv'
6
+ dotenv({ path: path.resolve(__dirname, '.env.test') })
7
+
8
+ export const STORAGE_STATE = path.join(__dirname, 'playwright/.auth/customer.json')
9
+
10
+ // Use port 3001 to avoid colliding with any dashboard dev server on :3000
11
+ const BASE_URL = 'http://localhost:3001'
12
+
13
+ export default defineConfig({
14
+ testDir: './tests/e2e',
15
+ fullyParallel: false, // sequential — share backend state safely
16
+ retries: process.env.CI ? 2 : 0,
17
+ workers: 1,
18
+ reporter: [['list'], ['html', { open: 'never' }]],
19
+ timeout: 45_000,
20
+ expect: { timeout: 10_000 },
21
+
22
+ use: {
23
+ baseURL: BASE_URL,
24
+ // Use system-installed Chrome to avoid downloading Chromium
25
+ channel: 'chrome',
26
+ headless: true,
27
+ trace: 'on-first-retry',
28
+ screenshot: 'only-on-failure',
29
+ },
30
+
31
+ projects: [
32
+ // Global setup: login once, save storage state
33
+ {
34
+ name: 'setup',
35
+ testMatch: /global-setup\.ts/,
36
+ },
37
+ // Public suites — no auth required
38
+ {
39
+ name: 'smoke',
40
+ testMatch: /smoke\.spec\.ts/,
41
+ dependencies: ['setup'],
42
+ },
43
+ {
44
+ name: 'product',
45
+ testMatch: /product\.spec\.ts/,
46
+ dependencies: ['setup'],
47
+ },
48
+ {
49
+ name: 'cart',
50
+ testMatch: /cart\.spec\.ts/,
51
+ dependencies: ['setup'],
52
+ },
53
+ {
54
+ name: 'checkout',
55
+ testMatch: /checkout\.spec\.ts/,
56
+ dependencies: ['setup'],
57
+ use: { storageState: STORAGE_STATE },
58
+ },
59
+ // Auth suite — uses saved storage state
60
+ {
61
+ name: 'auth',
62
+ testMatch: /auth\.spec\.ts/,
63
+ dependencies: ['setup'],
64
+ },
65
+ // Backend unavailable fallback
66
+ {
67
+ name: 'backend-unavailable',
68
+ testMatch: /backend-unavailable\.spec\.ts/,
69
+ },
70
+ ],
71
+
72
+ // Start the core storefront dev server on port 3001
73
+ webServer: {
74
+ command: 'yarn dev --port 3001',
75
+ url: BASE_URL,
76
+ reuseExistingServer: true, // reuse if already running (start fresh if not)
77
+ timeout: 90_000,
78
+ env: {
79
+ NEXT_PUBLIC_COMMERCE_PROVIDER: 'medusa',
80
+ NEXT_PUBLIC_COMMERCE_API_URL: 'https://dev.erpthor.com',
81
+ NEXT_PUBLIC_COMMERCE_API_KEY:
82
+ 'pk_aa2627358b3ebf74fcf9da2733d080bea8585b30d9df32ef4d46e2d7868dce6f',
83
+ NEXT_PUBLIC_DEFAULT_CURRENCY: 'USD',
84
+ },
85
+ },
86
+ })
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Auth tests — customer login, logout, and unauthenticated state.
3
+ *
4
+ * Uses Playwright's server-side `request` context to bypass CORS restrictions
5
+ * when calling the Medusa auth endpoints directly. The storefront itself only
6
+ * stores the JWT in localStorage (`thor_auth_token`); there is no server-side
7
+ * session cookie on the storefront.
8
+ */
9
+ import { test, expect, request } from '@playwright/test'
10
+
11
+ const EMAIL = process.env.TEST_CUSTOMER_EMAIL ?? 'test.e2e@thorprovider.com'
12
+ const PASSWORD = process.env.TEST_CUSTOMER_PASSWORD ?? 'TestE2E#2026!'
13
+ const API_URL = 'https://dev.erpthor.com'
14
+ const API_KEY = 'pk_aa2627358b3ebf74fcf9da2733d080bea8585b30d9df32ef4d46e2d7868dce6f'
15
+
16
+ test.describe('Auth', () => {
17
+ test.beforeEach(async ({ page }) => {
18
+ // Start unauthenticated
19
+ await page.goto('/')
20
+ await page.evaluate(() => localStorage.removeItem('thor_auth_token'))
21
+ })
22
+
23
+ test('login returns a valid JWT token', async () => {
24
+ const apiContext = await request.newContext({ baseURL: API_URL })
25
+ const res = await apiContext.post('/auth/customer/emailpass', {
26
+ data: { email: EMAIL, password: PASSWORD },
27
+ })
28
+ expect(res.ok()).toBe(true)
29
+ const { token } = await res.json()
30
+ expect(token).toBeTruthy()
31
+ expect(typeof token).toBe('string')
32
+ await apiContext.dispose()
33
+ })
34
+
35
+ test('wrong credentials return 401 from backend', async () => {
36
+ const apiContext = await request.newContext({ baseURL: API_URL })
37
+ const res = await apiContext.post('/auth/customer/emailpass', {
38
+ data: { email: 'nobody@nowhere.com', password: 'wrongpassword' },
39
+ })
40
+ expect(res.status()).toBe(401)
41
+ await apiContext.dispose()
42
+ })
43
+
44
+ test('getCurrentCustomer returns customer data when authenticated', async () => {
45
+ const apiContext = await request.newContext({ baseURL: API_URL })
46
+
47
+ // Login
48
+ const loginRes = await apiContext.post('/auth/customer/emailpass', {
49
+ data: { email: EMAIL, password: PASSWORD },
50
+ })
51
+ const { token } = await loginRes.json()
52
+
53
+ // Fetch customer profile
54
+ const meRes = await apiContext.get('/store/customers/me', {
55
+ headers: {
56
+ Authorization: `Bearer ${token}`,
57
+ 'x-publishable-api-key': API_KEY,
58
+ },
59
+ })
60
+ expect(meRes.ok()).toBe(true)
61
+ const { customer } = await meRes.json()
62
+ expect(customer.email).toBe(EMAIL)
63
+ expect(customer.has_account).toBe(true)
64
+ await apiContext.dispose()
65
+ })
66
+
67
+ test('storefront homepage loads without authentication', async ({ page }) => {
68
+ // No auth token set — public routes must work without a session
69
+ await page.goto('/')
70
+ const productCards = page.locator('main article')
71
+ await expect(productCards.first()).toBeVisible({ timeout: 15_000 })
72
+ })
73
+
74
+ test('JWT injected into localStorage is readable by the page', async ({ page }) => {
75
+ // Simulate what the commerce adapter does on login
76
+ await page.evaluate((jwt) => localStorage.setItem('thor_auth_token', jwt), 'test-token-value')
77
+ const stored = await page.evaluate(() => localStorage.getItem('thor_auth_token'))
78
+ expect(stored).toBe('test-token-value')
79
+ })
80
+ })
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Backend unavailable tests — verifies the graceful fallback when the commerce
3
+ * backend is unreachable.
4
+ *
5
+ * Strategy: navigate directly to /backend-unavailable (which is a static route),
6
+ * and also verify that next.config.ts redirects properly when API calls fail.
7
+ * We do NOT spin up a broken server — we test the page itself directly.
8
+ */
9
+ import { test, expect } from '@playwright/test'
10
+
11
+ test.describe('Backend Unavailable', () => {
12
+ test('/backend-unavailable page renders correctly', async ({ page }) => {
13
+ const res = await page.goto('/backend-unavailable')
14
+
15
+ // Page should return 200 (it's a Next.js page, not a redirect)
16
+ expect(res?.status()).toBe(200)
17
+ // The page uses a <div> wrapper, not <main> — verify via heading text
18
+ await expect(page.getByRole('heading', { name: /service temporarily unavailable/i })).toBeVisible()
19
+ })
20
+
21
+ test('/backend-unavailable with returnTo query param is accessible', async ({ page }) => {
22
+ await page.goto('/backend-unavailable?returnTo=/')
23
+ await expect(page.getByRole('heading', { name: /service temporarily unavailable/i })).toBeVisible()
24
+ })
25
+ })
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Cart tests — cart state management via real backend.
3
+ */
4
+ import { test, expect } from '@playwright/test'
5
+
6
+ const PRODUCT_HANDLE =
7
+ 'tel-fono-xiaomi-redmi-15c-4gb-ram-4gb-virtual-total-8gb-128gb-almacenamiento-con-cover-mica-y-aud-fonos-negro-e8d4a168'
8
+
9
+ test.describe('Cart', () => {
10
+ test.setTimeout(60_000)
11
+
12
+ test.beforeEach(async ({ page }) => {
13
+ // Clear cart without triggering a heavy getProducts call.
14
+ // /cart is a lightweight page that doesn't fetch the product catalog.
15
+ await page.goto('/cart')
16
+ await page.evaluate(() => localStorage.removeItem('thor-cart-id'))
17
+ })
18
+
19
+ test('empty cart shows empty state', async ({ page }) => {
20
+ await page.goto('/cart')
21
+ await expect(page.getByText('Your cart is empty')).toBeVisible()
22
+ await expect(page.getByRole('link', { name: /continue shopping/i })).toBeVisible()
23
+ })
24
+
25
+ test('adding a product appears in cart', async ({ page }) => {
26
+ // Add product via PDP
27
+ await page.goto(`/products/${PRODUCT_HANDLE}`)
28
+ const addBtn = page.getByRole('button', { name: /add to cart/i })
29
+ await expect(addBtn).toBeVisible({ timeout: 15_000 })
30
+ await addBtn.click()
31
+ // Wait for the button to show "Added to cart!" confirming the cart API call succeeded
32
+ await expect(page.getByRole('button', { name: /added to cart/i })).toBeVisible({ timeout: 15_000 })
33
+
34
+ // Navigate to cart
35
+ await page.goto('/cart')
36
+
37
+ // Cart should show at least one item
38
+ await expect(page.locator('main').getByRole('img').first().or(page.locator('main article, main .rounded-xl.border').first())).toBeVisible({
39
+ timeout: 10_000,
40
+ })
41
+
42
+ // Should show subtotal and total
43
+ await expect(page.getByText(/subtotal/i)).toBeVisible()
44
+ await expect(page.getByText('Total', { exact: true })).toBeVisible()
45
+ })
46
+
47
+ test('cart shows "Proceed to checkout" link', async ({ page }) => {
48
+ // Add product first
49
+ await page.goto(`/products/${PRODUCT_HANDLE}`)
50
+ await expect(page.getByRole('button', { name: /add to cart/i })).toBeVisible({ timeout: 25_000 })
51
+ await page.getByRole('button', { name: /add to cart/i }).click()
52
+ await expect(page.getByRole('button', { name: /added to cart/i })).toBeVisible({ timeout: 25_000 })
53
+
54
+ await page.goto('/cart')
55
+
56
+ // Proceed to checkout link should exist
57
+ await expect(page.getByRole('link', { name: /proceed to checkout/i })).toBeVisible({
58
+ timeout: 10_000,
59
+ })
60
+ })
61
+
62
+ test('removing item from cart returns to empty state', async ({ page }) => {
63
+ // Add product
64
+ await page.goto(`/products/${PRODUCT_HANDLE}`)
65
+ await expect(page.getByRole('button', { name: /add to cart/i })).toBeVisible({ timeout: 25_000 })
66
+ await page.getByRole('button', { name: /add to cart/i }).click()
67
+ await expect(page.getByRole('button', { name: /added to cart/i })).toBeVisible({ timeout: 25_000 })
68
+
69
+ await page.goto('/cart')
70
+
71
+ // Click the remove (×) button
72
+ const removeBtn = page.getByRole('button', { name: /remove item/i })
73
+ await expect(removeBtn).toBeVisible({ timeout: 10_000 })
74
+ await removeBtn.click()
75
+
76
+ // Cart should be empty now
77
+ await expect(page.getByText('Your cart is empty')).toBeVisible({ timeout: 10_000 })
78
+ })
79
+ })