npm.io
9.6.60 • Published 3d agoCLI

@bsb/base

Licence
(AGPL-3.0-only OR Commercial)
Version
9.6.60
Deps
4
Size
1.3 MB
Vulns
0
Weekly
7.2K
Stars
3

@bsb/base (Node.js Service Base)

Better Service Base (BSB) is an event-driven microservices framework for Node.js and TypeScript with AnyVali-based config validation, BSB type-safe event schemas, and a pluggable architecture for config, observability (logging, metrics, tracing), and events. It is designed for production-ready, secure-by-default backends with validated APIs and a type-safe event bus.

Version 9.0 introduces breaking changes with improved type safety, cross-language support, and automated code generation. See the Plugin Development Guide for v9 patterns: https://github.com/BetterCorp/better-service-base/blob/master/nodejs/PLUGIN_DEVELOPMENT.md

  • GitHub: https://github.com/BetterCorp/better-service-base/tree/master/nodejs
  • BSB Registry (package): https://io.bsbcode.dev/packages/nodejs/@bsb/base

Intended Usage (Container-first)

  • This project is designed to run standalone inside a Docker container and execute plugins authored and published separately.
  • It is not intended to be embedded or imported as a library into another application package.
  • Deploy the container and supply plugins via BSB_PLUGIN_DIRS (recommended, comma-separated) or BSB_PLUGINS installation at container startup.
Requirements
  • Node.js >= 24.0.0, npm >= 11.0.0
  • TypeScript 5.x for development
Project Structure
  • src/
    • index.ts: Public exports for the package (base classes, interfaces, controllers).
    • cli.ts: Production CLI entry (also exposed as bin -> bsb).
    • dev.ts: Development runner with hot-reload and restart controls.
    • client.ts: Legacy helper for embedding a client; avoid in new code.
    • base/: Core building blocks used by plugins and services
      • BSBService, BSBServiceClient: Base classes for service plugins and their clients
      • PluginObservable, PluginEvents: Per-plugin facades into observability and events
      • BSBConfig, BSBObservable, BSBEvents: Base plugin contracts
      • factory.ts: Option resolution and presets for ServiceBase
    • interfaces/: Strong TypeScript contracts for options, observability, events, results, tools
    • serviceBase/: Runtime controllers that orchestrate the system
      • serviceBase.ts: Main runtime (ServiceBase) - boot/init/run/dispose pipeline
      • config.ts: Loads and initializes the configuration plugin
      • observable.ts: Unified logging, metrics, and tracing via observable plugins
      • events.ts: Manages event plugins and exposes event APIs (broadcast, emit, return, streams)
      • plugins.ts: Resolves and loads plugins from local build or external locations
      • services.ts: Loads, orders, and runs service plugins + their clients
    • plugins/: Built-in plugins
      • config-default/: Default configuration plugin
      • events-default/: Default event bus
      • observable-default/: Console-based logging, metrics, and tracing
      • service-default{0..4}/, service-benchmarkify/: Example/demo service plugins
    • tests/: Mocha + ts-node test suite
  • lib/: Compiled JavaScript output (generated by tsc)
  • templates/: Scaffolding for new plugins (plugin.ts, pluginClient.ts, events.ts, logger.ts)
  • Dockerfile, entrypoint.sh, entrypoint.js: Container build/runtime assets
  • typedoc.json, docs.json, typedoc-theme/: API docs generation configuration/theme
What's New in v9

v9 introduces breaking changes focused on type safety, developer experience, and cross-language support:

Type Safety Improvements:

  • createEventSchemas() - No more as const required, automatic type inference
  • Type branding - Compile-time validation that event types match categories
  • Duplicate name validation - Builds fail when an EventSchemas key is reused across categories

Simplified Configuration:

  • createConfigSchema() - Single function replaces class pattern
  • Plugin metadata - Define once, auto-generates PLUGIN_CLIENT and bsb-plugin.json
  • Centralized schemas - All generated JSON in lib/schemas/ with JSON $ref references

Cross-Language Support:

  • Type helpers - int32, int64, uuid, datetime for precise type mapping
  • Schema export - Auto-generates JSON schemas for client code generation
  • Multi-language clients - Generate type-safe clients in TypeScript, C#, Go, Java
  • Cross-plugin events - Type-safe communication between plugins (no any types)

See Plugin Development Guide for migration details and examples.

Runtime Architecture

The ServiceBase class is the primary entry point. It coordinates the framework subsystems and plugin lifecycle.

Boot flow (high level):

  1. Construct ServiceBase (select mode, cwd, and controller implementations)
  2. init() sequence
    • SBConfig.init() -> choose and init configuration plugin
    • SBObservable.init() -> load observable plugins (logging, metrics, tracing)
    • SBEvents.init() -> load events plugins (+ always adds events-default first)
    • SBServices.setup() -> discover service plugins from config, create instances, and map dependencies; then SBServices.init() respecting declared ordering
  3. run() sequence
    • Start observable, events, then SBServices.run() (ordered)
    • Dispose config for safety, start heartbeat metric
  4. dispose()
    • Disposes services, events, observable, and config; exits the process

