@thorprovider/create-thor-app 3.0.2 → 3.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 (3) hide show
  1. package/README.md +37 -6
  2. package/dist/index.js +600 -99
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
+ ---
2
+ title: create-thor-app
3
+ purpose: CLI scaffolding tool for generating new Thor Commerce applications from the core template
4
+ lastReviewed: "2026-04-27"
5
+ ---
6
+
1
7
  # create-thor-app
2
8
 
3
9
  CLI scaffolding tool to generate a new Thor Commerce application from the `@thorprovider/core` template.
@@ -135,7 +141,7 @@ export NODE_AUTH_TOKEN=ghp_xxxxx # For GitHub Packages .npmrc
135
141
  | `--skip-install` | Skip yarn install | `false` |
136
142
  | `--skip-remote` | Skip GitHub remote repo creation | `false` |
137
143
  | `--skip-vercel` | Skip Vercel project linking | `false` |
138
- | `--skip-v0-context` | Skip .v0-context.md generation | `false` |
144
+ | `--no-context` | Skip .agents/ directory generation | `false` |
139
145
  | `-h, --help` | Show help | — |
140
146
 
141
147
  > **Security note**: `--commerce-api-key` values appear in shell history.
@@ -188,7 +194,7 @@ Next steps:
188
194
 
189
195
  3. Connect to V0:
190
196
  Open https://v0.dev → New project → Connect GitHub repo
191
- Then paste .v0-context.md as the first message
197
+ V0 will auto-discover .agents/AGENTS.md for context
192
198
 
193
199
  4. Start developing:
194
200
  cd projects/my-store && yarn dev
@@ -199,7 +205,24 @@ Next steps:
199
205
  projects/my-store/
200
206
  ├── .env # Backend config (copy from .env.example)
201
207
  ├── .npmrc # GitHub Packages auth (included)
202
- ├── .v0-context.md # 14 frozen architecture files for V0
208
+ ├── .agents/
209
+ │ ├── AGENTS.md # Entry point for AI agents (V0, Claude Code, OpenCode)
210
+ │ ├── context/ # Architecture, types, API, patterns, rules
211
+ │ │ ├── architecture.md
212
+ │ │ ├── project-structure.md
213
+ │ │ ├── dependencies.md
214
+ │ │ ├── components.md
215
+ │ │ ├── types.md
216
+ │ │ ├── commerce-api.md
217
+ │ │ ├── patterns.md
218
+ │ │ └── rules.md
219
+ │ └── skills/ # Playbooks for repeatable tasks
220
+ │ ├── generate-page.md
221
+ │ ├── generate-component.md
222
+ │ ├── generate-module.md
223
+ │ ├── add-commerce-feature.md
224
+ │ ├── add-route.md
225
+ │ └── audit-changes.md
203
226
  ├── .vercel/
204
227
  │ └── project.json # Vercel org/project IDs (when Vercel linked)
205
228
  ├── .github/
@@ -230,9 +253,17 @@ projects/my-store/
230
253
 
231
254
  GitHub Packages registry config. Uses `NODE_AUTH_TOKEN` ENV for authentication.
232
255
 
233
- ### .v0-context.md
256
+ ### .agents/
257
+
258
+ Contains persistent AI context for V0 and other agents (Claude Code, OpenCode, Cursor, etc.).
259
+ Inspired by Claude Code's `CLAUDE.md + .claude/skills/` and OpenCode's `AGENTS.md + .opencode/agents/` patterns.
260
+
261
+ Structure:
262
+ - **`AGENTS.md`** — root entry point: what the app is, what agents can/cannot do, read order
263
+ - **`context/`** — architecture rules, types, API signatures, patterns, hard constraints (adapted from `packages/core/docs/`)
264
+ - **`skills/`** — playbooks for repeatable tasks (generate-page, generate-component, audit-changes, etc.)
234
265
 
235
- Contains 14 frozen architecture files (docs, lib, components, config) for V0 prompting. Paste this as the first message when setting up V0 to avoid re-implementing patterns.
266
+ Use `--no-context` to skip generation.
236
267
 
237
268
  ### .env
238
269
 
@@ -432,7 +463,7 @@ The package is structured for maintainability:
432
463
  | `src/helpers/install.ts` | Yarn install wrapper |
433
464
  | `src/helpers/env.ts` | .env + .npmrc creation (accepts overrides for backend flags) |
434
465
  | `src/helpers/site-config.ts` | Patches `config/site.config.ts` with `--preset` / `--site-url` |
435
- | `src/helpers/v0-context.ts` | .v0-context.md generation |
466
+ | `src/helpers/agents-dir.ts` | .agents/ directory generation (AGENTS.md + context/ + skills/) |
436
467
  | `tsup.config.ts` | Build config + template bundling hook (copies regions script) |
437
468
 
438
469
  ### Dual-mode detection
package/dist/index.js CHANGED
@@ -66,7 +66,7 @@ function createCopyFilter(sourceRoot) {
66
66
  import {
67
67
  cpSync,
68
68
  existsSync as existsSync8,
69
- mkdirSync as mkdirSync2,
69
+ mkdirSync as mkdirSync3,
70
70
  rmSync
71
71
  } from "fs";
72
72
  import { join as join8, relative as relative2 } from "path";
@@ -425,120 +425,621 @@ function patchSiteConfig(targetDir, overrides) {
425
425
  }
426
426
  }
427
427
 
