[data-reveal]{opacity:1!important;transform:none!important}
DocumentationEmbed AntelopeJS in an existing app

Embed AntelopeJS in an existing app

Run AntelopeJS modules inside an application that owns the process, with an AdonisJS application as a complete worked example.

Overview

This guide runs AntelopeJS in embedded mode. Your application owns the process and starts an AntelopeJS runtime as a guest. In standalone mode, the ajs CLI owns the process instead. Embedded Runtime compares the two modes and holds the full API reference.

The steps below apply to any Node.js host. The worked example uses AdonisJS and comes from the template-dms-adonis template.

Important

The only host we test is the AdonisJS release that template-dms-adonis pins in its package.json. Express, Fastify, NestJS and other Node.js hosts follow the same pattern, but they are untested.

Prerequisites

Install @antelopejs/core and every module the host loads as regular dependencies of the host application:

npm install @antelopejs/core @antelopejs/mongodb

The runtime resolves modules from the host's node_modules. It downloads nothing at startup. If a module is missing from the dependencies, start() fails with an error that asks you to install it.

Embed the runtime

Create the runtime

Call createRuntime() once, in the host's setup phase. List the modules to load in modules, keyed by package name. List the interface packages the host calls in uses.

antelope.ts typescript
import { createRuntime } from "@antelopejs/core";

export const runtime = createRuntime({
  projectFolder: process.cwd(),
  modules: {
    "@antelopejs/mongodb": {
      config: { url: process.env.MONGODB_URL, database: "app" },
    },
  },
  uses: ["@antelopejs/interface-database"],
});

Module configuration is plain JavaScript. There is no antelope.config.ts, so read environment variables and secrets in host code, with the host's own configuration system.

Start and stop it with the host

Call runtime.start() before the host starts to serve requests. Call runtime.stop() when the host shuts down. start() rejects when a module fails to start or a uses package does not resolve. Let that error stop the host's boot.

By default, the runtime leaves SIGINT, SIGTERM and the process error handlers to the host. If the host never calls stop(), the runtime does not stop or destroy the modules cleanly.

Reach an interface through runtime.use()

Host code is not a module, so it reaches interfaces through the runtime handle. runtime.use() returns the runtime's own copy of an interface package, or of one of its subpaths, bound to a provider. The host declares each request it uses, with its type, in the EmbeddedInterfaces map of @antelopejs/core. use() returns that type.

users.ts typescript
import { runtime } from "./antelope";

declare module "@antelopejs/core" {
  interface EmbeddedInterfaces {
    "@antelopejs/interface-database": typeof import("@antelopejs/interface-database");
  }
}

const database = runtime.use("@antelopejs/interface-database");

A request missing from the map does not compile. use() takes no type argument. To migrate older code, replace each runtime.use<T>("<request>") call with an entry "<request>": T in the map.

The request names an interface package, never the module that implements it. List the interface in uses and load a module that implements it. Otherwise use() throws. It also throws before start().

Never import an interface package from host code

Do not write import { ... } from "@antelopejs/interface-..." in host code. A plain import loads a second copy of the interface package, and no provider is attached to that copy, so its calls never reach a module. Type-only imports, such as import type or typeof import(...) as above, are safe because the compiler erases them.

Tip

To let modules call into the host, list the interface in provides and declare it in the EmbeddedInterfaces map, as for use(). After start(), attach the implementation with runtime.provide(packageName, implementation). The compiler checks the implementation against the declared interface. To remove the implementation, call detach() on the returned handle.

Worked example with template-dms-adonis

The template-dms-adonis template runs the AntelopeJS DMS inside an AdonisJS application. A service provider ties the runtime to the AdonisJS lifecycle:

AdonisJS hookAction
register()createRuntime({ ... }), bound into the container.
start()runtime.start(), which boots the modules before HTTP serving.
shutdown()runtime.stop(), which tears the modules down with the app.

The service provider

The provider reads its configuration from the validated AdonisJS environment. It binds the runtime into the container, so routes and services can resolve it.

providers/antelope_provider.ts typescript
import type { ApplicationService } from '@adonisjs/core/types'
import { createRuntime, type AntelopeRuntime } from '@antelopejs/core'
import env from '#start/env'

export const AntelopeRuntimeBinding = 'antelope.runtime'

declare module '@adonisjs/core/types' {
  interface ContainerBindings {
    [AntelopeRuntimeBinding]: AntelopeRuntime
  }
}

export default class AntelopeProvider {
  private runtime?: AntelopeRuntime

  constructor(protected app: ApplicationService) {}

