import { defineCommand } from 'citty' import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { dirname, join, relative, resolve } from 'node:path' import { strToU8, zipSync } from 'fflate' import { diagnosticsPass, type Diagnostic } from '@pandacss/compiler-shared' import { includeArgs, parseCliFlags, runtimeArgs } from '../args' import { runCommand } from '../run-command' import { normalizeCliDiagnostics } from '../diagnostics' import { debugFlagsSchema } from '../schema' import { consoleOutput, renderCommandDiagnostics, resolveCwd, shouldPrintHumanSummary, type OutputSink, } from '../output' import { setExitCode } from '../result' import type { DebugFlags, DebugResult } from '../schema' export const debugCommand = defineCommand({ meta: { name: 'debug', description: 'Dump resolved config and per-file extraction for bug reports', }, args: () => ({ ...runtimeArgs(), ...includeArgs(), outdir: { type: 'string', description: 'Debug output directory (used as-is; default /debug)' }, dry: { type: 'boolean', description: 'Print the dump to stdout instead of writing files' }, zip: { type: 'boolean', description: 'Write the dump as a single .zip archive' }, onlyConfig: { type: 'boolean', description: 'Only dump the resolved config, skip per-file extraction' }, }), run: async ({ args, rawArgs }) => setExitCode(await runDebug(parseCliFlags(debugFlagsSchema, args, rawArgs))), }) export async function runDebug(flags: DebugFlags = {}, output: OutputSink = consoleOutput): Promise { if (flags.profile && flags.dry) { throw new Error('--profile writes trace.json/timings.json to disk; drop --dry or --profile.') } if (flags.zip && flags.dry) { throw new Error('--zip writes an archive to disk; drop --dry or --zip.') } if (flags.zip && flags.profile) { throw new Error('--profile traces are written outside the archive; drop --zip or --profile.') } // Default debug outdir needs config, resolved after tracing must already start. let profilePaths: { trace: string; timings: string } | undefined if (flags.profile && flags.outdir) { const outdir = resolve(resolveCwd(flags.cwd), flags.outdir) profilePaths = { trace: join(outdir, 'trace.json'), timings: join(outdir, 'timings.json') } } return runCommand({ command: 'debug', flags, output, profilePaths, failData: () => ({ files: [], sourceCount: 0 }), async execute(ctx) { const { driver, cwd } = ctx const outdir = flags.outdir ? driver.resolvePath(flags.outdir) : join(driver.paths().root, 'debug') const sources = driver.scan() const dump: Record = { 'system-info.json': JSON.stringify( { platform: process.platform, arch: process.arch, node: process.version, configPath: driver.configPath ?? null, sourceCount: sources.length, }, null, 2, ), 'config.json': JSON.stringify(driver.config, null, 2), } const fileDiagnostics: Diagnostic[] = [] if (!flags.onlyConfig) { for (const source of sources) { // A debug dump should survive a broken project: capture a read/extract failure as a diagnostic // and write the error into the per-file slot instead of aborting the whole command. try { const code = readFileSync(source, 'utf8') const result = driver.compiler.extractFileSource(source, code) fileDiagnostics.push(...normalizeCliDiagnostics(result.diagnostics, { cwd, file: source })) dump[`${safeName(cwd, source)}.extract.json`] = JSON.stringify(result, null, 2) } catch (error) { const message = error instanceof Error ? error.message : String(error) fileDiagnostics.push( ...normalizeCliDiagnostics( [{ code: 'debug_extract_error', severity: 'error', message, category: 'debug' }], { cwd, file: source }, ), ) dump[`${safeName(cwd, source)}.extract.json`] = JSON.stringify({ error: message }, null, 2) } } // v2 emits atomic CSS at the project level (atoms dedupe across files), so the dump carries the // whole-project stylesheet once rather than a per-file slice. Parse populates project state first. driver.parseFiles() dump['styles.css'] = driver.cssgen().css } const diagnostics = normalizeCliDiagnostics( [...normalizeCliDiagnostics(driver.compiler.diagnostics(), { cwd }), ...fileDiagnostics], { cwd }, ) const archive = flags.zip ? `${resolve(outdir)}.zip` : undefined const files = flags.dry ? writeDryDump(ctx.output, dump) : archive ? writeZipDump(archive, dump) : writeDiskDump(outdir, dump) if (shouldPrintHumanSummary(flags)) { ctx.output.log( flags.dry ? `debug: ${Object.keys(dump).length} files (dry run)` : `debug: wrote ${files.length} files to ${archive ?? outdir}`, ) } return { data: { outdir: flags.dry || archive ? undefined : outdir, archive, files, sourceCount: sources.length }, diagnostics, ok: diagnosticsPass(diagnostics, { maxWarnings: flags.maxWarnings }), } }, renderHuman(ctx, result) { renderCommandDiagnostics(result.diagnostics, ctx.output, flags, ctx.cwd) }, }) as Promise } function writeDiskDump(outdir: string, dump: Record): string[] { return Object.entries(dump).map(([name, content]) => { const target = join(outdir, name) mkdirSync(dirname(target), { recursive: true }) writeFileSync(target, content) return target }) } function writeZipDump(archive: string, dump: Record): string[] { const entries = Object.fromEntries(Object.entries(dump).map(([name, content]) => [name, strToU8(content)])) mkdirSync(dirname(archive), { recursive: true }) writeFileSync(archive, zipSync(entries)) return Object.keys(dump) } function writeDryDump(output: OutputSink, dump: Record): string[] { for (const [name, content] of Object.entries(dump)) { output.log(`--- ${name} ---\n${content}`) } return Object.keys(dump) } // Flatten a source path into a single filename, e.g. `src/App.tsx` -> `src__App.tsx`. function safeName(cwd: string, file: string): string { return relative(cwd, file).replace(/[\\/]/g, '__') }