428
- // src/helpers/v0-context.ts
429
- import { existsSync as existsSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
428
+ // src/helpers/agents-dir.ts
429
+ import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
430
430
  import { join as join6 } from "path";
431
- var V0_CONTEXT_FILES = [
432
- "HOW_TO_USE_THIS_PACKAGE.md",
433
- "docs/components.md",
434
- "lib/commerce.ts",
435
- "lib/storefront-config.ts",
436
- "lib/commerce-provider.tsx",
437
- "lib/region-provider.tsx",
438
- "lib/auth-context.tsx",
439
- "lib/cart-provider.tsx",
440
- "components/providers/app-providers.tsx",
441
- "components/providers/navigation-provider.tsx",
442
- "app/layout.tsx",
443
- "app/page.tsx",
444
- "config/site.config.ts"
445
- ];
446
- function generateV0Context(name, targetDir, sourceDir) {
447
- let md = `# V0 Context \u2014 ${name}
431
+ function write(filePath, content) {
432
+ writeFileSync4(filePath, content, "utf-8");
433
+ }
434
+ function readSource(sourceDir, relPath) {
435
+ const abs = join6(sourceDir, relPath);
436
+ if (!existsSync6(abs)) return "";
437
+ return readFileSync5(abs, "utf-8");
438
+ }
439
+ function buildAgentsMd(name) {
440
+ return `# ${name} \u2014 Agent Instructions
448
441
 
449
- `;
450
- md += `> Generated by create-thor-app on ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}
442
+ > This file is the entry point for any AI agent (V0, Claude Code, OpenCode, Cursor, etc.) working on this app.
443
+ > Read this first. Then read the files listed below in order.
451
444
 
452
- `;
453
- md += `## Project
454
- `;
455
- md += `- **Package**: \`@thorprovider/${name}\`
456
- `;
457
- md += `- **Stack**: Next.js 16, React 19, Tailwind CSS 4, @thorprovider/* packages
458
- `;
459
- md += `- **Architecture**: L1 (types) \u2192 L2 (adapters) \u2192 L2.5 (providers) \u2192 L3 (components) \u2192 L5 (this app)
445
+ ## What This App Is
460
446
 
461
- `;
462
- md += `---
447
+ \`@thorprovider/${name}\` is a **Thor Commerce storefront** \u2014 a Next.js 16 headless e-commerce app
448
+ built on the \`@thorprovider/*\` package ecosystem.
463
449
 
464
- `;
465
- md += `## Before Implementing \u2014 Read @thorprovider/core Docs First
450
+ Stack: **Next.js 16 \xB7 React 19 \xB7 Tailwind CSS 4 \xB7 @thorprovider/components \xB7 @thorprovider/adapters**
466
451
 
467
- `;
468
- md += `Read these 7 files **in order** before writing any feature. They are your single source of truth for types, method signatures, component inventory, and patterns.
452
+ Architecture: **L1 (types) \u2192 L2 (adapters) \u2192 L2.5 (providers) \u2192 L3 (components) \u2192 L5 (this app)**
469
453
 
470
- `;
471
- md += `| Order | File | What you get |
472
- `;
473
- md += `|------:|------|-------------|
474
- `;
475
- md += `| 1 | \`packages/core/docs/README.md\` | Doc map + entry point |
476
- `;
477
- md += `| 2 | \`packages/core/docs/project-structure.md\` | Directory layout + conventions |
478
- `;
479
- md += `| 3 | \`packages/core/docs/dependencies.md\` | 55-component inventory (TIER 1\u20134) + which components exist |
480
- `;
481
- md += `| 3b | \`packages/core/docs/components.md\` | Complete @thorprovider/components API: import paths, key props, callbacks, usage examples |
482
- `;
483
- md += `| 4 | \`packages/core/docs/types.md\` | All domain types: Product, Cart, Order, Customer, Address, Money\u2026 |
484
- `;
485
- md += `| 5 | \`packages/core/docs/commerce-api.md\` | Every \`commerce.*()\` method with exact signatures + circuit breaker rules |
486
- `;
487
- md += `| 6 | \`packages/core/docs/patterns.md\` | Page patterns, server/client boundaries, data fetching |
488
- `;
489
- md += `| 7 | \`packages/core/docs/rules.md\` | Hard constraints \u2014 what V0 must never do |
454
+ ---
490
455
 
491
- `;
492
- md += `> **AGENTS.md** (root) is the navigation index for the full monorepo. Use it to discover where anything lives.
456
+ ## Read Order (Required Before Implementing Anything)
493
457
 
494
- `;
495
- md += `### Quick rules from docs
458
+ | # | File | What you get |
459
+ |---|------|-------------|
460
+ | 1 | \`.agents/context/architecture.md\` | L1\u2013L5 layer rules, import constraints, frozen files |
461
+ | 2 | \`.agents/context/project-structure.md\` | Folder map, where to create files |
462
+ | 3 | \`.agents/context/dependencies.md\` | @thorprovider/* packages, 55-component inventory |
463
+ | 4 | \`.agents/context/components.md\` | Full @thorprovider/components API with props and examples |
464
+ | 5 | \`.agents/context/types.md\` | All domain types: Product, Cart, Order, Customer, Address, Money |
465
+ | 6 | \`.agents/context/commerce-api.md\` | Every \`commerce.*()\` method + circuit breaker rules |
466
+ | 7 | \`.agents/context/patterns.md\` | Server/client boundaries, data fetching, styling patterns |
467
+ | 8 | \`.agents/context/rules.md\` | Hard constraints \u2014 what you must NEVER do |
496
468
 
497
- `;
498
- md += `- **Types are in \`types.md\`** \u2014 never guess field names. \`Product\` has \`handle\`, not \`slug\`. \`Cart\` has \`cost.totalAmount\`, not \`total\`.
499
- `;
500
- md += `- **Method signatures are in \`commerce-api.md\`** \u2014 \`getProducts({ query, sortKey, first, skip })\`, not \`getProducts(filter)\`.
501
- `;
502
- md += `- **Check \`dependencies.md\` before creating UI** \u2014 if a component exists in TIER 1\u20134, use it. Do not create a new \`<Button>\` or \`<ProductCard>\`.
503
- `;
504
- md += `- **Optional methods need a guard** \u2014 \`if (commerce.method) { await commerce.method() }\` (see commerce-api.md).
505
- `;
506
- md += `- **All backend reads use circuit breaker** \u2014 \`backendCircuitBreaker.execute(() => commerce.getProducts(), [])\`.
469
+ ---
470
+
471
+ ## What You CAN Do
472
+
473
+ - Add new pages in \`app/\`
474
+ - Add new components in \`components/\`
475
+ - Extend \`config/site.config.ts\` (values only \u2014 shape is frozen)
476
+ - Add API routes in \`app/api/\`
477
+ - Use any component from \`@thorprovider/components\` (check \`dependencies.md\` first)
478
+ - Call any \`commerce.*\` method (see \`commerce-api.md\` for signatures)
479
+
480
+ ## What You MUST NOT Do
481
+
482
+ - Modify \`lib/\` files (frozen infrastructure \u2014 see \`architecture.md\`)
483
+ - Modify \`components/providers/\` (frozen provider chain)
484
+ - Modify \`app/layout.tsx\` (frozen root layout)
485
+ - Import \`next/link\` or \`next/image\` inside \`components/\` (use \`useNavigation()\`)
486
+ - Use hardcoded hex colors or \`rgb()\` (use CSS tokens: \`var(--foreground)\`, etc.)
487
+ - Import backend SDKs directly (\`@medusajs/js-sdk\`, \`@shopify/api\`, etc.)
488
+ - Call \`commerce.*\` read methods without \`backendCircuitBreaker.execute()\`
489
+
490
+ ---
507
491
 
492
+ ## Available Skills
493
+
494
+ Skills are playbooks for common tasks. Load them when you need step-by-step guidance:
495
+
496
+ | Skill | When to use |
497
+ |-------|-------------|
498
+ | \`.agents/skills/generate-page.md\` | Creating a new Next.js page |
499
+ | \`.agents/skills/generate-component.md\` | Creating a new React component |
500
+ | \`.agents/skills/generate-module.md\` | Creating an L4 feature module |
501
+ | \`.agents/skills/add-commerce-feature.md\` | Adding a feature that uses commerce.* methods |
502
+ | \`.agents/skills/add-route.md\` | Adding an API route with circuit breaker |
503
+ | \`.agents/skills/audit-changes.md\` | Validating generated code before committing |
504
+
505
+ ---
506
+
507
+ ## Quick Rules (Memorize These)
508
+
509
+ - **Types**: \`Product.handle\` (not \`slug\`), \`Cart.cost.totalAmount\` (not \`total\`), \`Money.amount\` is a string
510
+ - **Methods**: \`getProducts({ query, sortKey, first, skip })\` \u2014 see \`commerce-api.md\` for exact signatures
511
+ - **Components**: Check \`dependencies.md\` before creating any UI \u2014 55 components already exist
512
+ - **Optional methods**: Guard with \`if (commerce.method)\` before calling
513
+ - **All reads**: Wrap with \`backendCircuitBreaker.execute(() => commerce.method(), fallback)\`
508
514
  `;
509
- md += `---
515
+ }
516
+ function buildArchitectureMd() {
517
+ return `---
518
+ title: "Architecture"
519
+ purpose: "L1\u2013L5 layer system, import rules, frozen files"
520
+ ---
521
+
522
+ # Architecture
523
+
524
+ ## 5-Layer System (Non-Negotiable)
525
+
526
+ \`\`\`
527
+ L1: @thorprovider/types \u2192 Domain types only. Zero dependencies.
528
+ L2: @thorprovider/adapters \u2192 Backend abstraction. Imports L1 only.
529
+ L2.5: @thorprovider/providers \u2192 React context/hooks. Imports L1, L2.
530
+ L3: @thorprovider/components \u2192 UI components. Imports L1. NO Next.js.
531
+ L4: modules/ \u2192 Feature modules. Imports L3, L2 via props. NO Next.js.
532
+ L5: this app \u2192 Next.js app. Imports everything. Orchestrates L4.
533
+ \`\`\`
534
+
535
+ **Rule**: Imports flow L5 \u2192 L4 \u2192 L3 \u2192 L2 \u2192 L1. Never the reverse.
536
+ **Rule**: L3 and L4 NEVER import \`next/link\`, \`next/image\`, or any \`next/*\`.
537
+ **Rule**: L2 NEVER imports React or any UI library.
510
538
 
539
+ ---
540
+
541
+ ## Frozen Files (Do NOT Modify)
542
+
543
+ These files define the app's infrastructure. Changing them breaks the architecture.
544
+
545
+ | File | Why frozen |
546
+ |------|-----------|
547
+ | \`lib/commerce.ts\` | Commerce singleton \u2014 backend is swappable via adapters |
548
+ | \`lib/commerce-provider.tsx\` | ClientCommerceProvider + useCommerce hook |
549
+ | \`lib/region-provider.tsx\` | ClientRegionProvider + useRegion hook |
550
+ | \`lib/auth-context.tsx\` | AuthProvider + useAuth hook |
551
+ | \`lib/cart-provider.tsx\` | ClientCartProvider + useCart hook |
552
+ | \`lib/storefront-config.ts\` | Backend-driven theme accent fetch |
553
+ | \`lib/region-detection.ts\` | IP-based region detection |
554
+ | \`components/providers/app-providers.tsx\` | Provider chain composite (order is critical) |
555
+ | \`components/providers/navigation-provider.tsx\` | ClientNavigationProvider wrapper |
556
+ | \`app/layout.tsx\` | Root layout: ThemeProvider + AppProviders |
557
+ | \`config/site.config.ts\` | Shape is frozen; values can change |
558
+
559
+ ---
560
+
561
+ ## Provider Chain (Frozen Order)
562
+
563
+ \`\`\`tsx
564
+ // app/layout.tsx
565
+ <ThemeProvider preset={siteConfig.preset}>
566
+ <AppProviders initialRegionId={initialRegionId}>
567
+ {children}
568
+ </AppProviders>
569
+ </ThemeProvider>
570
+
571
+ // components/providers/app-providers.tsx
572
+ <ClientCommerceProvider>
573
+ <ClientRegionProvider initialRegionId={initialRegionId}>
574
+ <AuthProvider>
575
+ <ClientCartProvider>
576
+ <ClientNavigationProvider>
577
+ {children}
578
+ </ClientNavigationProvider>
579
+ </ClientCartProvider>
580
+ </AuthProvider>
581
+ </ClientRegionProvider>
582
+ </ClientCommerceProvider>
583
+ \`\`\`
584
+
585
+ Each provider depends on the context of the prior one. **Reordering = runtime crash.**
586
+ To add a custom provider \u2192 wrap \`{children}\` **inside** \`ClientNavigationProvider\`.
587
+
588
+ ---
589
+
590
+ ## Backend Swappability
591
+
592
+ The commerce backend is abstracted via \`@thorprovider/adapters\`. Never import backend SDKs directly.
593
+
594
+ \`\`\`ts
595
+ // \u2705 Correct \u2014 backend is swappable
596
+ import { commerce } from '@/lib/commerce';
597
+
598
+ // \u274C Never \u2014 vendor lock-in
599
+ import Medusa from '@medusajs/js-sdk';
600
+ \`\`\`
511
601
  `;
512
- md += `## Frozen Architecture Files
602
+ }
603
+ function buildGeneratePageSkill() {
604
+ return `---
605
+ name: generate-page
606
+ description: Step-by-step playbook for creating a new Next.js page in a Thor Commerce app. Use when adding a new route or page.
607
+ ---
608
+
609
+ # Skill: Generate Page
610
+
611
+ ## Before You Start
612
+
613
+ 1. Read \`.agents/context/project-structure.md\` \u2014 confirm where the page goes
614
+ 2. Read \`.agents/context/commerce-api.md\` \u2014 identify which \`commerce.*\` methods you need
615
+ 3. Read \`.agents/context/dependencies.md\` \u2014 check if needed components already exist
616
+
617
+ ## Steps
618
+
619
+ ### 1. Create the page file
620
+
621
+ \`\`\`
622
+ app/[your-route]/page.tsx
623
+ \`\`\`
624
+
625
+ ### 2. Server component pattern (data fetch)
513
626
 
627
+ \`\`\`tsx
628
+ // app/products/page.tsx
629
+ import { backendCircuitBreaker } from '@thorprovider/adapters';
630
+ import { commerce } from '@/lib/commerce';
631
+ import { ProductCard } from '@thorprovider/components';
632
+
633
+ export default async function ProductsPage() {
634
+ const products = await backendCircuitBreaker.execute(
635
+ () => commerce.getProducts({ first: 20 }),
636
+ [] // fallback when backend is unreachable
637
+ );
638
+
639
+ return (
640
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
641
+ {products.map((p) => (
642
+ <ProductCard
643
+ key={p.id}
644
+ title={p.title}
645
+ price={parseFloat(p.priceRange.minVariantPrice.amount)}
646
+ image={p.featuredImage?.url ?? ''}
647
+ href={\`/products/\${p.handle}\`}
648
+ />
649
+ ))}
650
+ </div>
651
+ );
652
+ }
653
+ \`\`\`
654
+
655
+ ### 3. Rules
656
+
657
+ - \u2705 Pages are **server components** by default \u2014 fetch data here, pass via props
658
+ - \u2705 Always wrap reads with \`backendCircuitBreaker.execute(fn, fallback)\`
659
+ - \u2705 Use \`product.handle\` for URLs (not \`id\` or \`slug\`)
660
+ - \u274C Never \`useEffect\` + \`fetch\` in pages \u2014 causes loading flash + worse LCP
661
+ - \u274C Never import \`next/link\` or \`next/image\` in \`components/\`
662
+
663
+ ### 4. After generating
664
+
665
+ Run \`.agents/skills/audit-changes.md\` checklist before committing.
514
666
  `;
515
- md += `These files define constraints that **must not be modified** by V0.
667
+ }
668
+ function buildGenerateComponentSkill() {
669
+ return `---
670
+ name: generate-component
671
+ description: Step-by-step playbook for creating a new React component in a Thor Commerce app. Use when adding UI that doesn't exist in @thorprovider/components.
672
+ ---
673
+
674
+ # Skill: Generate Component
675
+
676
+ ## Before You Start
677
+
678
+ 1. Check \`.agents/context/dependencies.md\` \u2014 the component may already exist in \`@thorprovider/components\`
679
+ 2. If it exists \u2192 import it, don't recreate it
680
+ 3. If it doesn't \u2192 follow this playbook
681
+
682
+ ## Steps
683
+
684
+ ### 1. Create the component file
685
+
686
+ \`\`\`
687
+ components/[feature-name].tsx
688
+ \`\`\`
689
+
690
+ ### 2. Client component pattern
691
+
692
+ \`\`\`tsx
693
+ // components/product-card-custom.tsx
694
+ 'use client';
695
+ import { useNavigation } from '@thorprovider/providers';
696
+ import { Button, Card } from '@thorprovider/components';
697
+ import type { Product } from '@thorprovider/types';
698
+
699
+ interface ProductCardCustomProps {
700
+ product: Product;
701
+ onAddToCart?: (variantId: string) => void;
702
+ }
703
+
704
+ export function ProductCardCustom({ product, onAddToCart }: ProductCardCustomProps) {
705
+ const { Link, Image } = useNavigation();
706
+
707
+ return (
708
+ <Card>
709
+ <Link href={\`/products/\${product.handle}\`}>
710
+ <Image
711
+ src={product.featuredImage?.url ?? ''}
712
+ alt={product.featuredImage?.altText ?? product.title}
713
+ width={300}
714
+ height={300}
715
+ />
716
+ <p style={{ color: 'var(--foreground)' }}>{product.title}</p>
717
+ </Link>
718
+ {onAddToCart && (
719
+ <Button onClick={() => onAddToCart(product.variants[0]?.id ?? '')}>
720
+ Add to cart
721
+ </Button>
722
+ )}
723
+ </Card>
724
+ );
725
+ }
726
+ \`\`\`
727
+
728
+ ### 3. Rules
729
+
730
+ - \u2705 Use \`useNavigation()\` for Link and Image \u2014 never \`next/link\` or \`next/image\`
731
+ - \u2705 Use CSS tokens for colors: \`var(--foreground)\`, \`var(--background)\`, \`var(--primary-9)\`
732
+ - \u2705 Accept data via props \u2014 components never fetch
733
+ - \u2705 Compose using \`@thorprovider/components\` primitives inside
734
+ - \u274C Never hardcode \`#hex\` or \`rgb()\` colors
735
+ - \u274C Never call \`commerce.*\` or \`fetch()\` inside a component
736
+
737
+ ### 4. After generating
738
+
739
+ Run \`.agents/skills/audit-changes.md\` checklist before committing.
516
740
  `;
517
- md += `Paste this entire document as the **first message** in V0.
741
+ }
742
+ function buildGenerateModuleSkill() {
743
+ return `---
744
+ name: generate-module
745
+ description: Playbook for creating an L4 feature module using the Variant/Composition pattern. Use when building a complex feature (checkout, product detail, account, etc.).
746
+ ---
747
+
748
+ # Skill: Generate Module (L4)
749
+
750
+ ## What Is an L4 Module?
751
+
752
+ A module is a self-contained feature unit that:
753
+ - Lives in \`components/modules/[feature]/\` or \`app/[route]/\`
754
+ - Composes L3 components (\`@thorprovider/components\`)
755
+ - Receives data and callbacks via props from L5 (the page)
756
+ - Never fetches data itself
757
+
758
+ ## Pattern: Variant/Composition
759
+
760
+ \`\`\`tsx
761
+ // components/modules/checkout/checkout-module.tsx
762
+ 'use client';
763
+ import { CheckoutStepIndicator, CartSummary } from '@thorprovider/components';
764
+ import type { Cart } from '@thorprovider/types';
765
+
766
+ type CheckoutVariant = 'simple' | 'wizard' | 'one-page';
767
+
768
+ interface CheckoutModuleProps {
769
+ cart: Cart;
770
+ variant?: CheckoutVariant;
771
+ onPayment: (cartId: string) => Promise<void>;
772
+ onAddress: (cartId: string, address: unknown) => Promise<void>;
773
+ }
774
+
775
+ export function CheckoutModule({
776
+ cart,
777
+ variant = 'wizard',
778
+ onPayment,
779
+ onAddress,
780
+ }: CheckoutModuleProps) {
781
+ const steps = ['Address', 'Shipping', 'Payment'];
782
+
783
+ return (
784
+ <div>
785
+ <CheckoutStepIndicator steps={steps} currentStep={0} completedSteps={[]} />
786
+ <CartSummary
787
+ subtotal={parseFloat(cart.cost.subtotalAmount.amount)}
788
+ total={parseFloat(cart.cost.totalAmount.amount)}
789
+ onCheckout={() => onPayment(cart.id ?? '')}
790
+ />
791
+ </div>
792
+ );
793
+ }
794
+ \`\`\`
795
+
796
+ ## Rules
518
797
 
798
+ - \u2705 Accept all data via props \u2014 never fetch inside a module
799
+ - \u2705 Use Variant/Composition pattern \u2014 configurable via props, not hardcoded flows
800
+ - \u2705 Domain values (status colors, filter options) come from L5 as props
801
+ - \u274C Never hardcode business logic like \`case 'pending': return 'yellow'\`
802
+ - \u274C Never import \`next/*\` \u2014 use \`useNavigation()\`
803
+
804
+ ## After generating
805
+
806
+ Run \`.agents/skills/audit-changes.md\` checklist before committing.
519
807
  `;
520
- for (const relPath of V0_CONTEXT_FILES) {
521
- const absPath = join6(sourceDir, relPath);
522
- if (!existsSync6(absPath)) continue;
523
- const content = readFileSync5(absPath, "utf-8");
524
- const ext = relPath.split(".").pop() || "";
525
- const lang = ext === "md" ? "markdown" : ext === "ts" || ext === "tsx" ? "typescript" : ext;
526
- md += `### ${relPath}
808
+ }
809
+ function buildAddCommerceFeatureSkill() {
810
+ return `---
811
+ name: add-commerce-feature
812
+ description: Playbook for adding a feature that uses commerce.* methods (product listing, cart, checkout, auth, etc.). Use when implementing any commerce functionality.
813
+ ---
814
+
815
+ # Skill: Add Commerce Feature
816
+
817
+ ## Before You Start
818
+
819
+ 1. Read \`.agents/context/commerce-api.md\` \u2014 find the exact method signatures
820
+ 2. Read \`.agents/context/types.md\` \u2014 understand the data shapes
821
+ 3. Identify: is this a **read** (needs circuit breaker) or a **mutation** (direct call)?
822
+
823
+ ## Read Operations (Server Components / API Routes)
824
+
825
+ Always wrap with \`backendCircuitBreaker.execute()\`:
826
+
827
+ \`\`\`ts
828
+ import { commerce } from '@/lib/commerce';
829
+ import { backendCircuitBreaker } from '@thorprovider/adapters';
830
+
831
+ // In a server component or API route
832
+ const products = await backendCircuitBreaker.execute(
833
+ () => commerce.getProducts({ query: 'shoes', first: 20 }),
834
+ [] // fallback value when backend is down
835
+ );
836
+ \`\`\`
837
+
838
+ ## Mutation Operations (Client Components)
839
+
840
+ Call directly \u2014 adapters handle retry internally:
841
+
842
+ \`\`\`ts
843
+ // In a client component
844
+ const { addItem } = useCart(); // from '@/lib/cart-provider'
845
+ await addItem(variantId, quantity);
846
+
847
+ // Or directly via commerce instance
848
+ const cart = await commerce.addToCart(cartId, [{ merchandiseId: variantId, quantity: 1 }]);
849
+ \`\`\`
850
+
851
+ ## Optional Methods
852
+
853
+ Methods marked with \`?\` in \`commerce-api.md\` may not exist. Always guard:
854
+
855
+ \`\`\`ts
856
+ // \u2705 Guard optional methods
857
+ if (commerce.getAdminOrder) {
858
+ const order = await backendCircuitBreaker.execute(
859
+ () => commerce.getAdminOrder!(orderId),
860
+ null
861
+ );
862
+ }
863
+ \`\`\`
864
+
865
+ ## Common Patterns
866
+
867
+ ### Product listing page
868
+ \`\`\`ts
869
+ const products = await backendCircuitBreaker.execute(
870
+ () => commerce.getProducts({ query, sortKey: 'title', first: 20 }),
871
+ []
872
+ );
873
+ \`\`\`
527
874
 
875
+ ### Single product page
876
+ \`\`\`ts
877
+ const product = await backendCircuitBreaker.execute(
878
+ () => commerce.getProduct(handle), // handle = URL slug
879
+ undefined
880
+ );
881
+ if (!product) notFound();
882
+ \`\`\`
883
+
884
+ ### Cart operations (client)
885
+ \`\`\`ts
886
+ const { cart, addItem, removeItem, updateQuantity } = useCart();
887
+ \`\`\`
888
+
889
+ ### Auth (client)
890
+ \`\`\`ts
891
+ const { customer, isAuthenticated, login, logout } = useAuth();
892
+ \`\`\`
893
+
894
+ ## After generating
895
+
896
+ Run \`.agents/skills/audit-changes.md\` checklist before committing.
528
897
  `;
529
- md += `\`\`\`${lang}
898
+ }
899
+ function buildAddRouteSkill() {
900
+ return `---
901
+ name: add-route
902
+ description: Playbook for adding a Next.js API route that calls commerce methods. Use when creating app/api/** route handlers.
903
+ ---
904
+
905
+ # Skill: Add API Route
906
+
907
+ ## Pattern
908
+
909
+ \`\`\`ts
910
+ // app/api/products/route.ts
911
+ import { backendCircuitBreaker } from '@thorprovider/adapters';
912
+ import { commerce } from '@/lib/commerce';
913
+
914
+ export async function GET(request: Request) {
915
+ try {
916
+ const { searchParams } = new URL(request.url);
917
+ const query = searchParams.get('q') ?? undefined;
918
+
919
+ const products = await backendCircuitBreaker.execute(
920
+ () => commerce.getProducts({ query, first: 20 }),
921
+ []
922
+ );
923
+
924
+ return Response.json(products);
925
+ } catch {
926
+ return Response.json({ error: 'Service unavailable' }, { status: 503 });
927
+ }
928
+ }
929
+ \`\`\`
930
+
931
+ ## Rules
932
+
933
+ - \u2705 Always wrap reads with \`backendCircuitBreaker.execute(fn, fallback)\`
934
+ - \u2705 Return \`Response.json()\` (not \`NextResponse\`)
935
+ - \u2705 Catch errors and return \`503\` when backend is unavailable
936
+ - \u2705 Use \`commerce\` from \`@/lib/commerce\` (not a new instance)
937
+ - \u274C Never import backend SDKs directly (\`@medusajs/js-sdk\`, etc.)
938
+ - \u274C Never use raw \`fetch(COMMERCE_API_URL + '...')\`
939
+
940
+ ## Admin Routes
941
+
942
+ Admin routes live in \`app/api/admin/\` and use \`adminFetch\` for internal calls:
943
+
944
+ \`\`\`ts
945
+ // app/api/admin/orders/route.ts
946
+ import { backendCircuitBreaker } from '@thorprovider/adapters';
947
+ import { commerce } from '@/lib/commerce';
948
+
949
+ export async function GET() {
950
+ const { orders, count } = await backendCircuitBreaker.execute(
951
+ () => commerce.getAdminOrders({ limit: 20 }),
952
+ { orders: [], count: 0 }
953
+ );
954
+ return Response.json({ orders, count });
955
+ }
956
+ \`\`\`
957
+
958
+ ## After generating
959
+
960
+ Run \`.agents/skills/audit-changes.md\` checklist before committing.
530
961
  `;
531
- md += content;
532
- if (!content.endsWith("\n")) md += "\n";
533
- md += `\`\`\`
962
+ }
963
+ function buildAuditChangesSkill() {
964
+ return `---
965
+ name: audit-changes
966
+ description: Post-generation checklist to validate that generated code follows Thor Commerce architecture rules. Run this before every commit.
967
+ ---
968
+
969
+ # Skill: Audit Changes
970
+
971
+ Run this checklist after generating any code. Every item must pass before committing.
972
+
973
+ ## Architecture
974
+
975
+ - [ ] No \`next/*\` imports (\`next/link\`, \`next/image\`, \`next/router\`) inside \`components/\`
976
+ - [ ] No backend SDK imports (\`@medusajs/js-sdk\`, \`@shopify/api\`, etc.) anywhere
977
+ - [ ] No raw \`fetch(COMMERCE_API_URL + '...')\` calls
978
+ - [ ] Types imported from \`@thorprovider/types\`, not from vendor packages
979
+
980
+ ## Data Fetching
534
981
 
982
+ - [ ] All \`commerce.get*()\` reads wrapped in \`backendCircuitBreaker.execute(fn, fallback)\`
983
+ - [ ] Mutations (\`addToCart\`, \`checkout\`, etc.) called directly (no circuit breaker)
984
+ - [ ] Optional methods (\`commerce.method?\`) guarded with \`if (commerce.method)\`
985
+ - [ ] Server components fetch data; client components receive data via props
986
+
987
+ ## Styling
988
+
989
+ - [ ] No hardcoded \`#hex\` colors in components
990
+ - [ ] No \`rgb()\` or \`hsl()\` inline colors in components
991
+ - [ ] Colors use CSS tokens: \`var(--foreground)\`, \`var(--background)\`, \`var(--primary-9)\`, etc.
992
+
993
+ ## Components
994
+
995
+ - [ ] Checked \`@thorprovider/components\` inventory before creating new UI (see \`dependencies.md\`)
996
+ - [ ] No duplicate implementations of existing components (Button, ProductCard, CartItem, etc.)
997
+ - [ ] \`useNavigation()\` used for Link and Image (not \`next/link\` / \`next/image\`)
998
+
999
+ ## Provider Chain
1000
+
1001
+ - [ ] \`components/providers/app-providers.tsx\` order unchanged
1002
+ - [ ] \`app/layout.tsx\` structure unchanged
1003
+
1004
+ ## Build
1005
+
1006
+ - [ ] \`yarn type-check\` passes
1007
+ - [ ] No TypeScript errors in generated files
535
1008
  `;
1009
+ }
1010
+ function generateAgentsDir(name, targetDir, sourceDir) {
1011
+ const agentsDir = join6(targetDir, ".agents");
1012
+ const contextDir = join6(agentsDir, "context");
1013
+ const skillsDir = join6(agentsDir, "skills");
1014
+ mkdirSync(contextDir, { recursive: true });
1015
+ mkdirSync(skillsDir, { recursive: true });
1016
+ write(join6(agentsDir, "AGENTS.md"), buildAgentsMd(name));
1017
+ write(join6(contextDir, "architecture.md"), buildArchitectureMd());
1018
+ const docFiles = [
1019
+ "project-structure.md",
1020
+ "dependencies.md",
1021
+ "components.md",
1022
+ "types.md",
1023
+ "commerce-api.md",
1024
+ "patterns.md",
1025
+ "rules.md"
1026
+ ];
1027
+ for (const docFile of docFiles) {
1028
+ const content = readSource(sourceDir, `docs/${docFile}`);
1029
+ if (content) {
1030
+ write(join6(contextDir, docFile), content);
1031
+ }
536
1032
  }
537
- writeFileSync4(join6(targetDir, ".v0-context.md"), md, "utf-8");
1033
+ write(join6(skillsDir, "generate-page.md"), buildGeneratePageSkill());
1034
+ write(join6(skillsDir, "generate-component.md"), buildGenerateComponentSkill());
1035
+ write(join6(skillsDir, "generate-module.md"), buildGenerateModuleSkill());
1036
+ write(join6(skillsDir, "add-commerce-feature.md"), buildAddCommerceFeatureSkill());
1037
+ write(join6(skillsDir, "add-route.md"), buildAddRouteSkill());
1038
+ write(join6(skillsDir, "audit-changes.md"), buildAuditChangesSkill());
538
1039
  }
539
1040
 
540
1041
  // src/helpers/vercel.ts
541
- import { existsSync as existsSync7, mkdirSync, writeFileSync as writeFileSync5 } from "fs";
1042
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, writeFileSync as writeFileSync5 } from "fs";
542
1043
  import { join as join7 } from "path";
543
1044
  var VERCEL_API = "https://api.vercel.com";
544
1045
  async function createVercelProject(name, token, teamSlug, gitRepo) {
@@ -571,7 +1072,7 @@ async function createVercelProject(name, token, teamSlug, gitRepo) {
571
1072
  }
572
1073
  function writeProjectJson(targetDir, orgId, projectId) {
573
1074
  const vercelDir = join7(targetDir, ".vercel");
574
- if (!existsSync7(vercelDir)) mkdirSync(vercelDir, { recursive: true });
1075
+ if (!existsSync7(vercelDir)) mkdirSync2(vercelDir, { recursive: true });
575
1076
  writeFileSync5(
576
1077
  join7(vercelDir, "project.json"),
577
1078
  JSON.stringify({ orgId, projectId }, null, 2) + "\n"
@@ -579,7 +1080,7 @@ function writeProjectJson(targetDir, orgId, projectId) {
579
1080
  }
580
1081
  function generateDeployWorkflow(targetDir) {
581
1082
  const workflowDir = join7(targetDir, ".github", "workflows");
582
- mkdirSync(workflowDir, { recursive: true });
1083
+ mkdirSync2(workflowDir, { recursive: true });
583
1084
  const workflow = `# Vercel deploy workflow \u2014 generated by create-thor-app.
584
1085
  # Required GitHub Actions secrets:
585
1086
  # VERCEL_TOKEN \u2014 Vercel Access Token
@@ -740,7 +1241,7 @@ function bundleRegionsScript(monorepoRoot, targetDir) {
740
1241
  );
741
1242
  if (existsSync8(regionsScriptSrc)) {
742
1243
  const scriptsDir = join8(targetDir, "scripts");
743
- mkdirSync2(scriptsDir, { recursive: true });
1244
+ mkdirSync3(scriptsDir, { recursive: true });
744
1245
  cpSync(regionsScriptSrc, join8(scriptsDir, "generate-regions-config.ts"));
745
1246
  log(" \u2713 Bundled generate-regions-config.ts", c.green);
746
1247
  }
@@ -755,7 +1256,7 @@ async function createApp(opts) {
755
1256
  skipInstall,
756
1257
  skipRemote,
757
1258
  skipVercel,
758
- skipV0Context,
1259
+ noContext,
759
1260
  commerceProvider,
760
1261
  commerceApiUrl,
761
1262
  commerceApiKey,
@@ -794,7 +1295,7 @@ async function createApp(opts) {
794
1295
  }
795
1296
  log("\u{1F4CB} Copying template...", c.cyan);
796
1297
  try {
797
- mkdirSync2(outputDir, { recursive: true });
1298
+ mkdirSync3(outputDir, { recursive: true });
798
1299
  } catch (err) {
799
1300
  const code = err.code;
800
1301
  if (code === "EACCES") {
@@ -844,11 +1345,11 @@ async function createApp(opts) {
844
1345
  log("\u2699\uFE0F Applying site configuration...", c.cyan);
845
1346
  patchSiteConfig(outputDir, { preset, siteUrl });
846
1347
  }
847
- if (!skipV0Context) {
848
- log("\u{1F4C4} Generating .v0-context.md...", c.cyan);
1348
+ if (!noContext) {
1349
+ log("\u{1F4C1} Generating .agents/ directory...", c.cyan);
849
1350
  const contextSourceDir = mode === "monorepo" && monorepoRoot ? join8(monorepoRoot, "packages", "core") : outputDir;
850
- generateV0Context(name, outputDir, contextSourceDir);
851
- log(" \u2713 .v0-context.md generated", c.green);
1351
+ generateAgentsDir(name, outputDir, contextSourceDir);
1352
+ log(" \u2713 .agents/ generated (AGENTS.md + context/ + skills/)", c.green);
852
1353
  }
853
1354
  if (!skipInstall) {
854
1355
  installDependencies(outputDir);
@@ -978,7 +1479,7 @@ ${step++}. Connect to V0:`, c.cyan);
978
1479
  " Open https://v0.dev \u2192 New project \u2192 Connect GitHub repo",
979
1480
  c.yellow
980
1481
  );
981
- log(` Then paste .v0-context.md as the first message`, c.yellow);
1482
+ log(` V0 will auto-discover .agents/AGENTS.md for context`, c.yellow);
982
1483
  log(`
983
1484
  ${step++}. Start developing:`, c.cyan);
984
1485
  log(` cd ${relPath} && yarn dev`, c.yellow);
@@ -1014,7 +1515,7 @@ if (nodeMajor < NODE_MIN_MAJOR || nodeMajor === NODE_MIN_MAJOR && nodeMinor < NO
1014
1515
  );
1015
1516
  process.exit(1);
1016
1517
  }
1017
- 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("--skip-v0-context", "Skip .v0-context.md generation").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").option("--preset <preset>", "Visual preset for site.config.ts (e.g., electro, minimal)").option("--site-url <url>", "Public site URL for site.config.ts").option("--generate-regions", "Run region generation from backend after install (requires --commerce-api-url and --commerce-api-key)").action(async (positionalName, opts) => {
1518
+ 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("--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").option("--preset <preset>", "Visual preset for site.config.ts (e.g., electro, minimal)").option("--site-url <url>", "Public site URL for site.config.ts").option("--generate-regions", "Run region generation from backend after install (requires --commerce-api-url and --commerce-api-key)").action(async (positionalName, opts) => {
1018
1519
  let rawName = positionalName || opts.name || "";
1019
1520
  if (!rawName) {
1020
1521
  rawName = await promptForName();
@@ -1042,7 +1543,7 @@ program.name("create-thor-app").description("Create a new Thor Commerce applicat
1042
1543
  skipInstall: !!opts.skipInstall,
1043
1544
  skipRemote: !!opts.skipRemote,
1044
1545
  skipVercel: !!opts.skipVercel,
1045
- skipV0Context: !!opts.skipV0Context,
1546
+ noContext: !!opts.noContext,
1046
1547
  commerceProvider: opts.commerceProvider,
1047
1548
  commerceApiUrl: opts.commerceApiUrl,
1048
1549
  commerceApiKey: opts.commerceApiKey,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thorprovider/create-thor-app",
3
- "version": "3.0.2",
3
+ "version": "3.1.0",
4
4
  "description": "CLI to scaffold a new Thor Commerce application from @thorprovider/core template",
5
5
  "type": "module",
6
6
  "bin": "./dist/index.js",