From 81634fe5fe60a9c3ea4a467d2b7aec5a64d59c98 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 7 May 2026 11:53:26 +0800 Subject: [PATCH] feat(cli/deploy): persistent JSONL trace and structured client logging Adds ~/.void/logs/deploy-.jsonl forensic trace for every deploy so failures (e.g. Connection lost during deploy: terminated) can be diagnosed from the trace alone. Records: phase boundaries, network calls with cf-ray correlation, every NDJSON event with raw slice and elapsed ms, full error.cause chain. New --debug flag (alongside back-compat VOID_DEPLOY_DEBUG=1) mirrors the JSONL stream to stderr inline. Failed deploys append the log path to the user-visible error so it can be attached to bug reports. Replaces the env-gated [void-deploy-debug] stderr writes from the prior diagnostic session. Co-Authored-By: Claude Opus 4.7 --- docs/reference/cli.md | 17 +- packages/void/src/cli/args.ts | 5 +- packages/void/src/cli/cli.ts | 1 + packages/void/src/cli/client.ts | 100 ++++++-- packages/void/src/cli/deploy-errors.ts | 47 +++- packages/void/src/cli/deploy.ts | 183 ++++++++++++++- packages/void/src/cli/help.ts | 4 + packages/void/src/cli/log-file.ts | 242 ++++++++++++++++++++ packages/void/test/unit/deploy-args.test.ts | 7 + 9 files changed, 559 insertions(+), 47 deletions(-) create mode 100644 packages/void/src/cli/log-file.ts diff --git a/docs/reference/cli.md b/docs/reference/cli.md index f590d0e40..245f70513 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -203,19 +203,22 @@ If `--project` is provided, purges that project's cache instead of the linked pr ### `void deploy` ``` -void deploy [--project ] [--dir ] [--spa] [--skip-build] +void deploy [--project ] [--dir ] [--spa] [--skip-build] [--debug] ``` Auto-detects your project type and chooses the right pipeline. See [Supported App Types](../guide/app-types.md) and [Deployment](../guide/deployment.md) for details. For Drizzle projects, deploy performs a read-only schema drift check. If a new migration would be generated, deploy stops and tells you to run `void db generate`, review the migration, commit it yourself, and rerun `void deploy`. -| Flag | Purpose | -| ------------------ | ------------------------------------------------- | -| `--project ` | Target a specific project by slug | -| `--dir ` | Deploy a pre-built static directory (skips build) | -| `--spa` | Use SPA mode instead of SSG for static deploys | -| `--skip-build` | Skip the build step (use existing build output) | +| Flag | Purpose | +| ------------------ | ---------------------------------------------------------------------------- | +| `--project ` | Target a specific project by slug | +| `--dir ` | Deploy a pre-built static directory (skips build) | +| `--spa` | Use SPA mode instead of SSG for static deploys | +| `--skip-build` | Skip the build step (use existing build output) | +| `--debug` | Mirror the structured deploy log to stderr (also written to `~/.void/logs/`) | + +Every deploy writes a structured JSONL trace to `~/.void/logs/deploy-.jsonl` regardless of `--debug`. On failure the path is printed at the end of the error message so you can attach it when reporting platform issues. `VOID_DEPLOY_DEBUG=1` is accepted as an alternate trigger for stderr mirroring. Project resolution precedence: diff --git a/packages/void/src/cli/args.ts b/packages/void/src/cli/args.ts index cd31e47de..d30007ba0 100644 --- a/packages/void/src/cli/args.ts +++ b/packages/void/src/cli/args.ts @@ -5,6 +5,7 @@ export interface DeployArgs { dir?: string; spa?: boolean; skipBuild?: boolean; + debug?: boolean; } export function parseDeployArgs(args: Array): DeployArgs { @@ -17,6 +18,7 @@ export function parseDeployArgs(args: Array): DeployArgs { dir: { type: 'string' }, spa: { type: 'boolean' }, 'skip-build': { type: 'boolean' }, + debug: { type: 'boolean' }, }, allowPositionals: true, strict: true, @@ -58,6 +60,7 @@ export function parseDeployArgs(args: Array): DeployArgs { const dir = typeof parsed.values.dir === 'string' ? parsed.values.dir : undefined; const spa = parsed.values.spa === true ? true : undefined; const skipBuild = parsed.values['skip-build'] === true ? true : undefined; + const debug = parsed.values.debug === true ? true : undefined; - return { projectSlug, dir, spa, skipBuild }; + return { projectSlug, dir, spa, skipBuild, debug }; } diff --git a/packages/void/src/cli/cli.ts b/packages/void/src/cli/cli.ts index 4f3125b5d..9630068b8 100644 --- a/packages/void/src/cli/cli.ts +++ b/packages/void/src/cli/cli.ts @@ -98,6 +98,7 @@ if (helpPath) { dir: deployArgs.dir, spa: deployArgs.spa, skipBuild: deployArgs.skipBuild, + debug: deployArgs.debug, }).catch((err) => { log.error(err.message ?? err); process.exit(1); diff --git a/packages/void/src/cli/client.ts b/packages/void/src/cli/client.ts index 5dd1c9f19..f4c4696cb 100644 --- a/packages/void/src/cli/client.ts +++ b/packages/void/src/cli/client.ts @@ -1,6 +1,7 @@ import { cfAccessHeaders } from '../shared/cf-access.ts'; import { getApiUrl } from './auth.ts'; import { ensureCloudflaredToken } from './cf-access.ts'; +import type { CliLogger } from './log-file.ts'; import type { DeployEvent } from './types.ts'; export type PlatformErrorPayload = { @@ -122,12 +123,17 @@ export interface DomainStatusResponse extends DomainResponse { export class PlatformClient { private baseUrl: string; private authHeaders: Record; + private cliLog?: CliLogger; - constructor(token: string, options?: string | { apiUrl?: string; root?: string }) { + constructor( + token: string, + options?: string | { apiUrl?: string; root?: string; cliLog?: CliLogger }, + ) { if (typeof options === 'string') { this.baseUrl = options; } else { this.baseUrl = options?.apiUrl ?? getApiUrl(options?.root); + this.cliLog = options?.cliLog; } ensureCloudflaredToken(this.baseUrl); this.authHeaders = { @@ -282,12 +288,34 @@ export class PlatformClient { } async *deploy(projectId: string, formData: FormData): AsyncGenerator { - const res = await fetch(`${this.baseUrl}/projects/${projectId}/deploy`, { - method: 'POST', - headers: { - ...this.authHeaders, - }, - body: formData, + const cliLog = this.cliLog; + const url = `${this.baseUrl}/projects/${projectId}/deploy`; + cliLog?.info('deploy_post', { url }); + + let res: Response; + try { + res = await fetch(url, { + method: 'POST', + headers: { + ...this.authHeaders, + }, + body: formData, + }); + } catch (err) { + cliLog?.error('deploy_fetch_rejected', err, { url }); + throw err; + } + + // `cf-ray` and `cf-cache-status` are the correlation keys that platform + // engineers need to look up server-side tail logs. Capture them whenever + // the response makes it back. + const cfRay = res.headers.get('cf-ray'); + const cfCacheStatus = res.headers.get('cf-cache-status'); + cliLog?.info('deploy_response', { + status: res.status, + cfRay, + cfCacheStatus, + contentType: res.headers.get('content-type'), }); if (!res.ok) { @@ -297,22 +325,54 @@ export class PlatformClient { const reader = res.body!.getReader(); const decoder = new TextDecoder(); let buffer = ''; + let bytesRead = 0; + let firstByteAt: number | null = null; + const startedAt = Date.now(); + let eventCount = 0; + let lastEventName = ''; - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - buffer += decoder.decode(value, { stream: true }); - - let newlineIdx; - while ((newlineIdx = buffer.indexOf('\n')) !== -1) { - const line = buffer.slice(0, newlineIdx); - buffer = buffer.slice(newlineIdx + 1); - if (line.trim()) { - yield JSON.parse(line) as DeployEvent; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) { + cliLog?.info('deploy_stream_eof', { + bytesRead, + eventCount, + lastEvent: lastEventName, + }); + break; + } + if (firstByteAt === null) { + firstByteAt = Date.now() - startedAt; + cliLog?.info('deploy_stream_ttfb', { ttfbMs: firstByteAt }); + } + bytesRead += value.byteLength; + buffer += decoder.decode(value, { stream: true }); + + let newlineIdx; + while ((newlineIdx = buffer.indexOf('\n')) !== -1) { + const line = buffer.slice(0, newlineIdx); + buffer = buffer.slice(newlineIdx + 1); + if (line.trim()) { + const event = JSON.parse(line) as DeployEvent; + eventCount++; + lastEventName = (event as { event?: string }).event ?? ''; + cliLog?.info('deploy_event', { + eventCount, + event: lastEventName, + raw: line.slice(0, 200), + }); + yield event; + } } } + } catch (err) { + cliLog?.error('deploy_stream_error', err, { + bytesRead, + eventCount, + lastEvent: lastEventName, + }); + throw err; } } diff --git a/packages/void/src/cli/deploy-errors.ts b/packages/void/src/cli/deploy-errors.ts index dbe39f845..bee736a43 100644 --- a/packages/void/src/cli/deploy-errors.ts +++ b/packages/void/src/cli/deploy-errors.ts @@ -14,11 +14,27 @@ function appendDeploymentLine(message: string, deploymentId: string | null): str return deploymentId ? `${message}\nDeployment: ${deploymentId}` : message; } +function appendLogLine(message: string, logPath: string | null | undefined): string { + return logPath ? `${message}\nDetailed log: ${logPath}` : message; +} + +function appendTrailingLines( + message: string, + deploymentId: string | null, + logPath: string | null | undefined, +): string { + return appendLogLine(appendDeploymentLine(message, deploymentId), logPath); +} + /** * Format a server-emitted `event: 'error'` payload with an optional deployment id. */ -export function formatDeployFailureMessage(message: string, deploymentId: string | null): string { - return appendDeploymentLine(message, deploymentId); +export function formatDeployFailureMessage( + message: string, + deploymentId: string | null, + logPath?: string | null, +): string { + return appendTrailingLines(message, deploymentId, logPath); } /** @@ -28,8 +44,11 @@ export function formatDeployFailureMessage(message: string, deploymentId: string * deploy" message — the server closed the NDJSON stream without emitting * `done` or `error`, so there is no underlying error to carry. */ -export function formatConnectionLostMessage(deploymentId: string | null): string { - return appendDeploymentLine('deploy: Connection lost during deploy.', deploymentId); +export function formatConnectionLostMessage( + deploymentId: string | null, + logPath?: string | null, +): string { + return appendTrailingLines('deploy: Connection lost during deploy.', deploymentId, logPath); } /** @@ -45,7 +64,11 @@ export function formatConnectionLostMessage(deploymentId: string | null): string * during deploy: ` prefix so the caller can still tell network, * parse, and transport errors apart. */ -export function formatStreamDeployError(err: unknown, deploymentId: string | null): Error { +export function formatStreamDeployError( + err: unknown, + deploymentId: string | null, + logPath?: string | null, +): Error { if (err instanceof PlatformApiError) { const parsed = parsePlatformErrorBody(err.body); const parsedError = parsed?.error ?? parsed?.message ?? null; @@ -54,7 +77,11 @@ export function formatStreamDeployError(err: unknown, deploymentId: string | nul if (err.status === 409 && parsedError) { return new Error( - appendDeploymentLine(`deploy: Deploy failed: ${parsedError}`, effectiveDeploymentId), + appendTrailingLines( + `deploy: Deploy failed: ${parsedError}`, + effectiveDeploymentId, + logPath, + ), ); } @@ -62,11 +89,15 @@ export function formatStreamDeployError(err: unknown, deploymentId: string | nul const base = detail ? `deploy: Deploy failed (HTTP ${err.status}): ${detail}` : `deploy: Deploy failed (HTTP ${err.status}).`; - return new Error(appendDeploymentLine(base, effectiveDeploymentId)); + return new Error(appendTrailingLines(base, effectiveDeploymentId, logPath)); } const original = err instanceof Error ? err.message : String(err); return new Error( - appendDeploymentLine(`deploy: Connection lost during deploy: '${original}'.`, deploymentId), + appendTrailingLines( + `deploy: Connection lost during deploy: '${original}'.`, + deploymentId, + logPath, + ), ); } diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 5c967c8c8..e662ab705 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -65,6 +65,7 @@ import { validateProdEnv, } from './env-validation.ts'; import { lintDestinationSplats, lintDuplicateSources, mergeRoutingRules } from './headers.ts'; +import { openDeployLog, type CliLogger } from './log-file.ts'; import { promptForLoginToken } from './login.ts'; import { cliTitle, createSpinner, pc } from './output.ts'; import { @@ -96,6 +97,7 @@ export interface RunDeployOptions { dir?: string; spa?: boolean; skipBuild?: boolean; + debug?: boolean; } type DeployDoneEvent = Extract; @@ -177,6 +179,36 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi console.log(); intro(cliTitle('deploy')); + const cliLog = openDeployLog({ + mirrorToStderr: options?.debug === true || process.env.VOID_DEPLOY_DEBUG === '1', + }); + cliLog.info('deploy_start', { + cwd: root, + projectSlug: options?.projectSlug, + dir: options?.dir, + spa: options?.spa === true ? true : undefined, + skipBuild: options?.skipBuild === true ? true : undefined, + nodeVersion: process.version, + platform: process.platform, + arch: process.arch, + }); + + try { + await runDeployInner(root, options, cliLog); + cliLog.info('deploy_end', { ok: true }); + } catch (err) { + cliLog.error('deploy_end', err, { ok: false }); + throw err; + } finally { + await cliLog.close().catch(() => {}); + } +} + +async function runDeployInner( + root: string, + options: RunDeployOptions | undefined, + cliLog: CliLogger, +): Promise { let reauthenticated = false; while (true) { try { @@ -187,7 +219,7 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi process.exit(1); } - const client = new PlatformClient(token, { root }); + const client = new PlatformClient(token, { root, cliLog }); // 2. Resolve target project (CLI flag > env var > linked project file) const requestedProjectSlug = getRequestedProjectSlug(options); @@ -200,7 +232,7 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi if (!config) { if (!process.stdin.isTTY) { // CI: auto-create when --project is explicitly specified - config = await createProjectFromSlug(root, client, requestedProjectSlug); + config = await createProjectFromSlug(root, client, requestedProjectSlug, cliLog); } else { const shouldCreate = await confirm({ message: `Project "${requestedProjectSlug}" does not exist. Create it?`, @@ -210,7 +242,7 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi process.exit(0); } - config = await createProjectFromSlug(root, client, requestedProjectSlug); + config = await createProjectFromSlug(root, client, requestedProjectSlug, cliLog); } } } else { @@ -225,15 +257,29 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi } if (!config) { - config = await promptDeployProjectConfig(root, client); + config = await promptDeployProjectConfig(root, client, cliLog); } + cliLog.info('project_resolved', { + projectId: config.projectId, + slug: config.slug, + }); + // 3. Resolve deploy app type: void.json > CLI flags > auto-detection const voidConfig = readConfig(root); + cliLog.info('config_resolved', { + target: voidConfig.target, + appType: voidConfig.inference?.appType, + output: voidConfig.output, + }); // Check for known framework first const detected = detectFramework(root); if (detected) { + cliLog.info('framework_detected', { + name: detected.name, + class: detected.class, + }); const gitCommit = options?.skipBuild ? null : getGitCommit(root); const fwPreset = FRAMEWORK_PRESETS[detected.name]; if (detected.class === 'b' || detected.class === 'c') { @@ -250,6 +296,7 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi voidConfig, options?.skipBuild, gitCommit, + cliLog, ); } else { // Class A: preset is optional (e.g. vinext probes at runtime) @@ -261,6 +308,7 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi options?.skipBuild, gitCommit, detected, + cliLog, ); } return; @@ -315,9 +363,19 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi undefined, undefined, voidConfig.routing, + cliLog, ); } else { - await runFullDeploy(root, config, client, undefined, options?.skipBuild, gitCommit); + await runFullDeploy( + root, + config, + client, + undefined, + options?.skipBuild, + gitCommit, + undefined, + cliLog, + ); } return; } catch (error) { @@ -344,6 +402,7 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi export async function promptDeployProjectConfig( root: string, client: PlatformClient, + cliLog?: CliLogger, ): Promise { const projects = await client.listProjects(); const action = await promptProjectSetupAction('Set up a Void project for deploy:', { @@ -365,6 +424,7 @@ export async function promptDeployProjectConfig( const config = { projectId: result.project.id, slug: result.project.slug }; writeProjectConfig(root, config); log.step(`Linked to ${pc.blue(config.slug)}`); + cliLog?.info('project_linked', { projectId: config.projectId, slug: config.slug }); return config; } @@ -448,9 +508,12 @@ async function streamDeploy( projectId: string, formData: FormData, s: SpinnerResult, + cliLog?: CliLogger, ): Promise { + const startedAt = Date.now(); let deploymentId: string | null = null; let interrupted = false; + cliLog?.info('stream_start', { projectId }); const onSigint = () => { interrupted = true; s.stop('Deploy interrupted'); @@ -459,6 +522,12 @@ async function streamDeploy( } else { log.info('Deployment id was not received before the interrupt.'); } + cliLog?.warn('stream_interrupted', { deploymentId }); + // Best-effort flush of the JSONL log before the process exits. The + // returned promise is intentionally not awaited — `process.exit(130)` + // would race the awaiter, and the OS flushes the page cache for the + // line-delimited file regardless. + cliLog?.close().catch(() => {}); process.exit(130); }; @@ -469,10 +538,24 @@ async function streamDeploy( const result = applyDeployEvent(event, s); if (result.kind === 'start') { deploymentId = result.deploymentId; + cliLog?.info('stream_deployment_id', { deploymentId }); } else if (result.kind === 'done') { + cliLog?.info('deploy_success', { + deploymentId, + url: result.event.url, + assets: result.event.assets, + workers: result.event.workers, + durationMs: Date.now() - startedAt, + }); return result.event; } else if (result.kind === 'error') { - throw new DeployEventError(formatDeployFailureMessage(result.message, deploymentId)); + cliLog?.error('deploy_server_error', undefined, { + deploymentId, + message: result.message, + }); + throw new DeployEventError( + formatDeployFailureMessage(result.message, deploymentId, cliLog?.path ?? null), + ); } } } catch (err) { @@ -482,14 +565,16 @@ async function streamDeploy( if (interrupted) { throw err; } + cliLog?.error('stream_deploy_caught', err, { deploymentId }); s.stop('Deploy failed'); - throw formatStreamDeployError(err, deploymentId); + throw formatStreamDeployError(err, deploymentId, cliLog?.path ?? null); } finally { process.removeListener('SIGINT', onSigint); } + cliLog?.warn('stream_no_terminal_event', { deploymentId }); s.stop('Deploy failed'); - throw new Error(formatConnectionLostMessage(deploymentId)); + throw new Error(formatConnectionLostMessage(deploymentId, cliLog?.path ?? null)); } function formatKnownAssetSummary(result: DeployDoneEvent, skipped: number): string { @@ -511,14 +596,21 @@ async function runStaticDeploy( redirectRules?: Array, fallbackRules?: Array, routing?: RoutingConfig, + cliLog?: CliLogger, ): Promise { const typeLabel = preset.appType === 'spa' ? 'Static SPA' : 'Static Site'; log.info(`${typeLabel} deploy`); + cliLog?.info('deploy_mode', { mode: 'static', appType: preset.appType }); // Build (if needed) if (preset.buildCommand && !skipBuild) { log.step('Building...'); + cliLog?.info('build_start', { command: preset.buildCommand }); + const buildStartedAt = Date.now(); execSync(preset.buildCommand, { cwd: root, stdio: 'inherit' }); + cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); + } else if (skipBuild) { + cliLog?.info('build_skipped', { reason: 'skipBuild' }); } if (!existsSync(preset.outputDir)) { @@ -543,15 +635,23 @@ async function runStaticDeploy( // Preflight: hash assets and check which ones changed s.start('Checking for changes...'); + cliLog?.info('preflight_start', { dir: preset.outputDir }); const { assetManifest } = await collectAndHashAssets(preset.outputDir, onProgress); const { needed, skipped } = await client.preflight(config.projectId, assetManifest); s.stop('Checked for changes'); + cliLog?.info('preflight_end', { + total: Object.keys(assetManifest).length, + needed: needed.length, + skipped, + }); if (skipped > 0) { log.info(`Skipping ${skipped} unchanged asset(s)`); } s.start('Packaging...'); + cliLog?.info('package_start', { mode: 'static' }); + const packageStartedAt = Date.now(); const neededSet = skipped > 0 ? new Set(needed) : null; const formData = await packageStaticBuild( preset.outputDir, @@ -568,8 +668,12 @@ async function runStaticDeploy( if (commit) { formData.append('commit', commit); } + cliLog?.info('package_end', { + mode: 'static', + durationMs: Date.now() - packageStartedAt, + }); - const result = await streamDeploy(client, config.projectId, formData, s); + const result = await streamDeploy(client, config.projectId, formData, s, cliLog); const summary = [`${typeLabel} — ${formatKnownAssetSummary(result, skipped)}`]; note(summary.join('\n'), result.url); @@ -605,8 +709,10 @@ async function runFrameworkDeploy( voidConfig: VoidConfig, skipBuild?: boolean, commit?: string | null, + cliLog?: CliLogger, ): Promise { log.info(`${detected.name} framework deploy`); + cliLog?.info('deploy_mode', { mode: 'framework', framework: detected.name }); const dialect = getDatabaseDialect(voidConfig); @@ -614,10 +720,15 @@ async function runFrameworkDeploy( const buildCmd = voidConfig.inference?.build ?? formatProjectCommand(root, fwPreset.buildCommand); if (!skipBuild) { log.step(`Building (${buildCmd})...`); + cliLog?.info('build_start', { command: buildCmd }); + const buildStartedAt = Date.now(); execSync(voidConfig.inference?.build ?? resolveProjectCommand(root, fwPreset.buildCommand), { cwd: root, stdio: 'inherit', }); + cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); + } else { + cliLog?.info('build_skipped', { reason: 'skipBuild' }); } // 2. Verify output paths @@ -795,17 +906,25 @@ async function runFrameworkDeploy( // Preflight: hash assets and check which ones changed s.start('Checking for changes...'); + cliLog?.info('preflight_start', { dir: assetsDir }); const { assetManifest } = await collectAndHashAssets(assetsDir, onProgress, { ignorePatterns: frameworkAssetIgnorePatterns, }); const { needed, skipped } = await client.preflight(config.projectId, assetManifest, true); s.stop('Checked for changes'); + cliLog?.info('preflight_end', { + total: Object.keys(assetManifest).length, + needed: needed.length, + skipped, + }); if (skipped > 0) { log.info(`Skipping ${skipped} unchanged asset(s)`); } s.start('Packaging...'); + cliLog?.info('package_start', { mode: 'framework', framework: detected.name }); + const packageStartedAt = Date.now(); const neededSet = skipped > 0 ? new Set(needed) : null; const formData = await packageFrameworkBuild({ frameworkName: detected.name, @@ -841,8 +960,12 @@ async function runFrameworkDeploy( if (commit) { formData.append('commit', commit); } + cliLog?.info('package_end', { + mode: 'framework', + durationMs: Date.now() - packageStartedAt, + }); - const result = await streamDeploy(client, config.projectId, formData, s); + const result = await streamDeploy(client, config.projectId, formData, s, cliLog); const summary = [ `${result.workers} worker module(s), ${formatKnownAssetSummary(result, skipped)}`, @@ -883,11 +1006,19 @@ async function runFullDeploy( skipBuild?: boolean, commit?: string | null, detected?: DetectedFramework, + cliLog?: CliLogger, ): Promise { + cliLog?.info('deploy_mode', { + mode: 'full', + framework: detected?.name, + }); + // 3. Build (child process to avoid Vite API side effects on bundle output) if (!skipBuild) { const buildCmd = formatProjectCommand(root, 'vite build'); log.step(`Building (${buildCmd})...`); + cliLog?.info('build_start', { command: buildCmd }); + const buildStartedAt = Date.now(); try { // Pass VOID_DEPLOY_PROJECT_ID so plugin-prerender (running inside this // child vite build) can resolve the Void projectId without relying on @@ -897,9 +1028,13 @@ async function runFullDeploy( stdio: 'inherit', env: { ...process.env, VOID_DEPLOY_PROJECT_ID: config.projectId }, }); + cliLog?.info('build_end', { durationMs: Date.now() - buildStartedAt }); } catch (err: unknown) { + cliLog?.error('build_failed', err, { durationMs: Date.now() - buildStartedAt }); process.exit(getExitCode(err)); } + } else { + cliLog?.info('build_skipped', { reason: 'skipBuild' }); } // 4. Resolve build output paths from build artifacts (avoids re-resolving @@ -1107,6 +1242,7 @@ async function runFullDeploy( const hasNonPageBackend = hasRoutes || hasMiddleware || hasWebSockets || authEnabled; if (allPrerenderable && !hasNonPageBackend && schedules.length === 0 && queues.length === 0) { log.info('All pages prerendered — deploying as static site'); + cliLog?.info('full_to_static_redirect', { reason: 'all_pages_prerendered' }); return runStaticDeploy( root, config, @@ -1122,6 +1258,8 @@ async function runFullDeploy( headerRules, redirectRules, fallbackRules, + undefined, + cliLog, ); } } @@ -1187,15 +1325,31 @@ async function runFullDeploy( // Preflight: hash assets and check which ones changed s.start('Checking for changes...'); + cliLog?.info('preflight_start', { dir: clientDir }); const { assetManifest } = await collectAndHashAssets(clientDir, onProgress); const { needed, skipped } = await client.preflight(config.projectId, assetManifest, true); s.stop('Checked for changes'); + cliLog?.info('preflight_end', { + total: Object.keys(assetManifest).length, + needed: needed.length, + skipped, + }); if (skipped > 0) { log.info(`Skipping ${skipped} unchanged asset(s)`); } s.start('Packaging...'); + cliLog?.info('package_start', { + mode: 'full', + isSsr, + hasRoutes, + hasMiddleware, + hasWebSockets, + authEnabled, + framework: detected?.name, + }); + const packageStartedAt = Date.now(); const neededSet = skipped > 0 ? new Set(needed) : null; const formData = await packageBuild( distDir, @@ -1230,8 +1384,12 @@ async function runFullDeploy( if (commit) { formData.append('commit', commit); } + cliLog?.info('package_end', { + mode: 'full', + durationMs: Date.now() - packageStartedAt, + }); - const result = await streamDeploy(client, config.projectId, formData, s); + const result = await streamDeploy(client, config.projectId, formData, s, cliLog); const summary = [ `${result.workers} worker module(s), ${formatKnownAssetSummary(result, skipped)}`, @@ -1270,12 +1428,15 @@ async function createProjectFromSlug( root: string, client: PlatformClient, slug: string, + cliLog?: CliLogger, ): Promise { log.step(`Creating project ${pc.blue(slug)}...`); + cliLog?.info('project_create_start', { slug }); const project = await client.createProject(slug); const config = { projectId: project.id, slug: project.slug }; writeProjectConfig(root, config); log.success(`Project created: ${pc.blue(config.slug)}`); + cliLog?.info('project_create_success', { projectId: config.projectId, slug: config.slug }); return config; } diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index 36cf7d80e..279541097 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -43,6 +43,10 @@ const HELP_TREE: HelpTree = { { command: '--dir ', description: 'Deploy a static directory and skip build' }, { command: '--spa', description: 'Use SPA mode for static deploys' }, { command: '--skip-build', description: 'Skip the build step and use existing output' }, + { + command: '--debug', + description: 'Mirror the deploy log to stderr (always written to ~/.void/logs)', + }, ], examples: [ { command: 'void deploy', description: 'Deploy the linked project' }, diff --git a/packages/void/src/cli/log-file.ts b/packages/void/src/cli/log-file.ts new file mode 100644 index 000000000..3141d636b --- /dev/null +++ b/packages/void/src/cli/log-file.ts @@ -0,0 +1,242 @@ +import { createWriteStream, mkdirSync, type WriteStream } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'pathe'; + +type Level = 'debug' | 'info' | 'warn' | 'error'; + +export interface CliLogger { + info(msg: string, fields?: Record): void; + warn(msg: string, fields?: Record): void; + error(msg: string, err?: unknown, fields?: Record): void; + debug(msg: string, fields?: Record): void; + /** path to the file backing this logger, or null if unable to open */ + readonly path: string | null; + /** Close stream and return final path. Idempotent. */ + close(): Promise; +} + +interface ErrChainNode { + name?: string; + message?: string; + code?: string | number; + errno?: string | number; + cause?: ErrChainNode; +} + +/** + * Walk `err.cause` up to 6 levels and return a plain JSON-friendly chain. + * Skips stack traces deliberately — keeps output line-oriented and readable. + */ +export function describeErrorChain(err: unknown, depth = 0): ErrChainNode | string { + if (depth > 5 || err == null) { + return String(err); + } + if (err instanceof Error) { + const node: ErrChainNode = { + name: err.name, + message: err.message, + }; + const code = (err as Error & { code?: string | number }).code; + if (code !== undefined) { + node.code = code; + } + const errno = (err as Error & { errno?: string | number }).errno; + if (errno !== undefined) { + node.errno = errno; + } + const cause = (err as Error & { cause?: unknown }).cause; + if (cause != null) { + const sub = describeErrorChain(cause, depth + 1); + if (typeof sub === 'object') { + node.cause = sub; + } else { + node.cause = { message: sub }; + } + } + return node; + } + return String(err); +} + +/** + * Flatten an error and its `cause` chain to a single inline string suitable + * for stderr skimming. Mirrors `describeErrorChain`'s walk (depth cap 6, + * same fields, no stack traces) but joins levels with ` -> ` instead of + * nesting JSON. + */ +function formatErrorChainInline(err: unknown, depth = 0): string { + if (depth > 5 || err == null) { + return String(err); + } + if (err instanceof Error) { + let head = err.name ? `${err.name}: ${err.message}` : err.message; + const code = (err as Error & { code?: string | number }).code; + const errno = (err as Error & { errno?: string | number }).errno; + const tags: Array = []; + if (code !== undefined) { + tags.push(`code=${code}`); + } + if (errno !== undefined) { + tags.push(`errno=${errno}`); + } + if (tags.length > 0) { + head = `${head} (${tags.join(' ')})`; + } + const cause = (err as Error & { cause?: unknown }).cause; + if (cause != null) { + return `${head} -> ${formatErrorChainInline(cause, depth + 1)}`; + } + return head; + } + return String(err); +} + +function formatStderrLine( + level: Level, + msg: string, + err: unknown | undefined, + fields?: Record, +): string { + const parts: Array = [level, msg]; + if (fields) { + for (const [k, v] of Object.entries(fields)) { + if (v === undefined) { + continue; + } + let s: string; + if (v == null || typeof v === 'number' || typeof v === 'boolean') { + s = String(v); + } else if (typeof v === 'string') { + s = v.length > 200 ? `${v.slice(0, 200)}...` : v; + } else { + try { + s = JSON.stringify(v); + } catch { + s = String(v); + } + } + parts.push(`${k}=${s}`); + } + } + if (err !== undefined) { + parts.push(`-> err=${formatErrorChainInline(err)}`); + } + return parts.join(' '); +} + +export function openDeployLog(opts?: { mirrorToStderr?: boolean }): CliLogger { + const mirror = opts?.mirrorToStderr === true; + const startedAt = Date.now(); + + let path: string | null = null; + let stream: WriteStream | null = null; + let broken = false; + let closed = false; + + try { + const dir = join(homedir(), '.void', 'logs'); + mkdirSync(dir, { recursive: true }); + const ts = new Date().toISOString().replace(/[:.]/g, '-'); + const filePath = join(dir, `deploy-${ts}.jsonl`); + stream = createWriteStream(filePath, { flags: 'a', autoClose: true }); + stream.on('error', () => { + // Disable subsequent writes silently. Stream errors should never + // bubble up into the deploy pipeline. + broken = true; + }); + path = filePath; + } catch { + broken = true; + path = null; + stream = null; + } + + function write( + level: Level, + msg: string, + err: unknown | undefined, + fields?: Record, + ): void { + if (mirror) { + try { + process.stderr.write(`${formatStderrLine(level, msg, err, fields)}\n`); + } catch { + // Stderr write failures are not actionable. + } + } + if (broken || !stream || closed) { + return; + } + const now = Date.now(); + const record: Record = { + ts: now, + elapsedMs: now - startedAt, + lvl: level, + msg, + }; + if (fields) { + for (const [k, v] of Object.entries(fields)) { + if ( + v !== undefined && + k !== 'ts' && + k !== 'elapsedMs' && + k !== 'lvl' && + k !== 'msg' && + k !== 'err' + ) { + record[k] = v; + } + } + } + if (err !== undefined) { + record.err = describeErrorChain(err); + } + let line: string; + try { + line = `${JSON.stringify(record)}\n`; + } catch { + // Non-serializable fields shouldn't crash the logger; fall back to a + // minimal record. + line = `${JSON.stringify({ ts: now, elapsedMs: now - startedAt, lvl: level, msg, err: 'unserializable fields' })}\n`; + } + try { + stream.write(line); + } catch { + broken = true; + } + } + + return { + get path() { + return path; + }, + info(msg, fields) { + write('info', msg, undefined, fields); + }, + warn(msg, fields) { + write('warn', msg, undefined, fields); + }, + error(msg, err, fields) { + write('error', msg, err, fields); + }, + debug(msg, fields) { + write('debug', msg, undefined, fields); + }, + close(): Promise { + if (closed) { + return Promise.resolve(); + } + closed = true; + if (!stream) { + return Promise.resolve(); + } + return new Promise((resolveClose) => { + try { + stream!.end(() => resolveClose()); + } catch { + resolveClose(); + } + }); + }, + }; +} diff --git a/packages/void/test/unit/deploy-args.test.ts b/packages/void/test/unit/deploy-args.test.ts index 95e172b57..091179c19 100644 --- a/packages/void/test/unit/deploy-args.test.ts +++ b/packages/void/test/unit/deploy-args.test.ts @@ -8,6 +8,7 @@ describe('parseDeployArgs', () => { dir: undefined, spa: undefined, skipBuild: undefined, + debug: undefined, }); }); @@ -17,9 +18,15 @@ describe('parseDeployArgs', () => { dir: undefined, spa: undefined, skipBuild: undefined, + debug: undefined, }); }); + it('parses --debug flag', () => { + const result = parseDeployArgs(['--debug']); + expect(result.debug).toBe(true); + }); + it('parses --dir flag', () => { const result = parseDeployArgs(['--dir', 'public']); expect(result.dir).toBe('public');