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
Add CLI tool to spin up new dashboard plugins
Damian Legawiec969a646f6d9a
diff --git a/biome.json b/biome.jsonindex ce9b2b4ca3..87492dcc4b 100644--- a/biome.json+++ b/biome.json@@ -56,7 +56,8 @@"!**/*.d.ts","!server/**","!spree/**",- "!docs/**"+ "!docs/**",+ "!packages/cli/templates/**"]}}diff --git a/docs/developer/customization/dashboard-plugins.mdx b/docs/developer/customization/dashboard-plugins.mdxindex e6fc0faae4..cc985ddde7 100644--- a/docs/developer/customization/dashboard-plugins.mdx+++ b/docs/developer/customization/dashboard-plugins.mdx@@ -18,10 +18,50 @@ A dashboard plugin is an npm package that extends the Spree admin without forkin- Register **their own resource tables** for use with `<ResourceTable>`- Contribute **translations** that merge into the framework's i18next namespace-A working reference implementation lives in [`packages/dashboard-plugin-example/`](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) in the Spree monorepo — a Brands plugin that exercises every extension point. This guide walks through its structure; copy the package shape for your own plugin.+A working reference implementation lives in [`packages/dashboard-plugin-example/`](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) in the Spree monorepo — a Brands plugin that exercises every extension point. The Spree CLI scaffolds the same shape for any new plugin.++## Quick start: scaffold with `@spree/cli`++```bash+npx @spree/cli plugin new brands+```++The CLI walks you through the prompts (plugin name, npm scope, author, license) and produces a monorepo with the dashboard plugin pre-wired. It picks the npm package name, peer dependencies, and `defineDashboardPlugin` skeleton based on your answers.++```bash+brands/+├── package.json # workspace root (e.g. "@acme/brands")+├── pnpm-workspace.yaml+├── README.md+├── LICENSE+└── packages/+ └── dashboard/ # the dashboard plugin (e.g. "@acme/brands-dashboard")+ ├── package.json+ ├── tsconfig.json+ ├── biome.json+ └── src/+ ├── index.tsx # entry — defineDashboardPlugin call+ ├── types.ts # TypeScript shapes for your records+ ├── client.ts # adminClient.request wrappers+ ├── routes/+ │ └── brands-list.tsx # custom route mounted at /$storeId/brands+ ├── slots/+ │ └── product-brands-card.tsx+ └── locales/+ └── en.json+```++Flags:+- `--no-dashboard` — skip the dashboard plugin half+- `--no-install` — don't run `pnpm install` after scaffolding+- `--force` — overwrite a non-empty destination directory++The CLI also reserves `--no-engine` for the upcoming Rails-engine scaffolding (the Ruby half that ships your Admin API endpoints). For now, generate the Ruby side with the existing [`spree-extension`](https://github.com/spree/spree_extension) gem alongside the CLI's dashboard output.## Anatomy of a plugin+If you're not using the CLI, the minimum layout is:+```my-spree-plugin/├── package.json # peer deps + versiondiff --git a/packages/cli/src/commands/plugin.ts b/packages/cli/src/commands/plugin.tsnew file mode 100644index 0000000000..f122393c9a--- /dev/null+++ b/packages/cli/src/commands/plugin.ts@@ -0,0 +1,347 @@+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 { execaCommand } from 'execa'+import pc from 'picocolors'+import { render, type TemplateVars } from '../lib/template.js'++const TEMPLATE_RELATIVE_PATH = '../../templates/plugin'++interface PluginNewFlags {+ dashboard: boolean+ engine: boolean+ install: boolean+ force: boolean+}++export function registerPluginCommand(program: Command): void {+ const plugin = program+ .command('plugin')+ .description('Scaffold and manage Spree plugins (dashboard + Rails engine)')++ plugin+ .command('new')+ .description(+ 'Scaffold a new Spree plugin monorepo (dashboard plugin half today; Rails engine coming soon)',+ )+ .argument('[name]', 'Plugin name (e.g. brands). If omitted, you will be prompted.')+ .option('--no-dashboard', 'Skip the dashboard plugin half')+ .option(+ '--no-engine',+ 'Skip the Rails engine half (currently always skipped — engine support coming soon)',+ )+ .option('--no-install', 'Skip running pnpm install')+ .option('--force', 'Overwrite a non-empty destination directory')+ .action(async (nameArg: string | undefined, flags: PluginNewFlags) => {+ p.intro(pc.bgCyan(pc.black(' Spree Plugin Scaffolder ')))++ const answers = await collectAnswers(nameArg, flags)+ if (p.isCancel(answers)) {+ p.cancel('Scaffolding cancelled.')+ process.exit(0)+ }++ const dst = path.resolve(process.cwd(), answers.name)+ if (fs.existsSync(dst) && fs.readdirSync(dst).length > 0 && !flags.force) {+ p.cancel(+ `Destination ${pc.bold(dst)} is not empty. Choose a different name or rerun with ${pc.cyan('--force')}.`,+ )+ process.exit(1)+ }++ const vars = buildVars(answers)+ const templateSrc = resolveTemplatePath()++ const s = p.spinner()+ s.start(`Scaffolding ${pc.cyan(answers.name)}...`)+ try {+ render({+ src: templateSrc,+ dst,+ vars,+ skip: buildSkipPredicate(answers),+ force: flags.force,+ })+ } catch (err) {+ s.stop('Scaffolding failed.')+ p.log.error(err instanceof Error ? err.message : String(err))+ process.exit(1)+ }+ s.stop(`Created ${pc.cyan(dst)}`)++ if (flags.install) {+ await runInstall(dst, answers)+ } else {+ p.log.info(pc.dim('Skipping dependency install — run them yourself when ready.'))+ }++ printNextSteps(answers, dst, flags.install)+ p.outro('Happy hacking!')+ })+}++// ---------------------------------------------------------------------------+// Prompts + flag parsing+// ---------------------------------------------------------------------------++interface Answers {+ name: string+ rubyName: string+ moduleName: string+ npmScope: string+ authorName: string+ authorEmail: string+ license: string+ includeDashboard: boolean+ includeEngine: boolean+}++async function collectAnswers(+ nameArg: string | undefined,+ flags: PluginNewFlags,+): Promise<Answers | symbol> {+ const name =+ nameArg ??+ (await p.text({+ message: 'Plugin name',+ placeholder: 'brands',+ validate: (value) => {+ if (!value) return 'Required'+ if (!/^[a-z][a-z0-9-]*$/.test(value)) {+ return 'Use lowercase letters, digits, and dashes (e.g. "brands" or "loyalty-points")'+ }+ return undefined+ },+ }))+ if (p.isCancel(name)) return name as symbol++ const rubyDefault = `spree_${(name as string).replace(/-/g, '_')}`+ const rubyName = await p.text({+ message: 'Ruby gem name',+ placeholder: rubyDefault,+ initialValue: rubyDefault,+ validate: (value) =>+ value && /^[a-z][a-z0-9_]*$/.test(value)+ ? undefined+ : 'Use lowercase letters, digits, and underscores (e.g. "spree_brands")',+ })+ if (p.isCancel(rubyName)) return rubyName as symbol++ const moduleDefault = pascalCase(rubyName as string)+ const moduleName = await p.text({+ message: 'Ruby module / TS namespace',+ placeholder: moduleDefault,+ initialValue: moduleDefault,+ validate: (value) =>+ value && /^[A-Z][A-Za-z0-9]*$/.test(value) ? undefined : 'PascalCase (e.g. "SpreeBrands")',+ })+ if (p.isCancel(moduleName)) return moduleName as symbol++ const npmScope = await p.text({+ message: 'npm scope (optional, leave blank for unscoped)',+ placeholder: '@my-org',+ initialValue: '',+ validate: (value) =>+ !value || /^@[a-z0-9][a-z0-9-]*$/.test(value)+ ? undefined+ : 'Must start with @ and contain lowercase letters/digits/dashes',+ })+ if (p.isCancel(npmScope)) return npmScope as symbol++ const authorName = await p.text({+ message: 'Author name',+ placeholder: 'Jane Developer',+ validate: (value) => (value ? undefined : 'Required'),+ })+ if (p.isCancel(authorName)) return authorName as symbol++ const authorEmail = await p.text({+ message: 'Author email',+ placeholder: '[email protected]',+ validate: (value) =>+ value && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value) ? undefined : 'Enter a valid email',+ })+ if (p.isCancel(authorEmail)) return authorEmail as symbol++ const license = await p.select({+ message: 'License',+ options: [+ { value: 'MIT', label: 'MIT' },+ { value: 'Apache-2.0', label: 'Apache-2.0' },+ { value: 'BSD-3-Clause', label: 'BSD-3-Clause' },+ ],+ initialValue: 'MIT',+ })+ if (p.isCancel(license)) return license as symbol++ // The `--no-dashboard` flag pre-answers this; otherwise prompt.+ const includeDashboard =+ flags.dashboard === false ? false : await prompt_confirm('Include dashboard plugin?', true)+ if (p.isCancel(includeDashboard)) return includeDashboard as symbol++ // The engine half is not yet generated by the CLI — the Rails templates+ // land in a follow-up PR. For now, we always answer false and note it.+ // Once the engine templates exist, restore the prompt:+ //+ // const includeEngine = flags.engine === false+ // ? false+ // : await prompt_confirm('Include Rails engine (API endpoints)?', true)+ const includeEngine = false+ if (flags.engine !== false) {+ p.log.warn(+ 'Rails engine generation is coming in a future release. For now, scaffold the dashboard half here and use `spree-extension create` for the Ruby side.',+ )+ }++ if (!includeDashboard && !includeEngine) {+ p.log.error('Nothing to scaffold (dashboard half declined).')+ return Symbol('cancel') as symbol+ }++ return {+ name: name as string,+ rubyName: rubyName as string,+ moduleName: moduleName as string,+ npmScope: (npmScope as string).trim(),+ authorName: authorName as string,+ authorEmail: authorEmail as string,+ license: license as string,+ includeDashboard: includeDashboard as boolean,+ includeEngine: includeEngine as boolean,+ }+}++async function prompt_confirm(message: string, initial: boolean): Promise<boolean | symbol> {+ const result = await p.confirm({ message, initialValue: initial })+ return result+}++// ---------------------------------------------------------------------------+// Template variable + skip-predicate builders+// ---------------------------------------------------------------------------++function buildVars(a: Answers): TemplateVars {+ const npmPackageName = a.npmScope ? `${a.npmScope}/${a.name}` : a.name+ return {+ name: a.name,+ plugin_name: a.name,+ ruby_name: a.rubyName,+ module_name: a.moduleName,+ npm_scope: a.npmScope,+ npm_package_name: npmPackageName,+ npm_dashboard_package: a.npmScope ? `${a.npmScope}/${a.name}-dashboard` : `${a.name}-dashboard`,+ author_name: a.authorName,+ author_email: a.authorEmail,+ license: a.license,+ year: String(new Date().getFullYear()),+ }+}++function buildSkipPredicate(a: Answers): (relPath: string) => boolean {+ const skipDashboard = !a.includeDashboard+ const skipEngine = !a.includeEngine+ return (rel) => {+ if (skipDashboard && (rel === 'packages/dashboard' || rel.startsWith('packages/dashboard/'))) {+ return true+ }+ if (skipEngine && (rel === 'engine' || rel.startsWith('engine/'))) return true+ return false+ }+}++// ---------------------------------------------------------------------------+// Post-scaffold install + banner+// ---------------------------------------------------------------------------++async function runInstall(dst: string, answers: Answers): Promise<void> {+ const s = p.spinner()+ if (answers.includeDashboard) {+ s.start('Running pnpm install...')+ try {+ await execaCommand('pnpm install', { cwd: dst, stdio: 'pipe' })+ s.stop('pnpm install complete.')+ } catch (err) {+ s.stop(pc.yellow('pnpm install failed — run it manually.'))+ p.log.warn(err instanceof Error ? err.message : String(err))+ }+ }+ if (answers.includeEngine) {+ s.start('Running bundle install in engine/...')+ try {+ await execaCommand('bundle install', { cwd: path.join(dst, 'engine'), stdio: 'pipe' })+ s.stop('bundle install complete.')+ } catch (err) {+ s.stop(pc.yellow('bundle install failed — run it manually.'))+ p.log.warn(err instanceof Error ? err.message : String(err))+ }+ }+}++function printNextSteps(answers: Answers, dst: string, installed: boolean): void {+ const lines: string[] = ['']+ lines.push(pc.bold('Next steps'))+ lines.push(` ${pc.dim('cd')} ${path.relative(process.cwd(), dst) || '.'}`)+ if (!installed) {+ if (answers.includeDashboard) lines.push(` ${pc.dim('pnpm')} install`)+ if (answers.includeEngine)+ lines.push(` ${pc.dim('cd engine && bundle')} install && ${pc.dim('cd ..')}`)+ }+ if (answers.includeDashboard) {+ lines.push('')+ lines.push(pc.bold('Dashboard plugin'))+ lines.push(+ ` Edit ${pc.cyan('packages/dashboard/src/index.tsx')} to wire your nav/route/slot extensions.`,+ )+ lines.push(+ ` See ${pc.cyan('https://docs.spreecommerce.org/developer/customization/dashboard-plugins')}`,+ )+ }+ if (answers.includeEngine) {+ lines.push('')+ lines.push(pc.bold('Rails engine'))+ lines.push(+ ` Edit ${pc.cyan(`engine/app/controllers/spree/api/v3/admin/${answers.rubyName}_controller.rb`)}`,+ )+ lines.push(+ ` See ${pc.cyan('https://docs.spreecommerce.org/developer/customization/extensions')}`,+ )+ }+ lines.push('')+ p.note(lines.join('\n'), 'Your plugin is scaffolded.')+}++// ---------------------------------------------------------------------------+// Utilities+// ---------------------------------------------------------------------------++function pascalCase(input: string): string {+ return input+ .split(/[_-]/)+ .filter(Boolean)+ .map((part) => part[0].toUpperCase() + part.slice(1))+ .join('')+}++/**+ * The bundled template lives next to the CLI's dist/ in the published+ * tarball (`dist/templates/plugin/`) and next to source in dev+ * (`packages/cli/templates/plugin/`). Resolve relative to this file so+ * both layouts work.+ */+function resolveTemplatePath(): string {+ const here = path.dirname(fileURLToPath(import.meta.url))+ // dev: src/commands/plugin.ts → templates/plugin/ via ../../templates/plugin+ // built: dist/index.js → templates/plugin/ via ../templates/plugin+ const candidates = [+ path.resolve(here, TEMPLATE_RELATIVE_PATH),+ path.resolve(here, '../templates/plugin'),+ ]+ for (const candidate of candidates) {+ if (fs.existsSync(candidate)) return candidate+ }+ throw new Error(+ `Plugin template not found. Looked in:\n ${candidates.join('\n ')}\n\nReinstall @spree/cli to fix.`,+ )+}diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex efdfe196c7..57e51580a3 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -16,6 +16,7 @@ import { registerInitCommand } from './commands/init.js'import { registerLogsCommand } from './commands/logs.js'import { registerMigrateCommand } from './commands/migrate.js'import { registerOpenCommand } from './commands/open.js'+import { registerPluginCommand } from './commands/plugin.js'import { registerRailsCommand } from './commands/rails.js'import { registerRakeCommand } from './commands/rake.js'import { registerRestartCommand } from './commands/restart.js'@@ -92,6 +93,7 @@ registerApiKeyCommand(program)registerOpenCommand(program)registerSeedCommand(program)registerSampleDataCommand(program)+registerPluginCommand(program)// Admin API access (works against any Spree 5.5+ instance, not just local projects)registerApiCommand(program)diff --git a/packages/cli/src/lib/template.ts b/packages/cli/src/lib/template.tsnew file mode 100644index 0000000000..c86774fd9e--- /dev/null+++ b/packages/cli/src/lib/template.ts@@ -0,0 +1,127 @@+import fs from 'node:fs'+import path from 'node:path'++/**+ * Variables exposed to template files. Keys are matched as `{{key}}` in any+ * file content and renamed inside path segments (so a directory or file named+ * `{{ruby_name}}` becomes the resolved value).+ */+export type TemplateVars = Record<string, string>++export interface RenderOptions {+ /** Source directory containing the template tree. */+ src: string+ /** Destination directory. Must not exist or be empty (unless `force` is set). */+ dst: string+ /** Variables substituted into `{{key}}` placeholders. */+ vars: TemplateVars+ /**+ * Predicate evaluated against each path *relative to `src`*. When it+ * returns `true`, the file or directory (and its children) is skipped.+ * Used to gate optional subtrees like `packages/dashboard/` behind flags.+ */+ skip?: (relPath: string) => boolean+ /**+ * Overwrite a non-empty destination. Off by default — the CLI errors+ * before calling render when the target dir has content.+ */+ force?: boolean+}++/**+ * Render a template tree from `src` into `dst`.+ *+ * Behavior:+ * - Files ending in `.tt` have their contents passed through+ * `substitute` and are written without the `.tt` suffix.+ * - All other files are copied verbatim (no substitution — keeps binary+ * files and code with literal `{{` tokens safe).+ * - Path segments (file and directory names) ARE substituted on both+ * regular and `.tt` files. A directory named `lib/{{ruby_name}}`+ * becomes `lib/spree_brands/` in the output.+ * - Subtrees skipped by the `skip` predicate are not visited; their+ * parent directories are still created if they contain other content+ * (e.g. `packages/` survives when `packages/engine/` is skipped).+ */+export function render(opts: RenderOptions): void {+ const { src, dst, vars, skip, force } = opts++ if (!fs.existsSync(src)) {+ throw new Error(`Template source not found: ${src}`)+ }+ if (fs.existsSync(dst)) {+ const contents = fs.readdirSync(dst)+ if (contents.length > 0 && !force) {+ throw new Error(`Destination ${dst} is not empty. Pass force=true to overwrite.`)+ }+ } else {+ fs.mkdirSync(dst, { recursive: true })+ }++ walk(src, dst, '', vars, skip)+}++function walk(+ srcRoot: string,+ dstRoot: string,+ relPath: string,+ vars: TemplateVars,+ skip?: (relPath: string) => boolean,+): void {+ const srcDir = path.join(srcRoot, relPath)+ for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {+ const childRel = relPath ? `${relPath}/${entry.name}` : entry.name+ if (skip?.(childRel)) continue++ // Resolve any `{{var}}` tokens in the path segment itself before+ // writing to disk. Most names pass through unchanged.+ const dstName = substitute(entry.name, vars)+ const srcChild = path.join(srcRoot, childRel)++ if (entry.isDirectory()) {+ // Compute the destination directory path with renamed segment.+ const dstChildRel = relPath ? `${substituteSegments(relPath, vars)}/${dstName}` : dstName+ const dstChild = path.join(dstRoot, dstChildRel)+ fs.mkdirSync(dstChild, { recursive: true })+ walk(srcRoot, dstRoot, childRel, vars, skip)+ continue+ }++ // Strip the `.tt` suffix on template files so output is `package.json`+ // rather than `package.json.tt`. Non-template files keep their name.+ const isTemplate = dstName.endsWith('.tt')+ const finalName = isTemplate ? dstName.slice(0, -3) : dstName+ const dstChildRel = relPath ? `${substituteSegments(relPath, vars)}/${finalName}` : finalName+ const dstChild = path.join(dstRoot, dstChildRel)++ if (isTemplate) {+ const content = fs.readFileSync(srcChild, 'utf8')+ fs.writeFileSync(dstChild, substitute(content, vars))+ } else {+ // Use copyFile so file modes, etc. round-trip correctly. Binary+ // files (images, etc.) survive without re-encoding.+ fs.copyFileSync(srcChild, dstChild)+ }+ }+}++/**+ * Replace `{{key}}` tokens in `input` with `vars[key]`. Keys not in `vars`+ * are left untouched so users see the literal placeholder in output and+ * notice the typo, rather than getting silent empty-string substitution.+ *+ * Exported for testing; templates use it via `render()` indirectly.+ */+export function substitute(input: string, vars: TemplateVars): string {+ return input.replace(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g, (match, key) =>+ Object.hasOwn(vars, key) ? vars[key] : match,+ )+}++/** Substitute each path segment independently (we never want `/` from a value to inject a slash). */+function substituteSegments(p: string, vars: TemplateVars): string {+ return p+ .split('/')+ .map((seg) => substitute(seg, vars))+ .join('/')+}diff --git a/packages/cli/templates/plugin/.gitignore b/packages/cli/templates/plugin/.gitignorenew file mode 100644index 0000000000..44846ac2b2--- /dev/null+++ b/packages/cli/templates/plugin/.gitignore@@ -0,0 +1,16 @@+node_modules/+dist/+.DS_Store+*.log++# Rails engine+engine/Gemfile.lock+engine/tmp/+engine/log/+engine/spec/dummy/+engine/coverage/++# IDE+.idea/+.vscode/+*.swpdiff --git a/packages/cli/templates/plugin/LICENSE.tt b/packages/cli/templates/plugin/LICENSE.ttnew file mode 100644index 0000000000..4f6ba91a58--- /dev/null+++ b/packages/cli/templates/plugin/LICENSE.tt@@ -0,0 +1,3 @@+Copyright (c) {{year}} {{author_name}}++Licensed under the {{license}} License. See the license's full text for the canonical terms.diff --git a/packages/cli/templates/plugin/README.md.tt b/packages/cli/templates/plugin/README.md.ttnew file mode 100644index 0000000000..a43c36476d--- /dev/null+++ b/packages/cli/templates/plugin/README.md.tt@@ -0,0 +1,45 @@+# {{plugin_name}}++A Spree plugin: **{{name}}**.++This is a hybrid Node/Ruby monorepo with two halves:++- `packages/dashboard/` — TypeScript dashboard plugin (extends the Spree 6.0 admin via [`@spree/dashboard-core`](https://www.npmjs.com/package/@spree/dashboard-core))+- `engine/` — Ruby Rails engine (Spree extension gem) that ships the Admin API endpoints and ActiveRecord models++Both halves work together: the engine ships `/api/v3/admin/...` endpoints, the dashboard plugin calls them via the SDK's `request` method.++## Development setup++```bash+# Install JavaScript dependencies+pnpm install++# Install Ruby dependencies for the engine+cd engine && bundle install && cd ..+```++## Running against a Spree host app++The engine needs to live alongside a Spree host (typically scaffolded via `create-spree-app`). Point your host's Gemfile at the local engine:++```ruby+# in your Spree host's Gemfile+gem '{{ruby_name}}', path: '../path/to/{{plugin_name}}/engine'+```++Activate the dashboard plugin by adding a side-effect import to your dashboard's `main.tsx`, **before the router mounts**:++```tsx+import '{{npm_dashboard_package}}'+```++## Documentation++- [Dashboard Plugins guide](https://docs.spreecommerce.org/developer/customization/dashboard-plugins)+- [Custom Admin Endpoints](https://docs.spreecommerce.org/developer/sdk/admin/extending)+- [Spree Extensions guide](https://docs.spreecommerce.org/developer/customization/extensions)++## License++{{license}} © {{year}} {{author_name}}diff --git a/packages/cli/templates/plugin/package.json.tt b/packages/cli/templates/plugin/package.json.ttnew file mode 100644index 0000000000..28ae553874--- /dev/null+++ b/packages/cli/templates/plugin/package.json.tt@@ -0,0 +1,19 @@+{+ "name": "{{npm_package_name}}",+ "private": true,+ "version": "0.1.0",+ "description": "Spree plugin: {{name}}",+ "author": "{{author_name}} <{{author_email}}>",+ "license": "{{license}}",+ "type": "module",+ "scripts": {+ "build": "pnpm -r build",+ "lint": "pnpm -r lint",+ "typecheck": "pnpm -r typecheck",+ "test": "pnpm -r test"+ },+ "packageManager": "[email protected]",+ "engines": {+ "node": ">=22"+ }+}diff --git a/packages/cli/templates/plugin/packages/dashboard/biome.json b/packages/cli/templates/plugin/packages/dashboard/biome.jsonnew file mode 100644index 0000000000..1edeb564c7--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/biome.json@@ -0,0 +1,24 @@+{+ "$schema": "https://biomejs.dev/schemas/2.4.14/schema.json",+ "files": {+ "includes": ["src/**"]+ },+ "linter": {+ "enabled": true,+ "rules": {+ "recommended": true+ }+ },+ "formatter": {+ "enabled": true,+ "indentStyle": "space",+ "indentWidth": 2,+ "lineWidth": 100+ },+ "javascript": {+ "formatter": {+ "quoteStyle": "single",+ "semicolons": "asNeeded"+ }+ }+}diff --git a/packages/cli/templates/plugin/packages/dashboard/package.json.tt b/packages/cli/templates/plugin/packages/dashboard/package.json.ttnew file mode 100644index 0000000000..3993fd9ef8--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/package.json.tt@@ -0,0 +1,43 @@+{+ "name": "{{npm_dashboard_package}}",+ "private": true,+ "version": "0.1.0",+ "description": "Dashboard plugin half of {{plugin_name}}",+ "author": "{{author_name}} <{{author_email}}>",+ "license": "{{license}}",+ "type": "module",+ "main": "./src/index.tsx",+ "module": "./src/index.tsx",+ "types": "./src/index.tsx",+ "exports": {+ ".": "./src/index.tsx"+ },+ "files": [+ "src",+ "README.md"+ ],+ "scripts": {+ "lint": "biome check src",+ "lint:fix": "biome check --fix src",+ "typecheck": "tsc --noEmit"+ },+ "peerDependencies": {+ "@spree/admin-sdk": "^0.1.0",+ "@spree/dashboard-core": "^0.1.0",+ "@spree/dashboard-ui": "^0.1.0",+ "@tanstack/react-query": "^5",+ "@tanstack/react-router": "^1",+ "i18next": "^26",+ "lucide-react": "^1",+ "react": "^19",+ "react-dom": "^19",+ "react-i18next": "^17"+ },+ "devDependencies": {+ "@biomejs/biome": "^2.4.14",+ "@types/react": "^19.2.14",+ "@types/react-dom": "^19.2.3",+ "typescript": "~6.0.3",+ "vite": "^8"+ }+}diff --git a/packages/cli/templates/plugin/packages/dashboard/src/client.ts.tt b/packages/cli/templates/plugin/packages/dashboard/src/client.ts.ttnew file mode 100644index 0000000000..65b407a891--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/src/client.ts.tt@@ -0,0 +1,29 @@+/**+ * Typed wrappers around `adminClient.request` for the {{name}} endpoints+ * shipped by the engine. Keeping the wrappers in one file means consumers+ * (route pages, slot widgets) never call `request` directly — they import+ * from here, which makes it easy to swap implementations or rename paths.+ *+ * See https://docs.spreecommerce.org/developer/sdk/admin/extending for the+ * underlying `request` API.+ */+import type { PaginatedResponse } from '@spree/admin-sdk'+import { adminClient } from '@spree/dashboard-core'+import type { {{module_name}}, {{module_name}}CreateParams, {{module_name}}UpdateParams } from './types'++type ListParams = Record<string, string | number | boolean | (string | number)[] | undefined>++export const {{module_name}}Client = {+ list: (params?: ListParams) =>+ adminClient.request<PaginatedResponse<{{module_name}}>>('GET', '/{{name}}', { params }),++ get: (id: string) => adminClient.request<{{module_name}}>('GET', `/{{name}}/${id}`),++ create: (body: {{module_name}}CreateParams) =>+ adminClient.request<{{module_name}}>('POST', '/{{name}}', { body }),++ update: (id: string, body: {{module_name}}UpdateParams) =>+ adminClient.request<{{module_name}}>('PATCH', `/{{name}}/${id}`, { body }),++ delete: (id: string) => adminClient.request<void>('DELETE', `/{{name}}/${id}`),+}diff --git a/packages/cli/templates/plugin/packages/dashboard/src/index.tsx.tt b/packages/cli/templates/plugin/packages/dashboard/src/index.tsx.ttnew file mode 100644index 0000000000..01c7cc38ff--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/src/index.tsx.tt@@ -0,0 +1,100 @@+/**+ * {{plugin_name}} — dashboard plugin entry.+ *+ * Wires nav + route + slot + table extensions via defineDashboardPlugin and+ * merges plugin translations into the dashboard's i18next namespace. The host+ * dashboard activates this plugin by importing it as a side-effect:+ *+ * import '{{npm_dashboard_package}}'+ *+ * That single import (placed in `main.tsx` before the router mounts) triggers+ * every defineDashboardPlugin call and i18n.addResourceBundle call below.+ */+import { defineDashboardPlugin, defineTable, i18n } from '@spree/dashboard-core'+import { RelativeTime } from '@spree/dashboard-ui'+import { Link } from '@tanstack/react-router'+import { PackageIcon } from 'lucide-react'+import { {{module_name}}Client } from './client'+import en from './locales/en.json'+import { {{module_name}}ListPage } from './routes/{{name}}-list'+import { {{module_name}}Card } from './slots/product-{{name}}-card'+import type { {{module_name}} } from './types'++// ---------------------------------------------------------------------------+// 1. Translations+// ---------------------------------------------------------------------------+// `deep: true` + `overwrite: true` merge our `admin.{{name}}_plugin.*` keys+// into the framework's `admin.*` namespace without dropping base translations.+i18n.addResourceBundle('en', 'translation', en, true, true)++// ---------------------------------------------------------------------------+// 2. Declare the table used by our list page+// ---------------------------------------------------------------------------+defineTable<{{module_name}}>('{{name}}', {+ title: i18n.t('admin.{{name}}_plugin.table.title'),+ searchParam: 'search',+ searchPlaceholder: i18n.t('admin.{{name}}_plugin.table.search_placeholder'),+ defaultSort: { field: 'name', direction: 'asc' },+ emptyMessage: i18n.t('admin.{{name}}_plugin.table.empty'),+ columns: [+ {+ key: 'name',+ label: i18n.t('admin.{{name}}_plugin.fields.name'),+ sortable: true,+ filterable: true,+ default: true,+ render: (record) => (+ <Link+ to={'/$storeId/{{name}}/$id' as string}+ params={{ id: record.id }}+ className="font-medium text-foreground no-underline"+ >+ {record.name}+ </Link>+ ),+ },+ {+ key: 'created_at',+ label: i18n.t('admin.{{name}}_plugin.fields.created_at'),+ sortable: true,+ default: true,+ render: (record) => <RelativeTime iso={record.created_at} />,+ },+ ],+})++// ---------------------------------------------------------------------------+// 3. Register everything else+// ---------------------------------------------------------------------------+defineDashboardPlugin({+ nav: [+ {+ key: '{{name}}',+ label: i18n.t('admin.{{name}}_plugin.nav'),+ path: '/{{name}}',+ icon: PackageIcon,+ position: 50,+ },+ ],+ routes: [+ {+ key: '{{name}}',+ path: '/{{name}}',+ component: {{module_name}}ListPage,+ },+ ],+ slots: {+ 'product.form_sidebar': [+ {+ id: '{{name}}-card',+ // dashboard-core types `slots` generically; the slot's context shape+ // is documented in @spree/dashboard's source per slot name.+ component: {{module_name}}Card as never,+ position: 250,+ },+ ],+ },+})++export { {{module_name}}Client } from './client'+export type { {{module_name}} } from './types'diff --git a/packages/cli/templates/plugin/packages/dashboard/src/locales/en.json.tt b/packages/cli/templates/plugin/packages/dashboard/src/locales/en.json.ttnew file mode 100644index 0000000000..a07a24ce54--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/src/locales/en.json.tt@@ -0,0 +1,25 @@+{+ "admin": {+ "{{name}}_plugin": {+ "nav": "{{module_name}}",+ "page": {+ "title": "{{module_name}}",+ "subtitle": "Manage your {{name}}",+ "new_cta": "New {{name}}"+ },+ "table": {+ "title": "{{module_name}}",+ "search_placeholder": "Search by name…",+ "empty": "No {{name}} yet"+ },+ "fields": {+ "name": "Name",+ "created_at": "Created"+ },+ "product_card": {+ "title": "{{module_name}}",+ "placeholder": "Replace this widget with your own slot UI."+ }+ }+ }+}diff --git a/packages/cli/templates/plugin/packages/dashboard/src/routes/{{name}}-list.tsx.tt b/packages/cli/templates/plugin/packages/dashboard/src/routes/{{name}}-list.tsx.ttnew file mode 100644index 0000000000..7f33673a04--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/src/routes/{{name}}-list.tsx.tt@@ -0,0 +1,50 @@+/**+ * {{module_name}} list page. Mounted at `/$storeId/{{name}}` via the plugin's+ * route registration in `index.tsx`. Uses `<ResourceTable>` for filtering,+ * sorting, pagination — the same UX as core's Products/Customers/Orders.+ *+ * Plugin route components receive `{ params, storeId, searchParams }` from+ * the dashboard's catch-all dispatcher. We forward `searchParams` to+ * ResourceTable so filter/sort/pagination round-trip through the URL.+ */+import { PageHeader, type ResourceSearch, ResourceTable } from '@spree/dashboard-core'+import { Button, ResourceLayout } from '@spree/dashboard-ui'+import { PlusIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import { {{module_name}}Client } from '../client'+import type { {{module_name}} } from '../types'++interface {{module_name}}ListPageProps {+ searchParams: Record<string, unknown>+}++export function {{module_name}}ListPage({ searchParams }: {{module_name}}ListPageProps) {+ const { t } = useTranslation()++ return (+ <ResourceLayout+ header={+ <PageHeader+ title={t('admin.{{name}}_plugin.page.title')}+ subtitle={t('admin.{{name}}_plugin.page.subtitle')}+ actions={+ <Button size="sm">+ <PlusIcon className="size-4" />+ {t('admin.{{name}}_plugin.page.new_cta')}+ </Button>+ }+ />+ }+ main={+ <ResourceTable<{{module_name}}>+ tableKey="{{name}}"+ queryKey="{{name}}"+ // ResourceTable hands `params` to queryFn as Record<string, unknown>;+ // we narrow to our client's known param shape at the boundary.+ queryFn={(params) => {{module_name}}Client.list(params as Record<string, never>)}+ searchParams={searchParams as ResourceSearch}+ />+ }+ />+ )+}diff --git a/packages/cli/templates/plugin/packages/dashboard/src/slots/product-{{name}}-card.tsx.tt b/packages/cli/templates/plugin/packages/dashboard/src/slots/product-{{name}}-card.tsx.ttnew file mode 100644index 0000000000..20400b31f7--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/src/slots/product-{{name}}-card.tsx.tt@@ -0,0 +1,33 @@+/**+ * Sidebar widget rendered on the product detail page via the+ * `product.form_sidebar` slot. Demonstrates the slot extension pattern:+ * the host page knows nothing about {{name}}; the plugin contributes+ * this card via the slot registry.+ *+ * The slot's context (typed by the dashboard's slot catalogue as+ * `{ product }`) gives us the product being edited.+ */+import { Card, CardContent, CardHeader, CardTitle } from '@spree/dashboard-ui'+import { useTranslation } from 'react-i18next'++interface {{module_name}}CardProps {+ product: { id: string }+}++export function {{module_name}}Card({ product }: {{module_name}}CardProps) {+ const { t } = useTranslation()++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.{{name}}_plugin.product_card.title')}</CardTitle>+ </CardHeader>+ <CardContent>+ <p className="text-sm text-muted-foreground">+ {t('admin.{{name}}_plugin.product_card.placeholder')}+ </p>+ <p className="mt-2 text-xs font-mono text-muted-foreground">{product.id}</p>+ </CardContent>+ </Card>+ )+}diff --git a/packages/cli/templates/plugin/packages/dashboard/src/types.ts.tt b/packages/cli/templates/plugin/packages/dashboard/src/types.ts.ttnew file mode 100644index 0000000000..2c90dc1a8d--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/src/types.ts.tt@@ -0,0 +1,17 @@+/**+ * Shape of a {{module_name}} record returned by the engine. Generated by hand+ * here; a real plugin should regenerate this from the Alba serializer via+ * Spree's Typelizer pipeline once the engine is publishing types.+ */+export interface {{module_name}} {+ id: string+ name: string+ created_at: string+ updated_at: string+}++export interface {{module_name}}CreateParams {+ name: string+}++export type {{module_name}}UpdateParams = Partial<{{module_name}}CreateParams>diff --git a/packages/cli/templates/plugin/packages/dashboard/tsconfig.json b/packages/cli/templates/plugin/packages/dashboard/tsconfig.jsonnew file mode 100644index 0000000000..fbb2ea3e56--- /dev/null+++ b/packages/cli/templates/plugin/packages/dashboard/tsconfig.json@@ -0,0 +1,25 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "ignoreDeprecations": "6.0",+ "useDefineForClassFields": true,+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "types": ["vite/client"],+ "skipLibCheck": true,+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "moduleDetection": "force",+ "noEmit": true,+ "jsx": "react-jsx",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "erasableSyntaxOnly": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true,+ "resolveJsonModule": true+ },+ "include": ["src"]+}diff --git a/packages/cli/templates/plugin/pnpm-workspace.yaml b/packages/cli/templates/plugin/pnpm-workspace.yamlnew file mode 100644index 0000000000..dee51e928d--- /dev/null+++ b/packages/cli/templates/plugin/pnpm-workspace.yaml@@ -0,0 +1,2 @@+packages:+ - "packages/*"diff --git a/packages/cli/tests/plugin-template.test.ts b/packages/cli/tests/plugin-template.test.tsnew file mode 100644index 0000000000..a8fa947920--- /dev/null+++ b/packages/cli/tests/plugin-template.test.ts@@ -0,0 +1,151 @@+/**+ * Integration test for the bundled plugin template. Renders the real+ * `templates/plugin/` tree into a temp dir and verifies the output looks+ * right end-to-end. Catches missing variables, broken paths, and bad+ * substitution in a way the renderer's unit tests can't.+ */+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { render, type TemplateVars } from '../src/lib/template'++const TEMPLATE_SRC = path.resolve(__dirname, '../templates/plugin')++const SAMPLE_VARS: TemplateVars = {+ name: 'brands',+ plugin_name: 'brands',+ ruby_name: 'spree_brands',+ module_name: 'SpreeBrands',+ npm_scope: '@acme',+ npm_package_name: '@acme/brands',+ npm_dashboard_package: '@acme/brands-dashboard',+ author_name: 'Jane Developer',+ author_email: '[email protected]',+ license: 'MIT',+ year: '2026',+}++describe('bundled plugin template', () => {+ const tempDirs: string[] = []++ function tempDir(): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-plugin-test-'))+ tempDirs.push(dir)+ return dir+ }++ afterEach(() => {+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })+ tempDirs.length = 0+ })++ it('renders into a working structure with all halves', () => {+ const dst = path.join(tempDir(), 'out')+ render({ src: TEMPLATE_SRC, dst, vars: SAMPLE_VARS })++ expect(fs.existsSync(path.join(dst, 'package.json'))).toBe(true)+ expect(fs.existsSync(path.join(dst, 'pnpm-workspace.yaml'))).toBe(true)+ expect(fs.existsSync(path.join(dst, 'README.md'))).toBe(true)+ expect(fs.existsSync(path.join(dst, 'LICENSE'))).toBe(true)+ expect(fs.existsSync(path.join(dst, '.gitignore'))).toBe(true)++ expect(fs.existsSync(path.join(dst, 'packages/dashboard/package.json'))).toBe(true)+ expect(fs.existsSync(path.join(dst, 'packages/dashboard/src/index.tsx'))).toBe(true)+ expect(fs.existsSync(path.join(dst, 'packages/dashboard/src/client.ts'))).toBe(true)+ expect(fs.existsSync(path.join(dst, 'packages/dashboard/src/types.ts'))).toBe(true)++ expect(fs.existsSync(path.join(dst, 'packages/dashboard/src/routes/brands-list.tsx'))).toBe(+ true,+ )+ expect(+ fs.existsSync(path.join(dst, 'packages/dashboard/src/slots/product-brands-card.tsx')),+ ).toBe(true)+ expect(fs.existsSync(path.join(dst, 'packages/dashboard/src/locales/en.json'))).toBe(true)+ })++ it('renders the root package.json with substituted name', () => {+ const dst = path.join(tempDir(), 'out')+ render({ src: TEMPLATE_SRC, dst, vars: SAMPLE_VARS })++ const pkg = JSON.parse(fs.readFileSync(path.join(dst, 'package.json'), 'utf8'))+ expect(pkg.name).toBe('@acme/brands')+ expect(pkg.author).toBe('Jane Developer <[email protected]>')+ expect(pkg.license).toBe('MIT')+ })++ it('renders the dashboard package.json with the dashboard sub-name', () => {+ const dst = path.join(tempDir(), 'out')+ render({ src: TEMPLATE_SRC, dst, vars: SAMPLE_VARS })++ const pkg = JSON.parse(+ fs.readFileSync(path.join(dst, 'packages/dashboard/package.json'), 'utf8'),+ )+ expect(pkg.name).toBe('@acme/brands-dashboard')+ expect(pkg.peerDependencies['@spree/dashboard-core']).toBeDefined()+ })++ it('substitutes module names + paths consistently in the dashboard entry', () => {+ const dst = path.join(tempDir(), 'out')+ render({ src: TEMPLATE_SRC, dst, vars: SAMPLE_VARS })++ const index = fs.readFileSync(path.join(dst, 'packages/dashboard/src/index.tsx'), 'utf8')+ expect(index).toContain("from './client'")+ expect(index).toContain("from './routes/brands-list'")+ expect(index).toContain("from './slots/product-brands-card'")+ expect(index).toContain('SpreeBrandsClient')+ expect(index).toContain('SpreeBrandsListPage')+ expect(index).toContain('SpreeBrandsCard')+ expect(index).toContain("path: '/brands'")+ expect(index).toContain('admin.brands_plugin')+ })++ it('substitutes the README', () => {+ const dst = path.join(tempDir(), 'out')+ render({ src: TEMPLATE_SRC, dst, vars: SAMPLE_VARS })++ const readme = fs.readFileSync(path.join(dst, 'README.md'), 'utf8')+ expect(readme).toContain('# brands')+ expect(readme).toContain('@acme/brands-dashboard')+ expect(readme).toContain("gem 'spree_brands'")+ expect(readme).toContain('Jane Developer')+ expect(readme).not.toContain('{{')+ })++ it('skips the dashboard subtree when asked', () => {+ const dst = path.join(tempDir(), 'out')+ render({+ src: TEMPLATE_SRC,+ dst,+ vars: SAMPLE_VARS,+ skip: (rel) => rel === 'packages/dashboard' || rel.startsWith('packages/dashboard/'),+ })++ expect(fs.existsSync(path.join(dst, 'package.json'))).toBe(true)+ expect(fs.existsSync(path.join(dst, 'packages/dashboard'))).toBe(false)+ })++ it('leaves no `{{...}}` tokens in any rendered file', () => {+ const dst = path.join(tempDir(), 'out')+ render({ src: TEMPLATE_SRC, dst, vars: SAMPLE_VARS })++ const stragglers: string[] = []+ function walk(dir: string) {+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {+ const p = path.join(dir, e.name)+ if (e.isDirectory()) walk(p)+ else {+ const content = fs.readFileSync(p, 'utf8')+ if (/\{\{[a-zA-Z_]/.test(content)) {+ stragglers.push(+ `${path.relative(dst, p)}: ${content.match(/\{\{[a-zA-Z_][a-zA-Z0-9_]*\}\}/)?.[0]}`,+ )+ }+ }+ }+ }+ walk(dst)++ expect(stragglers).toEqual([])+ })+})diff --git a/packages/cli/tests/template.test.ts b/packages/cli/tests/template.test.tsnew file mode 100644index 0000000000..ffcf4a27fe--- /dev/null+++ b/packages/cli/tests/template.test.ts@@ -0,0 +1,150 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { render, substitute } from '../src/lib/template'++describe('substitute', () => {+ it('replaces known keys', () => {+ expect(substitute('Hello {{name}}!', { name: 'World' })).toBe('Hello World!')+ })++ it('leaves unknown keys untouched so typos surface', () => {+ expect(substitute('Hi {{nayme}} from {{place}}', { name: 'A', place: 'B' })).toBe(+ 'Hi {{nayme}} from B',+ )+ })++ it('handles multiple keys + repeats', () => {+ expect(substitute('{{a}} - {{a}} - {{b}}', { a: 'x', b: 'y' })).toBe('x - x - y')+ })++ it('does not match incomplete tokens', () => {+ expect(substitute('{name}} {{name}', { name: 'x' })).toBe('{name}} {{name}')+ })+})++describe('render', () => {+ const tempDirs: string[] = []++ function tempDir(): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-template-test-'))+ tempDirs.push(dir)+ return dir+ }++ function writeFile(p: string, content: string): void {+ fs.mkdirSync(path.dirname(p), { recursive: true })+ fs.writeFileSync(p, content)+ }++ function read(p: string): string {+ return fs.readFileSync(p, 'utf8')+ }++ afterEach(() => {+ for (const dir of tempDirs) {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ tempDirs.length = 0+ })++ it('copies plain files verbatim', () => {+ const src = tempDir()+ const dst = path.join(tempDir(), 'out')+ writeFile(path.join(src, 'README.md'), 'unchanged content {{not_a_var}}')++ render({ src, dst, vars: {} })++ expect(read(path.join(dst, 'README.md'))).toBe('unchanged content {{not_a_var}}')+ })++ it('renders .tt files with substitution and strips the suffix', () => {+ const src = tempDir()+ const dst = path.join(tempDir(), 'out')+ writeFile(path.join(src, 'package.json.tt'), '{"name": "{{name}}"}')++ render({ src, dst, vars: { name: 'spree-brands' } })++ expect(fs.existsSync(path.join(dst, 'package.json.tt'))).toBe(false)+ expect(read(path.join(dst, 'package.json'))).toBe('{"name": "spree-brands"}')+ })++ it('substitutes variables in directory names', () => {+ const src = tempDir()+ const dst = path.join(tempDir(), 'out')+ writeFile(path.join(src, 'lib', '{{ruby_name}}', 'engine.rb'), 'module {{module_name}}; end')++ render({+ src,+ dst,+ vars: { ruby_name: 'spree_brands', module_name: 'SpreeBrands' },+ })++ expect(fs.existsSync(path.join(dst, 'lib', 'spree_brands', 'engine.rb'))).toBe(true)+ expect(read(path.join(dst, 'lib', 'spree_brands', 'engine.rb'))).toBe(+ 'module {{module_name}}; end',+ )+ })++ it('substitutes variables in .tt content AND in path segments simultaneously', () => {+ const src = tempDir()+ const dst = path.join(tempDir(), 'out')+ writeFile(path.join(src, 'lib', '{{ruby_name}}.rb.tt'), 'require "{{ruby_name}}/engine"')++ render({ src, dst, vars: { ruby_name: 'spree_brands' } })++ expect(read(path.join(dst, 'lib', 'spree_brands.rb'))).toBe('require "spree_brands/engine"')+ })++ it('skips paths matching the skip predicate', () => {+ const src = tempDir()+ const dst = path.join(tempDir(), 'out')+ writeFile(path.join(src, 'packages', 'dashboard', 'index.ts'), '// dashboard')+ writeFile(path.join(src, 'engine', 'lib.rb'), '# engine')+ writeFile(path.join(src, 'README.md'), 'top-level')++ render({+ src,+ dst,+ vars: {},+ skip: (rel) => rel === 'engine' || rel.startsWith('engine/'),+ })++ expect(fs.existsSync(path.join(dst, 'engine'))).toBe(false)+ expect(fs.existsSync(path.join(dst, 'packages', 'dashboard', 'index.ts'))).toBe(true)+ expect(fs.existsSync(path.join(dst, 'README.md'))).toBe(true)+ })++ it('rejects a non-empty destination without force', () => {+ const src = tempDir()+ const dst = tempDir() // already exists, will populate below+ writeFile(path.join(src, 'file.txt'), 'a')+ writeFile(path.join(dst, 'preexisting.txt'), 'b')++ expect(() => render({ src, dst, vars: {} })).toThrow(/not empty/)+ })++ it('overwrites an existing destination with force=true', () => {+ const src = tempDir()+ const dst = tempDir()+ writeFile(path.join(src, 'file.txt'), 'new')+ writeFile(path.join(dst, 'old.txt'), 'remains')++ render({ src, dst, vars: {}, force: true })++ expect(read(path.join(dst, 'file.txt'))).toBe('new')+ // Force doesn't clean — old files remain unless they collide.+ expect(read(path.join(dst, 'old.txt'))).toBe('remains')+ })++ it('creates a missing destination directory', () => {+ const src = tempDir()+ const dst = path.join(tempDir(), 'does', 'not', 'exist', 'yet')+ writeFile(path.join(src, 'file.txt'), 'hello')++ render({ src, dst, vars: {} })++ expect(read(path.join(dst, 'file.txt'))).toBe('hello')+ })+})diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.tsindex 0fa8c006d6..d7f0f38ef9 100644--- a/packages/cli/tsup.config.ts+++ b/packages/cli/tsup.config.ts@@ -1,3 +1,4 @@+import { cpSync } from 'node:fs'import { defineConfig } from 'tsup'export default defineConfig({@@ -16,4 +17,11 @@ export default defineConfig({'const require = __createRequire(import.meta.url);',].join('\n'),},+ // Copy the scaffolding templates into dist/ so the published tarball ships+ // them. `src/commands/plugin.ts` resolves the path relative to the running+ // file via `resolveTemplatePath()` — both `src/commands → ../../templates`+ // (dev) and `dist/index.js → ../templates` (published) work.+ async onSuccess() {+ cpSync('templates', 'dist/templates', { recursive: true })+ },})diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ed0b409b2f..8b97015ac0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -390,6 +390,52 @@ importers:specifier: ^8.0.16version: 8.0.16(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ packages/dashboard-plugin-example:+ dependencies:+ '@spree/admin-sdk':+ specifier: workspace:^+ version: link:../admin-sdk+ '@spree/dashboard-core':+ specifier: workspace:^+ version: link:../dashboard-core+ '@spree/dashboard-ui':+ specifier: workspace:^+ version: link:../dashboard-ui+ '@tanstack/react-query':+ specifier: ^5.100.9+ version: 5.100.9([email protected])+ '@tanstack/react-router':+ specifier: ^1.169.2+ i18next:+ specifier: ^26.2.0+ version: 26.2.0([email protected])+ lucide-react:+ specifier: ^1.14.0+ version: 1.14.0([email protected])+ react:+ specifier: ^19.2.6+ version: 19.2.6+ react-dom:+ specifier: ^19.2.6+ version: 19.2.6([email protected])+ react-i18next:+ specifier: ^17.0.8+ version: 17.0.8([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])+ devDependencies:+ '@types/react':+ specifier: ^19.2.14+ version: 19.2.14+ '@types/react-dom':+ specifier: ^19.2.3+ version: 19.2.3(@types/[email protected])+ typescript:+ specifier: ~6.0.3+ version: 6.0.3+ vite:+ specifier: ^8.0.11+ version: 8.0.11(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+packages/dashboard-ui:dependencies:'@base-ui/react':