@lunora/cli
Version:
The Lunora CLI: init, dev, deploy, codegen, run, reset, and migrate commands
982 lines (981 loc) • 44.2 kB
text/typescript
import { CodegenOptions, SchemaIR } from '@lunora/codegen';
import '@visulima/cerebro';
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, materializeRemoteWranglerConfig } from '@lunora/config';
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config';
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules"];
type CommandName = (typeof COMMANDS)[number];
declare const VERSION: string;
interface RunCliOptions {
argv?: ReadonlyArray<string>;
cwd?: string;
/**
* Inject a console-like logger so callers (tests) can capture cerebro's
* help / version / usage rendering. Omitted in production, where cerebro
* uses its default stdout/stderr logger.
*/
logger?: Console;
}
/**
* Run the CLI and resolve to the process exit code. cerebro handles help,
* version, usage, and unknown commands (the latter throws, caught here as 1).
* `shouldExitProcess: false` keeps the process alive so callers/tests read the
* captured exit code.
*/
declare const runCli: (options?: RunCliOptions) => Promise<number>;
/**
* The `--api-spec` flag's accepted values, mirroring `@lunora/codegen`'s
* `CodegenOptions["apiSpec"]`. `"openapi"` (the default) emits `openapi.json`;
* `"openrpc"` emits `openrpc.json`; `"both"` emits both; `"none"` emits neither.
*/
type ApiSpec = NonNullable<CodegenOptions["apiSpec"]>;
interface Logger {
debug?: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
success: (message: string) => void;
warn: (message: string) => void;
}
/**
* Narrowed view over the pail instance. `createPail` returns an intersection
* type that includes a constructor signature and `(...args: any[])` logger
* overloads, which the type-aware linter cannot safely resolve. We only ever
* call the level methods with a string, so we describe exactly that surface.
*/
interface PailLogger {
debug: (message: string) => void;
error: (message: string) => void;
info: (message: string) => void;
success: (message: string) => void;
warn: (message: string) => void;
}
declare const createLogger: () => Logger;
/**
* Direct access to the underlying pail instance for advanced use-cases.
* A Proxy keeps the public `pail` binding lazy: the real pail is only
* constructed on first property access, so importing this module (and thus
* the package barrel) stays side-effect-free.
*/
declare const pail: PailLogger;
interface CodegenCommandOptions {
/** Which API spec(s) to emit. Defaults to codegen's `"openapi"` when omitted. */
apiSpec?: ApiSpec;
cwd?: string;
/** Output format: `pretty` (default) or `json`. */
format?: string;
logger: Logger;
}
interface CodegenCommandResult {
advisories: ReadonlyArray<{
detail: string;
level: string;
name: string;
remediation: string;
}>;
cronTriggers: ReadonlyArray<string>;
/** Set when the run aborted on an invalid `--format` before codegen ran. */
error?: string;
outputDirectory: string;
}
declare const runCodegenCommand: (options: CodegenCommandOptions) => CodegenCommandResult;
/** Rows per HTTP request when importing. Convex uses ~500; same here. */
declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
/**
* Minimal projection of `globalThis.fetch` for the export path — we need
* `body` as a stream-iterable, which the shared {@link FetchLike} type
* intentionally hides for the JSON-only commands.
*/
type StreamingFetchLike = (input: string, init?: {
body?: string;
headers?: Record<string, string>;
method?: string;
}) => Promise<{
body: ReadableStream<Uint8Array> | null;
json: () => Promise<unknown>;
ok: boolean;
status: number;
text: () => Promise<string>;
}>;
interface ExportCommandOptions {
cwd?: string;
fetchImpl?: StreamingFetchLike;
logger: Logger;
/** Output file path; `undefined`/`-` streams to stdout. */
out?: string;
/** Guardrail: refuse to target localhost when set. */
prod?: boolean;
/** Comma-separated table list; omit to export every table. */
tables?: string;
/** Admin bearer token (or `LUNORA_ADMIN_TOKEN`). */
token?: string;
/** Worker URL (default `http://localhost:8787`). */
url?: string;
}
interface ExportCommandResult {
bytes: number;
code: number;
/** Number of NDJSON lines streamed (0 on error). */
rows: number;
}
/**
* Stream an export. The worker emits NDJSON; we count newlines as we go and
* pipe straight to the output sink, so a 10M-row export doesn't materialise
* the body in memory.
*/
declare const runExportCommand: (options: ExportCommandOptions) => Promise<ExportCommandResult>;
interface ImportCommandOptions {
/** Rows per HTTP request. Defaults to {@link DEFAULT_IMPORT_BATCH_SIZE}. */
batchSize?: number;
cwd?: string;
fetchImpl?: StreamingFetchLike;
/** Source NDJSON file. Required. */
file: string;
logger: Logger;
prod?: boolean;
/**
* Wrap each line as `{table:<name>,doc:<line>}`. Use when the source NDJSON
* is bare docs from a single table — Convex's `convex import --table users`
* shape.
*/
table?: string;
token?: string;
url?: string;
/** Confirm bulk-writing production. Required alongside `--prod`. */
yes?: boolean;
}
interface ImportCommandResult {
body: unknown;
code: number;
/** Total inserted rows across batches. */
inserted: number;
}
/**
* Stream an NDJSON file in chunks, POSTing each batch to
* `/_lunora/admin/import`. We keep the line buffer bounded by `batchSize` so a
* multi-GiB file imports without buffering everything in memory.
*/
declare const runImportCommand: (options: ImportCommandOptions) => Promise<ImportCommandResult>;
/**
* Injectable probe for a Docker-compatible container engine. Tests pass a
* stub; production uses {@link isDockerAvailable}.
*/
type DockerProbe = () => boolean;
interface SpawnDescriptor {
args: ReadonlyArray<string>;
/**
* Capture the child's stdout (in addition to streaming it to the parent), so
* the caller can parse it — used by `deploy` to read the deployed URL from
* `wrangler deploy` output. Each chunk is still teed to the parent's stdout
* so the user sees live progress. Mutually exclusive with `stdoutToStderr`.
*/
captureStdout?: boolean;
command: string;
cwd?: string;
env?: Readonly<Record<string, string>>;
/**
* Pipe this string into the child's stdin and close it. Used to feed
* `wrangler secret put` its value without exposing it on the command
* line or in env. When absent, stdin is inherited from the parent.
*/
input?: string;
/**
* Route the child's stdout to the parent's STDERR instead of stdout. Set in
* `--format json` mode so a spawned tool's human output (e.g. `wrangler
* deploy`'s progress + the deployed URL) can't interleave with — and corrupt
* — the single JSON document the command prints to stdout.
*/
stdoutToStderr?: boolean;
}
interface SpawnResult {
code: number;
/** The captured stdout, present only when the descriptor set `captureStdout`. */
stdout?: string;
}
/**
* Injectable spawner. Tests pass a stub that just records the descriptor
* instead of executing a real subprocess.
*/
type Spawner = (descriptor: SpawnDescriptor) => Promise<SpawnResult>;
declare const defaultSpawner: Spawner;
interface RecordedSpawn {
descriptor: SpawnDescriptor;
}
/**
* Test helper: returns a spawner that records every invocation and resolves
* with the configured exit code.
*/
declare const createRecordingSpawner: (exitCode?: number) => {
calls: RecordedSpawn[];
spawner: Spawner;
};
interface SecretListRunnerResult {
code: number;
stderr: string;
stdout: string;
}
/** Runs an argv and resolves its captured output. Injected in tests. */
type SecretListRunner = (command: string, args: ReadonlyArray<string>, cwd: string) => Promise<SecretListRunnerResult>;
interface ListRemoteSecretsInputs {
cwd: string;
/** Cloudflare environment name (`--env`). */
env?: string;
/** Injected command runner; defaults to a real `wrangler secret list`. */
runner?: SecretListRunner;
/** Target a temporary-account deployment (`--temporary`). */
temporary?: boolean;
}
interface ListRemoteSecretsResult {
/** Diagnostic message when `ok` is false. */
error?: string;
/** Remote secret names (sorted), empty when none or on failure. */
names: ReadonlyArray<string>;
/** False when wrangler failed or its output could not be parsed. */
ok: boolean;
}
type FetchLike = (input: string, init?: {
body?: string;
headers?: Record<string, string>;
method?: string;
}) => Promise<{
json: () => Promise<unknown>;
ok: boolean;
status: number;
text: () => Promise<string>;
}>;
interface RunCommandOptions {
args?: string;
cwd?: string;
fetchImpl?: FetchLike;
functionPath: string;
logger: Logger;
shard?: string;
url?: string;
}
interface RunCommandResult {
body: unknown;
code: number;
requestUrl: string;
}
declare const runRpcCommand: (options: RunCommandOptions) => Promise<RunCommandResult>;
interface DeployCommandOptions {
/** Override the schema-drift gate — deploy even with breaking drift and no new migration. */
allowSchemaDrift?: boolean;
/** Which API spec(s) codegen emits. Defaults to codegen's `"openapi"` when omitted. */
apiSpec?: ApiSpec;
cwd?: string;
/** Docker-availability probe injected in tests. Defaults to a real `docker info` check. */
dockerAvailable?: DockerProbe;
/**
* Validate, bundle, and run all pre-deploy gates without publishing
* (`wrangler deploy --dry-run`). Post-deploy steps (data migrations, schema
* baseline re-bless) are skipped since nothing shipped.
*/
dryRun?: boolean;
env?: string;
/** Fetch implementation injected in tests for `--migrate` RPC calls. */
fetchImpl?: FetchLike;
/** Output format: `pretty` (default) or `json`. */
format?: string;
/** Set to `false` to disable interactive spinners (test injection). */
interactive?: boolean;
logger: Logger;
/**
* When true, after a successful `wrangler deploy`, discover and run all
* pending data migrations via the worker's `/_lunora/migrate` admin RPC.
* The worker must be live (exit 0) before migrations are attempted.
*
* Implementation note: the status RPC returns the full shard-level
* migration state, but there is no single authoritative "list of pending
* migration ids" that can be read client-side before running the worker.
* Instead, `--migrate` runs `migrate status` followed by `migrate up` for
* each migration id discovered locally via `discoverMigrations`. The
* worker's `MigrationRunner` is idempotent — running `up` on an already-
* applied migration is a no-op — so this approach is safe.
*/
migrate?: boolean;
/** Admin bearer token for `--migrate` (falls back to `LUNORA_ADMIN_TOKEN`). */
migrateToken?: string;
/**
* Worker URL for `--migrate`. REQUIRED when `--migrate` is set — the deploy
* handler never captures the URL `wrangler deploy` published to, so there is
* no safe default; omitting it would silently target `http://localhost:8787`
* (the dev worker), applying the migration to local state instead of prod.
*/
migrateUrl?: string;
/**
* Confirm a production data migration triggered via `--migrate` (the
* `migrate up --prod` confirmation the standalone command requires). Without
* it a `--migrate --migrate-url <prod>` deploy refuses to run the migration.
*/
migrateYes?: boolean;
/**
* Emit the bundled worker to this directory via `wrangler deploy --outdir`
* (paired with `dryRun` by `lunora build`). Also writes esbuild metadata to
* `<outDir>/bundle-meta.json`. When unset, no artifact is written.
*/
outDir?: string;
/**
* Upload a preview version (`wrangler versions upload`) instead of a live
* `wrangler deploy`. Codegen + the drift gate + validation still run, but
* the post-deploy finalize (migrations, baseline re-bless, auto-link, the
* production summary) is skipped — a preview never shifts live traffic.
*/
preview?: boolean;
/** Railpack-availability probe injected in tests. Defaults to a real `railpack --version` + `BUILDKIT_HOST` check. */
railpackAvailable?: DockerProbe;
/** Confirm prompt for the missing-secret offer; injected in tests. Defaults to the TTY prompt. */
secretConfirm?: (message: string) => Promise<boolean>;
/** Remote-secret lister for the missing-secret offer; injected in tests. Defaults to `wrangler secret list`. */
secretLister?: (inputs: ListRemoteSecretsInputs) => Promise<ListRemoteSecretsResult>;
skipCodegen?: boolean;
spawner?: Spawner;
/**
* Deploy to a temporary Cloudflare account (`wrangler deploy --temporary`).
* For unauthenticated use only: wrangler provisions a short-lived account +
* token, deploys, and prints a claim URL; the deployment stays live ~60
* minutes before the unclaimed account is deleted. Wrangler itself errors
* if credentials are already present (OAuth / `CLOUDFLARE_API_TOKEN` /
* global API key), so we pass the flag straight through without guarding.
*/
temporary?: boolean;
/** Re-bless the committed schema baseline with the current shape (accepts breaking drift). */
updateSchemaBaseline?: boolean;
}
interface DeployCommandResult {
code: number;
descriptor: SpawnDescriptor | undefined;
/** Set when the run aborted before reaching the wrangler invocation. */
error?: string;
/** The schema-drift gate verdict, when it ran (skipped on `--skip-codegen`). */
schemaDrift?: {
blocked: boolean;
reason: string;
};
validation: {
problems: ReadonlyArray<string>;
wranglerPath: string | undefined;
};
}
/**
* Run a deploy, then (in `--format json` mode) serialize the structured
* {@link DeployCommandResult} to stdout. Human/progress logging is routed to
* stderr for json output so stdout carries only the single JSON document.
*/
declare const runDeployCommand: (options: DeployCommandOptions) => Promise<DeployCommandResult>;
/**
* Start the codegen watch loop and return a handle to stop it. Regenerates on
* startup, then on debounced changes under `lunora/` (ignoring writes to the
* `_generated/` output to avoid a feedback loop). If the platform can't do a
* recursive watch, it logs once and falls back to startup-only codegen.
*/
declare const startCodegenWatch: (options: CodegenWatcherOptions) => CodegenWatcherHandle;
interface CodegenWatcherOptions {
/** Which API spec(s) to emit. Defaults to codegen's `"openapi"` when omitted. */
apiSpec?: CodegenOptions["apiSpec"];
/** Debounce window for coalescing rapid edits. Defaults to 100ms. */
debounceMs?: number;
logger: Logger;
/** Override the lunora subdirectory name. Defaults to `"lunora"`. */
lunoraDirectory?: string;
/** Project root containing the `lunora/` directory. */
projectRoot: string;
}
interface CodegenWatcherHandle {
/** Stop watching and cancel any pending regeneration. */
close: () => void;
/**
* `true` when the platform supports recursive watch and the loop is active.
* `false` when `fs.watch({ recursive })` threw — startup-only codegen was run
* but schema edits will NOT auto-regenerate. Callers can surface this in the
* dev banner so the degraded state is visible beyond the single startup warning.
*/
watchAvailable: boolean;
}
/**
* Start the studio server and resolve once it is listening. Loads the static
* bundle + renders the host HTML once up front; serves them and proxies
* `/_lunora/*` (HTTP + WS) to the worker.
*/
declare const startStudioServer: (options: StudioServerOptions) => Promise<StudioServerHandle>;
interface StudioServerOptions {
/** Project root — `.dev.vars` is read from here for the admin token. */
cwd: string;
/** Loopback host to bind. Defaults to `127.0.0.1` (admin tooling stays local). */
host?: string;
/** One-time warning sink for a missing/unbuilt `@lunora/studio`. */
logger?: {
warnOnce?: (message: string) => void;
};
/** Port to listen on. */
port: number;
/** Origin of the `wrangler dev` worker, e.g. `http://localhost:8787`. */
workerOrigin: string;
}
interface StudioServerHandle {
/** Stop listening and release the port. */
close: () => Promise<void>;
/** The URL to open in a browser. */
url: string;
}
/**
* How the dev child runs. `wrangler` is the classic `lunora dev` stack (wrangler
* worker + embedded studio + codegen watch) for a standalone class-C project.
* `vite` is a project on `@lunora/vite`: the plugin already runs the worker,
* studio, and codegen inside the Vite dev server, so `lunora dev` runs the
* project's own dev script and gets out of the way — this also covers class-B
* frameworks whose own dev server runs the worker in `workerd` (Astro 6 +
* `@astrojs/cloudflare`, which embeds `@cloudflare/vite-plugin` in `astro dev`:
* SSR + `/_lunora/*` + `ShardDO` in one process, HMR intact). `framework-worker`
* is a class-B framework whose dev server CANNOT host the `ShardDO` Durable
* Object (SvelteKit / Nuxt: their adapters use wrangler's `getPlatformProxy()`,
* which runs an empty-script Miniflare and does not emulate internal DOs); there
* `lunora dev` runs the framework's own dev server (front door, HMR, and — via
* its `@lunora/vite` plugin — studio + codegen) AND a second `wrangler dev`
* sidecar that owns the real `ShardDO` in `workerd`, wired via the committed
* `wrangler.dev.jsonc`.
*/
type DevFlavor = "framework-worker" | "vite" | "wrangler";
/** A running worker child the orchestrator controls: send signals, await its exit. */
interface WorkerProcess {
/** Resolves with the worker's exit code (1 if it failed to start). */
exited: Promise<number>;
kill: (signal: NodeJS.Signals) => void;
}
/** Spawns the worker child. Injectable so tests drive the orchestration without a real process. */
type WorkerSpawner = (descriptor: SpawnDescriptor & {
tag: string;
}, logger: Logger) => WorkerProcess;
interface DevCommandOptions {
/** Which API spec(s) the codegen watcher emits. Defaults to codegen's `"openapi"` when omitted. */
apiSpec?: ApiSpec;
/** Disable the codegen watch loop. */
codegen?: boolean;
cwd?: string;
/** Injection seam for tests — defaults to the real `.dev.vars` scaffolder. */
ensureEnv?: typeof ensureDevVariables;
/** Injection seam for tests — defaults to the real `.dev.vars.example` package-aware scaffolder. */
ensureExample?: typeof ensureDevVarsExample;
/** Injection seam for tests — defaults to the real empty-secret/admin-token filler. */
fillSecrets?: typeof fillDevSecrets;
/** Injection seam for tests — defaults to the real free-port probe ({@link findAvailablePort}). */
findFreePort?: (preferred: number) => Promise<number>;
/** Dev flavor override (tests / callers that already detected it) — defaults to {@link detectDevFlavor}. */
flavor?: DevFlavor;
/** Injection seam for tests — defaults to the real IPv6-loopback probe ({@link hasIpv6Loopback}). */
hasIpv6Loopback?: () => boolean;
logger: Logger;
/** Injection seam for tests — defaults to the real remote-config materializer. */
materializeRemote?: typeof materializeRemoteWranglerConfig;
/** Studio server port. */
port?: number;
/** Proxy D1/KV/R2 bindings to the deployed worker during dev (`LUNORA_REMOTE=1` / `--remote`); DO shards stay local. */
remote?: boolean;
/** Injection seam for tests — defaults to the real codegen watcher. */
startCodegen?: typeof startCodegenWatch;
/** Injection seam for tests — defaults to the real studio server. */
startStudio?: typeof startStudioServer;
/** Injection seam for tests — defaults to spawning a real `wrangler dev`. */
startWorker?: WorkerSpawner;
/** Disable the embedded studio server. */
studio?: boolean;
/** `wrangler dev` port. */
workerPort?: number;
}
interface DevRemotePlan {
/** Short binding labels remoted (e.g. `"DB (D1)"`), for the banner. */
bindings: string[];
/**
* Removes the generated temp wrangler config when dev exits. Always present
* and idempotent — a no-op when remote mode is off or nothing was
* materialized. The dev loop calls it on every shutdown path.
*/
cleanup: () => void;
/** Whether remote mode was requested. */
enabled: boolean;
/** Why remote mode didn't take effect despite being requested, for logging. */
reason?: string;
}
interface DevCommandPlan {
codegenEnabled: boolean;
/** Which stack the child runs — see {@link DevFlavor}. */
flavor: DevFlavor;
/**
* One-line redirect hint printed when a meta-framework is detected on the
* wrangler flavor: without `@lunora/vite` in the dependencies the worker
* still runs *inside* the framework's dev server, so the user should run
* their framework dev script for the full app. `undefined` for the vite
* flavor (`lunora dev` already runs the project's dev script there) and
* for a standalone project. Purely informational: the wrangler spawn runs
* regardless.
*/
frameworkHint?: string;
/**
* True when `wrangler dev` was given `--ip 127.0.0.1` because the host has no
* IPv6 loopback (`::1`) — surfaced so the dev loop can note the rebind.
* Always `false` for the vite flavor (the plugin owns its own bind).
*/
ipv4LoopbackForced: boolean;
/** The remote-binding decision: which D1/KV/R2 bindings hit the deployed worker. */
remote: DevRemotePlan;
/**
* The `wrangler dev` sidecar for the `framework-worker` flavor (SvelteKit /
* Nuxt): a second child that owns the real `ShardDO` in `workerd`, wired via
* the committed `wrangler.dev.jsonc`. `undefined` for every other flavor —
* only the two-process class-B stack has a sidecar. When present, `wrangler`
* (above) is the framework's own dev server (the front door / HMR) and this
* is the Lunora realtime plane.
*/
sidecar?: SpawnDescriptor & {
tag: string;
};
studioEnabled: boolean;
studioPort: number;
workerOrigin: string;
workerPort: number;
/** The primary child `lunora dev` spawns: `wrangler dev` (wrangler flavor) or the framework/`vite dev` server (vite / framework-worker). */
wrangler: SpawnDescriptor & {
tag: string;
};
}
/**
* Plan `lunora dev`. Wrangler flavor: the worker runs via `wrangler dev` and
* nothing else as a child process. Vite flavor (`@lunora/vite` declared): the
* plugin already runs the worker inside the Vite dev server, so the one child
* is the project's own dev script (`vite dev`, `astro dev`, …) and every CLI
* sibling is disabled. Pure + synchronous so it's unit-testable.
*/
declare const planDevCommand: (options: DevCommandOptions) => DevCommandPlan;
/**
* Start codegen watch + the studio server, spawn `wrangler dev`, print the
* banner, and resolve when the worker exits or the user interrupts — tearing
* down the sibling servers either way. The three side-effecting pieces (worker,
* studio, codegen) are injectable so this is testable without real I/O.
*/
declare const runDevCommand: (options: DevCommandOptions) => Promise<{
code: number;
plan: DevCommandPlan;
}>;
/** Supported CI providers. */
type CiProvider = "github" | "gitlab";
type PackageManager = "pnpm" | "npm" | "yarn" | "bun";
/** True when `manager` is on PATH — probed by running `<manager> --version`. Injectable for tests. */
type PackageManagerProbe = (manager: PackageManager) => boolean;
/** A registry item a feature can install. */
type FeatureItem = "auth" | "auth-auth0" | "auth-clerk" | "mail";
/** A single file the item scaffolds into the project. */
interface RegistryFile {
/** Source path inside the item dir (e.g. `schema.ts`). */
from: string;
/** Merge strategy. `create-or-skip` writes whole files; `schema-extension` AST-merges schema.ts. */
merge: "create-or-skip" | "schema-extension";
/** Destination relative to the project root (e.g. `lunora/ratelimit/index.ts`). */
to: string;
}
/** A wrangler.jsonc binding addition. `path` is the jsonc key path; `value` the value to set. */
interface RegistryBinding {
path: ReadonlyArray<string>;
value: unknown;
}
/**
* An environment variable an item needs. Scaffolded into `.dev.vars` (Workers'
* local-secrets file) on add — non-secrets get their `value`; secrets get an
* empty placeholder and a reminder to run `wrangler secret put` for production.
*/
interface RegistryEnvVariable {
/** Human note on what the variable is for. */
description?: string;
/** The variable name (e.g. `RESEND_API_KEY`). */
name: string;
/** Mark as a secret: never write a value, only a placeholder, and remind about prod. Defaults to `true` when no `value` is given. */
secret?: boolean;
/** A default/example value for non-secret vars. */
value?: string;
}
/** A re-export the item needs injected into the worker entry point (class-B/C only). */
interface EntrypointReexport {
/** Optional JS comment placed above the re-export line. */
comment?: string;
/** Module specifier (e.g. `"_generated/workflows"` → `export * from "./lunora/_generated/workflows"`). */
module: string;
}
/** The `registry.json` manifest shape. */
interface RegistryManifest {
/** wrangler.jsonc additions (best-effort structural edits). */
bindings?: ReadonlyArray<RegistryBinding>;
/** npm deps to add to the project package.json (name → version range). */
deps?: Readonly<Record<string, string>>;
description?: string;
/** npm devDependencies to add to the project package.json. */
devDependencies?: Readonly<Record<string, string>>;
/** Post-install guidance printed after the item is added (per-item next steps). */
docs?: string;
/** Worker-entry re-exports the item needs (class-B/C only). */
entrypointReexports?: ReadonlyArray<EntrypointReexport>;
/** Environment variables the item needs; scaffolded into `.dev.vars`. */
envVars?: ReadonlyArray<RegistryEnvVariable>;
files: ReadonlyArray<RegistryFile>;
name: string;
/** Other registry items this one depends on (resolved transitively, deps first). */
requires?: ReadonlyArray<string>;
/** Short human-readable label (distinct from the longer `description`). */
title?: string;
}
interface AddCommandOptions {
/** Bypass the `--source` safety gate (matches init). */
allowUnsafeSource?: boolean;
/** `registry build --check`: verify the index is current instead of rewriting it. */
check?: boolean;
/** Inject a confirmer for non-interactive callers / tests. */
confirm?: (prompt: string) => Promise<boolean>;
cwd?: string;
/** Preview the file-level changes (a content diff) and write nothing. */
diff?: boolean;
/** Print the plan and stop without writing anything. */
dryRun?: boolean;
/** Local registry root (offline / tests). Expects per-item subdirs, each with a `registry.json`. */
from?: string;
/** Emit a JSON snapshot of the plan/result. */
json?: boolean;
/** `--list`: enumerate available items instead of adding. */
list?: boolean;
logger: Logger;
/** Item names to add (positional args). */
names: ReadonlyArray<string>;
/** `registry build` output path for the generated catalog (defaults to the root's `index.json`). */
out?: string;
/** Force-overwrite existing files (take the incoming copy) instead of skipping/conflicting. */
overwrite?: boolean;
/** Override the git ref (branch, tag, or commit) items are fetched from (default: version-derived); appended to the `source` base when that is set. Ignored when `from` is set. */
ref?: string;
/** Override the remote registry source base (default gh:anolilab/lunora/registry). */
source?: string;
/**
* Customize each resolved manifest after it is loaded but before the plan is
* printed / reconciled — used to inject user-chosen values into otherwise
* static manifests (e.g. the R2 `bucket_name` the init storage prompt asks
* for). Applied to every item; return the manifest unchanged to leave it as-is.
*/
transformManifest?: (manifest: RegistryManifest) => RegistryManifest;
/** Skip the package.json mutation confirmation prompt. */
yes?: boolean;
}
interface AddCommandResult {
/** Bindings written to wrangler.jsonc. */
bindings: ReadonlyArray<string>;
code: number;
/** Deps added to package.json. */
deps: ReadonlyArray<string>;
/** Files skipped because they already existed. */
skipped: ReadonlyArray<string>;
/** Files written (absolute paths). */
written: ReadonlyArray<string>;
}
/**
* A feature offered in the post-scaffold multi-select. `auth`/`email` carry a
* sub-prompt or alias; every other value IS the registry item name applied
* directly (`storage` → the `storage` registry item, etc.).
*/
type StackFeature = "ai" | "auth" | "backup" | "browser" | "cloudflare-access" | "crons" | "email" | "flags" | "hyperdrive" | "payment" | "presence" | "queue" | "storage" | "workflow";
/** Customize a resolved manifest before it is written (e.g. inject the chosen R2 bucket name). */
type OfferTransformManifest = (manifest: RegistryManifest) => RegistryManifest;
/**
* One feature ready to apply: the registry item name(s), an optional manifest
* transform, and a short `label` (the feature value) shown on the combined
* progress line. Built up-front by the collectors so every prompt is answered
* before any apply runs.
*/
interface FeatureApply {
label: string;
names: ReadonlyArray<string>;
transformManifest?: OfferTransformManifest;
}
interface OfferDeps {
/**
* Apply the collected features into the new project in one batch — resolves
* `true` when every item succeeds. The CLI renders this as a single progress
* line whose label changes per feature; each plan's `transformManifest`
* customizes that item's manifest before it is written.
*/
applyAll: (plans: ReadonlyArray<FeatureApply>) => Promise<boolean>;
/** When `false`, skip all prompts and print the later-setup hint. */
interactive: boolean;
logger: Logger;
/** Multi-select among the stack features to add (TTY-backed in production). */
multiSelect: (message: string, options: ReadonlyArray<{
description?: string;
label: string;
value: StackFeature;
}>, settings?: {
defaults?: ReadonlyArray<StackFeature>;
}) => Promise<StackFeature[]>;
/**
* Features chosen non-interactively (the `--add` flag). When set, the
* multi-select and every sub-prompt are skipped — each feature is applied with
* its shipped defaults (base registry item, placeholder bindings).
*/
preselected?: ReadonlyArray<StackFeature>;
/** The new project's name — seeds smart defaults like the `project-uploads` bucket name. */
projectName: string;
/** Single-select among the auth providers (TTY-backed in production). */
select: (message: string, options: ReadonlyArray<{
description?: string;
label: string;
value: FeatureItem;
}>, settings?: {
default?: FeatureItem;
}) => Promise<FeatureItem | undefined>;
/** Single-line text input (TTY-backed in production) — used for the storage bucket-name prompt. */
text: (message: string, settings?: {
default?: string;
placeholder?: string;
}) => Promise<string>;
}
type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid";
interface InitCommandOptions {
/**
* Add features non-interactively after scaffolding (the `--add` flag): a
* comma-separated list of `ai | auth | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow`.
* Bypasses the interactive multi-select and sub-prompts —
* each named feature is applied with its shipped defaults.
*/
add?: string;
/**
* When true, accept `--source` values that don't start with `gh:` /
* `github:` / `https://` or that contain `..`. Defaults to false; the CLI
* gate exists to stop arbitrary filesystem / scheme sources from being
* pulled without the caller opting in.
*/
allowUnsafeSource?: boolean;
/** When set, also scaffold a CI deploy pipeline for the given provider. */
ci?: CiProvider;
cwd?: string;
/**
* Walk the whole flow — prompts, task list, next-steps, mascot — but make no
* changes: skip the template fetch/copy, the feature applies, the dependency
* install, and `git init`. Each skipped action logs a `would …` line instead.
*/
dryRun?: boolean;
/**
* Local directory containing the template subdirs (e.g. `vite/`,
* `standalone/`). When provided, skips the network fetch entirely.
* Useful for offline runs, the clean-machine smoke test, and unit tests.
*/
from?: string;
/**
* When true, configure Lunora into the CURRENT project (`cwd`) instead of
* scaffolding a new directory. Finds an existing `vite.config.*` and
* patches it via `patchViteConfig`, or creates a minimal one when absent.
* All other scaffold options (`name`, `templateType`, `source`, `from`)
* are ignored in this mode.
*/
inPlace?: boolean;
/**
* Inject the post-scaffold install offer's prompts (tests). When set, the
* offer runs regardless of TTY: `confirmInstall` drives the yes/no, and
* `selectManager` picks among the detected managers.
*/
installPrompt?: {
confirmInstall: () => Promise<boolean>;
selectManager: (managers: ReadonlyArray<PackageManager>) => Promise<PackageManager>;
};
/**
* Force the post-scaffold "add auth / email?" offer on (the `--interactive`
* flag). When omitted, the offer runs only when stdin is a TTY. `--yes`
* suppresses it regardless. Has no effect once {@link prompt} is injected.
*/
interactive?: boolean;
logger: Logger;
name?: string;
/**
* Local directory holding create-vite bases (one `template-<id>/` subdir per
* framework). When set with `vite`, the overlay copies the base from disk
* instead of fetching `create-vite` over the network — offline mode + tests.
*/
overlayBaseFrom?: string;
/** Probe for which package managers are installed (tests). Defaults to a real `<pm> --version` check. */
packageManagerProbe?: PackageManagerProbe;
/**
* Inject the offer's prompts (tests). When set, the offer is treated as
* interactive regardless of TTY, and these drive the feature multi-select,
* the auth-provider sub-select, and the storage bucket-name text input.
*/
prompt?: Pick<OfferDeps, "multiSelect" | "select" | "text">;
/**
* Override the git ref (branch, tag, or commit) the default template source
* is fetched from. Takes precedence over the version-derived ref. Ignored
* when `source` or `from` is set.
*/
ref?: string;
/** Local registry root for the offer's `runAddCommand` (offline / tests). Mirrors `from` but for registry items. */
registryFrom?: string;
/** Override the remote registry source base for the offer (default `gh:anolilab/lunora/registry`). */
registrySource?: string;
/**
* Override the remote source giget downloads from. Default:
* `gh:anolilab/lunora/templates/<templateType>#<ref>`, where `<ref>` is
* the `ref` option when set, else derived from the CLI version (pre-release
* channels → their branch, stable → `main`). Tests typically use `from`
* instead to skip the network.
*/
source?: string;
/** Spawner for the post-scaffold dependency install (tests inject a recording stub). Defaults to a real subprocess. */
spawner?: Spawner;
templateType?: Template;
/**
* Scaffold via the **create-vite overlay** for this framework (`react`,
* `vue`, `solid`, `svelte`, `vanilla`) instead of a bespoke template: fetch
* the official create-vite base and apply the Lunora layer on top. Takes
* precedence over `templateType`.
*/
vite?: string;
/** Suppress the offer entirely (the `--yes` flag): scaffold only, print the later-setup hint. */
yes?: boolean;
}
interface InitCommandResult {
code: number;
files: ReadonlyArray<string>;
target: string;
}
declare const runInitCommand: (options: InitCommandOptions) => Promise<InitCommandResult>;
interface MigrateGenerateCommandOptions {
cwd?: string;
logger: Logger;
/** Migration name slug. Defaults to `auto`. */
name?: string;
/** Override the current time — used by tests for deterministic file names. */
now?: () => Date;
}
interface MigrateGenerateCommandResult {
code: number;
/** Whether the diff was empty (no changes detected). */
empty: boolean;
/** Absolute path to the migration file (empty string when nothing was written). */
migrationFile: string;
}
declare const runMigrateGenerateCommand: (options: MigrateGenerateCommandOptions) => MigrateGenerateCommandResult;
/** One catalog entry as `lunora registry list` reports it. */
interface CatalogItem {
description?: string;
name: string;
}
/** A built index entry (catalog item plus its short `title`). */
interface IndexItem extends CatalogItem {
title?: string;
}
/**
* Build the catalog (`index.json` contents) from a local registry root by
* reading every item's `registry.json`. Used by both `lunora registry build`
* and the registry tests so the committed index can't drift from the item dirs.
*/
declare const buildRegistryIndex: (root: string) => {
items: IndexItem[];
};
/** `lunora registry add` (one or more item names): scaffold items into the project. */
declare const runAddCommand: (options: AddCommandOptions) => Promise<AddCommandResult>;
/**
* `lunora registry view` — inspect a registry item without installing it:
* print its plan (files / deps / env vars) followed by the full contents of each
* file it would scaffold. Resolves only the named item — no `requires` expansion.
*/
declare const runRegistryViewCommand: (options: AddCommandOptions) => Promise<AddCommandResult>;
/**
* `lunora registry build` — regenerate `index.json` from the item directories
* (the catalog `list` reads). With `--check`, verify the committed index matches
* instead of rewriting it (exits non-zero on drift) — a CI guard.
*/
declare const runBuildIndexCommand: (options: AddCommandOptions) => Promise<AddCommandResult>;
/** Validate + narrow a parsed JSON value into a {@link RegistryManifest}. */
declare const parseManifest: (raw: unknown, itemName: string) => RegistryManifest;
interface ResetCommandOptions {
all?: boolean;
/** Inject a custom confirmer (tests, non-TTY callers). Returns `true` on confirmation. */
confirm?: (prompt: string) => Promise<boolean>;
cwd?: string;
logger: Logger;
/** Skip confirmation. Required when stdin is not a TTY. */
yes?: boolean;
}
interface ResetCommandResult {
code: number;
removed: ReadonlyArray<string>;
}
declare const runResetCommand: (options: ResetCommandOptions) => Promise<ResetCommandResult>;
type InsertSchemaExtensionResult = {
ok: true;
text: string;
} | {
ok: false;
reason: "already-applied" | "invalid-identifier" | "no-define-schema" | "non-object-argument";
};
/**
* Append `.extend(<key>.extension)` and a managed import to an existing
* `lunora/schema.ts`. Idempotent: a second call for the same `key` returns
* `already-applied` and leaves the text unchanged.
* @param source the current `lunora/schema.ts` contents
* @param key the registry item key (e.g. `"ratelimit"`)
*/
declare const insertSchemaExtension: (source: string, key: string) => InsertSchemaExtensionResult;
/** Compact snapshot of a single global table — what we persist + diff. */
interface TableSnapshot {
columns: Record<string, ColumnSnapshot>;
indexes: Record<string, IndexSnapshot>;
/** Table name (also the JSON key — duplicated for ease of iteration). */
name: string;
}
interface ColumnSnapshot {
/** True when the column accepts NULL (validator wrapped in v.optional). */
nullable: boolean;
/** SQLite type affinity, derived from the validator. */
sqlType: "BLOB" | "INTEGER" | "REAL" | "TEXT";
}
interface IndexSnapshot {
fields: ReadonlyArray<string>;
name: string;
unique: boolean;
}
interface SchemaSnapshot {
tables: Record<string, TableSnapshot>;
version: 1;
}
interface DiffEntry {
kind: "addColumn" | "createIndex" | "createTable" | "dropIndex" | "dropTable";
/** Generated SQL for this delta (already terminated with `;`). */
sql: string;
/** Human-readable summary, used in migration headers. */
summary: string;
}
interface UnsupportedEntry {
kind: "columnTypeChange" | "dropColumn" | "indexRename" | "renameColumn";
/** Human-readable description, embedded as SQL comments. */
summary: string;
}
interface SchemaDiff {
/** No-op marker — true when there is genuinely nothing to apply. */
empty: boolean;
entries: ReadonlyArray<DiffEntry>;
unsupported: ReadonlyArray<UnsupportedEntry>;
}
/**
* Map a Lunora validator kind to a SQLite type affinity — the canonical
* `@lunora/d1/dialect` mapping. Re-exported under this name because
* `schema-snapshot.ts` builds the persisted snapshot from it.
*/
declare const validatorKindToSqlType: (kind: string) => ColumnSnapshot["sqlType"];
/** Emit `CREATE TABLE` SQL for a new global table. */
declare const renderCreateTable: (table: TableSnapshot) => string;
declare const renderDropTable: (tableName: string) => string;
declare const renderAddColumn: (tableName: string, columnName: string, column: ColumnSnapshot) => string;
declare const renderCreateIndex: (tableName: string, index: IndexSnapshot) => string;
declare const renderDropIndex: (tableName: string, indexName: string) => string;
/**
* Compute a {@link SchemaDiff} from two snapshots. Pure function — no I/O.
*/
declare const diffSnapshots: (previous: SchemaSnapshot | undefined, next: SchemaSnapshot) => SchemaDiff;
/**
* Render a complete migration file body from a diff. Includes a header,
* each SQL statement, and (if any) a trailing comment block describing the
* manual SQL the user needs to fill in for unsupported deltas.
*/
declare const renderMigrationFile: (name: string, diff: SchemaDiff, generatedAt: string) => string;
declare const schemaIrToSnapshot: (ir: SchemaIR) => SchemaSnapshot;
export { type AddCommandOptions, type AddCommandResult, COMMANDS, type ColumnSnapshot, type CommandName, DEFAULT_IMPORT_BATCH_SIZE, type DeployCommandOptions, type DeployCommandResult, type DevCommandOptions, type DevCommandPlan, type DiffEntry, type ExportCommandOptions, type ExportCommandResult, type FetchLike, type ImportCommandOptions, type ImportCommandResult, type IndexSnapshot, type InitCommandOptions, type InitCommandResult, type InsertSchemaExtensionResult, type Logger, type MigrateGenerateCommandOptions, type MigrateGenerateCommandResult, type RecordedSpawn, type RegistryBinding, type RegistryFile, type RegistryManifest, type ResetCommandOptions, type ResetCommandResult, type RunCliOptions, type RunCommandOptions, type RunCommandResult, type SchemaDiff, type SchemaSnapshot, type SpawnDescriptor, type SpawnResult, type Spawner, type StreamingFetchLike, type TableSnapshot, type Template, type UnsupportedEntry, VERSION, buildRegistryIndex, createLogger, createRecordingSpawner, defaultSpawner, diffSnapshots, insertSchemaExtension, pail, parseManifest, planDevCommand, renderAddColumn, renderCreateIndex, renderCreateTable, renderDropIndex, renderDropTable, renderMigrationFile, runAddCommand, runBuildIndexCommand, runCli, runCodegenCommand, runDeployCommand, runDevCommand, runExportCommand, runImportCommand, runInitCommand, runMigrateGenerateCommand, runRegistryViewCommand, runResetCommand, runRpcCommand, schemaIrToSnapshot, validatorKindToSqlType };