@smitejs/cli
Compile-time toolchain for Smite: compile apps in collect mode and run generator plugins.
yarn add @smitejs/cli50 documented symbols · version 2.0.0-SNAPSHOT.0 · source
Build
functionbuild
function build(options?: BuildOptions): Promise<readonly string[]>;Runs a production build: load config, compile app entries in collect mode, run every generator plugin, then bundle runtime entries with descriptor collection disabled.
interfaceBuildOptions
interface BuildOptions {
readonly config?: string;
readonly alias?: Readonly<Record<string, string>>;
}Options for build.
functionbundleBuildEntries
function bundleBuildEntries(options: BundleBuildEntriesOptions): Promise<readonly string[]>;Bundles runtime entries for production/deployment. The registry flag is always folded to false, so runtime bundles cannot collect descriptors.
const [outfile] = await bundleBuildEntries({
cwd: dir,
entries: ["./server.ts"],
outdir: "dist",
alias: sourceAliases,
});join(dir, "dist/server.mjs")
"globalRegistry"interfaceBundleBuildEntriesOptions
interface BundleBuildEntriesOptions extends SmiteBuildConfig {
readonly cwd: string;
readonly entries: readonly string[];
readonly alias?: Readonly<Record<string, string>>;
}Options for bundleBuildEntries.
Commands
constcli
const cli: {
exe: typeof exe;
};The local-command DSL surface: cli.exe('name', handler).
packages/cli/src/commands.ts:64
interfaceCliCommandDescriptor
interface CliCommandDescriptor extends Descriptor<"cli.command", {
readonly name: string;
readonly fn: (ctx: CliRunContext) => void | Promise<void>;
}> {
}A local command registered with exe and collected from compiled entries by collectCommands.
packages/cli/src/commands.ts:21
interfaceCliRunContext
interface CliRunContext {
readonly apps: readonly AppDescriptor[];
readonly entries?: readonly string[];
readonly compiledEntries?: readonly CompiledEntry[];
}Context passed to a local command handler registered with exe.
packages/cli/src/commands.ts:7
functioncollectCommands
function collectCommands(compiledEntries: readonly CompiledEntry[]): readonly CliCommandDescriptor[];Collects the cli.command descriptors registered across compiled entries, deduplicated by name. Duplicate names across entries throw.
packages/cli/src/commands.ts:73
functionexe
function exe(name: string, handler: (ctx: CliRunContext) => void | Promise<void>): void;Registers a local CLI command callable with smite run <name>. The handler closes over the module scope it is declared in, so it can reach the app, @smitejs/aws providers, and generated artifacts directly. Registration is collect-mode only; production runtime bundles fold it out.
cli.exe("publish:docs", async () => {});[
"publish:docs",
]packages/cli/src/commands.ts:38
functionrunCommand
function runCommand(commands: readonly CliCommandDescriptor[], name: string, ctx: CliRunContext): Promise<void>;Runs the command whose name matches, erroring on unknown or duplicate names. Used by smite run <name>.
packages/cli/src/commands.ts:105
Compile
functioncompileApp
function compileApp(options: CompileAppOptions): Promise<AppDescriptor>;Bundles a single app entry in collect mode, executes it, and locates the app node in globalThis.globalRegistry. Thin wrapper over compileApps for the single-entry case.
const app = await compileApp({ entry, alias: sourceAliases });"app"
1packages/cli/src/compile.ts:117
interfaceCompileAppOptions
interface CompileAppOptions {
readonly entry: string;
readonly appName?: string;
readonly alias?: Readonly<Record<string, string>>;
}Options for compileApp.
packages/cli/src/compile.ts:19
functioncompileApps
function compileApps(options: CompileAppsOptions): Promise<readonly AppDescriptor[]>;Bundles each app entry in collect mode, executes it, and returns the union of app nodes registered across all entries, deduplicated by __key. Each entry compiles in its own registry session (a serverless handler does not see the descriptors of its siblings), so the same app declared in several handler entries collapses to a single node.
Uses this package's own @smitejs/core copy to read the registry, which works across module instances because the registry lives on globalThis and the child index uses Symbol.for.
const apps = await compileApps({
entries: [entry, join(cwd, "packages/cli/test/admin.ts")],
alias: sourceAliases,
});[
"admin",
"cli-fixture",
]packages/cli/src/compile.ts:75
interfaceCompileAppsOptions
interface CompileAppsOptions {
readonly entries: readonly string[];
readonly alias?: Readonly<Record<string, string>>;
}Options for compileApps.
Config
constbuildEntriesOf
const buildEntriesOf: (config: SmiteConfig) => readonly string[];Resolves the runtime entries for smite build: build.entries, else the build.entry shorthand, else the collect-mode app entries.
constcliEntriesOf
const cliEntriesOf: (config: SmiteConfig) => readonly string[];Resolves the local command entries for smite run: cliEntries, else the app entries.
constdefineSmiteConfig
const defineSmiteConfig: <Config extends SmiteConfig>(config: Config) => Config;Type-only helper for smite.config.ts; returns its argument unchanged.
const config = defineSmiteConfig({
entry: "./src/app.ts",
plugins: [],
});"./src/app.ts"
[]constentriesOf
const entriesOf: (config: SmiteConfig) => readonly string[];Resolves the effective entry list: entries, else the entry shorthand.
functionloadConfig
function loadConfig(configPath?: string, alias?: Readonly<Record<string, string>>): Promise<SmiteConfig>;Bundles and executes smite.config.ts, returning its default export. Written under the nearest node_modules so external esbuild/commander requires resolve; removed in a finally.
const config = await loadConfig(configPath, configAliases);entry
1
"client"packages/cli/src/config.ts:116
interfaceSmiteBuildConfig
interface SmiteBuildConfig {
readonly entry?: string;
readonly entries?: readonly string[];
readonly outdir?: string;
readonly esbuild?: esbuild.BuildOptions;
}Runtime bundle settings for smite build.
Shared esbuild options (minify, sourcemap, target, …) go under esbuild, straight through to esbuild.build, so they reuse esbuild's own typings instead of duplicating fields that drift with esbuild releases.
interfaceSmiteConfig
interface SmiteConfig {
readonly entry?: string;
readonly entries?: readonly string[];
readonly cliEntries?: readonly string[];
readonly plugins: readonly SmitePlugin[];
readonly appName?: string;
readonly alias?: Readonly<Record<string, string>>;
readonly build?: SmiteBuildConfig;
}The composition root the CLI reads: the app entries plus the generator plugins contributed by user-installed packages.
Serverless apps often declare one entry per handler (a Lambda function, a GCP function, …). Use entries for those; entry is shorthand for a single entry and equals entries: [entry].
Create
functioncreateApp
function createApp(options: CreateAppOptions): Promise<string>;Scaffolds a starter application into <baseDir>/<name> from the selected template — a generated directory under packages/cli/templates-built/ whose sources, config, and README all come from tested snippets. Returns the created directory.
const appDir = await createApp({ name: "demo-app", baseDir: dir });const configPath = join(appDir, "smite.config.ts");
const configSource = await readFile(configPath, "utf8");
expect(configSource).toContain("client({ outfile");
expect(configSource).toContain("openapi({ outfile");
const appSource = await readFile(join(appDir, "src/app.ts"), "utf8");
expect(appSource).toContain("http.app");
const serverSource = await readFile(join(appDir, "src/server.ts"), "utf8");
expect(serverSource).toContain("serveNode");
expect(serverSource).toContain('from "./app.ts"');
const tsconfigSource = await readFile(
join(appDir, "tsconfig.json"),
"utf8",
);
expect(tsconfigSource).toContain("NodeNext");
expect(tsconfigSource).toContain("allowImportingTsExtensions");
const config = await loadConfig(configPath, configAliases);
const previousCwd = process.cwd();
process.chdir(appDir);
try {
const apps = await compileApps({
entries: entriesOf(config),
alias: sourceAliases,
});
expect(apps).toHaveLength(1);
const appNode = apps[0];
if (appNode !== undefined) {
expect(childrenOf(appNode, "http.route")).toHaveLength(1);
}
await dispatch(config.plugins, "client", { apps });
await dispatch(config.plugins, "openapi", { apps });
} finally {
process.chdir(previousCwd);
}
const clientCode = await readFile(
join(appDir, "src/app.client.ts"),
"utf8",
);
expect(clientCode).toContain("items");
expect(clientCode).toContain('request("GET", "/items/:id"');
const openapiDoc = JSON.parse(
await readFile(join(appDir, "openapi.json"), "utf8"),
) as { paths: Record<string, unknown> };
expect(openapiDoc.paths["/items/{id}"]).toBeDefined();
await rm(dir, { recursive: true, force: true });interfaceCreateAppOptions
interface CreateAppOptions {
readonly name: string;
readonly baseDir?: string;
readonly template?: CreateTemplate;
readonly force?: boolean;
}Options for createApp.
typeCreateTemplate
type CreateTemplate = "http" | "serverless";The starter templates available to createApp.
constlistTemplates
const listTemplates: () => Promise<readonly CreateTemplate[]>;Lists the available starter templates (the generated directories under packages/cli/templates-built/, built from tested snippets).
const templates = await listTemplates();["http", "serverless"]Dev
functionbundleDevServer
function bundleDevServer(options: BundleDevServerOptions): Promise<string>;Bundles a self-contained dev server in runtime mode (ALLOW_GLOBAL_REGISTRY folded to false) from a generated entry that imports the user's app and serves it over node:http. Returns outfile.
The CLI never imports @smitejs/http itself; esbuild resolves it from the user's installed packages at bundle time.
await bundleDevServer({
cwd,
entry,
alias: sourceAliases,
outfile,
});"globalRegistry"interfaceBundleDevServerOptions
interface BundleDevServerOptions {
readonly cwd: string;
readonly entry: string;
readonly alias?: Readonly<Record<string, string>>;
readonly docs?: boolean;
readonly title?: string;
readonly outfile: string;
}Options for bundleDevServer.
functioncollectWatchedFiles
function collectWatchedFiles(options: CollectWatchedFilesOptions): Promise<string[]>;The files smite dev watches: the config plus every .ts/.mjs/.json source under each entry's directory, excluding generated artifacts (*.client.ts, openapi.json) and build/install directories so regeneration never re-triggers a rebuild.
interfaceCollectWatchedFilesOptions
interface CollectWatchedFilesOptions {
readonly cwd: string;
readonly configPath: string;
readonly entries: readonly string[];
}Options for collectWatchedFiles.
functiondev
function dev(options?: DevOptions): Promise<void>;Runs the local development loop:
- Loads
smite.config.tsand compiles the app entries in collect mode. - Runs every generator plugin (typed client, OpenAPI, …).
- Bundles a runtime dev server with esbuild and spawns it as a child
nodeprocess. - Watches the sources; on change it reloads the config (when the config itself changed), re-runs the generators, rebundles, and restarts the server.
Resolves when signal aborts or the process receives SIGINT/SIGTERM.
interfaceDevOptions
interface DevOptions {
readonly config?: string;
readonly port?: number;
readonly host?: string;
readonly watch?: boolean;
readonly alias?: Readonly<Record<string, string>>;
readonly signal?: AbortSignal;
}Options for dev.
classDevWatcher
class DevWatcher {
private readonly options;
private readonly intervalMs;
private last;
private timer;
constructor(options: DevWatcherOptions);
poll(): Promise<void>;
start(): void;
stop(): void;
}A small file watcher that fingerprints mtimeMs + size on a poll interval. Works everywhere (recursive fs.watch is not portable) and needs no native dependency. The first poll only seeds the baseline.
const watcher = new DevWatcher({
watch: async () => [join(dir, "file.txt")],
intervalMs: 20,
onChange: (paths) => changed.push(...paths),
});
await watcher.poll();[]
[join(dir, "file.txt")]interfaceDevWatcherOptions
interface DevWatcherOptions {
readonly watch: () => Promise<readonly string[]>;
readonly intervalMs?: number;
readonly onChange: (changed: readonly string[]) => void | Promise<void>;
}Options for DevWatcher.
functionspawnServer
function spawnServer(outfile: string, options: SpawnServerOptions): ChildProcess;Spawns a bundled dev server as a child node process with PORT/HOST in its environment. The child's output is inherited by default so logs stream to the terminal; pass stdio: "pipe" to capture them.
interfaceSpawnServerOptions
interface SpawnServerOptions {
readonly cwd: string;
readonly port: number;
readonly host: string;
readonly stdio?: "inherit" | "pipe";
}Options for spawnServer.
Inspect
interfaceAppSummary
interface AppSummary {
readonly app: string;
readonly routes: readonly RouteSummary[];
readonly aspects: readonly string[];
readonly extensions: Readonly<Record<string, number>>;
}The routes and aspects of one compiled app.
packages/cli/src/inspect.ts:18
functiondescriptorTree
function descriptorTree(node: Descriptor<string, unknown>, maxDepth?: number): DescriptorTree;Builds the descriptor tree under a node, following child references and stopping at nodes already visited. Data values are summarized: functions, zod schemas and objects print as placeholders.
const [app] = await compileApps({ entries: [entry], alias });
const tree = app ? descriptorTree(app) : undefined;"app"
[
"http.aspect",
"http.aspect",
"http.route",
"http.route",
]
"├─ http.route shop:http.route:products"
"http.handler"
"req={ params }"
"fn=[function]"packages/cli/src/inspect.ts:124
interfaceDescriptorTree
interface DescriptorTree {
readonly kind: string;
readonly key: string;
readonly relation?: string;
readonly data: Readonly<Record<string, string>>;
readonly children: readonly DescriptorTree[];
}A descriptor and its children, as printed by smite inspect.
packages/cli/src/inspect.ts:30
functionformatRoutes
function formatRoutes(summaries: readonly AppSummary[]): string;Renders route summaries as an aligned text table.
packages/cli/src/inspect.ts:171
functionformatTree
function formatTree(tree: DescriptorTree): string;Renders a descriptor tree with box-drawing branches.
packages/cli/src/inspect.ts:214
interfaceRouteSummary
interface RouteSummary {
readonly app: string;
readonly method: string;
readonly path: string;
readonly router: string;
readonly inputs: readonly string[];
readonly handler: boolean;
}One endpoint of a compiled app, as listed by smite routes.
functionsummarizeApps
function summarizeApps(apps: readonly AppDescriptor[]): AppSummary[];Lists the routes, aspects and other extensions of compiled apps by walking their descriptors generically, without importing @smitejs/http.
const apps = await compileApps({ entries: [entry], alias });
const [shop] = summarizeApps(apps);"shop"
["middleware", "guard"]
[
{
app: "shop",
method: "POST",
path: "/orders",
router: "orders",
inputs: ["headers", "body"],
handler: true,
},
{
app: "shop",
method: "GET",
path: "/products/:id",
router: "products",
inputs: ["params"],
handler: true,
},
]packages/cli/src/inspect.ts:69
Plugins
functiondeploy
function deploy(plugins: readonly SmitePlugin[], name: string): Promise<void>;Deploys through the named provider plugin after its artifact has been generated.
packages/cli/src/plugins.ts:78
functiondispatch
function dispatch(plugins: readonly SmitePlugin[], name: string, ctx: PluginContext): Promise<void>;Runs the plugin whose name matches, erroring on unknown or duplicate names.
await dispatch([plugin], "client", { apps: [app] });packages/cli/src/plugins.ts:32
interfacePluginContext
interface PluginContext {
readonly apps: readonly AppDescriptor[];
readonly entries?: readonly string[];
readonly buildEntries?: readonly string[];
readonly build?: SmiteBuildConfig;
readonly compiledEntries?: readonly CompiledEntry[];
}The context every generator receives: the union of app nodes registered by all compiled entries. Generators traverse the IR themselves via childrenOf for the kinds they know.
functionrunAll
function runAll(plugins: readonly SmitePlugin[], ctx: PluginContext): Promise<void>;Runs every plugin in declaration order. Used by smite dev to regenerate all artifacts before serving.
await runAll(plugins, { apps: [] });["first", "second"]packages/cli/src/plugins.ts:62
interfaceSmitePlugin
interface SmitePlugin {
readonly name: string;
readonly run: (ctx: PluginContext) => void | Promise<void>;
readonly deploy?: () => void | Promise<void>;
}A generator contributed by a user-installed package. The CLI loads plugins from smite.config.ts and runs the one named on the command line.
packages/cli/src/plugins.ts:20
Reference
functionappsOf
function appsOf(entries: readonly CompiledEntry[]): readonly AppDescriptor[];Returns the deduplicated app union from compiled entry snapshots.
packages/cli/src/compile.ts:37
functioncompileAppEntries
function compileAppEntries(options: CompileAppsOptions): Promise<readonly CompiledEntry[]>;Bundles each entry in collect mode and retains its descriptor graph for artifact generators that need entry-scoped metadata.
packages/cli/src/compile.ts:95
interfaceCompiledEntry
interface CompiledEntry {
readonly entry: string;
readonly apps: readonly AppDescriptor[];
readonly descriptors: readonly Descriptor<string, unknown>[];
}The descriptor snapshot collected from one runtime entry.