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.

Embed the dashboard-starter template in the @spree/cli tarball

Damian Legawiec2ecebc9c16f0
diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml
index cd4be088c1..574321256d 100644
--- a/.github/workflows/packages.yml
+++ b/.github/workflows/packages.yml
@@ -419,61 +419,11 @@ jobs:
cd ../..
done
- # Push the monorepo-canonical packages/dashboard-starter out to the
- # spree/dashboard-starter template repo (what `spree add dashboard` and
- # create-spree-app clone). Runs after release-dashboard so the rewritten
- # `^x.y.z` pins always reference versions that exist on npm. Requires the
- # DASHBOARD_STARTER_SYNC_TOKEN secret: a fine-grained PAT with contents
- # write on spree/dashboard-starter.
- sync-dashboard-starter:
- name: "dashboard-starter - Sync template repo"
- needs: release-dashboard
- if: github.repository == 'spree/spree' && github.ref == 'refs/heads/main' && github.event_name == 'push'
- runs-on: ubuntu-latest
- permissions:
- contents: read
- steps:
- - uses: actions/checkout@v4
-
- - uses: actions/setup-node@v4
- with:
- node-version: 22
-
- - name: Check sync token
- id: token
- env:
- SYNC_TOKEN: ${{ secrets.DASHBOARD_STARTER_SYNC_TOKEN }}
- run: |
- if [ -z "$SYNC_TOKEN" ]; then
- echo "DASHBOARD_STARTER_SYNC_TOKEN is not configured — skipping sync."
- echo "present=false" >> $GITHUB_OUTPUT
- else
- echo "present=true" >> $GITHUB_OUTPUT
- fi
-
- - name: Clone template repo
- if: steps.token.outputs.present == 'true'
- env:
- SYNC_TOKEN: ${{ secrets.DASHBOARD_STARTER_SYNC_TOKEN }}
- run: git clone "https://x-access-token:${SYNC_TOKEN}@github.com/spree/dashboard-starter.git" /tmp/dashboard-starter
-
- - name: Sync starter into the template working tree
- if: steps.token.outputs.present == 'true'
- run: node scripts/sync-dashboard-starter.mjs /tmp/dashboard-starter
-
- - name: Commit and push
- if: steps.token.outputs.present == 'true'
- working-directory: /tmp/dashboard-starter
- run: |
- git config user.name "spree-releases"
- git config user.email "[email protected]"
- git add -A
- if git diff --cached --quiet; then
- echo "Template repo already up to date."
- exit 0
- fi
- git commit -m "Sync from spree/spree@${{ github.sha }}"
- git push origin HEAD:main
+ # The dashboard-starter template is NOT distributed via a template repo:
+ # `@spree/cli` and `create-spree-app` embed it at build time
+ # (scripts/sync-dashboard-starter.mjs renders packages/dashboard-starter
+ # with published version pins into their templates/ dir), so the template
+ # and the released package versions are in lockstep by construction.
release-create-spree-app:
name: "create-spree-app - Release"
diff --git a/.gitignore b/.gitignore
index 038d485b18..8bde16c029 100644
--- a/.gitignore
+++ b/.gitignore
@@ -60,6 +60,9 @@ packages/*/package-lock.json
.turbo
.tanstack
packages/*/dist
+# Build-time-generated dashboard-starter template embed (see
+# scripts/sync-dashboard-starter.mjs)
+packages/cli/templates/dashboard-starter
.claude/worktrees
*.tsbuildinfo
.claude/scheduled_tasks.lock
diff --git a/CLAUDE.md b/CLAUDE.md
index 3bfdb97c87..edee9f3211 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 (synced to the `spree/dashboard-starter` template repo on release), `spree add dashboard` + create-spree-app dashboard phase (env carries only `VITE_SPREE_API_URL` — never secret keys), npm release job for `@spree/dashboard{,-ui,-core}` (0.x → `next` tag) + template sync job. Pending: layout rename + `detectApiDir` dual-layout CLI, `spree upgrade layout`.
+- `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_SPREE_API_URL` — never secret keys), 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/developer/dashboard/customization/quickstart.mdx b/docs/developer/dashboard/customization/quickstart.mdx
index 40d1fd0c9f..57f3cbfc56 100644
--- a/docs/developer/dashboard/customization/quickstart.mdx
+++ b/docs/developer/dashboard/customization/quickstart.mdx
@@ -7,7 +7,7 @@ description: Add your first customization to the Spree dashboard in under 5 minu
This guide assumes two things are running:
1. A Spree API server (your Spree store's backend).
-2. Your dashboard app — the small Vite project that renders the admin. In a `create-spree-app` project it lives at `apps/dashboard/` (add it to an existing project with `npx spree add dashboard`); it can also be a standalone clone of the [dashboard starter](https://github.com/spree/dashboard-starter). Start it with `pnpm dev`.
+2. Your dashboard app — the small Vite project that renders the admin. In a `create-spree-app` project it lives at `apps/dashboard/`; add it to an existing project with `npx spree add dashboard`, or scaffold it anywhere with `npx spree add dashboard --template` pointing at your own copy. Start it with `pnpm dev`.
All customizations in this guide are edits to your dashboard app's own code. **You don't need to scaffold a plugin** — plugins are for [distributing features to other stores](/developer/dashboard/plugins/overview).
diff --git a/docs/plans/5.6-project-layout-and-dashboard.md b/docs/plans/5.6-project-layout-and-dashboard.md
index c9bb308b43..db443e9639 100644
--- a/docs/plans/5.6-project-layout-and-dashboard.md
+++ b/docs/plans/5.6-project-layout-and-dashboard.md
@@ -16,7 +16,7 @@ Ship the React dashboard as part of `create-spree-app` in 5.6 (Developer Preview
2. **The 5.4 plan reserved `apps/admin/` for the future dashboard.** That name collides with the legacy Rails `spree/admin` engine and with `@spree/dashboard`, the package name used everywhere else in the monorepo. We should land on one name and use it consistently.
-3. **No way to add the dashboard after the fact.** A user who skipped the dashboard at scaffolding time (or generated their project before the dashboard existed) has no command to bolt it on. They have to clone `spree/dashboard-starter` manually, mint API keys, write `.env.local`, and install deps — none of which is hard, but it's exactly the kind of glue `create-spree-app` already automates for the storefront.
+3. **No way to add the dashboard after the fact.** A user who skipped the dashboard at scaffolding time (or generated their project before the dashboard existed) has no command to bolt it on. They have to hand-assemble the dashboard app — copy a starter, write `.env.local`, install deps — none of which is hard, but it's exactly the kind of glue `create-spree-app` already automates for the storefront.
4. **No upgrade path for existing 5.4 projects.** Anyone who generated a project with 5.4's `create-spree-app` has `backend/` baked into Dockerfiles, CI configs, and shell habits. Without a migration command, every user has to do the rename by hand when they want to align with the new layout.
@@ -27,7 +27,7 @@ Ship the React dashboard as part of `create-spree-app` in 5.6 (Developer Preview
- **`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.
- **`@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.
-- **Dashboard ships from a `spree/dashboard-starter` GitHub template repo** (same pattern as `spree-starter`), but the **canonical source lives in the monorepo at `packages/dashboard-starter`**. The template repo is a build artifact: a release job copies the package, rewrites `workspace:^` to the published `^5.6.0-next` versions, and strips monorepo-only devDependencies (the example plugin). 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 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.
- **Rename ships day-one in 5.6 for *new* projects.** `npx create-spree-app` on 5.6+ produces `api/` directly. We don't ship 5.6 with the dashboard inside `backend/` only to rename in 6.0 — that'd give the Developer Preview audience a layout we know will change. Get it right once.
- **Existing projects are NOT auto-migrated in 5.6.** They keep `backend/` and continue to work. The CLI detects the layout per-command (see `detectApiDir` in Design Details). Users opt in to the rename via `spree upgrade layout` on their own schedule.
@@ -126,9 +126,9 @@ export function detectProject(cwd: string = process.cwd()): ProjectContext {
- **6.0 RC:** `spree dev` (and other commands) print a deprecation warning when `backend/` is detected, pointing to `spree upgrade layout`.
- **6.0 GA:** `detectApiDir` drops the `backend/` branch. Old-layout projects must run `spree upgrade layout` before any CLI command works.
-### Dashboard starter (`packages/dashboard-starter` → `spree/dashboard-starter`)
+### Dashboard starter (`packages/dashboard-starter`, embedded at build time)
-Canonical source in the monorepo at `packages/dashboard-starter`; a release job syncs it to the `spree/dashboard-starter` GitHub template repo (rewriting `workspace:^` deps to published versions and stripping monorepo-only devDependencies). `create-spree-app` and `spree add dashboard` clone the template repo:
+Canonical source in the monorepo at `packages/dashboard-starter` (doubles as the plugin pipeline's CI consumer test). Distribution is **Vendure-style npm embedding, not a template repo**: at build time, `@spree/cli` runs `scripts/sync-dashboard-starter.mjs` to render a standalone copy into its `templates/dashboard-starter/` (gitignored, shipped in the tarball via the dist copy) — rewriting `workspace:^` deps to the published versions, stripping monorepo-only devDependencies, inlining the workspace `biome.json`, and shipping `.gitignore` as `gitignore.template` (npm never packs `.gitignore`; the scaffolder renames it back). `prepublishOnly` rebuilds on publish, so the template's version pins are in lockstep with every CLI release by construction — no repo to drift, no sync token, no 404 window. The CLI is the **single template source**: `create-spree-app` doesn't embed a copy — its dashboard phase delegates to the project-local `npx spree add dashboard` (the generated project already depends on `@spree/cli`, installed with root deps before the phase runs, and the command reads the API port from the project `.env`). Decision informed by a Medusa/Vendure comparison: Vendure embeds templates in `@vendure/create` and gets alignment for free; Medusa's separate starter repo needs a scheduled bot to stay current. A public `spree/dashboard-starter` template repo (for browsability / "Use this template") can be added at 6.0 GA — the sync script takes any target directory, so it would reuse this machinery verbatim. The scaffolded app:
```
dashboard-starter/
@@ -209,7 +209,7 @@ Mirror file: `src/dashboard.ts` following `src/storefront.ts` shape exactly.
```typescript
// src/constants.ts
export const DASHBOARD_PORT = 5173
-export const DASHBOARD_REPO = 'https://github.com/spree/dashboard-starter.git'
+// (no DASHBOARD_REPO — the template is embedded in the package at build time)
// rename:
export const API_REPO = 'https://github.com/spree/spree-starter.git' // was BACKEND_REPO
```
@@ -447,9 +447,9 @@ New projects scaffold straight to `api/`. There is **no dual-layout output mode*
- No structural changes needed — it's the contents of `api/`, not the directory name.
- README references to "the backend" → "the API server" or just "this app".
-**`packages/dashboard-starter` (new package) + `spree/dashboard-starter` (new repo):**
+**`packages/dashboard-starter` (new package, embedded at build time):**
- Canonical source in the monorepo, following the shape above, with `workspace:^` deps.
-- Release sync job copies to the template repo, pinning `@spree/dashboard@^5.6.0-next` and `@spree/admin-sdk@^5.6.0-next` (Developer Preview dist-tag), rolling forward to `^6.0.0` at 6.0 GA.
+- Rendered standalone into the `@spree/cli` tarball at build time (pins stamped from the versions being released); `create-spree-app` delegates to the project-local CLI. No separate repo; a public template repo remains an option at 6.0 GA.
## Migration Path
@@ -470,13 +470,13 @@ All phases ship in **5.6**. The dashboard ships as Developer Preview alongside `
3. Add an `exports` map to `package.json` (`.` → shell export, `./styles.css`).
4. Teach `spreeDashboardPlugin()` to scan `@spree/dashboard` for Tailwind classes when installed (optional resolution — silent for custom dashboards without the shell).
-### Phase 3: Create `packages/dashboard-starter` *(implemented, incl. sync job)*
+### Phase 3: Create `packages/dashboard-starter` *(implemented, incl. build-time embedding)*
1. Scaffold the thin host in the monorepo per the shape above, with `workspace:^` deps. It compiles `<Dashboard />` from source and (dev-only) activates `@spree/dashboard-plugin-example` through auto-discovery — the standing consumer test for the plugin pipeline.
2. Write minimal Vite config that proxies to `localhost:3000` in dev. The proxy path is irrelevant to the Rails directory name — it's an HTTP URL.
3. Write README covering: dev workflow, installing plugins, `plugins.ts` customizations, deploying.
-4. Add the release sync job *(implemented — `sync-dashboard-starter` in `packages.yml` + `scripts/sync-dashboard-starter.mjs`; runs after the npm release job so version pins always resolve; also inlines the workspace `biome.json`)*. Manual one-time setup: create the `spree/dashboard-starter` repo, mark it as a GitHub template, and add the `DASHBOARD_STARTER_SYNC_TOKEN` secret (fine-grained PAT, contents write). Note: the first npm publish of `@spree/dashboard{,-ui,-core}` must be manual (Trusted Publishing can only be configured once a package exists).
-5. Add CI on the template repo: typecheck, build, e2e smoke test against a Dockerized Spree backend.
+4. Embed the rendered template in the `@spree/cli` tarball at build time *(implemented — `scripts/sync-dashboard-starter.mjs` runs in the CLI's build script; `prepublishOnly` guarantees fresh pins at publish; `.gitignore` ships as `gitignore.template` because npm never packs `.gitignore` files, and the scaffolder renames it back)*. `create-spree-app` carries no copy — its dashboard phase runs the project-local `npx spree add dashboard`, keeping the CLI the single template source. This superseded the earlier template-repo + CI-sync-job design after comparing Medusa (separate starter repo kept current by a scheduled bot) and Vendure (templates embedded in `@vendure/create`, lockstep for free). Remaining manual step for the preview: the first npm publish of `@spree/dashboard{,-ui,-core}` (Trusted Publishing can only be configured once a package exists).
+5. *(Deferred to 6.0 GA, optional)* Public `spree/dashboard-starter` template repo for browsability — reuse the same script with the repo as a second target, plus CI on that repo.
### Phase 4: Rename `backend/` → `api/` in create-spree-app (new projects only)
@@ -564,4 +564,4 @@ Manual QA checklist:
- Current `packages/cli/src/commands/eject.ts` — pattern for new commands; needs `ctx.apiDir` refactor.
- Current `packages/cli/src/context.ts` — extended with `detectApiDir` and `apiDir` field on `ProjectContext`.
- `spree/spree-starter` repo — existing template, no structural change needed.
-- **New repo to create:** `spree/dashboard-starter` — GitHub template for `apps/dashboard/` contents.
+- No new repos: the dashboard template is embedded in the `@spree/cli` / `create-spree-app` tarballs (an optional public `spree/dashboard-starter` template repo is deferred to 6.0 GA).
diff --git a/packages/cli/.changeset/add-dashboard-and-plugin-scaffold.md b/packages/cli/.changeset/add-dashboard-and-plugin-scaffold.md
index 910d12f43a..e41267a687 100644
--- a/packages/cli/.changeset/add-dashboard-and-plugin-scaffold.md
+++ b/packages/cli/.changeset/add-dashboard-and-plugin-scaffold.md
@@ -2,9 +2,10 @@
'@spree/cli': minor
---
-Add `spree add dashboard` — clones the React Dashboard starter (Developer
-Preview) into `apps/dashboard/` of an existing project and points it at the
-project's API. Also make `spree plugin new` fully non-interactive: every prompt
-has a flag (`--ruby-name`, `--module-name`, `--npm-scope`, `--author`,
-`--author-email`, `--license`, `-y`), with author details defaulting from git
-config.
+Add `spree add dashboard` — scaffolds the React Dashboard starter (Developer
+Preview), bundled inside the CLI with version pins matching the release, into
+`apps/dashboard/` of an existing project and points it at the project's API
+(`--template <path|git-url>` overrides the bundled copy). Also make
+`spree plugin new` fully non-interactive: every prompt has a flag
+(`--ruby-name`, `--module-name`, `--npm-scope`, `--author`, `--author-email`,
+`--license`, `-y`), with author details defaulting from git config.
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 03823e68ad..8230f65c29 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -12,7 +12,7 @@
"LICENSE"
],
"scripts": {
- "build": "node scripts/bundle-spec.mjs && tsup",
+ "build": "node scripts/bundle-spec.mjs && node ../../scripts/sync-dashboard-starter.mjs templates/dashboard-starter && tsup",
"dev": "tsup --watch",
"test": "vitest run",
"typecheck": "tsc --noEmit",
diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts
index 40a877bffe..73f9d4d45a 100644
--- a/packages/cli/src/commands/add.ts
+++ b/packages/cli/src/commands/add.ts
@@ -1,10 +1,11 @@
import fs from 'node:fs'
import path from 'node:path'
+import { fileURLToPath } from 'node:url'
import * as p from '@clack/prompts'
import type { Command } from 'commander'
import { execa } from 'execa'
import pc from 'picocolors'
-import { DASHBOARD_PORT, DASHBOARD_REPO } from '../constants.js'
+import { DASHBOARD_PORT } from '../constants.js'
import { detectProject } from '../context.js'
import type { ProjectContext } from '../types.js'
@@ -25,7 +26,7 @@ export function registerAddCommand(program: Command) {
.argument('<thing>', 'Component to add (currently: dashboard)')
.option(
'--template <src>',
- 'Starter template: git URL or local path (default: the spree/dashboard-starter repo; env SPREE_DASHBOARD_TEMPLATE overrides)',
+ '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 }) => {
@@ -37,7 +38,8 @@ export function registerAddCommand(program: Command) {
p.intro(pc.bgCyan(pc.black(' Spree Dashboard ')))
const ctx = detectProject()
await addDashboard(ctx, {
- template: flags.template ?? process.env.SPREE_DASHBOARD_TEMPLATE ?? DASHBOARD_REPO,
+ template:
+ flags.template ?? process.env.SPREE_DASHBOARD_TEMPLATE ?? resolveBundledTemplate(),
install: flags.install,
})
p.outro('Done!')
@@ -73,6 +75,7 @@ export async function addDashboard(ctx: ProjectContext, opts: AddDashboardOption
s.start('Fetching dashboard starter...')
try {
await fetchTemplate(opts.template, dashboardDir)
+ restoreGitignore(dashboardDir)
} catch (err) {
s.stop('Fetch failed.')
p.log.error(err instanceof Error ? err.message : String(err))
@@ -106,6 +109,43 @@ export async function addDashboard(ctx: ProjectContext, opts: AddDashboardOption
)
}
+/**
+ * The dashboard-starter template bundled inside this package. Generated at
+ * build time from the monorepo's `packages/dashboard-starter` (workspace
+ * deps rewritten to the published versions — see
+ * `scripts/sync-dashboard-starter.mjs`) and shipped in `dist/templates/`.
+ * Bundling it with the CLI keeps the template and the `@spree/dashboard*`
+ * versions it pins in lockstep with every release — there is no separate
+ * template repo to drift.
+ */
+function resolveBundledTemplate(): string {
+ const here = path.dirname(fileURLToPath(import.meta.url))
+ // dev: src/commands/add.ts → ../../templates/dashboard-starter
+ // built: dist/index.js → dist/templates/dashboard-starter
+ const candidates = [
+ path.resolve(here, '../../templates/dashboard-starter'),
+ path.resolve(here, 'templates/dashboard-starter'),
+ ]
+ for (const candidate of candidates) {
+ if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate
+ }
+ console.error(
+ `\n${pc.red('Error:')} Bundled dashboard template not found. In the monorepo, ` +
+ `run ${pc.cyan('pnpm build')} in packages/cli first (it generates the template), ` +
+ 'or pass --template <path|git-url>.\n',
+ )
+ process.exit(1)
+}
+
+/**
+ * The bundled template ships its `.gitignore` as `gitignore.template`
+ * (npm never packs `.gitignore` files) — restore the real name on scaffold.
+ */
+function restoreGitignore(dir: string): void {
+ const template = path.join(dir, 'gitignore.template')
+ if (fs.existsSync(template)) fs.renameSync(template, path.join(dir, '.gitignore'))
+}
+
/** Git-clone a URL template, or copy a local directory (used in tests/CI). */
async function fetchTemplate(template: string, dst: string): Promise<void> {
if (fs.existsSync(template) && fs.statSync(template).isDirectory()) {
diff --git a/packages/cli/src/constants.ts b/packages/cli/src/constants.ts
index f399d444d7..53a9c32d26 100644
--- a/packages/cli/src/constants.ts
+++ b/packages/cli/src/constants.ts
@@ -2,7 +2,3 @@ export const DEFAULT_ADMIN_EMAIL = '[email protected]'
export const DEFAULT_ADMIN_PASSWORD = 'spree123'
export const DEFAULT_SPREE_PORT = 3000
export const DASHBOARD_PORT = 5173
-// Template repo cloned by `spree add dashboard`. Canonical source lives at
-// packages/dashboard-starter in the spree/spree monorepo; a release job syncs
-// it out with published package versions.
-export const DASHBOARD_REPO = 'https://github.com/spree/dashboard-starter.git'
diff --git a/packages/cli/tests/add-dashboard.test.ts b/packages/cli/tests/add-dashboard.test.ts
index 7dec532405..64e968fd77 100644
--- a/packages/cli/tests/add-dashboard.test.ts
+++ b/packages/cli/tests/add-dashboard.test.ts
@@ -26,6 +26,9 @@ describe('addDashboard', () => {
fs.writeFileSync(path.join(templateDir, 'package.json'), '{"name":"starter"}\n')
fs.mkdirSync(path.join(templateDir, 'src'))
fs.writeFileSync(path.join(templateDir, 'src', 'main.tsx'), '// entry\n')
+ // The bundled template ships its .gitignore under this name (npm never
+ // packs .gitignore files) — the scaffolder must restore the real name.
+ fs.writeFileSync(path.join(templateDir, 'gitignore.template'), 'node_modules/\n')
// Junk that must not be copied into the project
fs.mkdirSync(path.join(templateDir, 'node_modules', 'leftover'), { recursive: true })
fs.mkdirSync(path.join(templateDir, 'dist'))
@@ -49,6 +52,10 @@ describe('addDashboard', () => {
const env = fs.readFileSync(path.join(dashboardDir, '.env.local'), 'utf-8')
expect(env).toContain('VITE_SPREE_API_URL=http://localhost:3999')
expect(env).not.toMatch(/sk_/)
+
+ // gitignore.template restored to its real name
+ expect(fs.existsSync(path.join(dashboardDir, '.gitignore'))).toBe(true)
+ expect(fs.existsSync(path.join(dashboardDir, 'gitignore.template'))).toBe(false)
})
it('is a no-op when apps/dashboard already exists', async () => {
diff --git a/packages/create-spree-app/.changeset/dashboard-scaffold-phase.md b/packages/create-spree-app/.changeset/dashboard-scaffold-phase.md
index 377c2dbfe5..0ea1d6eaa4 100644
--- a/packages/create-spree-app/.changeset/dashboard-scaffold-phase.md
+++ b/packages/create-spree-app/.changeset/dashboard-scaffold-phase.md
@@ -3,6 +3,7 @@
---
Offer the React Dashboard (Developer Preview) as an optional component: a new
-prompt (and `--no-dashboard` flag) clones the dashboard starter into
-`apps/dashboard/`, writes its `.env.local` (API URL only — never credentials),
-installs dependencies, and wires the README, CLAUDE.md, and Dependabot config.
+prompt (and `--no-dashboard` flag) scaffolds it into `apps/dashboard/` by
+delegating to the project-local `npx spree add dashboard` (the CLI bundles the
+starter template with version pins matching its release), and wires the
+README, CLAUDE.md, and Dependabot config.
diff --git a/packages/create-spree-app/src/constants.ts b/packages/create-spree-app/src/constants.ts
index 0ff8bc0796..2a3a1a8812 100644
--- a/packages/create-spree-app/src/constants.ts
+++ b/packages/create-spree-app/src/constants.ts
@@ -4,9 +4,6 @@ export const DASHBOARD_PORT = 5173
export const STOREFRONT_REPO = 'https://github.com/spree/storefront.git'
export const BACKEND_REPO = 'https://github.com/spree/spree-starter.git'
-// Canonical source lives at packages/dashboard-starter in the spree/spree
-// monorepo; a release job syncs it out with published package versions.
-export const DASHBOARD_REPO = 'https://github.com/spree/dashboard-starter.git'
export const DEFAULT_ADMIN_EMAIL = '[email protected]'
export const DEFAULT_ADMIN_PASSWORD = 'spree123'
diff --git a/packages/create-spree-app/src/dashboard.ts b/packages/create-spree-app/src/dashboard.ts
index ee211057b1..d1e9de80b3 100644
--- a/packages/create-spree-app/src/dashboard.ts
+++ b/packages/create-spree-app/src/dashboard.ts
@@ -1,26 +1,19 @@
-import fs from 'node:fs'
-import path from 'node:path'
import { execa } from 'execa'
-import { DASHBOARD_REPO } from './constants.js'
-import { dashboardEnvContent } from './templates/env.js'
-import type { PackageManager } from './types.js'
-import { installCommand } from './utils.js'
-export async function downloadDashboard(projectDir: string): Promise<void> {
- const dashboardDir = path.join(projectDir, 'apps', 'dashboard')
- await execa('git', ['clone', '--depth', '1', '--', DASHBOARD_REPO, dashboardDir], {
- stdio: 'ignore',
- })
- fs.rmSync(path.join(dashboardDir, '.git'), { recursive: true, force: true })
-}
-
-export async function installDashboardDeps(projectDir: string, pm: PackageManager): Promise<void> {
- const dashboardDir = path.join(projectDir, 'apps', 'dashboard')
- const [cmd, ...args] = installCommand(pm).split(' ')
- await execa(cmd, args, { cwd: dashboardDir, stdio: 'ignore' })
-}
-
-export function writeDashboardEnv(projectDir: string, port: number): void {
- const envPath = path.join(projectDir, 'apps', 'dashboard', '.env.local')
- fs.writeFileSync(envPath, dashboardEnvContent(port))
+/**
+ * Scaffold the React Dashboard into `apps/dashboard/` by delegating to the
+ * project-local CLI: `npx spree add dashboard`. The generated project already
+ * depends on `@spree/cli` (installed with the root deps, before this phase),
+ * and the CLI bundles the dashboard-starter template with version pins
+ * matching its release — one template source, no copy in this package. The
+ * command reads the API port from the project's `.env` and writes
+ * `apps/dashboard/.env.local` itself (API URL only — never credentials).
+ */
+export async function scaffoldDashboard(
+ projectDir: string,
+ opts: { install: boolean },
+): Promise<void> {
+ const args = ['spree', 'add', 'dashboard']
+ if (!opts.install) args.push('--no-install')
+ await execa('npx', args, { cwd: projectDir, stdio: 'inherit' })
}
diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.ts
index 7c3c3c9f6a..7174a334a3 100644
--- a/packages/create-spree-app/src/scaffold.ts
+++ b/packages/create-spree-app/src/scaffold.ts
@@ -5,7 +5,7 @@ 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 { downloadDashboard, installDashboardDeps, writeDashboardEnv } from './dashboard.js'
+import { scaffoldDashboard } from './dashboard.js'
import {
downloadStorefront,
installRootDeps,
@@ -112,17 +112,12 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {
s.stop('Storefront dependencies installed.')
}
- // Phase 3b: React Dashboard (optional, Developer Preview)
+ // 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.
if (dashboard) {
- s.start('Downloading dashboard starter...')
- await downloadDashboard(projectDir)
- s.stop('Dashboard starter downloaded.')
-
- writeDashboardEnv(projectDir, port)
-
- s.start('Installing dashboard dependencies...')
- await installDashboardDeps(projectDir, options.packageManager)
- s.stop('Dashboard dependencies installed.')
+ await scaffoldDashboard(projectDir, { install: true })
}
// Phase 4: Initialize and start services
diff --git a/packages/create-spree-app/src/templates/env.ts b/packages/create-spree-app/src/templates/env.ts
index ded88322b0..c470cf5ca1 100644
--- a/packages/create-spree-app/src/templates/env.ts
+++ b/packages/create-spree-app/src/templates/env.ts
@@ -10,10 +10,3 @@ export function storefrontEnvContent(port: number, apiKey?: string): string {
SPREE_PUBLISHABLE_KEY=${apiKey ?? 'pk_REPLACE_ME_AFTER_DOCKER_START'}
`
}
-
-export function dashboardEnvContent(port: number): string {
- return `# URL of your Spree API server. No credentials belong in this file —
-# every VITE_-prefixed value is compiled into the client bundle.
-VITE_SPREE_API_URL=http://localhost:${port}
-`
-}
diff --git a/packages/create-spree-app/tests/scaffold.test.ts b/packages/create-spree-app/tests/scaffold.test.ts
index 4a6e153c82..352298be16 100644
--- a/packages/create-spree-app/tests/scaffold.test.ts
+++ b/packages/create-spree-app/tests/scaffold.test.ts
@@ -69,18 +69,12 @@ vi.mock('../src/storefront', async (importOriginal) => {
}
})
-vi.mock('../src/dashboard', async (importOriginal) => {
- const mod = await importOriginal<typeof import('../src/dashboard')>()
- return {
- ...mod,
- // Simulate the clone so the real writeDashboardEnv has a directory to
- // write into.
- downloadDashboard: vi.fn(async (projectDir: string) => {
- fs.mkdirSync(path.join(projectDir, 'apps', 'dashboard'), { recursive: true })
- }),
- installDashboardDeps: vi.fn(),
- }
-})
+vi.mock('../src/dashboard', () => ({
+ // The real implementation shells out to the project-local
+ // `npx spree add dashboard` — its behavior is covered by @spree/cli's own
+ // tests. Here we only assert the delegation happens (or doesn't).
+ scaffoldDashboard: vi.fn(),
+}))
vi.mock('../src/backend', () => ({
downloadBackend: vi.fn(async (projectDir: string) => {
@@ -227,7 +221,8 @@ describe('scaffold (no-start)', () => {
expect(pkg.scripts.eject).toBe('spree eject')
})
- it('writes the dashboard env when the dashboard is included', async () => {
+ it('delegates dashboard scaffolding to the project-local CLI when included', async () => {
+ const { scaffoldDashboard } = await import('../src/dashboard')
const projectDir = getTempProjectDir()
await scaffold({
@@ -240,15 +235,15 @@ describe('scaffold (no-start)', () => {
port: 4567,
})
- const envPath = path.join(projectDir, 'apps', 'dashboard', '.env.local')
- const env = fs.readFileSync(envPath, 'utf-8')
- expect(env).toContain('VITE_SPREE_API_URL=http://localhost:4567')
+ expect(scaffoldDashboard).toHaveBeenCalledWith(projectDir, { install: true })
expect(fs.readFileSync(path.join(projectDir, 'README.md'), 'utf-8')).toContain(
'React Dashboard',
)
})
- it('skips the dashboard by default', async () => {
+ it('skips the dashboard when not included', async () => {
+ const { scaffoldDashboard } = await import('../src/dashboard')
+ vi.mocked(scaffoldDashboard).mockClear()
const projectDir = getTempProjectDir()
await scaffold({
@@ -261,7 +256,7 @@ describe('scaffold (no-start)', () => {
port: 3000,
})
- expect(fs.existsSync(path.join(projectDir, 'apps', 'dashboard'))).toBe(false)
+ expect(scaffoldDashboard).not.toHaveBeenCalled()
expect(fs.readFileSync(path.join(projectDir, 'README.md'), 'utf-8')).not.toContain(
'React Dashboard',
)
diff --git a/packages/create-spree-app/tests/templates.test.ts b/packages/create-spree-app/tests/templates.test.ts
index de3a37b036..c6072f3cf2 100644
--- a/packages/create-spree-app/tests/templates.test.ts
+++ b/packages/create-spree-app/tests/templates.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { rootClaudeMdContent } from '../src/templates/claude-md'
import { dependabotContent } from '../src/templates/dependabot'
-import { dashboardEnvContent, envContent, storefrontEnvContent } from '../src/templates/env'
+import { envContent, storefrontEnvContent } from '../src/templates/env'
import { gitignoreContent } from '../src/templates/gitignore'
import { rootPackageJsonContent } from '../src/templates/package-json'
import { readmeContent } from '../src/templates/readme'
@@ -45,17 +45,6 @@ describe('storefrontEnvContent', () => {
})
})
-describe('dashboardEnvContent', () => {
- it('points VITE_SPREE_API_URL at the given port', () => {
- expect(dashboardEnvContent(4567)).toContain('VITE_SPREE_API_URL=http://localhost:4567')
- })
-
- it('contains no credentials — VITE_ values ship to every browser', () => {
- const content = dashboardEnvContent(3000)
- expect(content).not.toMatch(/pk_|sk_|KEY=(?!http)/)
- })
-})
-
describe('rootPackageJsonContent', () => {
it('returns valid JSON', () => {
const content = rootPackageJsonContent('my-store')
diff --git a/packages/dashboard-starter/README.md b/packages/dashboard-starter/README.md
index 2819f33c80..578edc0aae 100644
--- a/packages/dashboard-starter/README.md
+++ b/packages/dashboard-starter/README.md
@@ -2,7 +2,7 @@
The host app for the [Spree React Dashboard](https://spreecommerce.org/docs/developer/dashboard/overview) — the admin for your Spree store. `@spree/dashboard` is the actual app shell (routes, chrome, resource pages); this project is your customization point: plugins, your own pages, theming, and deployment config.
-> **Monorepo note.** The canonical source of this template lives at `packages/dashboard-starter` in [spree/spree](https://github.com/spree/spree), where its Spree dependencies resolve via the pnpm workspace and `@spree/dashboard-plugin-example` is installed as a devDependency — booting it here doubles as the end-to-end test for the plugin pipeline. A release job syncs it to the `spree/dashboard-starter` template repo with published package versions, which is what `create-spree-app` and `spree add dashboard` clone.
+> **Monorepo note.** The canonical source of this template lives at `packages/dashboard-starter` in [spree/spree](https://github.com/spree/spree), where its Spree dependencies resolve via the pnpm workspace and `@spree/dashboard-plugin-example` is installed as a devDependency — booting it here doubles as the end-to-end test for the plugin pipeline. At build time, `@spree/cli` and `create-spree-app` embed a standalone rendering of it (workspace deps rewritten to the published versions — see `scripts/sync-dashboard-starter.mjs`), which is what `spree add dashboard` and the create-spree-app dashboard prompt scaffold from.
## Develop
diff --git a/scripts/sync-dashboard-starter.mjs b/scripts/sync-dashboard-starter.mjs
index 17e575695d..b3cfb92561 100644
--- a/scripts/sync-dashboard-starter.mjs
+++ b/scripts/sync-dashboard-starter.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
-// Sync packages/dashboard-starter (the monorepo-canonical source) into a
-// working clone of the spree/dashboard-starter template repo, rewriting the
-// bits that only make sense inside the monorepo:
+// Render packages/dashboard-starter (the monorepo-canonical source, which
+// doubles as the plugin pipeline's CI consumer test) into a standalone
+// template, rewriting the bits that only make sense inside the monorepo:
//
// - `workspace:^` dependency ranges → `^<version>` of the published packages
// - monorepo-only devDependencies dropped (the example plugin isn't on npm)
@@ -11,6 +11,13 @@
// Everything else copies verbatim, including src/routeTree.gen.ts (committed
// by design — its diff on upgrade shows which admin pages changed).
//
+// Runs at build time in @spree/cli and create-spree-app, targeting their
+// `templates/dashboard-starter/` (gitignored; shipped inside the tarball via
+// the dist copy). `prepublishOnly` rebuilds on publish, so the version pins
+// are always stamped from the versions being released — Vendure-style
+// lockstep, no template repo to keep in sync. (A public template repo can
+// reuse this script as a second target later.)
+//
// Usage: node scripts/sync-dashboard-starter.mjs <target-dir>
import fs from 'node:fs'
import path from 'node:path'
@@ -25,10 +32,7 @@ if (!target) {
process.exit(2)
}
const targetDir = path.resolve(target)
-if (!fs.existsSync(targetDir)) {
- console.error(`Target directory does not exist: ${targetDir}`)
- process.exit(2)
-}
+fs.mkdirSync(targetDir, { recursive: true })
const EXCLUDE = new Set(['node_modules', 'dist', '.turbo', '.tanstack'])
const MONOREPO_ONLY_DEV_DEPS = new Set(['@spree/dashboard-plugin-example'])
@@ -45,6 +49,13 @@ fs.cpSync(starterDir, targetDir, {
filter: (src) => !EXCLUDE.has(path.basename(src)),
})
+// npm never packs `.gitignore` files (at any depth), so an embedded template
+// would silently lose it and scaffolded apps would commit node_modules. Ship
+// it as `gitignore.template`; the scaffolders rename it back after copying.
+if (fs.existsSync(path.join(targetDir, '.gitignore'))) {
+ fs.renameSync(path.join(targetDir, '.gitignore'), path.join(targetDir, 'gitignore.template'))
+}
+
// --- package.json: pin published versions -----------------------------------
function publishedRange(name) {