Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/void/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Core Vite plugin — routing, inference, migrations, CLI.

User-facing CLI output and documentation describe Cloudflare operations through Void. Never ask users to install, authenticate, or invoke Wrangler directly. Keep `wrangler.jsonc` / `wrangler.json` and `WRANGLER_*` names only where users must recognize an actual file or environment variable; implementation details may remain in source comments, tests, and debug logs.

Completed CLI actions use `printSuccess` from `src/cli/output.ts`: a blank line, a green checkmark, and green text. Use `log.step` for intermediate work. Keep listings, no-op notices, cancellations, warnings, and checkpointed or pending operations out of the success renderer. `void init` records its work in `InitReport` (`src/cli/init-report.ts`) instead of logging each step, and prints a summary before `printSuccess`: `printDone` (green ✓) for finished work and `printNextStep` (blue →) for what the user should do next. A new starter prints one line instead of its files; files outside the app and later changes to files that existed before init are listed under it. A run that stops early, on a failed step or a cancelled prompt, prints the same record under a warning, so record each change right where init makes it. Preserve JSON, token, and SQL stdout contracts.
Completed CLI actions use `printSuccess` from `src/cli/output.ts`: a blank line, a green checkmark, and green text. Use `log.step` for intermediate work. Keep listings, no-op notices, cancellations, warnings, and checkpointed or pending operations out of the success renderer. `void init` records its work in `InitReport` (`src/cli/init-report.ts`) instead of logging each step, and prints a summary before `printSuccess`: `printDone` (green ✓) for finished work and `printNextStep` (blue →) for what the user should do next. A new starter prints one line instead of its files; files outside the app and later changes to files that existed before init are listed under it. A run that stops early, on a failed step or a cancelled prompt, prints the same record under a warning, so record each change right where init makes it. Init runs its installer and drizzle-kit behind a spinner (`runBehindSpinner` in `src/cli/init-subprocess.ts`) and prints their output only when they fail. When init exits during such a step, it stops the command with the processes it started, waits until they have ended, and then calls the step's `undo`. Before such a step, set `report.unfinished` to the commands that finish it by hand; a run that stops during the step prints them. Name the install there by `resolveProjectInstall().manualCommand`, which also works for a user without `vp` on PATH. Preserve JSON, token, and SQL stdout contracts.

Human-facing URLs use `formatUrl` or `formatLink` from `src/cli/output.ts` for terminal hyperlinks with readable plain-text fallbacks. Use the shared `note` renderer for URL box titles; it pads the URL with spaces and adds the hyperlink after layout. Keep machine-readable output and copyable commands free of terminal links.

Expand Down
9 changes: 5 additions & 4 deletions packages/void/src/cli/init-git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { cancel, confirm, isCancel, log } from '@voidzero-dev/vite-plus-prompts';
import { dirname, join, resolve } from 'pathslash';
import { quoteShellPath, shellDirectory } from './init-shell.ts';
import { projectPathFromShell } from './init-shell.ts';

