# Lifecycle, dependencies & order

How and when a plugin runs — the setup/init/destroy lifecycle, load order, declaring dependencies on other plugins, version compatibility, and enabling/disabling.

This page covers *when* a plugin's code runs, in *what order*, and how to express
ordering and version constraints. For the errors these rules produce, see the
[error reference](https://nextlyhq.com/docs/plugins/error-reference.md).

## The lifecycle: `contributes → setup → init → destroy` (D4)

```ts
definePlugin({
  name: "@acme/nextly-plugin-thing",
  version: "1.0.0", // your plugin's semver (used by others' dependsOn ranges)
  nextly: ">=0.0.2-alpha.63", // core-compat range (see Version compatibility)
  contributes: {
    /* declarative nouns: collections, extend, permissions, routes, admin, events */
  },
  setup(config) {
    // Escape-hatch config transform. ALL plugins' setup() run before ANY init().
    // Don't mutate — spread and return a new object.
    return { ...config };
  },
  async init(ctx) {
    // Runtime wiring: subscribe to events, register hooks, read/write via ctx.services.
  },
  async destroy(ctx) {
    // Teardown on shutdown, re-registration and test teardown. Undo anything init() set up.
  },
});
```

Phase order:

1. **`contributes`** is read first (without running your plugin) — the host folds your
   schema, permissions, routes, and admin contributions into the merged config.
   `contributes.transforms` run once everything is merged, so they can change entities
   other plugins declared (see [Change entities you don't own](https://nextlyhq.com/docs/plugins/schema.md#change-entities-you-dont-own)).
2. **`setup(config)`** runs for **every** plugin before any `init` — so a plugin can
   adjust config that a later plugin's `init` relies on.
3. **`init(ctx)`** runs once services are live. This is where you do runtime work.
4. **`destroy(ctx)`** runs, in reverse init order, on shutdown (`nextly.shutdown()`),
   when a failed start is rolled back, before services register again, and on test
   teardown. A config hot reload runs neither `init` nor `destroy`: a running plugin
   keeps running, and a change to either takes effect on the next start. Always clean
   up here — a subscription or timer left behind outlives the plugin and breaks tests.

## Load order (D5)

Plugins are run in a **topological sort** over their declared dependencies, so a plugin
always initializes **after** the plugins it depends on. When two plugins have no
dependency relationship, their **array order** in `defineConfig({ plugins: [...] })`
breaks the tie.

```ts
import { defineConfig } from "nextly";

export default defineConfig({
  // a runs before b (array order), unless dependsOn says otherwise
  plugins: [a(), b()],
});
```

A **dependency cycle** is a fail-fast boot error (`PLUGIN_RESOLUTION_ERROR`,
`reason: "dependency-cycle"`).

## Dependencies (D5)

Declare dependencies on other plugins by **package name → version range**:

```ts
definePlugin({
  name: "@acme/nextly-plugin-reports",
  version: "1.0.0",
  nextly: ">=0.0.2-alpha.63",
  // Hard requirement: must be installed and in-range, and inits first.
  dependsOn: { "@acme/nextly-plugin-core": "^2" },
  // Enhance-if-present: fine if absent; if present it must be in-range and inits first.
  optionalDependsOn: { "@acme/nextly-plugin-search": "^1" },
});
```

* **`dependsOn`.** A missing dependency, or one whose installed version is outside the
  range, is a fail-fast boot error (`reason: "missing-dependency"` /
  `"version-incompatible"`).
* **`optionalDependsOn`.** An **absent** optional dependency is fine; a **present but
  out-of-range** one fails fast (`reason: "optional-version-incompatible"`). Use
  `ctx.nextlyVersion` or feature checks to branch on whether an optional dep is active.

If your plugin **extends or relates to another plugin's entity**, you must declare a
`dependsOn` on it — otherwise you get `NEXTLY_SCHEMA_CROSS_PLUGIN_RELATION`.

## Version compatibility (D6)

Every plugin declares the **core** range it supports via `nextly`. It's checked at boot;
an out-of-range core is a fail-fast error (`reason: "core-incompatible"` /
`"invalid-nextly-range"`).

```ts
nextly: ">=0.0.2-alpha.63", // a range may span multiple majors once they exist
```

Prereleases (alpha/beta) count as in-range. For runtime feature-detection, read
`ctx.nextlyVersion` rather than branching on the declared range.

## Enabling & disabling (D49)

`enabled` defaults to `true`. Setting it to `false` **skips the plugin's behavior**
(`init`, hooks, events, routes, admin UI) but **still applies its declarative schema** —
so disabling a plugin doesn't drop its tables or strand its data. This lets an
integrator turn a plugin's behavior off without a destructive schema change.

```ts
definePlugin({
  name: "@acme/nextly-plugin-thing",
  version: "1.0.0",
  nextly: ">=0.0.2-alpha.63",
  enabled: false,
});
```

To actually remove a plugin's tables and data, run `nextly plugins uninstall <name>`
while it is still in the config, then remove it — see
[Schema & data lifecycle](https://nextlyhq.com/docs/plugins/schema.md#uninstalling--data-cleanup).

## Install and uninstall hooks

`onInstall` and `onUninstall` (`@experimental`) are for work that belongs to installing
or removing the plugin rather than to every start: seeding a row, registering with an
external service, deregistering from it. They never run at boot.

```ts
import { definePlugin } from "@nextlyhq/plugin-sdk";

export default definePlugin({
  name: "@acme/nextly-plugin-thing",
  version: "1.0.0",
  nextly: ">=0.0.2-alpha.67",
  async onInstall(ctx) {
    // After the plugin's migrations, so its tables exist.
    ctx.logger.info("installed");
  },
  async onUninstall(ctx, { keepData }) {
    // Before its DOWN migrations, so its tables are still readable.
    ctx.logger.info(keepData ? "uninstalled, data kept" : "uninstalled");
  },
});
```

`nextly plugins install <name>` applies the plugin's pending migration modules and then
calls `onInstall`; `nextly plugins uninstall <name>` calls `onUninstall` and then runs
the DOWN of each applied module, newest first. Each boots the app from your config to
build the hook's context, and only when the plugin declares the hook. Write both so
they can run again: an install that failed part-way is repaired by running it again,
which calls `onInstall` again, and an uninstall that stopped part-way is finished by
running it again, which calls `onUninstall` again. A plugin counts as installed only
once `nextly plugins install` has finished on that database: a production boot
refuses it before then while it is enabled, and so does the install of a plugin that depends on it.
`nextly plugins install --all` installs every enabled plugin in your config, its
dependencies first, and stops at the first that fails.

A pending module that deletes data needs the data-loss consent before the install
applies anything, exactly as `nextly migrate` asks for it. The install lists each
module above what it deletes. At a terminal it asks once. Without a terminal it is
refused, with nothing changed, unless `--accept-data-loss` (alone, or naming each
table or `table.column`) or `NEXTLY_ACCEPT_DATA_LOSS` covers every deletion:

```bash
nextly plugins install @acme/notes --accept-data-loss=acme__drafts
```

A no at the terminal stops the install with exit code 1, and nothing is changed.
With `--all`, each plugin is judged before its own install changes anything, and the
run stops at the first refusal: the plugins installed before it stay installed.

`--dry-run` on either command shows what it would do and changes nothing: it
opens the database read-only, takes no lock, asks no consent and exits 0, naming
the refusal a real run would meet. An install names each pending module with
what it deletes, and the record it would make; with `--all`, a plugin is planned
as if the installs before it had run. An uninstall names each module's DOWN, the
tables and columns it drops (none with `--keep-data`), and the records it would
make. Neither runs `onInstall` or `onUninstall`: a hook is plugin code the dry
run does not simulate, and it says so.

```bash
nextly plugins uninstall @acme/notes --dry-run
```

A disabled plugin (`enabled: false`) is not installed, by `--all` or by name, and a
production boot does not require it to be: you can keep a plugin disabled, never
installed, and boot. Its tables exist, because its schema still applies, but its
`onInstall` runs only when you enable it and run `nextly plugins install <name>`.
Once you enable it, a production boot refuses it until that install has run. A
disabled plugin that was uninstalled, or whose uninstall stopped part way, is still
refused, as an enabled one is.

## Inspecting

```bash
nextly plugins list           # installed plugins + their contributions
nextly plugins info <name>    # one plugin's details (resolution runs here too)
```

See also: [Author guide](https://nextlyhq.com/docs/plugins/author-guide.md) ·
[Schema & data lifecycle](https://nextlyhq.com/docs/plugins/schema.md) ·
[Error reference](https://nextlyhq.com/docs/plugins/error-reference.md).
