[sourcemaps] Reuse source map payloads and consumers across stack frames (#96198)
Follow-up to https://github.com/vercel/next.js/pull/95946. Every fake stack frame is eval'd as its own script, so error formatting resolved a source map once per frame. This sucks for two reasons: `SourceMap#payload` returns a deep clone of the payload *on every access*, and constructing a `SyncSourceMapConsumer` indexes the whole payload. So an error with 50 fake frames pointing into one chunk cloned that chunk's map 50 times and indexed it 50 times. This change caches both steps per map instead of per script. `findSourceMapPayload` wraps `module.findSourceMap` and reads payload only once per `SourceMap` instance. This works because Node.js keeps one instance per script, so the instance is a reliable identity for "same map". (This also helps `filterStackFrameDEV`, which cloned the payload for every frame it filtered.) Consumers are cached in a WeakMap with (payload, base URL) pairs as a key since that's what they vary by. (Note that consumer sharing only works because the payload memo makes references stable, that's why they're in one commit.) This lets us share computation for identical sourcemaps despite them being used by different virtual frames. I previously tried to do this by keying a map from a physical filename to the sourcemap, but as noted in https://github.com/vercel/next.js/pull/95946#discussion_r3613450061, each fake frame could technically receive a different map, even if we don't do that. Caching based on returned value's identity lets us preserve the ability to be more granular later without worrying that the cache will start behaving incorrectly. ## Test Plan Microbench (20 errors × 20 fake frames, 5.6MB map, native path): canary 688.2 ms/error → this commit 0.2 ms/error. On a real devserver route with an artificially deep error (50-deep stacks in a chunk with a 19MB map), the route serve time goes down from ~400ms to ~70ms. Co-authored-by:Claude Fable 5 <noreply@anthropic.com>
Showing
Please
register
or
sign in
to comment