export async function setupGit(root: string, git?: boolean): Promise<boolean> {
if (git === false) {
Expand Down Expand Up @@ -59,8 +59,9 @@ export async function setupGit(root: string, git?: boolean): Promise<boolean> {
}

export function initialCommitCommand(root: string): string {
// Use the absolute path because init can create a subfolder.
const directory = resolve(root);
const git = directory === shellDirectory() ? 'git' : `git -C ${quoteShellPath(directory)}`;
// Init can create a subfolder. Like `vp create`, name it relative to the
// user's shell: the command repeats the path, and an absolute one wraps.
const path = projectPathFromShell(root);
const git = path === undefined ? 'git' : `git -C ${path}`;
return `${git} add -A && ${git} commit -m "chore: initial commit"`;
}
15 changes: 13 additions & 2 deletions packages/void/src/cli/init-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export class InitReport {
readonly completed: Array<string> = [];
/** What the user should do next. */
readonly nextSteps: Array<string> = [];
/**
* How to finish by hand the step that init is on, such as "Run `vp install`
* to finish setup". Only a run that stops during that step prints it.
*/
unfinished: string | undefined;
/** The new starter in one line. See `setStarter`. */
private starter: string | undefined;
/** Files recorded by the time the starter was created. */
Expand Down Expand Up @@ -140,7 +145,10 @@ export class InitReport {
}
}

/** Print what the run did before it stopped. Prints nothing if it did nothing. */
/**
* Print what the run did before it stopped, and how to finish the step it
* stopped in. Prints nothing if there is neither.
*/
private printStopped(): void {
if (this.printed) {
return;
Expand All @@ -154,10 +162,13 @@ export class InitReport {
log.warn(['Setup did not finish. Files changed so far:', ...lines].join('\n'));
} else if (this.completed.length > 0 || this.nextSteps.length > 0) {
log.warn('Setup did not finish. Done so far:');
} else {
} else if (!this.unfinished) {
return;
}
this.printOtherWork();
if (this.unfinished) {
printNextStep(this.unfinished);
}
}

private printOtherWork(): void {
Expand Down
29 changes: 19 additions & 10 deletions packages/void/src/cli/init-shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,31 @@ export function shellDirectory(): string {
return resolve(process.cwd());
}

/** Quote a path for the user's shell, including names containing quotes, $ or backticks. */
export function quoteShellPath(path: string): string {
if (/^[A-Za-z0-9_@./:-]+$/.test(path)) {
return path;
/** Quote an argument for the user's shell, such as a path with spaces, quotes, $ or backticks. */
export function quoteShellArgument(argument: string): string {
if (/^[A-Za-z0-9_@./:-]+$/.test(argument)) {
return argument;
}
return process.platform === 'win32' ? `"${path}"` : `'${path.replaceAll("'", "'\\''")}'`;
return process.platform === 'win32' ? `"${argument}"` : `'${argument.replaceAll("'", "'\\''")}'`;
}

/** Prefix `command` with a `cd` from the user's shell into `root` when they differ. */
export function commandInProject(root: string, command: string): string {
/**
* The path from the user's shell to `root`, quoted as a command argument, or
* undefined when the shell is already there.
*/
export function projectPathFromShell(root: string): string | undefined {
const shell = shellDirectory();
const directory = resolve(root);
if (directory === shell) {
return command;
return undefined;
}
const path = relative(shell, directory);
// `cd` would read a leading dash as an option, and `cd -` as the previous directory.
return `cd ${quoteShellPath(path.startsWith('-') ? `./${path}` : path)} && ${command}`;
// A command would read a leading dash as an option, and `cd -` as the previous directory.
return quoteShellArgument(path.startsWith('-') ? `./${path}` : path);
}

/** Prefix `command` with a `cd` from the user's shell into `root` when they differ. */
export function commandInProject(root: string, command: string): string {
const path = projectPathFromShell(root);
return path === undefined ? command : `cd ${path} && ${command}`;
}
248 changes: 248 additions & 0 deletions packages/void/src/cli/init-subprocess.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
import { readdirSync, readFileSync } from 'node:fs';
import { constants } from 'node:os';
import { createSpinner } from './output.ts';

export type SubprocessResult = {
/** The exit code, or null when a signal ended the command. */
status: number | null;
/** What the command wrote to stdout and stderr, in the order it arrived. */
output: string;
/** How long the command ran, in milliseconds. */
durationMs: number;
/** Why the command did not start. */
error?: Error;
};

/**
* The signals that end init: Ctrl+C where no spinner reads the keyboard, and
* `kill`. SIGHUP is left alone, since listening for it would undo `nohup`.
*/
const STOP_SIGNALS = ['SIGINT', 'SIGTERM'] as const;

/** How long a command that init stops has to end by itself before init kills it. */
const STOP_GRACE_MS = 5_000;
/** How long init waits for the killed processes to go. */
const KILL_WAIT_MS = 1_000;
/** How often init checks whether a stopped command has ended. */
const STOP_POLL_MS = 25;

/** Wait without the event loop, which an `exit` listener cannot return to. */
function sleepSync(ms: number): void {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}

/** Read the process states from /proc, which works without `ps` (slim container images have none). */
function isRunningInProc(pgid: number): boolean | undefined {
let entries: Array<string>;
try {
entries = readdirSync('/proc');
} catch {
return undefined;
}
for (const entry of entries) {
if (!/^\d+$/.test(entry)) {
continue;
}
let stat: string;
try {
stat = readFileSync(`/proc/${entry}/stat`, 'latin1');
} catch {
// The process has ended since the listing.
continue;
}
// "pid (name) state ppid pgrp …". The name can contain spaces and parentheses.
const [state, , group] = stat.slice(stat.lastIndexOf(')') + 2).split(' ', 3);
if (Number(group) === pgid && state !== 'Z' && state !== 'X') {
return true;
}
}
return false;
}

function isRunningInPs(pgid: number): boolean | undefined {
// By its path, so that init finds it whatever the user's PATH is. One `-o`
// for each column: POSIX reads the rest of an argument after "=" as the
// column's header, so "pgid=,state=" would print the group alone.
const listed = spawnSync('/bin/ps', ['-A', '-o', 'pgid=', '-o', 'state='], { encoding: 'utf8' });
if (listed.status !== 0) {
return undefined;
}
return listed.stdout.split('\n').some((row) => {
const [group, state] = row.trim().split(/\s+/);
return Number(group) === pgid && state !== undefined && !state.startsWith('Z');
});
}

/**
* Whether a process group still has a running member.
*
* A process that has exited stays in its group until its parent collects it,
* and Node cannot collect init's own child while an `exit` listener runs. For
* such a group `kill(-pgid, 0)` keeps succeeding, so read the process states.
*/
export function isProcessGroupRunning(
pgid: number,
platform: NodeJS.Platform = process.platform,
): boolean {
const running = platform === 'linux' ? isRunningInProc(pgid) : isRunningInPs(pgid);
if (running !== undefined) {
return running;
}
try {
process.kill(-pgid, 0);
return true;
} catch {
return false;
}
}

function signalGroup(pgid: number, signal: NodeJS.Signals): boolean {
try {
process.kill(-pgid, signal);
return true;
} catch {
// The group has already ended.
return false;
}
}

function waitForGroupToEnd(pgid: number, timeoutMs: number): boolean {
const deadline = performance.now() + timeoutMs;
while (isProcessGroupRunning(pgid)) {
if (performance.now() >= deadline) {
return false;
}
sleepSync(STOP_POLL_MS);
}
return true;
}

/**
* Stop a command that init started, together with the processes it started,
* and return when they have ended. Init exits next: a process that still ran
* then would go on changing the project while the user retries.
*/
export function stopCommand(
child: ChildProcess | undefined,
graceMs: number = STOP_GRACE_MS,
): void {
const pid = child?.pid;
if (!pid) {
return;
}
if (process.platform === 'win32') {
// `child.kill()` would end only the shell that runs the command.
spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
stdio: 'ignore',
windowsHide: true,
});
return;
}
// The command leads its own process group.
if (!signalGroup(pid, 'SIGTERM') || waitForGroupToEnd(pid, graceMs)) {
return;
}
// A process can ignore SIGTERM, but not SIGKILL.
signalGroup(pid, 'SIGKILL');
waitForGroupToEnd(pid, KILL_WAIT_MS);
}

/**
* Run a command behind a spinner, with its output kept for the caller instead
* of printed. `spawnSync` would block the event loop and freeze the spinner.
* The spinner goes away when the command ends.
*/
export function runBehindSpinner(
message: string,
command: string,
args: Array<string>,
options: {
cwd: string;
env?: NodeJS.ProcessEnv;
shell?: boolean;
/** The line to leave in place of the spinner when the command fails. */
failed?: string;
/**
* Removes what the command wrote. Runs when the command fails, and when
* init exits before the command ends, after the command has stopped.
*/
undo?: () => void;
},
): Promise<SubprocessResult> {
const { failed, undo, ...spawnOptions } = options;
return new Promise((resolve) => {
let child: ChildProcess | undefined;
const progress = createSpinner({ indicator: 'timer', cancelMessage: message });
// A spinner reads Ctrl+C as a key press and exits the process, so the
// terminal interrupts nothing. Go before the exit listener that reports
// init's work: mark this step as stopped, then stop the command.
const onExit = (code: number): void => {
progress.cancel(message);
stopCommand(child);
undo?.();
// The prompt library exits with 0 there. Keep the exit code of an
// interrupt, so that a caller such as create-void does not carry on.
if (code === 0) {
process.exitCode = 130;
}
};
// The command is not one of the terminal's foreground processes, so a
// signal that ends init would leave it running. Exit instead, which runs
// the listener above.
const onSignal = (signal: NodeJS.Signals): void => {
process.exit(128 + constants.signals[signal]);
};
const chunks: Array<Buffer> = [];
const startedAt = performance.now();
let settled = false;
const settle = (status: number | null, error?: Error): void => {
if (settled) {
return;
}
settled = true;
process.removeListener('exit', onExit);
for (const signal of STOP_SIGNALS) {
process.removeListener(signal, onSignal);
}
const succeeded = !error && status === 0;
if (!succeeded) {
undo?.();
}
if (failed && !succeeded) {
progress.error(failed);
} else {
progress.clear();
}
resolve({
status,
output: Buffer.concat(chunks).toString('utf8'),
durationMs: performance.now() - startedAt,
error,
});
};

progress.start(message);
process.prependListener('exit', onExit);
for (const signal of STOP_SIGNALS) {
process.on(signal, onSignal);
}
try {
const spawned = spawn(command, args, {
...spawnOptions,
// Without stdin or a terminal, a command that asks a question fails
// instead of waiting for an answer behind the spinner.
stdio: ['ignore', 'pipe', 'pipe'],
// Its own process group, so that init can stop what the command starts.
detached: process.platform !== 'win32',
});
child = spawned;
spawned.stdout.on('data', (chunk: Buffer) => chunks.push(chunk));
spawned.stderr.on('data', (chunk: Buffer) => chunks.push(chunk));
spawned.once('error', (error) => settle(null, error));
spawned.once('close', (status) => settle(status));
} catch (error) {
settle(null, error instanceof Error ? error : new Error(String(error)));
}
});
}
Loading
Loading