Modules
A module is the building block of an AntelopeJS application. It is a self-contained package with a defined lifecycle, configuration, and interface bindings.
Module structure
A module is a standard npm package with an antelopeJs field in its package.json. This field declares the interfaces the module provides, its import aliases, and its default configuration. The package's main field selects the entry point, unless the configured source overrides it.
A module runs in the application's process. It is a lifecycle and dependency boundary. It is not a security sandbox or a separately deployed service.
{
"name": "my-module",
"main": "dist/index.js",
"antelopeJs": {
"implements": ["@antelopejs/interface-example"],
"baseUrl": "dist",
"paths": { "@/*": ["*"] },
"moduleAliases": {},
"defaultConfig": {}
}
}
The implements array lists the interface packages this module provides. baseUrl is the base folder for the paths aliases. It does not select an entry point or compile TypeScript. defaultConfig is the configuration that ajs project modules add writes into the project's entry for this module.
Entry point
The module entry point (src/index.ts, compiled to dist/index.js) exports lifecycle functions. The core calls these functions in order as the module moves through its lifecycle states.
export async function construct(config: unknown): Promise<void> {
// Open connections and attach interface implementations
}
export function start(): void {
// Every module is constructed and every interface is available
}
export async function drain(): Promise<void> {
// Finish the work in flight while every module still runs
}
export async function stop(): Promise<void> {
// Stop ongoing work
}
export async function destroy(): Promise<void> {
// Release resources
}
construct receives the module's configuration object. Use it to open database connections, attach interface implementations, and prepare internal state. start runs after every module has been constructed and the interfaces are resolved.
A module can also export a provide callback. It runs before any module constructs and returns the config variables the module publishes. Other modules reference those values in their own configuration with ${@<module>.<VAR_NAME>}. Only providers implement provide, and it is the only place that produces config variables. The core ignores any value that construct returns.
The core calls provide only for a module that lists the variable names in antelopeJs.configVars. If provide does not return every listed name, startup fails with an error that names the missing variables.
import type { ConfigVars } from "@antelopejs/interface-core/config";
declare function reservePort(config: unknown): Promise<number>;
export async function provide(config: unknown): Promise<ConfigVars> {
const port = await reservePort(config);
return { API_PORT: port };
}
reservePort stands for your own port allocation. Its declare line only gives it a type.
No module has constructed while provide runs, so provide cannot await another module's interface.
Lifecycle states
Every module passes through a fixed sequence of states. The core runs the transitions and keeps them in order.
| State | Description |
|---|---|
loaded | The core has resolved the module's files and loaded them into memory. |
constructed | Construction has begun. A partly constructed module still needs cleanup. |
active | start() has completed and the module is serving its interfaces. |
A successful startup moves a module from loaded to constructed to active. stop() returns an active module to constructed. destroy() returns it to loaded, and runs stop() first when the module is still active. The core runs one transition at a time per module, but different modules can construct and start at the same time. Do not rely on the order of keys in the configuration for initialization.
At shutdown the core stops the modules one at a time, then destroys them one at a time. A module stops, and is destroyed, before every module that provides an interface it is bound to, so a provider such as a database client is still running while its consumers stop. Modules bound to each other in a cycle stop one after the other, with no order between them, once every module bound to one of them has stopped.
The core marks a module constructed before it calls construct(), so it can still destroy a module whose construction failed partway. A failed start() never makes the module active, so destroy() must release resources even when stop() has not run.
The state transition diagram shows the forward and cleanup paths.
Finish work in flight before the project stops
A module can export drain. The core calls it once when the project stops as a whole, at shutdown or when a failed start tears the project down. It calls drain on every started module at the same time, and calls the first stop() only once every drain has returned or 5 seconds have passed. Every module, providers included, is still running during the drain, so a request in flight can still call another module's interface.
drain changes no state. The module stays active until its stop() returns. The core never calls drain when it stops, reloads, or removes one module at run time.
An HTTP server stops accepting connections in drain and waits for the requests it is still answering:
import {
createServer,
type IncomingMessage,
type ServerResponse,
} from "node:http";
declare function handleRequest(
request: IncomingMessage,
response: ServerResponse,
): void;
const server = createServer(handleRequest);
export function start(): void {
server.listen(8080);
}
export async function drain(): Promise<void> {
await new Promise<void>((resolve) => {
server.close(() => resolve());
});
}
export function stop(): void {
server.closeAllConnections();
}
handleRequest stands for your request handler. Its declare line only gives it a type.
server.close() stops accepting connections, and its callback runs once the requests in flight have ended. The core waits at most 5 seconds for all the drains together. After that, it logs a warning that names the modules still draining and stops every module anyway. Here stop() then closes the connections that are left. A drain that throws is logged and does not delay the stops.
The core emits Events.ModulesStopping just before it calls the drains. The core does not wait for the listeners of that event. Export drain for the work that the shutdown must wait for.
Startup and cleanup failures
| Failure | Runtime behavior | Module author's responsibility |
|---|---|---|
construct() rejects | The core collects construction failures and destroys the partly constructed modules. | Make destroy() safe after partial initialization. |
start() rejects | Other starts can already be running. The manager waits for them and tears down the failed launch. | Release in destroy() the resources acquired before the failure. A failed start never becomes active and does not receive stop(). |
drain() rejects or runs past 5 seconds | The core logs it and stops every module anyway. | End in stop() the work that drain() left running. |
stop() rejects | Teardown still tries to destroy and clean up the other modules. | Report the error without assuming that other cleanup is skipped. |
destroy() rejects | The core reports cleanup errors together with the original failure. | Close each resource safely and leave no background work running. |
A module marked optional: true in the project configuration starts after the others. If it fails, the core logs the failure and the project runs without it. Diagnostics covers lifecycle events and failed reloads.
Child processes
A module that starts processes of its own, such as a sidecar, a dev server, or a worker, stops them in stop() or destroy(). When the project stops, after every module has been stopped and destroyed, the core also terminates the processes descending from it that are still running. It sends SIGTERM, then SIGKILL two seconds later, so a process that nobody reaped does not outlive the project.
This cleanup works only on Linux, and reaches only processes that still descend from the project. A module must stop any process that is no longer a descendant itself. Examples are a daemon started in an earlier run and reused, or a process started through a detached shell.
Module events
Other modules can listen for lifecycle transitions. The core emits an event each time a module completes a transition, so modules can react when another module becomes available or goes away.
import { Events } from "@antelopejs/interface-core/modules";
Events.ModuleConstructed.register((moduleId: string) => {
// After a module completes construct()
});
Events.ModuleStarted.register((moduleId: string) => {
// After a module completes start()
});
Events.ModuleStopped.register((moduleId: string) => {
// After a module completes stop()
});
Events.ModuleDestroyed.register((moduleId: string) => {
// After a module completes destroy()
});
The core sends each module event to every registered listener. Use these events to start initialization that depends on another module being ready, or to drop references when a dependency goes away.
Module management functions
These APIs are for tooling, and for modules that manage other modules. An ordinary application module needs only its own lifecycle callbacks. For reloads during development, use ajs project dev --watch. The functions below come from @antelopejs/interface-core/modules and take module IDs as defined in your project configuration.
Listing and inspecting modules
ListModules returns the IDs of the loaded modules. GetModuleInfo returns details about one module. Both functions return promises.
import { ListModules, GetModuleInfo } from "@antelopejs/interface-core/modules";
const modules = await ListModules();
const info = await GetModuleInfo("my-module");
// info.status: "loaded" | "constructed" | "active" | "unknown"
// info.source, info.config, info.importOverrides, info.disabledExports, info.localPath
Loading modules dynamically
LoadModule adds a module to a running application without a restart. The third argument controls whether the module starts right after it loads. It defaults to false. If a module with that ID is already loaded, LoadModule stops and destroys it first, so the call acts as a reload.
import { LoadModule } from "@antelopejs/interface-core/modules";
await LoadModule(
"new-module",
{
source: { type: "package", package: "@scope/module", version: "1.0.0" },
config: {},
},
true,
);
Lifecycle control
These functions start, stop, destroy, or hot reload one module at run time.
import {
StartModule,
StopModule,
DestroyModule,
ReloadModule,
} from "@antelopejs/interface-core/modules";
await StartModule("my-module");
await StopModule("my-module");
await DestroyModule("my-module");
await ReloadModule("my-module");
ReloadModule loads the module's source again, stops and destroys the running module, then constructs and starts the new one. During development, the --watch flag of ajs project dev does this each time a source file changes.
A module that writes many source files in a row, such as a code generator, can hold the watcher's reloads so the project reloads once at the end instead of after each write:
import { HoldReloads, ReleaseReloads } from "@antelopejs/interface-core/modules";
declare function writeGeneratedFiles(): Promise<void>;
const hold = await HoldReloads();
try {
await writeGeneratedFiles();
} finally {
await ReleaseReloads(hold);
}
While a hold is open, a module whose files change is queued, and a change to antelope.config.ts or .env defers the project restart. When the last hold ends, the watcher waits until it has seen no change for 500 ms, so writes made just before the release are counted. Then each queued module reloads once, or the project restarts once if a restart was due, and ReleaseReloads resolves after that. A hold ends with the module that took it when that module is destroyed or reloaded. Outside --watch, a hold holds nothing.
When a watched module fails to reload, the core logs the error and the module stays stopped. Its next source change reloads it again. The dev process keeps running. Asynchronous work that the destroyed module left pending fails with ModuleContextInvalidatedError when it resumes, and the core logs that failure instead of shutting the process down. To keep the log clean, cancel such work in destroy().