Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

create-spree-app always yields a working app; spree dev completes first-run setup automatically (#14308)

Damian Legawieca5d65fae59eb
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index 4c0667e98a..1e3a854a81 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,27 @@
# @spree/cli
+## 2.4.2
+
+### Patch Changes
+
+- `spree dev` on a project that was never set up now runs the full first-run
+flow automatically (pull fresh images, start services, seed the database,
+configure API keys) instead of a bare `docker compose up`. A bare `up` never
+pulls, so a mutable tag (`latest`) cached weeks ago by another project
+silently booted an old Spree whenever the first boot happened through
+`spree dev` — a `--no-start` scaffold, an interrupted create-spree-app run,
+or a fresh clone. A setup that was itself interrupted partway (e.g. Ctrl+C
+during the first image pull) is also detected and completed on the next
+`spree dev`, for projects scaffolded by create-spree-app 1.1.1+. The
+sample-data choice create-spree-app persists in `.env`
+(`SPREE_SAMPLE_DATA`) is honored, so a deferred first run keeps the answer
+given at scaffold time. Setup also installs `apps/storefront` and
+`apps/dashboard` dependencies when they're missing (a fresh clone, or a
+scaffold whose install step failed) — mirroring create-spree-app's per-app
+install steps — so every app is runnable with `pnpm dev` right after.
+Already-initialized projects are untouched: later boots never pull, dev
+stays offline-friendly, and upgrades stay explicit via `spree update`.
+
## 2.4.1
### Patch Changes
diff --git a/packages/cli/package.json b/packages/cli/package.json
index f9c266ddcc..eebf3f27a8 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/cli",
- "version": "2.4.1",
+ "version": "2.4.2",
"description": "CLI for managing Spree Commerce projects",
"type": "module",
"bin": {
diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts
index 2dedd77f68..958cf1fc4e 100644
--- a/packages/cli/src/commands/add.ts
+++ b/packages/cli/src/commands/add.ts
@@ -252,7 +252,7 @@ function writeDashboardEnv(envPath: string, port: number): void {
}
/** Prefer the project's own package manager (by lockfile); default to pnpm. */
-function detectPackageManager(projectDir: string, dashboardDir: string): string {
+export function detectPackageManager(projectDir: string, dashboardDir: string): string {
for (const dir of [dashboardDir, projectDir]) {
if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm'
if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn'
diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.ts
index 6375bbf5f1..e6e25d81e8 100644
--- a/packages/cli/src/commands/dev.ts
+++ b/packages/cli/src/commands/dev.ts
@@ -3,14 +3,22 @@ import path from 'node:path'
import * as p from '@clack/prompts'
import type { Command } from 'commander'
import pc from 'picocolors'
+import { projectCredentialsPath, projectSetupMarkerPath } from '../config.js'
import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
-import { detectProject, hasMonorepoSpreePath, isEjectedProject } from '../context.js'
+import {
+ detectProject,
+ hasMonorepoSpreePath,
+ isEjectedProject,
+ readSampleDataFromEnv,
+} from '../context.js'
import {
buildAdminStylesheets,
dockerCompose,
+ hasProjectContainers,
primeBundleVolume,
watchAdminStylesheets,
} from '../docker.js'
+import { runFirstRunSetup } from './init.js'
export function registerDevCommand(program: Command): void {
program
@@ -30,6 +38,44 @@ export function registerDevCommand(program: Command): void {
process.exit(1)
}
+ // A project that was never set up gets the full first-run flow instead
+ // of a bare `up`: pull a fresh image (a mutable tag cached weeks ago by
+ // another project would otherwise boot an old Spree), seed the database,
+ // mint API keys. This keeps create-spree-app's contract — the app just
+ // works — on every path to a first boot (--no-start, an interrupted
+ // scaffold, a fresh clone) without requiring anyone to run `spree init`.
+ // Completed setup writes a marker (separate from credentials.json,
+ // which `spree auth logout` deletes — losing auth must not look like a
+ // fresh project). Credentials still count as "set up" for projects
+ // initialized by older CLIs that minted them without a marker. When
+ // both are missing: a project whose .env declares SPREE_SAMPLE_DATA was
+ // scaffolded by a create-spree-app that persists setup state, so that
+ // alone means setup never finished — even if an interrupted init
+ // already created containers. For older projects the only safe signal
+ // is "compose never created a container": an initialized
+ // pre-credentials-era project must not be re-set-up (that would load
+ // sample data into a real store). Ejected projects build the image
+ // locally and manage their own lifecycle.
+ if (
+ !isEjectedProject(ctx.projectDir) &&
+ !fs.existsSync(projectSetupMarkerPath(ctx.projectDir)) &&
+ !fs.existsSync(projectCredentialsPath(ctx.projectDir))
+ ) {
+ let neverSetUp = readSampleDataFromEnv(ctx.projectDir) !== undefined
+ if (!neverSetUp) {
+ try {
+ neverSetUp = !(await hasProjectContainers(ctx.projectDir))
+ } catch {
+ // Daemon trouble surfaces with compose's own error on the up below.
+ }
+ }
+ if (neverSetUp) {
+ p.log.info('First run detected — completing setup automatically.')
+ await runFirstRunSetup({ sampleData: true, open: true })
+ return
+ }
+ }
+
p.note(
[
'',
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 387fa28835..29a1b5e6f6 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -3,12 +3,13 @@ import { platform } from 'node:os'
import path from 'node:path'
import * as p from '@clack/prompts'
import type { Command } from 'commander'
-import { execaCommand } from 'execa'
+import { execa, execaCommand } from 'execa'
import pc from 'picocolors'
-import { mintProjectCredentials } from '../config.js'
+import { mintProjectCredentials, writeProjectSetupMarker } from '../config.js'
import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
-import { detectProject } from '../context.js'
+import { detectProject, readSampleDataFromEnv } from '../context.js'
import { dockerCompose, primeBundleVolume, rakeTask, streamLogs } from '../docker.js'
+import { detectPackageManager } from './add.js'
const HEALTH_CHECK_INTERVAL_MS = 3000
const HEALTH_CHECK_TIMEOUT_MS = 120_000
@@ -20,78 +21,135 @@ export function registerInitCommand(program: Command): void {
.option('--no-sample-data', 'skip loading sample data')
.option('--no-open', 'skip opening browser')
.action(async (flags: { sampleData: boolean; open: boolean }) => {
- const ctx = detectProject()
-
- p.log.step('Pulling latest images...')
- await dockerCompose(['pull'], ctx.projectDir, { stdio: 'inherit' })
-
- const s = p.spinner()
- s.start('Starting Docker services...')
- // Prime the shared bundle_cache volume with web alone so the up below
- // doesn't race the cold-volume copy-up. stdio: 'ignore' keeps the spinner
- // clean — the inherited `pull` above already showed image progress.
- await primeBundleVolume(ctx.projectDir, { stdio: 'ignore' })
- await dockerCompose(['up', '-d'], ctx.projectDir)
- s.stop('Docker services started.')
-
- s.start('Waiting for Spree to be ready...')
- await waitForHealthy(ctx.port)
- s.stop('Spree is ready.')
-
- s.start('Seeding database...')
- await rakeTask('db:seed', ctx.projectDir)
- s.stop('Database seeded.')
-
- s.start('Configuring API keys...')
- // Sequential, not Promise.all: finish the publishable key (and its
- // storefront env write) before minting the secret, so a failure on the
- // first step never leaves a freshly minted secret stranded on disk while
- // init aborts.
- const publishableKey = await fetchApiKey(ctx.projectDir)
- updateStorefrontEnv(ctx.projectDir, publishableKey)
- const secretKey = await mintCliCredentials(ctx.projectDir, ctx.port)
- s.stop('API keys configured.')
-
- if (flags.sampleData) {
- s.start('Loading sample data...')
- await rakeTask('spree:load_sample_data', ctx.projectDir)
- s.stop('Sample data loaded.')
- }
-
- s.start('Indexing products for search...')
- await rakeTask('spree:search:reindex', ctx.projectDir)
- s.stop('Search index ready.')
-
- p.note(
- [
- '',
- pc.bold('Admin Dashboard'),
- ` ${pc.cyan(`http://localhost:${ctx.port}/admin`)}`,
- ` Email: ${DEFAULT_ADMIN_EMAIL}`,
- ` Password: ${DEFAULT_ADMIN_PASSWORD}`,
- '',
- pc.bold('Store API'),
- ` ${pc.cyan(`http://localhost:${ctx.port}/api/v3/store`)}`,
- ` Publishable key: ${pc.cyan(publishableKey)}`,
- '',
- pc.bold('Admin API'),
- ` ${pc.cyan(`http://localhost:${ctx.port}/api/v3/admin`)}`,
- ` Secret key: ${pc.cyan(secretKey)}`,
- ` ${pc.dim('Saved to .spree/credentials.json')}`,
- '',
- ].join('\n'),
- 'Your Spree store is ready!',
- )
-
- if (flags.open) {
- await openBrowser(`http://localhost:${ctx.port}/admin`)
- }
-
- p.log.info('Streaming logs (Ctrl+C to stop)...\n')
- await streamLogs('web', ctx.projectDir)
+ await runFirstRunSetup(flags)
})
}
+/**
+ * The whole first-run flow, callable outside the `init` command: `spree dev`
+ * delegates here when it detects a project that has never been set up, so
+ * create-spree-app's contract — the app just works — holds on every path
+ * (--no-start, an interrupted scaffold, a fresh clone) without anyone having
+ * to know `spree init` exists.
+ */
+export async function runFirstRunSetup(flags: {
+ sampleData: boolean
+ open: boolean
+}): Promise<void> {
+ const ctx = detectProject()
+
+ // `--no-sample-data` always wins; otherwise the choice create-spree-app
+ // persisted in .env decides, so a deferred first run keeps the answer the
+ // operator gave at scaffold time. Load sample data later any time with
+ // `spree sample-data`.
+ const sampleData = flags.sampleData && (readSampleDataFromEnv(ctx.projectDir) ?? true)
+
+ p.log.step('Pulling latest images...')
+ await dockerCompose(['pull'], ctx.projectDir, { stdio: 'inherit' })
+
+ const s = p.spinner()
+ s.start('Starting Docker services...')
+ // Prime the shared bundle_cache volume with web alone so the up below
+ // doesn't race the cold-volume copy-up. stdio: 'ignore' keeps the spinner
+ // clean — the inherited `pull` above already showed image progress.
+ await primeBundleVolume(ctx.projectDir, { stdio: 'ignore' })
+ await dockerCompose(['up', '-d'], ctx.projectDir)
+ s.stop('Docker services started.')
+
+ s.start('Waiting for Spree to be ready...')
+ await waitForHealthy(ctx.port)
+ s.stop('Spree is ready.')
+
+ s.start('Seeding database...')
+ await rakeTask('db:seed', ctx.projectDir)
+ s.stop('Database seeded.')
+
+ s.start('Configuring API keys...')
+ // Sequential, not Promise.all: finish the publishable key (and its
+ // storefront env write) before minting the secret, so a failure on the
+ // first step never leaves a freshly minted secret stranded on disk while
+ // init aborts.
+ const publishableKey = await fetchApiKey(ctx.projectDir)
+ updateStorefrontEnv(ctx.projectDir, publishableKey)
+ const secretKey = await mintCliCredentials(ctx.projectDir, ctx.port)
+ s.stop('API keys configured.')
+
+ await installAppDeps(ctx.projectDir, 'storefront')
+ await installAppDeps(ctx.projectDir, 'dashboard')
+
+ if (sampleData) {
+ s.start('Loading sample data...')
+ await rakeTask('spree:load_sample_data', ctx.projectDir)
+ s.stop('Sample data loaded.')
+ }
+
+ s.start('Indexing products for search...')
+ await rakeTask('spree:search:reindex', ctx.projectDir)
+ s.stop('Search index ready.')
+
+ writeProjectSetupMarker(ctx.projectDir)
+
+ const dashboardDir = path.join(ctx.projectDir, 'apps', 'dashboard')
+ const dashboardPm = detectPackageManager(ctx.projectDir, dashboardDir)
+
+ p.note(
+ [
+ '',
+ pc.bold('Admin Dashboard'),
+ ` ${pc.cyan(`http://localhost:${ctx.port}/admin`)}`,
+ ` Email: ${DEFAULT_ADMIN_EMAIL}`,
+ ` Password: ${DEFAULT_ADMIN_PASSWORD}`,
+ '',
+ pc.bold('Store API'),
+ ` ${pc.cyan(`http://localhost:${ctx.port}/api/v3/store`)}`,
+ ` Publishable key: ${pc.cyan(publishableKey)}`,
+ '',
+ pc.bold('Admin API'),
+ ` ${pc.cyan(`http://localhost:${ctx.port}/api/v3/admin`)}`,
+ ` Secret key: ${pc.cyan(secretKey)}`,
+ ` ${pc.dim('Saved to .spree/credentials.json')}`,
+ '',
+ ...(fs.existsSync(path.join(dashboardDir, 'package.json'))
+ ? [
+ pc.bold('React Dashboard (Developer Preview)'),
+ ` ${pc.cyan(`cd apps/dashboard && ${dashboardPm} run dev`)}`,
+ '',
+ ]
+ : []),
+ ].join('\n'),
+ 'Your Spree store is ready!',
+ )
+
+ if (flags.open) {
+ await openBrowser(`http://localhost:${ctx.port}/admin`)
+ }
+
+ p.log.info('Streaming logs (Ctrl+C to stop)...\n')
+ await streamLogs('web', ctx.projectDir)
+}
+
+// Install an optional app's dependencies when they're missing — a fresh
+// clone, or a scaffold whose install step failed — mirroring
+// create-spree-app's per-app install steps, so first-run setup leaves every
+// app runnable with `pnpm dev`. Best-effort: a registry hiccup shouldn't
+// fail backend setup.
+async function installAppDeps(projectDir: string, app: 'storefront' | 'dashboard'): Promise<void> {
+ const appDir = path.join(projectDir, 'apps', app)
+ if (!fs.existsSync(path.join(appDir, 'package.json'))) return
+ if (fs.existsSync(path.join(appDir, 'node_modules'))) return
+
+ const pm = detectPackageManager(projectDir, appDir)
+ const s = p.spinner()
+ s.start(`Installing ${app} dependencies with ${pm}...`)
+ try {
+ await execa(pm, ['install'], { cwd: appDir })
+ s.stop(`${app === 'dashboard' ? 'Dashboard' : 'Storefront'} dependencies installed.`)
+ } catch (err) {
+ s.stop(pc.yellow(`${pm} install failed — run it manually in apps/${app}/.`))
+ p.log.warn(err instanceof Error ? err.message : String(err))
+ }
+}
+
async function waitForHealthy(port: number): Promise<void> {
const url = `http://localhost:${port}/up`
const start = Date.now()
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index 6d6d2fde21..270dbc7e33 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -131,6 +131,25 @@ export function projectCredentialsPath(projectDir: string): string {
return path.join(projectDir, '.spree', 'credentials.json')
}
+/**
+ * Marker written when first-run setup completes on this machine. Kept
+ * separate from credentials.json, which `spree auth logout` removes — losing
+ * auth must not make `spree dev` mistake an initialized project for a fresh
+ * one and re-run setup against its database. Lives in the fully gitignored
+ * `.spree/`, so a teammate's clone correctly reads as not-set-up.
+ */
+export function projectSetupMarkerPath(projectDir: string): string {
+ return path.join(projectDir, '.spree', 'setup-complete')
+}
+
+/** Records completed first-run setup — see {@link projectSetupMarkerPath}. */
+export function writeProjectSetupMarker(projectDir: string): void {
+ const file = projectSetupMarkerPath(projectDir)
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
+ ensureGitignoreCatchAll(path.join(path.dirname(file), '.gitignore'))
+ fs.writeFileSync(file, `${new Date().toISOString()}\n`)
+}
+
export function readProjectCredentials(projectDir: string): ProjectCredentials | null {
let raw: string
try {
diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts
index b4f93fbf9f..4ee438d324 100644
--- a/packages/cli/src/context.ts
+++ b/packages/cli/src/context.ts
@@ -91,6 +91,24 @@ export function isEjectedProject(projectDir: string): boolean {
}
}
+/**
+ * The sample-data choice create-spree-app persists in `.env`, so a deferred
+ * first run (through `spree dev`) honors the answer given at scaffold time.
+ * Returns `undefined` when `.env` doesn't declare one (older projects,
+ * hand-rolled `.env`) — callers decide the default. A declared value also
+ * fingerprints the project as scaffolded by a create-spree-app that persists
+ * setup state, which `spree dev` uses to detect unfinished setup.
+ */
+export function readSampleDataFromEnv(projectDir: string): boolean | undefined {
+ try {
+ const content = fs.readFileSync(path.join(projectDir, '.env'), 'utf-8')
+ const match = content.match(/^SPREE_SAMPLE_DATA=(true|false)\b/m)
+ return match ? match[1] === 'true' : undefined
+ } catch {
+ return undefined
+ }
+}
+
export function readPortFromEnv(projectDir: string): number {
const envPath = path.join(projectDir, '.env')
diff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.ts
index de39b04a3f..ed4c76aee6 100644
--- a/packages/cli/src/docker.ts
+++ b/packages/cli/src/docker.ts
@@ -65,6 +65,15 @@ export async function rakeTask(
.trim()
}
+/**
+ * Whether compose has ever created a container (any state, including exited)
+ * for this project.
+ */
+export async function hasProjectContainers(projectDir: string): Promise<boolean> {
+ const { stdout } = await execa('docker', ['compose', 'ps', '-a', '-q'], { cwd: projectDir })
+ return stdout.trim().length > 0
+}
+
// Whether a compose service has a running container — used by commands that
// can fall back to `compose run` when the stack is down. A defined service
// with no containers exits 0 with empty output (the legitimate false case);
diff --git a/packages/cli/tests/env.test.ts b/packages/cli/tests/env.test.ts
index acd5aa1722..1bf8a7af96 100644
--- a/packages/cli/tests/env.test.ts
+++ b/packages/cli/tests/env.test.ts
@@ -2,7 +2,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
-import { readPortFromEnv } from '../src/context'
+import { readPortFromEnv, readSampleDataFromEnv } from '../src/context'
describe('readPortFromEnv', () => {
const tempDirs: string[] = []
@@ -43,3 +43,42 @@ describe('readPortFromEnv', () => {
expect(readPortFromEnv(dir)).toBe(3000)
})
})
+
+describe('readSampleDataFromEnv', () => {
+ const tempDirs: string[] = []
+
+ function makeTempDir(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-env-test-'))
+ tempDirs.push(dir)
+ return dir
+ }
+
+ afterEach(() => {
+ for (const dir of tempDirs) {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ tempDirs.length = 0
+ })
+
+ it('returns undefined when .env is missing', () => {
+ expect(readSampleDataFromEnv(makeTempDir())).toBeUndefined()
+ })
+
+ it('returns undefined when the flag is absent', () => {
+ const dir = makeTempDir()
+ fs.writeFileSync(path.join(dir, '.env'), 'SPREE_PORT=3000\n')
+ expect(readSampleDataFromEnv(dir)).toBeUndefined()
+ })
+
+ it('honors an opt-out persisted by create-spree-app', () => {
+ const dir = makeTempDir()
+ fs.writeFileSync(path.join(dir, '.env'), 'SPREE_PORT=3000\nSPREE_SAMPLE_DATA=false\n')
+ expect(readSampleDataFromEnv(dir)).toBe(false)
+ })
+
+ it('treats an explicit true as true', () => {
+ const dir = makeTempDir()
+ fs.writeFileSync(path.join(dir, '.env'), 'SPREE_SAMPLE_DATA=true\n')
+ expect(readSampleDataFromEnv(dir)).toBe(true)
+ })
+})
diff --git a/packages/create-spree-app/CHANGELOG.md b/packages/create-spree-app/CHANGELOG.md
index 8566462027..32f644de5d 100644
--- a/packages/create-spree-app/CHANGELOG.md
+++ b/packages/create-spree-app/CHANGELOG.md
@@ -1,5 +1,25 @@
# create-spree-app
+## 1.1.1
+
+### Patch Changes
+
+- A finished `create-spree-app` run now always means a working app. The
+optional storefront and React Dashboard phases used to abort the whole
+scaffold on failure — before the final setup phase (`spree init`: fresh
+image pull, seeded database, API keys) ever ran — leaving a project whose
+first boot silently started a stale, locally cached Spree image. Those
+phases now warn and continue with a recovery command, cleaning up their
+partial `apps/` directory so the recovery command actually works, and setup
+always runs. Project docs (README.md, CLAUDE.md, dependabot.yml) are
+generated after those phases from their actual outcomes, so they never
+document an app whose setup failed. When services can't start during
+scaffolding (`--no-start`, Docker off), the first `spree dev` completes
+setup automatically (requires `@spree/cli` 2.4.2), honoring the sample-data
+choice now persisted in `.env` (`SPREE_SAMPLE_DATA`), and the printed next
+steps plus the generated README reflect that — nobody has to know
+`spree init` exists.
+
## 1.1.0
### Minor Changes
diff --git a/packages/create-spree-app/package.json b/packages/create-spree-app/package.json
index 731439c520..22b1d91824 100644
--- a/packages/create-spree-app/package.json
+++ b/packages/create-spree-app/package.json
@@ -1,6 +1,6 @@
{
"name": "create-spree-app",
- "version": "1.1.0",
+ "version": "1.1.1",
"description": "Create a new Spree Commerce project with a single command",
"type": "module",
"bin": "./dist/index.js",
diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.ts
index ac9db899e1..46fe3ee839 100644
--- a/packages/create-spree-app/src/scaffold.ts
+++ b/packages/create-spree-app/src/scaffold.ts
@@ -4,7 +4,12 @@ import * as p from '@clack/prompts'
import { execa } from 'execa'
import pc from 'picocolors'
import { downloadBackend } from './backend.js'
-import { DASHBOARD_PORT, DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from './constants.js'
+import {
+ DASHBOARD_PORT,
+ DEFAULT_ADMIN_EMAIL,
+ DEFAULT_ADMIN_PASSWORD,
+ STOREFRONT_REPO,
+} from './constants.js'
import { scaffoldDashboard } from './dashboard.js'
import {
downloadStorefront,
@@ -84,23 +89,14 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {
fs.rmSync(path.join(backendDir, 'docker-compose.yml'), { force: true })
fs.rmSync(path.join(backendDir, 'docker-compose.dev.yml'), { force: true })
- fs.writeFileSync(path.join(projectDir, '.env'), envContent(generateSecretKeyBase(), port))
- fs.writeFileSync(path.join(projectDir, 'package.json'), rootPackageJsonContent(projectName))
fs.writeFileSync(
- path.join(projectDir, 'README.md'),
- readmeContent(projectName, storefront, port, dashboard, options.packageManager),
+ path.join(projectDir, '.env'),
+ envContent(generateSecretKeyBase(), port, options.sampleData),
)
+ fs.writeFileSync(path.join(projectDir, 'package.json'), rootPackageJsonContent(projectName))
fs.writeFileSync(path.join(projectDir, '.gitignore'), gitignoreContent())
- fs.writeFileSync(
- path.join(projectDir, 'CLAUDE.md'),
- rootClaudeMdContent(storefront, dashboard, options.packageManager),
- )
fs.writeFileSync(path.join(projectDir, 'AGENTS.md'), agentsMdContent())
- const githubDir = path.join(projectDir, '.github')
- fs.mkdirSync(githubDir, { recursive: true })
- fs.writeFileSync(path.join(githubDir, 'dependabot.yml'), dependabotContent(storefront, dashboard))
-
s.stop('Project structure created.')
// Install root dependencies (@spree/cli)
@@ -108,49 +104,109 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {
await installRootDeps(projectDir, options.packageManager)
s.stop('Dependencies installed.')
+ // Phases 3/3b are optional apps — their failures warn and continue. They
+ // must never abort the scaffold before Phase 4: `spree init` is what
+ // guarantees a fresh Spree image (skipping it leaves a stale local `latest`
+ // to boot) and a seeded, credentialed backend.
+
// Phase 3: Storefront (optional)
+ let storefrontReady = storefront
if (storefront) {
- s.start('Downloading storefront template...')
- await downloadStorefront(projectDir)
- s.stop('Storefront template downloaded.')
+ try {
+ s.start('Downloading storefront template...')
+ await downloadStorefront(projectDir)
+ s.stop('Storefront template downloaded.')
- writeStorefrontEnv(projectDir, port)
+ writeStorefrontEnv(projectDir, port)
- s.start('Installing storefront dependencies...')
- await installStorefrontDeps(projectDir, options.packageManager)
- s.stop('Storefront dependencies installed.')
+ s.start('Installing storefront dependencies...')
+ await installStorefrontDeps(projectDir, options.packageManager)
+ s.stop('Storefront dependencies installed.')
+ } catch (err) {
+ storefrontReady = false
+ s.stop('Storefront setup failed.')
+ // Remove the partial checkout so the recovery command (a fresh clone)
+ // actually works instead of failing on a non-empty directory.
+ fs.rmSync(path.join(projectDir, 'apps', 'storefront'), { recursive: true, force: true })
+ p.log.warn(
+ `Continuing without the storefront — add it later by cloning ${STOREFRONT_REPO} into apps/storefront.\n${errorMessage(err)}`,
+ )
+ }
}
// Phase 3b: React Dashboard (optional, Developer Preview). Delegates to the
// project-local `npx spree add dashboard` — @spree/cli is already installed
// (root deps, above) and bundles the dashboard-starter template. It reads
// the port from the project's .env and prints its own progress.
+ let dashboardReady = dashboard
if (dashboard) {
- await scaffoldDashboard(projectDir, { install: true, packageManager: options.packageManager })
+ try {
+ await scaffoldDashboard(projectDir, { install: true, packageManager: options.packageManager })
+ } catch (err) {
+ dashboardReady = false
+ // Remove the partial scaffold so the recovery command (`spree add
+ // dashboard`, which expects the directory to be absent) actually works.
+ fs.rmSync(path.join(projectDir, 'apps', 'dashboard'), { recursive: true, force: true })
+ p.log.warn(
+ `Continuing without the React Dashboard — add it later with ${pc.bold(`${runCommand(options.packageManager)} spree add dashboard`)}.\n${errorMessage(err)}`,
+ )
+ }
}
+ // Project docs are generated only now, from the phases' actual outcomes —
+ // a README written up front from the requested flags would document apps
+ // whose setup failed.
+ fs.writeFileSync(
+ path.join(projectDir, 'README.md'),
+ readmeContent(projectName, storefrontReady, port, dashboardReady, options.packageManager),
+ )
+ fs.writeFileSync(
+ path.join(projectDir, 'CLAUDE.md'),
+ rootClaudeMdContent(storefrontReady, dashboardReady, options.packageManager),
+ )
+ const githubDir = path.join(projectDir, '.github')
+ fs.mkdirSync(githubDir, { recursive: true })
+ fs.writeFileSync(
+ path.join(githubDir, 'dependabot.yml'),
+ dependabotContent(storefrontReady, dashboardReady),
+ )
+
// Phase 4: Initialize and start services
if (options.start) {
const initArgs = ['spree', 'init']
if (!options.sampleData) initArgs.push('--no-sample-data')
- await execa(runCommand(options.packageManager), initArgs, {
- cwd: projectDir,
- stdio: 'inherit',
- })
+ try {
+ await execa(runCommand(options.packageManager), initArgs, {
+ cwd: projectDir,
+ stdio: 'inherit',
+ })
+ } catch {
+ // init streams its own output, so the underlying failure is already on
+ // screen — what the operator needs from us is the recovery command.
+ throw new Error(
+ `Setup did not finish. Start your app with: cd ${projectName} && ${options.packageManager} run dev — the first run completes setup automatically.`,
+ )
+ }
- if (storefront) {
+ if (storefrontReady) {
p.log.info(
`${pc.bold('Storefront')}: ${pc.cyan(`cd ${projectName}/apps/storefront && ${options.packageManager} run dev`)}`,
)
}
- if (dashboard) {
+ if (dashboardReady) {
p.log.info(
`${pc.bold('React Dashboard')}: ${pc.cyan(`cd ${projectName}/apps/dashboard && ${options.packageManager} run dev`)} → http://localhost:${DASHBOARD_PORT}`,
)
}
} else {
- printSuccessWithoutDocker(projectName, storefront, dashboard, port, options.packageManager)
+ printSuccessWithoutDocker(
+ projectName,
+ storefrontReady,
+ dashboardReady,
+ port,
+ options.packageManager,
+ )
}
}
@@ -167,6 +223,7 @@ function printSuccessWithoutDocker(
`${pc.bold('Next steps:')}`,
` cd ${projectName}`,
` ${run} spree dev`,
+ ` ${pc.dim('# First run completes setup automatically — pulls the latest image, seeds data, configures API keys.')}`,
]
if (hasStorefront) {
@@ -214,3 +271,7 @@ function printSuccessWithoutDocker(
p.note(lines.join('\n'), 'Project created!')
}
+
+function errorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err)
+}
diff --git a/packages/create-spree-app/src/templates/env.ts b/packages/create-spree-app/src/templates/env.ts
index c470cf5ca1..4384abd463 100644
--- a/packages/create-spree-app/src/templates/env.ts
+++ b/packages/create-spree-app/src/templates/env.ts
@@ -1,7 +1,14 @@
-export function envContent(secretKeyBase: string, port: number): string {
+/**
+ * The project root `.env`: Rails secret, backend port, image tag, and the
+ * persisted sample-data choice (`SPREE_SAMPLE_DATA`) that first-run setup
+ * reads back when it runs deferred (through `spree dev`).
+ */
+export function envContent(secretKeyBase: string, port: number, sampleData: boolean): string {
return `SECRET_KEY_BASE=${secretKeyBase}
SPREE_PORT=${port}
SPREE_VERSION_TAG=latest
+# Whether first-run setup loads demo products and orders.
+SPREE_SAMPLE_DATA=${sampleData}
`
}
diff --git a/packages/create-spree-app/src/templates/readme.ts b/packages/create-spree-app/src/templates/readme.ts
index 4332b3e822..1ed7759203 100644
--- a/packages/create-spree-app/src/templates/readme.ts
+++ b/packages/create-spree-app/src/templates/readme.ts
@@ -32,6 +32,9 @@ cd ${name}
${run} spree dev
\`\`\`
+The first run completes setup automatically — it pulls the latest Spree image,
+seeds the database, and configures API keys.
+
Wait for the services to be healthy, then open:
- **Admin Dashboard:** http://localhost:${port}/admin
@@ -101,7 +104,7 @@ This project uses [\`@spree/cli\`](https://spreecommerce.org/docs/developer/cli/
| Command | Description |
|---------|-------------|
-| \`spree dev\` | Run the backend in the foreground — streams logs, Ctrl+C stops it |
+| \`spree dev\` | Run the backend in the foreground — streams logs, Ctrl+C stops it. First run completes setup automatically |
| \`spree stop\` | Stop backend services |
| \`spree update\` | Pull latest Spree image and restart (runs migrations automatically) |
| \`spree eject\` | Switch from prebuilt image to building from \`backend/\` |
diff --git a/packages/create-spree-app/tests/templates.test.ts b/packages/create-spree-app/tests/templates.test.ts
index 28d67f6f8b..5d19a800a1 100644
--- a/packages/create-spree-app/tests/templates.test.ts
+++ b/packages/create-spree-app/tests/templates.test.ts
@@ -8,19 +8,24 @@ import { readmeContent } from '../src/templates/readme'
describe('envContent', () => {
it('includes the provided secret key', () => {
- const content = envContent('my-secret-123', 3000)
+ const content = envContent('my-secret-123', 3000, true)
expect(content).toContain('SECRET_KEY_BASE=my-secret-123')
})
it('includes SPREE_PORT', () => {
- const content = envContent('any', 3000)
+ const content = envContent('any', 3000, true)
expect(content).toContain('SPREE_PORT=3000')
})
it('uses custom port value', () => {
- const content = envContent('any', 4567)
+ const content = envContent('any', 4567, true)
expect(content).toContain('SPREE_PORT=4567')
})
+
+ it('persists the sample-data choice', () => {
+ expect(envContent('any', 3000, true)).toContain('SPREE_SAMPLE_DATA=true')
+ expect(envContent('any', 3000, false)).toContain('SPREE_SAMPLE_DATA=false')
+ })
})
describe('storefrontEnvContent', () => {