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.

Activate discovered plugins via virtual:spree-dashboard-plugins

Damian Legawiec65d3d4395f26
diff --git a/docs/developer/dashboard/overview.mdx b/docs/developer/dashboard/overview.mdx
index 735ea0f2f6..0c369d1a93 100644
--- a/docs/developer/dashboard/overview.mdx
+++ b/docs/developer/dashboard/overview.mdx
@@ -48,12 +48,12 @@ That's the entire setup. No npm publishing, no peer-deps, no Vite plugin registr
### 2. Ship a redistributable plugin
-You're building a feature that multiple Spree stores will install — a Brands gem, a Wishlists integration, a Stripe Tax connector. Package the customization as an npm module so any host app can `pnpm add my-plugin` + flip two switches in their host config.
+You're building a feature that multiple Spree stores will install — a Brands gem, a Wishlists integration, a Stripe Tax connector. Package the customization as an npm module so any host app can install it with a single `pnpm add my-plugin`.
This adds three concerns on top of in-app customization:
- **Peer-dependency rules** so your plugin's `@spree/dashboard-core` resolves to the host's instance (registries are module singletons — see [Publishing](/developer/dashboard/plugins/publishing))
-- **Host-side activation** — the host side-effect-imports your package in `main.tsx`. Tailwind scanning happens automatically: `spreeDashboardPlugin()` discovers plugins by reading the host's `package.json` deps and picking up any with the `spree.dashboard.plugin` marker. See [Distributing](/developer/dashboard/plugins/distributing) for the auto-discovery details and the manual-whitelist escape hatch.
+- **Auto-discovery** — `spreeDashboardPlugin()` reads the host's `package.json` deps, picks up any with the `spree.dashboard.plugin` marker, and both activates them (via the `virtual:spree-dashboard-plugins` module the app entry imports) and wires Tailwind scanning. Installing is `pnpm add` + dev-server restart. See [Distributing](/developer/dashboard/plugins/distributing) for details and the manual-whitelist escape hatch.
- **A backend half** — a Rails extension gem that ships the API endpoints your dashboard plugin calls
The `@spree/cli` scaffolds the dashboard half for you:
diff --git a/docs/developer/dashboard/plugins/distributing.mdx b/docs/developer/dashboard/plugins/distributing.mdx
index 9628d6c5db..31016c992c 100644
--- a/docs/developer/dashboard/plugins/distributing.mdx
+++ b/docs/developer/dashboard/plugins/distributing.mdx
@@ -6,32 +6,30 @@ description: What consumers do to install your plugin — the wiring on the host
This page is the *consumer's* perspective on installing your plugin. Cover it in your README so users have a one-page reference.
-## The three steps
+## The two steps
A consumer installing your plugin needs to:
-1. **Install the npm package** — `pnpm add @your-scope/your-plugin`
-2. **Import it in `main.tsx`** — so its side-effects (`defineDashboardPlugin`) run
-3. **Apply any backend changes** — usually adding a Rails gem, running migrations
-
-In code:
-
-```tsx
-// packages/dashboard/src/main.tsx
-import '@/i18n-setup'
-import '@your-scope/your-plugin' // ⬅ step 2
-import '@/customizations'
-// rest of bootstrap
-```
+1. **Install the npm package** — `pnpm add @your-scope/your-plugin`, then restart the dev server
+2. **Apply any backend changes** — usually adding a Rails gem, running migrations
```bash
+pnpm add @your-scope/your-plugin
+
# Rails side, if your plugin has a backend
bundle add your_plugin
bin/rails generate your_plugin:install
bin/rails db:migrate
```
-**No `vite.config.ts` edit.** As long as your plugin's `package.json` declares the `spree.dashboard.plugin` marker (the CLI scaffold does this for you — see [Publishing](/developer/dashboard/plugins/publishing#tell-the-vite-plugin-where-to-find-you)), `spreeDashboardPlugin()` walks the host's dependencies at build time and finds it automatically. Tailwind picks up the plugin's class names without any extra wiring.
+**No host-code edit.** As long as your plugin's `package.json` declares the `spree.dashboard.plugin` marker (the CLI scaffold does this for you — see [Publishing](/developer/dashboard/plugins/publishing#tell-the-vite-plugin-where-to-find-you)), `spreeDashboardPlugin()` walks the host's dependencies at build time and finds it automatically. Discovery feeds two things:
+
+- **Activation** — the app entry imports `virtual:spree-dashboard-plugins` (the dashboard app shell and the starter template already do), a module the Vite plugin synthesizes with one side-effect import per discovered plugin. Your `defineDashboardPlugin` call runs before first render without the host touching `main.tsx`.
+- **Tailwind scanning** — your plugin's class names compile without any extra wiring.
+
+Installing a package activating its code in the admin is the same trust model as adding a gem to a Rails `Gemfile` — vet your dependencies. Hosts that want explicit control use the whitelist below.
+
+Plugins that take configuration (the `definePlugin(config)` factory pattern — see below) are the exception: the factory call is host code, so the host imports and invokes it in `main.tsx` themselves.
### Manual whitelist (advanced)
diff --git a/packages/cli/templates/plugin/packages/dashboard/src/index.tsx.tt b/packages/cli/templates/plugin/packages/dashboard/src/index.tsx.tt
index ddbb0b54e6..5c68dab3e6 100644
--- a/packages/cli/templates/plugin/packages/dashboard/src/index.tsx.tt
+++ b/packages/cli/templates/plugin/packages/dashboard/src/index.tsx.tt
@@ -2,13 +2,14 @@
* {{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:
+ * merges plugin translations into the dashboard's i18next namespace.
*
- * import '{{npm_dashboard_package}}'
- *
- * That single import (placed in `main.tsx` before the router mounts) triggers
- * every defineDashboardPlugin call and i18n.addResourceBundle call below.
+ * Activation is automatic: the package.json's `spree.dashboard.plugin`
+ * marker makes `spreeDashboardPlugin()` discover this package and import it
+ * through `virtual:spree-dashboard-plugins` in the host's app entry, running
+ * every defineDashboardPlugin and i18n.addResourceBundle call below before
+ * the router mounts. Hosts without the virtual import can side-effect-import
+ * '{{npm_dashboard_package}}' directly.
*/
import { defineDashboardPlugin, defineTable, i18n } from '@spree/dashboard-core'
import { RelativeTime } from '@spree/dashboard-ui'
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.ts
index 6f7a2ef697..1484715f38 100644
--- a/packages/dashboard-core/src/index.ts
+++ b/packages/dashboard-core/src/index.ts
@@ -1,3 +1,4 @@
+/// <reference path="./virtual.d.ts" />
// @spree/dashboard-core — Spree Dashboard framework.
//
// The extension API for plugin authors. Consumers import flat from this barrel:
diff --git a/packages/dashboard-core/src/virtual.d.ts b/packages/dashboard-core/src/virtual.d.ts
new file mode 100644
index 0000000000..04d7b8590a
--- /dev/null
+++ b/packages/dashboard-core/src/virtual.d.ts
@@ -0,0 +1,5 @@
+// Ambient declaration for the module synthesized by `spreeDashboardPlugin()`
+// (see src/vite/index.ts). Referenced from src/index.ts so any program that
+// imports @spree/dashboard-core can `import 'virtual:spree-dashboard-plugins'`
+// without its own shim.
+declare module 'virtual:spree-dashboard-plugins'
diff --git a/packages/dashboard-core/src/vite/discover.ts b/packages/dashboard-core/src/vite/discover.ts
index 740c0b00eb..d93d546e4d 100644
--- a/packages/dashboard-core/src/vite/discover.ts
+++ b/packages/dashboard-core/src/vite/discover.ts
@@ -8,11 +8,11 @@ import { fileURLToPath } from 'node:url'
* packages that opt-in as dashboard plugins by declaring
* `"spree": { "dashboard": { "plugin": true } }` in their own `package.json`.
*
- * Auto-discovery removes the `vite.config.ts` half of a plugin install —
- * Tailwind scanning is wired up the moment the dependency lands. (The host
- * still activates the plugin's code with a side-effect import in `main.tsx`.)
- * Plugin authors opt-in by adding the marker field; hosts never have to know
- * it exists.
+ * Auto-discovery is what makes `pnpm add @acme/foo-plugin` a one-step
+ * install: the discovered list feeds both Tailwind source scanning and the
+ * `virtual:spree-dashboard-plugins` activation module the app entry imports
+ * (see index.ts). Plugin authors opt-in by adding the marker field; hosts
+ * never have to know it exists.
*
* Order is deterministic — the order packages appear in the host's combined
* `dependencies` + `devDependencies` maps. Tailwind class scanning is
diff --git a/packages/dashboard-core/src/vite/index.ts b/packages/dashboard-core/src/vite/index.ts
index da35540e9a..63acdb9dcd 100644
--- a/packages/dashboard-core/src/vite/index.ts
+++ b/packages/dashboard-core/src/vite/index.ts
@@ -41,20 +41,26 @@ export interface SpreeDashboardPluginOptions {
}
/**
- * Vite plugin that wires up Tailwind v4 for a Spree dashboard.
+ * Vite plugin that wires up a Spree dashboard's plugin system and Tailwind v4.
*
- * Combines two concerns:
+ * Combines three concerns:
*
- * 1. Source-scanning: tells Tailwind to scan `@spree/dashboard-core`,
- * `@spree/dashboard-ui`, and any host-named plugin packages, by
- * injecting `@source` directives into the host's CSS entry. Tailwind v4
+ * 1. Plugin activation: serves `virtual:spree-dashboard-plugins`, a
+ * synthesized module that side-effect-imports every dashboard plugin
+ * (auto-discovered or whitelisted). The app entry imports it once —
+ * after that, installing a plugin is just `pnpm add`; its
+ * `defineDashboardPlugin` call runs without any host-code edit.
+ *
+ * 2. Source-scanning: tells Tailwind to scan `@spree/dashboard-core`,
+ * `@spree/dashboard-ui`, and every plugin package, by injecting
+ * `@source` directives into the host's CSS entry. Tailwind v4
* doesn't scan `node_modules` by default and only accepts filesystem
* paths in `@source` directives (not bare package specifiers), so we
* resolve each package through Node module resolution to get an
* absolute path that works under any package layout (workspace
* symlinks, npm tarballs, pnpm's `.pnpm/` hoisting).
*
- * 2. Tailwind itself: returns `@tailwindcss/vite` bundled alongside the
+ * 3. Tailwind itself: returns `@tailwindcss/vite` bundled alongside the
* source-injection plugin, in the right order. Hosts don't add
* `@tailwindcss/vite` separately.
*
@@ -65,38 +71,57 @@ export interface SpreeDashboardPluginOptions {
*
* export default defineConfig({
* plugins: [
- * spreeDashboardPlugin({
- * plugins: ['@my-store/orders-plugin'],
- * }),
+ * spreeDashboardPlugin(),
* // … react(), TanStack Router, etc. — host owns these.
* ],
* })
*
+ * // host src/main.tsx (once, before the router mounts)
+ * import 'virtual:spree-dashboard-plugins'
+ *
* For a custom dashboard built on `@spree/dashboard-core` + `@spree/dashboard-ui`,
* point `cssEntry` at the host's own CSS file:
*
* spreeDashboardPlugin({
* cssEntry: './src/admin.css',
- * plugins: ['@my-store/vendor-portal-plugin'],
+ * plugins: ['@my-store/vendor-portal-plugin'], // explicit whitelist opt-out
* })
*/
export function spreeDashboardPlugin(options: SpreeDashboardPluginOptions = {}): PluginOption[] {
return [dashboardTailwindSourcePlugin(options), tailwindcss()]
}
+/** Module specifier hosts import to activate discovered dashboard plugins. */
+export const VIRTUAL_PLUGIN_MODULE_ID = 'virtual:spree-dashboard-plugins'
+// Rollup convention: \0 marks the resolved id as virtual so other plugins
+// (and Vite's own resolver) leave it alone.
+const RESOLVED_VIRTUAL_PLUGIN_MODULE_ID = `\0${VIRTUAL_PLUGIN_MODULE_ID}`
+
+/**
+ * Source of `virtual:spree-dashboard-plugins`: one side-effect import per
+ * activatable plugin, in discovery order. Exported for tests.
+ */
+export function generateVirtualPluginModule(packages: readonly string[]): string {
+ const header = '// generated by @spree/dashboard-core/vite — one import per dashboard plugin'
+ if (packages.length === 0) return `${header}\nexport {}\n`
+ const imports = packages.map((pkg) => `import ${JSON.stringify(pkg)}`).join('\n')
+ return `${header}\n${imports}\nexport {}\n`
+}
+
function dashboardTailwindSourcePlugin(options: SpreeDashboardPluginOptions): Plugin {
const explicitPlugins = options.plugins
const cssEntry = options.cssEntry ?? './src/styles.css'
- // Resolution roots from this file's location. Wherever
+ // Resolution root for the framework's own siblings. Wherever
// `@spree/dashboard-core` ends up on disk (workspace symlink, hoisted
- // npm install, pnpm `.pnpm/` directory), the sibling `@spree/*` packages
- // are reachable from here via Node module resolution.
+ // npm install, pnpm `.pnpm/` directory), `@spree/dashboard-ui` is
+ // reachable from here via Node module resolution.
const fromHere = createRequire(import.meta.url)
let resolvedSources: string[] = []
let resolvedCssEntry = ''
let pluginErrors: PluginError[] = []
+ let activatablePlugins: string[] = []
return {
name: 'spree:dashboard-tailwind-source',
@@ -115,11 +140,15 @@ function dashboardTailwindSourcePlugin(options: SpreeDashboardPluginOptions): Pl
onWarn: (msg) => console.warn(`[@spree/dashboard-core/vite] ${msg}`),
})
- const packagesToScan = ['@spree/dashboard-core', '@spree/dashboard-ui', ...pluginPackages]
+ // Plugins are the host's dependencies, so resolve them from the host
+ // root — under pnpm's strict layout they are not necessarily reachable
+ // from dashboard-core's own location.
+ const fromHost = createRequire(path.join(config.root, 'package.json'))
pluginErrors = []
resolvedSources = []
- for (const pkg of packagesToScan) {
+ activatablePlugins = []
+ for (const pkg of ['@spree/dashboard-core', '@spree/dashboard-ui']) {
const dir = resolvePackageSourceDir(pkg, fromHere)
if (dir) {
resolvedSources.push(dir)
@@ -127,6 +156,28 @@ function dashboardTailwindSourcePlugin(options: SpreeDashboardPluginOptions): Pl
pluginErrors.push({ pkg, kind: 'unresolved' })
}
}
+ for (const pkg of pluginPackages) {
+ const dir = resolvePackageSourceDir(pkg, fromHost)
+ if (dir) {
+ resolvedSources.push(dir)
+ activatablePlugins.push(pkg)
+ } else {
+ // Unresolved plugins are reported via the dev overlay instead of
+ // being imported — a bare failing import would crash the dev
+ // server with a much less actionable error.
+ pluginErrors.push({ pkg, kind: 'unresolved' })
+ }
+ }
+ },
+
+ resolveId(id) {
+ if (id === VIRTUAL_PLUGIN_MODULE_ID) return RESOLVED_VIRTUAL_PLUGIN_MODULE_ID
+ return null
+ },
+
+ load(id) {
+ if (id !== RESOLVED_VIRTUAL_PLUGIN_MODULE_ID) return null
+ return generateVirtualPluginModule(activatablePlugins)
},
transform(code, id) {
diff --git a/packages/dashboard-core/tests/virtual-module.test.ts b/packages/dashboard-core/tests/virtual-module.test.ts
new file mode 100644
index 0000000000..ae88bd7c6c
--- /dev/null
+++ b/packages/dashboard-core/tests/virtual-module.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { generateVirtualPluginModule, VIRTUAL_PLUGIN_MODULE_ID } from '../src/vite'
+
+describe('generateVirtualPluginModule', () => {
+ it('emits one side-effect import per plugin, in order', () => {
+ const code = generateVirtualPluginModule(['@acme/reviews-plugin', 'wishlists-plugin'])
+ expect(code).toContain('import "@acme/reviews-plugin"')
+ expect(code).toContain('import "wishlists-plugin"')
+ expect(code.indexOf('@acme/reviews-plugin')).toBeLessThan(code.indexOf('wishlists-plugin'))
+ expect(code).toContain('export {}')
+ })
+
+ it('emits an empty module when no plugins are installed', () => {
+ const code = generateVirtualPluginModule([])
+ expect(code).not.toContain('import "')
+ expect(code).toContain('export {}')
+ })
+
+ it('escapes package names as string literals', () => {
+ const code = generateVirtualPluginModule(['@acme/it\'s-a-plugin"'])
+ expect(code).toContain(JSON.stringify('@acme/it\'s-a-plugin"'))
+ })
+
+ it('exposes the module id hosts import', () => {
+ expect(VIRTUAL_PLUGIN_MODULE_ID).toBe('virtual:spree-dashboard-plugins')
+ })
+})
diff --git a/packages/dashboard-plugin-example/README.md b/packages/dashboard-plugin-example/README.md
index 1130a97601..8a3a3fbd8b 100644
--- a/packages/dashboard-plugin-example/README.md
+++ b/packages/dashboard-plugin-example/README.md
@@ -31,21 +31,21 @@ For the request layer pattern (`adminClient.request<T>` against custom endpoints
## Activate this plugin in the dashboard
-In this monorepo, `@spree/dashboard` already wires the plugin up behind an env flag — no code changes needed:
+In this monorepo, the dashboard's `vite.config.ts` opts into plugin auto-discovery behind an env flag — no code changes needed:
```bash
cd packages/dashboard
VITE_EXAMPLE_PLUGIN=true pnpm dev
```
-In your own dashboard app, add a side-effect import to the entry (`packages/dashboard/src/main.tsx` for the bundled dashboard, your own `main.tsx` for a custom admin app):
+That exercises the exact path a real host uses: discovery finds this package via its `spree.dashboard.plugin` marker, and the `virtual:spree-dashboard-plugins` module imported by `main.tsx` activates it before the router mounts. Nav entry registers, `/brands` route mounts, slot widget appears on product pages, table column lands on the products table.
+
+In your own dashboard app, `pnpm add @spree/dashboard-plugin-example` and restart the dev server — same mechanism, no host-code edit. If your entry doesn't import the virtual module (custom admin apps built directly on `@spree/dashboard-core`), a plain side-effect import does the same job:
```ts
import '@spree/dashboard-plugin-example'
```
-The import must run **before the router mounts** so the route registry is populated when the catch-all dispatcher reads it. The single side-effect import triggers everything: nav entry registers, `/brands` route mounts, slot widget appears on product pages, table column lands on the products table.
-
## File layout
```
diff --git a/packages/dashboard-plugin-example/src/index.tsx b/packages/dashboard-plugin-example/src/index.tsx
index df1fac73e9..feafeb6581 100644
--- a/packages/dashboard-plugin-example/src/index.tsx
+++ b/packages/dashboard-plugin-example/src/index.tsx
@@ -20,13 +20,11 @@
* Alba serializer); this package only contains the dashboard half. See
* `README.md` for the full setup story.
*
- * To activate this plugin in the dashboard, the app's `main.tsx` imports
- * `@spree/dashboard-plugin-example` once as a side-effect (before the
- * router mounts):
- *
- * import '@spree/dashboard-plugin-example'
- *
- * That single import triggers the `defineDashboardPlugin` call below.
+ * Activation is automatic: this package declares the
+ * `spree.dashboard.plugin` marker in its package.json, so a host running
+ * `spreeDashboardPlugin()` discovers it and imports it via the
+ * `virtual:spree-dashboard-plugins` module in the app entry — which
+ * triggers the `defineDashboardPlugin` call below before first render.
*/
import { defineDashboardPlugin, defineTable, i18n } from '@spree/dashboard-core'
import { RelativeTime } from '@spree/dashboard-ui'
diff --git a/packages/dashboard/src/main.tsx b/packages/dashboard/src/main.tsx
index 50fca90455..51013c653a 100644
--- a/packages/dashboard/src/main.tsx
+++ b/packages/dashboard/src/main.tsx
@@ -12,21 +12,17 @@ import '@/i18n-setup'
import '@/nav/default'
import '@/nav/settings'
import '@/search/default'
+// Activate installed dashboard plugins. The module is synthesized by
+// `spreeDashboardPlugin()` in vite.config.ts from the auto-discovered plugin
+// list (package.json deps carrying the `spree.dashboard.plugin` marker) —
+// installing a plugin needs no edit here. Must come after '@/i18n-setup' so
+// plugins can call i18n.t at module load.
+import 'virtual:spree-dashboard-plugins'
import { AuthProvider, PermissionProvider, queryClient } from '@spree/dashboard-core'
import { ThemeProvider } from '@spree/dashboard-ui'
import { router } from '@/router'
import '@/styles.css'
-// Dev-only: run the reference plugin (packages/dashboard-plugin-example)
-// against the real shell with VITE_EXAMPLE_PLUGIN=true. Keeps the example
-// honest — its slots, routes, and table extensions render in a live
-// dashboard instead of only existing on paper. Awaited so registration
-// lands before the first render, same contract as any plugin import.
-// Statically eliminated from production builds via the DEV guard.
-if (import.meta.env.DEV && import.meta.env.VITE_EXAMPLE_PLUGIN === 'true') {
- await import('@spree/dashboard-plugin-example')
-}
-
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
diff --git a/packages/dashboard/vite.config.ts b/packages/dashboard/vite.config.ts
index cf04948c8a..49b5bd632c 100644
--- a/packages/dashboard/vite.config.ts
+++ b/packages/dashboard/vite.config.ts
@@ -8,7 +8,21 @@ export default defineConfig({
// The plugin bundles `@tailwindcss/vite`, so we don't register it separately.
// `cssEntry` defaults to `./src/styles.css`, which matches our entry — pass
// it here only as a hint for readers of this config.
- plugins: [spreeDashboardPlugin({ cssEntry: './src/styles.css' }), TanStackRouterVite(), react()],
+ //
+ // Plugin selection: hosts normally omit `plugins` so auto-discovery picks up
+ // every dep with the `spree.dashboard.plugin` marker. This monorepo copy
+ // defaults to an explicit empty whitelist because our only marked dep is the
+ // reference plugin (@spree/dashboard-plugin-example, a devDependency) —
+ // opt in with VITE_EXAMPLE_PLUGIN=true to exercise the real discovery +
+ // activation path end-to-end.
+ plugins: [
+ spreeDashboardPlugin({
+ cssEntry: './src/styles.css',
+ plugins: process.env.VITE_EXAMPLE_PLUGIN === 'true' ? undefined : [],
+ }),
+ TanStackRouterVite(),
+ react(),
+ ],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),