Timekeeping metrics are recorded for each step and logged as timers. A heartbeat counter runs hourly.

Subsystems
  • SBConfig (configuration)
    • Defaults to config-default plugin; can be replaced via environment variables
    • Provides resolved plugin lists: services, events, observable
    • Exposes getPluginConfig() for per-plugin configuration
  • SBObservable (observability)
    • Manages observable plugins for logging, metrics, and tracing
    • Routes log, metric, and trace operations via an internal bus with filtering
  • SBEvents (events)
    • Loads events plugins and always includes events-default as a fallback
    • Offers APIs for broadcast, fire-and-forget, request/response, and streaming
  • SBServices (services)
    • Loads service plugins from config, re-maps declared init/run before/after dependencies, and initializes/runs them in order
Plugin Resolution & Layout

SBPlugins looks for plugins in the following order (container usage prefers the first external option):

  • Local project (dev): src/plugins/<type>-<name>/index.ts
  • Local build: lib/plugins/<type>-<name>/index.js
  • External plugin directories (BSB_PLUGIN_DIRS, comma-separated) [preferred in container]: <dir>/<npmPackage>/<major>/<minor>/<micro>/lib/plugins/<type>-<name>/index.js
  • Node modules: node_modules/<npmPackage>/lib/plugins/<type>-<name>/index.js

Each plugin folder must export at least a Plugin class. Optionally export a Config class that extends BSBPluginConfig to provide validation and structured config.

Built-in plugin types include: config-*, observable-*, events-*, service-*.

Development vs Production
  • Container runtime (production): The container runs lib/cli.js (bin: bsb) and is the supported production path.
    • Runs new ServiceBase(false, true, CWD) (legacy signature -> optimized for production) inside the container entrypoint.
  • Development runner: src/dev.ts
    • Runs new ServiceBase(true, false, CWD) with file watching
    • Creates .bsbdevwatch on first run; supports include/exclude patterns
    • Interactive controls:
      • Ctrl+R or typing rs to restart
      • Ctrl+C/Ctrl+D to dispose and exit
  • Plugin CLI dev runner: bsb-plugin-cli dev
    • Watches package.json, sec-config.yaml, and src
    • Ignores dot-directories, .git, lib, node_modules, and src/.bsb
    • Add bsb.dev.ignore in package.json to append project-specific ignored paths/globs
NPM Scripts
  • npm run dev: Start development runner with hot-reload
  • npm start: Run production CLI (lib/cli.js or bsb)
  • npm run tsc: Clean and compile TypeScript to lib/
  • npm run build: Clean -> tsc -> tests -> generate docs -> export schemas -> generate plugin metadata
  • npm run build-release: Compile using tsconfig-release.json
  • npm run lint: ESLint over src/
  • npm test: Mocha in TS mode with JSON reporter output
  • npm run testDev: Run tests with the default Mocha reporter
  • npm run generate-docs: Generate TypeDoc JSON to docs.json
  • API Reference: Hosted at https://types.bsbcode.dev/nodejs/
  • npm run export-schemas: Export event schemas to lib/schemas/{plugin-name}.json
  • npm run generate-plugin-json: Generate plugin metadata in lib/schemas/
  • npm run list-plugin-search-paths: Print the packages/plugins visible to BSB, including package versions, plugin types, paths, and config-reference snippets; runs automatically during build and build-release
Docker

Multi-stage build produces a minimal runtime image:

  • Primary published image: code.bettercorp.dev/bettercorp/service-base:node
  • Docker Hub mirror: betterweb/service-base:node
  • ENV NODE_ENV=production, ENV BSB_LIVE=true, ENV BSB_CONTAINER=true, ENV BSB_PLUGIN_DIRS=/mnt/plugins
  • Dockerfiles that extend the BSB Node image do not need to repeat those defaults unless intentionally overriding them.
  • Volumes: /mnt/plugins (external plugins), /mnt/temp
  • Entrypoint runs node /home/bsb/node_modules/@bsb/base/lib/cli.js as an unprivileged node user
  • Built-in core plugins resolve from the installed @bsb/base package, not from a copied local /home/bsb/lib/plugins tree.
  • The runtime package includes npm run start, npm run debug, and npm run plugins for shell/debug use inside the container.
  • Optional plugin install/update at startup:
    • BSB_PLUGINS="@scope/plugin-a:1.2.3,@scope/plugin-b@10" -> installs listed packages
    • BSB_PLUGIN_UPDATE=yes -> refreshes packages listed in BSB_PLUGINS
  • BSB_SHOW_PACKAGES=true -> prints the package/plugin discovery report before BSB starts
  • BSB_PLUGIN_WATCHER=true runs plugin sync mode instead of BSB. It checks BSB_PLUGINS on an interval, installs missing/new matching versions into the shared plugin directory, and skips complete versions that already exist.
  • Derived Dockerfiles can log visible plugins after copying/installing them with RUN node /home/bsb/node_modules/@bsb/base/lib/scripts/list-plugin-search-paths.js

