# Writing a plugin

Start an Axle plugin in TypeScript, teach Axle new projects, tasks and dependencies, test it and publish it.

A plugin teaches Axle what it can't see on its own: projects in another language, tasks from files those projects already have, dependencies hidden in source code, reports in another format, hooks around a run, and tasks of many projects run in one process. This guide writes one in TypeScript with `@axle-rs/plugin`, the kit that speaks Axle's [protocol](https://axlers.dev/docs/reference/plugins.md#the-protocol) for you. A plugin in another language speaks the protocol itself.

## Start a plugin

```sh
pnpm create axle-plugin axle-make               # pnpm
npm create axle-plugin@latest axle-make         # npm
yarn create axle-plugin axle-make               # Yarn
bun create axle-plugin axle-make                # Bun
nub dlx create-axle-plugin axle-make            # nub
aube create axle-plugin axle-make               # aube
```

This creates the folder `axle-make` with a plugin that already works: it finds a project in each folder with a `Makefile` and adds a task for each of its targets.

| File                            | What it is                                                                  |
| ------------------------------- | --------------------------------------------------------------------------- |
| `axle-plugin.toml`              | the plugin's name, the protocol version it speaks and the command Axle runs |
| `src/plugin.ts`                 | what the plugin does                                                        |
| `src/main.ts`                   | starts the plugin when Axle runs it                                         |
| `test/plugin.test.ts`           | its tests, with Vitest                                                      |
| `.github/workflows/ci.yml`      | checks types, runs the tests and builds on every push and pull request      |
| `.github/workflows/release.yml` | publishes it to npm when you push a tag such as `v0.2.0`                    |

In that folder, install its dependencies and run its tests:

```sh
pnpm install                                    # pnpm
npm install                                     # npm
yarn install                                    # Yarn
bun install                                     # Bun
nub install                                     # nub
aube install                                    # aube
```

```sh
pnpm run test                                   # pnpm
npm run test                                    # npm
yarn run test                                   # Yarn
bun run test                                    # Bun
nub run test                                    # nub
aube run test                                   # aube
```

## What a plugin does

`definePlugin` takes what the plugin can do. Axle asks only for what it defines:

```ts
import { definePlugin } from '@axle-rs/plugin'

export default definePlugin({
    watch: ['**/Makefile'],
    discover: (known, { root }) => [{ name: 'docs', folder: 'tools/docs' }],
    tasks: (projects, { root }) => [{ project: 'docs', name: 'build', command: 'make build' }],
})
```

Each function gets what Axle asks with, then the context: `root`, the repository's absolute path, `axle`, the version of Axle, and `settings`, the keys of the plugin's table in `axle.toml` besides `source`, `hash` and `timeout`. Each may return its answer or a promise of it. Paths in answers are relative to the root and use `/`.

### watch

The files the plugin's answers depend on, as [glob patterns](https://axlers.dev/docs/reference/globs.md) from the root, or a function of the context that returns them. Axle keeps the plugin's answers and [asks again](https://axlers.dev/docs/reference/plugins.md#when-plugins-run) only when one of these files changes, or the plugin's settings, its own files or the projects Axle knows do. A plugin that reads a file it doesn't list gives answers that go stale.

### discover

Finds projects Axle doesn't know. It gets the packages and projects Axle already knows, as `{ name, folder }`, and returns the new ones:

```ts
discover: (known, { root }) => [
    {
        name: 'api',
        folder: 'services/api',
        dependencies: ['web'],
        lockfile: [{ name: 'fastapi', version: '0.135.1' }],
    },
]
```

`dependencies` names projects Axle knows or this plugin found. `lockfile` lists the versions of the project's own dependencies, which Axle hashes like a JavaScript lockfile, so a new version misses the cache of the project's tasks. A project can't take the name or folder of one Axle already knows.

When the versions come from a lockfile, return the projects with the lockfiles they came from. Axle then leaves those files out of what every task reads, so a new version only misses the cache of the projects that use it:

```ts
discover: (known, { root }) => ({
    projects: [{ name: 'api', folder: 'python/api', lockfile: versions(root, 'python/uv.lock') }],
    lockfiles: ['python/uv.lock'],
})
```

### tasks

Adds tasks to any project, those from `discover` included. `settings` takes the keys of a task in [`axle.toml`](https://axlers.dev/docs/reference/configuration.md#tasks), and the repository's own `axle.toml` wins over them:

```ts
tasks: (projects) =>
    projects.map((project) => ({
        project: project.name,
        name: 'build',
        command: 'uv build',
        settings: { outputs: ['dist/**'], dependsOn: ['^build'] },
    }))
```

### dependencies

Adds dependencies between projects Axle knows, such as those the plugin finds in source code. `from` depends on `to`, so `from`'s tasks wait for `to`'s:

```ts
dependencies: () => [{ from: 'web', to: 'api' }]
```

### report

Hears every [event of a run](https://axlers.dev/docs/reference/run.md#json-events) as it happens, then writes its report and returns the files it wrote:

```ts
report: {
    event: (event) => {
        if (event.event === 'task-finished') finished.push(event)
    },
    finish: ({ root }) => {
        writeFileSync(join(root, 'reports/junit.xml'), junit(finished))
        return ['reports/junit.xml']
    },
}
```

### hooks

Run before the first task starts and after the run ends:

```ts
hooks: {
    before: (tasks, { settings }) => {
        if (settings.frozen) throw new Error('the repository is frozen for the release')
    },
    after: ({ status, results }) => notify(status, results),
}
```

`tasks` are names such as `web#build`. `after` gets the run's `status`, `passed`, `failed` or `stopped`, and each finished task's `status` and `durationMs`.

### batch

Runs the tasks of many projects together, for a tool that is faster started once. Mark the tasks it can run with `batch: true`, and Axle gives it those that are ready at the same moment. It calls `print` with each line a task prints and returns each task's exit code:

```ts
tasks: (projects) =>
    projects.map((project) => ({
        project: project.name,
        name: 'test',
        command: 'vitest run',
        settings: { batch: true },
    })),
batch: async (jobs, print, { root }) => {
    const results = await vitest(root, jobs.map((job) => job.folder))
    return jobs.map((job) => {
        for (const line of results[job.folder].lines) print(job.task, line)
        return { task: job.task, exitCode: results[job.folder].passed ? 0 : 1 }
    })
},
```

Each job has the `task`, its `project` and `folder`, the `command` and `arguments` it was given and its `setEnv` as `env`. `print` takes `'stderr'` as a third argument for the error stream. Axle still caches and reports each task on its own; [batch mode](https://axlers.dev/docs/reference/plugins.md#batch-mode) says when a task runs without the plugin.

### migrate

Updates settings written for an earlier version of the plugin, when `axle migrate` runs. It gets the settings and returns the new ones, with a line for each change, and no changes when there is nothing to do:

```ts
migrate: ({ python, ...rest }) =>
    python === undefined
        ? { settings: rest, changes: [] }
        : { settings: { ...rest, version: python }, changes: ['python is now version'] },
```

Axle writes the new settings into `axle.toml` and prints each change. Keep the old name working until the repository has run `axle migrate`, or fail with a message that says to run it.

### publish

Publishes released packages to a registry Axle doesn't know, when `axle release publish` runs. It gets every package whose version is tagged at the commit, with its `name`, `version`, `folder` and `private`, and whether it's a dry run, and returns a line for each thing it did:

```ts
publish: async (packages, dryRun) => {
    const images = packages.filter((found) => !found.private && found.folder.startsWith('services/'))
    if (!dryRun) for (const image of images) await push(image)
    return images.map((image) => `${dryRun ? 'Would push' : 'Pushed'} ${image.name}:${image.version}`)
},
```

Skip versions the registry already has, so publishing can run again after a failure.

### sync

Keeps files that follow from the repository in step, such as a `CODEOWNERS`, when `axle sync` runs. It gets every project with its `name`, `folder`, `kind`, `tags` and `dependencies`, and returns the files it wants, each with its `path` from the root and all its `contents`:

```ts
sync: (projects) => [
    {
        path: 'docs/projects.md',
        contents: projects.map((project) => `- ${project.name}: ${project.folder}
`).join(''),
    },
],
```

`axle sync` writes the files that differ, `--dry-run` shows the diff and `--check` fails while one is out of date. Return the same contents for the same repository, so a file only changes when something it shows does. A path can't leave the repository or go into `.git`.

### check

Checks the repository's own rules when `axle boundaries` runs. It gets the projects `--filter` or `--affected` chose, as `sync` does, and returns a violation for each rule broken:

```ts
check: (projects, { root }) =>
    projects
        .filter((project) => !existsSync(join(root, project.folder, 'README.md')))
        .map((project) => ({
            rule: 'readme',
            message: 'has no README.md',
            project: project.name,
            severity: 'warning',
        })),
```

`rule` and `message` are needed. `project`, `file`, `line` and `hint` say where and how to fix it when the plugin knows. `severity` is `error`, the default, which fails `axle boundaries`, or `warning`, which doesn't.

### upgrade

Moves the projects that use the plugin's tool to the version it supports when `axle migrate --upgrade` runs, with the changes their code needs, as a codemod would. It gets every project, as `sync` does, and returns the files it changes, each with all its new `contents`, and a line for each change:

```ts
upgrade: (projects, { root }) => {
    const files = []
    const changes = []
    for (const project of projects) {
        const path = posix.join(project.folder, 'package.json')
        const before = readFileSync(join(root, path), 'utf8')
        const after = withVersions(before, { jest: '^30.0.0' })
        if (after === before) continue
        files.push({ path, contents: after })
        changes.push(`${project.name}: jest is now ^30.0.0`)
    }
    return { files, changes }
},
```

Return nothing for a project that's already upgraded, so running it again changes nothing. Read each file from disk and return its whole new contents; Axle writes the ones that differ, and `--dry-run` shows the diff.

## Settings

Give `definePlugin` the type of the plugin's settings, and the context has it:

```ts
export default definePlugin<{ format?: 'junit' | 'json' }>({
    report: {
        event: () => {},
        finish: ({ settings }) => [`reports/run.${settings.format ?? 'json'}`],
    },
})
```

```toml
[plugins.reports]
source = "npm:axle-reports@1.0.0"
hash = "sha256-…"
format = "junit"
```

Axle passes the settings as they are, so check them before you trust them.

## Tasks for JavaScript tools

A plugin that adds tasks for a JavaScript tool, such as a test runner, to the packages that have its config file can use `@axle-rs/plugin/javascript`, as the official [Vite](https://axlers.dev/docs/official-plugins/vite.md), [Vitest](https://axlers.dev/docs/official-plugins/vitest.md), [Jest](https://axlers.dev/docs/official-plugins/jest.md), [Playwright](https://axlers.dev/docs/official-plugins/playwright.md), [ESLint](https://axlers.dev/docs/official-plugins/eslint.md), [Next.js](https://axlers.dev/docs/official-plugins/next.md) and [webpack](https://axlers.dev/docs/official-plugins/webpack.md) plugins do:

```ts
import { definePlugin } from '@axle-rs/plugin'
import { findConfig, PACKAGE_FILES, taskName, toolTask } from '@axle-rs/plugin/javascript'

export default definePlugin({
    watch: ['**/jest.config.*', ...PACKAGE_FILES],
    tasks: (projects, { root, settings }) =>
        projects
            .filter((project) => findConfig(root, project.folder, 'jest.config'))
            .flatMap((project) =>
                toolTask(root, project, {
                    name: taskName(settings, 'test', 'test'),
                    command: 'jest',
                    settings: { outputs: ['coverage/**'] },
                }),
            ),
})
```

| Helper           | What it does                                                                                                                                                                                                                                                                |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `toolTask`       | the task that runs `command`, or each of a list of commands in turn, through the package manager, or none when `name` is `false` or the package has a script of that name that runs anything but `command` or one of `scripts`                                              |
| `exec`           | a command that runs a tool from `node_modules`: `pnpm exec`, `npx --no --`, `yarn`, `bunx`, `nubx` or `aube exec` before it. Given a package's folder, it uses `yarn run -T` with Yarn 2 or later when the package doesn't install the tool itself, so the root's copy runs |
| `packageManager` | `npm`, `pnpm`, `yarn`, `bun`, `nub` or `aube`, read from the root `package.json` and lockfiles the way Axle reads it                                                                                                                                                        |
| `PACKAGE_FILES`  | the files those answers depend on, for `watch`                                                                                                                                                                                                                              |
| `findConfig`     | the first config file in a folder with one of the extensions, such as `vite.config.ts`                                                                                                                                                                                      |
| `packageJson`    | a folder's `package.json`, or `undefined` when it has none or it isn't an object                                                                                                                                                                                            |
| `hasDependency`  | whether a folder's `package.json` lists a package among its dependencies, dev, peer or optional                                                                                                                                                                             |
| `readOption`     | an option written as a string in a config file, without running it: `undefined` when it isn't set, `null` when it's set to anything Axle can't read                                                                                                                         |
| `outputGlob`     | an `outputs` pattern for a folder, relative to the project or `{root}/`, or `undefined` for a folder that can't be stored                                                                                                                                                   |
| `outputsFrom`    | the `outputs` for the folder an option names, from `readOption` and `outputGlob`, or for a fallback folder when the option isn't set; `undefined` when either can't read or store it                                                                                        |
| `taskName`       | a task name or `false` from the settings, with a default, failing on anything else                                                                                                                                                                                          |
| `majorVersion`   | the major version a range such as `^15.2.0` asks for, or `undefined` for a tag, a link or a `workspace:` range                                                                                                                                                              |
| `withVersions`   | a `package.json`'s text with new versions for the dependencies it lists, keeping its indentation and line endings; links, tags and `workspace:` ranges stay                                                                                                                 |

Axle runs a task's `command` through the shell without `node_modules/.bin` on the `PATH`, so a plain `jest` would only find a global one. And a command from a plugin replaces the package's script of the same name, which is why `toolTask` adds nothing when that script runs something else.

## Generators

A plugin can ship [generators](https://axlers.dev/docs/crafting-your-repository/writing-generators.md) for `axle generate`, such as one that starts a new service the plugin understands. Name their folder in `axle-plugin.toml`:

```toml
generators = "generators"
```

Each folder inside it with a `generator.toml` is a generator, run as `axle generate <plugin>:<folder>`. They're templates, or a `generator.ts`, as in a repository, so they need nothing from the plugin's code. A plugin that only ships generators leaves out `command` and needs no code at all:

```toml
name = "service-kit"
protocol = 1
generators = "generators"
```

`pnpm create axle-plugin` asks whether to start the plugin with an example generator.

## Errors and logs

When a function throws, Axle stops with the plugin's [message](https://axlers.dev/docs/messages/plugin-failed.md) and shows its error. An error in `before` stops the run before any task starts; one in `finish` or `after` is a warning, since the run has already happened.

Standard output belongs to the protocol, so `console.log`, `console.info` and `console.debug` write to standard error, and Axle shows the end of it when the plugin fails. Don't write to `process.stdout` yourself.

## Test it

`start` from `@axle-rs/plugin/testing` starts the plugin the way Axle does and asks it questions:

```ts
import { start } from '@axle-rs/plugin/testing'
import { expect, it } from 'vitest'
import plugin from '../src/plugin.ts'

it('finds the docs', async () => {
    const axle = await start(plugin, { root: repository, settings: { format: 'junit' } })
    const { projects } = await axle.discover([])
    expect(projects).toEqual([{ name: 'docs', folder: 'tools/docs' }])
    await axle.stop()
})
```

It has `initialized`, the plugin's answer to `initialize`, and `discover`, which gives `{ projects, lockfiles }`, `tasks`, `dependencies`, `before`, `event`, `finish`, `after`, `run`, which gives `{ results, output }`, `migrate`, which gives `{ settings, changes }`, `publish`, which gives the plugin's `published` lines, `sync`, which gives the files, `check`, which gives the violations, `upgrade`, which gives `{ files, changes }`, and `stop`.

## Try it in a repository

Axle runs a plugin as it is, without installing its dependencies, so the starter bundles it and the kit into one file, `dist/plugin.js`, which `axle-plugin.toml` runs. Build it:

```sh
pnpm run build                                  # pnpm
npm run build                                   # npm
yarn run build                                  # Yarn
bun run build                                   # Bun
nub run build                                   # nub
aube run build                                  # aube
```

Then add its folder to a repository and see what it found:

```sh
axle add ../axle-make
axle list
```

Axle asks the plugin again after each build, since its own files changed.

## Publish it

Publish the first version by hand with `npm publish --access public`, then make the release workflow a [trusted publisher](https://docs.npmjs.com/trusted-publishers) of the package on npmjs.com. From then on, raise the version, commit, and push a tag such as `v0.2.0`: the workflow runs the tests and publishes the plugin with provenance. The workflows install with the package manager that created the plugin, from its lockfile, so commit the lockfile.

Repositories add it with [`axle add`](https://axlers.dev/docs/reference/plugins.md#adding-a-plugin), which downloads it and records its hash:

```sh
axle add npm:axle-make
```

To have `axle plugins` and the [plugins page](https://axlers.dev/docs/plugins.md#add-yours) list it, open a pull request that adds it to [`plugins/community/plugins.json`](https://github.com/axle-rs/axle/blob/main/plugins/community/plugins.json).
