Skip to content
Merged
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
5 changes: 5 additions & 0 deletions packages/nuxt-cli/src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { resolveDotenvFileNames } from '../utils/args'
import { showBanner } from '../utils/banner'
import { BuildProgress } from '../utils/build-progress'
import { createBuildReport } from '../utils/build-report'
import { configureProjectConsola, reportThroughClack } from '../utils/console'
import { overrideEnv } from '../utils/env'

import { ActionableError } from '../utils/errors'
Expand Down Expand Up @@ -63,8 +64,10 @@ export default defineCommand({
const releaseLocks: Array<() => void> = []
const progress = new BuildProgress()
let stopReporting = () => {}
let stopClackReporting = () => {}
try {
intro(styleText('cyan', 'Building Nuxt for production...'))
stopClackReporting = reportThroughClack()

// The phase line owns a row of the terminal, which a silent build has no
// business drawing on. Subscribed after the intro so the first phase is
Expand All @@ -83,6 +86,7 @@ export default defineCommand({
}

const kit = await loadKit(cwd)
await configureProjectConsola(cwd)
const nuxt = await kit.loadNuxt({
cwd,
ready: false,
Expand Down Expand Up @@ -190,6 +194,7 @@ export default defineCommand({
}
finally {
stopReporting()
stopClackReporting()
for (const release of releaseLocks.reverse()) {
release()
}
Expand Down
66 changes: 62 additions & 4 deletions packages/nuxt-cli/src/utils/console.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,43 @@
import type { ConsolaInstance, ConsolaOptions, ConsolaReporter } from 'consola'
import type { ConsolaInstance, ConsolaOptions, ConsolaReporter, FormatOptions, LogObject } from 'consola'

import process from 'node:process'
import { pathToFileURL } from 'node:url'
import { format, styleText } from 'node:util'

import { consola } from 'consola'
import { resolveModulePath } from 'exsolve'
import { isCI } from 'std-env'

import { isRemotePeerError } from './errors'
import { debug } from './logger'
import { debug, isEmittingCliLog, logger } from './logger'
import { tryResolveNuxt } from './resolve-nuxt'
import { holdScreen, isScreenHeld, takeUnseenOutput } from './screen'
import { withUserAttention } from './startup-clock'
import { isInteractiveSession, trackOutputSpacing, writeDirect } from './stdout'
import { MUTED } from './terminal-theme'

function wrapReporter(reporter: ConsolaReporter) {
type FormattingReporter = ConsolaReporter & {
formatArgs?: (args: unknown[], opts: FormatOptions) => string
}

let clackReporting = false

/**
* Render consola logs as clack log lines, so the project's logs share the
* gutter the CLI draws down the side of a command's output. Only takes effect
* where that gutter is drawn. Returns a function that switches it off again.
*/
export function reportThroughClack(): () => void {
if (!process.stdout.isTTY || isCI) {
return () => {}
}
clackReporting = true
return () => {
clackReporting = false
}
}

export function wrapReporter(reporter: FormattingReporter): ConsolaReporter {
return ({
log(logObj, ctx) {
if (!logObj.args || !logObj.args.length) {
Expand All @@ -26,11 +50,45 @@ function wrapReporter(reporter: ConsolaReporter) {
return
}
}
if (clackReporting && !isEmittingCliLog() && logObj.type !== 'box' && logObj.type !== 'trace') {
const opts = { columns: process.stdout.columns || 0, ...ctx.options.formatOptions }
const message = reporter.formatArgs
? reporter.formatArgs(logObj.args, opts)
: format(...logObj.args)
return logThroughClack(logObj, message)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
return reporter.log(logObj, ctx)
},
}) satisfies ConsolaReporter
}

/** Bypasses `consola.wrapStd()`, which would hand each line back to consola. */
const directOutput = { write: writeDirect } as unknown as NodeJS.WriteStream

function logThroughClack(logObj: LogObject, message: string): void {
message = message.replace(/`([^`\n]+)`/g, (_, code) => styleText('cyan', code))
if (logObj.tag) {
message = `${styleText(MUTED, `[${logObj.tag}]`)} ${message}`
}
const options = { output: directOutput }
switch (logObj.type) {
case 'fatal':
case 'error':
case 'fail':
return logger.error(message, options)
case 'warn':
return logger.warn(message, options)
case 'success':
case 'ready':
return logger.success(message, options)
case 'info':
case 'start':
return logger.info(message, options)
default:
return logger.message(message, options)
}
}

/** How Node opens a process warning, such as `(node:1234) DeprecationWarning: …`. */
const PROCESS_WARNING_RE = /^\(node:\d+\) /

Expand Down Expand Up @@ -62,7 +120,7 @@ export async function configureProjectConsola(rootDir: string): Promise<void> {
projectConsola.options.formatOptions.date = false
routeProcessWarnings(projectConsola)
interceptPrompts(projectConsola)
// Logs from a separate instance would otherwise bypass the dev UI's reporters.
// Logs from a separate instance would otherwise bypass the CLI's reporters.
if (projectConsola !== consola) {
projectConsola.setReporters([
{
Expand Down
10 changes: 5 additions & 5 deletions packages/nuxt-cli/src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ export function setLoggerImpl(next?: LoggerImpl): void {
}

export const logger: LoggerImpl = {
info: message => emit(() => (impl ?? defaultImpl()).info(message)),
warn: message => emit(() => (impl ?? defaultImpl()).warn(message)),
error: message => emit(() => (impl ?? defaultImpl()).error(message)),
success: message => emit(() => (impl ?? defaultImpl()).success(message)),
step: message => emit(() => (impl ?? defaultImpl()).step(message)),
info: (message, options) => emit(() => (impl ?? defaultImpl()).info(message, options)),
warn: (message, options) => emit(() => (impl ?? defaultImpl()).warn(message, options)),
error: (message, options) => emit(() => (impl ?? defaultImpl()).error(message, options)),
success: (message, options) => emit(() => (impl ?? defaultImpl()).success(message, options)),
step: (message, options) => emit(() => (impl ?? defaultImpl()).step(message, options)),
message: (message, options) => emit(() => (impl ?? defaultImpl()).message(message, options)),
}

Expand Down
33 changes: 33 additions & 0 deletions packages/nuxt-cli/test/unit/commands/build.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ const mocks = vi.hoisted(() => ({
acquireOutputLock: vi.fn(),
buildNuxt: vi.fn(),
clearBuildDir: vi.fn(),
configureProjectConsola: vi.fn(),
loadNuxt: vi.fn(),
releaseBuildDir: vi.fn(),
releaseOutputDir: vi.fn(),
reportThroughClack: vi.fn(),
startCpuProfile: vi.fn(),
stopClackReporting: vi.fn(),
stopCpuProfile: vi.fn(),
useNitro: vi.fn(),
writeTypes: vi.fn(),
Expand All @@ -26,6 +29,10 @@ vi.mock('@clack/prompts', () => ({
vi.mock('../../../src/utils/banner', () => ({
showBanner: vi.fn(),
}))
vi.mock('../../../src/utils/console', () => ({
configureProjectConsola: mocks.configureProjectConsola,
reportThroughClack: mocks.reportThroughClack,
}))
vi.mock('../../../src/utils/env', () => ({
overrideEnv: vi.fn(),
}))
Expand Down Expand Up @@ -86,6 +93,32 @@ describe('build', () => {
})
mocks.acquireLock.mockReturnValue({ release: mocks.releaseBuildDir })
mocks.acquireOutputLock.mockReturnValue({ release: mocks.releaseOutputDir })
mocks.reportThroughClack.mockReturnValue(mocks.stopClackReporting)
})

it.each([
['succeeds', undefined],
[
'fails',
new Error('build failed'),
],
])('renders project logs through clack while the build runs, and stops when it %s', async (_, error) => {
mocks.buildNuxt.mockImplementationOnce(async () => {
expect(mocks.reportThroughClack).toHaveBeenCalledOnce()
expect(mocks.configureProjectConsola).toHaveBeenCalledWith(cwd)
expect(mocks.reportThroughClack.mock.invocationCallOrder[0]).toBeLessThan(mocks.loadNuxt.mock.invocationCallOrder[0]!)
expect(mocks.configureProjectConsola.mock.invocationCallOrder[0]).toBeLessThan(mocks.loadNuxt.mock.invocationCallOrder[0]!)
expect(mocks.stopClackReporting).not.toHaveBeenCalled()
if (error) {
throw error
}
})

await (error
? expect(run()).rejects.toBe(error)
: run())

expect(mocks.stopClackReporting).toHaveBeenCalledOnce()
})

it('loads Nuxt with build arguments and runs the build in order', async () => {
Expand Down
Loading
Loading