Skip to content
Spraxium

Primary navigation

Creating a Plugin

Declare a plugin entry, give it a schema and inject its options inside the application.

A Spraxium plugin is an npm package that brings a module and its configuration to a bot. Package a feature when several bots need it and each project should be able to activate it with a package name. Code specific to one bot belongs in its feature modules.

In this guide, you will build @acme/ready-message, a plugin that logs a message when the bot is ready. You can build it, pack it and install it in a bot using Spraxium 0.11.

How registration works

The bot puts the installed package name under plugins in spraxium.config.ts. Core loads the default export of the package’s spraxium-plugin entry, merges the bot’s options with the plugin’s defaults and checks the result against its schema. Invalid options or duplicate IDs stop startup and appear in the Spraxium logger.

Core registers the validated options under the configuration token and loads the plugin’s module. Its providers use the same dependency injection and lifecycle hooks as the bot’s own providers. Each package maintains its own schema. The CLI uses the package’s JSON manifest for discovery and the exported TypeScript declaration for option types.

Describe the options

Create src/ready-message.options.ts. message is the line that appears in the logger and must contain at least one character. enabled controls whether the plugin logs that line. The descriptor will default it to true.

src/ready-message.options.ts
import { type PluginSchema, PluginSchemaType } from '@spraxium/core';

export interface ReadyMessageOptions {
  message: string;
  enabled?: boolean;
}

export const READY_MESSAGE_OPTIONS = Symbol('acme.ready-message.options');

export const readyMessageSchema: PluginSchema = {
  type: PluginSchemaType.Object,

  properties: {
    message: {
      type: PluginSchemaType.String,
      description: 'Message written to the logger when the bot is ready.',
      minLength: 1,
    },

    enabled: {
      type: PluginSchemaType.Boolean,
      description: 'Whether the plugin writes its ready message.',
    },
  },

  required: ['message'],
  additionalProperties: false,
};

The interface describes the options in TypeScript, and the schema validates the values the bot supplies at runtime. required checks for specific keys after defaults are applied. additionalProperties: false catches a misspelled option name.

Read the options in a service

Create src/ready-message.service.ts. The service injects the plugin’s configuration token and writes the message in onReady, once the Discord client is ready.

src/ready-message.service.ts
import { Inject, Injectable, type SpraxiumOnReady } from '@spraxium/common';
import { Logger } from '@spraxium/logger';

import { READY_MESSAGE_OPTIONS, type ReadyMessageOptions } from './ready-message.options.js';

@Injectable()
export class ReadyMessageService implements SpraxiumOnReady {
  private readonly logger = new Logger(ReadyMessageService.name);

  constructor(
    @Inject(READY_MESSAGE_OPTIONS)
    private readonly options: Readonly<ReadyMessageOptions>,
  ) {}

  onReady(): void {
    if (this.options.enabled) this.logger.info(this.options.message);
  }
}

List the service in providers in src/ready-message.module.ts. Core loads this module when the bot activates the plugin.

src/ready-message.module.ts
import { Module } from '@spraxium/common';

import { ReadyMessageService } from './ready-message.service.js';

@Module({
  providers: [ReadyMessageService],
})
export class ReadyMessageModule {}

Export the plugin descriptor

Create src/ready-message.plugin.ts. The id matches name in package.json. Use the same configToken you injected in the service. Give each plugin its own symbol so Core can keep their options separate.

src/ready-message.plugin.ts
import { definePlugin } from '@spraxium/core';

import { ReadyMessageModule } from './ready-message.module.js';
import {
  READY_MESSAGE_OPTIONS,
  type ReadyMessageOptions,
  readyMessageSchema,
} from './ready-message.options.js';

export default definePlugin<ReadyMessageOptions>({
  id: '@acme/ready-message',

  module: ReadyMessageModule,
  configToken: READY_MESSAGE_OPTIONS,

  schema: readyMessageSchema,
  defaults: {
    enabled: true,
  },
});

The object in defaults is optional. Bot options override those defaults. Nested data objects merge, arrays replace their defaults, and undefined leaves a default in place.

Build and package it

Give the package a name under a scope you control. In package.json, declare the Spraxium packages as peer dependencies so the plugin shares the bot’s framework instance. Keep them in development dependencies too so you can build the plugin in its own checkout.

