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 extension installs to spree add (V-3753) (#14926)

Damian Legawiece0e980e3443f
diff --git a/.changeset/cli-add-extensions.md b/.changeset/cli-add-extensions.md
new file mode 100644
index 0000000000..2b214aab9b
--- /dev/null
+++ b/.changeset/cli-add-extensions.md
@@ -0,0 +1,6 @@
+---
+"@spree/cli": minor
+"create-spree-app": patch
+---
+
+`spree add <extension>` installs an official extension in one step: Stripe, PayPal, Adyen, Avalara AvaTax, Klaviyo, EasyPost, Meilisearch, the MCP server and OpenTelemetry. It ejects a project still on the prebuilt image (after asking), adds the gem at the right version, runs the extension's installer and migrations, installs its dashboard plugin when it has one, and restarts a running server. A failed install puts the Gemfile back as it was. Extensions outside the list install with `spree add --gem <name> --npm <package>`, after a confirmation. New projects' agent instructions point coding agents at `spree add`.
diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdx
index 41eba28c56..a478bac893 100644
--- a/docs/developer/cli/quickstart.mdx
+++ b/docs/developer/cli/quickstart.mdx
@@ -132,16 +132,47 @@ See [Customizing the Backend](/developer/create-spree-app/quickstart#customizing
### `spree add`
-Add an optional part to an existing project.
+Add an optional part or an extension to an existing project.
```bash
spree add dashboard # the Admin Dashboard app in apps/dashboard/, to customize it
spree add seller-dashboard # the marketplace Seller Panel in apps/seller-dashboard/
spree add ai # Spree agent skills + the docs MCP server for coding agents
+spree add stripe # an extension, installed end to end
```
`spree add ai` installs the [Spree agent skills](/developer/agentic/agent-skills) and connects Claude Code, Cursor and VS Code to the [docs MCP server](/developer/agentic/docs-mcp). It keeps the MCP servers your config files already list and is safe to re-run. Pass `--no-skills` or `--no-mcp` to set up only one of the two.
+#### Extensions
+
+`spree add <extension>` installs an official extension in one step: it adds the gem, runs the extension's installer if it has one, runs the migrations, installs its dashboard plugin if it has one, and restarts the server if it is running.
+
+| Extension | Command |
+| --- | --- |
+| [Stripe](/integrations/payments/stripe) | `spree add stripe` |
+| [PayPal](/integrations/payments/paypal) | `spree add paypal` |
+| [Adyen](/integrations/payments/adyen) | `spree add adyen` |
+| [Avalara AvaTax](/integrations/tax/avalara) | `spree add avatax` |
+| [Klaviyo](/integrations/marketing/klaviyo) | `spree add klaviyo` |
+| [EasyPost](/integrations/shipping/easypost) | `spree add easypost` |
+| [Meilisearch](/integrations/search/meilisearch) | `spree add meilisearch` |
+| [MCP server](/developer/mcp/quick-start) | `spree add mcp` |
+| [OpenTelemetry](/developer/providers/observability) | `spree add opentelemetry` |
+
+A few things to know:
+
+- **A project on the prebuilt image is ejected first.** The prebuilt image cannot load new gems, so the command offers to [eject](#spree-eject) the project. Ejecting switches to a new development database without your current data, so it asks before doing it. Pass `--yes` to agree up front, for example in a script.
+- **New projects already include some extensions.** Stripe, EasyPost, Meilisearch and OpenTelemetry come with every new project. Until you eject, the command tells you there is nothing to install for those. After ejecting, it runs their installer and migrations again, which is harmless.
+- **It is safe to run again.** If an install fails partway, the command puts your `Gemfile` and `config/` back as they were. Running it again finishes an install that stopped halfway, and keeps files the first run created.
+- **Setup notes come from the extension.** If an extension needs anything else, such as an environment variable, it says so while it installs.
+
+To install an extension that is not in this list, name its gem or dashboard plugin package. The command asks you to confirm, since Spree does not vouch for it:
+
+```bash
+spree add --gem spree_acme_loyalty
+spree add --gem spree_acme_loyalty --npm @acme/loyalty-dashboard
+```
+
### `spree logs`
Stream service logs.
@@ -358,7 +389,7 @@ Run a `bundle` command. Gems land in the `bundle_cache` volume (no image rebuild
```bash
spree bundle install
-spree bundle add stripe
+spree bundle add faker
spree bundle update spree_core
spree bundle outdated
```
diff --git a/docs/developer/contributing/creating-an-extension.mdx b/docs/developer/contributing/creating-an-extension.mdx
index ab2cef91cc..25728ad73a 100644
--- a/docs/developer/contributing/creating-an-extension.mdx
+++ b/docs/developer/contributing/creating-an-extension.mdx
@@ -344,6 +344,17 @@ bin/rails g spree_reviews:install
The Store API now serves reviews at `/api/v3/store/reviews`, and the Admin API manages them at `/api/v3/admin/reviews`.
+Once you publish the gem, Spree projects install it with one command, which adds the gem, runs your install generator, runs the migrations and restarts the server:
+
+```bash
+spree add --gem spree_reviews
+```
+
+To work well with it:
+
+- **Make the install generator optional.** The CLI runs `spree_reviews:install` only if it exists, so the gem must work without it.
+- **Put any manual setup in the gemspec's `post_install_message`**, such as an environment variable to set. Bundler prints it during the install. Keep it short; most extensions need none.
+
## Test the extension
An extension is not a full Rails application, so its tests run against a small generated Spree application. Create it from the extension's root directory:
diff --git a/docs/developer/dashboard/plugins/distributing.mdx b/docs/developer/dashboard/plugins/distributing.mdx
index e555976fa2..ddb827390e 100644
--- a/docs/developer/dashboard/plugins/distributing.mdx
+++ b/docs/developer/dashboard/plugins/distributing.mdx
@@ -10,17 +10,31 @@ This page is the *consumer's* perspective on installing your plugin. Cover it in
A consumer installing your plugin needs to:
-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
-```
+1. **Install the npm package** into their dashboard app, then restart the dev server
+2. **Apply any backend changes** — usually adding a Rails gem and running migrations
+
+The Spree CLI does both in one command:
+
+<Tabs>
+ <Tab title="Spree CLI">
+ ```bash
+ spree add --gem your_plugin --npm @your-scope/your-plugin
+ ```
+ </Tab>
+ <Tab title="Without CLI">
+ ```bash
+ # in apps/dashboard
+ pnpm add @your-scope/your-plugin
+
+ # in server/, if your plugin has a backend
+ bundle add your_plugin
+ bin/rails generate your_plugin:install
+ bin/rails db:migrate
+ ```
+ </Tab>
+</Tabs>
+
+Leave out `--gem` for a dashboard-only plugin, or `--npm` for a backend-only one. The CLI asks the consumer to confirm, because your plugin is not in the official [extension list](/developer/cli/quickstart#extensions). It runs your install generator only if you ship one.
**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:
diff --git a/docs/developer/mcp/quick-start.mdx b/docs/developer/mcp/quick-start.mdx
index 181a4cb3ba..4e710cfbfc 100644
--- a/docs/developer/mcp/quick-start.mdx
+++ b/docs/developer/mcp/quick-start.mdx
@@ -27,7 +27,8 @@ Upgrading an older store, or deliberately removed it? Add the gem back:
</Tab>
<Tab title="Without CLI">
```ruby server/Gemfile
- gem 'spree_mcp'
+ # use the same version requirement as your `spree` gem
+ gem 'spree_mcp', '>= 6.0.0'
```
```bash
diff --git a/docs/developer/providers/observability.mdx b/docs/developer/providers/observability.mdx
index eafbae9857..f3e07ccf65 100644
--- a/docs/developer/providers/observability.mdx
+++ b/docs/developer/providers/observability.mdx
@@ -12,11 +12,21 @@ Tempo, Jaeger, Datadog, Honeycomb, New Relic, Dynatrace, and others.
## Setup
-Add the gem to your application's Gemfile:
-
-```ruby
-gem 'spree_opentelemetry'
-```
+New Spree projects include `spree_opentelemetry` already. To add it to an older project:
+
+<Tabs>
+ <Tab title="Spree CLI">
+ ```bash
+ spree add opentelemetry
+ ```
+ </Tab>
+ <Tab title="Without CLI">
+ ```ruby server/Gemfile
+ # use the same version requirement as your `spree` gem, then run `bundle install`
+ gem 'spree_opentelemetry', '>= 6.0.0'
+ ```
+ </Tab>
+</Tabs>
Then configure the exporter through the standard OpenTelemetry environment
variables:
diff --git a/docs/integrations/marketing/klaviyo.mdx b/docs/integrations/marketing/klaviyo.mdx
index 6c17f40320..2c74e65dfc 100644
--- a/docs/integrations/marketing/klaviyo.mdx
+++ b/docs/integrations/marketing/klaviyo.mdx
@@ -19,16 +19,16 @@ To install the Klaviyo integration, you need to run the following command:
<CodeGroup>
```bash Spree CLI (Docker)
-spree bundle add spree_klaviyo && spree generate spree_klaviyo:install
+spree add klaviyo
```
```bash Without Spree CLI
-bundle add spree_klaviyo && bin/rails g spree_klaviyo:install
+bundle add spree_klaviyo && bin/rails g spree_klaviyo:install && bin/rails db:migrate
```
</CodeGroup>
-After that, you need to make sure to restart the server.
+The Spree CLI also runs the migrations and restarts the server for you. Without it, restart the server yourself after the commands finish.
## Connect Klaviyo
diff --git a/docs/integrations/payments/adyen.mdx b/docs/integrations/payments/adyen.mdx
index 56e2c645fc..1fbe12076f 100644
--- a/docs/integrations/payments/adyen.mdx
+++ b/docs/integrations/payments/adyen.mdx
@@ -13,16 +13,16 @@ Before you can enable Adyen, it must be installed. To do so, you need to run the
<CodeGroup>
```bash Spree CLI (Docker)
-spree bundle add spree_adyen --github spree/spree_adyen && spree generate spree_adyen:install
+spree add adyen
```
```bash Without Spree CLI
-bundle add spree_adyen --github spree/spree_adyen && bin/rails g spree_adyen:install
+bundle add spree_adyen && bin/rails g spree_adyen:install && bin/rails db:migrate
```
</CodeGroup>
-After that, you need to make sure to restart the server.
+The Spree CLI also runs the migrations and restarts the server for you. Without it, restart the server yourself after the commands finish.
## Connect Adyen
diff --git a/docs/integrations/payments/paypal.mdx b/docs/integrations/payments/paypal.mdx
index fda8bc1075..b264387a73 100644
--- a/docs/integrations/payments/paypal.mdx
+++ b/docs/integrations/payments/paypal.mdx
@@ -13,16 +13,16 @@ Before you can enable PayPal, it must be installed. To do so, you need to run th
<CodeGroup>
```bash Spree CLI (Docker)
-spree bundle add spree_paypal_checkout && spree generate spree_paypal_checkout:install
+spree add paypal
```
```bash Without Spree CLI
-bundle add spree_paypal_checkout && bin/rails g spree_paypal_checkout:install
+bundle add spree_paypal_checkout && bin/rails g spree_paypal_checkout:install && bin/rails db:migrate
```
</CodeGroup>
-After that, you need to make sure to restart the server.
+The Spree CLI also runs the migrations and restarts the server for you. Without it, restart the server yourself after the commands finish.
## Connect PayPal
diff --git a/docs/integrations/payments/stripe.mdx b/docs/integrations/payments/stripe.mdx
index 36b6f687b6..5f8c792b96 100644
--- a/docs/integrations/payments/stripe.mdx
+++ b/docs/integrations/payments/stripe.mdx
@@ -15,16 +15,19 @@ Before you can enable Stripe, it must be installed. To do so, you need to run th
<CodeGroup>
```bash Spree CLI (Docker)
-spree bundle add spree_stripe && spree generate spree_stripe:install
+spree add stripe
```
-```bash Without Spree CLI
-bundle add spree_stripe && bin/rails g spree_stripe:install
+```ruby Without Spree CLI
+# server/Gemfile — use the same version requirement as your `spree` gem, then run `bundle install`
+gem 'spree_stripe', '>= 6.0.0'
```
</CodeGroup>
-After that, you need to make sure to restart the server.
+The Spree CLI restarts the server for you. Without it, restart the server yourself.
+
+<Note>New Spree projects include Stripe already, so you can skip this step.</Note>
## Connect Stripe
diff --git a/docs/integrations/search/meilisearch.mdx b/docs/integrations/search/meilisearch.mdx
index 9078d2cda8..60cfad9a2b 100644
--- a/docs/integrations/search/meilisearch.mdx
+++ b/docs/integrations/search/meilisearch.mdx
@@ -49,20 +49,19 @@ docker run -d --name meilisearch \
For local development, Meilisearch runs without authentication by default — no API key is needed. For production, set a master key (minimum 16 bytes) via `MEILI_MASTER_KEY` when starting Meilisearch. Use this master key as your `MEILISEARCH_API_KEY`.
</Info>
-### 2. Add the gem to your Gemfile
+### 2. Install the extension
-```ruby
-gem 'spree_meilisearch'
-```
+New Spree projects include `spree_meilisearch` already, so you can skip this step. To add it to an older project:
<CodeGroup>
```bash Spree CLI (Docker)
-spree bundle install
+spree add meilisearch
```
-```bash Without Spree CLI
-bundle install
+```ruby Without Spree CLI
+# server/Gemfile — use the same version requirement as your `spree` gem, then run `bundle install`
+gem 'spree_meilisearch', '>= 6.0.0'
```
</CodeGroup>
diff --git a/docs/integrations/shipping/easypost.mdx b/docs/integrations/shipping/easypost.mdx
index f29fdcc277..48ec73cdac 100644
--- a/docs/integrations/shipping/easypost.mdx
+++ b/docs/integrations/shipping/easypost.mdx
@@ -25,16 +25,23 @@ one price, or digital-only stores.
## Setup
-### 1. Add the gem
+### 1. Install the extension
-```ruby Gemfile
-gem 'spree_easypost'
+New Spree projects include `spree_easypost` already, so you can skip this step. To add it to an older project:
+
+<CodeGroup>
+
+```bash Spree CLI (Docker)
+spree add easypost
```
-```bash
-bundle install
+```ruby Without Spree CLI
+# server/Gemfile — use the same version requirement as your `spree` gem, then run `bundle install`
+gem 'spree_easypost', '>= 6.0.0'
```
+</CodeGroup>
+
### 2. Get an API key
Sign up at [easypost.com](https://www.easypost.com/) and copy a key from
diff --git a/docs/integrations/tax/avalara.mdx b/docs/integrations/tax/avalara.mdx
index 211fccfbd8..40aa2c152d 100644
--- a/docs/integrations/tax/avalara.mdx
+++ b/docs/integrations/tax/avalara.mdx
@@ -15,16 +15,16 @@ Before you can enable Avalara AvaTax, it must be installed. To do so, run the fo
<CodeGroup>
```bash Spree CLI (Docker)
-spree bundle add spree_avatax_official && spree generate spree_avatax_official:install
+spree add avatax
```
```bash Without Spree CLI
-bundle add spree_avatax_official && bin/rails g spree_avatax_official:install
+bundle add spree_avatax_official && bin/rails g spree_avatax_official:install && bin/rails db:migrate
```
</CodeGroup>
-After that, make sure to restart the server.
+The Spree CLI also runs the migrations and restarts the server for you. Without it, restart the server yourself after the commands finish.
## Connect Avalara
diff --git a/docs/plans/6.0-cli-add-extensions.md b/docs/plans/6.0-cli-add-extensions.md
new file mode 100644
index 0000000000..cfb9eb2b2a
--- /dev/null
+++ b/docs/plans/6.0-cli-add-extensions.md
@@ -0,0 +1,105 @@
+# Spree CLI: add extensions with one command
+
+**Status:** In Progress — building the catalog, the install steps and the documentation updates
+**Target:** Spree 6.0
+**Depends on:** `5.6-project-layout-and-dashboard.md` (`spree add`, project layout, `spree eject`)
+**Author:** Damian Legawiec (`[email protected]`)
+**Last updated:** 2026-10-19
+**Tracking:** Linear V-3753 · GitHub spree/spree#14924
+
+## Summary
+
+Installing a Spree extension today takes four commands and some Docker background: eject the project if it still runs the prebuilt image, `spree bundle add <gem>`, `spree generate <gem>:install`, `spree migrate`, then restart the server. Skip the eject and the gem silently does nothing. Extend `spree add` so `spree add paypal` does all of it, and also installs the extension's dashboard plugin when it has one. The CLI looks up what `paypal` means in a catalog of extensions shipped inside the CLI package, so the command never needs to know where an extension's code comes from. That keeps the planned move of extensions from RubyGems to npm a catalog change, not a command change.
+
+## Key Decisions (do not deviate without discussion)
+
+- **One command, `spree add`, for components and extensions.** `dashboard`, `seller-dashboard` and `ai` keep their current behaviour; any other name is looked up in the extension catalog. A separate `spree install` or `spree extension add` was rejected: users should not have to know whether the thing they want is an app, a file set or a gem.
+- **Names resolve only through the catalog.** `spree add paypal` never guesses `spree_paypal`; the real gem is `spree_paypal_checkout`, and a guessed name turns a typo into installing whatever gem happens to carry it, which is a known supply-chain attack. Extensions outside the catalog are installed with an explicit `spree add --gem <name>` (and `--npm <package>` for a dashboard plugin), which prints what it is about to install and asks first.
+- **The catalog is a JSON file shipped inside `@spree/cli`.** Its source lives in the monorepo; each CLI release bundles the current copy. No network call. That means the command works offline, stays fast, and a compromised remote file cannot change what gets installed. New first-party extensions show up with the next CLI release, and the CLI already releases often. Fetching the catalog from GitHub at runtime was rejected for now: it adds a failure mode and an attack surface to save a few days of lag.
+- **Ejecting needs the developer's consent.** Gems added to the prebuilt image are lost when the container is recreated, so a non-ejected project must eject first. Ejecting moves the app to a fresh `spree_development` database, so the command explains that and asks. `--yes` answers for non-interactive use, and a non-interactive run without `--yes` stops with an explanation.
+- **Setup messages belong to the gem.** Anything the merchant must do after installing (set an environment variable, create a payment method in the dashboard) goes in the gemspec's `post_install_message`, which Bundler prints during `bundle add`. Most gems need none. The catalog carries no per-extension help text.
+- **The install generator is optional; migrations always run.** An extension may ship `<gem>:install`. The command runs it when it exists and skips it otherwise. It then always runs `db:migrate`, which does nothing when there is nothing to migrate.
+- **Safe to run twice.** A gem already in the Gemfile skips `bundle add` but still runs the generator and migrations, so re-running repairs a half-finished install. If any step after `bundle add` fails, the command restores the Gemfile, Gemfile.lock and `config/` it started with, so a half-installed gem's initializer cannot stop the app from booting. Copied migrations are kept: one that already ran would otherwise run again on the next attempt. A repair run passes `--skip` to the install generator, keeping files the first run wrote.
+- **A gem the project already lists is reported as installed (decided 2026-10-19).** New projects already carry `spree_stripe`, `spree_meilisearch`, `spree_easypost` and `spree_opentelemetry`, and the prebuilt image contains them. On a project that has not been ejected, `spree add stripe` checks the image's own `Gemfile.lock` (not the one on disk, which may list gems added by hand since), says the gem is already part of the project and stops: no eject, no new database. On an ejected project it re-runs the install generator and migrations, to repair a half-finished install. Ejecting and repairing every time was rejected as costing the developer a fresh database for nothing.
+- **Gems released with Spree are pinned to at least the project's Spree version (decided 2026-10-19).** Catalog entries marked `"release": "spree"` (mcp, opentelemetry, stripe, meilisearch, easypost) are added as `gem '<name>', '>= <locked spree version>'`, the same shape the project Gemfile already uses for the other Spree gems. Without the pin Bundler picks an old release: RubyGems' newest stable `spree_stripe` is the 5.x line's 1.8.2. Each of these gems depends on the exact `spree_core`, so `bundle update spree` moves them together. An exact pin was rejected because every Spree upgrade would then have to edit the line by hand.
+- **The dashboard plugin step ships now (decided 2026-10-19).** The catalog's `dashboard` field and the `--npm` flag are built in this release, though none of the nine extensions has a plugin yet, so third-party plugins installed with `spree add --gem … --npm …` work today and the first first-party plugin needs only a catalog line. Accepted trade-off: the step has no first-party user yet and is covered by unit tests only.
+- **The server restarts in place (decided 2026-10-19).** When web is running, the command restarts the app containers, which starts a fresh Rails process that loads the new gem from the shared gem volume. A full stop and start was rejected as slower for no gain.
+- **Projects booted from the monorepo are out of scope.** That setup (`SPREE_PATH`) is internal Spree development only, and the command does not special-case it.
+
+## Design Details
+
+### Command surface
+
+```bash
+spree add paypal # catalog extension: gem + dashboard plugin if any
+spree add paypal --yes # also consent to ejecting, for CI and scripts
+spree add --gem acme_loyalty # an extension outside the catalog (asks first)
+spree add --gem acme_loyalty --npm @acme/loyalty-dashboard
+spree add dashboard | seller-dashboard | ai # unchanged
+```
+
+### Steps
+
+1. **Resolve** the name against the catalog, or take `--gem` / `--npm`.
+2. **Eject** if the project still runs the prebuilt image (`isEjectedProject`), after consent. Reuses the `spree eject` code.
+3. **Add the gem** with the same path `spree bundle` uses (exec into `web`, or a one-off container when it is down). Bundler prints the gem's post-install message here.
+4. **Run the install generator** when `bin/rails generate --help` lists `<gem>:install`.
+5. **Migrate** with `db:migrate`.
+6. **Install the dashboard plugin** into `apps/dashboard/` (and `apps/seller-dashboard/` when the entry says it has a seller half), when that app exists, with the project's package manager.
+7. **Restart** web and worker, only if they are running.
+
+### Catalog
+
+`packages/cli/src/extensions.json`, imported at build time. The first release supports exactly these gems:
+
+```json
+{
+ "extensions": {
+ "mcp": { "label": "MCP server", "gem": "spree_mcp", "release": "spree" },
+ "opentelemetry": { "label": "OpenTelemetry", "gem": "spree_opentelemetry", "release": "spree" },
+ "stripe": { "label": "Stripe", "gem": "spree_stripe", "release": "spree" },
+ "paypal_checkout": { "label": "PayPal", "gem": "spree_paypal_checkout", "aliases": ["paypal"] },
+ "adyen": { "label": "Adyen", "gem": "spree_adyen" },
+ "klaviyo": { "label": "Klaviyo", "gem": "spree_klaviyo" },
+ "avatax_official": { "label": "Avalara AvaTax", "gem": "spree_avatax_official", "aliases": ["avatax"] },
+ "meilisearch": { "label": "Meilisearch", "gem": "spree_meilisearch", "release": "spree" },
+ "easypost": { "label": "EasyPost", "gem": "spree_easypost", "release": "spree" }
+ }
+}
+```
+
+Three spellings resolve to an entry: its key (the gem name without `spree_`), any of its `aliases`, and the full gem name. So `spree add paypal`, `spree add paypal_checkout` and `spree add spree_paypal_checkout` all install the same gem. An alias may not repeat another entry's key, alias or gem name, or the name of a built-in component (`dashboard`, `seller-dashboard`, `ai`); a Vitest spec enforces this. An unknown name lists the supported extensions and points at `--gem`.
+
+`"release": "spree"` marks a gem released together with Spree, which is pinned to at least the project's Spree version. An optional `dashboard` names the npm package of the extension's dashboard plugin (and `sellerDashboard` its seller panel plugin). An entry without `dashboard` installs only the gem; none of the first nine ships a dashboard plugin yet. An entry names where each part comes from and nothing about how to install it; the generator and migrations are discovered, not declared. When extensions move to npm, an entry changes from `"gem": "spree_paypal_checkout"` to an npm source, and only the step that adds the gem learns the new source.
+
+`spree add mcp` installs the store's own MCP server (`spree_mcp`). It is unrelated to `spree add ai`, which connects coding agents to the Spree documentation MCP server; the closing message of each says which one it set up.
+
+### Extension author contract
+
+Documented in `docs/developer/contributing/creating-an-extension.mdx`:
+
+- Optionally ship `<gem_name>:install`; never require it for the gem to work.
+- Ship migrations in the engine. The generator copies them, or the engine adds its migration path.
+- Put any manual setup in `post_install_message`, and keep it short.
+
+## Migration Path
+
+1. Add the catalog, the resolver and the steps to `spree add`, with Vitest coverage for resolution, consent and rollback.
+2. Add the nine catalog entries above, with the `paypal` and `avatax` aliases.
+3. Replace the manual four-step recipe in the server template's `AGENTS.md` ("Extensions") and in the CLI docs with `spree add <extension>`.
+4. Have `spree plugin new` print the matching `spree add --gem … --npm …` line, so plugin authors see how their users will install the plugin.
+
+## Constraints on Current Work
+
+- New first-party extension gems must work without running an install generator, and must put manual setup steps in `post_install_message`.
+- Don't add new `spree add <name>` special cases in `add.ts` for gems. Extensions go in the catalog.
+
+## Open Questions
+
+- `spree remove <extension>`: wanted eventually; the catalog makes it straightforward, but rolling back migrations safely needs its own design.
+
+## References
+
+- `docs/plans/5.6-project-layout-and-dashboard.md` — `spree add`, `spree eject`, project layout
+- `packages/cli/src/commands/add.ts`, `bundle.ts`, `eject.ts`, `restart.ts`
+- `spree/providers/stripe/lib/generators/spree_stripe/install/install_generator.rb` — an install generator that does nothing, which the step skipping must tolerate
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 216c2e1b83..3f0e38f164 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -6434,3 +6434,23 @@ relaxation.
The registry was split by surface during the 6.0 build for exactly this —
`Spree.store_agent_tools` exists and is empty, and a tool filed on the wrong
surface is refused at registration.
+
+## 2026-10-19 — `spree add` installs extensions from a catalog shipped with the CLI
+
+`spree add paypal` will eject (with consent), add the gem, run its install
+generator if it has one, migrate, install any dashboard plugin and restart a
+running server (`docs/plans/6.0-cli-add-extensions.md`). Names resolve only
+through a JSON catalog bundled in `@spree/cli`, never by guessing a gem name,
+because a guessed name turns a typo into installing a stranger's gem. The
+catalog ships with the CLI rather than being fetched, so the command works
+offline and a remote file cannot change what gets installed. Setup notes live
+in each gem's `post_install_message`, not in the CLI.
+
+## 2026-10-19 — Extensions released with Spree are pinned to the project's Spree version
+
+`spree add` adds the gems that ship from this repository (`spree_stripe`,
+`spree_meilisearch`, `spree_easypost`, `spree_opentelemetry`, `spree_mcp`) as
+`>= <locked spree version>`. An unpinned `bundle add spree_stripe` resolves to
+the 5.x line's 1.8.2, the newest stable release on RubyGems. A gem a project
+already lists is reported as installed rather than ejecting the project to
+re-add it.
diff --git a/packages/cli/src/commands/add-extension.ts b/packages/cli/src/commands/add-extension.ts
new file mode 100644
index 0000000000..019e47dd10
--- /dev/null
+++ b/packages/cli/src/commands/add-extension.ts
@@ -0,0 +1,198 @@
+import fs from 'node:fs'
+import path from 'node:path'
+import * as p from '@clack/prompts'
+import { execa } from 'execa'
+import pc from 'picocolors'
+import { findApiDir, isEjectedProject } from '../context.js'
+import { dockerComposeCapture, dockerComposeExecOrRun, restartAppServices } from '../docker.js'
+import {
+ type Extension,
+ gemfileDeclares,
+ lockedSpreeVersion,
+ lockfileIncludes,
+ snapshotInstallFiles,
+} from '../lib/extensions.js'
+import { confirmOrExit } from '../lib/prompt.js'
+import type { ProjectContext } from '../types.js'
+import { detectPackageManager } from './add.js'
+import { ejectProject } from './eject.js'
+
+export interface AddExtensionOptions {
+ /** Agree to every confirmation: ejecting, and installing outside the catalog. */
+ yes: boolean
+}
+
+// `dir` is both the folder under apps/ and the `spree add` name that creates it.
+const PLUGIN_TARGETS = [
+ { field: 'dashboard', dir: 'dashboard' },
+ { field: 'sellerDashboard', dir: 'seller-dashboard' },
+] as const
+
+/**
+ * Install an extension end to end: eject a project still on the prebuilt
+ * image, add the gem, run its install generator when it has one, migrate,
+ * install its dashboard plugins, and restart a running server.
+ *
+ * Safe to re-run. A gem the Gemfile already lists is not added again; on an
+ * ejected project its generator (keeping files that exist) and migrations run
+ * again to repair a half-finished install. If a step after `bundle add`
+ * fails, the Gemfile, its lock and `config/` are put back as they were.
+ */
+export async function addExtension(
+ ctx: ProjectContext,
+ extension: Extension,
+ opts: AddExtensionOptions,
+): Promise<void> {
+ const gemChanged = extension.gem ? await installGem(ctx, extension.gem, extension, opts) : false
+ const pluginsAdded = await installPlugins(ctx, extension)
+
+ if (gemChanged)
+ await restartAppServices(ctx.projectDir, 'Restarting the server to load the new gem')
+ if (pluginsAdded) {
+ p.log.info(`Restart ${pc.bold('spree dev')} so the dashboard picks up the new plugin.`)
+ }
+}
+
+/** @return whether the gem was installed or repaired, so the server needs a restart */
+async function installGem(
+ ctx: ProjectContext,
+ gem: string,
+ extension: Extension,
+ opts: AddExtensionOptions,
+): Promise<boolean> {
+ const apiDir = findApiDir(ctx.projectDir)
+ const apiPath = path.join(ctx.projectDir, apiDir)
+ const gemfilePath = path.join(apiPath, 'Gemfile')
+ if (!fs.existsSync(gemfilePath)) {
+ p.cancel(`No ${apiDir}/Gemfile found.`)
+ process.exit(1)
+ }
+
+ if (!isEjectedProject(ctx.projectDir)) {
+ // What the prebuilt image runs is its own Gemfile.lock, not the one on
+ // disk, which may list gems added by hand since.
+ const imageLockfile = await dockerComposeCapture(['cat', 'Gemfile.lock'], ctx.projectDir)
+ if (lockfileIncludes(imageLockfile, gem)) {
+ p.log.info(`${pc.bold(gem)} is already part of this project. Nothing to install.`)
+ return false
+ }
+
+ await confirmOrExit(
+ [
+ `This project runs the prebuilt Spree image, which cannot load new gems.`,
+ `Installing ${extension.label} ejects it first: the Rails app is then built from`,
+ `./${apiDir}, with a new development database that does not have your current data.`,
+ 'Eject now?',
+ ].join('\n'),
+ opts.yes,
+ )
+ try {
+ await ejectProject(ctx.projectDir)
+ } catch (error) {
+ p.cancel(
+ `Ejecting failed, so ${extension.label} was not installed. Fix the problem above, run ${pc.bold('spree eject')}, then run this command again. ${error instanceof Error ? error.message : String(error)}`,
+ )
+ process.exit(1)
+ }
+ }
+
+ const listed = gemfileDeclares(fs.readFileSync(gemfilePath, 'utf-8'), gem)
+ // A repair adds nothing, so there is nothing to roll back.
+ const restore = listed ? undefined : snapshotInstallFiles(apiPath)
+ try {
+ if (!listed) await bundleAdd(ctx.projectDir, apiPath, gem, extension.release)
+ await runInstallGenerator(ctx.projectDir, gem, listed)
+ p.log.step('Running migrations...')
+ await dockerComposeExecOrRun(
+ ['bin/rails', 'spree:install:migrations', 'db:migrate'],
+ ctx.projectDir,
+ )
+ } catch (error) {
+ if (restore) {
+ restore()
+ p.log.warn(
+ `Put ${apiDir}/Gemfile, Gemfile.lock and config/ back as they were. Copied migrations were kept so running this command again picks up where it stopped; check ${pc.bold('git status')} for anything else the installer wrote.`,
+ )
+ }
+ p.cancel(
+ `Could not install ${extension.label}. ${error instanceof Error ? error.message : String(error)}`,
+ )
+ process.exit(1)
+ }
+
+ p.log.success(
+ listed
+ ? `${pc.bold(gem)} was already in the Gemfile; ran its installer and migrations again.`
+ : `${pc.bold(gem)} installed.`,
+ )
+ return true
+}
+
+async function bundleAdd(
+ projectDir: string,
+ apiPath: string,
+ gem: string,
+ release: Extension['release'],
+): Promise<void> {
+ const args = ['bundle', 'add', gem]
+ // Unpinned, Bundler picks the newest stable release, which for a gem that
+ // moved into Spree is its old pre-6.0 line.
+ if (release === 'spree') {
+ const lockfile = path.join(apiPath, 'Gemfile.lock')
+ const version = fs.existsSync(lockfile)
+ ? lockedSpreeVersion(fs.readFileSync(lockfile, 'utf-8'))
+ : undefined
+ if (!version) throw new Error("Could not read the project's Spree version from Gemfile.lock.")
+ args.push('--version', `>= ${version}`)
+ }
+ p.log.step(`Adding ${pc.bold(gem)}...`)
+ await dockerComposeExecOrRun(args, projectDir)
+}
+
+// An install generator is optional — many gems register themselves from their
+// engine and have nothing to copy into the app.
+async function runInstallGenerator(
+ projectDir: string,
+ gem: string,
+ keepExisting: boolean,
+): Promise<void> {
+ const generator = `${gem}:install`
+ const help = await dockerComposeCapture(['bin/rails', 'generate', '--help'], projectDir)
+ const listed = help.split('\n').some((line) => line.trim() === generator)
+ if (!listed) return
+
+ p.log.step(`Running ${pc.bold(generator)}...`)
+ // On a repair, files the first run wrote (and the developer may have
+ // edited) are kept rather than stopping at Thor's overwrite prompt.
+ const args = ['bin/rails', 'generate', generator, ...(keepExisting ? ['--skip'] : [])]
+ await dockerComposeExecOrRun(args, projectDir)
+}
+
+/** @return whether any plugin was installed */
+async function installPlugins(ctx: ProjectContext, extension: Extension): Promise<boolean> {
+ let installed = false
+ for (const target of PLUGIN_TARGETS) {
+ const pkg = extension[target.field]
+ if (!pkg) continue
+
+ const appDir = path.join(ctx.projectDir, 'apps', target.dir)
+ if (!fs.existsSync(path.join(appDir, 'package.json'))) {
+ p.log.warn(
+ `Skipped ${pc.bold(pkg)}: this project has no apps/${target.dir}/. Add it with ${pc.bold(`spree add ${target.dir}`)}, then run this command again.`,
+ )
+ continue
+ }
+
+ const pm = detectPackageManager(ctx.projectDir, appDir)
+ p.log.step(`Adding ${pc.bold(pkg)} to apps/${target.dir}/...`)
+ try {
+ await execa(pm, [pm === 'npm' ? 'install' : 'add', pkg], { cwd: appDir, stdio: 'inherit' })
+ installed = true
+ } catch (error) {
+ p.log.warn(
+ `Could not add ${pkg}; add it by hand in apps/${target.dir}/. ${error instanceof Error ? error.message : String(error)}`,
+ )
+ }
+ }
+ return installed
+}
diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts
index 2fe8a57cfb..4fb047ade8 100644
--- a/packages/cli/src/commands/add.ts
+++ b/packages/cli/src/commands/add.ts
@@ -15,7 +15,16 @@ import {
dlxCommand,
installAgentSkills,
} from '../lib/ai.js'
+import {
+ EXTENSIONS,
+ extensionNames,
+ isValidGemName,
+ isValidNpmName,
+ resolveExtension,
+} from '../lib/extensions.js'
+import { confirmOrExit } from '../lib/prompt.js'
import type { ProjectContext } from '../types.js'
+import { type AddExtensionOptions, addExtension } from './add-extension.js'
/**
* The two admin SPAs `spree add` can scaffold. They differ only in where they
@@ -71,14 +80,21 @@ interface AddAiOptions {
quiet?: boolean
}
-// `spree add <thing>` — bolt an optional component onto an existing project.
-// Dashboard, seller panel and the AI coding agent setup for now; storefront
-// parity is planned (see docs/plans/5.6-project-layout-and-dashboard.md).
+// `spree add <thing>` — bolt an optional component or an extension onto an
+// existing project. Components (dashboard, seller panel, AI coding agent
+// setup) are built in; extensions come from the catalog in extensions.json
+// (see docs/plans/6.0-cli-add-extensions.md).
export function registerAddCommand(program: Command) {
program
.command('add')
- .description('Add an optional component to your project')
- .argument('<thing>', 'Component to add: dashboard, seller-dashboard or ai')
+ .description('Add an optional component or an extension to your project')
+ .argument(
+ '[thing]',
+ `Component (dashboard, seller-dashboard, ai) or extension (${extensionNames().join(', ')})`,
+ )
+ .option('--gem <name>', 'Install a gem that is not in the extension catalog')
+ .option('--npm <package>', 'Install a dashboard plugin that is not in the extension catalog')
+ .option('-y, --yes', 'Agree to ejecting the project and to installing outside the catalog')
.option(
'--template <src>',
'Starter template: git URL or local path (default: the template bundled with the CLI; env SPREE_DASHBOARD_TEMPLATE / SPREE_SELLER_DASHBOARD_TEMPLATE overrides)',
@@ -89,15 +105,25 @@ export function registerAddCommand(program: Command) {
.option('--quiet', 'Skip the final summary note (for wrapping tools that print their own)')
.action(
async (
- thing: string,
+ thing: string | undefined,
flags: {
template?: string
install: boolean
skills: boolean
mcp: boolean
quiet?: boolean
+ gem?: string
+ npm?: string
+ yes?: boolean
},
) => {
+ if (flags.gem || flags.npm) {
+ if (thing) usageError('Pass either a name or --gem/--npm, not both.')
+ await addUncataloguedExtension(flags.gem, flags.npm, { yes: Boolean(flags.yes) })
+ return
+ }
+ if (!thing) usageError('Name a component or an extension to add.')
+
if (thing === 'ai') {
if (!flags.quiet) p.intro(pc.bgCyan(pc.black(' Spree AI coding agents ')))
const ready = await addAi(detectProject(), flags)
@@ -106,12 +132,23 @@ export function registerAddCommand(program: Command) {
return
}
- const app = APPS[thing]
+ const app = Object.hasOwn(APPS, thing) ? APPS[thing] : undefined
if (!app) {
- console.error(
- `\n${pc.red('Error:')} Unknown component: ${thing}. Try: ${[...Object.keys(APPS), 'ai'].join(', ')}\n`,
- )
- process.exit(2)
+ const extension = resolveExtension(thing)
+ if (!extension) {
+ usageError(
+ [
+ `Unknown component or extension: ${thing}.`,
+ `Components: ${[...Object.keys(APPS), 'ai'].join(', ')}`,
+ `Extensions: ${extensionNames().join(', ')}`,
+ `For a gem that is not listed, use ${pc.bold('spree add --gem <name>')}.`,
+ ].join('\n'),
+ )
+ }
+ p.intro(pc.bgCyan(pc.black(` Spree ${extension.label} `)))
+ await addExtension(detectProject(), extension, { yes: Boolean(flags.yes) })
+ p.outro('Done!')
+ return
}
p.intro(pc.bgCyan(pc.black(` Spree ${app.label} `)))
@@ -127,6 +164,45 @@ export function registerAddCommand(program: Command) {
)
}
+function usageError(message: string): never {
+ console.error(`\n${pc.red('Error:')} ${message}\n`)
+ process.exit(2)
+}
+
+/**
+ * Install a gem or dashboard plugin named on the command line rather than
+ * through the catalog. Names are checked so neither can be read as a flag,
+ * and the developer confirms, since nothing vouches for the package.
+ */
+async function addUncataloguedExtension(
+ gem: string | undefined,
+ npm: string | undefined,
+ opts: AddExtensionOptions,
+): Promise<void> {
+ if (gem && !isValidGemName(gem)) usageError(`Not a valid gem name: ${gem}`)
+ if (npm && !isValidNpmName(npm)) usageError(`Not a valid npm package name: ${npm}`)
+
+ // An official gem named with --gem still installs as the catalog says
+ // (pinned to the Spree version where it is released with Spree).
+ const catalogued = Object.values(EXTENSIONS).find((entry) => entry.gem === gem)
+ const uncatalogued = [catalogued ? undefined : gem, npm].filter(Boolean)
+ const label = catalogued?.label ?? uncatalogued.join(' and ')
+
+ p.intro(pc.bgCyan(pc.black(` ${label} `)))
+ if (uncatalogued.length > 0) {
+ await confirmOrExit(
+ `${uncatalogued.join(' and ')} ${uncatalogued.length > 1 ? 'are' : 'is'} not in the Spree extension catalog. Install anyway?`,
+ opts.yes,
+ )
+ }
+ await addExtension(
+ detectProject(),
+ { ...catalogued, label, gem, dashboard: npm ?? catalogued?.dashboard },
+ opts,
+ )
+ p.outro('Done!')
+}
+
/**
* Set a project up for AI coding agents: connect each agent to the Spree docs
* MCP server, point the agent instructions at it, and install the Spree agent
diff --git a/packages/cli/src/commands/eject.ts b/packages/cli/src/commands/eject.ts
index 0b303274ee..0bd2bb4697 100644
--- a/packages/cli/src/commands/eject.ts
+++ b/packages/cli/src/commands/eject.ts
@@ -18,70 +18,76 @@ export function registerEjectCommand(program: Command) {
.command('eject')
.description('Switch to the dev compose: bind-mount the Rails app with hot reload')
.action(async () => {
- const ctx = detectProject()
+ await ejectProject(detectProject().projectDir)
+ })
+}
- const apiDir = findApiDir(ctx.projectDir)
- const apiPath = path.join(ctx.projectDir, apiDir)
- if (!fs.existsSync(apiPath)) {
- console.error(`\n${pc.red('Error:')} No ${apiDir}/ directory found.\n`)
- process.exit(1)
- }
+/**
+ * Swap in the dev compose, prepare its database and start the stack. Exits the
+ * process when the project has no API directory or no dev compose to eject to.
+ */
+export async function ejectProject(projectDir: string): Promise<void> {
+ const apiDir = findApiDir(projectDir)
+ const apiPath = path.join(projectDir, apiDir)
+ if (!fs.existsSync(apiPath)) {
+ console.error(`\n${pc.red('Error:')} No ${apiDir}/ directory found.\n`)
+ process.exit(1)
+ }
- const devCompose = path.join(ctx.projectDir, 'docker-compose.dev.yml')
- if (!fs.existsSync(devCompose)) {
- console.error(`\n${pc.red('Error:')} No docker-compose.dev.yml found.\n`)
- process.exit(1)
- }
+ const devCompose = path.join(projectDir, 'docker-compose.dev.yml')
+ if (!fs.existsSync(devCompose)) {
+ console.error(`\n${pc.red('Error:')} No docker-compose.dev.yml found.\n`)
+ process.exit(1)
+ }
- // Replace docker-compose.yml with the dev version.
- //
- // Projects scaffolded before create-spree-app 1.0.3 shipped a dev
- // compose that bind-mounts the project root (`.:/rails`) instead of
- // the API directory — rewrite it so the container finds bin/rails.
- let composeContent = fs.readFileSync(devCompose, 'utf-8')
- if (composeContent.includes('- .:/rails')) {
- composeContent = composeContent.replace('- .:/rails', `- ./${apiDir}:/rails`)
- fs.writeFileSync(devCompose, composeContent)
- }
- // Older dev composes check postgres over the unix socket, which the
- // image's temporary init server also answers on a brand-new volume —
- // so dependants started against a server that was about to restart.
- // Only the real server listens on TCP.
- if (composeContent.includes('test: pg_isready -U postgres')) {
- composeContent = composeContent.replace(
- 'test: pg_isready -U postgres',
- 'test: pg_isready -h 127.0.0.1 -U postgres',
- )
- fs.writeFileSync(devCompose, composeContent)
- }
- fs.writeFileSync(path.join(ctx.projectDir, 'docker-compose.yml'), composeContent)
+ // Replace docker-compose.yml with the dev version.
+ //
+ // Projects scaffolded before create-spree-app 1.0.3 shipped a dev
+ // compose that bind-mounts the project root (`.:/rails`) instead of
+ // the API directory — rewrite it so the container finds bin/rails.
+ let composeContent = fs.readFileSync(devCompose, 'utf-8')
+ if (composeContent.includes('- .:/rails')) {
+ composeContent = composeContent.replace('- .:/rails', `- ./${apiDir}:/rails`)
+ fs.writeFileSync(devCompose, composeContent)
+ }
+ // Older dev composes check postgres over the unix socket, which the
+ // image's temporary init server also answers on a brand-new volume —
+ // so dependants started against a server that was about to restart.
+ // Only the real server listens on TCP.
+ if (composeContent.includes('test: pg_isready -U postgres')) {
+ composeContent = composeContent.replace(
+ 'test: pg_isready -U postgres',
+ 'test: pg_isready -h 127.0.0.1 -U postgres',
+ )
+ fs.writeFileSync(devCompose, composeContent)
+ }
+ fs.writeFileSync(path.join(projectDir, 'docker-compose.yml'), composeContent)
- console.log(`\n${pc.bold(`Switching to dev compose (bind-mounts ./${apiDir})...`)}\n`)
+ console.log(`\n${pc.bold(`Switching to dev compose (bind-mounts ./${apiDir})...`)}\n`)
- // The dev environment uses its own spree_development database, and the
- // app server exits when it is missing — create and migrate it first.
- // The dev compose has `build:` defined, so this first `run` also builds
- // the image — no separate explicit build step needed.
- console.log(`${pc.bold('Preparing the development database...')}\n`)
- await prepareDatabase(ctx.projectDir, { stdio: 'inherit' })
+ // The dev environment uses its own spree_development database, and the
+ // app server exits when it is missing — create and migrate it first.
+ // The dev compose has `build:` defined, so this first `run` also builds
+ // the image — no separate explicit build step needed.
+ console.log(`${pc.bold('Preparing the development database...')}\n`)
+ await prepareDatabase(projectDir, { stdio: 'inherit' })
- await dockerCompose(['up', '-d'], ctx.projectDir, { stdio: 'inherit' })
+ await dockerCompose(['up', '-d'], projectDir, { stdio: 'inherit' })
- p.note(
- [
- `The Rails API is now bind-mounted from ${pc.bold(`./${apiDir}`)} — edits are live.`,
- '',
- `The dev stack uses its own ${pc.bold('spree_development')} database (just`,
- `created and seeded). Load demo products with ${pc.bold('spree sample-data')}.`,
- '',
- 'You can now customize:',
- ` ${pc.dim(`${apiDir}/app/`)} — models, controllers, services (instant reload)`,
- ` ${pc.dim(`${apiDir}/config/`)} — Rails configuration (instant reload)`,
- ` ${pc.dim(`${apiDir}/Gemfile`)} — add gems via ${pc.bold('spree bundle add <gem>')}`,
- '',
- `Rebuild only on Dockerfile / .ruby-version changes: ${pc.bold('spree build')}`,
- ].join('\n'),
- 'Ejected!',
- )
- })
+ p.note(
+ [
+ `The Rails API is now bind-mounted from ${pc.bold(`./${apiDir}`)} — edits are live.`,
+ '',
+ `The dev stack uses its own ${pc.bold('spree_development')} database (just`,
+ `created and seeded). Load demo products with ${pc.bold('spree sample-data')}.`,
+ '',
+ 'You can now customize:',
+ ` ${pc.dim(`${apiDir}/app/`)} — models, controllers, services (instant reload)`,
+ ` ${pc.dim(`${apiDir}/config/`)} — Rails configuration (instant reload)`,
+ ` ${pc.dim(`${apiDir}/Gemfile`)} — add gems via ${pc.bold('spree bundle add <gem>')}`,
+ '',
+ `Rebuild only on Dockerfile / .ruby-version changes: ${pc.bold('spree build')}`,
+ ].join('\n'),
+ 'Ejected!',
+ )
}
diff --git a/packages/cli/src/commands/plugin.ts b/packages/cli/src/commands/plugin.ts
index 94538dba63..97c443353a 100644
--- a/packages/cli/src/commands/plugin.ts
+++ b/packages/cli/src/commands/plugin.ts
@@ -473,6 +473,15 @@ function printNextSteps(answers: Answers, dst: string, installed: boolean): void
` See ${pc.cyan('https://spreecommerce.org/docs/developer/contributing/creating-an-extension')}`,
)
}
+ const installArgs = [
+ ...(answers.includeEngine ? ['--gem', answers.rubyName] : []),
+ ...(answers.includeDashboard ? ['--npm', buildVars(answers).npm_dashboard_package] : []),
+ ]
+ if (installArgs.length > 0) {
+ lines.push('')
+ lines.push(pc.bold('Installing it in a Spree project, once published'))
+ lines.push(` ${pc.cyan(['spree add', ...installArgs].join(' '))}`)
+ }
lines.push('')
p.note(lines.join('\n'), 'Your plugin is scaffolded.')
}
diff --git a/packages/cli/src/commands/restart.ts b/packages/cli/src/commands/restart.ts
index 29f0789232..9d75edad29 100644
--- a/packages/cli/src/commands/restart.ts
+++ b/packages/cli/src/commands/restart.ts
@@ -6,7 +6,7 @@ import { appServices, dockerCompose } from '../docker.js'
export function registerRestartCommand(program: Command): void {
program
.command('restart')
- .description('Restart web + worker in place (does not reload Gemfile or compose changes)')
+ .description('Restart web + worker in place (does not apply compose changes)')
.action(async () => {
const ctx = detectProject()
diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts
index 389cdd9734..ac45150a81 100644
--- a/packages/cli/src/commands/upgrade.ts
+++ b/packages/cli/src/commands/upgrade.ts
@@ -6,12 +6,12 @@ import { execa } from 'execa'
import pc from 'picocolors'
import { detectProject, hasMonorepoSpreePath, isEjectedProject } from '../context.js'
import {
- appServices,
dockerCompose,
dockerComposeCapture,
dockerComposeExecOrRun,
isServiceRunning,
primeBundleVolume,
+ restartAppServices,
} from '../docker.js'
import { APP_DIRS, detectPackageManager, generateRouteTree } from './add.js'
@@ -81,7 +81,9 @@ async function upgrade(flags: UpgradeFlags): Promise<void> {
await updateSpreePackages(ctx.projectDir, flags)
await runMigrate(ctx.projectDir, flags)
await runRakeUpgrade(ctx.projectDir, flags)
- if (gemsUpdated) await restartAppServices(ctx.projectDir)
+ // Puma loaded the old gems at boot; the rake steps ran in fresh processes.
+ if (gemsUpdated)
+ await restartAppServices(ctx.projectDir, 'Restarting the app to load the updated gems')
} else {
const imagePulled = await pullImage(ctx.projectDir, flags)
await updateSpreePackages(ctx.projectDir, flags)
@@ -124,16 +126,6 @@ async function recreateContainers(projectDir: string): Promise<void> {
await dockerCompose(['up', '-d', '--wait'], projectDir, { stdio: 'inherit' })
}
-// Puma loaded the old gems at boot; the rake steps ran in fresh processes,
-// but the server itself only picks up the bumped gems on restart.
-async function restartAppServices(projectDir: string): Promise<void> {
- if (!(await isServiceRunning('web', projectDir))) return
- p.log.step(pc.bold('Restarting the app to load the updated gems'))
- await dockerCompose(['restart', ...(await appServices(projectDir))], projectDir, {
- stdio: 'inherit',
- })
-}
-
// Upgrade migrates the DB and runs spree:upgrade rake against the project's
// REAL Postgres + warm bundle_cache. A one-off `compose run` reaches the same
// named volumes (`run`'s depends_on cold-starts postgres, like db:reset), so
diff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.ts
index c92feb8e62..56359f7382 100644
--- a/packages/cli/src/docker.ts
+++ b/packages/cli/src/docker.ts
@@ -75,6 +75,19 @@ export async function appServices(projectDir: string): Promise<string[]> {
}
}
+/**
+ * Restart the app services in place when web is running, so a new Puma
+ * process loads gems installed or updated since it booted. A stopped stack is
+ * left stopped.
+ */
+export async function restartAppServices(projectDir: string, message: string): Promise<void> {
+ if (!(await isServiceRunning('web', projectDir))) return
+ p.log.step(pc.bold(message))
+ await dockerCompose(['restart', ...(await appServices(projectDir))], projectDir, {
+ stdio: 'inherit',
+ })
+}
+
/**
* Whether compose has ever created a container (any state, including exited)
* for this project.
diff --git a/packages/cli/src/extensions.json b/packages/cli/src/extensions.json
new file mode 100644
index 0000000000..506c005cd7
--- /dev/null
+++ b/packages/cli/src/extensions.json
@@ -0,0 +1,17 @@
+{
+ "extensions": {
+ "mcp": { "label": "MCP server", "gem": "spree_mcp", "release": "spree" },
+ "opentelemetry": { "label": "OpenTelemetry", "gem": "spree_opentelemetry", "release": "spree" },
+ "stripe": { "label": "Stripe", "gem": "spree_stripe", "release": "spree" },
+ "paypal_checkout": { "label": "PayPal", "gem": "spree_paypal_checkout", "aliases": ["paypal"] },
+ "adyen": { "label": "Adyen", "gem": "spree_adyen" },
+ "klaviyo": { "label": "Klaviyo", "gem": "spree_klaviyo" },
+ "avatax_official": {
+ "label": "Avalara AvaTax",
+ "gem": "spree_avatax_official",
+ "aliases": ["avatax"]
+ },
+ "meilisearch": { "label": "Meilisearch", "gem": "spree_meilisearch", "release": "spree" },
+ "easypost": { "label": "EasyPost", "gem": "spree_easypost", "release": "spree" }
+ }
+}
diff --git a/packages/cli/src/lib/extensions.ts b/packages/cli/src/lib/extensions.ts
new file mode 100644
index 0000000000..91ad32d417
--- /dev/null
+++ b/packages/cli/src/lib/extensions.ts
@@ -0,0 +1,119 @@
+import fs from 'node:fs'
+import path from 'node:path'
+import catalog from '../extensions.json' with { type: 'json' }
+
+/**
+ * One installable extension: a Rails gem, a dashboard plugin, or both. Catalog
+ * entries and `spree add --gem … --npm …` both resolve to this shape, so the
+ * install steps never care where an extension was named.
+ */
+export interface Extension {
+ /** Human name used in prompts and messages. */
+ label: string
+ gem?: string
+ /** `spree` — released with Spree, so pinned to the project's Spree version. */
+ release?: 'spree'
+ /** npm package of the Admin Dashboard plugin. */
+ dashboard?: string
+ /** npm package of the Seller Panel plugin. */
+ sellerDashboard?: string
+}
+
+interface CatalogEntry extends Extension {
+ gem: string
+ aliases?: string[]
+}
+
+export const EXTENSIONS: Record<string, CatalogEntry> = catalog.extensions as Record<
+ string,
+ CatalogEntry
+>
+
+// RubyGems and npm naming rules, narrowed to what can never be read as a
+// command-line flag or a path.
+const GEM_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
+const NPM_NAME = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
+
+export function isValidGemName(name: string): boolean {
+ return GEM_NAME.test(name)
+}
+
+export function isValidNpmName(name: string): boolean {
+ return NPM_NAME.test(name)
+}
+
+/**
+ * The catalog entry a user-typed name refers to: its key, one of its aliases,
+ * or its full gem name. Never guesses — an unknown name is `undefined`, never
+ * `spree_<name>`, so a typo cannot install a stranger's gem.
+ */
+export function resolveExtension(name: string): CatalogEntry | undefined {
+ const wanted = name.trim().toLowerCase().replaceAll('-', '_')
+ return Object.entries(EXTENSIONS).find(
+ ([key, entry]) => key === wanted || entry.gem === wanted || entry.aliases?.includes(wanted),
+ )?.[1]
+}
+
+/** The shortest name of every catalog entry (`paypal`, not `paypal_checkout`), for help and errors. */
+export function extensionNames(): string[] {
+ return Object.entries(EXTENSIONS).map(([key, entry]) => entry.aliases?.[0] ?? key)
+}
+
+/** Whether the Gemfile already declares the gem (commented-out lines don't count). */
+export function gemfileDeclares(gemfile: string, gem: string): boolean {
+ const escaped = gem.replaceAll('.', '\\.')
+ return new RegExp(`^\\s*gem\\s+['"]${escaped}['"]`, 'm').test(gemfile)
+}
+
+/** Whether Bundler resolved the gem, according to a `Gemfile.lock`. */
+export function lockfileIncludes(lockfile: string, gem: string): boolean {
+ return lockfile.split('\n').some((line) => line.startsWith(` ${gem} (`))
+}
+
+/** The Spree version Bundler resolved, read from `Gemfile.lock`. */
+export function lockedSpreeVersion(lockfile: string): string | undefined {
+ return lockfile.match(/^ {4}spree_core \(([^)]+)\)\r?$/m)?.[1]
+}
+
+// Where `bundle add` and install generators write. Copied migrations are left
+// alone: once one has run, deleting its file would make the next attempt run
+// it again, while keeping it lets `spree:install:migrations` skip it.
+const INSTALL_TARGETS = ['Gemfile', 'Gemfile.lock', 'config']
+
+/**
+ * Snapshot of everything an install writes to, taken before `bundle add` so a
+ * failed install can put the app back as it was: changed files are rewritten
+ * and files the install created are deleted.
+ */
+export function snapshotInstallFiles(apiPath: string): () => void {
+ const currentFiles = () =>
+ INSTALL_TARGETS.flatMap((target) => listFiles(path.join(apiPath, target)))
+ const before = new Map(currentFiles().map((file) => [file, fs.readFileSync(file)]))
+ return () => {
+ for (const file of currentFiles()) {
+ const content = before.get(file)
+ if (!content) fs.rmSync(file)
+ else if (!content.equals(fs.readFileSync(file))) fs.writeFileSync(file, content)
+ }
+ // A file the install deleted outright is missing from currentFiles().
+ for (const [file, content] of before) {
+ if (fs.existsSync(file)) continue
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, content)
+ }
+ }
+}
+
+function listFiles(target: string): string[] {
+ if (!fs.existsSync(target)) return []
+ if (!fs.statSync(target).isDirectory()) return [target]
+ return fs
+ .readdirSync(target, { withFileTypes: true })
+ .flatMap((entry) =>
+ entry.isDirectory()
+ ? listFiles(path.join(target, entry.name))
+ : entry.isFile()
+ ? [path.join(target, entry.name)]
+ : [],
+ )
+}
diff --git a/packages/cli/src/lib/prompt.ts b/packages/cli/src/lib/prompt.ts
new file mode 100644
index 0000000000..69249ed6a0
--- /dev/null
+++ b/packages/cli/src/lib/prompt.ts
@@ -0,0 +1,20 @@
+import * as p from '@clack/prompts'
+import pc from 'picocolors'
+
+/**
+ * Ask before doing something the developer may not expect, exiting when they
+ * decline. `--yes` agrees up front; a run without a terminal to ask in stops
+ * instead of guessing.
+ */
+export async function confirmOrExit(message: string, yes: boolean): Promise<void> {
+ if (yes) return
+ if (!process.stdin.isTTY) {
+ p.cancel(`${message}\nRe-run with ${pc.bold('--yes')} to agree.`)
+ process.exit(1)
+ }
+ const answer = await p.confirm({ message })
+ if (p.isCancel(answer) || !answer) {
+ p.cancel('Nothing was changed.')
+ process.exit(0)
+ }
+}
diff --git a/packages/cli/tests/add-extension.test.ts b/packages/cli/tests/add-extension.test.ts
new file mode 100644
index 0000000000..6789c49727
--- /dev/null
+++ b/packages/cli/tests/add-extension.test.ts
@@ -0,0 +1,361 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import * as p from '@clack/prompts'
+import { Command } from 'commander'
+import { execa } from 'execa'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { registerAddCommand } from '../src/commands/add.js'
+import { addExtension } from '../src/commands/add-extension.js'
+import { ejectProject } from '../src/commands/eject.js'
+import { dockerComposeCapture, dockerComposeExecOrRun, restartAppServices } from '../src/docker.js'
+import {
+ EXTENSIONS,
+ gemfileDeclares,
+ isValidGemName,
+ isValidNpmName,
+ lockedSpreeVersion,
+ resolveExtension,
+} from '../src/lib/extensions.js'
+import type { ProjectContext } from '../src/types.js'
+
+vi.mock('execa', () => ({ execa: vi.fn(async () => ({})) }))
+
+vi.mock('@clack/prompts', () => ({
+ log: { info: vi.fn(), warn: vi.fn(), step: vi.fn(), success: vi.fn() },
+ spinner: () => ({ start: vi.fn(), stop: vi.fn() }),
+ confirm: vi.fn(),
+ isCancel: () => false,
+ cancel: vi.fn(),
+ intro: vi.fn(),
+ outro: vi.fn(),
+}))
+
+vi.mock('../src/docker.js', () => ({
+ dockerComposeCapture: vi.fn(async () => ''),
+ dockerComposeExecOrRun: vi.fn(async () => undefined),
+ restartAppServices: vi.fn(async () => undefined),
+}))
+
+vi.mock('../src/commands/eject.js', () => ({ ejectProject: vi.fn(async () => undefined) }))
+
+const GEMFILE = `source 'https://rubygems.org'
+gem 'spree', '>= 6.0.0.beta1'
+gem 'spree_stripe', spree_version
+# gem 'spree_adyen'
+`
+
+const LOCKFILE = `GEM
+ specs:
+ spree (6.0.0.rc3)
+ spree_core (6.0.0.rc3)
+`
+
+const EJECTED_COMPOSE = 'services:\n web:\n build:\n context: ./server\n'
+const PREBUILT_COMPOSE = 'services:\n web:\n image: spree/spree\n'
+const IMAGE_LOCKFILE = `${LOCKFILE} spree_stripe (6.0.0.rc3)\n`
+
+describe('extension catalog', () => {
+ it('resolves a name by key, alias or full gem name, never by guessing', () => {
+ expect(resolveExtension('paypal')?.gem).toBe('spree_paypal_checkout')
+ expect(resolveExtension('paypal_checkout')?.gem).toBe('spree_paypal_checkout')
+ expect(resolveExtension('spree_paypal_checkout')?.gem).toBe('spree_paypal_checkout')
+ expect(resolveExtension('AvaTax')?.gem).toBe('spree_avatax_official')
+ expect(resolveExtension('avatax-official')?.gem).toBe('spree_avatax_official')
+ expect(resolveExtension('stirpe')).toBeUndefined()
+ expect(resolveExtension('spree_paypal')).toBeUndefined()
+ })
+
+ it('gives every name exactly one meaning, distinct from the built-in components', () => {
+ const names = Object.entries(EXTENSIONS).flatMap(([key, entry]) => [
+ key,
+ ...(entry.gem === key ? [] : [entry.gem]),
+ ...(entry.aliases ?? []),
+ ])
+ expect(new Set(names).size).toBe(names.length)
+ for (const component of ['dashboard', 'seller_dashboard', 'seller-dashboard', 'ai']) {
+ expect(names).not.toContain(component)
+ }
+ for (const entry of Object.values(EXTENSIONS)) {
+ expect(isValidGemName(entry.gem)).toBe(true)
+ }
+ })
+
+ it('refuses names that could be read as a flag or a path', () => {
+ expect(isValidGemName('acme_loyalty')).toBe(true)
+ expect(isValidGemName('--git=https://example.com/x')).toBe(false)
+ expect(isValidGemName('../x')).toBe(false)
+ expect(isValidNpmName('@acme/loyalty-dashboard')).toBe(true)
+ expect(isValidNpmName('-D')).toBe(false)
+ expect(isValidNpmName('file:../x')).toBe(false)
+ })
+
+ it('reads declared gems and the locked Spree version', () => {
+ expect(gemfileDeclares(GEMFILE, 'spree_stripe')).toBe(true)
+ expect(gemfileDeclares(GEMFILE, 'spree_adyen')).toBe(false)
+ expect(gemfileDeclares(GEMFILE, 'spree')).toBe(true)
+ expect(gemfileDeclares(GEMFILE, 'spree_s')).toBe(false)
+ expect(lockedSpreeVersion(LOCKFILE)).toBe('6.0.0.rc3')
+ expect(lockedSpreeVersion(LOCKFILE.replaceAll('\n', '\r\n'))).toBe('6.0.0.rc3')
+ expect(lockedSpreeVersion('GEM\n')).toBeUndefined()
+ })
+})
+
+describe('addExtension', () => {
+ let projectDir: string
+ const originalIsTTY = process.stdin.isTTY
+
+ function ctx(): ProjectContext {
+ return { mode: 'docker', projectDir, port: 3000 }
+ }
+
+ function write(file: string, content: string): void {
+ fs.mkdirSync(path.dirname(path.join(projectDir, file)), { recursive: true })
+ fs.writeFileSync(path.join(projectDir, file), content)
+ }
+
+ function read(file: string): string {
+ return fs.readFileSync(path.join(projectDir, file), 'utf-8')
+ }
+
+ function commands(): string[][] {
+ return vi.mocked(dockerComposeExecOrRun).mock.calls.map(([argv]) => argv)
+ }
+
+ beforeEach(() => {
+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-add-extension-'))
+ write('server/Gemfile', GEMFILE)
+ write('server/Gemfile.lock', LOCKFILE)
+ write('docker-compose.yml', EJECTED_COMPOSE)
+ vi.clearAllMocks()
+ vi.mocked(dockerComposeCapture).mockImplementation(async (argv) =>
+ argv[0] === 'cat' ? IMAGE_LOCKFILE : '',
+ )
+ vi.mocked(dockerComposeExecOrRun).mockResolvedValue(undefined)
+ vi.spyOn(process, 'exit').mockImplementation((code?: number | string | null) => {
+ throw new Error(`process.exit(${code})`)
+ })
+ })
+
+ afterEach(() => {
+ fs.rmSync(projectDir, { recursive: true, force: true })
+ Object.defineProperty(process.stdin, 'isTTY', { value: originalIsTTY, configurable: true })
+ vi.restoreAllMocks()
+ })
+
+ it('adds a gem released with Spree pinned to the project version, then migrates and restarts', async () => {
+ await addExtension(ctx(), EXTENSIONS.mcp, { yes: false })
+
+ expect(commands()).toEqual([
+ ['bundle', 'add', 'spree_mcp', '--version', '>= 6.0.0.rc3'],
+ ['bin/rails', 'spree:install:migrations', 'db:migrate'],
+ ])
+ expect(restartAppServices).toHaveBeenCalledWith(projectDir, expect.any(String))
+ expect(ejectProject).not.toHaveBeenCalled()
+ })
+
+ it('adds a gem released on its own unpinned, and runs its install generator when it has one', async () => {
+ vi.mocked(dockerComposeCapture).mockResolvedValue(
+ 'SpreePaypalCheckout:\n spree_paypal_checkout:install\n',
+ )
+
+ await addExtension(ctx(), EXTENSIONS.paypal_checkout, { yes: false })
+
+ expect(commands()).toEqual([
+ ['bundle', 'add', 'spree_paypal_checkout'],
+ ['bin/rails', 'generate', 'spree_paypal_checkout:install'],
+ ['bin/rails', 'spree:install:migrations', 'db:migrate'],
+ ])
+ })
+
+ it('reports a gem the prebuilt image already contains without ejecting', async () => {
+ write('docker-compose.yml', PREBUILT_COMPOSE)
+
+ await addExtension(ctx(), EXTENSIONS.stripe, { yes: true })
+
+ expect(ejectProject).not.toHaveBeenCalled()
+ expect(commands()).toEqual([])
+ expect(restartAppServices).not.toHaveBeenCalled()
+ })
+
+ // The prebuilt image runs its own lockfile; a line added to the Gemfile by
+ // hand without ejecting never reached it.
+ it('ejects for a gem the Gemfile lists but the prebuilt image does not contain', async () => {
+ write('docker-compose.yml', PREBUILT_COMPOSE)
+ write('server/Gemfile', `${GEMFILE}gem 'spree_klaviyo'\n`)
+
+ await addExtension(ctx(), EXTENSIONS.klaviyo, { yes: true })
+
+ expect(ejectProject).toHaveBeenCalledWith(projectDir)
+ expect(commands()).toEqual([['bin/rails', 'spree:install:migrations', 'db:migrate']])
+ })
+
+ it('repairs a gem already listed in an ejected project, keeping files its installer wrote', async () => {
+ vi.mocked(dockerComposeCapture).mockResolvedValue('SpreeStripe:\n spree_stripe:install\n')
+
+ await addExtension(ctx(), EXTENSIONS.stripe, { yes: false })
+
+ expect(commands()).toEqual([
+ ['bin/rails', 'generate', 'spree_stripe:install', '--skip'],
+ ['bin/rails', 'spree:install:migrations', 'db:migrate'],
+ ])
+ })
+
+ it('ejects a project on the prebuilt image once the developer agrees', async () => {
+ write('docker-compose.yml', PREBUILT_COMPOSE)
+
+ await addExtension(ctx(), EXTENSIONS.adyen, { yes: true })
+
+ expect(ejectProject).toHaveBeenCalledWith(projectDir)
+ expect(commands()[0]).toEqual(['bundle', 'add', 'spree_adyen'])
+ })
+
+ it('stops without ejecting when there is no terminal to ask in and no --yes', async () => {
+ write('docker-compose.yml', PREBUILT_COMPOSE)
+ Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true })
+
+ await expect(addExtension(ctx(), EXTENSIONS.adyen, { yes: false })).rejects.toThrow(
+ 'process.exit(1)',
+ )
+ expect(ejectProject).not.toHaveBeenCalled()
+ expect(commands()).toEqual([])
+ })
+
+ it('stops when the developer declines to eject', async () => {
+ write('docker-compose.yml', PREBUILT_COMPOSE)
+ Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true })
+ vi.mocked(p.confirm).mockResolvedValue(false)
+
+ await expect(addExtension(ctx(), EXTENSIONS.adyen, { yes: false })).rejects.toThrow(
+ 'process.exit(0)',
+ )
+ expect(ejectProject).not.toHaveBeenCalled()
+ })
+
+ it('puts back the Gemfile, its lock and config when a step after bundle add fails, keeping copied migrations', async () => {
+ write('server/config/routes.rb', 'Rails.application.routes.draw {}\n')
+ vi.mocked(dockerComposeCapture).mockResolvedValue('SpreeKlaviyo:\n spree_klaviyo:install\n')
+ vi.mocked(dockerComposeExecOrRun).mockImplementation(async (argv) => {
+ if (argv[0] === 'bundle') {
+ fs.appendFileSync(path.join(projectDir, 'server/Gemfile'), "gem 'spree_klaviyo'\n")
+ fs.appendFileSync(
+ path.join(projectDir, 'server/Gemfile.lock'),
+ ' spree_klaviyo (1.1.2)\n',
+ )
+ } else if (argv[1] === 'generate') {
+ write('server/config/initializers/spree_klaviyo.rb', 'SpreeKlaviyo.setup\n')
+ write('server/db/migrate/20261019000000_create_klaviyo.rb', 'class CreateKlaviyo; end\n')
+ fs.appendFileSync(path.join(projectDir, 'server/config/routes.rb'), '# klaviyo\n')
+ } else {
+ throw new Error('migration failed')
+ }
+ })
+
+ await expect(addExtension(ctx(), EXTENSIONS.klaviyo, { yes: false })).rejects.toThrow(
+ 'process.exit(1)',
+ )
+ expect(read('server/Gemfile')).toBe(GEMFILE)
+ expect(read('server/Gemfile.lock')).toBe(LOCKFILE)
+ expect(read('server/config/routes.rb')).toBe('Rails.application.routes.draw {}\n')
+ expect(
+ fs.existsSync(path.join(projectDir, 'server/config/initializers/spree_klaviyo.rb')),
+ ).toBe(false)
+ // Kept so a re-run skips migrations that already ran.
+ expect(fs.readdirSync(path.join(projectDir, 'server/db/migrate'))).toEqual([
+ '20261019000000_create_klaviyo.rb',
+ ])
+ })
+
+ it('refuses to add a Spree-released gem when the locked Spree version is unknown', async () => {
+ write('server/Gemfile.lock', 'GEM\n')
+
+ await expect(addExtension(ctx(), EXTENSIONS.meilisearch, { yes: false })).rejects.toThrow(
+ 'process.exit(1)',
+ )
+ expect(commands()).toEqual([])
+ })
+
+ it('installs dashboard plugins into the apps that exist and skips the rest', async () => {
+ write('apps/dashboard/package.json', '{}')
+ write('apps/dashboard/pnpm-lock.yaml', '')
+
+ await addExtension(
+ ctx(),
+ { label: 'Loyalty', dashboard: '@acme/loyalty', sellerDashboard: '@acme/loyalty-seller' },
+ { yes: false },
+ )
+
+ expect(execa).toHaveBeenCalledTimes(1)
+ expect(execa).toHaveBeenCalledWith('pnpm', ['add', '@acme/loyalty'], {
+ cwd: path.join(projectDir, 'apps/dashboard'),
+ stdio: 'inherit',
+ })
+ expect(p.log.warn).toHaveBeenCalledWith(expect.stringContaining('apps/seller-dashboard/'))
+ expect(commands()).toEqual([])
+ })
+})
+
+describe('spree add', () => {
+ const originalIsTTY = process.stdin.isTTY
+
+ async function run(...args: string[]): Promise<void> {
+ const program = new Command()
+ registerAddCommand(program)
+ await program.parseAsync(['add', ...args], { from: 'user' })
+ }
+
+ beforeEach(() => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ vi.spyOn(process, 'exit').mockImplementation((code?: number | string | null) => {
+ throw new Error(`process.exit(${code})`)
+ })
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('refuses a name the catalog does not know, and lists what it does', async () => {
+ await expect(run('stirpe')).rejects.toThrow('process.exit(2)')
+ await expect(run('constructor')).rejects.toThrow('process.exit(2)')
+ expect(console.error).toHaveBeenCalledWith(
+ expect.stringContaining('paypal, adyen, klaviyo, avatax'),
+ )
+ expect(ejectProject).not.toHaveBeenCalled()
+ })
+
+ it('refuses gem and package names that could be read as flags', async () => {
+ await expect(run('--gem', '--git=https://example.com/x')).rejects.toThrow('process.exit(2)')
+ await expect(run('--npm', 'file:../x')).rejects.toThrow('process.exit(2)')
+ })
+
+ it('installs an official gem named with --gem as the catalog says, without asking', async () => {
+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-add-gem-'))
+ fs.mkdirSync(path.join(projectDir, 'server'))
+ fs.writeFileSync(path.join(projectDir, 'server/Gemfile'), GEMFILE)
+ fs.writeFileSync(path.join(projectDir, 'server/Gemfile.lock'), LOCKFILE)
+ fs.writeFileSync(path.join(projectDir, 'docker-compose.yml'), EJECTED_COMPOSE)
+ vi.spyOn(process, 'cwd').mockReturnValue(projectDir)
+ Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true })
+ vi.mocked(dockerComposeExecOrRun).mockClear()
+
+ try {
+ await run('--gem', 'spree_meilisearch')
+ } finally {
+ fs.rmSync(projectDir, { recursive: true, force: true })
+ Object.defineProperty(process.stdin, 'isTTY', { value: originalIsTTY, configurable: true })
+ }
+
+ expect(vi.mocked(dockerComposeExecOrRun).mock.calls[0][0]).toEqual([
+ 'bundle',
+ 'add',
+ 'spree_meilisearch',
+ '--version',
+ '>= 6.0.0.rc3',
+ ])
+ })
+
+ it('refuses a catalog name combined with --gem', async () => {
+ await expect(run('stripe', '--gem', 'acme_loyalty')).rejects.toThrow('process.exit(2)')
+ })
+})
diff --git a/packages/create-spree-app/src/templates/agents-md.ts b/packages/create-spree-app/src/templates/agents-md.ts
index 08ccf0628b..e41947daa5 100644
--- a/packages/create-spree-app/src/templates/agents-md.ts
+++ b/packages/create-spree-app/src/templates/agents-md.ts
@@ -77,7 +77,8 @@ export function agentsMdContent(
`${spree} console # Rails console`,
`${spree} migrate # run pending migrations`,
`${spree} generate <generator> # Rails and Spree generators`,
- `${spree} bundle add <gem> # add a gem`,
+ `${spree} add <extension> # install an extension end to end (stripe, paypal, avatax, …)`,
+ `${spree} bundle add <gem> # add any other gem`,
`${spree} rspec [path] # run tests against the test database`,
`${spree} routes # list routes`,
`${spree} --help # every command`,
@@ -85,7 +86,8 @@ export function agentsMdContent(
'',
'`server/AGENTS.md` maps every Rails command to its CLI equivalent.',
'',
- `Never run \`${spree} db:reset\` or \`${spree} eject\` without asking the developer first.`,
+ `Never run \`${spree} db:reset\` or \`${spree} eject\` without asking the developer first. The same goes for`,
+ `\`${spree} add <extension>\` on a project that is not ejected, because it ejects the project.`,
'',
'### Changes to `server/` need an ejected project',
'',
diff --git a/spree/mcp/README.md b/spree/mcp/README.md
index f129331943..a552604832 100644
--- a/spree/mcp/README.md
+++ b/spree/mcp/README.md
@@ -6,8 +6,8 @@ can merchandise the catalog, answer reporting questions and manage store setup
in plain language, under the same tenancy and permission rules as the Admin
API.
-```ruby
-gem 'spree_mcp'
+```bash
+spree add mcp # or add gem 'spree_mcp' to the Gemfile
```
The endpoint is `POST /api/v3/admin/mcp`, authenticated with a Spree secret API
diff --git a/spree/opentelemetry/README.md b/spree/opentelemetry/README.md
index 9157d68601..11701f30f7 100644
--- a/spree/opentelemetry/README.md
+++ b/spree/opentelemetry/README.md
@@ -6,9 +6,8 @@ Distributed tracing for [Spree Commerce](https://spreecommerce.org) via
With this gem installed, Spree exports traces as soon as the standard
OpenTelemetry environment variables point at a collector — no code changes:
-```ruby
-# Gemfile
-gem 'spree_opentelemetry'
+```bash
+spree add opentelemetry # or add gem 'spree_opentelemetry' to the Gemfile
```
```bash
diff --git a/spree/providers/easypost/README.md b/spree/providers/easypost/README.md
index d77b47800c..292c947e31 100644
--- a/spree/providers/easypost/README.md
+++ b/spree/providers/easypost/README.md
@@ -10,7 +10,7 @@ Live multi-carrier delivery rates for Spree via [EasyPost](https://www.easypost.
## Setup
-1. Add the gem: `bundle add spree_easypost`
+1. Install it with `spree add easypost` (new projects include it already). Without the Spree CLI, add `gem 'spree_easypost'` to the Gemfile with the same version requirement as your `spree` gem.
2. In the admin dashboard, open **Settings → Integrations**, connect **EasyPost**, and activate it (activation verifies the key against the EasyPost API).
3. Create ONE delivery method (**Settings → Delivery methods**) with **EasyPost** as its rate and fulfillment provider. The service picker lists what your EasyPost account can actually quote — read from a throwaway quote rather than the carrier-accounts endpoint, which is production-only and reports no service levels. That's enough — customers see every service EasyPost quotes. Optionally narrow the offered services, rename them ("UPS 1 day"), or add a handling-fee markup, per service or method-wide.
diff --git a/spree/providers/meilisearch/README.md b/spree/providers/meilisearch/README.md
index 11769d40fa..89ed08110b 100644
--- a/spree/providers/meilisearch/README.md
+++ b/spree/providers/meilisearch/README.md
@@ -22,7 +22,7 @@ Without this gem Spree searches the database directly (`Spree::SearchProvider::D
These are environment variables rather than dashboard settings because the index is infrastructure — one server serves every store in the installation, and the reindex task has to reach it outside a request.
-2. Add the gem: `bundle add spree_meilisearch`
+2. Install it with `spree add meilisearch` (new projects include it already). Without the Spree CLI, add `gem 'spree_meilisearch'` to the Gemfile with the same version requirement as your `spree` gem.
3. Select the provider in `config/initializers/spree.rb`:
diff --git a/spree/providers/stripe/README.md b/spree/providers/stripe/README.md
index f6459d8901..e47226f90a 100644
--- a/spree/providers/stripe/README.md
+++ b/spree/providers/stripe/README.md
@@ -11,14 +11,15 @@ through setup sessions.
## Installation
-Add the gem to your `Gemfile`:
+New Spree projects include it already. To add it to an older project:
-```ruby
-gem 'spree_stripe'
+```bash
+spree add stripe
```
-Then run `bundle install`. The gateway registers itself — there is nothing to
-generate and no migrations to run.
+Without the Spree CLI, add `gem 'spree_stripe'` to the `Gemfile` with the same
+version requirement as your `spree` gem and run `bundle install`. The gateway
+registers itself — there is nothing to generate and no migrations to run.
## Configuration