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.

Add spree add dashboard command

Damian Legawiecccded5cbc9c6
diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts
new file mode 100644
index 0000000000..6c78e58af5
--- /dev/null
+++ b/packages/cli/src/commands/add.ts
@@ -0,0 +1,146 @@
+import fs from 'node:fs'
+import path from 'node:path'
+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 { detectProject } from '../context.js'
+import type { ProjectContext } from '../types.js'
+
+interface AddDashboardOptions {
+ /** Git URL or local directory to copy the starter from. */
+ template: string
+ /** Run the package-manager install after scaffolding. */
+ install: boolean
+}
+
+// `spree add <thing>` — bolt an optional component onto an existing project.
+// Dashboard only for now; storefront parity is planned (see
+// docs/plans/5.6-project-layout-and-dashboard.md).
+export function registerAddCommand(program: Command) {
+ program
+ .command('add')
+ .description('Add an optional component to your project')
+ .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)',
+ )
+ .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)
+ }
+
+ p.intro(pc.bgCyan(pc.black(' Spree Dashboard ')))
+ const ctx = detectProject()
+ await addDashboard(ctx, {
+ template: flags.template ?? process.env.SPREE_DASHBOARD_TEMPLATE ?? DASHBOARD_REPO,
+ install: flags.install,
+ })
+ p.outro('Done!')
+ })
+}
+
+/**
+ * Clone the dashboard starter into `apps/dashboard/` and point it at the
+ * project's API. Writes no credentials — the dashboard authenticates admins
+ * interactively (email/password → JWT + refresh cookie), and `VITE_`-prefixed
+ * env values are compiled into the client bundle, so a key here would ship
+ * to every browser.
+ *
+ * Idempotent: an existing `apps/dashboard/` is left untouched (recovery mode
+ * rewrites a missing `.env.local` only).
+ */
+export async function addDashboard(ctx: ProjectContext, opts: AddDashboardOptions): Promise<void> {
+ const dashboardDir = path.join(ctx.projectDir, 'apps', 'dashboard')
+ const envPath = path.join(dashboardDir, '.env.local')
+
+ if (fs.existsSync(dashboardDir)) {
+ if (fs.existsSync(envPath)) {
+ p.log.warn(`${pc.bold('apps/dashboard/')} already exists. Nothing to do.`)
+ return
+ }
+ // Recovery: directory present but env missing (interrupted earlier run).
+ writeDashboardEnv(envPath, ctx.port)
+ p.log.info(`Wrote missing ${pc.bold('apps/dashboard/.env.local')}. Nothing else to do.`)
+ return
+ }
+
+ const s = p.spinner()
+ s.start('Fetching dashboard starter...')
+ try {
+ await fetchTemplate(opts.template, dashboardDir)
+ } catch (err) {
+ s.stop('Fetch failed.')
+ p.log.error(err instanceof Error ? err.message : String(err))
+ process.exit(1)
+ }
+ s.stop(`Created ${pc.cyan('apps/dashboard/')}`)
+
+ writeDashboardEnv(envPath, ctx.port)
+
+ if (opts.install) {
+ const pm = detectPackageManager(ctx.projectDir, dashboardDir)
+ s.start(`Installing dependencies with ${pm}...`)
+ try {
+ await execa(pm, ['install'], { cwd: dashboardDir })
+ s.stop('Dependencies installed.')
+ } catch (err) {
+ s.stop(pc.yellow(`${pm} install failed — run it manually in apps/dashboard/.`))
+ p.log.warn(err instanceof Error ? err.message : String(err))
+ }
+ }
+
+ p.note(
+ [
+ `Start it with:`,
+ ` ${pc.cyan('cd apps/dashboard && ' + (opts.install ? '' : 'pnpm install && ') + 'pnpm dev')}`,
+ '',
+ `Then open ${pc.bold(`http://localhost:${DASHBOARD_PORT}`)} and sign in`,
+ `with your admin email and password.`,
+ ].join('\n'),
+ 'Dashboard added!',
+ )
+}
+
+/** 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()) {
+ fs.cpSync(template, dst, {
+ recursive: true,
+ filter: (src) => {
+ const base = path.basename(src)
+ return base !== 'node_modules' && base !== 'dist' && base !== '.git'
+ },
+ })
+ return
+ }
+
+ await execa('git', ['clone', '--depth', '1', template, dst])
+ fs.rmSync(path.join(dst, '.git'), { recursive: true, force: true })
+}
+
+function writeDashboardEnv(envPath: string, port: number): void {
+ fs.writeFileSync(
+ envPath,
+ [
+ '# 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}`,
+ '',
+ ].join('\n'),
+ )
+}
+
+/** Prefer the project's own package manager (by lockfile); default to pnpm. */
+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'
+ if (fs.existsSync(path.join(dir, 'package-lock.json'))) return 'npm'
+ }
+ return 'pnpm'
+}
diff --git a/packages/cli/src/constants.ts b/packages/cli/src/constants.ts
index 66b6c4f4e2..f399d444d7 100644
--- a/packages/cli/src/constants.ts
+++ b/packages/cli/src/constants.ts
@@ -1,3 +1,8 @@
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/src/index.ts b/packages/cli/src/index.ts
index 57e51580a3..b896131bdf 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -1,5 +1,6 @@
import { Command } from 'commander'
import pc from 'picocolors'
+import { registerAddCommand } from './commands/add.js'
import { registerApiCommand } from './commands/api.js'
import { registerApiKeyCommand } from './commands/api-key.js'
import { registerAuthCommand } from './commands/auth.js'
@@ -62,6 +63,7 @@ const program = new Command()
// Lifecycle / setup
registerInitCommand(program)
+registerAddCommand(program)
registerDevCommand(program)
registerStopCommand(program)
registerRestartCommand(program)
diff --git a/packages/cli/tests/add-dashboard.test.ts b/packages/cli/tests/add-dashboard.test.ts
new file mode 100644
index 0000000000..7dec532405
--- /dev/null
+++ b/packages/cli/tests/add-dashboard.test.ts
@@ -0,0 +1,71 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { addDashboard } from '../src/commands/add.js'
+import type { ProjectContext } from '../src/types.js'
+
+/**
+ * Exercises the local-directory template path (the same code `--template
+ * <path>` and SPREE_DASHBOARD_TEMPLATE hit). The git-clone path is the same
+ * function with a URL — covered by the smoke flow, not unit-testable offline.
+ */
+describe('addDashboard', () => {
+ let projectDir: string
+ let templateDir: string
+
+ function ctx(): ProjectContext {
+ return { mode: 'docker', projectDir, port: 3999 }
+ }
+
+ beforeEach(() => {
+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-add-project-'))
+ templateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-add-template-'))
+ fs.writeFileSync(path.join(projectDir, 'docker-compose.yml'), 'services: {}\n')
+
+ 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')
+ // 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'))
+ fs.writeFileSync(path.join(templateDir, 'dist', 'bundle.js'), '')
+ })
+
+ afterEach(() => {
+ fs.rmSync(projectDir, { recursive: true, force: true })
+ fs.rmSync(templateDir, { recursive: true, force: true })
+ })
+
+ it('copies the template into apps/dashboard and writes .env.local with the project port', async () => {
+ await addDashboard(ctx(), { template: templateDir, install: false })
+
+ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')
+ expect(fs.existsSync(path.join(dashboardDir, 'package.json'))).toBe(true)
+ expect(fs.existsSync(path.join(dashboardDir, 'src', 'main.tsx'))).toBe(true)
+ expect(fs.existsSync(path.join(dashboardDir, 'node_modules'))).toBe(false)
+ expect(fs.existsSync(path.join(dashboardDir, 'dist'))).toBe(false)
+
+ 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_/)
+ })
+
+ it('is a no-op when apps/dashboard already exists', async () => {
+ await addDashboard(ctx(), { template: templateDir, install: false })
+ const marker = path.join(projectDir, 'apps', 'dashboard', 'src', 'custom.ts')
+ fs.writeFileSync(marker, '// user file\n')
+
+ await addDashboard(ctx(), { template: templateDir, install: false })
+ expect(fs.existsSync(marker)).toBe(true)
+ })
+
+ it('recovers a missing .env.local without touching anything else', async () => {
+ await addDashboard(ctx(), { template: templateDir, install: false })
+ const envPath = path.join(projectDir, 'apps', 'dashboard', '.env.local')
+ fs.rmSync(envPath)
+
+ await addDashboard(ctx(), { template: templateDir, install: false })
+ expect(fs.readFileSync(envPath, 'utf-8')).toContain('http://localhost:3999')
+ })
+})