Unverified Commit 9997c1c0 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Bundle Analyzer Agent Skill: Stream versioned analyzer graph as JSON Lines (#99387)

## Summary

Separate analyzer capture from versioned JSON Lines graph replay. `next
analyze` builds the analyzer data and serves its UI; `next analyze
--output --snapshot-name <name>` saves the usual binary snapshot and UI
without serving. `next analyze --export-graph --snapshot-name <name>`
reads a saved snapshot and streams one typed JSON record per line
**without building or spawning a child**. Bare `--export-graph` reads
the newest snapshot; `--snapshot <id>` selects an exact generated ID,
and `--route` filters route records. Replay rejects a duplicate/missing
name and an explicit `--port`, but accepts inherited `PORT`.

Capture honors the configured `distDir` and holds Next's existing build
lock from before Turbopack writes through snapshot completion (or until
the UI exits). SWC bindings are installed **before** acquiring that
native lock. Replay does not load the app config: apps using a custom
directory pass `--dist-dir <relative-dir>` explicitly, leaving stdout as
JSON Lines. The authoritative v1 record schema ships with the installed
`next` package at `next/analyze/graph-v1.schema.json`; this root layer
exports verified base fields, and the stacked producer PRs add typed
roots, output membership and load relationships. The former
`--output=json` shortcut and `--graph-json` spelling are intentionally
rejected. Analyzer-owned filesystem work uses synchronous I/O for
capture setup, snapshot persistence/history pruning and graph reads.
Export keeps stdout drain handling and validates selected route data
before emitting; serial reads do not eliminate retained route-buffer
memory.

## Verification

- Removed the broad `analyze-graph-dump.test.ts` fixture suite from this
root and all descendants, leaving existing e2e unchanged. This
intentionally drops unique malformed-input, stream/backpressure,
collision and package-allowlist checks as agreed. Also removed
`analyze-snapshot-selection.test.ts` (254 lines) without replacements;
targeted mocked-history/path coverage is intentionally dropped. Neither
analyzer unit suite remains. Next package no-emit types, ESLint and
formatting pass across the distinct code layers. Scratch runtime probes
match prior export bytes, check route filtering,
corruption-before-output, drain/error behavior and snapshot
history/pruning/cleanup. Existing e2e/schema/producer/skill files are
unchanged; this pass changes four source files to use synchronous
analyzer I/O. Earlier packaging checks confirmed the schema in a packed
tarball.
- Native e2e/full Rust build cannot run in this disk-limited sandbox.
Prior head `39726552` passed the analyzer changed-test dev/prod jobs;
**new-head CI is still required**. Its full CI had separate failures
outside analyzer tests. Full model-driven agent evals were not run
locally.

<!-- NEXT_JS_LLM -->

<!-- fleet d7bdbc2b-b0bc-4591-99eb-dccb0fa49c73 -->





<!-- fleet ea768377-d71c-4a15-90b2-f4d50d4f6a1c -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 263f6820
......@@ -48,7 +48,7 @@ import {
computeModuleDepthMap,
computeSourceLoadScopes,
} from '@/lib/module-graph'
import type { SnapshotMetadata } from '@/lib/snapshot'
import { snapshotBaseDir, type SnapshotMetadata } from '@/lib/snapshot'
import { NetworkError } from '@/lib/errors'
import { formatBytes } from '@/lib/utils'
import { createAnalyzeTreemapSource, SizeMode } from '@/lib/treemap-layout'
......@@ -214,7 +214,7 @@ function useAnalyzerModel(compare: boolean) {
// previous selection is unlikely to exist in the new diff.
useEffect(() => {
setCompareSelectedKey(null)
}, [selectedRoute, routeState.fromId, routeState.toId])
}, [selectedRoute, routeState.fromName, routeState.toName])
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
......@@ -333,19 +333,20 @@ function useAnalyzerModel(compare: boolean) {
return {
analyzeData,
baselineSnapshot,
baselineIsLatest: compare && routeState.fromId === 'latest',
baselineIsLatest: compare && routeState.fromName === null,
compareSelectedKey,
compareView: activeView,
comparisonSnapshot,
historySnapshots: history?.snapshots ?? [],
historyError: historyError instanceof NetworkError,
invalidComparison: routeState.invalidComparison,
invalidSingleBuild: routeState.invalidSingleBuild,
latestSnapshot,
isCompareMode: compare,
singleBuildId: routeState.singleBuildId,
singleBuildName: routeState.singleBuildName,
singleSnapshot: routeState.singleSnapshot,
fromId: routeState.fromId,
toId: routeState.toId,
fromName: routeState.fromName,
toName: routeState.toName,
activeBaseDir: routeState.activeBaseDir,
currentRoutes,
routePickerOpen,
......@@ -439,9 +440,9 @@ function AnalyzerTopBar({
historyLoading={model.isHistoryLoading}
historyError={model.historyError}
latestSnapshot={model.latestSnapshot}
singleBuildId={model.singleBuildId}
fromId={model.fromId}
toId={model.toId}
singleBuildName={model.singleBuildName}
fromName={model.fromName}
toName={model.toName}
onSingleBuildChange={model.routeState.setSingleBuild}
onComparisonChange={model.routeState.setComparison}
routesBaseDir={model.activeBaseDir}
......@@ -470,7 +471,7 @@ function CompareAnalyzerView({ model }: { model: AnalyzerModel }) {
if (
model.baselineSnapshot &&
!model.invalidComparison &&
model.fromId !== (model.toId ?? 'latest')
model.fromName !== model.toName
)
return <ValidComparison model={model} />
......@@ -501,7 +502,7 @@ function ValidComparisonContent({
}) {
const baselineBaseDir = model.baselineIsLatest
? '/data'
: `/history/${baselineSnapshot.id}`
: snapshotBaseDir(baselineSnapshot)
const { data: baselineModulesData } = useSWR(
`${baselineBaseDir}/modules.data`,
fetchModulesData,
......@@ -678,7 +679,7 @@ function ComparisonContent({
}
function SingleAnalyzerView({ model }: { model: AnalyzerModel }) {
if (model.singleBuildId && model.isHistoryLoading) {
if (model.singleBuildName && model.isHistoryLoading) {
return (
<AnalyzerFrame topBar={<AnalyzerTopBar model={model} />}>
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
......@@ -687,7 +688,10 @@ function SingleAnalyzerView({ model }: { model: AnalyzerModel }) {
</AnalyzerFrame>
)
}
if (model.singleBuildId && !model.singleSnapshot && !model.isHistoryLoading) {
if (
model.invalidSingleBuild ||
(model.singleBuildName && !model.singleSnapshot && !model.isHistoryLoading)
) {
return (
<AnalyzerFrame topBar={<AnalyzerTopBar model={model} />}>
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
......
......@@ -9,13 +9,14 @@ import {
PopoverTrigger,
} from '@/components/ui/popover'
import {
encodeBuildSelection,
formatRelativeTime,
formatSnapshotLabel,
type SnapshotMetadata,
} from '@/lib/snapshot'
import { cn } from '@/lib/utils'
type BuildId = string | null
type BuildName = string | null
type PickerMode = 'single' | 'compare'
interface BuildPickerProps {
......@@ -24,11 +25,11 @@ interface BuildPickerProps {
historyLoading: boolean
historyError: boolean
latestSnapshot: SnapshotMetadata
singleBuildId: string | null
fromId: string | null
toId: string | null
onSingleBuildChange: (id: BuildId) => void
onComparisonChange: (from: BuildId, to: BuildId) => void
singleBuildName: string | null
fromName: string | null | undefined
toName: string | null | undefined
onSingleBuildChange: (id: BuildName) => void
onComparisonChange: (from: BuildName, to: BuildName) => void
}
export function BuildPicker({
......@@ -37,9 +38,9 @@ export function BuildPicker({
historyLoading,
historyError,
latestSnapshot,
singleBuildId,
fromId,
toId,
singleBuildName,
fromName,
toName,
onSingleBuildChange,
onComparisonChange,
}: BuildPickerProps) {
......@@ -50,25 +51,25 @@ export function BuildPicker({
const [search, setSearch] = useState('')
const snapshots = historySnapshots.filter(
(snapshot) => snapshot.id !== latestSnapshot.id
(snapshot) => snapshot.name !== latestSnapshot.name
)
const builds = [null, ...snapshots.map((snapshot) => snapshot.id)]
const selectedFrom: BuildId | undefined = compareMode
? fromId === 'latest'
? null
: (fromId ?? snapshots[0]?.id)
: (singleBuildId ?? snapshots[0]?.id)
const selectedTo: BuildId = compareMode ? toId : null
const builds = [null, ...snapshots.map((snapshot) => snapshot.name)]
const selectedFrom: BuildName | undefined = compareMode
? fromName === undefined
? snapshots[0]?.name
: fromName
: (singleBuildName ?? snapshots[0]?.name)
const selectedTo: BuildName | undefined = compareMode ? toName : null
function getLabel(id: BuildId | undefined) {
function getLabel(id: BuildName | undefined) {
if (id === null) return 'Latest'
if (id === undefined) return 'Select build'
const snapshot = snapshots.find((item) => item.id === id)
const snapshot = snapshots.find((item) => item.name === id)
return snapshot ? formatSnapshotLabel(snapshot) : 'Unknown build'
}
function selectComparison(side: 'from' | 'to', id: BuildId) {
if (selectedFrom === undefined) return
function selectComparison(side: 'from' | 'to', id: BuildName) {
if (selectedFrom === undefined || selectedTo === undefined) return
if (side === 'from') {
onComparisonChange(id, id === selectedTo ? selectedFrom : selectedTo)
} else {
......@@ -80,10 +81,9 @@ export function BuildPicker({
const visibleBuilds = builds.filter((id) => {
if (!query) return true
if (id === null) return 'latest'.includes(query)
const snapshot = snapshots.find((item) => item.id === id)!
const snapshot = snapshots.find((item) => item.name === id)!
return [
snapshot.id,
snapshot.snapshotName,
snapshot.name,
snapshot.gitBranch,
snapshot.gitShortSha,
snapshot.gitMessage,
......@@ -94,8 +94,8 @@ export function BuildPicker({
})
const triggerLabel = compareMode
? `${getLabel(fromId === 'latest' ? null : (fromId ?? undefined))} → ${getLabel(toId)}`
: getLabel(singleBuildId)
? `${getLabel(fromName)} → ${getLabel(toName)}`
: getLabel(singleBuildName)
return (
<Popover
......@@ -167,12 +167,12 @@ export function BuildPicker({
const snapshot =
id === null
? latestSnapshot
: snapshots.find((item) => item.id === id)!
: snapshots.find((item) => item.name === id)!
const label =
id === null ? 'Latest' : formatSnapshotLabel(snapshot)
return (
<div
key={id ?? 'latest'}
key={encodeBuildSelection(id)}
className="flex min-h-14 items-center border-b last:border-b-0"
>
{mode === 'compare' ? (
......@@ -181,14 +181,18 @@ export function BuildPicker({
side="from"
label={label}
selected={selectedFrom === id}
disabled={selectedFrom === undefined}
disabled={
selectedFrom === undefined || selectedTo === undefined
}
onClick={() => selectComparison('from', id)}
/>
<SelectionCell
side="to"
label={label}
selected={selectedTo === id}
disabled={selectedFrom === undefined}
disabled={
selectedFrom === undefined || selectedTo === undefined
}
onClick={() => selectComparison('to', id)}
/>
<div className="min-w-0 flex-1 py-2 pl-2 pr-2 text-left">
......@@ -199,7 +203,7 @@ export function BuildPicker({
<button
type="button"
aria-label={`View ${label}`}
aria-pressed={!compareMode && singleBuildId === id}
aria-pressed={!compareMode && singleBuildName === id}
className="flex min-w-0 flex-1 items-center hover:bg-muted"
onClick={() => {
onSingleBuildChange(id)
......@@ -207,7 +211,7 @@ export function BuildPicker({
>
<span className="flex w-11 shrink-0 justify-center">
<SelectionMark
selected={!compareMode && singleBuildId === id}
selected={!compareMode && singleBuildName === id}
/>
</span>
<span className="min-w-0 flex-1 py-2 pl-2 pr-2 text-left">
......
......@@ -74,9 +74,9 @@ export function TopBar({
historyLoading,
historyError,
latestSnapshot,
singleBuildId,
fromId,
toId,
singleBuildName,
fromName,
toName,
onSingleBuildChange,
onComparisonChange,
routesBaseDir,
......@@ -109,10 +109,10 @@ export function TopBar({
historyLoading: boolean
historyError: boolean
latestSnapshot: SnapshotMetadata
singleBuildId: string | null
fromId: string | null
toId: string | null
onSingleBuildChange: (id: string | null) => void
singleBuildName: string | null
fromName: string | null | undefined
toName: string | null | undefined
onSingleBuildChange: (name: string | null) => void
onComparisonChange: (from: string | null, to: string | null) => void
routesBaseDir: string
compareView: CompareView
......@@ -142,9 +142,9 @@ export function TopBar({
historyLoading={historyLoading}
historyError={historyError}
latestSnapshot={latestSnapshot}
singleBuildId={singleBuildId}
fromId={fromId}
toId={toId}
singleBuildName={singleBuildName}
fromName={fromName}
toName={toName}
onSingleBuildChange={onSingleBuildChange}
onComparisonChange={onComparisonChange}
/>
......
......@@ -4,7 +4,7 @@
* sync.
*/
export interface SnapshotMetadata {
id: string
name: string
createdAt: string
nextVersion?: string
gitBranch?: string
......@@ -15,8 +15,6 @@ export interface SnapshotMetadata {
gitMessage?: string
appDirOnly?: boolean
noMangling?: boolean
/** User-supplied snapshot name, overriding branch/sha in display. See `--snapshot-name`. */
snapshotName?: string
routeCount: number
}
......@@ -25,20 +23,30 @@ export interface HistoryIndex {
snapshots: SnapshotMetadata[]
}
/**
* Returns a short, human-friendly label for a snapshot. Used by the picker
* and the diff header bar. Format prefers branch + short sha, falling back to
* timestamp when neither is available.
*/
/** Null selects the live build; undefined means no valid selection. */
export function decodeBuildSelection(
value: string | null
): string | null | undefined {
if (value === 'latest') return null
if (value?.startsWith('snapshot:') && value.length > 'snapshot:'.length) {
return value.slice('snapshot:'.length)
}
return undefined
}
/** Tag saved names so even a snapshot named "latest" is distinct from the live build. */
export function encodeBuildSelection(name: string | null): string {
return name === null ? 'latest' : `snapshot:${name}`
}
/** The snapshot's name is both its selection key and its display label. */
export function formatSnapshotLabel(metadata: SnapshotMetadata): string {
if (metadata.snapshotName) return metadata.snapshotName
const sha = metadata.gitShortSha ? metadata.gitShortSha : null
const branch = metadata.gitBranch ?? null
if (branch && sha)
return `${branch}@${sha}${metadata.gitDirty ? ' (dirty)' : ''}`
if (sha) return `${sha}${metadata.gitDirty ? ' (dirty)' : ''}`
if (branch) return branch
return formatRelativeTime(metadata.createdAt)
return metadata.name
}
/** Mirror the build's snapshotDirectory encoding, then escape the segment for HTTP. */
export function snapshotBaseDir(metadata: SnapshotMetadata): string {
return `/history/${encodeURIComponent(`snapshot-${encodeURIComponent(metadata.name)}`)}`
}
/**
......
import { CompareView, Environment } from '@/components/top-bar'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import type { SnapshotMetadata } from './snapshot'
import {
decodeBuildSelection,
encodeBuildSelection,
snapshotBaseDir,
type SnapshotMetadata,
} from './snapshot'
export function useAnalyzerRoute(
compare: boolean,
......@@ -11,27 +16,36 @@ export function useAnalyzerRoute(
const pathname = usePathname()
const searchParams = useSearchParams()
const selectedRoute = searchParams.get('route')
const singleBuildId = compare ? null : searchParams.get('build')
const singleSnapshot = singleBuildId
? (snapshots?.find((snapshot) => snapshot.id === singleBuildId) ?? null)
const singleBuildName = compare
? null
: decodeBuildSelection(searchParams.get('build') ?? 'latest')
const invalidSingleBuild = !compare && singleBuildName === undefined
const singleSnapshot =
typeof singleBuildName === 'string'
? (snapshots?.find((snapshot) => snapshot.name === singleBuildName) ??
null)
: null
const fromName = compare
? decodeBuildSelection(searchParams.get('from'))
: undefined
const toName = compare
? decodeBuildSelection(searchParams.get('to') ?? 'latest')
: null
const fromId = compare ? searchParams.get('from') : null
const toParam = compare ? searchParams.get('to') : null
const toId = toParam === 'latest' ? null : toParam
const invalidComparison =
compare &&
toId != null &&
!snapshots?.some((snapshot) => snapshot.id === toId)
(toName === undefined ||
(toName !== null &&
!snapshots?.some((snapshot) => snapshot.name === toName)))
const baselineSnapshot = compare
? fromId === 'latest'
? fromName === null
? latestSnapshot
: (snapshots?.find((snapshot) => snapshot.id === fromId) ?? null)
: (snapshots?.find((snapshot) => snapshot.name === fromName) ?? null)
: null
const comparisonSnapshot = compare
? (snapshots?.find((snapshot) => snapshot.id === toId) ?? null)
? (snapshots?.find((snapshot) => snapshot.name === toName) ?? null)
: singleSnapshot
const activeBaseDir = comparisonSnapshot
? `/history/${comparisonSnapshot.id}`
? snapshotBaseDir(comparisonSnapshot)
: '/data'
const viewParam = searchParams.get('view')
const compareView =
......@@ -85,11 +99,12 @@ export function useAnalyzerRoute(
activeBaseDir,
baselineSnapshot,
comparisonSnapshot,
fromId,
fromName,
invalidComparison,
singleBuildId,
invalidSingleBuild,
singleBuildName: singleBuildName ?? null,
singleSnapshot,
toId,
toName,
compareView,
environmentFilter,
searchQuery,
......@@ -102,15 +117,25 @@ export function useAnalyzerRoute(
pathname === '/'
? (route: string) => buildHref('/analyze', { route })
: undefined,
setSingleBuild: (id: string | null) =>
navigate('/analyze', { build: id, from: null, to: null }, 'push'),
setSingleBuild: (name: string | null) =>
navigate(
'/analyze',
{
build: name === null ? null : encodeBuildSelection(name),
from: null,
to: null,
},
'push'
),
setComparison: (from: string | null, to: string | null) =>
navigate(
'/compare',
{ from: from ?? 'latest', to, build: null },
pathname === '/compare' && fromId === (from ?? 'latest')
? 'replace'
: 'push'
{
from: encodeBuildSelection(from),
to: to === null ? null : encodeBuildSelection(to),
build: null,
},
pathname === '/compare' && fromName === from ? 'replace' : 'push'
),
setEnvironmentFilter: (environment: Environment) =>
replaceSearchParams({
......
......@@ -25,6 +25,8 @@ use turbopack_core::{
reference::all_assets_from_entries,
};
const ANALYZE_SCHEMA_VERSION: u32 = 1;
#[turbo_tasks::value]
#[derive(Clone, Copy, Serialize)]
pub struct BundleTotals {
......@@ -109,6 +111,8 @@ struct EdgesDataReference {
#[derive(Serialize)]
struct AnalyzeDataHeader {
/// Supported by the agent graph-dump decoder; UI readers ignore this field.
pub schema_version: u32,
pub sources: Vec<AnalyzeSource>,
pub chunk_parts: Vec<AnalyzeChunkPart>,
pub output_files: Vec<AnalyzeOutputFile>,
......@@ -124,6 +128,8 @@ struct AnalyzeDataHeader {
#[derive(Serialize)]
struct ModulesDataHeader {
/// Supported by the agent graph-dump decoder; UI readers ignore this field.
pub schema_version: u32,
pub modules: Vec<AnalyzeModule>,
/// Edges from modules to modules
pub module_dependents: EdgesDataReference,
......@@ -270,6 +276,7 @@ impl AnalyzeDataBuilder {
let mut binary_section = EdgesDataSectionBuilder::new();
let header = AnalyzeDataHeader {
schema_version: ANALYZE_SCHEMA_VERSION,
sources: self.sources.into_iter().map(|s| s.source).collect(),
chunk_parts: self.chunk_parts,
output_files: self
......@@ -371,6 +378,7 @@ impl ModulesDataBuilder {
let mut binary_section = EdgesDataSectionBuilder::new();
let header = ModulesDataHeader {
schema_version: ANALYZE_SCHEMA_VERSION,
modules: self.modules.into_iter().map(|s| s.module).collect(),
module_dependents: binary_section.add_edges(&module_dependents),
async_module_dependents: binary_section.add_edges(&async_module_dependents),
......
......@@ -252,26 +252,39 @@ By default, the command starts a local server after analysis completes, allowing
See [Package Bundling](/docs/app/guides/package-bundling#optimizing-large-bundles) for optimization strategies.
To write the analysis output to disk without starting the server, use the `--output` flag. The output is written to `.next/diagnostics/analyze` and contains static files that can be copied elsewhere or shared with others:
To write the analysis output to disk without starting the server, use `--output`. Snapshot and interactive UI files are written to `<distDir>/diagnostics/analyze` (normally `.next/diagnostics/analyze`).
```bash filename="Terminal"
# Write output to .next/diagnostics/analyze
npx next analyze --output
# Build and save a snapshot without starting the UI server
npx next analyze --output --snapshot audit-1
# Copy the output for comparison with a future analysis
cp -r .next/diagnostics/analyze ./analyze-before-refactor
# Stream that saved graph as one JSON object per line, without rebuilding
npx next analyze export --snapshot audit-1 > graph.jsonl
```
The following options are available for the `next analyze` command:
| Option | Description |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `-h, --help` | Show all available options. |
| `[directory]` | A directory on which to analyze the application. If not provided, the current directory will be used. |
| `--no-mangling` | Disables [mangling](https://en.wikipedia.org/wiki/Name_mangling). This may affect performance and should only be used for debugging purposes. |
| `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). This may affect performance. |
| `-o, --output` | Write analysis files to disk without starting the server. Output is written to `.next/diagnostics/analyze`. |
| `--port <port>` | Specify a port number to serve the analyzer on. (default: 4000, env: PORT) |
| Option | Description |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `-h, --help` | Show all available options. |
| `[directory]` | A directory on which to analyze the application. If not provided, the current directory will be used. |
| `--no-mangling` | Disables [mangling](https://en.wikipedia.org/wiki/Name_mangling). This may affect performance and should only be used for debugging purposes. |
| `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). This may affect performance. |
| `-o, --output` | Build and save binary analyzer data and UI files to `<distDir>/diagnostics/analyze` without serving. |
| `--snapshot <name>` | Save a named snapshot, replacing an earlier capture with the same name. |
| `--port <port>` | Specify a port number to serve the analyzer on. (default: 4000, env: PORT) |
### `next analyze export` options
The `export` subcommand reads a saved snapshot without building or starting the UI server. Place replay options after `export`: `next analyze export --snapshot audit-1` selects saved data; `--snapshot` before `export` is a capture option and is rejected.
| Option | Description |
| ------------------------ | ------------------------------------------------------------------------------------------- |
| `-h, --help` | Show all available export options. |
| `[directory]` | The application directory containing the saved analysis. Defaults to the current directory. |
| `--snapshot <name>` | Select a saved snapshot by name. Defaults to the newest retained snapshot. |
| `--route <route>` | Restrict export to one route (still includes the full module graph). |
| `--dist-dir <directory>` | Select an explicit relative or absolute build directory without reading `next.config`. |
## Examples
......
......@@ -172,6 +172,7 @@
"@vercel/kv": "3.0.0",
"@vercel/og": "1.0.1",
"@vercel/sandbox": "1.8.0",
"ajv": "8.17.1",
"alex": "9.1.0",
"async-sema": "3.0.1",
"babel-plugin-react-compiler": "0.0.0-experimental-1371fcb-20260227",
......
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:nextjs:analyze:analyzer-graph:v1",
"title": "Next.js analyzer graph v1 record",
"description": "The analyzer graph represents static dependency information from a Next.js application. The graph is produced as a set of newline-delimited JSON objects described in this schema.",
"oneOf": [
{ "$ref": "#/$defs/meta" },
{ "$ref": "#/$defs/module" },
{ "$ref": "#/$defs/route" },
{ "$ref": "#/$defs/output" },
{ "$ref": "#/$defs/part" }
],
"$defs": {
"index": { "type": "integer", "minimum": 0 },
"size": {
"$ref": "#/$defs/index",
"description": "Attributed bytes, not measured transfer or predicted savings."
},
"identity": {
"type": "string",
"description": "Exact module ident; variants can share a source path."
},
"identities": { "type": "array", "items": { "$ref": "#/$defs/identity" } },
"meta": {
"type": "object",
"required": [
"type",
"schema_version",
"snapshot_name",
"route_count",
"selected_routes"
],
"properties": {
"type": { "const": "meta" },
"schema_version": {
"const": 1,
"description": "Version of each emitted record."
},
"snapshot_name": {
"type": "string",
"minLength": 1,
"description": "Generated or provided snapshot name. Reusing an explicit name replaces its earlier capture."
},
"route_count": {
"$ref": "#/$defs/index",
"description": "Total routes in this snapshot."
},
"selected_routes": {
"$ref": "#/$defs/index",
"description": "Number of routes selected by the optional route filter; the total number of routes if no filter is set."
}
},
"additionalProperties": true,
"description": "Snapshot metadata, expected first in a complete stream."
},
"module": {
"type": "object",
"required": ["type", "ident", "path", "dependencies"],
"properties": {
"type": { "const": "module" },
"ident": {
"$ref": "#/$defs/identity",
"description": "Identity for this module."
},
"path": {
"type": "string",
"description": "Source path; may match multiple modules. Use `ident` as a key for this module."
},
"dependencies": {
"type": "object",
"required": ["sync", "async", "traced"],
"properties": {
"sync": {
"$ref": "#/$defs/identities",
"description": "Synchronous imports from this module."
},
"async": {
"$ref": "#/$defs/identities",
"description": "Asynchronous imports from this module."
},
"traced": {
"$ref": "#/$defs/identities",
"description": "Non-bundled file-tracing dependencies, not browser imports."
}
},
"additionalProperties": true,
"description": "Modules this module depends on, along with the type of dependency. The import graph may contain cycles."
}
},
"additionalProperties": true,
"description": "Whole-app module graph, including when --route filters route-local records."
},
"route": {
"type": "object",
"required": ["type", "route"],
"properties": {
"type": { "const": "route", "description": "Defines a route record." },
"route": {
"type": "string",
"description": "The unique normalized route key from routes.json."
}
},
"additionalProperties": true,
"description": "One route; route-local records join by this path."
},
"output": {
"type": "object",
"required": ["type", "route", "filename"],
"properties": {
"type": { "const": "output" },
"route": { "type": "string", "description": "Owning route path." },
"filename": {
"type": "string",
"description": "Snapshot-scoped emitted path, not stable across builds or proof of a browser request."
}
},
"additionalProperties": true,
"description": "Emitted file. Verify [client-fs]/ client-output provenance before treating it as browser work. Membership and size attribution are separate."
},
"part": {
"type": "object",
"required": [
"type",
"route",
"filename",
"source_path",
"size",
"compressed_size"
],
"properties": {
"type": { "const": "part" },
"route": { "type": "string", "description": "Owning route path." },
"filename": {
"type": "string",
"description": "Attributed output file."
},
"source_path": {
"type": "string",
"description": "Reconstructed source path, not a unique module ident."
},
"size": { "$ref": "#/$defs/size" },
"compressed_size": {
"$ref": "#/$defs/size",
"description": "Attributed compressed bytes, not observed network transfer."
}
},
"additionalProperties": true,
"description": "Source attribution within an emitted output."
}
}
}
......@@ -10,6 +10,7 @@
"types": "index.d.ts",
"files": [
"AGENTS.md",
"analyze",
"dist",
"app.js",
"app.d.ts",
......
......@@ -28,7 +28,10 @@ import type { NextTelemetryOptions } from '../cli/next-telemetry.js'
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 {
NextAnalyzeOptions,
NextAnalyzeExportOptions,
} from '../cli/next-analyze.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'
......@@ -152,6 +155,13 @@ function parseValidInspectAddress(value: string): DebugAddress {
const program = new NextRootCommand()
// Commander needs positional options on both ancestors (program and analyze)
// to keep identically named capture/export flags local after the subcommand.
// Leave option parsing for the rest of the CLI unchanged.
program.enablePositionalOptions(
process.argv[2] === 'analyze' || process.argv[2] === 'experimental-analyze'
)
program
.name('next')
.description(
......@@ -263,9 +273,11 @@ program
})
.usage('[directory] [options]')
program
const analyzeCommand = program
.command('analyze')
.alias('experimental-analyze')
.enablePositionalOptions()
.version(program.version()!, '-v, --version', 'Outputs the Next.js version.')
.description(
'Analyze production bundle output with an interactive web ui. Does not produce an application build. Only compatible with Turbopack.'
)
......@@ -279,8 +291,8 @@ program
.option('--profile', 'Enables production profiling for React.')
.option('--experimental-app-only', 'Analyzes only App Router routes.')
.option(
'--snapshot-name <name>',
'Name this snapshot in the metadata, overriding branch/sha in the comparison UI.'
'--snapshot <name>',
'Save a named snapshot, replacing an existing capture with that name.'
)
.option(
'-o, --output',
......@@ -297,8 +309,9 @@ program
.env('PORT')
)
.action((directory: string, options: NextAnalyzeOptions) => {
return import('../cli/next-analyze.js')
.then((mod) => mod.nextAnalyze(options, directory))
const { nextAnalyze } =
require('../cli/next-analyze.js') as typeof import('../cli/next-analyze.js')
return 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.
......@@ -306,6 +319,62 @@ program
process.exit(0)
}
})
.catch((error) => {
console.error(error)
process.exit(1)
})
})
analyzeCommand
.command('export')
.version(program.version()!, '-v, --version', 'Outputs the Next.js version.')
.description(
'Stream a saved analyzer graph as JSON Lines without building or serving.'
)
.argument(
'[directory]',
`The application directory containing the saved analysis. ${italic(
'If no directory is provided, the current directory will be used.'
)}`
)
.option(
'--snapshot <name>',
'Select a saved snapshot by name (defaults to latest).'
)
.option('--route <route>', 'Filter graph records to a route.')
.option(
'--dist-dir <directory>',
'Read from an explicitly chosen build directory (defaults to .next).'
)
.action(async (directory: string, options: NextAnalyzeExportOptions) => {
try {
// Reject explicit capture/server options before the subcommand, but
// ignore defaults and inherited PORT. Options after export are local.
const captureOptions = [
['output', '--output'],
['profile', '--profile'],
['experimentalAppOnly', '--experimental-app-only'],
['mangling', '--no-mangling'],
['port', '--port'],
['snapshot', '--snapshot'],
]
const offending = captureOptions
.filter(([key]) => analyzeCommand.getOptionValueSource(key) === 'cli')
.map(([, flag]) => flag)
if (offending.length > 0) {
throw new Error(
`next analyze export cannot use capture/server options before export: ${offending.join(', ')}`
)
}
const { nextAnalyzeExport } =
require('../cli/next-analyze.js') as typeof import('../cli/next-analyze.js')
nextAnalyzeExport(options, directory)
// The synchronous exporter has completed every fd write, including slow pipes.
process.exit(0)
} catch (error) {
console.error(error)
process.exit(1)
}
})
program
......
import { readFileSync, writeSync } from 'node:fs'
import { join, resolve, sep } from 'node:path'
const UINT32_LIMIT = 0x1_0000_0000
type EdgeRef = { offset: number; length: number }
type Module = { ident: string; path: string }
type Source = { parent_source_index: number | null; path: string }
type Part = {
source_index: number
output_file_index: number
size: number
compressed_size: number
}
type ModuleHeader = {
schema_version: number
modules: Module[]
module_dependencies: EdgeRef
async_module_dependencies: EdgeRef
traced_module_dependencies: EdgeRef
}
type RouteHeader = {
schema_version: number
sources: Source[]
chunk_parts: Part[]
output_files: Array<{ filename: string }>
}
type Data<H> = { header: H; binary: Buffer }
function integer(value: number, limit: number): boolean {
return Number.isSafeInteger(value) && value >= 0 && value < limit
}
function requireIndex(value: number, limit: number, label: string): void {
if (!integer(value, limit))
throw new Error(`Invalid ${label} index: ${value}`)
}
function readData<H extends { schema_version: number }>(file: string): Data<H> {
const data = readFileSync(file)
if (data.length < 4) throw new Error(`Truncated analyzer header: ${file}`)
const length = data.readUInt32BE(0)
if (length === 0 || length > data.length - 4) {
throw new Error(`Invalid analyzer header length: ${file}`)
}
const header = JSON.parse(data.toString('utf8', 4, 4 + length)) as H
if (!header || typeof header !== 'object') {
throw new Error(`Invalid analyzer header: ${file}`)
}
if (header.schema_version !== 1) {
throw new Error(
`Unsupported analyzer schema ${String(header.schema_version)}: ${file}`
)
}
return { header, binary: data.subarray(4 + length) }
}
/** Read the consumed dependency rows, checking their binary ranges and targets. */
function validateEdges(
binary: Buffer,
ref: EdgeRef,
rows: number,
targets: number,
label: string
): { row(index: number): number[] } {
if (
!ref ||
!integer(ref.offset, binary.length + 1) ||
!integer(ref.length, binary.length + 1) ||
ref.length < 4 ||
ref.offset + ref.length > binary.length
) {
throw new Error(`Invalid ${label} section`)
}
const count = binary.readUInt32BE(ref.offset)
if (count !== rows || ref.length < 4 + 4 * count) {
throw new Error(`Invalid ${label} row count`)
}
const offsets: number[] = []
let previous = 0
for (let i = 0; i < count; i++) {
const offset = binary.readUInt32BE(ref.offset + 4 + i * 4)
if (offset < previous || 4 + 4 * count + 4 * offset > ref.length) {
throw new Error(`Invalid ${label} offsets`)
}
offsets.push(offset)
previous = offset
}
if (4 + 4 * count + 4 * previous !== ref.length) {
throw new Error(`Invalid ${label} section length`)
}
const dataStart = ref.offset + 4 + 4 * count
for (let i = 0; i < previous; i++) {
requireIndex(binary.readUInt32BE(dataStart + i * 4), targets, label)
}
return {
row(index) {
const start = index === 0 ? 0 : offsets[index - 1]
const result: number[] = []
for (let i = start; i < offsets[index]; i++) {
result.push(binary.readUInt32BE(dataStart + i * 4))
}
return result
},
}
}
function sourcePaths(sources: Source[]): string[] {
const paths: Array<string | undefined> = Array(sources.length)
const visiting = new Set<number>()
function path(index: number): string {
requireIndex(index, sources.length, 'source')
if (paths[index] !== undefined) return paths[index]
if (visiting.has(index)) throw new Error('Cyclic analyzer source tree')
visiting.add(index)
const source = sources[index]
if (typeof source.path !== 'string') throw new Error('Invalid source path')
const parent = source.parent_source_index
paths[index] = parent === null ? source.path : path(parent) + source.path
visiting.delete(index)
return paths[index]
}
return sources.map((_, i) => path(i))
}
function routeFile(directory: string, route: string): string {
if (
!route.startsWith('/') ||
route.includes('\\') ||
route.includes('\0') ||
route.split('/').some((segment) => segment === '..' || segment === '.')
) {
throw new Error(`Invalid analyzer route: ${route}`)
}
const file = resolve(directory, route.slice(1), 'analyze.data')
if (!file.startsWith(resolve(directory) + sep)) {
throw new Error(`Analyzer route escapes snapshot: ${route}`)
}
return file
}
function parseModules(file: string) {
const { header, binary } = readData<ModuleHeader>(file)
if (!Array.isArray(header.modules))
throw new Error('Missing analyzer modules')
const modules = header.modules
const ids = new Set<string>()
for (const module of modules) {
if (
typeof module.ident !== 'string' ||
typeof module.path !== 'string' ||
ids.has(module.ident)
) {
throw new Error('Invalid or duplicated analyzer module identity')
}
ids.add(module.ident)
}
const edges = {} as Record<
'sync' | 'async' | 'traced',
ReturnType<typeof validateEdges>
>
for (const [kind, field] of [
['sync', 'module_dependencies'],
['async', 'async_module_dependencies'],
['traced', 'traced_module_dependencies'],
] as const) {
edges[kind] = validateEdges(
binary,
header[field],
modules.length,
modules.length,
field
)
}
return { modules, edges }
}
function parseRoutes(file: string) {
const { header } = readData<RouteHeader>(file)
if (
!Array.isArray(header.sources) ||
!Array.isArray(header.output_files) ||
!Array.isArray(header.chunk_parts)
) {
throw new Error('Invalid analyzer route header')
}
const paths = sourcePaths(header.sources)
const outputs = header.output_files
const parts = header.chunk_parts
for (const part of parts) {
requireIndex(part.source_index, paths.length, 'part source')
requireIndex(part.output_file_index, outputs.length, 'part output')
if (
!integer(part.size, UINT32_LIMIT) ||
!integer(part.compressed_size, UINT32_LIMIT)
) {
throw new Error('Invalid analyzer part size')
}
}
for (const output of outputs)
if (typeof output.filename !== 'string')
throw new Error('Invalid output filename')
return { paths, header }
}
function writeRecord(record: object): void {
const data = Buffer.from(JSON.stringify(record) + '\n')
let offset = 0
while (offset < data.length) {
const written = writeSync(1, data, offset, data.length - offset)
if (written === 0)
throw new Error('Could not write analyzer export to stdout')
offset += written
}
}
/** Read/validate the private UI format, and expose only versioned semantic records. */
export function dumpAnalyzeGraph(
directory: string,
snapshotName: string,
routeFilter: string | undefined
): void {
// Pipe stdout must block so writeSync supplies backpressure rather than EAGAIN.
if (process.stdout._handle != null) {
// @ts-ignore Node's internal handle, also used by the native bindings loader.
process.stdout._handle.setBlocking?.(true)
}
const routes = JSON.parse(
readFileSync(join(directory, 'routes.json'), 'utf8')
) as string[]
if (
!Array.isArray(routes) ||
routes.some((route) => typeof route !== 'string')
) {
throw new Error('Invalid analyzer routes')
}
const selected = routes.filter(
(route) => routeFilter === undefined || route === routeFilter
)
if (routeFilter !== undefined && selected.length === 0)
throw new Error(`Unknown analyzer route: ${routeFilter}`)
const { modules, edges } = parseModules(join(directory, 'modules.data'))
writeRecord({
type: 'meta',
schema_version: 1,
snapshot_name: snapshotName,
route_count: routes.length,
selected_routes: selected.length,
})
for (const [index, module] of modules.entries()) {
writeRecord({
type: 'module',
ident: module.ident,
path: module.path,
dependencies: Object.fromEntries(
(['sync', 'async', 'traced'] as const).map((kind) => [
kind,
edges[kind].row(index).map((i) => modules[i].ident),
])
),
})
}
// Retain only the current route's data. A later validation error may leave
// partial output; callers must check the exit status before using it.
for (const route of selected) {
const { paths, header } = parseRoutes(routeFile(directory, route))
const prefix = { route }
writeRecord({
type: 'route',
...prefix,
})
for (let i = 0; i < header.output_files.length; i++) {
writeRecord({
type: 'output',
...prefix,
filename: header.output_files[i].filename,
})
}
for (const part of header.chunk_parts) {
writeRecord({
type: 'part',
...prefix,
filename: header.output_files[part.output_file_index].filename,
source_path: paths[part.source_index],
size: part.size,
compressed_size: part.compressed_size,
})
}
}
}
......@@ -8,13 +8,19 @@ import loadConfig from '../../server/config'
import { PHASE_ANALYZE } from '../../shared/lib/constants'
import { turbopackAnalyze, type AnalyzeContext } from '../turbopack-analyze'
import { durationToString } from '../duration-to-string'
import { cp, writeFile, mkdir } from 'node:fs/promises'
import { Lockfile } from '../lockfile'
import { installBindings } from '../swc/install-bindings'
import { cpSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'
import { discoverRoutes } from '../route-discovery'
import { findPagesDir } from '../../lib/find-pages-dir'
import loadCustomRoutes from '../../lib/load-custom-routes'
import { generateRoutesManifest } from '../generate-routes-manifest'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { writeAnalyzeSnapshot } from './snapshot'
import {
writeAnalyzeSnapshot,
snapshotNameSchema,
type SnapshotMetadata,
} from './snapshot'
import http from 'node:http'
// @ts-expect-error types are in @types/serve-handler
......@@ -32,8 +38,8 @@ export type AnalyzeOptions = {
appDirOnly?: boolean
output?: boolean
port?: number
/** User-supplied snapshot name stored in the snapshot metadata, overriding branch/sha in the UI. */
snapshotName?: string
/** Reusing an explicit name replaces its retained snapshot. */
snapshot?: string
}
export default async function analyze({
......@@ -43,8 +49,10 @@ export default async function analyze({
appDirOnly = false,
output = false,
port = 4000,
snapshotName,
}: AnalyzeOptions): Promise<void> {
snapshot,
}: AnalyzeOptions): Promise<SnapshotMetadata> {
if (snapshot !== undefined) snapshotNameSchema.parse(snapshot)
let lockfile: Lockfile | undefined
try {
// analyze is Turbopack-only. Mirror what parseBundlerArgs does for build/dev
// so every process.env.TURBOPACK consumer in this run agrees with the bundler choice.
......@@ -57,12 +65,25 @@ export default async function analyze({
process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
const distDir = path.join(dir, '.next')
const distDir = path.join(dir, config.distDir)
const telemetry = new Telemetry({ distDir })
setGlobal('phase', PHASE_ANALYZE)
setGlobal('distDir', distDir)
setGlobal('telemetry', telemetry)
// Native locks require synchronous access to bindings. Like next build,
// install them before acquiring the lock, but still lock before writes.
await installBindings(config.experimental?.useWasmBinary)
// Lock the directory while capture reads/writes it. Static serving and
// saved-data replay do not need to hold the capture lock.
if (config.experimental.lockDistDir) {
mkdirSync(distDir, { recursive: true })
lockfile = await Lockfile.acquireWithRetriesOrExit(
path.join(distDir, 'lock'),
'next analyze'
)
}
Log.info('Analyzing a production build...')
const analyzeContext: AnalyzeContext = {
......@@ -73,6 +94,12 @@ export default async function analyze({
appDirOnly,
}
// Start a fresh live dataset so removed routes cannot leak into a replacement.
rmSync(path.join(distDir, 'diagnostics/analyze/data'), {
recursive: true,
force: true,
maxRetries: 3,
})
const { duration: analyzeDuration, shutdownPromise } =
await turbopackAnalyze(analyzeContext)
......@@ -83,24 +110,24 @@ export default async function analyze({
const routes = await collectRoutesForAnalyze(dir, config, appDirOnly)
await cp(path.join(__dirname, '../../bundle-analyzer'), analyzeDir, {
cpSync(path.join(__dirname, '../../bundle-analyzer'), analyzeDir, {
recursive: true,
})
await mkdir(path.join(analyzeDir, 'data'), { recursive: true })
await writeFile(
mkdirSync(path.join(analyzeDir, 'data'), { recursive: true })
writeFileSync(
path.join(analyzeDir, 'data', 'routes.json'),
JSON.stringify(routes, null, 2)
)
// Capture this build alongside any prior builds so the analyzer UI can
// offer it as a comparison baseline in the future.
await writeAnalyzeSnapshot({
const metadata = writeAnalyzeSnapshot({
projectDir: dir,
analyzeDir,
routes,
appDirOnly,
noMangling,
snapshotName,
snapshot,
})
let logMessage = `Analyze completed in ${durationString}.`
......@@ -120,6 +147,7 @@ export default async function analyze({
if (!output) {
await startServer(analyzeDir, port)
}
return metadata
} catch (e) {
const telemetry = traceGlobals.get('telemetry') as Telemetry | undefined
if (telemetry) {
......@@ -131,6 +159,8 @@ export default async function analyze({
}
throw e
} finally {
await lockfile?.unlock()
}
}
......
This diff is collapsed.
......@@ -4888,7 +4888,7 @@ export default async function build(
// Capture this build alongside any prior builds so the analyzer UI
// can offer it as a comparison baseline in the future.
await writeAnalyzeSnapshot({
writeAnalyzeSnapshot({
projectDir: dir,
analyzeDir,
routes,
......
......@@ -2,13 +2,20 @@
import '../server/lib/cpu-profile'
import { saveCpuProfile } from '../server/lib/cpu-profile'
import { existsSync } from 'fs'
import { existsSync, readFileSync } from 'node:fs'
import { resolve, join } from 'node:path'
import { italic } from '../lib/picocolors'
import analyze from '../build/analyze'
import { warn } from '../build/output/log'
import { printAndExit } from '../server/lib/utils'
import { getProjectDir } from '../lib/get-project-dir'
import { warnMissingReactDependencies } from '../lib/warn-missing-react-dependencies'
import { dumpAnalyzeGraph } from '../build/analyze/graph-dump'
import {
historyIndexSchema,
snapshotNameSchema,
snapshotDirectory,
} from '../build/analyze/snapshot'
export type NextAnalyzeOptions = {
experimentalAnalyze?: boolean
......@@ -17,7 +24,42 @@ export type NextAnalyzeOptions = {
port: number
output: boolean
experimentalAppOnly?: boolean
snapshotName?: string
snapshot?: string
}
export type NextAnalyzeExportOptions = {
distDir?: string
snapshot?: string
route?: string
}
function nextAnalyzeExport(
options: NextAnalyzeExportOptions,
directory?: string
): void {
// Replay does not load next.config, acquire the capture lock, or write artifacts.
const analyzeDir = join(
resolve(directory ?? '.', options.distDir ?? '.next'),
'diagnostics/analyze'
)
const { snapshots } = historyIndexSchema.parse(
JSON.parse(readFileSync(join(analyzeDir, 'history/history.json'), 'utf8'))
)
const name =
options.snapshot === undefined
? snapshots[0]?.name
: snapshotNameSchema.parse(options.snapshot)
if (
name === undefined ||
!snapshots.some((snapshot) => snapshot.name === name)
) {
throw new Error(`Analyzer snapshot not found: ${name ?? '(none)'}`)
}
dumpAnalyzeGraph(
join(analyzeDir, 'history', snapshotDirectory(name)),
name,
options.route
)
}
const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {
......@@ -30,8 +72,9 @@ const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {
process.exit(130)
})
const { profile, mangling, experimentalAppOnly, output, port, snapshotName } =
const { profile, mangling, experimentalAppOnly, output, port, snapshot } =
options
if (snapshot !== undefined) snapshotNameSchema.parse(snapshot)
if (!mangling) {
warn(
......@@ -52,15 +95,15 @@ const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {
printAndExit(`> No such directory exists as the project root: ${dir}`)
}
return analyze({
await analyze({
dir,
reactProductionProfiling: profile,
noMangling: !mangling,
appDirOnly: experimentalAppOnly,
output,
port,
snapshotName,
snapshot,
})
}
export { nextAnalyze }
export { nextAnalyze, nextAnalyzeExport }
......@@ -262,6 +262,9 @@ importers:
'@vercel/sandbox':
specifier: 1.8.0
version: 1.8.0
ajv:
specifier: 8.17.1
version: 8.17.1
alex:
specifier: 9.1.0
version: 9.1.0
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
This diff is collapsed.
{
"compilerOptions": {
"jsx": "react-jsx",
"module": "esnext",
"moduleResolution": "bundler",
"noEmit": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"app/**/*.ts",
"app/**/*.tsx",
"pages/**/*.ts",
"pages/**/*.tsx"
],
"exclude": ["node_modules"]
}
import Ajv2020 from 'ajv/dist/2020'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
const schema = JSON.parse(
readFileSync(
join(__dirname, '../../packages/next/analyze/graph-v1.schema.json'),
'utf8'
)
)
export const isValidGraphRecord = new Ajv2020({ allErrors: true }).compile(
schema
)
// JSON Schema describes a single line. Check stream framing and joins separately.
export function validateGraphDump(output: string): void {
if (!output.endsWith('\n')) throw new Error('Truncated analyzer graph stream')
const records = output
.slice(0, -1)
.split('\n')
.map((line) => JSON.parse(line))
if (records[0]?.type !== 'meta')
throw new Error('Analyzer graph stream must start with meta')
const routes = new Set<string>()
const outputs = new Set<string>()
let routeRecords = 0
for (const [index, parsed] of records.entries()) {
if (!isValidGraphRecord(parsed)) {
throw new Error(
`Invalid analyzer graph record ${index}: ${JSON.stringify(isValidGraphRecord.errors)}`
)
}
const record = parsed as {
type: string
route: string
filename: string
}
if (record.type === 'meta') {
if (index !== 0) throw new Error('Duplicate analyzer graph meta')
} else if (record.type === 'module') {
if (routeRecords) throw new Error('Module record after route records')
} else {
const key = record.route
if (record.type === 'route') {
if (routes.has(key)) throw new Error(`Duplicate analyzer route: ${key}`)
routes.add(key)
routeRecords++
} else if (!routes.has(key)) {
throw new Error(`Unknown route for graph record ${index}`)
}
if (record.type === 'output') {
outputs.add(JSON.stringify([key, record.filename]))
} else if (
(record.type === 'part' || record.type === 'unjoined') &&
!outputs.has(JSON.stringify([key, record.filename]))
) {
throw new Error(`Unknown output for graph record ${index}`)
}
}
}
if (routeRecords !== records[0].selected_routes) {
throw new Error('Incomplete analyzer route records')
}
if (routeRecords > records[0].route_count) {
throw new Error('Invalid analyzer route count')
}
}
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