Unverified Commit 91280dbb authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Add bundle analyzer query CLI

Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 4f96d766
......@@ -29,6 +29,7 @@ import type { NextStartOptions } from '../cli/next-start.js'
import type { NextInfoOptions } from '../cli/next-info.js'
import type { NextDevOptions } from '../cli/next-dev.js'
import type { NextAnalyzeOptions } from '../cli/next-analyze.js'
import type { NextAnalyzeQueryOptions } from '../cli/next-analyze-query.js'
import type { NextBuildOptions } from '../cli/next-build.js'
import type { NextTypegenOptions } from '../cli/next-typegen.js'
import type { NextPostBuildOptions } from '../cli/next-post-build.js'
......@@ -289,9 +290,27 @@ program
'--baseline-name <name>',
'Name this baseline in the snapshot metadata, overriding branch/sha in the comparison UI.'
)
.addOption(
new Option(
'-o, --output',
'Only write analysis files to disk. Does not start the server.'
).conflicts('query')
)
.addOption(
new Option(
'--query <tool>',
'Query previously generated analyzer data as JSON.'
).conflicts('output')
)
.option(
'--analyze-dir <directory>',
'Analyzer output directory for --query.',
'.next/diagnostics/analyze'
)
.option(
'-o, --output',
'Only write analysis files to disk. Does not start the server.'
'--input <json>',
'Tool arguments for --query as a JSON object.',
'{}'
)
.addOption(
new Option(
......@@ -303,17 +322,27 @@ program
.default(4000)
.env('PORT')
)
.action((directory: string, options: NextAnalyzeOptions) => {
return import('../cli/next-analyze.js')
.then((mod) => mod.nextAnalyze(options, directory))
.then(() => {
if (options.output) {
// The Next.js process is held open by something on the event loop. Exit manually like the `build` command does.
// TODO: Fix the underlying issue so this is not necessary.
process.exit(0)
}
})
})
.action(
(
directory: string,
options: NextAnalyzeOptions & NextAnalyzeQueryOptions
) => {
if (options.query) {
return import('../cli/next-analyze-query.js').then((mod) =>
mod.nextAnalyzeQuery(options.query!, options)
)
}
return import('../cli/next-analyze.js')
.then((mod) => mod.nextAnalyze(options, directory))
.then(() => {
if (options.output) {
// The Next.js process is held open by something on the event loop. Exit manually like the `build` command does.
// TODO: Fix the underlying issue so this is not necessary.
process.exit(0)
}
})
}
)
program
.command('dev', { isDefault: true })
......
import { AnalyzeRepository } from './repository'
import { createAnalyzeMcpServer } from './mcp-server'
type McpServer = ReturnType<typeof createAnalyzeMcpServer>
type Transport = Parameters<McpServer['connect']>[0]
type Message = Parameters<Transport['send']>[0]
type SendOptions = Parameters<Transport['send']>[1]
class LinkedTransport implements Transport {
private peer?: LinkedTransport
onclose?: Transport['onclose']
onerror?: Transport['onerror']
onmessage?: Transport['onmessage']
static createPair(): [LinkedTransport, LinkedTransport] {
const client = new LinkedTransport()
const server = new LinkedTransport()
client.peer = server
server.peer = client
return [client, server]
}
async start(): Promise<void> {}
async send(message: Message, _options?: SendOptions): Promise<void> {
if (!this.peer) throw new Error('MCP transport is closed')
this.peer.onmessage?.(message)
}
async close(): Promise<void> {
const peer = this.peer
this.peer = undefined
if (peer?.peer) await peer.close()
this.onclose?.()
}
}
type RpcResponse = {
id?: string | number
result?: {
content?: Array<{ type: string; text?: string }>
isError?: boolean
}
error?: { message?: string }
}
/** Invoke an analyzer tool in-process without starting an HTTP server. */
export async function queryAnalyzeData(
analyzeDir: string,
name: string,
args: Record<string, unknown>
): Promise<unknown> {
const mcpServer = createAnalyzeMcpServer(new AnalyzeRepository(analyzeDir))
const [clientTransport, serverTransport] = LinkedTransport.createPair()
const response = new Promise<RpcResponse>((resolve) => {
clientTransport.onmessage = (message) => resolve(message as RpcResponse)
})
try {
await mcpServer.connect(serverTransport)
await clientTransport.start()
await clientTransport.send({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name, arguments: args },
} as Message)
const message = await response
if (message.error)
throw new Error(message.error.message || 'MCP query failed')
const result = message.result
const text = result?.content?.find((item) => item.type === 'text')?.text
if (!text) throw new Error('MCP tool returned no JSON content')
const value: unknown = JSON.parse(text)
if (result?.isError) {
const detail =
typeof value === 'object' &&
value !== null &&
'error' in value &&
typeof value.error === 'string'
? value.error
: 'Analyzer query failed'
throw new Error(detail)
}
return value
} finally {
await mcpServer.close()
}
}
#!/usr/bin/env node
import * as path from 'node:path'
import { queryAnalyzeData } from '../build/analyze/query'
export type NextAnalyzeQueryOptions = {
query?: string
analyzeDir?: string
input?: string
}
export async function nextAnalyzeQuery(
tool: string,
options: NextAnalyzeQueryOptions
): Promise<void> {
try {
const input: unknown = JSON.parse(options.input ?? '{}')
if (typeof input !== 'object' || input === null || Array.isArray(input)) {
throw new Error('--input must be a JSON object')
}
const analyzeDir = path.resolve(
options.analyzeDir ?? '.next/diagnostics/analyze'
)
const result = await queryAnalyzeData(
analyzeDir,
tool,
input as Record<string, unknown>
)
process.stdout.write(`${JSON.stringify(result)}\n`)
} catch (error) {
const message =
error instanceof Error ? error.message : 'Analyzer query failed'
process.stderr.write(`${JSON.stringify({ error: message })}\n`)
process.exitCode = 1
}
}
......@@ -210,6 +210,66 @@ describe('next experimental-analyze', () => {
await exit.catch(() => {})
}
})
it('queries saved analyzer data as JSON', async () => {
const { exitCode } = await next.runCommand([
'experimental-analyze',
'--output',
])
expect(exitCode).toBe(0)
async function query(tool: string, input: Record<string, unknown> = {}) {
const result = await next.runCommand([
'experimental-analyze',
'--query',
tool,
'--input',
JSON.stringify(input),
])
expect(result.exitCode).toBe(0)
expect(result.stderr).toBe('')
return JSON.parse(result.stdout)
}
const overview = await query('get_bundle_overview', { limit: 1 })
expect(overview.routes).toHaveLength(1)
const sources = await query('query_bundle_sources', {
route: '/',
limit: 1,
})
expect(sources.sources).toHaveLength(1)
const explanation = await query('explain_bundle_source', {
route: '/',
sourcePath: sources.sources[0].sourcePath,
})
expect(explanation.sourcePath).toBe(sources.sources[0].sourcePath)
const comparison = await query('compare_bundles', {
baselineSnapshot: overview.snapshots.history[0].id,
limit: 1,
})
expect(comparison.rows).toHaveLength(1)
const malformed = await next.runCommand([
'experimental-analyze',
'--query',
'get_bundle_overview',
'--input',
'not-json',
])
expect(malformed.exitCode).toBe(1)
expect(JSON.parse(malformed.stderr)).toHaveProperty('error')
const conflicting = await next.runCommand([
'experimental-analyze',
'--query',
'get_bundle_overview',
'--output',
])
expect(conflicting.exitCode).toBe(1)
expect(conflicting.stderr).toContain('cannot be used with option')
})
;['-o', '--output'].forEach((flag) => {
describe(`with ${flag} flag`, () => {
it('writes output to .next/diagnostics/analyze path', async () => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment