UNPKG

@nuxt/cli

Version:
415 lines (414 loc) • 14.4 kB
import { C as tapOutput, h as logger, l as onScreenHeld } from "./startup-clock-SyYej6uN.mjs"; import { i as paint, n as MUTED } from "./terminal-theme-jW0dFyAX.mjs"; import { l as visibleWidth, r as formatDuration, s as terminalLink, t as decapitalise } from "./formatting-CCN_OARd.mjs"; import "./progress-snapshot-BVUmkNu7.mjs"; import { r as supportsUnicode } from "./support-DGfQlyBw.mjs"; import process from "node:process"; import { styleText } from "node:util"; import { isCI } from "std-env"; import { box } from "@clack/prompts"; import { join, relative } from "pathe"; import { mkdirSync, writeFileSync } from "node:fs"; // src/utils/profile.ts const RELATIVE_PATH_RE = /^(?![^.]{1,2}\/)/; let session; let profileCount = 0; async function startCpuProfile() { const cli = globalThis.__nuxt_cli__; if (cli?.cpuProfileSession) { session = cli.cpuProfileSession; delete cli.cpuProfileSession; return; } session = new (await (import("node:inspector"))).Session(); session.connect(); try { await new Promise((res, rej) => { session.post("Profiler.enable", (err) => { if (err) return rej(err); session.post("Profiler.start", (err) => { if (err) return rej(err); res(); }); }); }); } catch (err) { session.disconnect(); session = void 0; throw err; } } async function stopCpuProfile(outDir, command) { if (!session) return; const s = session; session = void 0; const count = profileCount++; const outPath = join(outDir, `nuxt-${command}${count ? `-${count}` : ""}.cpuprofile`); const relativeOutPath = relative(process.cwd(), outPath).replace(RELATIVE_PATH_RE, "./"); try { const profile = await new Promise((resolve, reject) => { s.post("Profiler.stop", (err, params) => err ? reject(err) : resolve(params?.profile)); }); if (!profile) return; try { mkdirSync(outDir, { recursive: true }); writeFileSync(outPath, JSON.stringify(profile)); } catch { return; } try { const nextSteps = [`CPU profile written to ${styleText("cyan", relativeOutPath)}.`, `Open it in a CPU profile viewer like your IDE, or ${styleText("cyan", "https://discoveryjs.github.io/cpupro")}.`]; box(`\n${nextSteps.map((step) => ` › ${step}`).join("\n")}\n`, "", { contentAlign: "left", titleAlign: "left", width: "auto", titlePadding: 2, contentPadding: 2, rounded: true, withGuide: false, formatBorder: (text) => paint("brand", text) }); } catch {} return outPath; } finally { s.disconnect(); } } // src/utils/phase-reporter.ts const FRAMES = [ "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" ]; const FRAME_INTERVAL = 80; const CLEAR_LINE = "\r\x1B[2K"; const COLUMN_ONE = "\r"; /** * How far the phase clock has to be behind the total before both are worth * showing. During the first phase they are the same number twice. */ const PHASE_ELAPSED_THRESHOLD = 100; const METER_WIDTH = 20; /** The shortest a meter's detail is cut to before it is left out. */ const METER_DETAIL_MIN = 8; const HIDE_CURSOR = "\x1B[?25l"; const SHOW_CURSOR = "\x1B[?25h"; /** * A ticking elapsed time, in tenths of a second. Anything finer changes the * line on every frame, which is the whole cost the frame-only repaint avoids. */ /** * How long the phase in flight has taken, and how long the command has been * running, where those have parted company. A phase can hold a command for most * of its run, and its own clock is what says a still label is still working. */ function formatElapsed(snapshot, drift) { const total = snapshot.elapsed + drift; const phase = snapshot.phaseElapsed + drift; return total - phase >= PHASE_ELAPSED_THRESHOLD ? `${formatDuration(phase)} \u00B7 total ${formatDuration(total)}` : formatDuration(total); } /** `42/180`, for output that has no room for a bar. */ function formatCount(meter) { return meter ? ` ${meter.done}/${meter.total}` : ""; } /** `━━━━━━━━ 42/180`, drawn like the progress bar in the `nuxt dev` panel. */ function formatMeter(meter, width = METER_WIDTH) { const filled = meter.total ? Math.min(width, Math.floor(meter.done / meter.total * width)) : 0; const glyph = supportsUnicode() ? "━" : "="; return `${styleText("green", glyph.repeat(filled))}${styleText(MUTED, glyph.repeat(width - filled))} ${styleText(MUTED, `${meter.done}/${meter.total}`)}`; } /** Cut `text` to `width` columns, or drop it when too little of it would be left. */ function fit(text, width) { if (text.length <= width) return text; return width >= METER_DETAIL_MIN ? `\u2026${text.slice(text.length - width + 1)}` : ""; } function bundlePhaseLabels(phase) { return phase.startsWith("bundle:") ? phase.slice(7).split("+") : void 0; } function isAnimationSupported(stream = process.stdout) { return !!stream.isTTY && !isCI && !process.env.NO_COLOR; } /** `config 40ms · modules 1.2s · …`, or nothing if every phase was trivial. */ function formatPhaseBreakdown(timings) { return timings.filter((timing) => timing.duration >= 10).map((timing) => `${timing.phase} ${formatDuration(timing.duration)}`).join(" · "); } const PHASE_BAR_WIDTH = 24; /** * One phase per line with a bar placed where it ran within the command, so the * slow step stands out and phases that overlapped are seen to. */ function formatPhaseTable(timings) { let elapsed = 0; const shown = timings.map((timing) => { const start = timing.start ?? elapsed; elapsed = Math.max(elapsed, start + timing.duration); return { ...timing, start }; }).filter((timing) => timing.duration >= 10); if (!shown.length) return ""; const from = Math.min(...shown.map((timing) => timing.start)); const span = Math.max(1, Math.max(...shown.map((timing) => timing.start + timing.duration)) - from); const nameWidth = Math.max(...shown.map((timing) => timing.phase.length)); const durations = shown.map((timing) => formatDuration(timing.duration)); const durationWidth = Math.max(...durations.map((duration) => duration.length)); return shown.map((timing, index) => { const left = Math.min(23, Math.floor((timing.start - from) / span * PHASE_BAR_WIDTH)); const right = Math.max(left + 1, Math.round((timing.start - from + timing.duration) / span * PHASE_BAR_WIDTH)); const bar = `${" ".repeat(left)}${styleText("cyan", "█".repeat(right - left))}${" ".repeat(PHASE_BAR_WIDTH - right)}`; return `${timing.phase.padEnd(nameWidth)} ${bar} ${styleText(MUTED, durations[index].padStart(durationWidth))}`; }).join("\n"); } /** * The URL the summary points at, so the address is on screen at the moment the * user is being told they can click it rather than a screenful further up. */ function formatURL(url) { return ` ${styleText("dim", "→")} ${styleText("cyan", terminalLink(url, url))}`; } /** * The line a long-running command leaves behind once it is up. A command that * only builds never reaches `ready` and reports its own completion instead. */ function formatSummary(snapshot, url) { const breakdown = formatPhaseBreakdown(snapshot.timings); const detail = snapshot.serving || !snapshot.message || snapshot.message === "Ready" ? "" : styleText("dim", ` \u00B7 ${decapitalise(snapshot.message)}`); const headline = `${snapshot.reload ? "Reloaded" : "Ready"} in ${formatDuration(snapshot.elapsed)}${detail}${url ? formatURL(url) : ""}`; return breakdown ? `${headline}\n${styleText("dim", breakdown)}` : headline; } /** * Report progress through a command's phases on a single line that updates in * place, collapsing to one summary line with a phase breakdown once the command * reports itself ready, and then narrating the first page render, which is where * the rest of the wait is spent. Falls back to sequential logs when the output * is not an interactive terminal. */ function createPhaseReporter(options = {}) { const stream = options.stream ?? process.stdout; const animated = options.animated ?? isAnimationSupported(stream); let snapshot; let summarised = false; let lastPhase; let lastMessage; let lastLoggedAt = 0; let frame = 0; let dirty = false; let painted; /** Whether the cursor is currently hidden for the transient line. */ let hidden = false; let timer; let stopped = false; let withheld = false; /** The latest line that was due while a question held the screen. */ let missed; let receivedAt = Date.now(); let pulse; let url; /** The request the line is currently reporting, so it is announced once. */ let narrating; /** Whether the wait was ever narrated, and so is worth closing off. */ let narrated = false; /** When the render being waited on arrived, so the wait can be measured. */ let renderStartedAt; const tap = animated ? tapOutput(stream, () => clear()) : void 0; const write = tap?.write ?? stream.write.bind(stream); function log(line, message) { if (withheld) { missed = [line, message]; return; } lastMessage = message; lastLoggedAt = Date.now(); logger.info(line); } function clear() { if (dirty) { write(CLEAR_LINE); dirty = false; painted = void 0; } } /** * The line after the spinner glyph: what the command is doing and how long it * has been doing it. Once the summary is printed that is no longer a phase but * the request being rendered, which has its own clock. */ function describe() { const pending = summarised ? snapshot.pending : void 0; if (pending) return `rendering ${pending.label} ${styleText(MUTED, formatDuration(Date.now() - pending.startedAt))}`; const { meter } = snapshot; const line = `${snapshot.message}${meter ? ` ${formatMeter(meter)}` : ""} ${styleText(MUTED, formatElapsed(snapshot, Date.now() - receivedAt))}`; if (!meter?.detail) return line; const room = (stream.columns || 80) - visibleWidth(line) - 4; const detail = fit(meter.detail, room); return detail ? `${line} ${styleText(MUTED, detail)}` : line; } function render() { if (!snapshot || stopped || withheld) return; const glyph = styleText("cyan", FRAMES[frame = (frame + 1) % FRAMES.length]); const line = describe(); if (dirty && line === painted) { write(`${COLUMN_ONE}${glyph}`); return; } clear(); write(`${glyph} ${line}`); painted = line; dirty = true; } function animate() { if (!animated || timer || withheld) return; hidden = true; write(HIDE_CURSOR); timer = setInterval(render, FRAME_INTERVAL); timer.unref?.(); } animate(); const offScreen = onScreenHeld((held) => { if (held) withhold(); else resumePainting(); }); /** * Repeat whatever is in flight, with the time it has taken so far, so a long * silent stretch in a piped log still shows something is alive. A render is * repeated the same way: nothing else is printed while it compiles. */ function schedulePulse() { clearInterval(pulse); pulse = void 0; if (!options.heartbeat || animated || withheld) return; pulse = setInterval(() => { if (!snapshot || stopped) return; const pending = summarised ? snapshot.pending : void 0; if (pending) { log(announce(pending.label, Date.now() - pending.startedAt), `rendering ${pending.label}`); return; } log(`${snapshot.message}${formatCount(snapshot.meter)} ${styleText("dim", `(${formatElapsed(snapshot, Date.now() - receivedAt)})`)}`, snapshot.message); }, options.heartbeat); pulse.unref?.(); } /** A render, as its own line, for output that cannot redraw one in place. */ function announce(label, elapsed) { return `Rendering ${label}${elapsed === void 0 ? "" : ` ${styleText("dim", `(${formatDuration(elapsed)})`)}`}`; } /** Take the line down, leaving the terminal as it was found. */ function restore() { clearInterval(pulse); pulse = void 0; if (timer) { clearInterval(timer); timer = void 0; } if (animated && hidden) { hidden = false; clear(); write(SHOW_CURSOR); } } function finish() { stopped = true; offScreen(); restore(); tap?.dispose(); } function withhold() { if (stopped || withheld) return; withheld = true; restore(); } function resumePainting() { if (stopped || !withheld) return; withheld = false; if (missed) { log(...missed); missed = void 0; } if (summarised && !snapshot?.pending) return; if (!animated) { schedulePulse(); return; } animate(); render(); } return { setURL(next) { url = next; }, update(next) { if (stopped) return; if (summarised && next.status !== "ready") return; snapshot = next; receivedAt = Date.now(); if (next.status === "error") { finish(); return; } if (next.status !== "ready") { if (animated) { if (!next.meter || next.phase !== lastPhase) { lastPhase = next.phase; render(); } return; } if (next.phase !== lastPhase) { const previous = lastPhase === void 0 ? void 0 : bundlePhaseLabels(lastPhase); const current = bundlePhaseLabels(next.phase); const finishing = previous !== void 0 && current !== void 0 && current.length < previous.length && current.every((label) => previous.includes(label)); lastPhase = next.phase; if (!finishing) { log(next.message, next.message); schedulePulse(); } return; } if (options.heartbeat && next.message !== lastMessage && Date.now() - lastLoggedAt >= options.heartbeat) log(`${next.message} ${styleText("dim", `(${formatElapsed(next, 0)})`)}`, next.message); return; } if (!summarised) { restore(); summarised = true; missed = void 0; narrated = !next.serving && next.message !== "Ready"; logger.success(formatSummary(next, url)); } if (next.serving) { restore(); if (narrated) logger.success(renderStartedAt === void 0 ? `Serving in ${formatDuration(next.elapsed)}` : `First render in ${formatDuration(Date.now() - renderStartedAt)}`); finish(); return; } if (!next.pending) { narrating = void 0; restore(); return; } narrated = true; renderStartedAt ??= next.pending.startedAt; if (animated) { animate(); render(); return; } if (narrating !== next.pending.label) { narrating = next.pending.label; log(announce(next.pending.label), `rendering ${next.pending.label}`); schedulePulse(); } }, stop() { finish(); } }; } export { stopCpuProfile as a, startCpuProfile as i, formatPhaseBreakdown as n, formatPhaseTable as r, createPhaseReporter as t };