package.json
{
  "name": "@acme/ready-message",
  "version": "0.1.0",
  "description": "Logs a message when a Spraxium bot is ready.",
  "type": "module",
  "files": ["dist"],
  "exports": {
    "./spraxium-plugin": {
      "types": "./dist/ready-message.plugin.d.ts",
      "import": "./dist/ready-message.plugin.js"
    },
    "./spraxium.plugin.json": "./dist/spraxium.plugin.json"
  },
  "scripts": {
    "build": "tsc -p tsconfig.json && node scripts/write-plugin-manifest.mjs"
  },
  "peerDependencies": {
    "@spraxium/common": "^0.11.0",
    "@spraxium/core": "^0.11.0",
    "@spraxium/logger": "^0.11.0"
  },
  "devDependencies": {
    "@spraxium/common": "^0.11.0",
    "@spraxium/core": "^0.11.0",
    "@spraxium/logger": "^0.11.0",
    "typescript": "^7.0.2"
  }
}

The ./spraxium-plugin export exposes the executable entry and its declaration. The ./spraxium.plugin.json export exposes metadata for tools. Set up tsconfig.json so TypeScript writes both JavaScript and declarations to dist. The .js specifiers in the TypeScript files resolve to the compiled files at runtime.

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "rootDir": "src",
    "outDir": "dist",
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "useDefineForClassFields": false,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts"]
}

Create scripts/write-plugin-manifest.mjs. The descriptor already contains a JSON Schema compiled from the TypeScript schema. The script adds the npm version, description and supported Core range from package.json before writing the exported file.

scripts/write-plugin-manifest.mjs
import { readFile, writeFile } from 'node:fs/promises';

import plugin from '../dist/ready-message.plugin.js';

const packageFile = new URL('../package.json', import.meta.url);
const pkg = JSON.parse(await readFile(packageFile, 'utf8'));

if (plugin.id !== pkg.name) {
  throw new Error('The plugin ID must match the package name.');
}

const manifest = {
  ...plugin.manifest,
  version: pkg.version,
  description: pkg.description,
  compatibility: pkg.peerDependencies['@spraxium/core'],
};

await writeFile(
  new URL('../dist/spraxium.plugin.json', import.meta.url),
  JSON.stringify(manifest, null, 2) + '\n',
);

Run these commands in the plugin directory. The archive should contain the executable entry, its declarations and the JSON manifest.

terminal
npm install
npm run build
npm pack

Try it in your bot

From the bot directory, install the archive you just built. This example assumes the plugin checkout is a sibling folder named ready-message. Adjust the path to where you built the package.

terminal
pnpm add file:../ready-message/acme-ready-message-0.1.0.tgz
pnpm exec spraxium plugin sync

Once the package is available in your registry, you can install it by name and refresh the types the same way.

terminal
pnpm add @acme/ready-message
pnpm exec spraxium plugin sync

Add the package name to plugins in the bot’s spraxium.config.ts. The default enables the ready message, so the bot just supplies the text.

spraxium.config.ts
import { defineConfig } from '@spraxium/core';

export default defineConfig({
  plugins: {
    '@acme/ready-message': {
      message: 'The support bot is ready.',
    },
  },
});

spraxium plugin sync writes src/spraxium-plugins.generated.d.ts. The CLI discovers the plugin through the manifest and gets ReadyMessageOptions from the declared return type of its entry. spraxium dev and spraxium build also sync automatically. Include the generated declaration in the TypeScript project that checks the configuration.

Start the bot and look for the message in the logger. Set message to an empty string to see the schema report the problem at startup.

Schema fields

Use these fields when the basic object schema needs to express more rules.

  • type uses PluginSchemaType to choose the expected value. For objects, properties names fields and required makes specific fields mandatory. additionalProperties accepts a boolean or a schema for fields outside that list.
  • patternProperties applies a schema to object keys that match a regular expression. minProperties sets the minimum number of keys, which can require at least one entry in a map whose key names come from the bot.
  • items defines either the schema for every array item or a list of schemas by position. minItems and maxItems bound the length of an array.
  • minimum and maximum are inclusive numeric bounds. minLength and maxLength bound text length, and pattern checks whether text matches a regular expression.
  • enum lists accepted values and const accepts one exact value. anyOf accepts at least one listed schema, oneOf requires exactly one, allOf requires every listed schema and not rejects values that match its schema.
  • description explains a field to someone configuring the plugin. definitions holds reusable schemas and $ref points to one, for example #/definitions/channelId.

The type enum includes Object, Array, String, Number, Integer, Boolean, Null and Function. Keep published defaults as JSON data. Use PluginSchemaType.Function for a callback that the bot supplies in TypeScript. Its JSON Schema uses x-spraxium-type to describe that field to tools.

When a plugin owns resources

For integrations that coordinate native shards from the parent process, onShardingManager receives the manager and validated options after the shards are ready. Return a cleanup callback if the parent owns resources. Ordinary bot services can rely on the module’s lifecycle hooks.

Plugin registration and migration