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

Add analyzer CLI query discovery

Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 12189a82
...@@ -294,13 +294,19 @@ program ...@@ -294,13 +294,19 @@ program
new Option( new Option(
'-o, --output', '-o, --output',
'Only write analysis files to disk. Does not start the server.' 'Only write analysis files to disk. Does not start the server.'
).conflicts('query') ).conflicts(['query', 'listQueries'])
) )
.addOption( .addOption(
new Option( new Option(
'--query <tool>', '--query <tool>',
'Query previously generated analyzer data as JSON.' 'Query previously generated analyzer data as JSON.'
).conflicts('output') ).conflicts(['output', 'listQueries'])
)
.addOption(
new Option(
'--list-queries',
'List agent-readable analyzer queries and input schemas as JSON.'
).conflicts(['output', 'query'])
) )
.option( .option(
'--analyze-dir <directory>', '--analyze-dir <directory>',
...@@ -327,6 +333,11 @@ program ...@@ -327,6 +333,11 @@ program
directory: string, directory: string,
options: NextAnalyzeOptions & NextAnalyzeQueryOptions options: NextAnalyzeOptions & NextAnalyzeQueryOptions
) => { ) => {
if (options.listQueries) {
return import('../cli/next-analyze-query.js').then((mod) =>
mod.nextAnalyzeListQueries(options)
)
}
if (options.query) { if (options.query) {
return import('../cli/next-analyze-query.js').then((mod) => return import('../cli/next-analyze-query.js').then((mod) =>
mod.nextAnalyzeQuery(options.query!, options) mod.nextAnalyzeQuery(options.query!, options)
......
...@@ -205,11 +205,9 @@ async function collectRoutesForAnalyze( ...@@ -205,11 +205,9 @@ async function collectRoutesForAnalyze(
} }
function startServer(dir: string, port: number): Promise<void> { function startServer(dir: string, port: number): Promise<void> {
const server = http.createServer((req, res) => { const server = http.createServer((req, res) =>
return serveHandler(req, res, { serveHandler(req, res, { public: dir })
public: dir, )
})
})
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
function onError(err: Error) { function onError(err: Error) {
...@@ -245,6 +243,9 @@ function startServer(dir: string, port: number): Promise<void> { ...@@ -245,6 +243,9 @@ function startServer(dir: string, port: number): Promise<void> {
} }
Log.info(`Bundle analyzer available at http://${addressString}`) Log.info(`Bundle analyzer available at http://${addressString}`)
Log.info(
'For agent-readable bundle queries, run: next experimental-analyze --list-queries'
)
resolve() resolve()
}) })
}) })
......
...@@ -122,14 +122,24 @@ function safeQuery<T, R>(fn: (args: T) => Promise<R>) { ...@@ -122,14 +122,24 @@ function safeQuery<T, R>(fn: (args: T) => Promise<R>) {
} }
} }
type StoredQuery = { export type AnalyzeQueryListing = {
name: string name: string
description: string
inputSchema: Record<string, unknown>
example: Record<string, unknown>
}
type StoredQuery = AnalyzeQueryListing & {
execute: (input: unknown) => Promise<unknown> execute: (input: unknown) => Promise<unknown>
} }
export class AnalyzeQueryRegistry { export class AnalyzeQueryRegistry {
constructor(private readonly queries: StoredQuery[]) {} constructor(private readonly queries: StoredQuery[]) {}
list(): AnalyzeQueryListing[] {
return this.queries.map(({ execute: _execute, ...query }) => query)
}
async execute(name: string, input: unknown): Promise<unknown> { async execute(name: string, input: unknown): Promise<unknown> {
const query = this.queries.find((item) => item.name === name) const query = this.queries.find((item) => item.name === name)
if (!query) { if (!query) {
...@@ -142,6 +152,7 @@ export class AnalyzeQueryRegistry { ...@@ -142,6 +152,7 @@ export class AnalyzeQueryRegistry {
if (error instanceof z.ZodError) { if (error instanceof z.ZodError) {
throw new AnalyzeQueryError({ throw new AnalyzeQueryError({
error: `Invalid arguments for query ${name}: ${error.message}`, error: `Invalid arguments for query ${name}: ${error.message}`,
example: query.example,
}) })
} }
throw error throw error
...@@ -545,34 +556,130 @@ function provenance(metadata: SnapshotMetadata) { ...@@ -545,34 +556,130 @@ function provenance(metadata: SnapshotMetadata) {
} }
} }
function jsonField(input: z.ZodTypeAny): {
schema: Record<string, unknown>
required: boolean
} {
const description = input.description
let field = input
let required = true
if (field instanceof z.ZodOptional) {
required = false
field = field.unwrap()
}
const schema: Record<string, unknown> = {}
if (field instanceof z.ZodString) {
schema.type = 'string'
for (const check of field._def.checks) {
if (check.kind === 'min') schema.minLength = check.value
if (check.kind === 'max') schema.maxLength = check.value
}
} else if (field instanceof z.ZodNumber) {
schema.type = field._def.checks.some((check) => check.kind === 'int')
? 'integer'
: 'number'
for (const check of field._def.checks) {
if (check.kind === 'min') schema.minimum = check.value
if (check.kind === 'max') schema.maximum = check.value
}
} else if (field instanceof z.ZodEnum) {
schema.type = 'string'
schema.enum = field.options
} else if (field instanceof z.ZodArray) {
schema.type = 'array'
schema.items = jsonField(field.element).schema
if (field._def.maxLength) schema.maxItems = field._def.maxLength.value
} else {
throw new Error(`Unsupported analyzer query schema: ${field._def.typeName}`)
}
if (description) schema.description = description
return { schema, required }
}
function jsonSchema(shape: z.ZodRawShape): Record<string, unknown> {
const properties: Record<string, unknown> = {}
const required: string[] = []
for (const [name, field] of Object.entries(shape)) {
const result = jsonField(field)
properties[name] = result.schema
if (result.required) required.push(name)
}
return {
type: 'object',
properties,
...(required.length ? { required } : {}),
additionalProperties: false,
}
}
const pagingSchema = { const pagingSchema = {
offset: z.number().int().nonnegative().optional(), offset: z
limit: z.number().int().min(1).max(MAX_LIMIT).optional(), .number()
.int()
.nonnegative()
.optional()
.describe('Zero-based result offset. Default: 0.'),
limit: z
.number()
.int()
.min(1)
.max(MAX_LIMIT)
.optional()
.describe(`Maximum results. Default: ${DEFAULT_LIMIT}; max: ${MAX_LIMIT}.`),
} }
const snapshotSchema = z.string().max(100).optional() const snapshotSchema = z
const metricSchema = z.enum(['raw', 'compressed']).optional() .string()
const environmentSchema = z.enum(['total', 'client', 'server']).optional() .max(100)
.optional()
.describe('Snapshot ID. Default: `current`.')
const metricSchema = z
.enum(['raw', 'compressed'])
.optional()
.describe('Size metric. Default: `raw`.')
const environmentSchema = z
.enum(['total', 'client', 'server'])
.optional()
.describe('Attribution environment. Default: `total`.')
export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) { export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) {
const queries: StoredQuery[] = [] const queries: StoredQuery[] = []
function registerQuery<T extends z.ZodRawShape>( function registerQuery<T extends z.ZodRawShape>(
name: string, name: string,
inputSchema: T, config: {
description: string
inputSchema: T
example: Record<string, unknown>
},
callback: (args: z.infer<z.ZodObject<T>>) => Promise<unknown> callback: (args: z.infer<z.ZodObject<T>>) => Promise<unknown>
) { ) {
const schema = z.object(inputSchema).strict() const schema = z.object(config.inputSchema).strict()
queries.push({ name, execute: (input) => callback(schema.parse(input)) }) queries.push({
name,
description: config.description,
inputSchema: jsonSchema(config.inputSchema),
example: config.example,
execute: (input) => callback(schema.parse(input)),
})
} }
registerQuery( registerQuery(
'get_bundle_overview', 'get_bundle_overview',
{ {
description:
'List analyzer snapshots and rank routes by raw or estimated compressed bundle contribution.',
inputSchema: {
snapshot: snapshotSchema, snapshot: snapshotSchema,
environment: z.enum(['total', 'client']).optional(), environment: z
.enum(['total', 'client'])
.optional()
.describe('Attribution environment. Default: `total`.'),
metric: metricSchema, metric: metricSchema,
routeFilter: z.string().max(1000).optional(), routeFilter: z.string().max(1000).optional(),
...pagingSchema, ...pagingSchema,
}, },
example: { environment: 'client', limit: 10 },
},
safeQuery(async (args: OverviewArgs) => { safeQuery(async (args: OverviewArgs) => {
const snapshot = await repository.getSnapshot(args.snapshot) const snapshot = await repository.getSnapshot(args.snapshot)
const snapshots = await repository.listSnapshots() const snapshots = await repository.listSnapshots()
...@@ -616,6 +723,9 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) { ...@@ -616,6 +723,9 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) {
registerQuery( registerQuery(
'query_bundle_sources', 'query_bundle_sources',
{ {
description:
'Query and rank source or npm-package contributions for one analyzed route.',
inputSchema: {
route: z.string().max(4096), route: z.string().max(4096),
snapshot: snapshotSchema, snapshot: snapshotSchema,
search: z.string().max(1000).optional(), search: z.string().max(1000).optional(),
...@@ -624,10 +734,20 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) { ...@@ -624,10 +734,20 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) {
.array(z.enum(['js', 'css', 'json', 'asset'])) .array(z.enum(['js', 'css', 'json', 'asset']))
.max(4) .max(4)
.optional(), .optional(),
groupBy: z.enum(['source', 'package']).optional(), groupBy: z
.enum(['source', 'package'])
.optional()
.describe('Result grouping. Default: `source`.'),
metric: metricSchema, metric: metricSchema,
...pagingSchema, ...pagingSchema,
}, },
example: {
route: '/',
environment: 'client',
groupBy: 'package',
limit: 20,
},
},
safeQuery(async (args: SourcesArgs) => { safeQuery(async (args: SourcesArgs) => {
const environment = args.environment ?? 'total' const environment = args.environment ?? 'total'
const metric = args.metric ?? 'raw' const metric = args.metric ?? 'raw'
...@@ -659,12 +779,23 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) { ...@@ -659,12 +779,23 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) {
registerQuery( registerQuery(
'explain_bundle_source', 'explain_bundle_source',
{ {
description:
'Explain one source contribution and return a bounded importer chain toward a heuristic route entry.',
inputSchema: {
route: z.string().max(4096), route: z.string().max(4096),
sourcePath: z.string().max(4096), sourcePath: z.string().max(4096),
snapshot: snapshotSchema, snapshot: snapshotSchema,
moduleIdent: z.string().max(4096).optional(), moduleIdent: z.string().max(4096).optional(),
environment: environmentSchema, environment: environmentSchema,
maxDepth: z.number().int().min(1).max(100).optional(), maxDepth: z
.number()
.int()
.min(1)
.max(100)
.optional()
.describe('Maximum importer-chain depth. Default: 25.'),
},
example: { route: '/', sourcePath: '[project]/src/app/page.tsx' },
}, },
safeQuery(async (args: ExplainArgs) => { safeQuery(async (args: ExplainArgs) => {
const environment = args.environment ?? 'total' const environment = args.environment ?? 'total'
...@@ -742,15 +873,32 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) { ...@@ -742,15 +873,32 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) {
registerQuery( registerQuery(
'compare_bundles', 'compare_bundles',
{ {
baselineSnapshot: z.string().max(100), description:
'Compare two analyzer snapshots at route, source, or npm-package granularity.',
inputSchema: {
baselineSnapshot: z
.string()
.max(100)
.describe(
'Required historical snapshot ID from get_bundle_overview.'
),
comparisonSnapshot: snapshotSchema, comparisonSnapshot: snapshotSchema,
granularity: z.enum(['route', 'source', 'package']).optional(), granularity: z
.enum(['route', 'source', 'package'])
.optional()
.describe('Comparison granularity. Default: `route`.'),
route: z.string().max(4096).optional(), route: z.string().max(4096).optional(),
environment: environmentSchema, environment: environmentSchema,
metric: metricSchema, metric: metricSchema,
search: z.string().max(1000).optional(), search: z.string().max(1000).optional(),
...pagingSchema, ...pagingSchema,
}, },
example: {
baselineSnapshot: '20260917-201045-abcdef0',
comparisonSnapshot: 'current',
limit: 20,
},
},
safeQuery(async (args: CompareArgs) => { safeQuery(async (args: CompareArgs) => {
const granularity = args.granularity ?? 'route' const granularity = args.granularity ?? 'route'
const environment = args.environment ?? 'total' const environment = args.environment ?? 'total'
......
import { AnalyzeRepository } from './repository' import { AnalyzeRepository } from './repository'
import { AnalyzeQueryError, createAnalyzeQueryRegistry } from './queries' import {
AnalyzeQueryError,
createAnalyzeQueryRegistry,
type AnalyzeQueryListing,
} from './queries'
export { AnalyzeQueryError } export { AnalyzeQueryError }
export function listAnalyzeQueries(analyzeDir: string): AnalyzeQueryListing[] {
return createAnalyzeQueryRegistry(new AnalyzeRepository(analyzeDir)).list()
}
export function queryAnalyzeData( export function queryAnalyzeData(
analyzeDir: string, analyzeDir: string,
name: string, name: string,
......
#!/usr/bin/env node #!/usr/bin/env node
import * as path from 'node:path' import * as path from 'node:path'
import { AnalyzeQueryError, queryAnalyzeData } from '../build/analyze/query' import {
AnalyzeQueryError,
listAnalyzeQueries,
queryAnalyzeData,
} from '../build/analyze/query'
export type NextAnalyzeQueryOptions = { export type NextAnalyzeQueryOptions = {
query?: string query?: string
listQueries?: boolean
analyzeDir?: string analyzeDir?: string
input?: string input?: string
} }
...@@ -45,3 +50,11 @@ export async function nextAnalyzeQuery( ...@@ -45,3 +50,11 @@ export async function nextAnalyzeQuery(
) )
}) })
} }
export async function nextAnalyzeListQueries(
options: NextAnalyzeQueryOptions
): Promise<void> {
return printJson(async () => ({
queries: listAnalyzeQueries(analyzeDir(options)),
}))
}
...@@ -23,7 +23,7 @@ describe('next experimental-analyze', () => { ...@@ -23,7 +23,7 @@ describe('next experimental-analyze', () => {
return return
} }
it('runs successfully without errors', async () => { it('serves the UI and points agents to CLI discovery', async () => {
let serveProcess: ChildProcess | undefined let serveProcess: ChildProcess | undefined
let stdoutBuffer = '' let stdoutBuffer = ''
let resolveUrl!: (url: string) => void let resolveUrl!: (url: string) => void
...@@ -42,7 +42,10 @@ describe('next experimental-analyze', () => { ...@@ -42,7 +42,10 @@ describe('next experimental-analyze', () => {
onStdout(msg) { onStdout(msg) {
stdoutBuffer += msg stdoutBuffer += msg
const urlMatch = stdoutBuffer.match(/http:\/\/[^\s]+/) const urlMatch = stdoutBuffer.match(/http:\/\/[^\s]+/)
if (urlMatch) { if (
urlMatch &&
stdoutBuffer.includes('next experimental-analyze --list-queries')
) {
resolveUrl(urlMatch[0]) resolveUrl(urlMatch[0])
} }
}, },
...@@ -61,11 +64,46 @@ describe('next experimental-analyze', () => { ...@@ -61,11 +64,46 @@ describe('next experimental-analyze', () => {
expect(await response.text()).toContain( expect(await response.text()).toContain(
'<title>Next.js Bundle Analyzer</title>' '<title>Next.js Bundle Analyzer</title>'
) )
expect(stdoutBuffer).toContain(
'For agent-readable bundle queries, run: next experimental-analyze --list-queries'
)
expect(stdoutBuffer).not.toContain('MCP')
expect((await fetch(`${url}/mcp`)).status).toBe(404)
} finally { } finally {
serveProcess?.kill() serveProcess?.kill()
await exit.catch(() => {}) await exit.catch(() => {})
} }
}) })
it('lists agent-readable queries without analyzer data', async () => {
const result = await next.runCommand([
'experimental-analyze',
'--list-queries',
'--analyze-dir',
path.join(next.testDir, 'missing-analyzer-data'),
])
expect(result.exitCode).toBe(0)
expect(result.stderr).toBe('')
const listed = JSON.parse(result.stdout)
expect(listed.queries.map((query: { name: string }) => query.name)).toEqual(
[
'get_bundle_overview',
'query_bundle_sources',
'explain_bundle_source',
'compare_bundles',
]
)
expect(
listed.queries.find(
(query: { name: string }) => query.name === 'query_bundle_sources'
)
).toMatchObject({
inputSchema: {
required: ['route'],
additionalProperties: false,
},
example: { route: '/', environment: 'client' },
})
})
;['-o', '--output'].forEach((flag) => { ;['-o', '--output'].forEach((flag) => {
describe(`with ${flag} flag`, () => { describe(`with ${flag} flag`, () => {
it('writes output to .next/diagnostics/analyze path', async () => { 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