  register() {
    this.runtime = createRuntime({
      projectFolder: this.app.makePath(),
      modules: {
        '@antelopejs/dms': {
          config: {
            homepage: '/modules',
            apiBaseUrl: env.get('DMS_API_BASE_URL'),
            clientBaseUrl: env.get('DMS_CLIENT_BASE_URL'),
            // The embedded runtime runs with `dev: false` unless you pass `dev: true`, so the DMS does not
            // publish a per-boot credential for `ajs dms dev`: both read this
            // one from `.env`.
            frontend: { bootstrapSecret: env.get('DMS_BOOTSTRAP_SECRET') },
            meta: {
              title: 'AntelopeJS DMS on AdonisJS',
              description: 'DMS running as a guest of an AdonisJS application',
            },
          },
        },
        '@antelopejs/dms-api': {},
        '@antelopejs/dms-media': {},
        '@antelopejs/dms-automation': {},
        '@antelopejs/dms-database': {},
        '@antelopejs/api': {
          config: {
            // Required outside development, where the runtime runs embedded:
            // the origin browsers reach this API at.
            publicBaseUrl: env.get('DMS_API_BASE_URL'),
            servers: [
              {
                protocol: 'http',
                host: env.get('DMS_API_HOST'),
                port: env.get('DMS_API_PORT'),
              },
            ],
            cors: {
              allowedOrigins: [env.get('DMS_CLIENT_BASE_URL')],
            },
          },
        },
        '@antelopejs/mongodb': {
          config: {
            url: env.get('MONGODB_URL'),
            database: env.get('MONGODB_DATABASE'),
          },
        },
        '@antelopejs/auth-jwt': {
          config: { secret: env.get('DMS_JWT_SECRET') },
        },
        '@antelopejs/file-storage-local': {
          config: {
            storagePath: '.antelope/file-storage',
            baseUrl: env.get('DMS_API_BASE_URL'),
            defaultVisibility: 'private',
          },
        },
        '@antelopejs/nodemailer': {
          config: { ethereal: true },
        },
      },
      uses: ['@antelopejs/interface-dms'],
    })

    this.app.container.bindValue(AntelopeRuntimeBinding, this.runtime)
  }

  async start() {
    await this.runtime?.start()
  }

  async shutdown() {
    await this.runtime?.stop()
  }
}

Register the provider in adonisrc.ts:

adonisrc.ts typescript
providers: [
  () => import('@adonisjs/core/providers/app_provider'),
  // ...
  () => import('#providers/antelope_provider'),
],

Declare every environment variable the provider reads in start/env.ts, so AdonisJS validates them at boot.

Call an interface from a route

Routes resolve the runtime from the container and call the DMS through runtime.use(). The template declares the interface's type in the EmbeddedInterfaces map, because @antelopejs/interface-dms is a dependency of the DMS module, not of the application.

start/routes.ts typescript
import router from '@adonisjs/core/services/router'
import app from '@adonisjs/core/services/app'
import { AntelopeRuntimeBinding } from '#providers/antelope_provider'

declare module '@antelopejs/core' {
  interface EmbeddedInterfaces {
    '@antelopejs/interface-dms/client-base-url': {
      GetClientBaseUrl(): Promise<string | undefined>
    }
  }
}

router.get('/dms/info', async () => {
  const runtime = await app.container.make(AntelopeRuntimeBinding)
  const clientBaseUrl = await runtime
    .use('@antelopejs/interface-dms/client-base-url')
    .GetClientBaseUrl()

  return { clientBaseUrl }
})

This route listens on the AdonisJS port, 3333 by default. The DMS API listens on DMS_API_PORT, which is 5010 in the template. The limitations below explain why.

Run the DMS dashboard

The DMS dashboard, @antelopejs/dms-frontend, runs as a separate process. In embedded mode, build it and then start it:

Terminal bash
pnpm frontend:build   # ajs dms build
pnpm frontend:start   # ajs dms start -p 3001

ajs dms dev does not work in embedded mode. It hot-reloads the layer sources that the DMS publishes only when the runtime runs in development mode. The embedded runtime runs with dev: false by default, so the DMS publishes nothing there. The dashboard presents DMS_BOOTSTRAP_SECRET to the DMS, which checks it against the frontend.bootstrapSecret value above. ajs dms build and ajs dms start read DMS_SESSION_SECRET from .env. Run pnpm frontend:build again after you add or remove a DMS module. The DMS AdonisJS page covers the full setup.

Limitations

  • Separate HTTP listeners. A module that opens its own HTTP server, such as @antelopejs/api, listens on its own host and port. The module is not mounted into the host's HTTP server, so the host and the module serve on two ports.
  • Non-development mode by default. The runtime reports dev: false through GetRuntimeInfo() unless you pass dev: true to createRuntime. Modules then apply their production behavior. For example, @antelopejs/api requires publicBaseUrl. With dev: true, modules see development mode, and DevRegistryStore writes the dev server registry file in the host project once a module calls RegisterDevServer.
  • No hot reload. The runtime does not watch module files. To pick up a change in a module, restart the host.
  • No ajs project commands. There is no antelope.config.ts, so ajs project dev, start, build, modules add and logging do not apply. To add a module, install it and add it to the modules map. ajs module init and ajs module test still work on the module folders themselves.
  • No configuration file features. Environments, envOverrides, ${path} template substitution and the build artifact belong to antelope.config.ts. They do not exist in embedded mode.
  • Installed modules only. Modules come from the host's node_modules or from a local path. The runtime does not download package or Git sources.
  • Default provider for the host. runtime.use() returns the copy bound to the default provider of each interface. The host cannot pin a provider with importOverrides. Set exportPriority on the modules instead.
  • No module logs by default. Without the logging option, the runtime writes no log lines, so module logs are not printed. With logging, the runtime takes over the AntelopeJS log output and writes it next to the host's own logs.
  • Every module is required. If a module fails to start, start() rejects and the runtime shuts down the modules it already started.

See also