Example run (with mounted plugins directory):

docker run --rm \
  -e BSB_PLUGINS="@bettercorp/your-plugin@1.2.3" \
  -v $(pwd)/plugins:/mnt/plugins \
  code.bettercorp.dev/bettercorp/service-base:node

Recommended plugin directory layout (when using BSB_PLUGIN_DIRS):

/mnt/plugins/
  @org/plugin-a/
    1/2/3/
      package.json
      lib/plugins/service-plugin-a/index.js
      lib/plugins/observable-xyz/index.js
  @org/plugin-b/
    2/4/1/
      package.json
      lib/plugins/events-abc/index.js

Notes

  • In container deployments, prefer placing prebuilt plugins under BSB_PLUGIN_DIRS as above. This avoids network installs on boot and ensures deterministic versions via immutable versioned folders.
  • BSB_PLUGINS is available for dynamic npm install at startup, but mounting a curated plugin repository via BSB_PLUGIN_DIRS is recommended for production.
  • For shared plugin storage, run code.bettercorp.dev/bettercorp/service-base:node with BSB_PLUGIN_WATCHER=true and write access to /mnt/plugins; mount that volume read-only into runtime BSB containers. Runtime containers skip plugin-dir ownership and permission fixes when the mount is read-only.
  • Avoid unversioned BSB_PLUGINS entries in production unless you intentionally want npm latest; @latest is rejected, and major/minor/exact selectors are supported.
  • After changing BSB image versions that affect plugin install layout, run once with BSB_PLUGIN_UPDATE=true or clear the plugin cache volume so stale installed plugin folders are rebuilt.
Environment Variables
  • APP_DIR: Override working directory (mainly used in local development/testing)
  • BSB_DEBUG: Enable debug logging in production mode (true|1|yes|y). Produces production-debug mode.
  • BSB_PLUGIN_DIRS: Comma-separated list of external plugin directories (searched in order; first is install target)
  • BSB_PLUGIN_DIR: Single external plugin directory (legacy, still supported). Accepts comma-separated paths.
  • BSB_PLUGINS: Comma-separated list of npm packages to install at container start (entrypoint.js). Supports no selector, major, minor, and exact selectors. If installation fails, the container exits before BSB starts. Shared plugin storage uses package-scoped install locks so unrelated packages do not block each other.
  • BSB_PLUGIN_UPDATE: yes|true to refresh packages explicitly listed in BSB_PLUGINS
  • BSB_PLUGIN_WATCHER: yes|y|true to run plugin watcher mode instead of BSB
  • BSB_PLUGIN_WATCH_INTERVAL_SECONDS: Seconds between node-watcher sync runs. Default: 3600.
  • BSB_PLUGIN_WATCH_ONCE: yes|y|true to run one watcher sync and exit.
  • BSB_SHOW_PACKAGES: yes|y|true to print package/plugin discovery before startup
  • Config plugin override (advanced):
    • BSB_CONFIG_PLUGIN: Name of config plugin (must start with config-)
    • BSB_CONFIG_PLUGIN_PACKAGE: npm package name hosting the config plugin
Documentation
Plugin Development (v9)
API Documentation
  • API docs are generated with TypeDoc (typedoc.json).
    • npm run generate-docs -> emits docs.json
    • API docs are served at https://types.bsbcode.dev/nodejs/
Testing
  • Tests: Mocha + tsx
    • npm test -> CI-style JSON output (junit.json)
    • npm run testDev -> dev-friendly TS execution
Creating Plugins

For v9 plugin development, see the Plugin Development Guide for complete examples and best practices.

Quick reference:

  • Use createEventSchemas() to define typed events with compile-time validation
  • Keep each EventSchemas key unique across emit/on and event type categories
  • Use createConfigSchema() to define plugin configuration with metadata
  • Use cross-language type helpers (uuid, int32, datetime, etc.) for better code generation
  • Plugin metadata auto-generates PLUGIN_CLIENT and schema files during build

At minimum, export a Plugin class in lib/plugins/<type>-<name>/index.js (or src/plugins/.../index.ts in dev). For configurable plugins, export a Config created with createConfigSchema(). Publish your plugin as an npm package or ship its prebuilt folder structure under BSB_PLUGIN_DIRS.

Quick Start (Container)
# Provide prebuilt plugins under ./plugins, matching the recommended layout
docker run --rm \
  -v $(pwd)/plugins:/mnt/plugins:ro \
  -e BSB_PLUGIN_DIR=/mnt/plugins \
  code.bettercorp.dev/bettercorp/service-base:node

Local development (for contributors only):

npm install
npm run dev

Keywords