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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Improve CLI/create-spree-app around new react dashboard preview (#14313)
Damian Legawiece9b22cce82d7
diff --git a/CLAUDE.md b/CLAUDE.mdindex b54c3bb8f2..0ef9200499 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -39,7 +39,7 @@ Multi-version plans (some phases shipped, some pending):- `6.0-order-routing.md` — Two-tier extension: pluggable `Spree::OrderRouting::Strategy::Base` + STI subclasses of `Spree::OrderRoutingRule`. Phase 1 (5.5) shipped: `Channel`, `OrderRoutingRule`, strategy base + Rules + Reducer + Legacy, `preferred_stock_location_id` + `channel_id` on Order. Phase 2+ (6.0) layers Catalog/Company on top via `6.0-channels-catalogs-b2b.md`.- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5. Channel-level gated storefront access (`storefront_access` enum + channel-owned `guest_checkout`, both with store fallback, enforced in the v3 Store API) targeted for 5.6. Catalog, Company/CompanyLocation/CompanyContact for B2B pending in 6.0. Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.- `5.6-6.0-single-store-promotions-payment-methods.md` — Migrate `Spree::Promotion` + `Spree::PaymentMethod` from multi-store (`has_many :stores` via `spree_promotions_stores` / `spree_payment_methods_stores` join tables) to single-owner `belongs_to :store`, mirroring the 5.5 single-owner Product migration. 5.6 (implemented): `store_id` FK + required-store presence via `Spree::SingleStoreResource`, backfill rake task (loud per-record deprecation on shared records), shared `LegacyMultiStoreSupport` deprecation bridge, deletes the `ResourceController` `store_ids=` seam, deprecates `StoreScopedResource`; multi-store sharing moves to the `spree_multi_store` extension (join tables left intact). 6.0 cleanup: enforce `null: false`, drop join tables + bridges. Paired with `6.0-channels-catalogs-b2b.md`.-- `5.6-project-layout-and-dashboard.md` — React Dashboard Developer Preview packaging + `backend/` → `api/` project layout. Implemented: `<Dashboard />` shell export from `@spree/dashboard` (source-only, relative imports only), monorepo-canonical `packages/dashboard-starter` thin host (embedded standalone into the `@spree/cli` tarball at build time via `scripts/sync-dashboard-starter.mjs` — Vendure-style, no template repo; create-spree-app delegates to the project-local `spree add dashboard`), `spree add dashboard` + create-spree-app dashboard phase (env carries only `VITE_API_PROXY_TARGET` — never secret keys, and never `VITE_SPREE_API_URL`, which would flip the SDK to absolute cross-origin URLs and break dev on CORS), npm release job for `@spree/dashboard{,-ui,-core}` (0.x → `next` tag). Pending: layout rename + `detectApiDir` dual-layout CLI, `spree upgrade layout`; optional public template repo at 6.0 GA.+- `5.6-project-layout-and-dashboard.md` — React Dashboard Developer Preview packaging + `backend/` → `api/` project layout. Implemented: `<Dashboard />` shell export from `@spree/dashboard` (source-only, relative imports only), monorepo-canonical `packages/dashboard-starter` thin host (embedded standalone into the `@spree/cli` tarball at build time via `scripts/sync-dashboard-starter.mjs` — Vendure-style, no template repo; create-spree-app delegates to the project-local `spree add dashboard`), `spree add dashboard` + create-spree-app dashboard phase (opt-in via `--react-dashboard` while WIP — not prompted; env carries only `VITE_API_PROXY_TARGET` — never secret keys, and never `VITE_SPREE_API_URL`, which would flip the SDK to absolute cross-origin URLs and break dev on CORS), npm release job for `@spree/dashboard{,-ui,-core}` (0.x → `next` tag). Pending: layout rename + `detectApiDir` dual-layout CLI, `spree upgrade layout`; optional public template repo at 6.0 GA.- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links, cross-package collision pre-flight with package-named errors. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike passed.Pending design work (drafts, no implementation yet):diff --git a/docs/plans/5.6-project-layout-and-dashboard.md b/docs/plans/5.6-project-layout-and-dashboard.mdindex f9c41ea84d..fa09289052 100644--- a/docs/plans/5.6-project-layout-and-dashboard.md+++ b/docs/plans/5.6-project-layout-and-dashboard.md@@ -25,7 +25,7 @@ Ship the React dashboard as part of `create-spree-app` in 5.6 (Developer Preview- **`api/` is the new name for the Rails app directory** in generated projects (not `backend/`, not `server/`). Pairs with `apps/dashboard/` + `apps/storefront/` — three peers, three roles.- **`apps/dashboard/`** is the canonical location for the React SPA admin (not `apps/admin/`, not `packages/dashboard/`). Matches the `@spree/dashboard` package name and avoids legacy `spree/admin` collision. **Supersedes the `apps/admin/` reference in `5.4-spree-starter-and-create-spree-app.md`.**- **`apps/` holds JS/TS deployables; `api/` stays at the root.** Don't move the Rails app under `apps/api/`. It's qualitatively different (different language, different runtime, different CLI surface via `spree console`/`spree logs`) and keeping it at the root signals "this is the core; the JS apps consume it."-- **The dashboard is optional, like the storefront.** Default to including it interactively; allow `--no-dashboard` / `--dashboard` flags and a non-interactive default for CI.+- **The dashboard is optional, like the storefront.** *(Revised during the preview:* the dashboard is hidden from the interactive prompts — a yes/no question reads as a recommendation while it's still WIP — and included only via the `--react-dashboard` flag, or later via `spree add dashboard`. The prompt returns when it's ready for prime time.)- **`@spree/dashboard` publishes to npm and exports the app shell.** The package exports a `<Dashboard />` component (provider stack + router, bootstrap side-effects included); hosts own `index.html`, `main.tsx`, `styles.css`, and the Vite config. Distribution is **source-only**, same model as `dashboard-core`/`dashboard-ui`: the host's Vite compiles the shell, which keeps TanStack Router's generated route types first-class in the host program. Consequence: shell source uses relative imports only — no `@/` alias in anything a host compiles.- **The dashboard template is embedded in the npm packages, not a template repo.** Canonical source lives in the monorepo at `packages/dashboard-starter`; at build time `@spree/cli` and `create-spree-app` render a standalone copy into their tarballs (`workspace:^` rewritten to published versions, monorepo-only devDependencies stripped). *(Superseded an earlier `spree/dashboard-starter` GitHub template-repo design — see "Dashboard starter" under Design Details for the rationale and the 6.0 GA option.)* In the workspace, the starter doubles as the live consumer test — it compiles `<Dashboard />` from source and activates `@spree/dashboard-plugin-example` through real auto-discovery.- **The dashboard scaffold carries no credentials.** `apps/dashboard/.env.local` holds only `VITE_SPREE_API_URL`. Admins sign in with email/password (JWT in memory + httpOnly refresh cookie, per `5.5-admin-auth-cookie-refresh.md`). Anything `VITE_`-prefixed is compiled into the client bundle, so a secret key there would ship to every browser — the scaffold and `spree add dashboard` never mint keys.@@ -192,7 +192,7 @@ npx create-spree-app my-shop \--no-start```-Defaults: dashboard included unless `--no-dashboard`. Matches the storefront default behavior.+Defaults *(revised during the preview)*: dashboard excluded unless `--react-dashboard` is passed — no prompt while it's WIP.**New scaffolding phase (runs after the optional storefront phase):**@@ -527,9 +527,9 @@ All phases ship in **5.6**. The dashboard ships as Developer Preview alongside `### Phase 8: Smoke test the full flowManual QA checklist:-- [ ] `npx create-spree-app fresh --dashboard --storefront` produces working project with `api/` + `apps/dashboard/` + `apps/storefront/`.-- [ ] `npx create-spree-app fresh --no-dashboard --no-storefront` produces api-only project (single `api/` directory at root).-- [ ] `npx create-spree-app fresh --dashboard --no-storefront` works.+- [ ] `npx create-spree-app fresh --react-dashboard --storefront` produces working project with `api/` + `apps/dashboard/` + `apps/storefront/`.+- [ ] `npx create-spree-app fresh --no-storefront` produces api-only project (single `api/` directory at root).+- [ ] `npx create-spree-app fresh --react-dashboard --no-storefront` works.- [ ] In a 5.4-generated project (with `backend/`): all existing commands (`spree dev`, `spree console`, `spree eject`) keep working unchanged.- [ ] In the same 5.4 project: `npx spree add dashboard` clones, mints key, installs, dashboard boots and connects to API — without forcing the layout upgrade first.- [ ] In the same 5.4 project: `npx spree upgrade layout` succeeds, commit looks clean, `npx spree dev` boots after rename.diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.mdindex b8000dfa8c..5810b16f3a 100644--- a/packages/cli/CHANGELOG.md+++ b/packages/cli/CHANGELOG.md@@ -1,5 +1,24 @@# @spree/cli+## 2.4.4++### Patch Changes++- Streamline the post-setup summary for projects with the React Dashboard.+The dashboard's dev server is presented as THE admin — the+`cd apps/dashboard && pnpm dev` command with the admin credentials and a+dim pointer to the classic admin — instead of listing two admins where only+the classic one carried credentials. The image-served `/dashboard` build+stays a deployment detail in the docs. `spree dev` (and first-run setup)+now co-runs the dashboard's Vite dev server with the Docker stack — one+command brings up the whole dev environment, its output joins the stream+with a `dashboard |` prefix, Ctrl+C stops everything, a dashboard crash+warns without taking the API down, and `--open` waits for Vite and opens+the URL it actually reports (ports auto-bump when 5173 is taken). `spree add dashboard` gains+`--quiet` to skip its summary note when a wrapping tool (create-spree-app)+prints its own. Projects without the dashboard keep the classic summary+unchanged.+## 2.4.3### Patch Changesdiff --git a/packages/cli/package.json b/packages/cli/package.jsonindex ca8390d28e..ecff58f771 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -1,6 +1,6 @@{"name": "@spree/cli",- "version": "2.4.3",+ "version": "2.4.4","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.tsindex a458569e8d..3b948d94bc 100644--- a/packages/cli/src/commands/add.ts+++ b/packages/cli/src/commands/add.ts@@ -15,6 +15,8 @@ interface AddDashboardOptions {template: string/** Run the package-manager install after scaffolding. */install: boolean+ /** Skip the final summary note — create-spree-app prints its own. */+ quiet?: boolean}// `spree add <thing>` — bolt an optional component onto an existing project.@@ -30,21 +32,25 @@ export function registerAddCommand(program: Command) {'Starter template: git URL or local path (default: the template bundled with the CLI; env SPREE_DASHBOARD_TEMPLATE overrides)',).option('--no-install', 'Skip dependency install')- .action(async (thing: string, flags: { template?: string; install: boolean }) => {- if (thing !== 'dashboard') {- console.error(`\n${pc.red('Error:')} Unknown component: ${thing}. Try: dashboard\n`)- process.exit(2)- }+ .option('--quiet', 'Skip the final summary note (for wrapping tools that print their own)')+ .action(+ async (thing: string, flags: { template?: string; install: boolean; quiet?: boolean }) => {+ if (thing !== 'dashboard') {+ console.error(`\n${pc.red('Error:')} Unknown component: ${thing}. Try: dashboard\n`)+ process.exit(2)+ }- p.intro(pc.bgCyan(pc.black(' Spree Dashboard ')))- const ctx = detectProject()- await addDashboard(ctx, {- template:- flags.template ?? process.env.SPREE_DASHBOARD_TEMPLATE ?? resolveBundledTemplate(),- install: flags.install,- })- p.outro('Done!')- })+ p.intro(pc.bgCyan(pc.black(' Spree Dashboard ')))+ const ctx = detectProject()+ await addDashboard(ctx, {+ template:+ flags.template ?? process.env.SPREE_DASHBOARD_TEMPLATE ?? resolveBundledTemplate(),+ install: flags.install,+ quiet: flags.quiet,+ })+ p.outro('Done!')+ },+ )}/**@@ -115,10 +121,15 @@ export async function addDashboard(ctx: ProjectContext, opts: AddDashboardOption}}+ if (opts.quiet) returnp.note([`Start it with:`,- ` ${pc.cyan(`cd apps/dashboard && ${opts.install ? '' : 'pnpm install && '}pnpm dev`)}`,+ ` ${pc.cyan(`${pm === 'npm' ? 'npx' : pm} spree dev`)}`,+ ` ${pc.dim('# runs the API and the dashboard together')}`,+ ...(opts.install+ ? []+ : [` ${pc.dim(`# install dependencies first: cd apps/dashboard && ${pm} install`)}`]),'',`Then open ${pc.bold(`http://localhost:${DASHBOARD_PORT}`)} and sign in`,`with your admin email and password.`,diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.tsindex cb61b8d34c..a0c505032b 100644--- a/packages/cli/src/commands/dev.ts+++ b/packages/cli/src/commands/dev.ts@@ -4,13 +4,19 @@ 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 { DASHBOARD_PORT, DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'import {detectProject,hasMonorepoSpreePath,isEjectedProject,readSampleDataFromEnv,} from '../context.js'+import {+ dashboardDevRunnable,+ hasDashboardApp,+ startDashboardDevServer,+ warnDashboardNotRunnable,+} from '../dashboard-server.js'import {buildAdminStylesheets,dockerCompose,@@ -24,7 +30,9 @@ import { runFirstRunSetup } from './init.js'export function registerDevCommand(program: Command): void {program.command('dev')- .description('Run the app in the foreground — streams web + worker logs; Ctrl+C stops them')+ .description(+ 'Run the app in the foreground — the API, plus the React Dashboard dev server when apps/dashboard exists; Ctrl+C stops them',+ ).action(async () => {const ctx = detectProject()@@ -83,13 +91,29 @@ export function registerDevCommand(program: Command): void {}}+ // The summary and the spawn key off the same runnable check so the+ // card never advertises a dev server that can't start (deps missing).+ const withDashboard = hasDashboardApp(ctx.projectDir) && dashboardDevRunnable(ctx.projectDir)+ if (hasDashboardApp(ctx.projectDir) && !withDashboard) {+ warnDashboardNotRunnable(ctx.projectDir)+ }p.note(['',- pc.bold('Admin Dashboard'),- ` ${pc.cyan(`http://localhost:${ctx.port}/admin`)}`,- ` Email: ${DEFAULT_ADMIN_EMAIL}`,- ` Password: ${DEFAULT_ADMIN_PASSWORD}`,+ ...(withDashboard+ ? [+ pc.bold('Admin Dashboard (React, Developer Preview)'),+ ` ${pc.cyan(`http://localhost:${DASHBOARD_PORT}`)}`,+ ` Email: ${DEFAULT_ADMIN_EMAIL}`,+ ` Password: ${DEFAULT_ADMIN_PASSWORD}`,+ ` ${pc.dim(`Live-reloading from apps/dashboard/ — classic admin: http://localhost:${ctx.port}/admin`)}`,+ ]+ : [+ 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`)}`,@@ -99,7 +123,8 @@ export function registerDevCommand(program: Command): void {)p.log.info(- `Starting services — web + worker logs stream below. ${pc.bold('Ctrl+C')} stops them ` ++ `Starting services — ${withDashboard ? 'API + dashboard logs' : 'web + worker logs'} stream below. ` ++ `${pc.bold('Ctrl+C')} stops them ` +`(databases keep running; ${pc.bold('spree stop')} shuts everything down).\n`,)@@ -111,6 +136,7 @@ export function registerDevCommand(program: Command): void {const ignoreSigint = () => {}process.on('SIGINT', ignoreSigint)let result: { exitCode?: number }+ let dashboard: ReturnType<typeof startDashboardDevServer> = nulltry {// Prime the shared bundle_cache volume with web alone first so the// foreground `up web worker` below doesn't race the cold-volume@@ -161,11 +187,19 @@ export function registerDevCommand(program: Command): void {}}+ // Co-run the dashboard's Vite dev server with the Docker stack — one+ // command, the whole dev environment. Its output joins the stream+ // below with a `dashboard |` prefix; the terminal's Ctrl+C reaches it+ // alongside compose (same foreground process group), and stop() in+ // the finally covers non-signal exits.+ dashboard = withDashboard ? startDashboardDevServer(ctx.projectDir) : null+result = await dockerCompose(['up', 'web', 'worker'], ctx.projectDir, {stdio: 'inherit',reject: false,})} finally {+ dashboard?.stop()process.off('SIGINT', ignoreSigint)}@@ -179,7 +213,7 @@ export function registerDevCommand(program: Command): void {}p.outro(- `Web + worker stopped. Databases keep running — ${pc.bold('spree stop')} shuts everything down.`,+ `${withDashboard ? 'API + dashboard' : 'Web + worker'} stopped. Databases keep running — ${pc.bold('spree stop')} shuts everything down.`,)})}diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 88eab3b5f1..6961c224ee 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -6,8 +6,14 @@ import type { Command } from 'commander'import { execa, execaCommand } from 'execa'import pc from 'picocolors'import { mintProjectCredentials, writeProjectSetupMarker } from '../config.js'-import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'+import { DASHBOARD_PORT, DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'import { detectProject, readSampleDataFromEnv } from '../context.js'+import {+ dashboardDevRunnable,+ hasDashboardApp,+ startDashboardDevServer,+ warnDashboardNotRunnable,+} from '../dashboard-server.js'import { dockerCompose, primeBundleVolume, rakeTask, streamLogs } from '../docker.js'import { detectPackageManager, ensureDashboardDevEnv } from './add.js'@@ -90,16 +96,37 @@ export async function runFirstRunSetup(flags: {writeProjectSetupMarker(ctx.projectDir)- const dashboardDir = path.join(ctx.projectDir, 'apps', 'dashboard')- const dashboardPm = detectPackageManager(ctx.projectDir, dashboardDir)+ // With the React Dashboard chosen, its dev server IS the admin — started+ // below alongside the stack, so what the user customizes is what they use.+ // One admin block; the classic admin gets a one-line pointer. (The+ // production image serves the built dashboard at /dashboard — a deployment+ // detail, not a dev-flow concept.) The summary, --open, and the spawn all+ // key off the same runnable check so they can't disagree — if the dev+ // server can't start (deps install failed above), the card leads with the+ // classic admin instead of advertising a dead URL.+ const dashboardRunnable = dashboardDevRunnable(ctx.projectDir)+ if (hasDashboardApp(ctx.projectDir) && !dashboardRunnable) {+ warnDashboardNotRunnable(ctx.projectDir)+ }+ const adminBlock = dashboardRunnable+ ? [+ pc.bold('Admin Dashboard (React, Developer Preview)'),+ ` ${pc.cyan(`http://localhost:${DASHBOARD_PORT}`)}`,+ ` Email: ${DEFAULT_ADMIN_EMAIL}`,+ ` Password: ${DEFAULT_ADMIN_PASSWORD}`,+ ` ${pc.dim(`Live-reloading from apps/dashboard/ — classic admin: http://localhost:${ctx.port}/admin`)}`,+ ]+ : [+ pc.bold('Admin Dashboard'),+ ` ${pc.cyan(`http://localhost:${ctx.port}/admin`)}`,+ ` Email: ${DEFAULT_ADMIN_EMAIL}`,+ ` Password: ${DEFAULT_ADMIN_PASSWORD}`,+ ]p.note(['',- pc.bold('Admin Dashboard'),- ` ${pc.cyan(`http://localhost:${ctx.port}/admin`)}`,- ` Email: ${DEFAULT_ADMIN_EMAIL}`,- ` Password: ${DEFAULT_ADMIN_PASSWORD}`,+ ...adminBlock,'',pc.bold('Store API'),` ${pc.cyan(`http://localhost:${ctx.port}/api/v3/store`)}`,@@ -110,23 +137,36 @@ export async function runFirstRunSetup(flags: {` 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`)+ // Co-run the dashboard's Vite dev server so the admin the card names is+ // actually running. Spawned after the card so its prefixed output doesn't+ // tear through the box. The server runs in its own process group, so+ // Ctrl+C (which would otherwise kill only this CLI and orphan Vite) gets+ // an explicit handler: stop the group, then exit as SIGINT would have.+ // The finally covers non-signal failures (daemon died mid-stream).+ const dashboard = dashboardRunnable ? startDashboardDevServer(ctx.projectDir) : null+ const onSigint = () => {+ dashboard?.stop()+ process.exit(130)}+ process.once('SIGINT', onSigint)- p.log.info('Streaming logs (Ctrl+C to stop)...\n')- await streamLogs('web', ctx.projectDir)+ try {+ if (flags.open) {+ // With the dashboard, wait for Vite to report ready (it auto-bumps the+ // port when 5173 is taken) so the browser opens the real URL.+ await openBrowser(dashboard ? await dashboard.url : `http://localhost:${ctx.port}/admin`)+ }++ p.log.info('Streaming logs (Ctrl+C to stop)...\n')+ await streamLogs('web', ctx.projectDir)+ } finally {+ process.removeListener('SIGINT', onSigint)+ dashboard?.stop()+ }}// Install an optional app's dependencies when they're missing — a freshdiff --git a/packages/cli/src/dashboard-server.ts b/packages/cli/src/dashboard-server.tsnew file mode 100644index 0000000000..63c35340ec--- /dev/null+++ b/packages/cli/src/dashboard-server.ts@@ -0,0 +1,154 @@+import { type ChildProcess, spawn } from 'node:child_process'+import fs from 'node:fs'+import path from 'node:path'+import * as p from '@clack/prompts'+import pc from 'picocolors'+import { detectPackageManager } from './commands/add.js'+import { DASHBOARD_PORT } from './constants.js'++export function hasDashboardApp(projectDir: string): boolean {+ return fs.existsSync(path.join(projectDir, 'apps', 'dashboard', 'package.json'))+}++/**+ * Whether the dashboard dev server can actually start — the app exists and+ * its dependencies are installed. Callers key the admin summary, `--open`,+ * and the spawn off this one answer so they can't disagree.+ */+export function dashboardDevRunnable(projectDir: string): boolean {+ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')+ return (+ fs.existsSync(path.join(dashboardDir, 'package.json')) &&+ fs.existsSync(path.join(dashboardDir, 'node_modules'))+ )+}++/** The install hint printed when the app exists but isn't runnable. */+export function warnDashboardNotRunnable(projectDir: string): void {+ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')+ p.log.warn(+ `${pc.bold('apps/dashboard/')} has no dependencies installed — skipping its dev server. ` ++ `Install them (cd apps/dashboard && ${detectPackageManager(projectDir, dashboardDir)} install) and rerun.`,+ )+}++export interface DashboardDevServer {+ /**+ * The URL Vite actually reports once ready (it auto-bumps the port when+ * 5173 is taken). Always settles — falls back to the default URL on+ * timeout, spawn failure, early exit, or stop().+ */+ url: Promise<string>+ stop: () => void+}++// Column-aligned with compose's `web-1 | ` log prefixes, so the+// multiplexed stream reads as one stack.+const LOG_PREFIX = pc.dim('dashboard | ')++// Strips ANSI color codes for matching (Vite's output is colored). Built+// from a char code — regex literals disallow control-character escapes.+const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g')++/**+ * Start the dashboard's Vite dev server as a sibling of the Docker stack —+ * `spree dev` and first-run setup co-run it, so one command brings up the+ * whole dev environment. Output is line-prefixed into the shared stream.+ * Any failure degrades to a warning: a dashboard that can't start or+ * crashes must never take the API down.+ */+export function startDashboardDevServer(projectDir: string): DashboardDevServer | null {+ if (!dashboardDevRunnable(projectDir)) return null++ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')+ const pm = detectPackageManager(projectDir, dashboardDir)+ // detached (POSIX): its own process group, so stop() can signal the whole+ // tree — `pm run dev` wraps Vite in a child, and SIGTERM to the wrapper+ // alone can leave Vite orphaned holding the port. Windows gets shell mode+ // for the .cmd shims and plain kill (no group signals).+ const windows = process.platform === 'win32'+ const child: ChildProcess = spawn(pm, ['run', 'dev'], {+ cwd: dashboardDir,+ stdio: ['ignore', 'pipe', 'pipe'],+ detached: !windows,+ shell: windows,+ })++ const fallbackUrl = `http://localhost:${DASHBOARD_PORT}`+ let settled = false+ let resolveUrl: (url: string) => void = () => {}+ const url = new Promise<string>((resolve) => {+ resolveUrl = resolve+ })+ const settle = (value: string) => {+ settled = true+ clearTimeout(fallback)+ resolveUrl(value)+ }+ // Vite is normally ready in well under a second; a generous fallback keeps+ // `--open` from hanging if its output format ever changes.+ const fallback = setTimeout(() => settle(fallbackUrl), 30_000)+ fallback.unref()++ const forward = (stream: NodeJS.ReadableStream, out: NodeJS.WriteStream) => {+ let pending = ''+ stream.on('data', (chunk: Buffer) => {+ pending += chunk.toString()+ const lines = pending.split('\n')+ pending = lines.pop() ?? ''+ for (const line of lines) {+ out.write(`${LOG_PREFIX}${line}\n`)+ if (!settled) {+ const match = line.replace(ANSI, '').match(/Local:\s+(http:\/\/\S+?)\/?\s*$/)+ if (match) settle(match[1])+ }+ }+ })+ }+ if (child.stdout) forward(child.stdout, process.stdout)+ if (child.stderr) forward(child.stderr, process.stderr)++ let stopping = false++ // A spawn failure (missing binary, PATH issues) emits 'error' — unhandled+ // it would crash the CLI, the opposite of crash isolation.+ child.on('error', (error) => {+ settle(fallbackUrl)+ p.log.warn(+ `Could not start the dashboard dev server (${error.message}) — start it manually with ` ++ `${pc.bold(`cd apps/dashboard && ${pm} run dev`)}. The API keeps running.`,+ )+ })++ child.on('exit', (code, signal) => {+ settle(fallbackUrl)+ // Only a genuine crash warns: not our stop(), and not a signal exit —+ // Ctrl+C reaches the child before stop() runs, as SIGINT (signal) or a+ // 130 exit code depending on the package manager.+ if (!stopping && signal === null && code !== null && code !== 0 && code !== 130) {+ p.log.warn(+ `The dashboard dev server exited (code ${code}) — restart it with ` ++ `${pc.bold(`cd apps/dashboard && ${pm} run dev`)}. The API keeps running.`,+ )+ }+ })++ return {+ url,+ stop: () => {+ stopping = true+ settle(fallbackUrl)+ if (child.exitCode !== null || child.killed) return+ if (!windows && child.pid) {+ // Signal the whole process group so Vite goes down with its wrapper.+ try {+ process.kill(-child.pid, 'SIGTERM')+ return+ } catch {+ // group already gone — fall through to the direct kill+ }+ }+ child.kill('SIGTERM')+ },+ }+}diff --git a/packages/cli/tests/dashboard-server.test.ts b/packages/cli/tests/dashboard-server.test.tsnew file mode 100644index 0000000000..c9a7031880--- /dev/null+++ b/packages/cli/tests/dashboard-server.test.ts@@ -0,0 +1,41 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { hasDashboardApp, startDashboardDevServer } from '../src/dashboard-server.js'++// The classic (no-dashboard) flow must be a strict no-op: no spawn, no+// output beyond a hint, nothing returned that dev/init would manage.+describe('dashboard-server gating', () => {+ let projectDir: string++ beforeEach(() => {+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-dash-server-'))+ })++ afterEach(() => {+ fs.rmSync(projectDir, { recursive: true, force: true })+ })++ it('hasDashboardApp is false without apps/dashboard', () => {+ expect(hasDashboardApp(projectDir)).toBe(false)+ })++ it('startDashboardDevServer returns null without apps/dashboard', () => {+ expect(startDashboardDevServer(projectDir)).toBeNull()+ })++ it('returns null (skip, not crash) when dependencies are not installed', () => {+ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')+ fs.mkdirSync(dashboardDir, { recursive: true })+ fs.writeFileSync(path.join(dashboardDir, 'package.json'), '{"name":"dashboard"}\n')+ expect(startDashboardDevServer(projectDir)).toBeNull()+ })++ it('hasDashboardApp is true with a dashboard app', () => {+ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')+ fs.mkdirSync(dashboardDir, { recursive: true })+ fs.writeFileSync(path.join(dashboardDir, 'package.json'), '{"name":"dashboard"}\n')+ expect(hasDashboardApp(projectDir)).toBe(true)+ })+})diff --git a/packages/create-spree-app/CHANGELOG.md b/packages/create-spree-app/CHANGELOG.mdindex 32f644de5d..7f20344913 100644--- a/packages/create-spree-app/CHANGELOG.md+++ b/packages/create-spree-app/CHANGELOG.md@@ -1,5 +1,32 @@# create-spree-app+## 1.1.2++### Patch Changes++- The React Dashboard is no longer prompted for — it's a work-in-progress+Developer Preview, and a yes/no prompt reads as a recommendation. Include it+with the new `--react-dashboard` flag (or later via `spree add dashboard`);+the `--no-dashboard` flag is gone with the prompt.++- Cut the duplicate output when scaffolding with the React Dashboard: the+delegated `spree add dashboard` summary card is suppressed (its content+lives in the main card), and the success card plus generated README present+the dashboard's dev server as THE admin — the `cd apps/dashboard &&+pnpm dev` command with the admin credentials and a dim classic-admin+pointer — instead of two admins where only the classic one carried+credentials. `spree dev` co-runs that dev server with the API (one command,+whole environment), so the printed URL is live as soon as the stack is up.+For testing unreleased CLIs, the `SPREE_CLI_VERSION` env var overrides the+scaffolded `@spree/cli` dependency spec (a range or a `file:` tarball path+— same name as the starter Dockerfile's ARG). The scaffolded pin's floor is+now `^2.4.4` — the CLI behavior the scaffold relies on; an older resolve+would reject the new flags and silently drop the dashboard phase. Projects scaffolded without the dashboard keep the classic+`/admin` block exactly as before. User-facing wording now calls the Rails+app what it is to a storefront/dashboard developer — the Spree API+("Customize the Spree API", "Start the Spree API") — ahead of the planned+`backend/` → `api/` directory rename. Requires `@spree/cli` 2.4.4.+## 1.1.1### Patch Changesdiff --git a/packages/create-spree-app/package.json b/packages/create-spree-app/package.jsonindex 22b1d91824..34b670c39e 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.1",+ "version": "1.1.2","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/dashboard.ts b/packages/create-spree-app/src/dashboard.tsindex b9c372a59f..f097aa6c1d 100644--- a/packages/create-spree-app/src/dashboard.ts+++ b/packages/create-spree-app/src/dashboard.ts@@ -15,7 +15,9 @@ export async function scaffoldDashboard(projectDir: string,opts: { install: boolean; packageManager: PackageManager },): Promise<void> {- const args = ['spree', 'add', 'dashboard']+ // --quiet: the scaffold's own summary cards cover the dashboard — the+ // command's "Dashboard added!" note would just duplicate them.+ const args = ['spree', 'add', 'dashboard', '--quiet']if (!opts.install) args.push('--no-install')await execa(runCommand(opts.packageManager), args, { cwd: projectDir, stdio: 'inherit' })}diff --git a/packages/create-spree-app/src/index.ts b/packages/create-spree-app/src/index.tsindex 8adb441bfc..7baa9f34e8 100644--- a/packages/create-spree-app/src/index.ts+++ b/packages/create-spree-app/src/index.ts@@ -13,7 +13,10 @@ const program = new Command().description('Create a new Spree Commerce project').argument('[directory]', 'project directory').option('--no-storefront', 'skip Next.js storefront setup')- .option('--no-dashboard', 'skip React Dashboard setup (Developer Preview)')+ .option(+ '--react-dashboard',+ 'include the React Dashboard (Developer Preview — work in progress; also available later via `spree add dashboard`)',+ ).option('--no-sample-data', 'skip loading sample data').option('--no-start', 'do not start Docker services').option('--port <number>', 'port for the Spree backend', String(DEFAULT_SPREE_PORT))@@ -37,7 +40,7 @@ const program = new Command()const options = await runPrompts({directory,noStorefront: flags.storefront === false ? true : undefined,- noDashboard: flags.dashboard === false ? true : undefined,+ reactDashboard: flags.reactDashboard === true,noSampleData: flags.sampleData === false ? true : undefined,noStart: flags.start === false ? true : undefined,packageManager,diff --git a/packages/create-spree-app/src/prompts.ts b/packages/create-spree-app/src/prompts.tsindex 1b0459f7a2..acaafc1de6 100644--- a/packages/create-spree-app/src/prompts.ts+++ b/packages/create-spree-app/src/prompts.ts@@ -4,7 +4,7 @@ import type { PackageManager, ScaffoldOptions } from './types.js'interface PromptFlags {directory?: stringnoStorefront?: boolean- noDashboard?: boolean+ reactDashboard?: booleannoSampleData?: booleannoStart?: booleanpackageManager?: PackageManager@@ -44,21 +44,11 @@ export async function runPrompts(flags: PromptFlags): Promise<Omit<ScaffoldOptiostorefront = storefrontResult}- let dashboard: boolean- if (flags.noDashboard !== undefined) {- dashboard = !flags.noDashboard- } else {- const dashboardResult = await p.confirm({- message: 'Include React Dashboard? (Developer Preview of the next-gen admin)',- initialValue: true,- })-- if (p.isCancel(dashboardResult)) {- p.cancel('Setup cancelled.')- process.exit(0)- }- dashboard = dashboardResult- }+ // Deliberately not prompted: the React Dashboard is a work-in-progress+ // Developer Preview, and a yes/no prompt reads as a recommendation. It's+ // opt-in via --react-dashboard (or later via `spree add dashboard`) until+ // it's ready for prime time.+ const dashboard = flags.reactDashboard ?? falselet sampleData: booleanif (flags.noSampleData !== undefined) {diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.tsindex 46fe3ee839..7724686c30 100644--- a/packages/create-spree-app/src/scaffold.ts+++ b/packages/create-spree-app/src/scaffold.ts@@ -194,11 +194,9 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {`${pc.bold('Storefront')}: ${pc.cyan(`cd ${projectName}/apps/storefront && ${options.packageManager} run dev`)}`,)}- if (dashboardReady) {- p.log.info(- `${pc.bold('React Dashboard')}: ${pc.cyan(`cd ${projectName}/apps/dashboard && ${options.packageManager} run dev`)} → http://localhost:${DASHBOARD_PORT}`,- )- }+ // No dashboard line here — with the dashboard chosen, `spree init`'s+ // summary already leads with it (served at /dashboard, plus the+ // customize command).} else {printSuccessWithoutDocker(projectName,@@ -236,26 +234,35 @@ function printSuccessWithoutDocker()}+ // With the React Dashboard chosen, its dev server IS the admin — and+ // `spree dev` co-runs it with the API, so the URL is live the moment the+ // stack is up. One admin block; the classic admin gets a one-line pointer.if (hasDashboard) {lines.push('',- ` ${pc.dim('# React Dashboard (Developer Preview), in another terminal:')}`,- ` cd ${projectName}/apps/dashboard`,- ` ${installCommand(pm)}`,- ` ${pm} run dev`,+ `${pc.bold('Admin Dashboard (React, Developer Preview)')}`,+ ` http://localhost:${DASHBOARD_PORT}`,+ ` ${pc.dim('# started automatically by `spree dev`, live-reloading from apps/dashboard/')}`,+ ` Email: ${DEFAULT_ADMIN_EMAIL}`,+ ` Password: ${DEFAULT_ADMIN_PASSWORD}`,+ ` ${pc.dim(`Classic admin: http://localhost:${port}/admin`)}`,+ '',+ )+ } else {+ lines.push(+ '',+ `${pc.bold('Admin Dashboard')}`,+ ` http://localhost:${port}/admin`,+ ` Email: ${DEFAULT_ADMIN_EMAIL}`,+ ` Password: ${DEFAULT_ADMIN_PASSWORD}`,+ '',)}lines.push(- '',- `${pc.bold('Admin Dashboard')}`,- ` http://localhost:${port}/admin`,- ` Email: ${DEFAULT_ADMIN_EMAIL}`,- ` Password: ${DEFAULT_ADMIN_PASSWORD}`,- '',- `${pc.bold('Customize the backend')}`,+ `${pc.bold('Customize the Spree API')}`,` ${run} spree eject`,- ` ${pc.dim('# Then edit backend/Gemfile, backend/app/, backend/config/')}`,+ ` ${pc.dim('# Then edit backend/ — the Rails API app (Gemfile, app/, config/)')}`,'',`${pc.bold('Agent skills (optional)')}`,` ${dlxCommand(pm)} skills add spree/agent-skills`,diff --git a/packages/create-spree-app/src/templates/claude-md.ts b/packages/create-spree-app/src/templates/claude-md.tsindex e56580b963..b40033d1c4 100644--- a/packages/create-spree-app/src/templates/claude-md.ts+++ b/packages/create-spree-app/src/templates/claude-md.ts@@ -111,12 +111,12 @@ export function rootClaudeMdContent('## Common Commands','','```bash',- `${pm} run dev # Start backend (Docker)`,+ `${pm} run dev # Start the Spree API (Docker)`,`${pm} run stop # Stop services`,`${pm} run console # Rails console`,`${pm} run logs # Backend logs`,`${run} spree api get products # Query the Admin API (read-only key preconfigured)`,- `${run} spree eject # Switch to local backend builds`,+ `${run} spree eject # Build the API locally from backend/`,'```','',)diff --git a/packages/create-spree-app/src/templates/package-json.ts b/packages/create-spree-app/src/templates/package-json.tsindex 734a610ef3..d6c9c65506 100644--- a/packages/create-spree-app/src/templates/package-json.ts+++ b/packages/create-spree-app/src/templates/package-json.ts@@ -18,7 +18,13 @@ export function rootPackageJsonContent(name: string): string {'api-key': 'spree api-key',},dependencies: {- '@spree/cli': '^2.0.0',+ // The floor matches the CLI behavior this scaffold relies on (the+ // --quiet delegation, dev co-run, first-run setup) — an older resolve+ // would reject the flags and silently drop the dashboard phase.+ // SPREE_CLI_VERSION overrides the spec for testing unreleased CLIs —+ // a range, or a `file:`/`link:` path to a packed tarball / checkout+ // (mirrors the starter Dockerfile's ARG of the same name).+ '@spree/cli': process.env.SPREE_CLI_VERSION ?? '^2.4.4','@spree/docs': 'latest',},}diff --git a/packages/create-spree-app/src/templates/readme.ts b/packages/create-spree-app/src/templates/readme.tsindex 1ed7759203..b5dfd95137 100644--- a/packages/create-spree-app/src/templates/readme.ts+++ b/packages/create-spree-app/src/templates/readme.ts@@ -25,7 +25,7 @@ A [Spree Commerce](https://spreecommerce.org) project.- [Docker](https://docs.docker.com/get-docker/) installed and running-### Start the backend+### Start the Spree API\`\`\`bashcd ${name}@@ -37,9 +37,16 @@ seeds the database, and configures API keys.Wait for the services to be healthy, then open:-- **Admin Dashboard:** http://localhost:${port}/admin+${+ hasDashboard+ ? `- **Admin Dashboard (React, Developer Preview):** http://localhost:${DASHBOARD_PORT} — started automatically by \`spree dev\`- Email: \`${DEFAULT_ADMIN_EMAIL}\`- Password: \`${DEFAULT_ADMIN_PASSWORD}\`+ - Classic admin: http://localhost:${port}/admin (same credentials)`+ : `- **Admin Dashboard:** http://localhost:${port}/admin+ - Email: \`${DEFAULT_ADMIN_EMAIL}\`+ - Password: \`${DEFAULT_ADMIN_PASSWORD}\``+}- **Store API:** http://localhost:${port}/api/v3/store`@@ -60,21 +67,22 @@ Open http://localhost:${STOREFRONT_PORT}if (hasDashboard) {content += `-### Start the React Dashboard (Developer Preview)+### The React Dashboard (Developer Preview)-The React Dashboard in \`apps/dashboard/\` is the next generation of the Spree-admin — a customizable React SPA you can extend with your own pages and-plugins. It's a Developer Preview: the classic admin at-http://localhost:${port}/admin remains the stable default.--Dependencies are already installed during setup — just start it:+\`apps/dashboard/\` is your admin — a customizable React SPA (plugins, your+own pages, table tweaks) with live reload. \`spree dev\` starts it+automatically alongside the API; to run it on its own:\`\`\`bashcd apps/dashboard${pm} run dev\`\`\`-Open http://localhost:${DASHBOARD_PORT} and sign in with the admin email and password above.+Open http://localhost:${DASHBOARD_PORT} and sign in with the admin email and+password above. The classic admin remains at http://localhost:${port}/admin.++When you deploy, the production image builds your dashboard and serves it at+\`/dashboard\` on the same origin as the API (\`${run} spree build --production\`).To learn how to add pages, tweak tables, or build plugins, see the[React Dashboard docs](https://spreecommerce.org/docs/developer/dashboard/overview).@@ -82,9 +90,9 @@ To learn how to add pages, tweak tables, or build plugins, see the}content += `-## Customizing the Backend+## Customizing the Spree API-The \`backend/\` directory contains a full Rails application with Spree installed. By default, the project uses a prebuilt Docker image. To switch to building from your local backend:+The \`backend/\` directory is the Spree API — a full Rails application serving the Store and Admin APIs (plus background jobs and transactional emails) that your storefront and dashboard talk to. By default, the project runs it from a prebuilt Docker image. To switch to building from your local copy:\`\`\`bash${run} spree eject@@ -92,20 +100,20 @@ ${run} spree ejectThis rebuilds the Docker image from \`backend/\` and restarts services. You can then:-- **Customize the backend** by editing the files in \`backend/\`+- **Customize the API** by editing the files in \`backend/\`- **Add gems** to \`backend/Gemfile\`- **Add new resources** with \`spree generate model <name> <attributes>\`## Spree CLI-This project uses [\`@spree/cli\`](https://spreecommerce.org/docs/developer/cli/quickstart) to manage the backend.+This project uses [\`@spree/cli\`](https://spreecommerce.org/docs/developer/cli/quickstart) to manage the Spree API.### Services| Command | Description ||---------|-------------|-| \`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 dev\` | Run the app in the foreground — streams logs, Ctrl+C stops it. First run completes setup automatically |+| \`spree stop\` | Stop the API services || \`spree update\` | Pull latest Spree image and restart (runs migrations automatically) || \`spree eject\` | Switch from prebuilt image to building from \`backend/\` || \`spree build --production\` | Build the production image — includes \`apps/dashboard\` when present |diff --git a/packages/create-spree-app/tests/templates.test.ts b/packages/create-spree-app/tests/templates.test.tsindex 5d19a800a1..52ab20cc0a 100644--- a/packages/create-spree-app/tests/templates.test.ts+++ b/packages/create-spree-app/tests/templates.test.ts@@ -61,6 +61,18 @@ describe('rootPackageJsonContent', () => {expect(pkg.name).toBe('my-store')})+ it('SPREE_CLI_VERSION overrides the @spree/cli spec (unreleased-CLI testing)', () => {+ process.env.SPREE_CLI_VERSION = 'file:/tmp/spree-cli-local.tgz'+ try {+ const pkg = JSON.parse(rootPackageJsonContent('my-store'))+ expect(pkg.dependencies['@spree/cli']).toBe('file:/tmp/spree-cli-local.tgz')+ } finally {+ delete process.env.SPREE_CLI_VERSION+ }+ const pkg = JSON.parse(rootPackageJsonContent('my-store'))+ expect(pkg.dependencies['@spree/cli']).toBe('^2.4.4')+ })+it('includes convenience scripts using spree cli', () => {const pkg = JSON.parse(rootPackageJsonContent('my-store'))expect(pkg.scripts.dev).toBe('spree dev')@@ -150,8 +162,10 @@ describe('readmeContent', () => {it('includes the React Dashboard section when included', () => {const content = readmeContent('my-store', true, 3000, true)- expect(content).toContain('### Start the React Dashboard (Developer Preview)')+ expect(content).toContain('### The React Dashboard (Developer Preview)')+ // The dashboard's dev server IS the admin; the classic admin is a pointer.expect(content).toContain('http://localhost:5173')+ expect(content).toContain('Classic admin: http://localhost:3000/admin')expect(content).toContain('docs/developer/dashboard')})